grobid 0.6.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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
//! Client for the GROBID REST API.
//!
//! [`GrobidClient`] talks to a running GROBID service (see
//! <https://grobid.readthedocs.io/>) and returns strongly typed, parsed TEI
//! structures. Requests are made asynchronously with `reqwest`; the client
//! retries requests with exponential backoff when the server responds with
//! HTTP 503 (all processing threads busy) or 429.

use std::path::PathBuf;
use std::time::Duration;

use reqwest::multipart::{Form, Part};
use reqwest::{Client, RequestBuilder, Response, StatusCode};
use url::Url;

use crate::tei::{parse_citation, parse_citation_list, parse_document, Citation, Document};
use crate::Error;

/// The default GROBID server URL (a locally running instance).
pub const DEFAULT_GROBID_URL: &str = "http://localhost:8070";

/// The fulltext processing service (`/api/processFulltextDocument`).
pub const SERVICE_FULLTEXT: &str = "processFulltextDocument";
/// The header processing service (`/api/processHeaderDocument`).
pub const SERVICE_HEADER: &str = "processHeaderDocument";
/// The reference extraction service (`/api/processReferences`).
pub const SERVICE_REFERENCES: &str = "processReferences";
/// The citation parsing service (`/api/processCitation`).
pub const SERVICE_CITATION: &str = "processCitation";
/// The citation list parsing service (`/api/processCitationList`).
pub const SERVICE_CITATION_LIST: &str = "processCitationList";

/// Retry policy for requests that hit a busy GROBID server (HTTP 503 or
/// 429). Retries are spaced with exponential backoff: the delay after the
/// n-th attempt is `initial_delay * multiplier^n`, capped at `max_delay`.
///
/// ```
/// use std::time::Duration;
///
/// use grobid::RetryPolicy;
///
/// let policy = RetryPolicy {
///     max_attempts: 3,
///     initial_delay: Duration::from_secs(1),
///     ..RetryPolicy::default()
/// };
/// assert_eq!(policy.max_attempts, 3);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct RetryPolicy {
    /// Total number of attempts, including the first one. Must be at least 1.
    pub max_attempts: usize,
    /// Delay after the first failed attempt.
    pub initial_delay: Duration,
    /// Upper bound for the delay between attempts.
    pub max_delay: Duration,
    /// Backoff growth factor, e.g. `2.0` for exponential backoff.
    pub multiplier: f64,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 5,
            initial_delay: Duration::from_secs(2),
            max_delay: Duration::from_secs(30),
            multiplier: 2.0,
        }
    }
}

impl RetryPolicy {
    /// The delay to wait after a failed attempt `attempt` (1-based).
    fn delay(&self, attempt: usize) -> Duration {
        let factor = self.multiplier.powi(attempt.saturating_sub(1) as i32);
        let delay = self.initial_delay.mul_f64(factor);
        delay.min(self.max_delay)
    }
}

/// Consolidation level for the document header.
///
/// Header consolidation asks GROBID to complete the extracted metadata with
/// an external lookup (CrossRef or biblio-glutton). The default, as on the
/// GROBID server, is [`HeaderConsolidation::Metadata`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum HeaderConsolidation {
    /// No consolidation (`0`): all metadata comes from the source PDF.
    None,
    /// Consolidate and inject all extra metadata (`1`, server default).
    #[default]
    Metadata,
    /// Consolidate and inject the DOI only (`2`).
    Doi,
    /// Consolidate using only the extracted DOI, if any (`3`).
    DoiOnly,
}

impl HeaderConsolidation {
    fn as_param(self) -> &'static str {
        match self {
            HeaderConsolidation::None => "0",
            HeaderConsolidation::Metadata => "1",
            HeaderConsolidation::Doi => "2",
            HeaderConsolidation::DoiOnly => "3",
        }
    }
}

/// Consolidation level for citations/references.
///
/// Consolidation is GROBID's first tier of reference processing; with the
/// `openalex` feature, the `openalex` module adds an optional second tier
/// that fills remaining gaps from OpenAlex.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum CitationConsolidation {
    /// No consolidation (`0`, server default).
    #[default]
    None,
    /// Consolidate and inject all extra metadata (`1`).
    Metadata,
    /// Consolidate and inject the DOI only (`2`).
    Doi,
}

impl CitationConsolidation {
    fn as_param(self) -> &'static str {
        match self {
            CitationConsolidation::None => "0",
            CitationConsolidation::Metadata => "1",
            CitationConsolidation::Doi => "2",
        }
    }
}

/// TEI structures for which PDF coordinates can be requested.
///
/// See <https://grobid.readthedocs.io/en/latest/Coordinates-in-PDF/> for the
/// coordinate system and the `@coords` notation.
///
/// ```
/// use grobid::{CoordinateElement, ProcessOptions};
///
/// let options = ProcessOptions {
///     tei_coordinates: vec![CoordinateElement::Figure, CoordinateElement::Ref],
///     ..ProcessOptions::default()
/// };
/// assert_eq!(options.tei_coordinates.len(), 2);
///
/// // The set requested by the Go GROBID client by default.
/// assert_eq!(CoordinateElement::COMMON.len(), 5);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum CoordinateElement {
    /// Reference markers (`ref`).
    Ref,
    /// Bibliographical references (`biblStruct`).
    BiblStruct,
    /// Author names (`persName`).
    PersName,
    /// Figures and tables (`figure`).
    Figure,
    /// Formulas (`formula`).
    Formula,
    /// Section titles (`head`).
    Head,
    /// Sentences (`s`), requires `segment_sentences`.
    Sentence,
    /// Paragraphs (`p`).
    Paragraph,
    /// Footnotes (`note`).
    Note,
    /// Titles (`title`).
    Title,
    /// Affiliations (`affiliation`).
    Affiliation,
}

impl CoordinateElement {
    /// The commonly used set of coordinate elements, as requested by the
    /// Go GROBID client by default.
    pub const COMMON: &'static [CoordinateElement] = &[
        CoordinateElement::Ref,
        CoordinateElement::Figure,
        CoordinateElement::PersName,
        CoordinateElement::Formula,
        CoordinateElement::BiblStruct,
    ];

    fn as_param(self) -> &'static str {
        match self {
            CoordinateElement::Ref => "ref",
            CoordinateElement::BiblStruct => "biblStruct",
            CoordinateElement::PersName => "persName",
            CoordinateElement::Figure => "figure",
            CoordinateElement::Formula => "formula",
            CoordinateElement::Head => "head",
            CoordinateElement::Sentence => "s",
            CoordinateElement::Paragraph => "p",
            CoordinateElement::Note => "note",
            CoordinateElement::Title => "title",
            CoordinateElement::Affiliation => "affiliation",
        }
    }
}

/// Options for a GROBID processing request.
///
/// Defaults follow the GROBID server defaults and the official Python
/// client: header consolidation enabled, citation consolidation and all
/// other extras disabled.
///
/// ```
/// use grobid::{CitationConsolidation, CoordinateElement, ProcessOptions};
///
/// let options = ProcessOptions {
///     generate_ids: true,
///     consolidate_citations: CitationConsolidation::Metadata,
///     include_raw_citations: true,
///     tei_coordinates: CoordinateElement::COMMON.to_vec(),
///     segment_sentences: true,
///     ..ProcessOptions::default()
/// };
/// assert!(options.generate_ids);
/// assert_eq!(options.tei_coordinates.len(), 5);
/// ```
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ProcessOptions {
    /// Generate unique identifiers for each text component
    /// (`generateIDs=1`).
    pub generate_ids: bool,
    /// Header consolidation level.
    pub consolidate_header: HeaderConsolidation,
    /// Citation consolidation level.
    pub consolidate_citations: CitationConsolidation,
    /// Include the raw reference strings in the result
    /// (`includeRawCitations=1`).
    pub include_raw_citations: bool,
    /// Include the raw affiliation strings in the result
    /// (`includeRawAffiliations=1`).
    pub include_raw_affiliations: bool,
    /// Include the raw copyrights/license strings in the result
    /// (`includeRawCopyrights=1`).
    pub include_raw_copyrights: bool,
    /// TEI structures for which PDF coordinates are added
    /// (`teiCoordinates`, repeated).
    pub tei_coordinates: Vec<CoordinateElement>,
    /// Further segment paragraphs into sentences (`segmentSentences=1`).
    pub segment_sentences: bool,
    /// Structuring flavor to apply, see the GROBID documentation.
    pub flavor: Option<String>,
    /// First PDF page to consider (1-based); `None` starts at the first
    /// page.
    pub start_page: Option<u32>,
    /// Last PDF page to consider (1-based); `None` ends at the last page.
    pub end_page: Option<u32>,
    /// Replace the structured response with a debug dump of the raw CRF
    /// labelling (`debugMode=1`). Note that the response is then *not*
    /// valid TEI and cannot be parsed by the typed methods.
    pub debug_mode: bool,
    /// Restrict the debug dump to the given model names (comma-separated
    /// in the request).
    pub models: Vec<String>,
}

impl ProcessOptions {
    /// Append all option fields to a multipart form.
    fn apply_to(&self, mut form: Form) -> Form {
        form = form.text("consolidateHeader", self.consolidate_header.as_param());
        form = form.text(
            "consolidateCitations",
            self.consolidate_citations.as_param(),
        );
        if self.generate_ids {
            form = form.text("generateIDs", "1");
        }
        if self.include_raw_citations {
            form = form.text("includeRawCitations", "1");
        }
        if self.include_raw_affiliations {
            form = form.text("includeRawAffiliations", "1");
        }
        if self.include_raw_copyrights {
            form = form.text("includeRawCopyrights", "1");
        }
        for element in &self.tei_coordinates {
            form = form.text("teiCoordinates", element.as_param());
        }
        if self.segment_sentences {
            form = form.text("segmentSentences", "1");
        }
        if let Some(flavor) = &self.flavor {
            form = form.text("flavor", flavor.clone());
        }
        if let Some(start) = self.start_page {
            form = form.text("start", start.to_string());
        }
        if let Some(end) = self.end_page {
            form = form.text("end", end.to_string());
        }
        if self.debug_mode {
            form = form.text("debugMode", "1");
        }
        if !self.models.is_empty() {
            form = form.text("models", self.models.join(","));
        }
        form
    }

    /// The citation-related fields for form-urlencoded services.
    fn apply_to_urlencoded(&self, fields: &mut Vec<(String, String)>) {
        if self.consolidate_citations != CitationConsolidation::None {
            fields.push((
                "consolidateCitations".to_string(),
                self.consolidate_citations.as_param().to_string(),
            ));
        }
        if self.include_raw_citations {
            fields.push(("includeRawCitations".to_string(), "1".to_string()));
        }
    }
}

/// A PDF to be processed by GROBID: either a path on disk, or the document
/// bytes with a file name. In-memory inputs avoid a round-trip through the
/// filesystem, e.g. when the PDF was downloaded or comes from an object
/// store.
///
/// ```
/// use std::path::PathBuf;
///
/// use grobid::PdfInput;
///
/// // From a path on disk ...
/// let from_path = PdfInput::from("paper.pdf");
/// assert!(matches!(from_path, PdfInput::Path(_)));
///
/// // ... or from bytes already in memory, with an explicit upload name.
/// let from_bytes = PdfInput::from(("paper.pdf", vec![0x25, 0x50, 0x44, 0x46]));
/// assert!(matches!(from_bytes, PdfInput::Data { .. }));
/// ```
#[derive(Debug, Clone)]
pub enum PdfInput {
    /// Read the PDF from the given path. The file name of the path is used
    /// as the upload name.
    Path(PathBuf),
    /// Use the given bytes, uploaded under the given file name.
    Data {
        /// The name the PDF is uploaded as, e.g. `paper.pdf`.
        filename: String,
        /// The PDF content.
        data: Vec<u8>,
    },
}

impl From<&str> for PdfInput {
    fn from(path: &str) -> Self {
        PdfInput::Path(PathBuf::from(path))
    }
}

impl From<String> for PdfInput {
    fn from(path: String) -> Self {
        PdfInput::Path(PathBuf::from(path))
    }
}

impl From<&std::path::Path> for PdfInput {
    fn from(path: &std::path::Path) -> Self {
        PdfInput::Path(path.to_path_buf())
    }
}

impl From<PathBuf> for PdfInput {
    fn from(path: PathBuf) -> Self {
        PdfInput::Path(path)
    }
}

impl From<(&str, Vec<u8>)> for PdfInput {
    fn from((filename, data): (&str, Vec<u8>)) -> Self {
        PdfInput::Data {
            filename: filename.to_string(),
            data,
        }
    }
}

impl From<(String, Vec<u8>)> for PdfInput {
    fn from((filename, data): (String, Vec<u8>)) -> Self {
        PdfInput::Data { filename, data }
    }
}

impl PdfInput {
    /// Resolve the input to an upload name and content bytes.
    async fn into_parts(self) -> Result<(String, Vec<u8>), Error> {
        match self {
            PdfInput::Path(path) => {
                let filename = path
                    .file_name()
                    .map(|name| name.to_string_lossy().into_owned())
                    .unwrap_or_else(|| "document.pdf".to_string());
                let data = tokio::fs::read(&path).await?;
                Ok((filename, data))
            }
            PdfInput::Data { filename, data } => Ok((filename, data)),
        }
    }
}

/// Builder for [`GrobidClient`].
#[derive(Debug, Clone)]
pub struct GrobidClientBuilder {
    base_url: Url,
    http: Option<Client>,
    retry: RetryPolicy,
}

impl GrobidClientBuilder {
    /// Use a custom HTTP client, e.g. with specific timeouts, proxies or
    /// TLS settings.
    pub fn http_client(mut self, client: Client) -> Self {
        self.http = Some(client);
        self
    }

    /// Use a custom retry policy for busy-server (503/429) responses.
    pub fn retry(mut self, policy: RetryPolicy) -> Self {
        self.retry = policy;
        self
    }

    /// Build the client.
    pub fn build(self) -> GrobidClient {
        GrobidClient {
            base_url: self.base_url,
            http: self.http.unwrap_or_default(),
            retry: self.retry,
        }
    }
}

/// A client for the GROBID REST API.
///
/// ```no_run
/// # async fn example() -> Result<(), grobid::Error> {
/// let client = grobid::GrobidClient::new("http://localhost:8070")?;
/// assert!(client.ping().await?);
///
/// let document = client
///     .process_fulltext_document("paper.pdf", &Default::default())
///     .await?;
/// println!("{}", document.header.title.as_deref().unwrap_or("untitled"));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct GrobidClient {
    base_url: Url,
    http: Client,
    retry: RetryPolicy,
}

impl GrobidClient {
    /// Create a client for a GROBID server with default settings.
    ///
    /// `base_url` may be given with or without a scheme and trailing slash,
    /// e.g. `http://localhost:8070`, `localhost:8070` or
    /// `https://grobid.example.org/`. An optional context path is
    /// preserved.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), grobid::Error> {
    /// use grobid::GrobidClient;
    ///
    /// let client = GrobidClient::new("localhost:8070")?;
    /// assert_eq!(client.base_url().as_str(), "http://localhost:8070/");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::InvalidBaseUrl`] if the string is not a valid URL,
    /// * [`Error::UnsupportedScheme`] if it uses a scheme other than `http`
    ///   or `https`.
    pub fn new(base_url: impl AsRef<str>) -> Result<Self, Error> {
        Ok(Self::builder(base_url)?.build())
    }

    /// Create a client builder for customizing the HTTP client and retry
    /// behaviour.
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> Result<(), grobid::Error> {
    /// use std::time::Duration;
    ///
    /// use grobid::{GrobidClient, RetryPolicy};
    ///
    /// let client = GrobidClient::builder("http://localhost:8070")?
    ///     .retry(RetryPolicy {
    ///         max_attempts: 3,
    ///         initial_delay: Duration::from_secs(1),
    ///         ..RetryPolicy::default()
    ///     })
    ///     .build();
    /// assert_eq!(client.retry_policy().max_attempts, 3);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::InvalidBaseUrl`] if the string is not a valid URL,
    /// * [`Error::UnsupportedScheme`] if it uses a scheme other than `http`
    ///   or `https`.
    pub fn builder(base_url: impl AsRef<str>) -> Result<GrobidClientBuilder, Error> {
        let base_url = normalize_base_url(base_url.as_ref())?;
        Ok(GrobidClientBuilder {
            base_url,
            http: None,
            retry: RetryPolicy::default(),
        })
    }

    /// The normalized base URL of the GROBID server.
    pub fn base_url(&self) -> &Url {
        &self.base_url
    }

    /// The underlying HTTP client.
    pub fn http_client(&self) -> &Client {
        &self.http
    }

    /// The retry policy used for busy-server responses.
    pub fn retry_policy(&self) -> &RetryPolicy {
        &self.retry
    }

    /// Check that the server is alive (`GET /api/isalive`). Returns `true`
    /// when the server responds successfully.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// let client = grobid::GrobidClient::new("http://localhost:8070")?;
    /// if client.ping().await? {
    ///     println!("server is ready");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::Http`] if the server cannot be reached,
    /// * [`Error::HttpStatus`] if it answers with an unexpected status
    ///   code,
    /// * [`Error::ServerBusy`] if it stays busy (HTTP 503/429) for all
    ///   attempts of the [`RetryPolicy`].
    pub async fn ping(&self) -> Result<bool, Error> {
        let url = self.api_url("isalive");
        let http = self.http.clone();
        let request_url = url.clone();
        let response = self.request(move || http.get(url.clone())).await?;
        let status = response.status();
        let body = response.text().await?;
        match status {
            StatusCode::OK => Ok(body.trim() == "true"),
            status => Err(Error::http_status(
                status.as_u16(),
                request_url.to_string(),
                body,
            )),
        }
    }

    /// Wait until the server reports itself ready (`GET /api/isalive`
    /// returns `true`), probing up to `attempts` times with `delay` between
    /// probes.  The number of attempts is clamped to at least one.
    ///
    /// GROBID can take a while to become ready (e.g. while preloading its
    /// models), so a batch job should wait here before its first request.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// use std::time::Duration;
    ///
    /// let client = grobid::GrobidClient::new("http://localhost:8070")?;
    /// client
    ///     .wait_until_ready(10, Duration::from_secs(3))
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::ServerNotReady`] if the server responds but reports that
    ///   it is not alive,
    /// * [`Error::HttpStatus`] if `/api/isalive` answers with an unexpected
    ///   status code (e.g. because the base URL is wrong),
    /// * [`Error::ServerUnreachable`] if no probe got a response.
    pub async fn wait_until_ready(&self, attempts: usize, delay: Duration) -> Result<(), Error> {
        let attempts = attempts.max(1);
        // Probe all but the last attempt without reporting: transport errors
        // are expected while the server is still starting.
        for _ in 1..attempts {
            match self.ping().await {
                Ok(true) => return Ok(()),
                // A reachable server that denies being alive will not become
                // ready by probing again; neither will an unexpected status
                // code (e.g. because the base URL is wrong).
                Ok(false) => {
                    return Err(Error::ServerNotReady {
                        url: self.base_url.to_string(),
                    });
                }
                Err(err @ Error::HttpStatus { .. }) => return Err(err),
                Err(_) => {}
            }
            tokio::time::sleep(delay).await;
        }
        // The final probe reports the outcome with its typed error.
        match self.ping().await {
            Ok(true) => Ok(()),
            Ok(false) => Err(Error::ServerNotReady {
                url: self.base_url.to_string(),
            }),
            Err(err @ Error::HttpStatus { .. }) => Err(err),
            Err(Error::Http(source)) => Err(Error::ServerUnreachable {
                url: self.base_url.to_string(),
                attempts,
                source,
            }),
            Err(err) => Err(err),
        }
    }

    /// The version of the running GROBID service (`GET /api/version`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// let client = grobid::GrobidClient::new("http://localhost:8070")?;
    /// println!("GROBID {}", client.version().await?);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::Http`] if the server cannot be reached,
    /// * [`Error::HttpStatus`] if it answers with an unexpected status
    ///   code,
    /// * [`Error::ServerBusy`] if it stays busy (HTTP 503/429) for all
    ///   attempts of the [`RetryPolicy`].
    pub async fn version(&self) -> Result<String, Error> {
        let url = self.api_url("version");
        let http = self.http.clone();
        let request_url = url.clone();
        let response = self.request(move || http.get(url.clone())).await?;
        let status = response.status();
        let body = response.text().await?;
        match status {
            StatusCode::OK => Ok(body.trim().to_string()),
            status => Err(Error::http_status(
                status.as_u16(),
                request_url.to_string(),
                body,
            )),
        }
    }

    /// Process a full document (header, body and references) and return the
    /// parsed TEI (`/api/processFulltextDocument`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// use grobid::{GrobidClient, ProcessOptions};
    ///
    /// let client = GrobidClient::new("http://localhost:8070")?;
    /// let document = client
    ///     .process_fulltext_document("paper.pdf", &ProcessOptions::default())
    ///     .await?;
    /// println!("{:?}", document.header.title);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::Io`] if a PDF path cannot be read,
    /// * [`Error::Http`] if the request fails at the transport level,
    /// * [`Error::HttpStatus`] if the server answers with an error status,
    /// * [`Error::ServerBusy`] if the server stays busy (HTTP 503/429) for
    ///   all attempts of the [`RetryPolicy`],
    /// * [`Error::NoContent`] if nothing could be extracted (HTTP 204),
    /// * [`Error::Xml`] / [`Error::InvalidDocument`] if the response cannot
    ///   be parsed as GROBID TEI.
    pub async fn process_fulltext_document(
        &self,
        pdf: impl Into<PdfInput>,
        options: &ProcessOptions,
    ) -> Result<Document, Error> {
        let xml = self
            .process_pdf(SERVICE_FULLTEXT, pdf.into(), options)
            .await?
            .ok_or(Error::NoContent)?;
        parse_document(&xml)
    }

    /// Process the header of a document and return the parsed TEI
    /// (`/api/processHeaderDocument`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// use grobid::{GrobidClient, ProcessOptions};
    ///
    /// let client = GrobidClient::new("http://localhost:8070")?;
    /// let document = client
    ///     .process_header_document("paper.pdf", &ProcessOptions::default())
    ///     .await?;
    /// for author in &document.header.authors {
    ///     println!("{:?}", author.full_name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// See [`GrobidClient::process_fulltext_document`]; the header service
    /// reports the same failures.
    pub async fn process_header_document(
        &self,
        pdf: impl Into<PdfInput>,
        options: &ProcessOptions,
    ) -> Result<Document, Error> {
        let xml = self
            .process_pdf(SERVICE_HEADER, pdf.into(), options)
            .await?
            .ok_or(Error::NoContent)?;
        parse_document(&xml)
    }

    /// Extract and parse all bibliographic references of a document
    /// (`/api/processReferences`). An HTTP 204 response (nothing extracted)
    /// yields an empty list.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// use grobid::{GrobidClient, ProcessOptions};
    ///
    /// let client = GrobidClient::new("http://localhost:8070")?;
    /// let references = client
    ///     .process_references("paper.pdf", &ProcessOptions::default())
    ///     .await?;
    /// for reference in &references {
    ///     println!("{:?}", reference.title);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// See [`GrobidClient::process_fulltext_document`], except that an
    /// empty result is not an error: it yields an empty vector.
    pub async fn process_references(
        &self,
        pdf: impl Into<PdfInput>,
        options: &ProcessOptions,
    ) -> Result<Vec<Citation>, Error> {
        match self
            .process_pdf(SERVICE_REFERENCES, pdf.into(), options)
            .await?
        {
            Some(xml) => parse_citation_list(&xml),
            None => Ok(Vec::new()),
        }
    }

    /// Parse a single raw bibliographic reference string
    /// (`/api/processCitation`). Returns `None` when GROBID could not
    /// extract any usable citation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// use grobid::{GrobidClient, ProcessOptions};
    ///
    /// let client = GrobidClient::new("http://localhost:8070")?;
    /// let citation = client
    ///     .process_citation(
    ///         "Graff, Expert. Opin. Ther. Targets (2002) 6(1): 103-113",
    ///         &ProcessOptions::default(),
    ///     )
    ///     .await?;
    /// if let Some(citation) = citation {
    ///     println!("{:?}", citation.journal);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::Http`] / [`Error::HttpStatus`] / [`Error::ServerBusy`]
    ///   for transport, status and capacity failures,
    /// * [`Error::Xml`] / [`Error::InvalidCoords`] if the response cannot be
    ///   parsed.
    pub async fn process_citation(
        &self,
        citation: &str,
        options: &ProcessOptions,
    ) -> Result<Option<Citation>, Error> {
        let mut fields = vec![("citations".to_string(), citation.to_string())];
        options.apply_to_urlencoded(&mut fields);
        match self.post_urlencoded(SERVICE_CITATION, fields).await? {
            Some(xml) if !xml.trim().is_empty() => parse_citation(&xml),
            _ => Ok(None),
        }
    }

    /// Parse a list of raw bibliographic reference strings
    /// (`/api/processCitationList`).
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// use grobid::{GrobidClient, ProcessOptions};
    ///
    /// let client = GrobidClient::new("http://localhost:8070")?;
    /// let references = client
    ///     .process_citation_list(
    ///         ["Graff, Expert. Opin. Ther. Targets (2002) 6(1): 103-113"],
    ///         &ProcessOptions::default(),
    ///     )
    ///     .await?;
    /// assert_eq!(references.len(), 1);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// See [`GrobidClient::process_citation`].
    pub async fn process_citation_list(
        &self,
        citations: impl IntoIterator<Item = impl AsRef<str>>,
        options: &ProcessOptions,
    ) -> Result<Vec<Citation>, Error> {
        let mut fields = Vec::new();
        for citation in citations {
            fields.push(("citations".to_string(), citation.as_ref().to_string()));
        }
        options.apply_to_urlencoded(&mut fields);
        match self.post_urlencoded(SERVICE_CITATION_LIST, fields).await? {
            Some(xml) => parse_citation_list(&xml),
            None => Ok(Vec::new()),
        }
    }

    /// Send a PDF to an arbitrary GROBID service (multipart form) and
    /// return the raw response body. Use this for services without a typed
    /// wrapper, e.g. the patent processing services.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), grobid::Error> {
    /// use grobid::{GrobidClient, ProcessOptions};
    ///
    /// let client = GrobidClient::new("http://localhost:8070")?;
    /// let tei = client
    ///     .process_pdf_raw(
    ///         "processCitationPatentST36",
    ///         "patent.xml",
    ///         &ProcessOptions::default(),
    ///     )
    ///     .await?;
    /// println!("{tei}");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// * [`Error::Io`] if a PDF path cannot be read,
    /// * [`Error::Http`] / [`Error::HttpStatus`] / [`Error::ServerBusy`]
    ///   for transport, status and capacity failures,
    /// * [`Error::NoContent`] if the server reports an empty result
    ///   (HTTP 204).
    pub async fn process_pdf_raw(
        &self,
        service: &str,
        pdf: impl Into<PdfInput>,
        options: &ProcessOptions,
    ) -> Result<String, Error> {
        match self.process_pdf(service, pdf.into(), options).await? {
            Some(body) => Ok(body),
            None => Err(Error::NoContent),
        }
    }

    /// Send a PDF to a processing service. Returns the response body, or
    /// `None` for HTTP 204.
    async fn process_pdf(
        &self,
        service: &str,
        pdf: PdfInput,
        options: &ProcessOptions,
    ) -> Result<Option<String>, Error> {
        let (filename, data) = pdf.into_parts().await?;
        let url = self.api_url(service);
        let http = self.http.clone();
        let options = options.clone();
        let request_url = url.clone();
        self.send_for_text(request_url, move || {
            let part = Part::bytes(data.clone())
                .file_name(filename.clone())
                .mime_str("application/pdf")
                .expect("fixed MIME type is always valid");
            let form = options.apply_to(Form::new()).part("input", part);
            http.post(url.clone()).multipart(form)
        })
        .await
    }

    /// POST urlencoded fields to `/api/{service}` and return the response
    /// body, or `None` for HTTP 204.
    async fn post_urlencoded(
        &self,
        service: &str,
        fields: Vec<(String, String)>,
    ) -> Result<Option<String>, Error> {
        let url = self.api_url(service);
        let http = self.http.clone();
        let request_url = url.clone();
        self.send_for_text(request_url, move || http.post(url.clone()).form(&fields))
            .await
    }

    /// Send a freshly built request (with busy-server retries), read the
    /// body and translate the status code. The builder closure is invoked
    /// anew for every retry attempt, so request bodies are always
    /// re-encodable.
    async fn send_for_text<F>(&self, url: Url, build: F) -> Result<Option<String>, Error>
    where
        F: Fn() -> RequestBuilder,
    {
        let response = self.request(build).await?;
        let status = response.status();
        let body = response.text().await?;
        match status {
            StatusCode::OK => Ok(Some(body)),
            StatusCode::NO_CONTENT => Ok(None),
            StatusCode::SERVICE_UNAVAILABLE | StatusCode::TOO_MANY_REQUESTS => {
                Err(Error::ServerBusy {
                    attempts: self.retry.max_attempts,
                })
            }
            status => Err(Error::http_status(status.as_u16(), url.to_string(), body)),
        }
    }

    /// Send a request, retrying busy-server responses (503/429) with
    /// exponential backoff until the retry budget is exhausted. The builder
    /// is invoked for every attempt.
    async fn request<F>(&self, build: F) -> Result<Response, Error>
    where
        F: Fn() -> RequestBuilder,
    {
        let mut attempt = 0usize;
        loop {
            attempt += 1;
            let response = build().send().await?;
            let busy = matches!(
                response.status(),
                StatusCode::SERVICE_UNAVAILABLE | StatusCode::TOO_MANY_REQUESTS
            );
            if !busy || attempt >= self.retry.max_attempts {
                return Ok(response);
            }
            tokio::time::sleep(self.retry.delay(attempt)).await;
        }
    }

    /// Build the URL of a service under the `/api/` path.
    fn api_url(&self, service: &str) -> Url {
        // Cannot fail: the constructor only accepts hierarchical http(s)
        // URLs as the base, which always support relative paths.
        self.base_url
            .join(&format!("api/{service}"))
            .expect("base URL always supports relative paths")
    }
}

/// Normalize a user-supplied base URL: add a scheme when missing, require
/// `http`/`https`, and ensure the path ends with a slash so that relative
/// paths can be joined.
fn normalize_base_url(base_url: &str) -> Result<Url, Error> {
    let trimmed = base_url.trim().trim_end_matches('/');
    let with_scheme = if trimmed.contains("://") {
        trimmed.to_string()
    } else {
        format!("http://{trimmed}")
    };
    let mut url = Url::parse(&with_scheme).map_err(|source| Error::InvalidBaseUrl {
        base_url: base_url.to_string(),
        source,
    })?;
    if !matches!(url.scheme(), "http" | "https") {
        return Err(Error::UnsupportedScheme {
            base_url: base_url.to_string(),
            scheme: url.scheme().to_string(),
        });
    }
    if !url.path().ends_with('/') {
        let path = format!("{}/", url.path());
        url.set_path(&path);
    }
    Ok(url)
}