datalab_marker_loader.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import os
  2. import time
  3. import requests
  4. import logging
  5. import json
  6. from typing import List, Optional
  7. from langchain_core.documents import Document
  8. from fastapi import HTTPException, status
  9. log = logging.getLogger(__name__)
  10. class DatalabMarkerLoader:
  11. def __init__(
  12. self,
  13. file_path: str,
  14. api_key: str,
  15. langs: Optional[str] = None,
  16. use_llm: bool = False,
  17. skip_cache: bool = False,
  18. force_ocr: bool = False,
  19. paginate: bool = False,
  20. strip_existing_ocr: bool = False,
  21. disable_image_extraction: bool = False,
  22. output_format: str = None,
  23. ):
  24. self.file_path = file_path
  25. self.api_key = api_key
  26. self.langs = langs
  27. self.use_llm = use_llm
  28. self.skip_cache = skip_cache
  29. self.force_ocr = force_ocr
  30. self.paginate = paginate
  31. self.strip_existing_ocr = strip_existing_ocr
  32. self.disable_image_extraction = disable_image_extraction
  33. self.output_format = output_format
  34. def _get_mime_type(self, filename: str) -> str:
  35. ext = filename.rsplit(".", 1)[-1].lower()
  36. mime_map = {
  37. "pdf": "application/pdf",
  38. "xls": "application/vnd.ms-excel",
  39. "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  40. "ods": "application/vnd.oasis.opendocument.spreadsheet",
  41. "doc": "application/msword",
  42. "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  43. "odt": "application/vnd.oasis.opendocument.text",
  44. "ppt": "application/vnd.ms-powerpoint",
  45. "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  46. "odp": "application/vnd.oasis.opendocument.presentation",
  47. "html": "text/html",
  48. "epub": "application/epub+zip",
  49. "png": "image/png",
  50. "jpeg": "image/jpeg",
  51. "jpg": "image/jpeg",
  52. "webp": "image/webp",
  53. "gif": "image/gif",
  54. "tiff": "image/tiff",
  55. }
  56. return mime_map.get(ext, "application/octet-stream")
  57. def check_marker_request_status(self, request_id: str) -> dict:
  58. url = f"https://www.datalab.to/api/v1/marker/{request_id}"
  59. headers = {"X-Api-Key": self.api_key}
  60. try:
  61. response = requests.get(url, headers=headers)
  62. response.raise_for_status()
  63. result = response.json()
  64. log.info(f"Marker API status check for request {request_id}: {result}")
  65. return result
  66. except requests.HTTPError as e:
  67. log.error(f"Error checking Marker request status: {e}")
  68. raise HTTPException(
  69. status.HTTP_502_BAD_GATEWAY,
  70. detail=f"Failed to check Marker request: {e}",
  71. )
  72. except ValueError as e:
  73. log.error(f"Invalid JSON checking Marker request: {e}")
  74. raise HTTPException(
  75. status.HTTP_502_BAD_GATEWAY, detail=f"Invalid JSON: {e}"
  76. )
  77. def load(self) -> List[Document]:
  78. url = "https://www.datalab.to/api/v1/marker"
  79. filename = os.path.basename(self.file_path)
  80. mime_type = self._get_mime_type(filename)
  81. headers = {"X-Api-Key": self.api_key}
  82. form_data = {
  83. "langs": self.langs,
  84. "use_llm": str(self.use_llm).lower(),
  85. "skip_cache": str(self.skip_cache).lower(),
  86. "force_ocr": str(self.force_ocr).lower(),
  87. "paginate": str(self.paginate).lower(),
  88. "strip_existing_ocr": str(self.strip_existing_ocr).lower(),
  89. "disable_image_extraction": str(self.disable_image_extraction).lower(),
  90. "output_format": self.output_format,
  91. }
  92. log.info(
  93. f"Datalab Marker POST request parameters: {{'filename': '{filename}', 'mime_type': '{mime_type}', **{form_data}}}"
  94. )
  95. try:
  96. with open(self.file_path, "rb") as f:
  97. files = {"file": (filename, f, mime_type)}
  98. response = requests.post(
  99. url, data=form_data, files=files, headers=headers
  100. )
  101. response.raise_for_status()
  102. result = response.json()
  103. except FileNotFoundError:
  104. raise HTTPException(
  105. status.HTTP_404_NOT_FOUND, detail=f"File not found: {self.file_path}"
  106. )
  107. except requests.HTTPError as e:
  108. raise HTTPException(
  109. status.HTTP_400_BAD_REQUEST,
  110. detail=f"Datalab Marker request failed: {e}",
  111. )
  112. except ValueError as e:
  113. raise HTTPException(
  114. status.HTTP_502_BAD_GATEWAY, detail=f"Invalid JSON response: {e}"
  115. )
  116. except Exception as e:
  117. raise HTTPException(status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
  118. if not result.get("success"):
  119. raise HTTPException(
  120. status.HTTP_400_BAD_REQUEST,
  121. detail=f"Datalab Marker request failed: {result.get('error', 'Unknown error')}",
  122. )
  123. check_url = result.get("request_check_url")
  124. request_id = result.get("request_id")
  125. if not check_url:
  126. raise HTTPException(
  127. status.HTTP_502_BAD_GATEWAY, detail="No request_check_url returned."
  128. )
  129. for _ in range(300): # Up to 10 minutes
  130. time.sleep(2)
  131. try:
  132. poll_response = requests.get(check_url, headers=headers)
  133. poll_response.raise_for_status()
  134. poll_result = poll_response.json()
  135. except (requests.HTTPError, ValueError) as e:
  136. raw_body = poll_response.text
  137. log.error(f"Polling error: {e}, response body: {raw_body}")
  138. raise HTTPException(
  139. status.HTTP_502_BAD_GATEWAY, detail=f"Polling failed: {e}"
  140. )
  141. status_val = poll_result.get("status")
  142. success_val = poll_result.get("success")
  143. if status_val == "complete":
  144. summary = {
  145. k: poll_result.get(k)
  146. for k in (
  147. "status",
  148. "output_format",
  149. "success",
  150. "error",
  151. "page_count",
  152. "total_cost",
  153. )
  154. }
  155. log.info(
  156. f"Marker processing completed successfully: {json.dumps(summary, indent=2)}"
  157. )
  158. break
  159. if status_val == "failed" or success_val is False:
  160. log.error(
  161. f"Marker poll failed full response: {json.dumps(poll_result, indent=2)}"
  162. )
  163. error_msg = (
  164. poll_result.get("error")
  165. or "Marker returned failure without error message"
  166. )
  167. raise HTTPException(
  168. status.HTTP_400_BAD_REQUEST,
  169. detail=f"Marker processing failed: {error_msg}",
  170. )
  171. else:
  172. raise HTTPException(
  173. status.HTTP_504_GATEWAY_TIMEOUT, detail="Marker processing timed out"
  174. )
  175. if not poll_result.get("success", False):
  176. error_msg = poll_result.get("error") or "Unknown processing error"
  177. raise HTTPException(
  178. status.HTTP_400_BAD_REQUEST,
  179. detail=f"Final processing failed: {error_msg}",
  180. )
  181. content_key = self.output_format.lower()
  182. raw_content = poll_result.get(content_key)
  183. if content_key == "json":
  184. full_text = json.dumps(raw_content, indent=2)
  185. elif content_key in {"markdown", "html"}:
  186. full_text = str(raw_content).strip()
  187. else:
  188. raise HTTPException(
  189. status.HTTP_400_BAD_REQUEST,
  190. detail=f"Unsupported output format: {self.output_format}",
  191. )
  192. if not full_text:
  193. raise HTTPException(
  194. status.HTTP_400_BAD_REQUEST,
  195. detail="Datalab Marker returned empty content",
  196. )
  197. marker_output_dir = os.path.join("/app/backend/data/uploads", "marker_output")
  198. os.makedirs(marker_output_dir, exist_ok=True)
  199. file_ext_map = {"markdown": "md", "json": "json", "html": "html"}
  200. file_ext = file_ext_map.get(content_key, "txt")
  201. output_filename = f"{os.path.splitext(filename)[0]}.{file_ext}"
  202. output_path = os.path.join(marker_output_dir, output_filename)
  203. try:
  204. with open(output_path, "w", encoding="utf-8") as f:
  205. f.write(full_text)
  206. log.info(f"Saved Marker output to: {output_path}")
  207. except Exception as e:
  208. log.warning(f"Failed to write marker output to disk: {e}")
  209. metadata = {
  210. "source": filename,
  211. "output_format": poll_result.get("output_format", self.output_format),
  212. "page_count": poll_result.get("page_count", 0),
  213. "processed_with_llm": self.use_llm,
  214. "request_id": request_id or "",
  215. }
  216. images = poll_result.get("images", {})
  217. if images:
  218. metadata["image_count"] = len(images)
  219. metadata["images"] = json.dumps(list(images.keys()))
  220. for k, v in metadata.items():
  221. if isinstance(v, (dict, list)):
  222. metadata[k] = json.dumps(v)
  223. elif v is None:
  224. metadata[k] = ""
  225. return [Document(page_content=full_text, metadata=metadata)]