geolith-dataset-builder 0.5.0

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! The official LGD (Local Government Directory) lists: states and districts.
//!
//! Ported from the former `scripts/datasets/lgd.ts`. `states` parses the public state
//! page (or a saved copy) into `states.csv` and the `states` entry of
//! `source.json`; `districts` checks the owner-saved district CSV and
//! records its digest and count. The district list itself is never
//! downloaded here: the official download sits behind a captcha, which these
//! tools never work around.

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::time::Duration;

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, JsonResultExt as _, Result, WithinExt as _,
};
use serde_json::{Map, Value, json};

use crate::cli::{LgdAction, LgdArgs};
use crate::exit::Exit;
use crate::layout::{days_of_date, hex, sha256_file};

/// Public page listing every state/UT with its LGD code (no captcha).
pub const STATES_URL: &str = "https://lgdirectory.gov.in/globalviewstateforcitizen.do";

/// Page the owner downloads the district list from (captcha).
pub const DOWNLOAD_URL: &str = "https://lgdirectory.gov.in/downloadDirectory.do";

/// LGD copyright policy page.
pub const TERMS_URL: &str = "https://lgdirectory.gov.in/copyRightPolicy.do";

/// The reuse terms shown on [`TERMS_URL`].
pub const TERMS: &str = "Material featured on this site may be reproduced free of charge in any format or media without requiring specific permission. This is subject to the material being reproduced accurately and not being used in a derogatory manner or in a misleading context. Where the material is being published or issued to others, the source must be prominently acknowledged.";

/// The acknowledgement every output carrying LGD codes shows.
pub const ACKNOWLEDGEMENT: &str = "Source: Local Government Directory, Government of India";

/// File name of the owner-saved district list under the LGD dir.
pub const DISTRICTS_FILE: &str = "districts.csv";

/// File name of the untouched download saved next to [`DISTRICTS_FILE`].
pub const ORIGINAL_FILE: &str = "districts-source.xlsx";

/// The LGD report the district list comes from.
pub const REPORT: &str = "All Districts of India";

/// The format of [`REPORT`] the owner downloads.
pub const REPORT_FORMAT: &str = "Xls Report";

/// The official data.gov.in copy of the LGD district list (captcha form).
pub const DATA_GOV_URL: &str =
    "https://www.data.gov.in/resource/local-government-directory-lgd-districts";

/// One LGD state or union territory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LgdState {
    /// LGD state code.
    pub code: String,
    /// State name.
    pub name: String,
    /// `State` or `Union Territory`.
    pub kind: String,
}

/// One LGD district.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LgdDistrict {
    /// LGD state code.
    pub state_code: String,
    /// LGD district code.
    pub code: String,
    /// District name.
    pub name: String,
}

/// The manual step that produces [`DISTRICTS_FILE`].
#[must_use]
pub fn manual_step(lgd_dir: &Path) -> String {
    let path = lgd_dir.join(DISTRICTS_FILE);
    format!(
        "open {DOWNLOAD_URL}, choose the report \"{REPORT}\" and the format \"{REPORT_FORMAT}\", \
type the captcha and press Download; open the file in LibreOffice or Excel and save it as \
\"CSV UTF-8\" at {}; then run: geolith dataset lgd districts. Other official route: the \
data.gov.in resource \"Local Government Directory (LGD) - Districts\" ({DATA_GOV_URL}), \
Download, CSV (a form with a captcha), saved at the same path",
        path.display()
    )
}

/// The text of `html` with its entities decoded and its tags as spaces.
fn cell_text(html: &str) -> String {
    let mut out = String::with_capacity(html.len());
    let mut in_tag = false;
    for ch in html.chars() {
        match ch {
            '<' => in_tag = true,
            '>' => {
                in_tag = false;
                out.push(' ');
            }
            _ if !in_tag => out.push(ch),
            _ => {}
        }
    }
    out.replace("&nbsp;", " ")
        .replace("&amp;", "&")
        .replace("&#39;", "'")
        .replace("&quot;", "\"")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

/// The cells of every `<tr>` of `html`, in page order.
fn table_rows(html: &str) -> Vec<Vec<String>> {
    let lower = html.to_ascii_lowercase();
    let mut rows = Vec::new();
    let mut at = 0;
    while let Some(start) = lower[at..].find("<tr") {
        let start = at + start;
        let Some(end) = lower[start..].find("</tr>") else {
            break;
        };
        let end = start + end;
        let row = &html[start..end];
        let row_lower = row.to_ascii_lowercase();
        let mut cells = Vec::new();
        let mut cursor = 0;
        while let Some(cell) = row_lower[cursor..]
            .find("<td")
            .or_else(|| row_lower[cursor..].find("<th"))
        {
            let cell = cursor + cell;
            let Some(open) = row[cell..].find('>') else {
                break;
            };
            let content_at = cell + open + 1;
            let Some(close) = row_lower[content_at..]
                .find("</td>")
                .or_else(|| row_lower[content_at..].find("</th>"))
            else {
                break;
            };
            let close = content_at + close;
            cells.push(cell_text(&row[content_at..close]));
            cursor = close;
        }
        rows.push(cells);
        at = end;
    }
    rows
}

/// The states of the LGD state page: rows of its table whose 2nd cell is the
/// numeric state code.
///
/// # Errors
///
/// Fails when the header row is missing, no state row is found, or a code
/// repeats.
pub fn parse_states_page(html: &str) -> Result<Vec<LgdState>> {
    let rows = table_rows(html);
    let header = rows
        .iter()
        .position(|row| {
            row.iter()
                .any(|cell| cell.eq_ignore_ascii_case("state lgd code"))
        })
        .ok_or_else(|| DatasetError::data("no \"State LGD Code\" header on the page"))?;
    let mut states: Vec<LgdState> = Vec::new();
    for row in &rows[header + 1..] {
        let code = row.get(1).map_or("", String::as_str);
        let name = row.get(2).map_or("", String::as_str);
        let kind = row.get(4).map_or("", String::as_str);
        if !code.bytes().all(|byte| byte.is_ascii_digit()) || code.is_empty() || name.is_empty() {
            continue;
        }
        if states.iter().any(|state| state.code == code) {
            return Err(DatasetError::data(format!("state code {code} repeats")));
        }
        states.push(LgdState {
            code: code.to_owned(),
            name: name.to_owned(),
            kind: kind.to_owned(),
        });
    }
    if states.is_empty() {
        return Err(DatasetError::data("no state rows on the page"));
    }
    Ok(states)
}

/// The header key of a CSV column.
fn header_key(header: &str) -> String {
    header
        .trim_start_matches('\u{feff}')
        .to_lowercase()
        .split(|ch: char| !ch.is_ascii_alphanumeric())
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Whether `key` is a state code column.
fn is_state_code(key: &str) -> bool {
    key == "state code" || key == "state lgd code"
}

/// Whether `key` is a district code column.
fn is_district_code(key: &str) -> bool {
    key == "district code" || key == "district lgd code"
}

/// Whether `key` is a district-name column.
fn is_district_name(key: &str) -> bool {
    matches!(
        key,
        "district name" | "district name in english" | "district name english"
    )
}

/// The districts of an LGD district list CSV.
///
/// # Errors
///
/// Fails when a column is missing, a row is malformed, or a code repeats.
pub fn parse_districts_csv(text: &str) -> Result<Vec<LgdDistrict>> {
    let rows = parse_csv_rows(text)?;
    let at = rows
        .iter()
        .position(|row| {
            let keys: Vec<String> = row.iter().map(|header| header_key(header)).collect();
            keys.iter().any(|key| is_state_code(key))
                && keys.iter().any(|key| is_district_code(key))
        })
        .ok_or_else(|| {
            DatasetError::data({
                format!(
                    "no header with a state code and a district code column (first row: {:?})",
                    rows.first()
                )
            })
        })?;
    let keys: Vec<String> = rows[at].iter().map(|header| header_key(header)).collect();
    let state = keys.iter().position(|key| is_state_code(key)).unwrap_or(0);
    let code = keys
        .iter()
        .position(|key| is_district_code(key))
        .unwrap_or(0);
    let name = keys
        .iter()
        .position(|key| is_district_name(key))
        .ok_or_else(|| DatasetError::data(format!("no district name column in {:?}", rows[at])))?;
    let mut districts: Vec<LgdDistrict> = Vec::new();
    for (index, row) in rows[at + 1..].iter().enumerate() {
        if row.iter().all(|cell| cell.trim().is_empty()) {
            continue;
        }
        let district = LgdDistrict {
            state_code: row.get(state).map_or("", String::as_str).trim().to_owned(),
            code: row.get(code).map_or("", String::as_str).trim().to_owned(),
            name: row.get(name).map_or("", String::as_str).trim().to_owned(),
        };
        let numeric =
            |value: &str| !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit());
        if !numeric(&district.state_code) || !numeric(&district.code) || district.name.is_empty() {
            return Err(DatasetError::data(format!(
                "row {}: bad district row {:?}",
                at + index + 2,
                row
            )));
        }
        if districts.iter().any(|known| known.code == district.code) {
            return Err(DatasetError::data(format!(
                "district code {} repeats",
                district.code
            )));
        }
        districts.push(district);
    }
    Ok(districts)
}

/// The rows of a CSV, quoted fields included.
fn parse_csv_rows(text: &str) -> Result<Vec<Vec<String>>> {
    crate::normals::parse_csv(text)
}

/// The states CSV text of `states`.
#[must_use]
pub fn states_csv(states: &[LgdState]) -> String {
    let quote = |field: &str| {
        if field.contains([',', '"', '\n']) {
            format!("\"{}\"", field.replace('"', "\"\""))
        } else {
            field.to_owned()
        }
    };
    let mut out = String::from("state_code,state_name,state_or_ut\n");
    for state in states {
        out.push_str(&format!(
            "{},{},{}\n",
            state.code,
            quote(&state.name),
            quote(&state.kind)
        ));
    }
    out
}

/// The states of a `states.csv`.
///
/// # Errors
///
/// Fails when the header is not the expected one.
pub fn read_states_csv(text: &str) -> Result<Vec<LgdState>> {
    let mut rows = parse_csv_rows(text)?;
    let header = rows.first().cloned().unwrap_or_default();
    if header.join(",") != "state_code,state_name,state_or_ut" {
        return Err(DatasetError::data(format!(
            "states.csv header is {header:?}"
        )));
    }
    rows.remove(0);
    Ok(rows
        .into_iter()
        .filter(|row| row.iter().any(|cell| !cell.is_empty()))
        .map(|row| LgdState {
            code: row.first().cloned().unwrap_or_default(),
            name: row.get(1).cloned().unwrap_or_default(),
            kind: row.get(2).cloned().unwrap_or_default(),
        })
        .collect())
}

/// Whether `text` is an ISO 8601 time with an offset that names an instant.
#[must_use]
pub fn is_iso_time(text: &str) -> bool {
    let bytes = text.as_bytes();
    // YYYY-MM-DDTHH:MM[:SS](Z|±HH:MM)
    if bytes.len() < 17
        || bytes[4] != b'-'
        || bytes[7] != b'-'
        || bytes[10] != b'T'
        || bytes[13] != b':'
    {
        return false;
    }
    let num = |range: std::ops::Range<usize>| -> Option<i64> {
        std::str::from_utf8(bytes.get(range)?).ok()?.parse().ok()
    };
    let (Some(year), Some(month), Some(day), Some(hour), Some(minute)) =
        (num(0..4), num(5..7), num(8..10), num(11..13), num(14..16))
    else {
        return false;
    };
    if !(1..=12).contains(&month) || !(1..=31).contains(&day) || days_of_date(&text[..10]).is_none()
    {
        return false;
    }
    if hour >= 24 || minute >= 60 {
        return false;
    }
    let rest = &text[16..];
    let rest = match rest.strip_prefix(':') {
        Some(rest) => rest,
        None => rest,
    };
    if rest.starts_with(':') {
        let Some(second) = rest.get(1..3).and_then(|value| value.parse::<u32>().ok()) else {
            return false;
        };
        if second >= 60 {
            return false;
        }
    }
    let _ = year;
    true
}

/// The text of `url`, up to five tries, 2 s × try apart.
fn fetch_text(url: &str) -> Result<String> {
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(60)))
        .build()
        .into();
    let mut attempt = 1;
    loop {
        match agent.get(url).call() {
            Ok(mut response) if response.status().is_success() => {
                return response
                    .body_mut()
                    .with_config()
                    .limit(16 * 1024 * 1024)
                    .read_to_string()
                    .within(format!("reading {url}"));
            }
            Ok(response) => {
                if attempt >= 5 {
                    return Err(DatasetError::data(format!(
                        "fetching {url}: HTTP {}",
                        response.status()
                    )));
                }
            }
            Err(error) => {
                if attempt >= 5 {
                    return Err(error).within(format!("fetching {url}"));
                }
            }
        }
        std::thread::sleep(Duration::from_secs(2 * attempt));
        attempt += 1;
    }
}

/// Write `text` at `path` through `<name>.tmp` and a rename.
fn write_atomic(path: &Path, text: &str) -> Result<()> {
    let tmp = path.with_extension("tmp");
    fs::write(&tmp, text).io_at(IoOp::Write, &tmp)?;
    fs::rename(&tmp, path).io_at(IoOp::RenameTo, path)
}

/// The `source.json` of `lgd_dir`.
fn read_source(lgd_dir: &Path) -> Map<String, Value> {
    fs::read_to_string(lgd_dir.join("source.json"))
        .ok()
        .and_then(|text| serde_json::from_str::<Value>(&text).ok())
        .and_then(|value| value.as_object().cloned())
        .unwrap_or_default()
}

/// Record `key` in `source.json`, with the acknowledgement.
fn update_source(
    lgd_dir: &Path,
    mut source: Map<String, Value>,
    key: &str,
    value: Value,
) -> Result<()> {
    source.insert(key.to_owned(), value);
    source.insert(
        "acknowledgement".to_owned(),
        Value::String(ACKNOWLEDGEMENT.to_owned()),
    );
    let mut text =
        serde_json::to_string_pretty(&Value::Object(source)).json_of("serializing source.json")?;
    text.push('\n');
    write_atomic(&lgd_dir.join("source.json"), &text)
}

/// The current UTC time as `YYYY-MM-DDTHH:MM:SSZ`.
fn utc_now() -> String {
    crate::layout::utc_now()
}

/// `states`: the LGD state page into `states.csv`.
///
/// # Errors
///
/// Fails when the page cannot be fetched or parsed, or a file cannot be
/// written.
pub fn states(force: bool, html: Option<&Path>, lgd_dir: &Path) -> Result<()> {
    fs::create_dir_all(lgd_dir).io_at(IoOp::Create, lgd_dir)?;
    let out = lgd_dir.join("states.csv");
    if out.is_file() && !force {
        let text = fs::read_to_string(&out).io_at(IoOp::Read, &out)?;
        println!(
            "states: {} (kept {})",
            read_states_csv(&text)?.len(),
            out.display()
        );
        return Ok(());
    }
    let page = match html {
        Some(path) => fs::read_to_string(path).io_at(IoOp::Read, path)?,
        None => fetch_text(STATES_URL)?,
    };
    let states = parse_states_page(&page)?;
    write_atomic(&out, &states_csv(&states))?;
    update_source(
        lgd_dir,
        read_source(lgd_dir),
        "states",
        json!({
            "url": STATES_URL,
            "fetched_at": utc_now(),
            "count": states.len(),
            "terms_url": TERMS_URL,
            "terms": TERMS,
        }),
    )?;
    println!("states: {} (wrote {})", states.len(), out.display());
    Ok(())
}

/// `districts`: check the owner-saved list and record it.
///
/// # Errors
///
/// Fails with [`Exit`] `1` and the manual step when the file is missing, and
/// on a malformed list, an unchanged-file mismatch, or a write error.
pub fn districts(lgd_dir: &Path, downloaded_at: Option<&str>) -> Result<usize> {
    fs::create_dir_all(lgd_dir).io_at(IoOp::Create, lgd_dir)?;
    let path = lgd_dir.join(DISTRICTS_FILE);
    if !path.is_file() {
        return Err(DatasetError::data(format!(
            "{} is missing. Manual step: {}",
            path.display(),
            manual_step(lgd_dir)
        )));
    }
    let text = fs::read_to_string(&path).io_at(IoOp::Read, &path)?;
    let districts = parse_districts_csv(&text)?;
    let mut source = read_source(lgd_dir);
    let earlier = source.get("districts").cloned().unwrap_or(Value::Null);
    let sha256 = hex(&sha256_file(&path)?);
    let original = lgd_dir.join(ORIGINAL_FILE);
    let original_sha = if original.is_file() {
        Some(hex(&sha256_file(&original)?))
    } else {
        None
    };
    let earlier_sha = earlier.get("sha256").and_then(Value::as_str);
    let earlier_original = earlier
        .get("original")
        .and_then(|value| value.get("sha256"))
        .and_then(Value::as_str);
    let same_files =
        earlier_sha == Some(sha256.as_str()) && earlier_original == original_sha.as_deref();
    if downloaded_at.is_none() && earlier.get("downloaded_at").is_some() && !same_files {
        eprintln!("lgd: the district files changed; downloaded_at dropped (pass --downloaded-at)");
    }
    let downloaded = downloaded_at.map(str::to_owned).or_else(|| {
        same_files
            .then(|| {
                earlier
                    .get("downloaded_at")
                    .and_then(Value::as_str)
                    .map(str::to_owned)
            })
            .flatten()
    });
    let saved_at = crate::layout::format_utc(
        i64::try_from(crate::layout::modified_millis(&path)? / 1000).unwrap_or_default(),
    );
    let mut entry = serde_json::Map::new();
    entry.insert("file".into(), Value::String(DISTRICTS_FILE.into()));
    entry.insert("from".into(), Value::String(DOWNLOAD_URL.into()));
    entry.insert("report".into(), Value::String(REPORT.into()));
    entry.insert("format".into(), Value::String(REPORT_FORMAT.into()));
    if let Some(downloaded) = downloaded {
        entry.insert("downloaded_at".into(), Value::String(downloaded));
    }
    if let Some(sha) = original_sha {
        entry.insert(
            "original".into(),
            json!({ "file": ORIGINAL_FILE, "sha256": sha }),
        );
    }
    entry.insert("saved_at".into(), Value::String(saved_at));
    entry.insert("sha256".into(), Value::String(sha256));
    entry.insert("count".into(), json!(districts.len()));
    entry.insert("terms_url".into(), Value::String(TERMS_URL.into()));
    entry.insert("terms".into(), Value::String(TERMS.into()));
    update_source(lgd_dir, source.clone(), "districts", Value::Object(entry))?;
    let _ = &mut source;
    println!("districts: {} ({})", districts.len(), path.display());
    Ok(districts.len())
}

/// Run `geolith dataset lgd`.
///
/// # Errors
///
/// Fails with [`Exit`] `2` on a usage error, and propagates the verb's
/// errors.
pub fn run(args: &LgdArgs) -> Result<()> {
    match &args.action {
        LgdAction::States(states_args) => {
            states(
                states_args.force,
                states_args.html.as_deref(),
                &ldg_dir(args)?,
            )?;
        }
        LgdAction::Districts(districts_args) => {
            if let Some(at) = districts_args.downloaded_at.as_deref()
                && !is_iso_time(at)
            {
                eprintln!("--downloaded-at needs an ISO 8601 time with an offset, got {at:?}");
                return Err(Exit(2).into());
            }
            districts(&ldg_dir(args)?, districts_args.downloaded_at.as_deref())?;
        }
    }
    Ok(())
}

/// The LGD dir: `LGD_DIR`, else `$DATA_ROOT/datasets/lgd`.
fn ldg_dir(args: &LgdArgs) -> Result<std::path::PathBuf> {
    if let Some(dir) = args.dir.clone() {
        return Ok(dir);
    }
    if let Some(dir) = crate::settings::current().run.lgd_dir.clone() {
        return Ok(dir);
    }
    Ok(crate::layout::data_root()?.join("datasets").join("lgd"))
}

/// A `BTreeMap` of the recorded source entries (for the crosswalk comments).
#[must_use]
pub fn source_entries(lgd_dir: &Path) -> BTreeMap<String, Value> {
    read_source(lgd_dir).into_iter().collect()
}