Spaces:
Sleeping
Sleeping
File size: 9,064 Bytes
097eaf0 | 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 | //! Parse endpoint for Firecrawl API v2.
use std::path::Path;
use reqwest::multipart::{Form, Part};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use super::client::Client;
use super::scrape::ParserConfig;
use super::types::{AttributeSelector, Document, JsonOptions};
use crate::FirecrawlError;
/// Uploaded file payload for the `/v2/parse` endpoint.
#[derive(Debug, Clone)]
pub struct ParseFile {
pub filename: String,
pub bytes: Vec<u8>,
pub content_type: Option<String>,
}
impl ParseFile {
/// Build a parse file from in-memory bytes.
pub fn from_bytes(filename: impl Into<String>, bytes: Vec<u8>) -> Self {
Self {
filename: filename.into(),
bytes,
content_type: None,
}
}
/// Build a parse file by reading bytes from disk.
pub fn from_path(path: impl AsRef<Path>) -> Result<Self, FirecrawlError> {
let path_ref = path.as_ref();
let bytes = std::fs::read(path_ref).map_err(|e| {
FirecrawlError::Misuse(format!(
"Failed to read parse file {}: {}",
path_ref.display(),
e
))
})?;
let filename = path_ref
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| {
FirecrawlError::Misuse("Could not derive a valid filename from path".to_string())
})?
.to_string();
Ok(Self {
filename,
bytes,
content_type: None,
})
}
/// Attach a content type hint (e.g. `text/html`, `application/pdf`).
pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = Some(content_type.into());
self
}
}
/// Response from parse endpoint.
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
struct ParseResponse {
success: bool,
data: Document,
#[serde(skip_serializing_if = "Option::is_none")]
warning: Option<String>,
}
/// Proxy settings accepted by `/v2/parse`.
#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ParseProxyType {
Basic,
Auto,
}
/// Output formats accepted by `/v2/parse`.
#[derive(Deserialize, Serialize, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ParseFormat {
Markdown,
Html,
RawHtml,
Links,
Images,
Summary,
Json,
Attributes,
}
/// Options accepted by the `/v2/parse` endpoint.
///
/// This intentionally omits scrape-only fields that `/v2/parse` rejects
/// (e.g. actions, waitFor, location, and screenshot/branding/changeTracking options).
#[serde_with::skip_serializing_none]
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ParseOptions {
/// Output formats to include in the response.
pub formats: Option<Vec<ParseFormat>>,
/// Additional HTTP headers.
pub headers: Option<HashMap<String, String>>,
/// HTML tags to include.
pub include_tags: Option<Vec<String>>,
/// HTML tags to exclude.
pub exclude_tags: Option<Vec<String>>,
/// Extract only the main content.
pub only_main_content: Option<bool>,
/// Timeout in milliseconds.
pub timeout: Option<u32>,
/// Parser configurations (e.g. PDF parser).
pub parsers: Option<Vec<ParserConfig>>,
/// Skip TLS verification.
pub skip_tls_verification: Option<bool>,
/// Remove base64 images.
pub remove_base64_images: Option<bool>,
/// Fast mode.
pub fast_mode: Option<bool>,
/// Mock fixture id to use.
pub use_mock: Option<String>,
/// Block ads.
pub block_ads: Option<bool>,
/// Proxy type.
pub proxy: Option<ParseProxyType>,
/// Integration identifier.
pub integration: Option<String>,
/// Request origin identifier.
pub origin: Option<String>,
/// Zero data retention mode.
pub zero_data_retention: Option<bool>,
/// JSON extraction options.
pub json_options: Option<JsonOptions>,
/// Attribute selectors for extraction.
pub attribute_selectors: Option<Vec<AttributeSelector>>,
}
impl Client {
/// Parse an uploaded file and return the extracted document.
pub async fn parse(
&self,
file: ParseFile,
options: impl Into<Option<ParseOptions>>,
) -> Result<Document, FirecrawlError> {
let resolved_filename = file.filename.trim().to_string();
if resolved_filename.is_empty() {
return Err(FirecrawlError::Misuse(
"filename cannot be empty".to_string(),
));
}
if file.bytes.is_empty() {
return Err(FirecrawlError::Misuse(
"file content cannot be empty".to_string(),
));
}
let options = options.into().unwrap_or_default();
let options_json =
serde_json::to_string(&options).map_err(FirecrawlError::ResponseParseError)?;
let mut part = Part::bytes(file.bytes).file_name(resolved_filename);
if let Some(content_type) = file.content_type {
part = part.mime_str(&content_type).map_err(|e| {
FirecrawlError::Misuse(format!("Invalid content type for parse file: {}", e))
})?;
}
let form = Form::new().text("options", options_json).part("file", part);
let headers = self.prepare_multipart_headers(None);
let response = self
.client
.post(self.url("/parse"))
.headers(headers)
.multipart(form)
.send()
.await
.map_err(|e| FirecrawlError::HttpError("Parsing uploaded file".to_string(), e))?;
let response: ParseResponse = self.handle_response(response, "parse").await?;
Ok(response.data)
}
}
#[cfg(test)]
mod tests {
use super::*;
use mockito::Matcher;
use serde_json::json;
#[tokio::test]
async fn test_parse_with_mock() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v2/parse")
.match_header(
"content-type",
Matcher::Regex("multipart/form-data".to_string()),
)
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"success": true,
"data": {
"markdown": "# Parsed File",
"metadata": {
"sourceURL": "https://parse.firecrawl.dev/uploads/upload.html",
"statusCode": 200
}
}
})
.to_string(),
)
.create();
let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
let file = ParseFile::from_bytes("upload.html", b"<html><body>ok</body></html>".to_vec())
.with_content_type("text/html");
let doc = client.parse(file, None).await.unwrap();
assert!(doc.markdown.is_some());
assert!(doc.markdown.unwrap().contains("Parsed File"));
mock.assert();
}
#[test]
fn test_parse_file_from_missing_path() {
let result = ParseFile::from_path("/tmp/this-file-should-not-exist-for-parse-sdk-test");
assert!(result.is_err());
}
#[tokio::test]
async fn test_parse_error_response() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v2/parse")
.match_header(
"content-type",
Matcher::Regex("multipart/form-data".to_string()),
)
.with_status(400)
.with_header("content-type", "application/json")
.with_body(
json!({
"success": false,
"error": "Unsupported upload type."
})
.to_string(),
)
.create();
let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
let file = ParseFile::from_bytes("upload.xyz", b"not a real file".to_vec());
let result = client.parse(file, None).await;
assert!(result.is_err());
mock.assert();
}
#[test]
fn test_parse_rejects_empty_bytes() {
let file = ParseFile::from_bytes("empty.html", vec![]);
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async {
let client = Client::new_selfhosted("http://localhost:9999", Some("k")).unwrap();
client.parse(file, None).await
});
assert!(result.is_err());
let err_msg = format!("{}", result.unwrap_err());
assert!(
err_msg.contains("empty"),
"Expected empty file error, got: {}",
err_msg
);
}
}
|