main.py 13 KB

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