use derive_builder::Builder;
use reqwest::{Method, multipart};
use serde::{Deserialize, Serialize};
use crate::{ApiErrorEnvelope, DeepSeekClient, api_request, check_response, error::DeepSeekError};
#[derive(Clone, PartialEq, Serialize, Builder)]
#[builder(
pattern = "owned",
setter(into, strip_option),
build_fn(validate = "Self::validate"),
name = "OCRRequestBuilder"
)]
pub struct OCRRequest {
#[serde(skip_serializing)]
pub client: DeepSeekClient,
pub file: Vec<u8>,
pub filename: String,
pub purpose: Purpose,
}
impl OCRRequestBuilder {
fn validate(&self) -> Result<(), String> {
if let Some(file) = self.file.as_ref()
&& file.is_empty()
{
return Err("file must not be empty".to_string());
}
if let Some(filename) = self.filename.as_ref()
&& filename.trim().is_empty()
{
return Err("filename must not be empty".to_string());
}
Ok(())
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Purpose {
TextRecognition,
RichLayoutRecognition,
}
impl Purpose {
pub fn text_recognition() -> Self {
Purpose::TextRecognition
}
pub fn rich_layout_recognition() -> Self {
Purpose::RichLayoutRecognition
}
pub fn as_str(&self) -> &'static str {
match self {
Purpose::TextRecognition => "text_recognition",
Purpose::RichLayoutRecognition => "rich_layout_recognition",
}
}
}
impl OCRRequest {
pub async fn send(self) -> Result<OCRResponse, DeepSeekError> {
let part = multipart::Part::bytes(self.file).file_name(self.filename);
let form = multipart::Form::new()
.text("purpose", self.purpose.as_str())
.part("file", part);
let response = api_request(
Method::POST,
"/v1/tools/ocr",
|request| request.multipart(form),
self.client.clone(),
)
.await?;
let response = check_response(response).await?;
let text = response.text().await?;
if let Ok(envelope) = serde_json::from_str::<ApiErrorEnvelope>(&text) {
return Err(DeepSeekError::api(envelope.error, Some(200), Some(text)));
}
serde_json::from_str::<OCRResponse>(&text)
.map_err(|err| DeepSeekError::decode(err.to_string(), text))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OCRResponse {
pub id: String,
pub object: String,
pub created: i64,
pub purpose: Purpose,
pub page_count: u32,
pub pages: Vec<OCRPage>,
pub usage: OCRUsage,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OCRPage {
pub index: u32,
pub text: String,
pub finish_reason: FinishReason,
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FinishReason {
Stop,
Length,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OCRUsage {
pub input_tokens: u64,
pub output_tokens: u64,
pub total_tokens: u64,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DEFAULT_BASE_URL;
use serde_json::json;
fn client() -> DeepSeekClient {
DeepSeekClient::new("sk-...", DEFAULT_BASE_URL.clone())
}
fn builder() -> OCRRequestBuilder {
OCRRequestBuilder::default()
.client(client())
.file(vec![0u8; 4])
.filename("document.pdf")
.purpose(Purpose::TextRecognition)
}
#[test]
fn purpose_serializes_api_values() {
assert_eq!(
serde_json::to_value(Purpose::TextRecognition).unwrap(),
json!("text_recognition")
);
assert_eq!(
serde_json::to_value(Purpose::RichLayoutRecognition).unwrap(),
json!("rich_layout_recognition")
);
assert_eq!(Purpose::text_recognition().as_str(), "text_recognition");
assert_eq!(
Purpose::rich_layout_recognition().as_str(),
"rich_layout_recognition"
);
}
#[test]
fn validation_rejects_empty_inputs() {
assert!(builder().file(Vec::new()).build().is_err());
assert!(builder().filename(" ").build().is_err());
assert!(
OCRRequestBuilder::default()
.file(vec![0u8])
.filename("document.pdf")
.purpose(Purpose::TextRecognition)
.build()
.is_err()
);
assert!(builder().build().is_ok());
}
#[test]
fn response_deserializes_api_example() {
let value = json!({
"id": "ocr-9b2f4c1e-3c0e-4d0f-9d3a-5f2a6f7e8b90",
"object": "ocr.result",
"created": 1762790000,
"purpose": "text_recognition",
"page_count": 2,
"pages": [
{"index": 0, "text": "first page", "finish_reason": "stop"},
{"index": 1, "text": "second page", "finish_reason": "length"}
],
"usage": {"input_tokens": 1536, "output_tokens": 412, "total_tokens": 1948}
});
let resp: OCRResponse = serde_json::from_value(value).unwrap();
assert_eq!(resp.purpose, Purpose::TextRecognition);
assert_eq!(resp.page_count, 2);
assert_eq!(resp.pages.len(), 2);
assert_eq!(resp.pages[1].finish_reason, FinishReason::Length);
assert_eq!(resp.usage.total_tokens, 1948);
}
}