Skip to main content

cloudiful_docling_convert/
facade.rs

1use bytes::Bytes;
2
3use crate::api::DoclingConfig;
4use crate::conversion::{
5    ConversionBehavior, DoclingRuntimeConfig, build_convert_options, build_docling_client,
6};
7use crate::document::{ConvertRequest, ConvertedDocument, InputDocument, InputKind, OutputFormat};
8use crate::error::{PdfConvertError, Result};
9use crate::processor::DocumentConverter;
10
11pub struct ConverterBuilder {
12    config: DoclingRuntimeConfig,
13    behavior: ConversionBehavior,
14    output_formats: Vec<OutputFormat>,
15}
16
17impl ConverterBuilder {
18    pub fn new(config: DoclingRuntimeConfig) -> Self {
19        Self {
20            config,
21            behavior: ConversionBehavior::default(),
22            output_formats: vec![OutputFormat::Md],
23        }
24    }
25
26    pub fn behavior(mut self, behavior: ConversionBehavior) -> Self {
27        self.behavior = behavior;
28        self
29    }
30
31    pub fn output_formats(mut self, output_formats: Vec<OutputFormat>) -> Self {
32        self.output_formats = output_formats;
33        self
34    }
35
36    pub fn build(self) -> Result<PdfConvert> {
37        let output_formats = if self.output_formats.is_empty() {
38            vec![OutputFormat::Md]
39        } else {
40            self.output_formats
41        };
42
43        Ok(PdfConvert {
44            converter: DocumentConverter::new(build_docling_client(self.config)?),
45            behavior: self.behavior,
46            output_formats,
47        })
48    }
49}
50
51pub struct PdfConvert {
52    converter: DocumentConverter,
53    behavior: ConversionBehavior,
54    output_formats: Vec<OutputFormat>,
55}
56
57impl PdfConvert {
58    pub fn builder(config: DoclingRuntimeConfig) -> ConverterBuilder {
59        ConverterBuilder::new(config)
60    }
61
62    pub fn from_runtime_config(config: DoclingRuntimeConfig) -> Result<Self> {
63        Self::builder(config).build()
64    }
65
66    pub fn from_docling_config(config: DoclingConfig) -> Result<Self> {
67        Ok(Self {
68            converter: DocumentConverter::new(crate::DoclingClient::new(config)?),
69            behavior: ConversionBehavior::default(),
70            output_formats: vec![OutputFormat::Md],
71        })
72    }
73
74    pub fn request_for_input(&self, input: InputDocument) -> Result<ConvertRequest> {
75        let input_kind = input.kind()?;
76
77        Ok(ConvertRequest {
78            input,
79            output_formats: self.output_formats.clone(),
80            options: build_convert_options(input_kind, &self.behavior)?,
81        })
82    }
83
84    pub async fn convert_input(&self, input: InputDocument) -> Result<ConvertedDocument> {
85        self.converter.convert(self.request_for_input(input)?).await
86    }
87
88    pub async fn convert_bytes(
89        &self,
90        filename: impl Into<String>,
91        bytes: impl Into<Bytes>,
92    ) -> Result<ConvertedDocument> {
93        let filename = filename.into();
94        let input_kind =
95            InputKind::from_filename_and_media_type(&filename, None).ok_or_else(|| {
96                PdfConvertError::validation_error(
97                    "filename",
98                    format!("unsupported input type for '{}'", filename),
99                )
100            })?;
101
102        self.convert_input(InputDocument::new(filename, input_kind.media_type(), bytes))
103            .await
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110
111    #[test]
112    fn builder_defaults_to_markdown_output() {
113        let converter = ConverterBuilder::new(DoclingRuntimeConfig {
114            docling_base_url: "http://127.0.0.1:5001/v1".into(),
115            openai_base_url: "https://example.com/v1".into(),
116            vlm_pipeline_model: "test-model".into(),
117            picture_description_model: "test-model".into(),
118            code_formula_model: "test-model".into(),
119            api_key: Some("key".into()),
120        })
121        .build()
122        .unwrap();
123
124        let request = converter
125            .request_for_input(InputDocument::new(
126                "notes.md",
127                "text/markdown",
128                Bytes::from("# hi"),
129            ))
130            .unwrap();
131
132        assert_eq!(request.output_formats, vec![OutputFormat::Md]);
133    }
134
135    #[test]
136    fn convert_bytes_rejects_unknown_extensions() {
137        let converter = ConverterBuilder::new(DoclingRuntimeConfig {
138            docling_base_url: "http://127.0.0.1:5001/v1".into(),
139            openai_base_url: "https://example.com/v1".into(),
140            vlm_pipeline_model: "test-model".into(),
141            picture_description_model: "test-model".into(),
142            code_formula_model: "test-model".into(),
143            api_key: Some("key".into()),
144        })
145        .build()
146        .unwrap();
147
148        let error = tokio::runtime::Runtime::new()
149            .unwrap()
150            .block_on(converter.convert_bytes("notes.csv", Bytes::from_static(b"test")))
151            .unwrap_err();
152
153        assert!(error.to_string().contains("unsupported input type"));
154    }
155}