colonizer 0.1.0

Catalogue of Life (ChecklistBank) client + CLI: search usages, browse tree, vernacular names, and an Inspire mode for crate-name ideas (with Wikipedia summaries).
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
use clap::{Parser, Subcommand, ValueEnum};
use colonizer::{ColClient, Error, Rank};
use indicatif::{ProgressBar, ProgressStyle};
use serde_json::json;
use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;
use unicode_normalization::UnicodeNormalization;

#[derive(Parser, Debug)]
#[command(name = "colonizer", version, about = "Catalogue of Life helper CLI")]
struct Cli {
    /// Override the dataset key (defaults to latest CoL release)
    #[arg(long)]
    dataset: Option<i32>,

    /// Output JSON instead of tab-separated text
    #[arg(long)]
    json: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Print the latest CoL release dataset key
    Latest,
    /// Resolve COL id for a scientific name
    Id {
        /// Scientific name to match (exact)
        name: String,
        /// Optional rank to disambiguate (e.g. SPECIES, GENUS)
        #[arg(long)]
        rank: Option<Rank>,
    },
    /// Download a full CoL package from the static download server
    Download {
        /// Package format: dwca, coldp, or txtree
        #[arg(value_enum)]
        format: DlFormat,
        /// Use latest package instead of matching the selected dataset's month
        #[arg(long)]
        latest: bool,
        /// Specific monthly date (YYYY-MM-DD) to fetch
        #[arg(long)]
        date: Option<String>,
        /// Output file path (defaults to filename from URL)
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// List usages at a given rank (beware: can be huge!)
    ListRank {
        /// Rank to list (e.g. SPECIES, GENUS, FAMILY)
        rank: Rank,
        /// Maximum number of results to print (default 50)
        #[arg(long, default_value_t = 50)]
        max: usize,
    },
    /// List roots of the tree (e.g., domains)
    Roots {
        /// Maximum number of results to print (default 50)
        #[arg(long, default_value_t = 50)]
        max: usize,
    },
    /// List direct children of a taxon (by id or name)
    Children {
        /// Taxon usage id or exact scientific name
        target: String,
        /// Treat target as an id; otherwise try exact-name resolution
        #[arg(long)]
        by_id: bool,
        /// Optional rank to disambiguate names (e.g., GENUS)
        #[arg(long)]
        rank: Option<Rank>,
        /// Maximum number of results to print (default 50)
        #[arg(long, default_value_t = 50)]
        max: usize,
    },
    /// Show the classification chain for a taxon
    Classify {
        /// Taxon usage id or exact scientific name
        target: String,
        /// Treat target as an id; otherwise try exact-name resolution
        #[arg(long)]
        by_id: bool,
        /// Optional rank to disambiguate names (e.g., SPECIES, GENUS)
        #[arg(long)]
        rank: Option<Rank>,
    },
    /// Suggest name usages for a text query
    Suggest {
        /// Free-text query
        q: String,
        /// Maximum number of suggestions
        #[arg(long, default_value_t = 10)]
        limit: usize,
    },
    /// List vernacular (common) names for a taxon
    Vernacular {
        /// Taxon usage id or exact scientific name
        target: String,
        /// Treat target as an id; otherwise try exact-name resolution
        #[arg(long)]
        by_id: bool,
        /// Optional rank to disambiguate names
        #[arg(long)]
        rank: Option<Rank>,
    },
    /// Pick a random vernacular name for a language via API
    Inspire {
        /// Language code to filter (e.g., fra)
        #[arg(long, default_value = "fra")]
        lang: String,
        /// Only one-word names (no spaces)
        #[arg(long)]
        one_word: bool,
    },
}

fn main() -> Result<(), Error> {
    let cli = Cli::parse();
    let client = match cli.dataset {
        Some(key) => ColClient::with_dataset_key(key)?,
        None => ColClient::from_latest()?,
    };

    match cli.command {
        Commands::Latest => {
            if cli.json {
                println!("{}", json!({"dataset_key": client.dataset_key}));
            } else {
                println!("{}", client.dataset_key);
            }
        }
        Commands::Id { name, rank } => match client.id_for_name(&name, rank)? {
            Some(id) => {
                if cli.json {
                    println!("{}", json!({"id": id}));
                } else {
                    println!("{}", id);
                }
            }
            None => {
                eprintln!("No match found");
                std::process::exit(1);
            }
        },
        Commands::ListRank { rank, max } => {
            let items = client.list_by_rank(rank, Some(max))?;
            if cli.json {
                println!("{}", serde_json::to_string(&items)?);
            } else {
                for it in items {
                    println!(
                        "{}\t{}\t{}",
                        it.id,
                        it.label,
                        it.rank.map(|r| r.to_string()).unwrap_or_default()
                    );
                }
            }
        }
        Commands::Roots { max } => {
            let items = client.roots(Some(max))?;
            if cli.json {
                println!("{}", serde_json::to_string(&items)?);
            } else {
                for it in items {
                    let label = it.name.unwrap_or_default();
                    let rank = it.rank.map(|r| r.to_string()).unwrap_or_default();
                    println!("{}\t{}\t{}", it.id, label, rank);
                }
            }
        }
        Commands::Download {
            format,
            latest,
            date,
            output,
        } => {
            let url = build_download_url(&client, format, latest, date.as_deref())?;
            let fname = output.unwrap_or_else(|| {
                let seg = url
                    .path_segments()
                    .and_then(|mut s| s.next_back())
                    .unwrap_or("col.zip");
                PathBuf::from(seg)
            });
            let http = reqwest::blocking::Client::builder().build()?;
            let mut resp = http.get(url.clone()).send()?.error_for_status()?;

            let total = resp.content_length();
            let pb = match total {
                Some(len) => {
                    let pb = ProgressBar::new(len);
                    pb.set_style(
                        ProgressStyle::with_template(
                            "{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({eta})",
                        )
                        .unwrap()
                        .progress_chars("#>-"),
                    );
                    pb
                }
                None => {
                    let pb = ProgressBar::new_spinner();
                    pb.set_style(
                        ProgressStyle::with_template(
                            "{spinner:.green} downloading... [{elapsed_precise}] {bytes}",
                        )
                        .unwrap(),
                    );
                    pb.enable_steady_tick(std::time::Duration::from_millis(100));
                    pb
                }
            };

            let mut file = File::create(&fname)?;
            let mut downloaded: u64 = 0;
            let mut buf = vec![0u8; 64 * 1024];
            loop {
                let n = resp.read(&mut buf)?;
                if n == 0 {
                    break;
                }
                file.write_all(&buf[..n])?;
                downloaded += n as u64;
                pb.set_position(downloaded);
            }
            pb.finish_and_clear();

            if cli.json {
                println!(
                    "{}",
                    json!({"url": url.as_str(), "bytes": downloaded, "path": fname})
                );
            } else {
                eprintln!(
                    "Downloaded {} bytes from {} to {}",
                    downloaded,
                    url,
                    fname.display()
                );
            }
        }
        Commands::Children {
            target,
            by_id,
            rank,
            max,
        } => {
            let id = if by_id {
                target.clone()
            } else {
                resolve_id_or_with_rank(&client, &target, rank)?
            };
            let items = client.children_of(&id, Some(max))?;
            if cli.json {
                println!("{}", serde_json::to_string(&items)?);
            } else {
                for it in items {
                    let label = it.name.unwrap_or_default();
                    let rank = it.rank.map(|r| r.to_string()).unwrap_or_default();
                    println!("{}\t{}\t{}", it.id, label, rank);
                }
            }
        }
        Commands::Classify {
            target,
            by_id,
            rank,
        } => {
            let id = if by_id {
                target.clone()
            } else {
                resolve_id_or_with_rank(&client, &target, rank)?
            };
            let chain = client.classification_of(&id)?;
            if cli.json {
                println!("{}", serde_json::to_string(&chain)?);
            } else {
                for n in chain {
                    let name = n.label.unwrap_or(n.name);
                    println!(
                        "{}\t{}\t{}",
                        n.id,
                        name,
                        n.rank.map(|r| r.to_string()).unwrap_or_default()
                    );
                }
            }
        }
        Commands::Suggest { q, limit } => {
            let items = client.suggest(&q, limit)?;
            if cli.json {
                println!("{}", serde_json::to_string(&items)?);
            } else {
                for it in items {
                    let s = it.suggestion.unwrap_or(it.match_.clone());
                    let rank = it.rank.map(|r| r.to_string()).unwrap_or_default();
                    let status = it.status.unwrap_or_default();
                    println!("{}\t{}\t{}\t{}", it.usage_id, s, rank, status);
                }
            }
        }
        Commands::Vernacular {
            target,
            by_id,
            rank,
        } => {
            let id = if by_id {
                target.clone()
            } else {
                resolve_id_or_with_rank(&client, &target, rank)?
            };
            let names = client.vernacular_of(&id)?;
            if cli.json {
                println!("{}", serde_json::to_string(&names)?);
            } else {
                for v in names {
                    println!("{}\t{}", v.name, v.language.unwrap_or_default());
                }
            }
        }
        Commands::Inspire { lang, one_word } => {
            // Use API to find a random vernacular name for the language
            let tries = if one_word { 64 } else { 24 };
            match client.random_vernacular_by_language_filtered(&lang, one_word, tries)? {
                Some(v) => {
                    let usage = client.taxon(&v.taxon_id)?;
                    let sci = usage
                        .name
                        .and_then(|n| n.scientificName)
                        .unwrap_or_default();
                    let hyph = hyphenize_and_sanitize(&v.name);
                    let link = format!("https://www.catalogueoflife.org/data/taxon/{}", v.taxon_id);
                    let wiki_lang = wiki_lang_from_col(&lang);
                    let wiki = client.wikipedia_summary(&sci, wiki_lang).ok().flatten();
                    if cli.json {
                        let mut obj = serde_json::json!({
                            "lang": lang,
                            "vernacularName": v.name,
                            "vernacularHyphenized": hyph,
                            "taxonID": v.taxon_id,
                            "scientificName": sci,
                            "link": link,
                            "oneWord": one_word,
                        });
                        if let Some(info) = wiki {
                            let m = obj.as_object_mut().unwrap();
                            m.insert("wikipediaSummary".to_string(), serde_json::Value::String(info.extract));
                            m.insert("wikipediaLang".to_string(), serde_json::Value::String(info.lang));
                            if !info.wikipedia_url.is_empty() {
                                m.insert("wikipediaUrl".to_string(), serde_json::Value::String(info.wikipedia_url));
                            }
                            if let Some(url) = info.wikidata_url { m.insert("wikidataUrl".to_string(), serde_json::Value::String(url)); }
                        }
                        println!("{}", obj);
                    } else {
                        if let Some(info) = wiki {
                            if !info.wikipedia_url.is_empty() {
                                if let Some(wd) = info.wikidata_url {
                                    println!(
                                        "{}\t{}\t{}\t{}\n[{} wiki] {}\n{}\n{}",
                                        hyph, v.taxon_id, sci, link,
                                        info.lang, info.extract,
                                        info.wikipedia_url,
                                        wd
                                    );
                                } else {
                                    println!(
                                        "{}\t{}\t{}\t{}\n[{} wiki] {}\n{}",
                                        hyph, v.taxon_id, sci, link,
                                        info.lang, info.extract,
                                        info.wikipedia_url
                                    );
                                }
                            } else {
                                println!("{}\t{}\t{}\t{}\n[{} wiki] {}", hyph, v.taxon_id, sci, link, info.lang, info.extract);
                            }
                        } else {
                            println!("{}\t{}\t{}\t{}", hyph, v.taxon_id, sci, link);
                        }
                    }
                }
                None => {
                    eprintln!("No matching vernacular found (lang='{}', one_word={}).", lang, one_word);
                    std::process::exit(1);
                }
            }
        }
    }

    Ok(())
}

fn resolve_id_or_with_rank(
    client: &ColClient,
    target: &str,
    rank: Option<Rank>,
) -> Result<String, Error> {
    if let Some(id) = client.id_for_name(target, rank)? {
        return Ok(id);
    }
    Ok(target.to_string())
}

#[derive(Copy, Clone, Debug, ValueEnum)]
enum DlFormat {
    Dwca,
    Coldp,
    Txtree,
}

impl DlFormat {
    fn suffix(self) -> &'static str {
        match self {
            DlFormat::Dwca => "dwca",
            DlFormat::Coldp => "coldp",
            DlFormat::Txtree => "txtree",
        }
    }
}

fn build_download_url(
    client: &ColClient,
    fmt: DlFormat,
    latest: bool,
    date: Option<&str>,
) -> Result<reqwest::Url, Error> {
    let base = reqwest::Url::parse("https://download.checklistbank.org")?;
    let suffix = fmt.suffix();
    if let Some(d) = date {
        return Ok(base.join(&format!("/col/monthly/{}_{}.zip", d, suffix))?);
    }
    if latest {
        return Ok(base.join(&format!("/col/latest_{}.zip", suffix))?);
    }
    // Default: use the selected dataset's created date
    let ds = client.dataset_meta()?;
    let created = ds.created.unwrap_or_default();
    if created.len() >= 10 {
        let date = &created[..10];
        Ok(base.join(&format!("/col/monthly/{}_{}.zip", date, suffix))?)
    } else {
        // Fallback to latest if created is missing or malformed
        Ok(base.join(&format!("/col/latest_{}.zip", suffix))?)
    }
}

fn hyphenize_and_sanitize(s: &str) -> String {
    let t = s.trim();
    if t.is_empty() {
        return String::new();
    }
    // Replace whitespace with hyphens and lowercase
    // Remove accents and non-alphanumeric characters except hyphens
    // e.g. "Éléphant d'Afrique" -> "elephant-d-afrique"
    t.split_whitespace()
        .collect::<Vec<_>>()
        .join("-")
        .to_lowercase()
        .nfd() // decompose accents
        .filter(|c| c.is_ascii_alphanumeric() || *c == '-') // keep only alnum and hyphen
        .collect()
}

fn wiki_lang_from_col(lang3: &str) -> &str {
    match lang3.to_ascii_lowercase().as_str() {
        "eng" => "en",
        "fra" | "fre" => "fr",
        "spa" => "es",
        "deu" | "ger" => "de",
        "ita" => "it",
        "por" => "pt",
        "nld" | "dut" => "nl",
        "rus" => "ru",
        "zho" | "chi" => "zh",
        "jpn" => "ja",
        "kor" => "ko",
        "pol" => "pl",
        "ara" => "ar",
        "heb" => "he",
        "ell" | "gre" => "el",
        "tur" => "tr",
        "ces" | "cze" => "cs",
        "ukr" => "uk",
        "swe" => "sv",
        "dan" => "da",
        "nor" => "no",
        "fin" => "fi",
        "ron" | "rum" => "ro",
        "hun" => "hu",
        "bul" => "bg",
        "slv" => "sl",
        "hrv" => "hr",
        "vie" => "vi",
        "tha" => "th",
        "ind" => "id",
        "msa" | "may" => "ms",
        "fas" | "per" => "fa",
        "urd" => "ur",
        "tam" => "ta",
        "tel" => "te",
        "mar" => "mr",
        "guj" => "gu",
        _ => "en",
    }
}