main.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. "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
  207. in [
  208. "pdf",
  209. "xls",
  210. "xlsx",
  211. "ods",
  212. "doc",
  213. "docx",
  214. "odt",
  215. "ppt",
  216. "pptx",
  217. "odp",
  218. "html",
  219. "epub",
  220. "png",
  221. "jpeg",
  222. "jpg",
  223. "webp",
  224. "gif",
  225. "tiff",
  226. ]
  227. ):
  228. loader = DatalabMarkerLoader(
  229. file_path=file_path,
  230. api_key=self.kwargs["DATALAB_MARKER_API_KEY"],
  231. langs=self.kwargs.get("DATALAB_MARKER_LANGS"),
  232. use_llm=self.kwargs.get("DATALAB_MARKER_USE_LLM", False),
  233. skip_cache=self.kwargs.get("DATALAB_MARKER_SKIP_CACHE", False),
  234. force_ocr=self.kwargs.get("DATALAB_MARKER_FORCE_OCR", False),
  235. paginate=self.kwargs.get("DATALAB_MARKER_PAGINATE", False),
  236. strip_existing_ocr=self.kwargs.get(
  237. "DATALAB_MARKER_STRIP_EXISTING_OCR", False
  238. ),
  239. disable_image_extraction=self.kwargs.get(
  240. "DATALAB_MARKER_DISABLE_IMAGE_EXTRACTION", False
  241. ),
  242. output_format=self.kwargs.get(
  243. "DATALAB_MARKER_OUTPUT_FORMAT", "markdown"
  244. ),
  245. )
  246. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  247. if self._is_text_file(file_ext, file_content_type):
  248. loader = TextLoader(file_path, autodetect_encoding=True)
  249. else:
  250. loader = DoclingLoader(
  251. url=self.kwargs.get("DOCLING_SERVER_URL"),
  252. file_path=file_path,
  253. mime_type=file_content_type,
  254. params={
  255. "ocr_engine": self.kwargs.get("DOCLING_OCR_ENGINE"),
  256. "ocr_lang": self.kwargs.get("DOCLING_OCR_LANG"),
  257. "do_picture_classification": self.kwargs.get(
  258. "DOCLING_DO_PICTURE_DESCRIPTION"
  259. ),
  260. },
  261. )
  262. elif (
  263. self.engine == "document_intelligence"
  264. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  265. and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
  266. and (
  267. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  268. or file_content_type
  269. in [
  270. "application/vnd.ms-excel",
  271. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  272. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  273. "application/vnd.ms-powerpoint",
  274. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  275. ]
  276. )
  277. ):
  278. loader = AzureAIDocumentIntelligenceLoader(
  279. file_path=file_path,
  280. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  281. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  282. )
  283. elif (
  284. self.engine == "mistral_ocr"
  285. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  286. and file_ext
  287. in ["pdf"] # Mistral OCR currently only supports PDF and images
  288. ):
  289. loader = MistralLoader(
  290. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  291. )
  292. elif (
  293. self.engine == "external"
  294. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  295. and file_ext
  296. in ["pdf"] # Mistral OCR currently only supports PDF and images
  297. ):
  298. loader = MistralLoader(
  299. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  300. )
  301. else:
  302. if file_ext == "pdf":
  303. loader = PyPDFLoader(
  304. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  305. )
  306. elif file_ext == "csv":
  307. loader = CSVLoader(file_path, autodetect_encoding=True)
  308. elif file_ext == "rst":
  309. loader = UnstructuredRSTLoader(file_path, mode="elements")
  310. elif file_ext == "xml":
  311. loader = UnstructuredXMLLoader(file_path)
  312. elif file_ext in ["htm", "html"]:
  313. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  314. elif file_ext == "md":
  315. loader = TextLoader(file_path, autodetect_encoding=True)
  316. elif file_content_type == "application/epub+zip":
  317. loader = UnstructuredEPubLoader(file_path)
  318. elif (
  319. file_content_type
  320. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  321. or file_ext == "docx"
  322. ):
  323. loader = Docx2txtLoader(file_path)
  324. elif file_content_type in [
  325. "application/vnd.ms-excel",
  326. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  327. ] or file_ext in ["xls", "xlsx"]:
  328. loader = UnstructuredExcelLoader(file_path)
  329. elif file_content_type in [
  330. "application/vnd.ms-powerpoint",
  331. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  332. ] or file_ext in ["ppt", "pptx"]:
  333. loader = UnstructuredPowerPointLoader(file_path)
  334. elif file_ext == "msg":
  335. loader = OutlookMessageLoader(file_path)
  336. elif self._is_text_file(file_ext, file_content_type):
  337. loader = TextLoader(file_path, autodetect_encoding=True)
  338. else:
  339. loader = TextLoader(file_path, autodetect_encoding=True)
  340. return loader