xberg 1.1.0

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 107 formats and 371 programming languages via tree-sitter code intelligence with async/sync APIs.
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
//! XML parsing and document structure traversal for JATS documents.

use crate::Result;
use crate::extractors::security::SecurityBudget;
use quick_xml::events::Event;

use crate::utils::xml_utils::EntityReader;

/// Extract the LaTeX for a `disp-formula` / `inline-formula` subtree.
///
/// JATS writes verbatim TeX in `tex-math` and the equation number in `label`.
pub(super) fn extract_formula_latex(reader: &mut EntityReader<'_>, budget: &mut SecurityBudget) -> Result<String> {
    crate::extraction::formula_xml::extract_formula_latex(
        reader,
        budget,
        &crate::extraction::formula_xml::FormulaElements {
            tex: "tex-math",
            label: Some("label"),
        },
    )
}

/// Extract text content from a JATS element and its children.
pub(super) fn extract_text_content(reader: &mut EntityReader<'_>, budget: &mut SecurityBudget) -> Result<String> {
    let mut text = String::new();
    let mut depth = 0;

    loop {
        budget.step()?;
        match reader.read_event() {
            Ok(Event::Start(_)) => {
                budget.enter()?;
                depth += 1;
            }
            Ok(Event::End(_)) => {
                budget.leave();
                if depth == 0 {
                    break;
                }
                depth -= 1;
                if !text.is_empty() && !text.ends_with('\n') {
                    text.push(' ');
                }
            }
            Ok(Event::Text(t)) => {
                let decoded = t.as_ref().to_string();
                if !decoded.trim().is_empty() {
                    budget.check_entity(&decoded)?;
                    budget.account_text(decoded.len())?;
                    text.push_str(&decoded);
                    text.push(' ');
                }
            }
            Ok(Event::CData(t)) => {
                let decoded = t.as_ref().to_string();
                if !decoded.trim().is_empty() {
                    budget.check_entity(&decoded)?;
                    budget.account_text(decoded.len())?;
                    text.push_str(&decoded);
                    text.push('\n');
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(crate::error::XbergError::parsing(format!("XML parsing error: {}", e)));
            }
            _ => {}
        }
    }

    Ok(text.trim().to_string())
}

/// Extract a formatted citation string from a `<ref>` element.
///
/// Parses structured `<element-citation>` children (person-group, article-title,
/// source, year, volume, fpage, lpage) into a conventional citation string like:
/// `Brown T, Davis K. Cognitive effects of caffeine. J Neurosci. 2002;15:234-241.`
///
/// Falls back to plain text extraction for `<mixed-citation>` or unrecognized structures.
pub(super) fn extract_citation_text(reader: &mut EntityReader<'_>, budget: &mut SecurityBudget) -> Result<String> {
    let mut depth: u32 = 0;
    let mut in_element_citation = false;
    let mut in_mixed_citation = false;
    let mut in_person_group = false;
    let mut in_name = false;

    let mut authors: Vec<String> = Vec::new();
    let mut current_surname = String::new();
    let mut current_given = String::new();
    let mut article_title = String::new();
    let mut source = String::new();
    let mut year = String::new();
    let mut volume = String::new();
    let mut fpage = String::new();
    let mut lpage = String::new();
    let mut doi = String::new();
    let mut publisher_name = String::new();
    let mut publisher_loc = String::new();

    let mut current_tag = String::new();

    let mut mixed_text = String::new();

    loop {
        budget.step()?;
        match reader.read_event() {
            Ok(Event::Start(e)) => {
                budget.enter()?;
                depth += 1;
                let tag = e.name().as_ref().to_string();

                match tag.as_str() {
                    "element-citation" => {
                        in_element_citation = true;
                    }
                    "mixed-citation" => {
                        in_mixed_citation = true;
                    }
                    "person-group" if in_element_citation => {
                        in_person_group = true;
                    }
                    "name" if in_person_group => {
                        in_name = true;
                        current_surname.clear();
                        current_given.clear();
                    }
                    "surname" | "given-names" | "article-title" | "source" | "year" | "volume" | "fpage" | "lpage"
                    | "publisher-name" | "publisher-loc"
                        if in_element_citation =>
                    {
                        current_tag = tag;
                    }
                    "pub-id" | "article-id" if in_element_citation => {
                        let mut id_type = String::new();
                        for attr in e.attributes().flatten() {
                            let key = std::borrow::Cow::Borrowed(attr.key.as_ref());
                            let val = std::borrow::Cow::Borrowed(attr.value.as_ref());
                            budget.check_attr(&key, &val)?;
                            if key == "pub-id-type" {
                                id_type = val.to_string();
                            }
                        }
                        if id_type == "doi" {
                            current_tag = "pub-id-doi".to_string();
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::End(e)) => {
                budget.leave();
                if depth == 0 {
                    break;
                }
                let tag = e.name().as_ref().to_string();

                match tag.as_str() {
                    "name" if in_name => {
                        in_name = false;
                        let mut author = String::new();
                        if !current_surname.is_empty() {
                            author.push_str(current_surname.trim());
                        }
                        if !current_given.is_empty() {
                            if !author.is_empty() {
                                author.push(' ');
                            }
                            author.push_str(current_given.trim());
                        }
                        if !author.is_empty() {
                            authors.push(author);
                        }
                    }
                    "person-group" => {
                        in_person_group = false;
                    }
                    "element-citation" => {
                        in_element_citation = false;
                    }
                    "mixed-citation" => {
                        in_mixed_citation = false;
                    }
                    _ => {}
                }

                current_tag.clear();
                depth -= 1;
            }
            Ok(Event::Text(t)) => {
                let decoded = t.as_ref().to_string();
                let trimmed = decoded.trim();

                if !trimmed.is_empty() {
                    budget.check_entity(trimmed)?;
                    budget.account_text(trimmed.len())?;
                    if in_mixed_citation {
                        if !mixed_text.is_empty() {
                            mixed_text.push(' ');
                        }
                        mixed_text.push_str(trimmed);
                    } else if in_element_citation {
                        match current_tag.as_str() {
                            "surname" => current_surname.push_str(trimmed),
                            "given-names" => current_given.push_str(trimmed),
                            "article-title" => {
                                if !article_title.is_empty() {
                                    article_title.push(' ');
                                }
                                article_title.push_str(trimmed);
                            }
                            "source" => source.push_str(trimmed),
                            "year" => year.push_str(trimmed),
                            "volume" => volume.push_str(trimmed),
                            "fpage" => fpage.push_str(trimmed),
                            "lpage" => lpage.push_str(trimmed),
                            "pub-id-doi" => doi.push_str(trimmed),
                            "publisher-name" => publisher_name.push_str(trimmed),
                            "publisher-loc" => publisher_loc.push_str(trimmed),
                            _ => {}
                        }
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(crate::error::XbergError::parsing(format!("XML parsing error: {}", e)));
            }
            _ => {}
        }
    }

    if !mixed_text.is_empty() {
        return Ok(mixed_text);
    }

    let mut citation = String::new();

    if !authors.is_empty() {
        citation.push_str(&authors.join(", "));
        citation.push_str(". ");
    }

    if !article_title.is_empty() {
        citation.push_str(&article_title);
        citation.push_str(". ");
    }

    if !source.is_empty() {
        citation.push_str(&source);
        citation.push('.');
    }

    if !year.is_empty() {
        citation.push(' ');
        citation.push_str(&year);
    }
    if !volume.is_empty() {
        citation.push(';');
        citation.push_str(&volume);
    }
    if !fpage.is_empty() {
        citation.push(':');
        citation.push_str(&fpage);
        if !lpage.is_empty() {
            citation.push('-');
            citation.push_str(&lpage);
        }
    }
    if !citation.is_empty() && !citation.ends_with('.') {
        citation.push('.');
    }

    if !publisher_name.is_empty() || !publisher_loc.is_empty() {
        if !citation.is_empty() {
            citation.push(' ');
        }
        if !publisher_loc.is_empty() {
            citation.push_str(&publisher_loc);
        }
        if !publisher_loc.is_empty() && !publisher_name.is_empty() {
            citation.push_str(": ");
        }
        if !publisher_name.is_empty() {
            citation.push_str(&publisher_name);
        }
        citation.push('.');
    }

    if !doi.is_empty() {
        if !citation.is_empty() {
            citation.push(' ');
        }
        citation.push_str("DOI: ");
        citation.push_str(&doi);
        citation.push('.');
    }

    Ok(citation.trim().to_string())
}

/// Extract structured content from a JATS `<fig>` element.
///
/// Parses `<label>`, `<caption>` (with nested `<title>`/`<p>`), and
/// `<graphic xlink:href="...">` so callers can associate the figure's caption
/// text with its graphic reference instead of dropping or flattening them.
///
/// Returns `(label, caption_text, graphic_href)`.
pub(super) fn extract_fig_content(
    reader: &mut EntityReader<'_>,
    budget: &mut SecurityBudget,
) -> Result<(Option<String>, Option<String>, Option<String>)> {
    let mut depth: u32 = 0;
    let mut in_caption = false;
    let mut current_tag = String::new();

    let mut label = String::new();
    let mut caption = String::new();
    let mut href: Option<String> = None;

    loop {
        budget.step()?;
        match reader.read_event() {
            Ok(Event::Start(e)) => {
                budget.enter()?;
                depth += 1;
                let name = e.name();
                let tag = crate::utils::xml_tag_name(name.as_ref()).to_string();

                match tag.as_str() {
                    "caption" => in_caption = true,
                    "label" | "title" | "p" => current_tag = tag.clone(),
                    "graphic" => {
                        for attr in e.attributes().flatten() {
                            let key = std::borrow::Cow::Borrowed(attr.key.as_ref());
                            let val = std::borrow::Cow::Borrowed(attr.value.as_ref());
                            budget.check_attr(&key, &val)?;
                            if key == "xlink:href" || key.ends_with(":href") || key == "href" {
                                href = Some(val.to_string());
                            }
                        }
                    }
                    _ => {}
                }
            }
            // `<graphic xlink:href="..."/>` is almost always self-closing, which quick-xml
            // reports as a standalone `Empty` event (no matching `Start`/`End` pair), so it
            // must be handled separately from `Event::Start` or the href is silently dropped.
            Ok(Event::Empty(e)) => {
                budget.enter()?;
                budget.leave();
                let name = e.name();
                let tag = crate::utils::xml_tag_name(name.as_ref());
                if tag.as_ref() == "graphic" {
                    for attr in e.attributes().flatten() {
                        let key = std::borrow::Cow::Borrowed(attr.key.as_ref());
                        let val = std::borrow::Cow::Borrowed(attr.value.as_ref());
                        budget.check_attr(&key, &val)?;
                        if key == "xlink:href" || key.ends_with(":href") || key == "href" {
                            href = Some(val.to_string());
                        }
                    }
                }
            }
            Ok(Event::End(e)) => {
                budget.leave();
                if depth == 0 {
                    break;
                }
                let name = e.name();
                let tag = crate::utils::xml_tag_name(name.as_ref());
                if tag.as_ref() == "caption" {
                    in_caption = false;
                }
                current_tag.clear();
                depth -= 1;
            }
            Ok(Event::Text(t)) => {
                let decoded = t.as_ref().to_string();
                let trimmed = decoded.trim();

                if !trimmed.is_empty() {
                    budget.check_entity(trimmed)?;
                    budget.account_text(trimmed.len())?;
                    match current_tag.as_str() {
                        "label" => {
                            if !label.is_empty() {
                                label.push(' ');
                            }
                            label.push_str(trimmed);
                        }
                        "title" | "p" if in_caption => {
                            if !caption.is_empty() {
                                caption.push(' ');
                            }
                            caption.push_str(trimmed);
                        }
                        _ => {}
                    }
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(crate::error::XbergError::parsing(format!("XML parsing error: {}", e)));
            }
            _ => {}
        }
    }

    Ok((
        if label.is_empty() { None } else { Some(label) },
        if caption.is_empty() { None } else { Some(caption) },
        href,
    ))
}