main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  25. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  26. log = logging.getLogger(__name__)
  27. log.setLevel(SRC_LOG_LEVELS["RAG"])
  28. known_source_ext = [
  29. "go",
  30. "py",
  31. "java",
  32. "sh",
  33. "bat",
  34. "ps1",
  35. "cmd",
  36. "js",
  37. "ts",
  38. "css",
  39. "cpp",
  40. "hpp",
  41. "h",
  42. "c",
  43. "cs",
  44. "sql",
  45. "log",
  46. "ini",
  47. "pl",
  48. "pm",
  49. "r",
  50. "dart",
  51. "dockerfile",
  52. "env",
  53. "php",
  54. "hs",
  55. "hsc",
  56. "lua",
  57. "nginxconf",
  58. "conf",
  59. "m",
  60. "mm",
  61. "plsql",
  62. "perl",
  63. "rb",
  64. "rs",
  65. "db2",
  66. "scala",
  67. "bash",
  68. "swift",
  69. "vue",
  70. "svelte",
  71. "msg",
  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 = {
  126. "image_export_mode": "placeholder",
  127. "table_mode": "accurate",
  128. }
  129. if self.params:
  130. if self.params.get("do_picture_classification"):
  131. params["do_picture_classification"] = self.params.get(
  132. "do_picture_classification"
  133. )
  134. if self.params.get("ocr_engine") and self.params.get("ocr_lang"):
  135. params["ocr_engine"] = self.params.get("ocr_engine")
  136. params["ocr_lang"] = [
  137. lang.strip()
  138. for lang in self.params.get("ocr_lang").split(",")
  139. if lang.strip()
  140. ]
  141. endpoint = f"{self.url}/v1alpha/convert/file"
  142. r = requests.post(endpoint, files=files, data=params)
  143. if r.ok:
  144. result = r.json()
  145. document_data = result.get("document", {})
  146. text = document_data.get("md_content", "<No text content found>")
  147. metadata = {"Content-Type": self.mime_type} if self.mime_type else {}
  148. log.debug("Docling extracted text: %s", text)
  149. return [Document(page_content=text, metadata=metadata)]
  150. else:
  151. error_msg = f"Error calling Docling API: {r.reason}"
  152. if r.text:
  153. try:
  154. error_data = r.json()
  155. if "detail" in error_data:
  156. error_msg += f" - {error_data['detail']}"
  157. except Exception:
  158. error_msg += f" - {r.text}"
  159. raise Exception(f"Error calling Docling: {error_msg}")
  160. class Loader:
  161. def __init__(self, engine: str = "", **kwargs):
  162. self.engine = engine
  163. self.kwargs = kwargs
  164. def load(
  165. self, filename: str, file_content_type: str, file_path: str
  166. ) -> list[Document]:
  167. loader = self._get_loader(filename, file_content_type, file_path)
  168. docs = loader.load()
  169. return [
  170. Document(
  171. page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata
  172. )
  173. for doc in docs
  174. ]
  175. def _is_text_file(self, file_ext: str, file_content_type: str) -> bool:
  176. return file_ext in known_source_ext or (
  177. file_content_type and file_content_type.find("text/") >= 0
  178. )
  179. def _get_loader(self, filename: str, file_content_type: str, file_path: str):
  180. file_ext = filename.split(".")[-1].lower()
  181. if (
  182. self.engine == "external"
  183. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL")
  184. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY")
  185. ):
  186. loader = ExternalDocumentLoader(
  187. file_path=file_path,
  188. url=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL"),
  189. api_key=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY"),
  190. mime_type=file_content_type,
  191. )
  192. if self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
  193. if self._is_text_file(file_ext, file_content_type):
  194. loader = TextLoader(file_path, autodetect_encoding=True)
  195. else:
  196. loader = TikaLoader(
  197. url=self.kwargs.get("TIKA_SERVER_URL"),
  198. file_path=file_path,
  199. mime_type=file_content_type,
  200. extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES"),
  201. )
  202. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  203. if self._is_text_file(file_ext, file_content_type):
  204. loader = TextLoader(file_path, autodetect_encoding=True)
  205. else:
  206. loader = DoclingLoader(
  207. url=self.kwargs.get("DOCLING_SERVER_URL"),
  208. file_path=file_path,
  209. mime_type=file_content_type,
  210. params={
  211. "ocr_engine": self.kwargs.get("DOCLING_OCR_ENGINE"),
  212. "ocr_lang": self.kwargs.get("DOCLING_OCR_LANG"),
  213. "do_picture_classification": self.kwargs.get(
  214. "DOCLING_DO_PICTURE_DESCRIPTION"
  215. ),
  216. },
  217. )
  218. elif (
  219. self.engine == "document_intelligence"
  220. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  221. and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
  222. and (
  223. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  224. or file_content_type
  225. in [
  226. "application/vnd.ms-excel",
  227. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  228. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  229. "application/vnd.ms-powerpoint",
  230. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  231. ]
  232. )
  233. ):
  234. loader = AzureAIDocumentIntelligenceLoader(
  235. file_path=file_path,
  236. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  237. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  238. )
  239. elif (
  240. self.engine == "mistral_ocr"
  241. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  242. and file_ext
  243. in ["pdf"] # Mistral OCR currently only supports PDF and images
  244. ):
  245. loader = MistralLoader(
  246. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  247. )
  248. elif (
  249. self.engine == "external"
  250. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  251. and file_ext
  252. in ["pdf"] # Mistral OCR currently only supports PDF and images
  253. ):
  254. loader = MistralLoader(
  255. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  256. )
  257. else:
  258. if file_ext == "pdf":
  259. loader = PyPDFLoader(
  260. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  261. )
  262. elif file_ext == "csv":
  263. loader = CSVLoader(file_path, autodetect_encoding=True)
  264. elif file_ext == "rst":
  265. loader = UnstructuredRSTLoader(file_path, mode="elements")
  266. elif file_ext == "xml":
  267. loader = UnstructuredXMLLoader(file_path)
  268. elif file_ext in ["htm", "html"]:
  269. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  270. elif file_ext == "md":
  271. loader = TextLoader(file_path, autodetect_encoding=True)
  272. elif file_content_type == "application/epub+zip":
  273. loader = UnstructuredEPubLoader(file_path)
  274. elif (
  275. file_content_type
  276. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  277. or file_ext == "docx"
  278. ):
  279. loader = Docx2txtLoader(file_path)
  280. elif file_content_type in [
  281. "application/vnd.ms-excel",
  282. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  283. ] or file_ext in ["xls", "xlsx"]:
  284. loader = UnstructuredExcelLoader(file_path)
  285. elif file_content_type in [
  286. "application/vnd.ms-powerpoint",
  287. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  288. ] or file_ext in ["ppt", "pptx"]:
  289. loader = UnstructuredPowerPointLoader(file_path)
  290. elif file_ext == "msg":
  291. loader = OutlookMessageLoader(file_path)
  292. elif self._is_text_file(file_ext, file_content_type):
  293. loader = TextLoader(file_path, autodetect_encoding=True)
  294. else:
  295. loader = TextLoader(file_path, autodetect_encoding=True)
  296. return loader