main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. import requests
  2. import logging
  3. import ftfy
  4. import sys
  5. import json
  6. from langchain_community.document_loaders import (
  7. AzureAIDocumentIntelligenceLoader,
  8. BSHTMLLoader,
  9. CSVLoader,
  10. Docx2txtLoader,
  11. OutlookMessageLoader,
  12. PyPDFLoader,
  13. TextLoader,
  14. UnstructuredEPubLoader,
  15. UnstructuredExcelLoader,
  16. UnstructuredODTLoader,
  17. UnstructuredPowerPointLoader,
  18. UnstructuredRSTLoader,
  19. UnstructuredXMLLoader,
  20. YoutubeLoader,
  21. )
  22. from langchain_core.documents import Document
  23. from open_webui.retrieval.loaders.external_document import ExternalDocumentLoader
  24. from open_webui.retrieval.loaders.mistral import MistralLoader
  25. from open_webui.retrieval.loaders.datalab_marker import DatalabMarkerLoader
  26. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  27. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  28. log = logging.getLogger(__name__)
  29. log.setLevel(SRC_LOG_LEVELS["RAG"])
  30. known_source_ext = [
  31. "go",
  32. "py",
  33. "java",
  34. "sh",
  35. "bat",
  36. "ps1",
  37. "cmd",
  38. "js",
  39. "ts",
  40. "css",
  41. "cpp",
  42. "hpp",
  43. "h",
  44. "c",
  45. "cs",
  46. "sql",
  47. "log",
  48. "ini",
  49. "pl",
  50. "pm",
  51. "r",
  52. "dart",
  53. "dockerfile",
  54. "env",
  55. "php",
  56. "hs",
  57. "hsc",
  58. "lua",
  59. "nginxconf",
  60. "conf",
  61. "m",
  62. "mm",
  63. "plsql",
  64. "perl",
  65. "rb",
  66. "rs",
  67. "db2",
  68. "scala",
  69. "bash",
  70. "swift",
  71. "vue",
  72. "svelte",
  73. "ex",
  74. "exs",
  75. "erl",
  76. "tsx",
  77. "jsx",
  78. "hs",
  79. "lhs",
  80. "json",
  81. ]
  82. class TikaLoader:
  83. def __init__(self, url, file_path, mime_type=None, extract_images=None):
  84. self.url = url
  85. self.file_path = file_path
  86. self.mime_type = mime_type
  87. self.extract_images = extract_images
  88. def load(self) -> list[Document]:
  89. with open(self.file_path, "rb") as f:
  90. data = f.read()
  91. if self.mime_type is not None:
  92. headers = {"Content-Type": self.mime_type}
  93. else:
  94. headers = {}
  95. if self.extract_images == True:
  96. headers["X-Tika-PDFextractInlineImages"] = "true"
  97. endpoint = self.url
  98. if not endpoint.endswith("/"):
  99. endpoint += "/"
  100. endpoint += "tika/text"
  101. r = requests.put(endpoint, data=data, headers=headers)
  102. if r.ok:
  103. raw_metadata = r.json()
  104. text = raw_metadata.get("X-TIKA:content", "<No text content found>").strip()
  105. if "Content-Type" in raw_metadata:
  106. headers["Content-Type"] = raw_metadata["Content-Type"]
  107. log.debug("Tika extracted text: %s", text)
  108. return [Document(page_content=text, metadata=headers)]
  109. else:
  110. raise Exception(f"Error calling Tika: {r.reason}")
  111. class DoclingLoader:
  112. def __init__(self, url, file_path=None, mime_type=None, params=None):
  113. self.url = url.rstrip("/")
  114. self.file_path = file_path
  115. self.mime_type = mime_type
  116. self.params = params or {}
  117. def load(self) -> list[Document]:
  118. with open(self.file_path, "rb") as f:
  119. files = {
  120. "files": (
  121. self.file_path,
  122. f,
  123. self.mime_type or "application/octet-stream",
  124. )
  125. }
  126. params = {"image_export_mode": "placeholder", "table_mode": "accurate"}
  127. if self.params:
  128. if self.params.get("do_picture_description"):
  129. params["do_picture_description"] = self.params.get(
  130. "do_picture_description"
  131. )
  132. picture_description_mode = self.params.get(
  133. "picture_description_mode", ""
  134. ).lower()
  135. if picture_description_mode == "local" and self.params.get(
  136. "picture_description_local", {}
  137. ):
  138. params["picture_description_local"] = json.dumps(
  139. self.params.get("picture_description_local", {})
  140. )
  141. elif picture_description_mode == "api" and self.params.get(
  142. "picture_description_api", {}
  143. ):
  144. params["picture_description_api"] = json.dumps(
  145. self.params.get("picture_description_api", {})
  146. )
  147. if self.params.get("ocr_engine") and self.params.get("ocr_lang"):
  148. params["ocr_engine"] = self.params.get("ocr_engine")
  149. params["ocr_lang"] = [
  150. lang.strip()
  151. for lang in self.params.get("ocr_lang").split(",")
  152. if lang.strip()
  153. ]
  154. endpoint = f"{self.url}/v1alpha/convert/file"
  155. r = requests.post(endpoint, files=files, data=params)
  156. if r.ok:
  157. result = r.json()
  158. document_data = result.get("document", {})
  159. text = document_data.get("md_content", "<No text content found>")
  160. metadata = {"Content-Type": self.mime_type} if self.mime_type else {}
  161. log.debug("Docling extracted text: %s", text)
  162. return [Document(page_content=text, metadata=metadata)]
  163. else:
  164. error_msg = f"Error calling Docling API: {r.reason}"
  165. if r.text:
  166. try:
  167. error_data = r.json()
  168. if "detail" in error_data:
  169. error_msg += f" - {error_data['detail']}"
  170. except Exception:
  171. error_msg += f" - {r.text}"
  172. raise Exception(f"Error calling Docling: {error_msg}")
  173. class Loader:
  174. def __init__(self, engine: str = "", **kwargs):
  175. self.engine = engine
  176. self.kwargs = kwargs
  177. def load(
  178. self, filename: str, file_content_type: str, file_path: str
  179. ) -> list[Document]:
  180. loader = self._get_loader(filename, file_content_type, file_path)
  181. docs = loader.load()
  182. return [
  183. Document(
  184. page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata
  185. )
  186. for doc in docs
  187. ]
  188. def _is_text_file(self, file_ext: str, file_content_type: str) -> bool:
  189. return file_ext in known_source_ext or (
  190. file_content_type
  191. and file_content_type.find("text/") >= 0
  192. # Avoid text/html files being detected as text
  193. and not file_content_type.find("html") >= 0
  194. )
  195. def _get_loader(self, filename: str, file_content_type: str, file_path: str):
  196. file_ext = filename.split(".")[-1].lower()
  197. if (
  198. self.engine == "external"
  199. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL")
  200. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY")
  201. ):
  202. loader = ExternalDocumentLoader(
  203. file_path=file_path,
  204. url=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL"),
  205. api_key=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY"),
  206. mime_type=file_content_type,
  207. )
  208. elif self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
  209. if self._is_text_file(file_ext, file_content_type):
  210. loader = TextLoader(file_path, autodetect_encoding=True)
  211. else:
  212. loader = TikaLoader(
  213. url=self.kwargs.get("TIKA_SERVER_URL"),
  214. file_path=file_path,
  215. mime_type=file_content_type,
  216. extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES"),
  217. )
  218. elif (
  219. self.engine == "datalab_marker"
  220. and self.kwargs.get("DATALAB_MARKER_API_KEY")
  221. and file_ext
  222. in [
  223. "pdf",
  224. "xls",
  225. "xlsx",
  226. "ods",
  227. "doc",
  228. "docx",
  229. "odt",
  230. "ppt",
  231. "pptx",
  232. "odp",
  233. "html",
  234. "epub",
  235. "png",
  236. "jpeg",
  237. "jpg",
  238. "webp",
  239. "gif",
  240. "tiff",
  241. ]
  242. ):
  243. api_base_url = self.kwargs.get("DATALAB_MARKER_API_BASE_URL", "")
  244. if not api_base_url or api_base_url.strip() == "":
  245. api_base_url = "https://www.datalab.to/api/v1/marker"
  246. loader = DatalabMarkerLoader(
  247. file_path=file_path,
  248. api_key=self.kwargs["DATALAB_MARKER_API_KEY"],
  249. api_base_url=api_base_url,
  250. additional_config=self.kwargs.get("DATALAB_MARKER_ADDITIONAL_CONFIG"),
  251. use_llm=self.kwargs.get("DATALAB_MARKER_USE_LLM", False),
  252. skip_cache=self.kwargs.get("DATALAB_MARKER_SKIP_CACHE", False),
  253. force_ocr=self.kwargs.get("DATALAB_MARKER_FORCE_OCR", False),
  254. paginate=self.kwargs.get("DATALAB_MARKER_PAGINATE", False),
  255. strip_existing_ocr=self.kwargs.get(
  256. "DATALAB_MARKER_STRIP_EXISTING_OCR", False
  257. ),
  258. disable_image_extraction=self.kwargs.get(
  259. "DATALAB_MARKER_DISABLE_IMAGE_EXTRACTION", False
  260. ),
  261. format_lines=self.kwargs.get("DATALAB_MARKER_FORMAT_LINES", False),
  262. output_format=self.kwargs.get(
  263. "DATALAB_MARKER_OUTPUT_FORMAT", "markdown"
  264. ),
  265. )
  266. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  267. if self._is_text_file(file_ext, file_content_type):
  268. loader = TextLoader(file_path, autodetect_encoding=True)
  269. else:
  270. # Build params for DoclingLoader
  271. params = self.kwargs.get("DOCLING_PARAMS", {})
  272. if not isinstance(params, dict):
  273. try:
  274. params = json.loads(params)
  275. except json.JSONDecodeError:
  276. log.error("Invalid DOCLING_PARAMS format, expected JSON object")
  277. params = {}
  278. loader = DoclingLoader(
  279. url=self.kwargs.get("DOCLING_SERVER_URL"),
  280. file_path=file_path,
  281. mime_type=file_content_type,
  282. params=params,
  283. )
  284. elif (
  285. self.engine == "document_intelligence"
  286. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  287. and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
  288. and (
  289. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  290. or file_content_type
  291. in [
  292. "application/vnd.ms-excel",
  293. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  294. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  295. "application/vnd.ms-powerpoint",
  296. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  297. ]
  298. )
  299. ):
  300. loader = AzureAIDocumentIntelligenceLoader(
  301. file_path=file_path,
  302. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  303. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  304. )
  305. elif (
  306. self.engine == "mistral_ocr"
  307. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  308. and file_ext
  309. in ["pdf"] # Mistral OCR currently only supports PDF and images
  310. ):
  311. loader = MistralLoader(
  312. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  313. )
  314. elif (
  315. self.engine == "external"
  316. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  317. and file_ext
  318. in ["pdf"] # Mistral OCR currently only supports PDF and images
  319. ):
  320. loader = MistralLoader(
  321. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  322. )
  323. else:
  324. if file_ext == "pdf":
  325. loader = PyPDFLoader(
  326. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  327. )
  328. elif file_ext == "csv":
  329. loader = CSVLoader(file_path, autodetect_encoding=True)
  330. elif file_ext == "rst":
  331. loader = UnstructuredRSTLoader(file_path, mode="elements")
  332. elif file_ext == "xml":
  333. loader = UnstructuredXMLLoader(file_path)
  334. elif file_ext in ["htm", "html"]:
  335. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  336. elif file_ext == "md":
  337. loader = TextLoader(file_path, autodetect_encoding=True)
  338. elif file_content_type == "application/epub+zip":
  339. loader = UnstructuredEPubLoader(file_path)
  340. elif (
  341. file_content_type
  342. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  343. or file_ext == "docx"
  344. ):
  345. loader = Docx2txtLoader(file_path)
  346. elif file_content_type in [
  347. "application/vnd.ms-excel",
  348. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  349. ] or file_ext in ["xls", "xlsx"]:
  350. loader = UnstructuredExcelLoader(file_path)
  351. elif file_content_type in [
  352. "application/vnd.ms-powerpoint",
  353. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  354. ] or file_ext in ["ppt", "pptx"]:
  355. loader = UnstructuredPowerPointLoader(file_path)
  356. elif file_ext == "msg":
  357. loader = OutlookMessageLoader(file_path)
  358. elif file_ext == "odt":
  359. loader = UnstructuredODTLoader(file_path)
  360. elif self._is_text_file(file_ext, file_content_type):
  361. loader = TextLoader(file_path, autodetect_encoding=True)
  362. else:
  363. loader = TextLoader(file_path, autodetect_encoding=True)
  364. return loader