main.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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):
  82. self.url = url
  83. self.file_path = file_path
  84. self.mime_type = mime_type
  85. def load(self) -> list[Document]:
  86. with open(self.file_path, "rb") as f:
  87. data = f.read()
  88. if self.mime_type is not None:
  89. headers = {"Content-Type": self.mime_type}
  90. else:
  91. headers = {}
  92. if self.kwargs.get("PDF_EXTRACT_IMAGES") == True:
  93. headers["X-Tika-PDFextractInlineImages"] = "true"
  94. endpoint = self.url
  95. if not endpoint.endswith("/"):
  96. endpoint += "/"
  97. endpoint += "tika/text"
  98. r = requests.put(endpoint, data=data, headers=headers)
  99. if r.ok:
  100. raw_metadata = r.json()
  101. text = raw_metadata.get("X-TIKA:content", "<No text content found>").strip()
  102. if "Content-Type" in raw_metadata:
  103. headers["Content-Type"] = raw_metadata["Content-Type"]
  104. log.debug("Tika extracted text: %s", text)
  105. return [Document(page_content=text, metadata=headers)]
  106. else:
  107. raise Exception(f"Error calling Tika: {r.reason}")
  108. class DoclingLoader:
  109. def __init__(
  110. self, url, file_path=None, mime_type=None, ocr_engine=None, ocr_lang=None
  111. ):
  112. self.url = url.rstrip("/")
  113. self.file_path = file_path
  114. self.mime_type = mime_type
  115. self.ocr_engine = ocr_engine
  116. self.ocr_lang = ocr_lang
  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.ocr_engine and self.ocr_lang:
  131. params["ocr_engine"] = self.ocr_engine
  132. params["ocr_lang"] = [
  133. lang.strip() for lang in self.ocr_lang.split(",") if lang.strip()
  134. ]
  135. endpoint = f"{self.url}/v1alpha/convert/file"
  136. r = requests.post(endpoint, files=files, data=params)
  137. if r.ok:
  138. result = r.json()
  139. document_data = result.get("document", {})
  140. text = document_data.get("md_content", "<No text content found>")
  141. metadata = {"Content-Type": self.mime_type} if self.mime_type else {}
  142. log.debug("Docling extracted text: %s", text)
  143. return [Document(page_content=text, metadata=metadata)]
  144. else:
  145. error_msg = f"Error calling Docling API: {r.reason}"
  146. if r.text:
  147. try:
  148. error_data = r.json()
  149. if "detail" in error_data:
  150. error_msg += f" - {error_data['detail']}"
  151. except Exception:
  152. error_msg += f" - {r.text}"
  153. raise Exception(f"Error calling Docling: {error_msg}")
  154. class Loader:
  155. def __init__(self, engine: str = "", **kwargs):
  156. self.engine = engine
  157. self.kwargs = kwargs
  158. def load(
  159. self, filename: str, file_content_type: str, file_path: str
  160. ) -> list[Document]:
  161. loader = self._get_loader(filename, file_content_type, file_path)
  162. docs = loader.load()
  163. return [
  164. Document(
  165. page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata
  166. )
  167. for doc in docs
  168. ]
  169. def _is_text_file(self, file_ext: str, file_content_type: str) -> bool:
  170. return file_ext in known_source_ext or (
  171. file_content_type and file_content_type.find("text/") >= 0
  172. )
  173. def _get_loader(self, filename: str, file_content_type: str, file_path: str):
  174. file_ext = filename.split(".")[-1].lower()
  175. if self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
  176. if self._is_text_file(file_ext, file_content_type):
  177. loader = TextLoader(file_path, autodetect_encoding=True)
  178. else:
  179. loader = TikaLoader(
  180. url=self.kwargs.get("TIKA_SERVER_URL"),
  181. file_path=file_path,
  182. mime_type=file_content_type,
  183. )
  184. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  185. if self._is_text_file(file_ext, file_content_type):
  186. loader = TextLoader(file_path, autodetect_encoding=True)
  187. else:
  188. loader = DoclingLoader(
  189. url=self.kwargs.get("DOCLING_SERVER_URL"),
  190. file_path=file_path,
  191. mime_type=file_content_type,
  192. ocr_engine=self.kwargs.get("DOCLING_OCR_ENGINE"),
  193. ocr_lang=self.kwargs.get("DOCLING_OCR_LANG"),
  194. )
  195. elif (
  196. self.engine == "document_intelligence"
  197. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  198. and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
  199. and (
  200. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  201. or file_content_type
  202. in [
  203. "application/vnd.ms-excel",
  204. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  205. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  206. "application/vnd.ms-powerpoint",
  207. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  208. ]
  209. )
  210. ):
  211. loader = AzureAIDocumentIntelligenceLoader(
  212. file_path=file_path,
  213. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  214. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  215. )
  216. elif (
  217. self.engine == "mistral_ocr"
  218. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  219. and file_ext
  220. in ["pdf"] # Mistral OCR currently only supports PDF and images
  221. ):
  222. loader = MistralLoader(
  223. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  224. )
  225. else:
  226. if file_ext == "pdf":
  227. loader = PyPDFLoader(
  228. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  229. )
  230. elif file_ext == "csv":
  231. loader = CSVLoader(file_path, autodetect_encoding=True)
  232. elif file_ext == "rst":
  233. loader = UnstructuredRSTLoader(file_path, mode="elements")
  234. elif file_ext == "xml":
  235. loader = UnstructuredXMLLoader(file_path)
  236. elif file_ext in ["htm", "html"]:
  237. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  238. elif file_ext == "md":
  239. loader = TextLoader(file_path, autodetect_encoding=True)
  240. elif file_content_type == "application/epub+zip":
  241. loader = UnstructuredEPubLoader(file_path)
  242. elif (
  243. file_content_type
  244. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  245. or file_ext == "docx"
  246. ):
  247. loader = Docx2txtLoader(file_path)
  248. elif file_content_type in [
  249. "application/vnd.ms-excel",
  250. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  251. ] or file_ext in ["xls", "xlsx"]:
  252. loader = UnstructuredExcelLoader(file_path)
  253. elif file_content_type in [
  254. "application/vnd.ms-powerpoint",
  255. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  256. ] or file_ext in ["ppt", "pptx"]:
  257. loader = UnstructuredPowerPointLoader(file_path)
  258. elif file_ext == "msg":
  259. loader = OutlookMessageLoader(file_path)
  260. elif self._is_text_file(file_ext, file_content_type):
  261. loader = TextLoader(file_path, autodetect_encoding=True)
  262. else:
  263. loader = TextLoader(file_path, autodetect_encoding=True)
  264. return loader