main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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.mistral import MistralLoader
  23. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  24. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  25. log = logging.getLogger(__name__)
  26. log.setLevel(SRC_LOG_LEVELS["RAG"])
  27. known_source_ext = [
  28. "go",
  29. "py",
  30. "java",
  31. "sh",
  32. "bat",
  33. "ps1",
  34. "cmd",
  35. "js",
  36. "ts",
  37. "css",
  38. "cpp",
  39. "hpp",
  40. "h",
  41. "c",
  42. "cs",
  43. "sql",
  44. "log",
  45. "ini",
  46. "pl",
  47. "pm",
  48. "r",
  49. "dart",
  50. "dockerfile",
  51. "env",
  52. "php",
  53. "hs",
  54. "hsc",
  55. "lua",
  56. "nginxconf",
  57. "conf",
  58. "m",
  59. "mm",
  60. "plsql",
  61. "perl",
  62. "rb",
  63. "rs",
  64. "db2",
  65. "scala",
  66. "bash",
  67. "swift",
  68. "vue",
  69. "svelte",
  70. "msg",
  71. "ex",
  72. "exs",
  73. "erl",
  74. "tsx",
  75. "jsx",
  76. "hs",
  77. "lhs",
  78. "json",
  79. ]
  80. class TikaLoader:
  81. def __init__(self, url, file_path, mime_type=None, extract_images=None):
  82. self.url = url
  83. self.file_path = file_path
  84. self.mime_type = mime_type
  85. self.extract_images = extract_images
  86. def load(self) -> list[Document]:
  87. with open(self.file_path, "rb") as f:
  88. data = f.read()
  89. if self.mime_type is not None:
  90. headers = {"Content-Type": self.mime_type}
  91. else:
  92. headers = {}
  93. if self.extract_images == True:
  94. headers["X-Tika-PDFextractInlineImages"] = "true"
  95. endpoint = self.url
  96. if not endpoint.endswith("/"):
  97. endpoint += "/"
  98. endpoint += "tika/text"
  99. r = requests.put(endpoint, data=data, headers=headers)
  100. if r.ok:
  101. raw_metadata = r.json()
  102. text = raw_metadata.get("X-TIKA:content", "<No text content found>").strip()
  103. if "Content-Type" in raw_metadata:
  104. headers["Content-Type"] = raw_metadata["Content-Type"]
  105. log.debug("Tika extracted text: %s", text)
  106. return [Document(page_content=text, metadata=headers)]
  107. else:
  108. raise Exception(f"Error calling Tika: {r.reason}")
  109. class DoclingLoader:
  110. def __init__(self, url, file_path=None, mime_type=None, params=None):
  111. self.url = url.rstrip("/")
  112. self.file_path = file_path
  113. self.mime_type = mime_type
  114. self.params = params or {}
  115. def load(self) -> list[Document]:
  116. with open(self.file_path, "rb") as f:
  117. files = {
  118. "files": (
  119. self.file_path,
  120. f,
  121. self.mime_type or "application/octet-stream",
  122. )
  123. }
  124. params = {
  125. "image_export_mode": "placeholder",
  126. "table_mode": "accurate",
  127. }
  128. if self.params:
  129. if self.params.get("do_picture_classification"):
  130. params["do_picture_classification"] = self.params.get(
  131. "do_picture_classification"
  132. )
  133. if self.params.get("ocr_engine") and self.params.get("ocr_lang"):
  134. params["ocr_engine"] = self.params.get("ocr_engine")
  135. params["ocr_lang"] = [
  136. lang.strip()
  137. for lang in self.params.get("ocr_lang").split(",")
  138. if lang.strip()
  139. ]
  140. endpoint = f"{self.url}/v1alpha/convert/file"
  141. r = requests.post(endpoint, files=files, data=params)
  142. if r.ok:
  143. result = r.json()
  144. document_data = result.get("document", {})
  145. text = document_data.get("md_content", "<No text content found>")
  146. metadata = {"Content-Type": self.mime_type} if self.mime_type else {}
  147. log.debug("Docling extracted text: %s", text)
  148. return [Document(page_content=text, metadata=metadata)]
  149. else:
  150. error_msg = f"Error calling Docling API: {r.reason}"
  151. if r.text:
  152. try:
  153. error_data = r.json()
  154. if "detail" in error_data:
  155. error_msg += f" - {error_data['detail']}"
  156. except Exception:
  157. error_msg += f" - {r.text}"
  158. raise Exception(f"Error calling Docling: {error_msg}")
  159. class Loader:
  160. def __init__(self, engine: str = "", **kwargs):
  161. self.engine = engine
  162. self.kwargs = kwargs
  163. def load(
  164. self, filename: str, file_content_type: str, file_path: str
  165. ) -> list[Document]:
  166. loader = self._get_loader(filename, file_content_type, file_path)
  167. docs = loader.load()
  168. return [
  169. Document(
  170. page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata
  171. )
  172. for doc in docs
  173. ]
  174. def _is_text_file(self, file_ext: str, file_content_type: str) -> bool:
  175. return file_ext in known_source_ext or (
  176. file_content_type and file_content_type.find("text/") >= 0
  177. )
  178. def _get_loader(self, filename: str, file_content_type: str, file_path: str):
  179. file_ext = filename.split(".")[-1].lower()
  180. if self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
  181. if self._is_text_file(file_ext, file_content_type):
  182. loader = TextLoader(file_path, autodetect_encoding=True)
  183. else:
  184. loader = TikaLoader(
  185. url=self.kwargs.get("TIKA_SERVER_URL"),
  186. file_path=file_path,
  187. mime_type=file_content_type,
  188. extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES"),
  189. )
  190. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  191. if self._is_text_file(file_ext, file_content_type):
  192. loader = TextLoader(file_path, autodetect_encoding=True)
  193. else:
  194. loader = DoclingLoader(
  195. url=self.kwargs.get("DOCLING_SERVER_URL"),
  196. file_path=file_path,
  197. mime_type=file_content_type,
  198. params={
  199. "ocr_engine": self.kwargs.get("DOCLING_OCR_ENGINE"),
  200. "ocr_lang": self.kwargs.get("DOCLING_OCR_LANG"),
  201. "do_picture_classification": self.kwargs.get(
  202. "DOCLING_DO_PICTURE_DESCRIPTION"
  203. ),
  204. },
  205. )
  206. elif (
  207. self.engine == "document_intelligence"
  208. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  209. and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
  210. and (
  211. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  212. or file_content_type
  213. in [
  214. "application/vnd.ms-excel",
  215. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  216. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  217. "application/vnd.ms-powerpoint",
  218. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  219. ]
  220. )
  221. ):
  222. loader = AzureAIDocumentIntelligenceLoader(
  223. file_path=file_path,
  224. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  225. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  226. )
  227. elif (
  228. self.engine == "mistral_ocr"
  229. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  230. and file_ext
  231. in ["pdf"] # Mistral OCR currently only supports PDF and images
  232. ):
  233. loader = MistralLoader(
  234. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  235. )
  236. else:
  237. if file_ext == "pdf":
  238. loader = PyPDFLoader(
  239. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  240. )
  241. elif file_ext == "csv":
  242. loader = CSVLoader(file_path, autodetect_encoding=True)
  243. elif file_ext == "rst":
  244. loader = UnstructuredRSTLoader(file_path, mode="elements")
  245. elif file_ext == "xml":
  246. loader = UnstructuredXMLLoader(file_path)
  247. elif file_ext in ["htm", "html"]:
  248. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  249. elif file_ext == "md":
  250. loader = TextLoader(file_path, autodetect_encoding=True)
  251. elif file_content_type == "application/epub+zip":
  252. loader = UnstructuredEPubLoader(file_path)
  253. elif (
  254. file_content_type
  255. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  256. or file_ext == "docx"
  257. ):
  258. loader = Docx2txtLoader(file_path)
  259. elif file_content_type in [
  260. "application/vnd.ms-excel",
  261. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  262. ] or file_ext in ["xls", "xlsx"]:
  263. loader = UnstructuredExcelLoader(file_path)
  264. elif file_content_type in [
  265. "application/vnd.ms-powerpoint",
  266. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  267. ] or file_ext in ["ppt", "pptx"]:
  268. loader = UnstructuredPowerPointLoader(file_path)
  269. elif file_ext == "msg":
  270. loader = OutlookMessageLoader(file_path)
  271. elif self._is_text_file(file_ext, file_content_type):
  272. loader = TextLoader(file_path, autodetect_encoding=True)
  273. else:
  274. loader = TextLoader(file_path, autodetect_encoding=True)
  275. return loader