main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 and file_content_type.find("text/") >= 0
  191. )
  192. def _get_loader(self, filename: str, file_content_type: str, file_path: str):
  193. file_ext = filename.split(".")[-1].lower()
  194. if (
  195. self.engine == "external"
  196. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL")
  197. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY")
  198. ):
  199. loader = ExternalDocumentLoader(
  200. file_path=file_path,
  201. url=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL"),
  202. api_key=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY"),
  203. mime_type=file_content_type,
  204. )
  205. elif self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
  206. if self._is_text_file(file_ext, file_content_type):
  207. loader = TextLoader(file_path, autodetect_encoding=True)
  208. else:
  209. loader = TikaLoader(
  210. url=self.kwargs.get("TIKA_SERVER_URL"),
  211. file_path=file_path,
  212. mime_type=file_content_type,
  213. extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES"),
  214. )
  215. elif (
  216. self.engine == "datalab_marker"
  217. and self.kwargs.get("DATALAB_MARKER_API_KEY")
  218. and file_ext
  219. in [
  220. "pdf",
  221. "xls",
  222. "xlsx",
  223. "ods",
  224. "doc",
  225. "docx",
  226. "odt",
  227. "ppt",
  228. "pptx",
  229. "odp",
  230. "html",
  231. "epub",
  232. "png",
  233. "jpeg",
  234. "jpg",
  235. "webp",
  236. "gif",
  237. "tiff",
  238. ]
  239. ):
  240. loader = DatalabMarkerLoader(
  241. file_path=file_path,
  242. api_key=self.kwargs["DATALAB_MARKER_API_KEY"],
  243. langs=self.kwargs.get("DATALAB_MARKER_LANGS"),
  244. use_llm=self.kwargs.get("DATALAB_MARKER_USE_LLM", False),
  245. skip_cache=self.kwargs.get("DATALAB_MARKER_SKIP_CACHE", False),
  246. force_ocr=self.kwargs.get("DATALAB_MARKER_FORCE_OCR", False),
  247. paginate=self.kwargs.get("DATALAB_MARKER_PAGINATE", False),
  248. strip_existing_ocr=self.kwargs.get(
  249. "DATALAB_MARKER_STRIP_EXISTING_OCR", False
  250. ),
  251. disable_image_extraction=self.kwargs.get(
  252. "DATALAB_MARKER_DISABLE_IMAGE_EXTRACTION", False
  253. ),
  254. output_format=self.kwargs.get(
  255. "DATALAB_MARKER_OUTPUT_FORMAT", "markdown"
  256. ),
  257. )
  258. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  259. if self._is_text_file(file_ext, file_content_type):
  260. loader = TextLoader(file_path, autodetect_encoding=True)
  261. else:
  262. # Build params for DoclingLoader
  263. params = self.kwargs.get("DOCLING_PARAMS", {})
  264. if not isinstance(params, dict):
  265. try:
  266. params = json.loads(params)
  267. except json.JSONDecodeError:
  268. log.error("Invalid DOCLING_PARAMS format, expected JSON object")
  269. params = {}
  270. loader = DoclingLoader(
  271. url=self.kwargs.get("DOCLING_SERVER_URL"),
  272. file_path=file_path,
  273. mime_type=file_content_type,
  274. params=params,
  275. )
  276. elif (
  277. self.engine == "document_intelligence"
  278. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  279. and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
  280. and (
  281. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  282. or file_content_type
  283. in [
  284. "application/vnd.ms-excel",
  285. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  286. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  287. "application/vnd.ms-powerpoint",
  288. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  289. ]
  290. )
  291. ):
  292. loader = AzureAIDocumentIntelligenceLoader(
  293. file_path=file_path,
  294. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  295. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  296. )
  297. elif (
  298. self.engine == "mistral_ocr"
  299. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  300. and file_ext
  301. in ["pdf"] # Mistral OCR currently only supports PDF and images
  302. ):
  303. loader = MistralLoader(
  304. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  305. )
  306. elif (
  307. self.engine == "external"
  308. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  309. and file_ext
  310. in ["pdf"] # Mistral OCR currently only supports PDF and images
  311. ):
  312. loader = MistralLoader(
  313. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  314. )
  315. else:
  316. if file_ext == "pdf":
  317. loader = PyPDFLoader(
  318. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  319. )
  320. elif file_ext == "csv":
  321. loader = CSVLoader(file_path, autodetect_encoding=True)
  322. elif file_ext == "rst":
  323. loader = UnstructuredRSTLoader(file_path, mode="elements")
  324. elif file_ext == "xml":
  325. loader = UnstructuredXMLLoader(file_path)
  326. elif file_ext in ["htm", "html"]:
  327. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  328. elif file_ext == "md":
  329. loader = TextLoader(file_path, autodetect_encoding=True)
  330. elif file_content_type == "application/epub+zip":
  331. loader = UnstructuredEPubLoader(file_path)
  332. elif (
  333. file_content_type
  334. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  335. or file_ext == "docx"
  336. ):
  337. loader = Docx2txtLoader(file_path)
  338. elif file_content_type in [
  339. "application/vnd.ms-excel",
  340. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  341. ] or file_ext in ["xls", "xlsx"]:
  342. loader = UnstructuredExcelLoader(file_path)
  343. elif file_content_type in [
  344. "application/vnd.ms-powerpoint",
  345. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  346. ] or file_ext in ["ppt", "pptx"]:
  347. loader = UnstructuredPowerPointLoader(file_path)
  348. elif file_ext == "msg":
  349. loader = OutlookMessageLoader(file_path)
  350. elif file_ext == "odt":
  351. loader = UnstructuredODTLoader(file_path)
  352. elif self._is_text_file(file_ext, file_content_type):
  353. loader = TextLoader(file_path, autodetect_encoding=True)
  354. else:
  355. loader = TextLoader(file_path, autodetect_encoding=True)
  356. return loader