grobid 0.3.0

Native Rust client for the GROBID REST API with a strongly typed TEI parser
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
//! BibTeX rendering for parsed bibliographic records.
//!
//! This module adapts the strongly typed [`crate::tei::Biblio`] records onto
//! the [`biblatex`] crate, which handles BibTeX/BibLaTeX parsing, writing
//! and field typing. Using a full-fidelity BibTeX library (instead of
//! hand-rolled string formatting) gives proper escaping, typed person lists
//! and dates, and opens the door to reading back `.bib` files — e.g. for
//! deduplicating or correcting references.
//!
//! The `pdf2bibtex` and `refs2bibtex` examples use these helpers.

use std::collections::HashSet;
use std::path::Path;

use biblatex::{Chunk, Date, DateValue, Datetime, Entry, EntryType, Person, Spanned};

use crate::tei::{Author, Biblio};

/// Pick a BibLaTeX entry type based on the available metadata.
///
/// * [`EntryType::Article`] for journal articles,
/// * [`EntryType::InCollection`] for chapters in a book,
/// * [`EntryType::InProceedings`] for conference series papers,
/// * [`EntryType::TechReport`] for records with an issuing institution,
/// * [`EntryType::Book`] for records with a publisher,
/// * [`EntryType::Misc`] otherwise.
///
/// ```
/// use grobid::{bibtex, Biblio};
///
/// let biblio = Biblio {
///     journal: Some("Nature".to_string()),
///     ..Biblio::default()
/// };
/// assert_eq!(bibtex::entry_type(&biblio), biblatex::EntryType::Article);
///
/// let biblio = Biblio {
///     title: Some("A dataset".to_string()),
///     ..Biblio::default()
/// };
/// assert_eq!(bibtex::entry_type(&biblio), biblatex::EntryType::Misc);
/// ```
pub fn entry_type(biblio: &Biblio) -> EntryType {
    if biblio.journal.is_some() {
        EntryType::Article
    } else if biblio.book_title.is_some() {
        EntryType::InCollection
    } else if biblio.series_title.is_some() {
        EntryType::InProceedings
    } else if biblio.institution.is_some() {
        EntryType::TechReport
    } else if biblio.publisher.is_some() {
        EntryType::Book
    } else {
        EntryType::Misc
    }
}

/// Extract the publication year (first four digits) from the date.
///
/// ```
/// use grobid::{bibtex, Biblio};
///
/// let biblio = Biblio {
///     date: Some("2019-01-30".to_string()),
///     ..Biblio::default()
/// };
/// assert_eq!(bibtex::year(&biblio).as_deref(), Some("2019"));
/// assert_eq!(bibtex::year(&Biblio::default()), None);
/// ```
pub fn year(biblio: &Biblio) -> Option<String> {
    let date = biblio.date.as_deref()?;
    let digits: String = date
        .chars()
        .take_while(|c| c.is_ascii_digit())
        .take(4)
        .collect();
    if digits.is_empty() {
        None
    } else {
        Some(digits)
    }
}

/// Suggest a BibTeX key from the first author's surname and the publication
/// year, e.g. `Kahle2000`. Falls back to `ref` when neither is known. The
/// key is filtered to ASCII alphanumerics.
///
/// Use [`unique_key`] when the suggested key must be collision-free.
///
/// ```
/// use grobid::{bibtex, Author, Biblio};
///
/// let biblio = Biblio {
///     authors: vec![Author {
///         surname: Some("Milašauskienė".to_string()),
///         ..Author::default()
///     }],
///     date: Some("2003".to_string()),
///     ..Biblio::default()
/// };
/// assert_eq!(bibtex::suggest_key(&biblio), "Milaauskien2003");
/// assert_eq!(bibtex::suggest_key(&Biblio::default()), "ref");
/// ```
pub fn suggest_key(biblio: &Biblio) -> String {
    let surname = biblio
        .authors
        .first()
        .and_then(|author| author.surname.as_deref())
        .unwrap_or_default();
    let base = format!("{surname}{}", year(biblio).unwrap_or_default());
    let key: String = base.chars().filter(char::is_ascii_alphanumeric).collect();
    if key.is_empty() {
        "ref".to_string()
    } else {
        key
    }
}

/// Return a citation key that is unique within `used`, derived from
/// [`suggest_key`] and extended with `-2`, `-3`, ... suffixes on
/// collisions. The returned key is inserted into `used`.
///
/// For deterministic output, feed the records in a stable order (e.g.
/// sorted by [`suggest_key`]).
///
/// ```
/// use std::collections::HashSet;
///
/// use grobid::{bibtex, Author, Biblio};
///
/// let make = |surname: &str| Biblio {
///     authors: vec![Author {
///         surname: Some(surname.to_string()),
///         ..Author::default()
///     }],
///     date: Some("2020".to_string()),
///     ..Biblio::default()
/// };
///
/// let mut used = HashSet::new();
/// assert_eq!(bibtex::unique_key(&make("Smith"), &mut used), "Smith2020");
/// assert_eq!(bibtex::unique_key(&make("Smith"), &mut used), "Smith2020-2");
/// assert_eq!(bibtex::unique_key(&make("Jones"), &mut used), "Jones2020");
/// ```
pub fn unique_key(biblio: &Biblio, used: &mut HashSet<String>) -> String {
    let base = suggest_key(biblio);
    if used.insert(base.clone()) {
        return base;
    }
    let mut suffix = 2usize;
    loop {
        let key = format!("{base}-{suffix}");
        if used.insert(key.clone()) {
            return key;
        }
        suffix += 1;
    }
}

/// Convert a bibliographic record into a typed BibLaTeX entry.
///
/// Authors and editors become typed person lists, the GROBID date (year,
/// year-month or year-month-day) becomes a typed date, and the remaining
/// fields become plain text values. The returned entry can be serialized
/// with [`Entry::to_bibtex_string`], inspected with the typed getters, or
/// inserted into a [`biblatex::Bibliography`].
///
/// ```
/// use grobid::{bibtex, Author, Biblio};
///
/// let biblio = Biblio {
///     authors: vec![Author {
///         given_name: Some("Brewster".to_string()),
///         surname: Some("Kahle".to_string()),
///         ..Author::default()
///     }],
///     title: Some("Dummy Example File".to_string()),
///     date: Some("2000-03-01".to_string()),
///     ..Biblio::default()
/// };
///
/// let entry = bibtex::to_entry("kahle2000", &biblio);
///
/// // The entry is typed, not just text: fields can be read back through
/// // the biblatex getters.
/// let authors = entry.get_as::<Vec<biblatex::Person>>("author").unwrap();
/// assert_eq!(authors[0].name, "Kahle");
/// assert_eq!(authors[0].given_name, "Brewster");
/// println!("{}", entry.to_bibtex_string().unwrap());
/// ```
pub fn to_entry(key: &str, biblio: &Biblio) -> Entry {
    let mut entry = Entry::new(key.to_string(), entry_type(biblio));

    let authors = persons(&biblio.authors);
    if !authors.is_empty() {
        entry.set_as("author", &authors);
    }
    let editors = persons(&biblio.editors);
    if !editors.is_empty() {
        entry.set_as("editor", &editors);
    }
    for (name, value) in [
        ("title", &biblio.title),
        ("booktitle", &biblio.book_title),
        ("journaltitle", &biblio.journal),
        ("series", &biblio.series_title),
        ("volume", &biblio.volume),
        ("number", &biblio.issue),
        ("pages", &biblio.pages),
        ("publisher", &biblio.publisher),
        ("institution", &biblio.institution),
        ("doi", &biblio.doi),
        ("url", &biblio.url),
        ("issn", &biblio.issn),
        ("note", &biblio.note),
    ] {
        set_text(&mut entry, name, value);
    }
    if let Some(date) = date(&biblio.date) {
        entry.set_as("date", &date);
    }
    entry
}

/// Render one record as a BibTeX entry.
///
/// ```
/// use grobid::{bibtex, Author, Biblio};
///
/// let biblio = Biblio {
///     authors: vec![Author {
///         given_name: Some("Brewster".to_string()),
///         surname: Some("Kahle".to_string()),
///         ..Author::default()
///     }],
///     title: Some("Dummy Example File".to_string()),
///     journal: Some("Journal of Fake News".to_string()),
///     date: Some("2000".to_string()),
///     ..Biblio::default()
/// };
///
/// let entry = bibtex::format_entry("kahle2000", &biblio);
/// assert!(entry.starts_with("@article{kahle2000,\n"));
/// assert!(entry.contains("author = {Kahle, Brewster},"));
/// assert!(entry.contains("journal = {Journal of Fake News},"));
/// ```
///
/// # Panics
///
/// This function does not panic for any input: entries built from typed
/// values in [`to_entry`] always serialize, and unparseable dates are
/// emitted as a literal `date = {...}` field rather than causing an error.
/// The internal assertion on that invariant exists so that a future
/// regression surfaces as a panic instead of a silently truncated entry.
pub fn format_entry(key: &str, biblio: &Biblio) -> String {
    render(to_entry(key, biblio))
}

/// Render one record as a BibTeX entry with a `file` field.
///
/// Like [`format_entry`], but records `file` (typically the path of the
/// document the metadata was extracted from) in the entry's `file` field,
/// so that reference managers can open the document. The path is written
/// verbatim; relative paths are kept as given.
///
/// ```
/// use grobid::{bibtex, Author, Biblio};
///
/// let biblio = Biblio {
///     authors: vec![Author {
///         given_name: Some("Brewster".to_string()),
///         surname: Some("Kahle".to_string()),
///         ..Author::default()
///     }],
///     title: Some("Dummy Example File".to_string()),
///     date: Some("2000".to_string()),
///     ..Biblio::default()
/// };
///
/// let entry = bibtex::format_entry_with_file("kahle2000", &biblio, "/papers/kahle2000.pdf");
/// assert!(entry.contains("file = {/papers/kahle2000.pdf},"));
/// ```
///
/// # Panics
///
/// See [`format_entry`]: entries built from typed values always serialize.
pub fn format_entry_with_file(key: &str, biblio: &Biblio, file: impl AsRef<Path>) -> String {
    let mut entry = to_entry(key, biblio);
    entry.set(
        "file",
        vec![Spanned::detached(Chunk::Normal(
            file.as_ref().to_string_lossy().into_owned(),
        ))],
    );
    render(entry)
}

/// Serialize an entry, treating a serialization failure as a bug.
fn render(entry: Entry) -> String {
    match entry.to_bibtex_string() {
        Ok(entry) => entry,
        // Unreachable in practice; prefer a panicking expect over silently
        // returning a truncated entry, because a bug here must be noticed.
        Err(err) => unreachable!("entries built from typed values always serialize: {err}"),
    }
}

/// Map GROBID authors onto typed BibLaTeX persons. Middle names are folded
/// into the given name; authors with neither surname nor full name are
/// dropped.
fn persons(authors: &[Author]) -> Vec<Person> {
    authors.iter().filter_map(person).collect()
}

fn person(author: &Author) -> Option<Person> {
    let given = [author.given_name.as_deref(), author.middle_name.as_deref()]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
        .join(" ");
    let name = author
        .surname
        .as_deref()
        .filter(|surname| !surname.is_empty())
        .map(str::to_string)
        .or_else(|| author.full_name.clone().filter(|n| !n.is_empty()))?;
    Some(Person {
        name,
        given_name: given,
        prefix: String::new(),
        suffix: String::new(),
        id: None,
        prefix_initials: None,
        given_initials: None,
        use_prefix: None,
    })
}

/// Parse a GROBID date (`YYYY`, `YYYY-MM` or `YYYY-MM-DD`) into a typed
/// BibLaTeX date. Dates without at least a four-digit year are dropped.
fn date(date: &Option<String>) -> Option<Date> {
    let raw = date.as_deref()?;
    let digits: String = raw.chars().filter(|c| c.is_ascii_digit()).take(8).collect();
    let year = digits.get(0..4)?.parse::<i32>().ok()?;
    let month = digits
        .get(4..6)
        .and_then(|m| m.parse::<u8>().ok())
        .filter(|m| (1..=12).contains(m))
        .map(|m| m - 1);
    let day = match month {
        Some(_) => digits
            .get(6..8)
            .and_then(|d| d.parse::<u8>().ok())
            .filter(|d| (1..=31).contains(d))
            .map(|d| d - 1),
        None => None,
    };
    Some(Date {
        value: DateValue::At(Datetime {
            year,
            month,
            day,
            time: None,
        }),
        uncertain: false,
        approximate: false,
    })
}

/// Set a field from a plain-text value, when present and non-empty.
fn set_text(entry: &mut Entry, name: &str, value: &Option<String>) {
    if let Some(value) = value.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
        entry.set(
            name,
            vec![Spanned::detached(Chunk::Normal(value.to_string()))],
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use biblatex::ChunksExt;

    fn author(surname: &str, given: Option<&str>) -> Author {
        Author {
            surname: Some(surname.to_string()),
            given_name: given.map(str::to_string),
            ..Author::default()
        }
    }

    #[test]
    fn test_suggest_key() {
        let biblio = Biblio {
            authors: vec![author("Milašauskienė", None)],
            date: Some("2003".to_string()),
            ..Biblio::default()
        };
        assert_eq!(suggest_key(&biblio), "Milaauskien2003");

        // Without author and date the key falls back to "ref"; uniqueness
        // is handled by unique_key.
        assert_eq!(suggest_key(&Biblio::default()), "ref");
    }

    #[test]
    fn test_year() {
        for (date, want) in [
            (Some("2019-01-30".to_string()), Some("2019")),
            (Some("2003".to_string()), Some("2003")),
            (Some("no digits".to_string()), None),
            (None, None),
        ] {
            let biblio = Biblio {
                date,
                ..Biblio::default()
            };
            assert_eq!(year(&biblio).as_deref(), want);
        }
    }

    #[test]
    fn test_entry_type() {
        assert_eq!(
            entry_type(&Biblio {
                journal: Some("X".to_string()),
                ..Biblio::default()
            }),
            EntryType::Article
        );
        assert_eq!(
            entry_type(&Biblio {
                book_title: Some("X".to_string()),
                ..Biblio::default()
            }),
            EntryType::InCollection
        );
        assert_eq!(
            entry_type(&Biblio {
                institution: Some("X".to_string()),
                ..Biblio::default()
            }),
            EntryType::TechReport
        );
        assert_eq!(
            entry_type(&Biblio {
                publisher: Some("X".to_string()),
                ..Biblio::default()
            }),
            EntryType::Book
        );
        assert_eq!(entry_type(&Biblio::default()), EntryType::Misc);
    }

    #[test]
    fn test_to_entry() {
        let mut biblio = Biblio::default();
        biblio.authors.push(author("Kahle", Some("Brewster")));
        biblio.authors.push(author("Doe", Some("J")));
        biblio.title = Some("Dummy Example File".to_string());
        biblio.journal = Some("Letters in the Alphabet".to_string());
        biblio.date = Some("2000-03-01".to_string());
        biblio.volume = Some("20".to_string());
        biblio.doi = Some("10.1234/example".to_string());

        let entry = to_entry("kahle2000", &biblio);
        assert_eq!(entry.entry_type, EntryType::Article);
        // The typed values round-trip through the field chunks.
        let authors: Vec<Person> = entry.get_as("author").expect("typed authors");
        assert_eq!(authors.len(), 2);
        assert_eq!(authors[0].name, "Kahle");
        assert_eq!(authors[0].given_name, "Brewster");
        let date: biblatex::Date = entry.get_as("date").expect("typed date");
        assert_eq!(
            date.value,
            DateValue::At(Datetime {
                year: 2000,
                month: Some(2),
                day: Some(0),
                time: None,
            })
        );
        assert_eq!(
            entry.get("doi").expect("doi").format_verbatim(),
            "10.1234/example"
        );
    }

    #[test]
    fn test_format_entry() {
        let mut biblio = Biblio::default();
        biblio.authors.push(author("Kahle", Some("Brewster")));
        biblio.authors.push(author("Doe", Some("J")));
        biblio.title = Some("Dummy Example File".to_string());
        biblio.date = Some("2000".to_string());
        biblio.volume = Some("20".to_string());

        let entry = format_entry("kahle2000", &biblio);
        assert!(entry.starts_with("@misc{kahle2000,"));
        assert!(entry.contains("author = {Kahle, Brewster and Doe, J},"));
        assert!(entry.contains("title = {Dummy Example File},"));
        assert!(entry.contains("year = {2000},"));
        assert!(entry.contains("volume = {20},"));
        assert!(entry.ends_with('}'));
    }

    #[test]
    fn test_format_entry_with_file() {
        let mut biblio = Biblio::default();
        biblio.authors.push(author("Kahle", Some("Brewster")));
        biblio.title = Some("Dummy Example File".to_string());
        biblio.date = Some("2000".to_string());

        let entry = format_entry_with_file("kahle2000", &biblio, "/papers/kahle2000.pdf");
        assert!(entry.contains("file = {/papers/kahle2000.pdf},"), "{entry}");
        // The field is read back verbatim, e.g. by a reference manager.
        let bibliography = biblatex::Bibliography::parse(&entry).expect("parse output");
        let parsed = bibliography.get("kahle2000").expect("entry by key");
        assert_eq!(
            parsed.get("file").expect("file").format_verbatim(),
            "/papers/kahle2000.pdf"
        );
    }

    #[test]
    fn test_roundtrip() {
        // Entries rendered to a .bib file must parse back into the same
        // typed values - the foundation for reading and deduplicating
        // references in the future.
        let mut biblio = Biblio::default();
        biblio.authors.push(author("Milašauskienė", Some("Žemyna")));
        biblio.title = Some("Dummy & \"quoted\" Example".to_string());
        biblio.journal = Some("A Journal".to_string());
        biblio.date = Some("2003-06-15".to_string());
        let key = unique_key(&biblio, &mut HashSet::new());
        let bibtex = format_entry(&key, &biblio);

        let bibliography = biblatex::Bibliography::parse(&bibtex).expect("parse output");
        let entry = bibliography.get(&key).expect("entry by key");
        assert_eq!(entry.entry_type, EntryType::Article);
        let authors: Vec<Person> = entry.get_as("author").expect("typed authors");
        assert_eq!(authors[0].name, "Milašauskienė");
        assert_eq!(authors[0].given_name, "Žemyna");
        // The BibTeX writer expands the date into year/month/day fields;
        // the typed getter falls back to them.
        let date = entry.date().expect("typed date");
        match date {
            biblatex::PermissiveType::Typed(date) => {
                assert_eq!(
                    date.value,
                    DateValue::At(Datetime {
                        year: 2003,
                        month: Some(5),
                        day: Some(14),
                        time: None,
                    })
                );
            }
            other => panic!("expected typed date, got {other:?}"),
        }
        assert_eq!(
            entry.get("title").expect("title").format_verbatim(),
            "Dummy & \"quoted\" Example"
        );
        // The escaped characters must have survived the round trip.
        assert!(bibtex.contains("&"));
        assert!(bibtex.contains("quoted"));
    }

    #[test]
    fn test_unique_key() {
        let make = |surname: &str| Biblio {
            authors: vec![author(surname, None)],
            date: Some("2020".to_string()),
            ..Biblio::default()
        };
        let mut used = HashSet::new();
        assert_eq!(unique_key(&make("Smith"), &mut used), "Smith2020");
        assert_eq!(unique_key(&make("Smith"), &mut used), "Smith2020-2");
        assert_eq!(unique_key(&make("Smith"), &mut used), "Smith2020-3");
        assert_eq!(unique_key(&make("Jones"), &mut used), "Jones2020");
    }
}