main.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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.datalab_marker_loader import DatalabMarkerLoader
  23. from open_webui.retrieval.loaders.external_document import ExternalDocumentLoader
  24. from open_webui.retrieval.loaders.mistral import MistralLoader
  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. "msg",
  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 = {
  127. "image_export_mode": "placeholder",
  128. "table_mode": "accurate",
  129. }
  130. if self.params:
  131. if self.params.get("do_picture_classification"):
  132. params["do_picture_classification"] = self.params.get(
  133. "do_picture_classification"
  134. )
  135. if self.params.get("ocr_engine") and self.params.get("ocr_lang"):
  136. params["ocr_engine"] = self.params.get("ocr_engine")
  137. params["ocr_lang"] = [
  138. lang.strip()
  139. for lang in self.params.get("ocr_lang").split(",")
  140. if lang.strip()
  141. ]
  142. endpoint = f"{self.url}/v1alpha/convert/file"
  143. r = requests.post(endpoint, files=files, data=params)
  144. if r.ok:
  145. result = r.json()
  146. document_data = result.get("document", {})
  147. text = document_data.get("md_content", "<No text content found>")
  148. metadata = {"Content-Type": self.mime_type} if self.mime_type else {}
  149. log.debug("Docling extracted text: %s", text)
  150. return [Document(page_content=text, metadata=metadata)]
  151. else:
  152. error_msg = f"Error calling Docling API: {r.reason}"
  153. if r.text:
  154. try:
  155. error_data = r.json()
  156. if "detail" in error_data:
  157. error_msg += f" - {error_data['detail']}"
  158. except Exception:
  159. error_msg += f" - {r.text}"
  160. raise Exception(f"Error calling Docling: {error_msg}")
  161. class Loader:
  162. def __init__(self, engine: str = "", **kwargs):
  163. self.engine = engine
  164. self.kwargs = kwargs
  165. def load(
  166. self, filename: str, file_content_type: str, file_path: str
  167. ) -> list[Document]:
  168. loader = self._get_loader(filename, file_content_type, file_path)
  169. docs = loader.load()
  170. return [
  171. Document(
  172. page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata
  173. )
  174. for doc in docs
  175. ]
  176. def _is_text_file(self, file_ext: str, file_content_type: str) -> bool:
  177. return file_ext in known_source_ext or (
  178. file_content_type and file_content_type.find("text/") >= 0
  179. )
  180. def _get_loader(self, filename: str, file_content_type: str, file_path: str):
  181. file_ext = filename.split(".")[-1].lower()
  182. if (
  183. self.engine == "external"
  184. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL")
  185. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY")
  186. ):
  187. loader = ExternalDocumentLoader(
  188. file_path=file_path,
  189. url=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL"),
  190. api_key=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY"),
  191. mime_type=file_content_type,
  192. )
  193. elif self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
  194. if self._is_text_file(file_ext, file_content_type):
  195. loader = TextLoader(file_path, autodetect_encoding=True)
  196. else:
  197. loader = TikaLoader(
  198. url=self.kwargs.get("TIKA_SERVER_URL"),
  199. file_path=file_path,
  200. mime_type=file_content_type,
  201. extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES"),
  202. )
  203. elif (
  204. self.engine == "datalab_marker"
  205. and self.kwargs.get("DATALAB_MARKER_API_KEY")
  206. and file_ext in ["pdf", "xls", "xlsx", "ods", "doc", "docx", "odt", "ppt", "pptx", "odp", "html", "epub", "png", "jpeg", "jpg", "webp", "gif", "tiff"]
  207. ):
  208. loader = DatalabMarkerLoader(
  209. file_path=file_path,
  210. api_key=self.kwargs["DATALAB_MARKER_API_KEY"],
  211. langs=self.kwargs.get("DATALAB_MARKER_LANGS"),
  212. use_llm=self.kwargs.get("DATALAB_MARKER_USE_LLM", False),
  213. skip_cache=self.kwargs.get("DATALAB_MARKER_SKIP_CACHE", False),
  214. force_ocr=self.kwargs.get("DATALAB_MARKER_FORCE_OCR", False),
  215. paginate=self.kwargs.get("DATALAB_MARKER_PAGINATE", False),
  216. strip_existing_ocr=self.kwargs.get("DATALAB_MARKER_STRIP_EXISTING_OCR", False),
  217. disable_image_extraction=self.kwargs.get("DATALAB_MARKER_DISABLE_IMAGE_EXTRACTION", False),
  218. output_format=self.kwargs.get("DATALAB_MARKER_OUTPUT_FORMAT", "markdown")
  219. )
  220. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  221. if self._is_text_file(file_ext, file_content_type):
  222. loader = TextLoader(file_path, autodetect_encoding=True)
  223. else:
  224. loader = DoclingLoader(
  225. url=self.kwargs.get("DOCLING_SERVER_URL"),
  226. file_path=file_path,
  227. mime_type=file_content_type,
  228. params={
  229. "ocr_engine": self.kwargs.get("DOCLING_OCR_ENGINE"),
  230. "ocr_lang": self.kwargs.get("DOCLING_OCR_LANG"),
  231. "do_picture_classification": self.kwargs.get(
  232. "DOCLING_DO_PICTURE_DESCRIPTION"
  233. ),
  234. },
  235. )
  236. elif (
  237. self.engine == "document_intelligence"
  238. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  239. and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
  240. and (
  241. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  242. or file_content_type
  243. in [
  244. "application/vnd.ms-excel",
  245. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  246. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  247. "application/vnd.ms-powerpoint",
  248. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  249. ]
  250. )
  251. ):
  252. loader = AzureAIDocumentIntelligenceLoader(
  253. file_path=file_path,
  254. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  255. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  256. )
  257. elif (
  258. self.engine == "mistral_ocr"
  259. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  260. and file_ext
  261. in ["pdf"] # Mistral OCR currently only supports PDF and images
  262. ):
  263. loader = MistralLoader(
  264. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  265. )
  266. elif (
  267. self.engine == "external"
  268. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  269. and file_ext
  270. in ["pdf"] # Mistral OCR currently only supports PDF and images
  271. ):
  272. loader = MistralLoader(
  273. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  274. )
  275. else:
  276. if file_ext == "pdf":
  277. loader = PyPDFLoader(
  278. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  279. )
  280. elif file_ext == "csv":
  281. loader = CSVLoader(file_path, autodetect_encoding=True)
  282. elif file_ext == "rst":
  283. loader = UnstructuredRSTLoader(file_path, mode="elements")
  284. elif file_ext == "xml":
  285. loader = UnstructuredXMLLoader(file_path)
  286. elif file_ext in ["htm", "html"]:
  287. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  288. elif file_ext == "md":
  289. loader = TextLoader(file_path, autodetect_encoding=True)
  290. elif file_content_type == "application/epub+zip":
  291. loader = UnstructuredEPubLoader(file_path)
  292. elif (
  293. file_content_type
  294. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  295. or file_ext == "docx"
  296. ):
  297. loader = Docx2txtLoader(file_path)
  298. elif file_content_type in [
  299. "application/vnd.ms-excel",
  300. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  301. ] or file_ext in ["xls", "xlsx"]:
  302. loader = UnstructuredExcelLoader(file_path)
  303. elif file_content_type in [
  304. "application/vnd.ms-powerpoint",
  305. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  306. ] or file_ext in ["ppt", "pptx"]:
  307. loader = UnstructuredPowerPointLoader(file_path)
  308. elif file_ext == "msg":
  309. loader = OutlookMessageLoader(file_path)
  310. elif self._is_text_file(file_ext, file_content_type):
  311. loader = TextLoader(file_path, autodetect_encoding=True)
  312. else:
  313. loader = TextLoader(file_path, autodetect_encoding=True)
  314. return loader