mistral.py 29 KB

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