1
0

main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import requests
  2. import logging
  3. import ftfy
  4. import sys
  5. import json
  6. from azure.identity import DefaultAzureCredential
  7. from langchain_community.document_loaders import (
  8. AzureAIDocumentIntelligenceLoader,
  9. BSHTMLLoader,
  10. CSVLoader,
  11. Docx2txtLoader,
  12. OutlookMessageLoader,
  13. PyPDFLoader,
  14. TextLoader,
  15. UnstructuredEPubLoader,
  16. UnstructuredExcelLoader,
  17. UnstructuredODTLoader,
  18. UnstructuredPowerPointLoader,
  19. UnstructuredRSTLoader,
  20. UnstructuredXMLLoader,
  21. YoutubeLoader,
  22. )
  23. from langchain_core.documents import Document
  24. from open_webui.retrieval.loaders.external_document import ExternalDocumentLoader
  25. from open_webui.retrieval.loaders.mistral import MistralLoader
  26. from open_webui.retrieval.loaders.datalab_marker import DatalabMarkerLoader
  27. from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
  28. logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
  29. log = logging.getLogger(__name__)
  30. log.setLevel(SRC_LOG_LEVELS["RAG"])
  31. known_source_ext = [
  32. "go",
  33. "py",
  34. "java",
  35. "sh",
  36. "bat",
  37. "ps1",
  38. "cmd",
  39. "js",
  40. "ts",
  41. "css",
  42. "cpp",
  43. "hpp",
  44. "h",
  45. "c",
  46. "cs",
  47. "sql",
  48. "log",
  49. "ini",
  50. "pl",
  51. "pm",
  52. "r",
  53. "dart",
  54. "dockerfile",
  55. "env",
  56. "php",
  57. "hs",
  58. "hsc",
  59. "lua",
  60. "nginxconf",
  61. "conf",
  62. "m",
  63. "mm",
  64. "plsql",
  65. "perl",
  66. "rb",
  67. "rs",
  68. "db2",
  69. "scala",
  70. "bash",
  71. "swift",
  72. "vue",
  73. "svelte",
  74. "ex",
  75. "exs",
  76. "erl",
  77. "tsx",
  78. "jsx",
  79. "hs",
  80. "lhs",
  81. "json",
  82. ]
  83. class TikaLoader:
  84. def __init__(self, url, file_path, mime_type=None, extract_images=None):
  85. self.url = url
  86. self.file_path = file_path
  87. self.mime_type = mime_type
  88. self.extract_images = extract_images
  89. def load(self) -> list[Document]:
  90. with open(self.file_path, "rb") as f:
  91. data = f.read()
  92. if self.mime_type is not None:
  93. headers = {"Content-Type": self.mime_type}
  94. else:
  95. headers = {}
  96. if self.extract_images == True:
  97. headers["X-Tika-PDFextractInlineImages"] = "true"
  98. endpoint = self.url
  99. if not endpoint.endswith("/"):
  100. endpoint += "/"
  101. endpoint += "tika/text"
  102. r = requests.put(endpoint, data=data, headers=headers)
  103. if r.ok:
  104. raw_metadata = r.json()
  105. text = raw_metadata.get("X-TIKA:content", "<No text content found>").strip()
  106. if "Content-Type" in raw_metadata:
  107. headers["Content-Type"] = raw_metadata["Content-Type"]
  108. log.debug("Tika extracted text: %s", text)
  109. return [Document(page_content=text, metadata=headers)]
  110. else:
  111. raise Exception(f"Error calling Tika: {r.reason}")
  112. class DoclingLoader:
  113. def __init__(self, url, file_path=None, mime_type=None, params=None):
  114. self.url = url.rstrip("/")
  115. self.file_path = file_path
  116. self.mime_type = mime_type
  117. self.params = params or {}
  118. def load(self) -> list[Document]:
  119. with open(self.file_path, "rb") as f:
  120. files = {
  121. "files": (
  122. self.file_path,
  123. f,
  124. self.mime_type or "application/octet-stream",
  125. )
  126. }
  127. params = {"image_export_mode": "placeholder", "table_mode": "accurate"}
  128. if self.params:
  129. if self.params.get("do_picture_description"):
  130. params["do_picture_description"] = self.params.get(
  131. "do_picture_description"
  132. )
  133. picture_description_mode = self.params.get(
  134. "picture_description_mode", ""
  135. ).lower()
  136. if picture_description_mode == "local" and self.params.get(
  137. "picture_description_local", {}
  138. ):
  139. params["picture_description_local"] = json.dumps(
  140. self.params.get("picture_description_local", {})
  141. )
  142. elif picture_description_mode == "api" and self.params.get(
  143. "picture_description_api", {}
  144. ):
  145. params["picture_description_api"] = json.dumps(
  146. self.params.get("picture_description_api", {})
  147. )
  148. if self.params.get("ocr_engine") and self.params.get("ocr_lang"):
  149. params["ocr_engine"] = self.params.get("ocr_engine")
  150. params["ocr_lang"] = [
  151. lang.strip()
  152. for lang in self.params.get("ocr_lang").split(",")
  153. if lang.strip()
  154. ]
  155. endpoint = f"{self.url}/v1/convert/file"
  156. r = requests.post(endpoint, files=files, data=params)
  157. if r.ok:
  158. result = r.json()
  159. document_data = result.get("document", {})
  160. text = document_data.get("md_content", "<No text content found>")
  161. metadata = {"Content-Type": self.mime_type} if self.mime_type else {}
  162. log.debug("Docling extracted text: %s", text)
  163. return [Document(page_content=text, metadata=metadata)]
  164. else:
  165. error_msg = f"Error calling Docling API: {r.reason}"
  166. if r.text:
  167. try:
  168. error_data = r.json()
  169. if "detail" in error_data:
  170. error_msg += f" - {error_data['detail']}"
  171. except Exception:
  172. error_msg += f" - {r.text}"
  173. raise Exception(f"Error calling Docling: {error_msg}")
  174. class Loader:
  175. def __init__(self, engine: str = "", **kwargs):
  176. self.engine = engine
  177. self.kwargs = kwargs
  178. def load(
  179. self, filename: str, file_content_type: str, file_path: str
  180. ) -> list[Document]:
  181. loader = self._get_loader(filename, file_content_type, file_path)
  182. docs = loader.load()
  183. return [
  184. Document(
  185. page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata
  186. )
  187. for doc in docs
  188. ]
  189. def _is_text_file(self, file_ext: str, file_content_type: str) -> bool:
  190. return file_ext in known_source_ext or (
  191. file_content_type
  192. and file_content_type.find("text/") >= 0
  193. # Avoid text/html files being detected as text
  194. and not file_content_type.find("html") >= 0
  195. )
  196. def _get_loader(self, filename: str, file_content_type: str, file_path: str):
  197. file_ext = filename.split(".")[-1].lower()
  198. if (
  199. self.engine == "external"
  200. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL")
  201. and self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY")
  202. ):
  203. loader = ExternalDocumentLoader(
  204. file_path=file_path,
  205. url=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_URL"),
  206. api_key=self.kwargs.get("EXTERNAL_DOCUMENT_LOADER_API_KEY"),
  207. mime_type=file_content_type,
  208. )
  209. elif self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
  210. if self._is_text_file(file_ext, file_content_type):
  211. loader = TextLoader(file_path, autodetect_encoding=True)
  212. else:
  213. loader = TikaLoader(
  214. url=self.kwargs.get("TIKA_SERVER_URL"),
  215. file_path=file_path,
  216. mime_type=file_content_type,
  217. extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES"),
  218. )
  219. elif (
  220. self.engine == "datalab_marker"
  221. and self.kwargs.get("DATALAB_MARKER_API_KEY")
  222. and file_ext
  223. in [
  224. "pdf",
  225. "xls",
  226. "xlsx",
  227. "ods",
  228. "doc",
  229. "docx",
  230. "odt",
  231. "ppt",
  232. "pptx",
  233. "odp",
  234. "html",
  235. "epub",
  236. "png",
  237. "jpeg",
  238. "jpg",
  239. "webp",
  240. "gif",
  241. "tiff",
  242. ]
  243. ):
  244. api_base_url = self.kwargs.get("DATALAB_MARKER_API_BASE_URL", "")
  245. if not api_base_url or api_base_url.strip() == "":
  246. api_base_url = "https://www.datalab.to/api/v1"
  247. loader = DatalabMarkerLoader(
  248. file_path=file_path,
  249. api_key=self.kwargs["DATALAB_MARKER_API_KEY"],
  250. api_base_url=api_base_url,
  251. additional_config=self.kwargs.get("DATALAB_MARKER_ADDITIONAL_CONFIG"),
  252. use_llm=self.kwargs.get("DATALAB_MARKER_USE_LLM", False),
  253. skip_cache=self.kwargs.get("DATALAB_MARKER_SKIP_CACHE", False),
  254. force_ocr=self.kwargs.get("DATALAB_MARKER_FORCE_OCR", False),
  255. paginate=self.kwargs.get("DATALAB_MARKER_PAGINATE", False),
  256. strip_existing_ocr=self.kwargs.get(
  257. "DATALAB_MARKER_STRIP_EXISTING_OCR", False
  258. ),
  259. disable_image_extraction=self.kwargs.get(
  260. "DATALAB_MARKER_DISABLE_IMAGE_EXTRACTION", False
  261. ),
  262. format_lines=self.kwargs.get("DATALAB_MARKER_FORMAT_LINES", False),
  263. output_format=self.kwargs.get(
  264. "DATALAB_MARKER_OUTPUT_FORMAT", "markdown"
  265. ),
  266. )
  267. elif self.engine == "docling" and self.kwargs.get("DOCLING_SERVER_URL"):
  268. if self._is_text_file(file_ext, file_content_type):
  269. loader = TextLoader(file_path, autodetect_encoding=True)
  270. else:
  271. # Build params for DoclingLoader
  272. params = self.kwargs.get("DOCLING_PARAMS", {})
  273. if not isinstance(params, dict):
  274. try:
  275. params = json.loads(params)
  276. except json.JSONDecodeError:
  277. log.error("Invalid DOCLING_PARAMS format, expected JSON object")
  278. params = {}
  279. loader = DoclingLoader(
  280. url=self.kwargs.get("DOCLING_SERVER_URL"),
  281. file_path=file_path,
  282. mime_type=file_content_type,
  283. params=params,
  284. )
  285. elif (
  286. self.engine == "document_intelligence"
  287. and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
  288. and (
  289. file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
  290. or file_content_type
  291. in [
  292. "application/vnd.ms-excel",
  293. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  294. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  295. "application/vnd.ms-powerpoint",
  296. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  297. ]
  298. )
  299. ):
  300. if self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != "":
  301. loader = AzureAIDocumentIntelligenceLoader(
  302. file_path=file_path,
  303. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  304. api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
  305. )
  306. else:
  307. loader = AzureAIDocumentIntelligenceLoader(
  308. file_path=file_path,
  309. api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
  310. azure_credential=DefaultAzureCredential(),
  311. )
  312. elif (
  313. self.engine == "mistral_ocr"
  314. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  315. and file_ext
  316. in ["pdf"] # Mistral OCR currently only supports PDF and images
  317. ):
  318. loader = MistralLoader(
  319. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  320. )
  321. elif (
  322. self.engine == "external"
  323. and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
  324. and file_ext
  325. in ["pdf"] # Mistral OCR currently only supports PDF and images
  326. ):
  327. loader = MistralLoader(
  328. api_key=self.kwargs.get("MISTRAL_OCR_API_KEY"), file_path=file_path
  329. )
  330. else:
  331. if file_ext == "pdf":
  332. loader = PyPDFLoader(
  333. file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
  334. )
  335. elif file_ext == "csv":
  336. loader = CSVLoader(file_path, autodetect_encoding=True)
  337. elif file_ext == "rst":
  338. loader = UnstructuredRSTLoader(file_path, mode="elements")
  339. elif file_ext == "xml":
  340. loader = UnstructuredXMLLoader(file_path)
  341. elif file_ext in ["htm", "html"]:
  342. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  343. elif file_ext == "md":
  344. loader = TextLoader(file_path, autodetect_encoding=True)
  345. elif file_content_type == "application/epub+zip":
  346. loader = UnstructuredEPubLoader(file_path)
  347. elif (
  348. file_content_type
  349. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  350. or file_ext == "docx"
  351. ):
  352. loader = Docx2txtLoader(file_path)
  353. elif file_content_type in [
  354. "application/vnd.ms-excel",
  355. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  356. ] or file_ext in ["xls", "xlsx"]:
  357. loader = UnstructuredExcelLoader(file_path)
  358. elif file_content_type in [
  359. "application/vnd.ms-powerpoint",
  360. "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  361. ] or file_ext in ["ppt", "pptx"]:
  362. loader = UnstructuredPowerPointLoader(file_path)
  363. elif file_ext == "msg":
  364. loader = OutlookMessageLoader(file_path)
  365. elif file_ext == "odt":
  366. loader = UnstructuredODTLoader(file_path)
  367. elif self._is_text_file(file_ext, file_content_type):
  368. loader = TextLoader(file_path, autodetect_encoding=True)
  369. else:
  370. loader = TextLoader(file_path, autodetect_encoding=True)
  371. return loader