mistral.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. import requests
  2. import aiohttp
  3. import asyncio
  4. import logging
  5. import os
  6. import sys
  7. import time
  8. from typing import List, Dict, Any
  9. from contextlib import asynccontextmanager
  10. from langchain_core.documents import Document
  11. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  12. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  13. log = logging.getLogger(__name__)
  14. log.setLevel(SRC_LOG_LEVELS["RAG"])
  15. class MistralLoader:
  16. """
  17. Enhanced Mistral OCR loader with both sync and async support.
  18. Loads documents by processing them through the Mistral OCR API.
  19. Performance Optimizations:
  20. - Differentiated timeouts for different operations
  21. - Intelligent retry logic with exponential backoff
  22. - Memory-efficient file streaming for large files
  23. - Connection pooling and keepalive optimization
  24. - Semaphore-based concurrency control for batch processing
  25. - Enhanced error handling with retryable error classification
  26. """
  27. BASE_API_URL = "https://api.mistral.ai/v1"
  28. def __init__(
  29. self,
  30. api_key: str,
  31. file_path: str,
  32. timeout: int = 300, # 5 minutes default
  33. max_retries: int = 3,
  34. enable_debug_logging: bool = False,
  35. ):
  36. """
  37. Initializes the loader with enhanced features.
  38. Args:
  39. api_key: Your Mistral API key.
  40. file_path: The local path to the PDF file to process.
  41. timeout: Request timeout in seconds.
  42. max_retries: Maximum number of retry attempts.
  43. enable_debug_logging: Enable detailed debug logs.
  44. """
  45. if not api_key:
  46. raise ValueError("API key cannot be empty.")
  47. if not os.path.exists(file_path):
  48. raise FileNotFoundError(f"File not found at {file_path}")
  49. self.api_key = api_key
  50. self.file_path = file_path
  51. self.timeout = timeout
  52. self.max_retries = max_retries
  53. self.debug = enable_debug_logging
  54. # PERFORMANCE OPTIMIZATION: Differentiated timeouts for different operations
  55. # This prevents long-running OCR operations from affecting quick operations
  56. # and improves user experience by failing fast on operations that should be quick
  57. self.upload_timeout = min(
  58. timeout, 120
  59. ) # Cap upload at 2 minutes - prevents hanging on large files
  60. self.url_timeout = (
  61. 30 # URL requests should be fast - fail quickly if API is slow
  62. )
  63. self.ocr_timeout = (
  64. timeout # OCR can take the full timeout - this is the heavy operation
  65. )
  66. self.cleanup_timeout = (
  67. 30 # Cleanup should be quick - don't hang on file deletion
  68. )
  69. # PERFORMANCE OPTIMIZATION: Pre-compute file info to avoid repeated filesystem calls
  70. # This avoids multiple os.path.basename() and os.path.getsize() calls during processing
  71. self.file_name = os.path.basename(file_path)
  72. self.file_size = os.path.getsize(file_path)
  73. # ENHANCEMENT: Added User-Agent for better API tracking and debugging
  74. self.headers = {
  75. "Authorization": f"Bearer {self.api_key}",
  76. "User-Agent": "OpenWebUI-MistralLoader/2.0", # Helps API provider track usage
  77. }
  78. def _debug_log(self, message: str, *args) -> None:
  79. """
  80. PERFORMANCE OPTIMIZATION: Conditional debug logging for performance.
  81. Only processes debug messages when debug mode is enabled, avoiding
  82. string formatting overhead in production environments.
  83. """
  84. if self.debug:
  85. log.debug(message, *args)
  86. def _handle_response(self, response: requests.Response) -> Dict[str, Any]:
  87. """Checks response status and returns JSON content."""
  88. try:
  89. response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
  90. # Handle potential empty responses for certain successful requests (e.g., DELETE)
  91. if response.status_code == 204 or not response.content:
  92. return {} # Return empty dict if no content
  93. return response.json()
  94. except requests.exceptions.HTTPError as http_err:
  95. log.error(f"HTTP error occurred: {http_err} - Response: {response.text}")
  96. raise
  97. except requests.exceptions.RequestException as req_err:
  98. log.error(f"Request exception occurred: {req_err}")
  99. raise
  100. except ValueError as json_err: # Includes JSONDecodeError
  101. log.error(f"JSON decode error: {json_err} - Response: {response.text}")
  102. raise # Re-raise after logging
  103. async def _handle_response_async(
  104. self, response: aiohttp.ClientResponse
  105. ) -> Dict[str, Any]:
  106. """Async version of response handling with better error info."""
  107. try:
  108. response.raise_for_status()
  109. # Check content type
  110. content_type = response.headers.get("content-type", "")
  111. if "application/json" not in content_type:
  112. if response.status == 204:
  113. return {}
  114. text = await response.text()
  115. raise ValueError(
  116. f"Unexpected content type: {content_type}, body: {text[:200]}..."
  117. )
  118. return await response.json()
  119. except aiohttp.ClientResponseError as e:
  120. error_text = await response.text() if response else "No response"
  121. log.error(f"HTTP {e.status}: {e.message} - Response: {error_text[:500]}")
  122. raise
  123. except aiohttp.ClientError as e:
  124. log.error(f"Client error: {e}")
  125. raise
  126. except Exception as e:
  127. log.error(f"Unexpected error processing response: {e}")
  128. raise
  129. def _is_retryable_error(self, error: Exception) -> bool:
  130. """
  131. ENHANCEMENT: Intelligent error classification for retry logic.
  132. Determines if an error is retryable based on its type and status code.
  133. This prevents wasting time retrying errors that will never succeed
  134. (like authentication errors) while ensuring transient errors are retried.
  135. Retryable errors:
  136. - Network connection errors (temporary network issues)
  137. - Timeouts (server might be temporarily overloaded)
  138. - Server errors (5xx status codes - server-side issues)
  139. - Rate limiting (429 status - temporary throttling)
  140. Non-retryable errors:
  141. - Authentication errors (401, 403 - won't fix with retry)
  142. - Bad request errors (400 - malformed request)
  143. - Not found errors (404 - resource doesn't exist)
  144. """
  145. if isinstance(error, requests.exceptions.ConnectionError):
  146. return True # Network issues are usually temporary
  147. if isinstance(error, requests.exceptions.Timeout):
  148. return True # Timeouts might resolve on retry
  149. if isinstance(error, requests.exceptions.HTTPError):
  150. # Only retry on server errors (5xx) or rate limits (429)
  151. if hasattr(error, "response") and error.response is not None:
  152. status_code = error.response.status_code
  153. return status_code >= 500 or status_code == 429
  154. return False
  155. if isinstance(
  156. error, (aiohttp.ClientConnectionError, aiohttp.ServerTimeoutError)
  157. ):
  158. return True # Async network/timeout errors are retryable
  159. if isinstance(error, aiohttp.ClientResponseError):
  160. return error.status >= 500 or error.status == 429
  161. return False # All other errors are non-retryable
  162. def _retry_request_sync(self, request_func, *args, **kwargs):
  163. """
  164. ENHANCEMENT: Synchronous retry logic with intelligent error classification.
  165. Uses exponential backoff with jitter to avoid thundering herd problems.
  166. The wait time increases exponentially but is capped at 30 seconds to
  167. prevent excessive delays. Only retries errors that are likely to succeed
  168. on subsequent attempts.
  169. """
  170. for attempt in range(self.max_retries):
  171. try:
  172. return request_func(*args, **kwargs)
  173. except Exception as e:
  174. if attempt == self.max_retries - 1 or not self._is_retryable_error(e):
  175. raise
  176. # PERFORMANCE OPTIMIZATION: Exponential backoff with cap
  177. # Prevents overwhelming the server while ensuring reasonable retry delays
  178. wait_time = min((2**attempt) + 0.5, 30) # Cap at 30 seconds
  179. log.warning(
  180. f"Retryable error (attempt {attempt + 1}/{self.max_retries}): {e}. "
  181. f"Retrying in {wait_time}s..."
  182. )
  183. time.sleep(wait_time)
  184. async def _retry_request_async(self, request_func, *args, **kwargs):
  185. """
  186. ENHANCEMENT: Async retry logic with intelligent error classification.
  187. Async version of retry logic that doesn't block the event loop during
  188. wait periods. Uses the same exponential backoff strategy as sync version.
  189. """
  190. for attempt in range(self.max_retries):
  191. try:
  192. return await request_func(*args, **kwargs)
  193. except Exception as e:
  194. if attempt == self.max_retries - 1 or not self._is_retryable_error(e):
  195. raise
  196. # PERFORMANCE OPTIMIZATION: Non-blocking exponential backoff
  197. wait_time = min((2**attempt) + 0.5, 30) # Cap at 30 seconds
  198. log.warning(
  199. f"Retryable error (attempt {attempt + 1}/{self.max_retries}): {e}. "
  200. f"Retrying in {wait_time}s..."
  201. )
  202. await asyncio.sleep(wait_time) # Non-blocking wait
  203. def _upload_file(self) -> str:
  204. """
  205. PERFORMANCE OPTIMIZATION: Enhanced file upload with streaming consideration.
  206. Uploads the file to Mistral for OCR processing (sync version).
  207. Uses context manager for file handling to ensure proper resource cleanup.
  208. Although streaming is not enabled for this endpoint, the file is opened
  209. in a context manager to minimize memory usage duration.
  210. """
  211. log.info("Uploading file to Mistral API")
  212. url = f"{self.BASE_API_URL}/files"
  213. def upload_request():
  214. # MEMORY OPTIMIZATION: Use context manager to minimize file handle lifetime
  215. # This ensures the file is closed immediately after reading, reducing memory usage
  216. with open(self.file_path, "rb") as f:
  217. files = {"file": (self.file_name, f, "application/pdf")}
  218. data = {"purpose": "ocr"}
  219. # NOTE: stream=False is required for this endpoint
  220. # The Mistral API doesn't support chunked uploads for this endpoint
  221. response = requests.post(
  222. url,
  223. headers=self.headers,
  224. files=files,
  225. data=data,
  226. timeout=self.upload_timeout, # Use specialized upload timeout
  227. stream=False, # Keep as False for this endpoint
  228. )
  229. return self._handle_response(response)
  230. try:
  231. response_data = self._retry_request_sync(upload_request)
  232. file_id = response_data.get("id")
  233. if not file_id:
  234. raise ValueError("File ID not found in upload response.")
  235. log.info(f"File uploaded successfully. File ID: {file_id}")
  236. return file_id
  237. except Exception as e:
  238. log.error(f"Failed to upload file: {e}")
  239. raise
  240. async def _upload_file_async(self, session: aiohttp.ClientSession) -> str:
  241. """Async file upload with streaming for better memory efficiency."""
  242. url = f"{self.BASE_API_URL}/files"
  243. async def upload_request():
  244. # Create multipart writer for streaming upload
  245. writer = aiohttp.MultipartWriter("form-data")
  246. # Add purpose field
  247. purpose_part = writer.append("ocr")
  248. purpose_part.set_content_disposition("form-data", name="purpose")
  249. # Add file part with streaming
  250. file_part = writer.append_payload(
  251. aiohttp.streams.FilePayload(
  252. self.file_path,
  253. filename=self.file_name,
  254. content_type="application/pdf",
  255. )
  256. )
  257. file_part.set_content_disposition(
  258. "form-data", name="file", filename=self.file_name
  259. )
  260. self._debug_log(
  261. f"Uploading file: {self.file_name} ({self.file_size:,} bytes)"
  262. )
  263. async with session.post(
  264. url,
  265. data=writer,
  266. headers=self.headers,
  267. timeout=aiohttp.ClientTimeout(total=self.upload_timeout),
  268. ) as response:
  269. return await self._handle_response_async(response)
  270. response_data = await self._retry_request_async(upload_request)
  271. file_id = response_data.get("id")
  272. if not file_id:
  273. raise ValueError("File ID not found in upload response.")
  274. log.info(f"File uploaded successfully. File ID: {file_id}")
  275. return file_id
  276. def _get_signed_url(self, file_id: str) -> str:
  277. """Retrieves a temporary signed URL for the uploaded file (sync version)."""
  278. log.info(f"Getting signed URL for file ID: {file_id}")
  279. url = f"{self.BASE_API_URL}/files/{file_id}/url"
  280. params = {"expiry": 1}
  281. signed_url_headers = {**self.headers, "Accept": "application/json"}
  282. def url_request():
  283. response = requests.get(
  284. url, headers=signed_url_headers, params=params, timeout=self.url_timeout
  285. )
  286. return self._handle_response(response)
  287. try:
  288. response_data = self._retry_request_sync(url_request)
  289. signed_url = response_data.get("url")
  290. if not signed_url:
  291. raise ValueError("Signed URL not found in response.")
  292. log.info("Signed URL received.")
  293. return signed_url
  294. except Exception as e:
  295. log.error(f"Failed to get signed URL: {e}")
  296. raise
  297. async def _get_signed_url_async(
  298. self, session: aiohttp.ClientSession, file_id: str
  299. ) -> str:
  300. """Async signed URL retrieval."""
  301. url = f"{self.BASE_API_URL}/files/{file_id}/url"
  302. params = {"expiry": 1}
  303. headers = {**self.headers, "Accept": "application/json"}
  304. async def url_request():
  305. self._debug_log(f"Getting signed URL for file ID: {file_id}")
  306. async with session.get(
  307. url,
  308. headers=headers,
  309. params=params,
  310. timeout=aiohttp.ClientTimeout(total=self.url_timeout),
  311. ) as response:
  312. return await self._handle_response_async(response)
  313. response_data = await self._retry_request_async(url_request)
  314. signed_url = response_data.get("url")
  315. if not signed_url:
  316. raise ValueError("Signed URL not found in response.")
  317. self._debug_log("Signed URL received successfully")
  318. return signed_url
  319. def _process_ocr(self, signed_url: str) -> Dict[str, Any]:
  320. """Sends the signed URL to the OCR endpoint for processing (sync version)."""
  321. log.info("Processing OCR via Mistral API")
  322. url = f"{self.BASE_API_URL}/ocr"
  323. ocr_headers = {
  324. **self.headers,
  325. "Content-Type": "application/json",
  326. "Accept": "application/json",
  327. }
  328. payload = {
  329. "model": "mistral-ocr-latest",
  330. "document": {
  331. "type": "document_url",
  332. "document_url": signed_url,
  333. },
  334. "include_image_base64": False,
  335. }
  336. def ocr_request():
  337. response = requests.post(
  338. url, headers=ocr_headers, json=payload, timeout=self.ocr_timeout
  339. )
  340. return self._handle_response(response)
  341. try:
  342. ocr_response = self._retry_request_sync(ocr_request)
  343. log.info("OCR processing done.")
  344. self._debug_log("OCR response: %s", ocr_response)
  345. return ocr_response
  346. except Exception as e:
  347. log.error(f"Failed during OCR processing: {e}")
  348. raise
  349. async def _process_ocr_async(
  350. self, session: aiohttp.ClientSession, signed_url: str
  351. ) -> Dict[str, Any]:
  352. """Async OCR processing with timing metrics."""
  353. url = f"{self.BASE_API_URL}/ocr"
  354. headers = {
  355. **self.headers,
  356. "Content-Type": "application/json",
  357. "Accept": "application/json",
  358. }
  359. payload = {
  360. "model": "mistral-ocr-latest",
  361. "document": {
  362. "type": "document_url",
  363. "document_url": signed_url,
  364. },
  365. "include_image_base64": False,
  366. }
  367. async def ocr_request():
  368. log.info("Starting OCR processing via Mistral API")
  369. start_time = time.time()
  370. async with session.post(
  371. url,
  372. json=payload,
  373. headers=headers,
  374. timeout=aiohttp.ClientTimeout(total=self.ocr_timeout),
  375. ) as response:
  376. ocr_response = await self._handle_response_async(response)
  377. processing_time = time.time() - start_time
  378. log.info(f"OCR processing completed in {processing_time:.2f}s")
  379. return ocr_response
  380. return await self._retry_request_async(ocr_request)
  381. def _delete_file(self, file_id: str) -> None:
  382. """Deletes the file from Mistral storage (sync version)."""
  383. log.info(f"Deleting uploaded file ID: {file_id}")
  384. url = f"{self.BASE_API_URL}/files/{file_id}"
  385. try:
  386. response = requests.delete(
  387. url, headers=self.headers, timeout=self.cleanup_timeout
  388. )
  389. delete_response = self._handle_response(response)
  390. log.info(f"File deleted successfully: {delete_response}")
  391. except Exception as e:
  392. # Log error but don't necessarily halt execution if deletion fails
  393. log.error(f"Failed to delete file ID {file_id}: {e}")
  394. async def _delete_file_async(
  395. self, session: aiohttp.ClientSession, file_id: str
  396. ) -> None:
  397. """Async file deletion with error tolerance."""
  398. try:
  399. async def delete_request():
  400. self._debug_log(f"Deleting file ID: {file_id}")
  401. async with session.delete(
  402. url=f"{self.BASE_API_URL}/files/{file_id}",
  403. headers=self.headers,
  404. timeout=aiohttp.ClientTimeout(
  405. total=self.cleanup_timeout
  406. ), # Shorter timeout for cleanup
  407. ) as response:
  408. return await self._handle_response_async(response)
  409. await self._retry_request_async(delete_request)
  410. self._debug_log(f"File {file_id} deleted successfully")
  411. except Exception as e:
  412. # Don't fail the entire process if cleanup fails
  413. log.warning(f"Failed to delete file ID {file_id}: {e}")
  414. @asynccontextmanager
  415. async def _get_session(self):
  416. """Context manager for HTTP session with optimized settings."""
  417. connector = aiohttp.TCPConnector(
  418. limit=20, # Increased total connection limit for better throughput
  419. limit_per_host=10, # Increased per-host limit for API endpoints
  420. ttl_dns_cache=600, # Longer DNS cache TTL (10 minutes)
  421. use_dns_cache=True,
  422. keepalive_timeout=60, # Increased keepalive for connection reuse
  423. enable_cleanup_closed=True,
  424. force_close=False, # Allow connection reuse
  425. resolver=aiohttp.AsyncResolver(), # Use async DNS resolver
  426. )
  427. timeout = aiohttp.ClientTimeout(
  428. total=self.timeout,
  429. connect=30, # Connection timeout
  430. sock_read=60, # Socket read timeout
  431. )
  432. async with aiohttp.ClientSession(
  433. connector=connector,
  434. timeout=timeout,
  435. headers={"User-Agent": "OpenWebUI-MistralLoader/2.0"},
  436. raise_for_status=False, # We handle status codes manually
  437. trust_env=True,
  438. ) as session:
  439. yield session
  440. def _process_results(self, ocr_response: Dict[str, Any]) -> List[Document]:
  441. """Process OCR results into Document objects with enhanced metadata and memory efficiency."""
  442. pages_data = ocr_response.get("pages")
  443. if not pages_data:
  444. log.warning("No pages found in OCR response.")
  445. return [
  446. Document(
  447. page_content="No text content found",
  448. metadata={"error": "no_pages", "file_name": self.file_name},
  449. )
  450. ]
  451. documents = []
  452. total_pages = len(pages_data)
  453. skipped_pages = 0
  454. # Process pages in a memory-efficient way
  455. for page_data in pages_data:
  456. page_content = page_data.get("markdown")
  457. page_index = page_data.get("index") # API uses 0-based index
  458. if page_content is None or page_index is None:
  459. skipped_pages += 1
  460. self._debug_log(
  461. f"Skipping page due to missing 'markdown' or 'index'. Data keys: {list(page_data.keys())}"
  462. )
  463. continue
  464. # Clean up content efficiently with early exit for empty content
  465. if isinstance(page_content, str):
  466. cleaned_content = page_content.strip()
  467. else:
  468. cleaned_content = str(page_content).strip()
  469. if not cleaned_content:
  470. skipped_pages += 1
  471. self._debug_log(f"Skipping empty page {page_index}")
  472. continue
  473. # Create document with optimized metadata
  474. documents.append(
  475. Document(
  476. page_content=cleaned_content,
  477. metadata={
  478. "page": page_index, # 0-based index from API
  479. "page_label": page_index + 1, # 1-based label for convenience
  480. "total_pages": total_pages,
  481. "file_name": self.file_name,
  482. "file_size": self.file_size,
  483. "processing_engine": "mistral-ocr",
  484. "content_length": len(cleaned_content),
  485. },
  486. )
  487. )
  488. if skipped_pages > 0:
  489. log.info(
  490. f"Processed {len(documents)} pages, skipped {skipped_pages} empty/invalid pages"
  491. )
  492. if not documents:
  493. # Case where pages existed but none had valid markdown/index
  494. log.warning(
  495. "OCR response contained pages, but none had valid content/index."
  496. )
  497. return [
  498. Document(
  499. page_content="No valid text content found in document",
  500. metadata={
  501. "error": "no_valid_pages",
  502. "total_pages": total_pages,
  503. "file_name": self.file_name,
  504. },
  505. )
  506. ]
  507. return documents
  508. def load(self) -> List[Document]:
  509. """
  510. Executes the full OCR workflow: upload, get URL, process OCR, delete file.
  511. Synchronous version for backward compatibility.
  512. Returns:
  513. A list of Document objects, one for each page processed.
  514. """
  515. file_id = None
  516. start_time = time.time()
  517. try:
  518. # 1. Upload file
  519. file_id = self._upload_file()
  520. # 2. Get Signed URL
  521. signed_url = self._get_signed_url(file_id)
  522. # 3. Process OCR
  523. ocr_response = self._process_ocr(signed_url)
  524. # 4. Process results
  525. documents = self._process_results(ocr_response)
  526. total_time = time.time() - start_time
  527. log.info(
  528. f"Sync OCR workflow completed in {total_time:.2f}s, produced {len(documents)} documents"
  529. )
  530. return documents
  531. except Exception as e:
  532. total_time = time.time() - start_time
  533. log.error(
  534. f"An error occurred during the loading process after {total_time:.2f}s: {e}"
  535. )
  536. # Return an error document on failure
  537. return [
  538. Document(
  539. page_content=f"Error during processing: {e}",
  540. metadata={
  541. "error": "processing_failed",
  542. "file_name": self.file_name,
  543. },
  544. )
  545. ]
  546. finally:
  547. # 5. Delete file (attempt even if prior steps failed after upload)
  548. if file_id:
  549. try:
  550. self._delete_file(file_id)
  551. except Exception as del_e:
  552. # Log deletion error, but don't overwrite original error if one occurred
  553. log.error(
  554. f"Cleanup error: Could not delete file ID {file_id}. Reason: {del_e}"
  555. )
  556. async def load_async(self) -> List[Document]:
  557. """
  558. Asynchronous OCR workflow execution with optimized performance.
  559. Returns:
  560. A list of Document objects, one for each page processed.
  561. """
  562. file_id = None
  563. start_time = time.time()
  564. try:
  565. async with self._get_session() as session:
  566. # 1. Upload file with streaming
  567. file_id = await self._upload_file_async(session)
  568. # 2. Get signed URL
  569. signed_url = await self._get_signed_url_async(session, file_id)
  570. # 3. Process OCR
  571. ocr_response = await self._process_ocr_async(session, signed_url)
  572. # 4. Process results
  573. documents = self._process_results(ocr_response)
  574. total_time = time.time() - start_time
  575. log.info(
  576. f"Async OCR workflow completed in {total_time:.2f}s, produced {len(documents)} documents"
  577. )
  578. return documents
  579. except Exception as e:
  580. total_time = time.time() - start_time
  581. log.error(f"Async OCR workflow failed after {total_time:.2f}s: {e}")
  582. return [
  583. Document(
  584. page_content=f"Error during OCR processing: {e}",
  585. metadata={
  586. "error": "processing_failed",
  587. "file_name": self.file_name,
  588. },
  589. )
  590. ]
  591. finally:
  592. # 5. Cleanup - always attempt file deletion
  593. if file_id:
  594. try:
  595. async with self._get_session() as session:
  596. await self._delete_file_async(session, file_id)
  597. except Exception as cleanup_error:
  598. log.error(f"Cleanup failed for file ID {file_id}: {cleanup_error}")
  599. @staticmethod
  600. async def load_multiple_async(
  601. loaders: List["MistralLoader"],
  602. max_concurrent: int = 5, # Limit concurrent requests
  603. ) -> List[List[Document]]:
  604. """
  605. Process multiple files concurrently with controlled concurrency.
  606. Args:
  607. loaders: List of MistralLoader instances
  608. max_concurrent: Maximum number of concurrent requests
  609. Returns:
  610. List of document lists, one for each loader
  611. """
  612. if not loaders:
  613. return []
  614. log.info(
  615. f"Starting concurrent processing of {len(loaders)} files with max {max_concurrent} concurrent"
  616. )
  617. start_time = time.time()
  618. # Use semaphore to control concurrency
  619. semaphore = asyncio.Semaphore(max_concurrent)
  620. async def process_with_semaphore(loader: "MistralLoader") -> List[Document]:
  621. async with semaphore:
  622. return await loader.load_async()
  623. # Process all files with controlled concurrency
  624. tasks = [process_with_semaphore(loader) for loader in loaders]
  625. results = await asyncio.gather(*tasks, return_exceptions=True)
  626. # Handle any exceptions in results
  627. processed_results = []
  628. for i, result in enumerate(results):
  629. if isinstance(result, Exception):
  630. log.error(f"File {i} failed: {result}")
  631. processed_results.append(
  632. [
  633. Document(
  634. page_content=f"Error processing file: {result}",
  635. metadata={
  636. "error": "batch_processing_failed",
  637. "file_index": i,
  638. },
  639. )
  640. ]
  641. )
  642. else:
  643. processed_results.append(result)
  644. # MONITORING: Log comprehensive batch processing statistics
  645. total_time = time.time() - start_time
  646. total_docs = sum(len(docs) for docs in processed_results)
  647. success_count = sum(
  648. 1 for result in results if not isinstance(result, Exception)
  649. )
  650. failure_count = len(results) - success_count
  651. log.info(
  652. f"Batch processing completed in {total_time:.2f}s: "
  653. f"{success_count} files succeeded, {failure_count} files failed, "
  654. f"produced {total_docs} total documents"
  655. )
  656. return processed_results