mineru 0.5.0

Rust client, CLI, and API server for OpenAI-compatible MinerU document parsing
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
use reqwest::{Method, StatusCode, redirect::Policy};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{collections::BTreeMap, fmt, time::Duration};
use url::Url;

#[path = "client/support.rs"]
mod support;
use support::{
    http_error, read_limited, remaining_budget, remote_file_error, result_metadata, segment,
    transport, validate_page_range, validate_zip,
};

const INPUT_MAX: usize = 16 * 1024 * 1024;
const JOB_INPUT_MAX: usize = 64 * 1024 * 1024;
const OUTPUT_MAX: usize = 64 * 1024 * 1024;
const JSON_MAX: usize = 2 * 1024 * 1024;
const MAX_FILES: usize = 100;

#[derive(Clone, Debug, thiserror::Error)]
pub enum OfficialApiError {
    #[error("invalid client configuration: {0}")]
    Invalid(String),
    #[error("official API request failed: {0}")]
    Transport(String),
    #[error("official API returned HTTP {status}: {message}")]
    Http { status: StatusCode, message: String },
    #[error("official API response exceeded the configured safety limit")]
    TooLarge,
    #[error("official API protocol error: {0}")]
    Protocol(String),
    #[error("remote file error {error_type}/{code}: {message}")]
    File {
        error_type: String,
        code: String,
        message: String,
    },
}

pub type OfficialApiResult<T> = Result<T, OfficialApiError>;

/// `TASK_OUTPUT_FORMATS`: the formats the 4.2.3 task API composes.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OfficialOutputFormat {
    Default,
    Docx,
    Html,
    Latex,
}

impl OfficialOutputFormat {
    fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Docx => "docx",
            Self::Html => "html",
            Self::Latex => "latex",
        }
    }
}

#[derive(Clone, Debug, Default)]
pub struct OfficialRemoteParseOptions {
    pub tier: Option<crate::official::OfficialTier>,
    pub ocr_mode: Option<crate::official::OfficialOcrMode>,
    pub output_formats: Vec<OfficialOutputFormat>,
}

#[derive(Clone)]
pub struct OfficialApiClient {
    base: Url,
    token: Option<String>,
    timeout: Duration,
    http: reqwest::Client,
}

impl fmt::Debug for OfficialApiClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OfficialApiClient")
            .field("base", &self.base)
            .field("token", &self.token.as_ref().map(|_| "[redacted]"))
            .field("timeout", &self.timeout)
            .finish()
    }
}

/// `TaskUploadLink` from the create response.
#[derive(Clone, Debug, Deserialize)]
struct UploadLink {
    url: String,
    #[serde(default)]
    headers: BTreeMap<String, String>,
}

#[derive(Clone, Debug, Deserialize)]
struct CreatedFile {
    file_id: String,
    #[serde(default)]
    upload: Option<UploadLink>,
}

#[derive(Clone, Debug, Deserialize)]
pub(crate) struct CreatedTask {
    pub(crate) task_id: String,
    files: Vec<CreatedFile>,
}

impl OfficialApiClient {
    pub fn new(base_url: &str) -> OfficialApiResult<Self> {
        let base = Url::parse(base_url)
            .map_err(|_| OfficialApiError::Invalid("base URL must be absolute HTTP(S)".into()))?;
        if !matches!(base.scheme(), "http" | "https")
            || base.host_str().is_none()
            || !base.username().is_empty()
            || base.password().is_some()
            || base.query().is_some()
            || base.fragment().is_some()
        {
            return Err(OfficialApiError::Invalid(
                "base URL must be HTTP(S), without userinfo, query, or fragment".into(),
            ));
        }
        let http = reqwest::Client::builder()
            .no_proxy()
            .redirect(Policy::none())
            .timeout(Duration::from_secs(600))
            .build()
            .map_err(transport)?;
        Ok(Self {
            base,
            token: None,
            timeout: Duration::from_secs(600),
            http,
        })
    }

    pub fn with_token(mut self, token: impl Into<String>) -> OfficialApiResult<Self> {
        let token = token.into();
        if token.trim().is_empty() || token.contains(['\r', '\n']) {
            return Err(OfficialApiError::Invalid(
                "token must be nonempty and contain no line breaks".into(),
            ));
        }
        self.token = Some(token);
        Ok(self)
    }

    pub fn with_timeout(mut self, timeout: Duration) -> OfficialApiResult<Self> {
        if timeout.is_zero() {
            return Err(OfficialApiError::Invalid("timeout must be positive".into()));
        }
        self.timeout = timeout;
        self.http = reqwest::Client::builder()
            .no_proxy()
            .redirect(Policy::none())
            .timeout(timeout)
            .build()
            .map_err(transport)?;
        Ok(self)
    }

    fn url(&self, path: &str) -> OfficialApiResult<Url> {
        let url = self
            .base
            .join(path)
            .map_err(|_| OfficialApiError::Invalid("invalid endpoint URL".into()))?;
        self.check_origin(&url)?;
        Ok(url)
    }
    fn check_origin(&self, url: &Url) -> OfficialApiResult<()> {
        if url.scheme() != self.base.scheme()
            || url.host_str() != self.base.host_str()
            || url.port_or_known_default() != self.base.port_or_known_default()
            || !url.username().is_empty()
            || url.password().is_some()
            || url.fragment().is_some()
        {
            return Err(OfficialApiError::Protocol(
                "follow-up URL is not same-origin".into(),
            ));
        }
        Ok(())
    }
    fn request(&self, method: Method, url: Url) -> reqwest::RequestBuilder {
        let mut req = self.http.request(method, url).timeout(self.timeout);
        if let Some(token) = &self.token {
            req = req.bearer_auth(token);
        }
        req
    }

    async fn send_json(
        &self,
        method: Method,
        url: Url,
        body: Option<Value>,
    ) -> OfficialApiResult<Value> {
        let mut request = self.request(method, url);
        if let Some(body) = body {
            request = request.json(&body);
        }
        let response = request.send().await.map_err(transport)?;
        let status = response.status();
        let bytes = read_limited(response, JSON_MAX).await?;
        if !status.is_success() {
            return Err(http_error(status, &bytes));
        }
        serde_json::from_slice(&bytes)
            .map_err(|_| OfficialApiError::Protocol("invalid JSON response".into()))
    }

    /// `POST /v1/tasks` with the JSON manifest; returns the 202 receipt.
    pub(crate) async fn create_task(
        &self,
        files: &[OfficialInput],
        options: &OfficialRemoteParseOptions,
    ) -> OfficialApiResult<CreatedTask> {
        if files.is_empty() || files.len() > MAX_FILES {
            return Err(OfficialApiError::Invalid(
                "task must contain 1..100 files".into(),
            ));
        }
        let mut total = 0usize;
        let mut manifest = Vec::with_capacity(files.len());
        for file in files {
            total = total
                .checked_add(file.bytes.len())
                .ok_or(OfficialApiError::TooLarge)?;
            if file.bytes.is_empty() || file.bytes.len() > INPUT_MAX || total > JOB_INPUT_MAX {
                return Err(OfficialApiError::TooLarge);
            }
            if crate::official_api::wire::validate_file_name(&file.filename).is_err() {
                return Err(OfficialApiError::Invalid("invalid file_name".into()));
            }
            let mut item = json!({
                "file_name": file.filename,
                "bytes": file.bytes.len(),
                "sha256sum": sha256_hex(&file.bytes),
            });
            if let Some(range) = &file.page_range {
                validate_page_range(range)?;
                item["page_range"] = json!(range);
            }
            manifest.push(item);
        }
        let mut body = json!({"files": manifest});
        if !options.output_formats.is_empty() {
            body["output_formats"] = json!(
                options
                    .output_formats
                    .iter()
                    .map(|format| format.as_str())
                    .collect::<Vec<_>>()
            );
        }
        if let Some(tier) = options.tier {
            body["tier"] = json!(tier.as_str());
        }
        if let Some(ocr) = options.ocr_mode {
            body["ocr_mode"] = json!(ocr.as_str());
        }
        let value = self
            .send_json(Method::POST, self.url("/v1/tasks")?, Some(body))
            .await?;
        let created: CreatedTask = serde_json::from_value(value)
            .map_err(|_| OfficialApiError::Protocol("invalid create response".into()))?;
        if created.files.len() != files.len()
            || created.files.iter().any(|file| file.file_id.is_empty())
        {
            return Err(OfficialApiError::Protocol(
                "create response omitted task files".into(),
            ));
        }
        Ok(created)
    }

    /// `PUT` one file to the server-provided upload link.
    async fn upload_file(&self, link: &UploadLink, data: &[u8]) -> OfficialApiResult<()> {
        let target = self
            .base
            .join(&link.url)
            .map_err(|_| OfficialApiError::Protocol("invalid upload URL".into()))?;
        self.check_origin(&target)?;
        let mut put = self.request(Method::PUT, target).body(data.to_vec());
        for (name, value) in &link.headers {
            if !name.eq_ignore_ascii_case("content-type") {
                return Err(OfficialApiError::Protocol(
                    "unsafe upload response header".into(),
                ));
            }
            put = put.header("content-type", value);
        }
        let response = put.send().await.map_err(transport)?;
        if !response.status().is_success() {
            return Err(http_error(
                response.status(),
                &read_limited(response, JSON_MAX).await?,
            ));
        }
        Ok(())
    }

    pub async fn get_task(&self, id: &str) -> OfficialApiResult<Value> {
        self.send_json(
            Method::GET,
            self.url(&format!("/v1/tasks/{}", segment(id)))?,
            None,
        )
        .await
    }

    pub async fn cancel_task(&self, id: &str) -> OfficialApiResult<Value> {
        self.send_json(
            Method::POST,
            self.url(&format!("/v1/tasks/{}/cancel", segment(id)))?,
            None,
        )
        .await
    }

    pub async fn get_file(&self, id: &str) -> OfficialApiResult<Value> {
        self.send_json(
            Method::GET,
            self.url(&format!("/v1/files/{}", segment(id)))?,
            None,
        )
        .await
    }

    pub async fn download_file(&self, id: &str) -> OfficialApiResult<Vec<u8>> {
        self.download_file_limited(id, OUTPUT_MAX).await
    }

    async fn download_file_limited(&self, id: &str, limit: usize) -> OfficialApiResult<Vec<u8>> {
        let url = self.url(&format!("/v1/files/{}/content", segment(id)))?;
        self.download(url, limit).await
    }

    /// Follow a `result_url` from the task detail, keeping it same-origin.
    pub(crate) async fn download_url(&self, raw: &str, limit: usize) -> OfficialApiResult<Vec<u8>> {
        let url = self
            .base
            .join(raw)
            .map_err(|_| OfficialApiError::Protocol("invalid result URL".into()))?;
        self.check_origin(&url)?;
        self.download(url, limit).await
    }

    async fn download(&self, url: Url, limit: usize) -> OfficialApiResult<Vec<u8>> {
        let response = self
            .request(Method::GET, url)
            .send()
            .await
            .map_err(transport)?;
        let status = response.status();
        let data = read_limited(response, limit).await?;
        if !status.is_success() {
            return Err(http_error(status, &data));
        }
        Ok(data)
    }
}

fn sha256_hex(data: &[u8]) -> String {
    Sha256::digest(data)
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

#[derive(Clone, Debug)]
pub struct OfficialInput {
    pub filename: String,
    pub bytes: Vec<u8>,
    pub page_range: Option<String>,
}
impl OfficialInput {
    pub fn new(filename: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
        Self {
            filename: filename.into(),
            bytes: bytes.into(),
            page_range: None,
        }
    }
    pub fn with_page_range(mut self, range: impl Into<String>) -> Self {
        self.page_range = Some(range.into());
        self
    }
}

#[derive(Clone, Debug)]
pub struct OfficialArtifact {
    pub kind: String,
    pub file_id: String,
    pub bytes: Vec<u8>,
    pub metadata: Value,
}
#[derive(Clone, Debug)]
pub struct OfficialParseResult {
    pub metadata: Value,
    pub artifacts: Vec<OfficialArtifact>,
}
impl OfficialParseResult {
    /// `default` results arrive as a zip; read its markdown member.
    pub fn markdown(&self) -> Option<String> {
        for artifact in &self.artifacts {
            if artifact.kind == "markdown" {
                return std::str::from_utf8(&artifact.bytes).ok().map(str::to_owned);
            }
            if artifact.kind == "zip"
                && let Some(text) = zip_member(&artifact.bytes, "markdown.md")
                    .and_then(|b| String::from_utf8(b).ok())
            {
                return Some(text);
            }
        }
        None
    }
    pub fn json(&self, kind: &str) -> Option<OfficialApiResult<Value>> {
        for artifact in &self.artifacts {
            let bytes = if artifact.kind == kind {
                Some(artifact.bytes.clone())
            } else if artifact.kind == "zip" {
                zip_member(&artifact.bytes, &format!("{kind}.json"))
            } else {
                None
            };
            if let Some(bytes) = bytes {
                return Some(serde_json::from_slice(&bytes).map_err(|_| {
                    OfficialApiError::Protocol("artifact contains invalid JSON".into())
                }));
            }
        }
        None
    }
}

fn zip_member(bytes: &[u8], name: &str) -> Option<Vec<u8>> {
    use std::io::Read;
    let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).ok()?;
    let mut entry = archive.by_name(name).ok()?;
    let mut data = Vec::new();
    entry.read_to_end(&mut data).ok()?;
    Some(data)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    fn archive() -> Vec<u8> {
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        for (name, body) in [
            ("markdown.md", "# title"),
            ("middle_json.json", "{\"a\":1}"),
        ] {
            writer
                .start_file(name, zip::write::SimpleFileOptions::default())
                .unwrap();
            writer.write_all(body.as_bytes()).unwrap();
        }
        writer.finish().unwrap().into_inner()
    }

    #[test]
    fn reads_markdown_and_json_out_of_the_default_archive() {
        let result = OfficialParseResult {
            metadata: Value::Null,
            artifacts: vec![OfficialArtifact {
                kind: "zip".into(),
                file_id: "file_1".into(),
                bytes: archive(),
                metadata: Value::Null,
            }],
        };
        assert_eq!(result.markdown().as_deref(), Some("# title"));
        let json = result.json("middle_json").unwrap().unwrap();
        assert_eq!(json["a"], 1);
        assert!(result.json("absent").is_none());
    }
}

#[path = "client/parse.rs"]
mod parse;