main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. from fastapi import (
  2. FastAPI,
  3. Depends,
  4. HTTPException,
  5. status,
  6. UploadFile,
  7. File,
  8. Form,
  9. )
  10. from fastapi.middleware.cors import CORSMiddleware
  11. import os, shutil, logging, re
  12. from pathlib import Path
  13. from typing import List
  14. from chromadb.utils import embedding_functions
  15. from langchain_community.document_loaders import (
  16. WebBaseLoader,
  17. TextLoader,
  18. PyPDFLoader,
  19. CSVLoader,
  20. BSHTMLLoader,
  21. Docx2txtLoader,
  22. UnstructuredEPubLoader,
  23. UnstructuredWordDocumentLoader,
  24. UnstructuredMarkdownLoader,
  25. UnstructuredXMLLoader,
  26. UnstructuredRSTLoader,
  27. UnstructuredExcelLoader,
  28. )
  29. from langchain.text_splitter import RecursiveCharacterTextSplitter
  30. from pydantic import BaseModel
  31. from typing import Optional
  32. import mimetypes
  33. import uuid
  34. import json
  35. from apps.web.models.documents import (
  36. Documents,
  37. DocumentForm,
  38. DocumentResponse,
  39. )
  40. from apps.rag.utils import query_doc, query_collection, get_embedding_model_path
  41. from utils.misc import (
  42. calculate_sha256,
  43. calculate_sha256_string,
  44. sanitize_filename,
  45. extract_folders_after_data_docs,
  46. )
  47. from utils.utils import get_current_user, get_admin_user
  48. from config import (
  49. SRC_LOG_LEVELS,
  50. UPLOAD_DIR,
  51. DOCS_DIR,
  52. RAG_EMBEDDING_MODEL,
  53. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  54. DEVICE_TYPE,
  55. CHROMA_CLIENT,
  56. CHUNK_SIZE,
  57. CHUNK_OVERLAP,
  58. RAG_TEMPLATE,
  59. )
  60. from constants import ERROR_MESSAGES
  61. log = logging.getLogger(__name__)
  62. log.setLevel(SRC_LOG_LEVELS["RAG"])
  63. app = FastAPI()
  64. app.state.PDF_EXTRACT_IMAGES = False
  65. app.state.CHUNK_SIZE = CHUNK_SIZE
  66. app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
  67. app.state.RAG_TEMPLATE = RAG_TEMPLATE
  68. app.state.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  69. app.state.RAG_EMBEDDING_MODEL_PATH = get_embedding_model_path(
  70. app.state.RAG_EMBEDDING_MODEL, RAG_EMBEDDING_MODEL_AUTO_UPDATE
  71. )
  72. app.state.TOP_K = 4
  73. app.state.sentence_transformer_ef = (
  74. embedding_functions.SentenceTransformerEmbeddingFunction(
  75. model_name=app.state.RAG_EMBEDDING_MODEL_PATH,
  76. device=DEVICE_TYPE,
  77. )
  78. )
  79. origins = ["*"]
  80. app.add_middleware(
  81. CORSMiddleware,
  82. allow_origins=origins,
  83. allow_credentials=True,
  84. allow_methods=["*"],
  85. allow_headers=["*"],
  86. )
  87. class CollectionNameForm(BaseModel):
  88. collection_name: Optional[str] = "test"
  89. class StoreWebForm(CollectionNameForm):
  90. url: str
  91. @app.get("/")
  92. async def get_status():
  93. return {
  94. "status": True,
  95. "chunk_size": app.state.CHUNK_SIZE,
  96. "chunk_overlap": app.state.CHUNK_OVERLAP,
  97. "template": app.state.RAG_TEMPLATE,
  98. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  99. }
  100. @app.get("/embedding/model")
  101. async def get_embedding_model(user=Depends(get_admin_user)):
  102. return {
  103. "status": True,
  104. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  105. "embedding_model_path": app.state.RAG_EMBEDDING_MODEL_PATH,
  106. }
  107. class EmbeddingModelUpdateForm(BaseModel):
  108. embedding_model: str
  109. @app.post("/embedding/model/update")
  110. async def update_embedding_model(
  111. form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
  112. ):
  113. status = True
  114. old_model_path = app.state.RAG_EMBEDDING_MODEL_PATH
  115. app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
  116. log.debug(f"form_data.embedding_model: {form_data.embedding_model}")
  117. log.info(
  118. f"Updating embedding model: {app.state.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
  119. )
  120. try:
  121. app.state.RAG_EMBEDDING_MODEL_PATH = get_embedding_model_path(
  122. app.state.RAG_EMBEDDING_MODEL, True
  123. )
  124. app.state.sentence_transformer_ef = (
  125. embedding_functions.SentenceTransformerEmbeddingFunction(
  126. model_name=app.state.RAG_EMBEDDING_MODEL_PATH,
  127. device=DEVICE_TYPE,
  128. )
  129. )
  130. except Exception as e:
  131. log.exception(f"Problem updating embedding model: {e}")
  132. raise HTTPException(
  133. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  134. detail=e,
  135. )
  136. if app.state.RAG_EMBEDDING_MODEL_PATH == old_model_path:
  137. status = False
  138. log.debug(
  139. f"app.state.RAG_EMBEDDING_MODEL_PATH: {app.state.RAG_EMBEDDING_MODEL_PATH}"
  140. )
  141. log.debug(f"old_model_path: {old_model_path}")
  142. log.debug(f"status: {status}")
  143. return {
  144. "status": status,
  145. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  146. "embedding_model_path": app.state.RAG_EMBEDDING_MODEL_PATH,
  147. }
  148. @app.get("/config")
  149. async def get_rag_config(user=Depends(get_admin_user)):
  150. return {
  151. "status": True,
  152. "pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
  153. "chunk": {
  154. "chunk_size": app.state.CHUNK_SIZE,
  155. "chunk_overlap": app.state.CHUNK_OVERLAP,
  156. },
  157. }
  158. class ChunkParamUpdateForm(BaseModel):
  159. chunk_size: int
  160. chunk_overlap: int
  161. class ConfigUpdateForm(BaseModel):
  162. pdf_extract_images: bool
  163. chunk: ChunkParamUpdateForm
  164. @app.post("/config/update")
  165. async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
  166. app.state.PDF_EXTRACT_IMAGES = form_data.pdf_extract_images
  167. app.state.CHUNK_SIZE = form_data.chunk.chunk_size
  168. app.state.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
  169. return {
  170. "status": True,
  171. "pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
  172. "chunk": {
  173. "chunk_size": app.state.CHUNK_SIZE,
  174. "chunk_overlap": app.state.CHUNK_OVERLAP,
  175. },
  176. }
  177. @app.get("/template")
  178. async def get_rag_template(user=Depends(get_current_user)):
  179. return {
  180. "status": True,
  181. "template": app.state.RAG_TEMPLATE,
  182. }
  183. @app.get("/query/settings")
  184. async def get_query_settings(user=Depends(get_admin_user)):
  185. return {
  186. "status": True,
  187. "template": app.state.RAG_TEMPLATE,
  188. "k": app.state.TOP_K,
  189. }
  190. class QuerySettingsForm(BaseModel):
  191. k: Optional[int] = None
  192. template: Optional[str] = None
  193. @app.post("/query/settings/update")
  194. async def update_query_settings(
  195. form_data: QuerySettingsForm, user=Depends(get_admin_user)
  196. ):
  197. app.state.RAG_TEMPLATE = form_data.template if form_data.template else RAG_TEMPLATE
  198. app.state.TOP_K = form_data.k if form_data.k else 4
  199. return {"status": True, "template": app.state.RAG_TEMPLATE}
  200. class QueryDocForm(BaseModel):
  201. collection_name: str
  202. query: str
  203. k: Optional[int] = None
  204. @app.post("/query/doc")
  205. def query_doc_handler(
  206. form_data: QueryDocForm,
  207. user=Depends(get_current_user),
  208. ):
  209. try:
  210. return query_doc(
  211. collection_name=form_data.collection_name,
  212. query=form_data.query,
  213. k=form_data.k if form_data.k else app.state.TOP_K,
  214. embedding_function=app.state.sentence_transformer_ef,
  215. )
  216. except Exception as e:
  217. log.exception(e)
  218. raise HTTPException(
  219. status_code=status.HTTP_400_BAD_REQUEST,
  220. detail=ERROR_MESSAGES.DEFAULT(e),
  221. )
  222. class QueryCollectionsForm(BaseModel):
  223. collection_names: List[str]
  224. query: str
  225. k: Optional[int] = None
  226. @app.post("/query/collection")
  227. def query_collection_handler(
  228. form_data: QueryCollectionsForm,
  229. user=Depends(get_current_user),
  230. ):
  231. return query_collection(
  232. collection_names=form_data.collection_names,
  233. query=form_data.query,
  234. k=form_data.k if form_data.k else app.state.TOP_K,
  235. embedding_function=app.state.sentence_transformer_ef,
  236. )
  237. @app.post("/web")
  238. def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
  239. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  240. try:
  241. loader = WebBaseLoader(form_data.url)
  242. data = loader.load()
  243. collection_name = form_data.collection_name
  244. if collection_name == "":
  245. collection_name = calculate_sha256_string(form_data.url)[:63]
  246. store_data_in_vector_db(data, collection_name, overwrite=True)
  247. return {
  248. "status": True,
  249. "collection_name": collection_name,
  250. "filename": form_data.url,
  251. }
  252. except Exception as e:
  253. log.exception(e)
  254. raise HTTPException(
  255. status_code=status.HTTP_400_BAD_REQUEST,
  256. detail=ERROR_MESSAGES.DEFAULT(e),
  257. )
  258. def store_data_in_vector_db(data, collection_name, overwrite: bool = False) -> bool:
  259. text_splitter = RecursiveCharacterTextSplitter(
  260. chunk_size=app.state.CHUNK_SIZE,
  261. chunk_overlap=app.state.CHUNK_OVERLAP,
  262. add_start_index=True,
  263. )
  264. docs = text_splitter.split_documents(data)
  265. if len(docs) > 0:
  266. return store_docs_in_vector_db(docs, collection_name, overwrite), None
  267. else:
  268. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  269. def store_text_in_vector_db(
  270. text, metadata, collection_name, overwrite: bool = False
  271. ) -> bool:
  272. text_splitter = RecursiveCharacterTextSplitter(
  273. chunk_size=app.state.CHUNK_SIZE,
  274. chunk_overlap=app.state.CHUNK_OVERLAP,
  275. add_start_index=True,
  276. )
  277. docs = text_splitter.create_documents([text], metadatas=[metadata])
  278. return store_docs_in_vector_db(docs, collection_name, overwrite)
  279. def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> bool:
  280. texts = [doc.page_content for doc in docs]
  281. metadatas = [doc.metadata for doc in docs]
  282. try:
  283. if overwrite:
  284. for collection in CHROMA_CLIENT.list_collections():
  285. if collection_name == collection.name:
  286. log.info(f"deleting existing collection {collection_name}")
  287. CHROMA_CLIENT.delete_collection(name=collection_name)
  288. collection = CHROMA_CLIENT.create_collection(
  289. name=collection_name,
  290. embedding_function=app.state.sentence_transformer_ef,
  291. )
  292. collection.add(
  293. documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
  294. )
  295. return True
  296. except Exception as e:
  297. log.exception(e)
  298. if e.__class__.__name__ == "UniqueConstraintError":
  299. return True
  300. return False
  301. def get_loader(filename: str, file_content_type: str, file_path: str):
  302. file_ext = filename.split(".")[-1].lower()
  303. known_type = True
  304. known_source_ext = [
  305. "go",
  306. "py",
  307. "java",
  308. "sh",
  309. "bat",
  310. "ps1",
  311. "cmd",
  312. "js",
  313. "ts",
  314. "css",
  315. "cpp",
  316. "hpp",
  317. "h",
  318. "c",
  319. "cs",
  320. "sql",
  321. "log",
  322. "ini",
  323. "pl",
  324. "pm",
  325. "r",
  326. "dart",
  327. "dockerfile",
  328. "env",
  329. "php",
  330. "hs",
  331. "hsc",
  332. "lua",
  333. "nginxconf",
  334. "conf",
  335. "m",
  336. "mm",
  337. "plsql",
  338. "perl",
  339. "rb",
  340. "rs",
  341. "db2",
  342. "scala",
  343. "bash",
  344. "swift",
  345. "vue",
  346. "svelte",
  347. ]
  348. if file_ext == "pdf":
  349. loader = PyPDFLoader(file_path, extract_images=app.state.PDF_EXTRACT_IMAGES)
  350. elif file_ext == "csv":
  351. loader = CSVLoader(file_path)
  352. elif file_ext == "rst":
  353. loader = UnstructuredRSTLoader(file_path, mode="elements")
  354. elif file_ext == "xml":
  355. loader = UnstructuredXMLLoader(file_path)
  356. elif file_ext in ["htm", "html"]:
  357. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  358. elif file_ext == "md":
  359. loader = UnstructuredMarkdownLoader(file_path)
  360. elif file_content_type == "application/epub+zip":
  361. loader = UnstructuredEPubLoader(file_path)
  362. elif (
  363. file_content_type
  364. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  365. or file_ext in ["doc", "docx"]
  366. ):
  367. loader = Docx2txtLoader(file_path)
  368. elif file_content_type in [
  369. "application/vnd.ms-excel",
  370. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  371. ] or file_ext in ["xls", "xlsx"]:
  372. loader = UnstructuredExcelLoader(file_path)
  373. elif file_ext in known_source_ext or (
  374. file_content_type and file_content_type.find("text/") >= 0
  375. ):
  376. loader = TextLoader(file_path, autodetect_encoding=True)
  377. else:
  378. loader = TextLoader(file_path, autodetect_encoding=True)
  379. known_type = False
  380. return loader, known_type
  381. @app.post("/doc")
  382. def store_doc(
  383. collection_name: Optional[str] = Form(None),
  384. file: UploadFile = File(...),
  385. user=Depends(get_current_user),
  386. ):
  387. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  388. log.info(f"file.content_type: {file.content_type}")
  389. try:
  390. unsanitized_filename = file.filename
  391. filename = os.path.basename(unsanitized_filename)
  392. file_path = f"{UPLOAD_DIR}/{filename}"
  393. contents = file.file.read()
  394. with open(file_path, "wb") as f:
  395. f.write(contents)
  396. f.close()
  397. f = open(file_path, "rb")
  398. if collection_name == None:
  399. collection_name = calculate_sha256(f)[:63]
  400. f.close()
  401. loader, known_type = get_loader(filename, file.content_type, file_path)
  402. data = loader.load()
  403. try:
  404. result = store_data_in_vector_db(data, collection_name)
  405. if result:
  406. return {
  407. "status": True,
  408. "collection_name": collection_name,
  409. "filename": filename,
  410. "known_type": known_type,
  411. }
  412. except Exception as e:
  413. raise HTTPException(
  414. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  415. detail=e,
  416. )
  417. except Exception as e:
  418. log.exception(e)
  419. if "No pandoc was found" in str(e):
  420. raise HTTPException(
  421. status_code=status.HTTP_400_BAD_REQUEST,
  422. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  423. )
  424. else:
  425. raise HTTPException(
  426. status_code=status.HTTP_400_BAD_REQUEST,
  427. detail=ERROR_MESSAGES.DEFAULT(e),
  428. )
  429. class TextRAGForm(BaseModel):
  430. name: str
  431. content: str
  432. collection_name: Optional[str] = None
  433. @app.post("/text")
  434. def store_text(
  435. form_data: TextRAGForm,
  436. user=Depends(get_current_user),
  437. ):
  438. collection_name = form_data.collection_name
  439. if collection_name == None:
  440. collection_name = calculate_sha256_string(form_data.content)
  441. result = store_text_in_vector_db(
  442. form_data.content,
  443. metadata={"name": form_data.name, "created_by": user.id},
  444. collection_name=collection_name,
  445. )
  446. if result:
  447. return {"status": True, "collection_name": collection_name}
  448. else:
  449. raise HTTPException(
  450. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  451. detail=ERROR_MESSAGES.DEFAULT(),
  452. )
  453. @app.get("/scan")
  454. def scan_docs_dir(user=Depends(get_admin_user)):
  455. for path in Path(DOCS_DIR).rglob("./**/*"):
  456. try:
  457. if path.is_file() and not path.name.startswith("."):
  458. tags = extract_folders_after_data_docs(path)
  459. filename = path.name
  460. file_content_type = mimetypes.guess_type(path)
  461. f = open(path, "rb")
  462. collection_name = calculate_sha256(f)[:63]
  463. f.close()
  464. loader, known_type = get_loader(
  465. filename, file_content_type[0], str(path)
  466. )
  467. data = loader.load()
  468. try:
  469. result = store_data_in_vector_db(data, collection_name)
  470. if result:
  471. sanitized_filename = sanitize_filename(filename)
  472. doc = Documents.get_doc_by_name(sanitized_filename)
  473. if doc == None:
  474. doc = Documents.insert_new_doc(
  475. user.id,
  476. DocumentForm(
  477. **{
  478. "name": sanitized_filename,
  479. "title": filename,
  480. "collection_name": collection_name,
  481. "filename": filename,
  482. "content": (
  483. json.dumps(
  484. {
  485. "tags": list(
  486. map(
  487. lambda name: {"name": name},
  488. tags,
  489. )
  490. )
  491. }
  492. )
  493. if len(tags)
  494. else "{}"
  495. ),
  496. }
  497. ),
  498. )
  499. except Exception as e:
  500. log.exception(e)
  501. pass
  502. except Exception as e:
  503. log.exception(e)
  504. return True
  505. @app.get("/reset/db")
  506. def reset_vector_db(user=Depends(get_admin_user)):
  507. CHROMA_CLIENT.reset()
  508. @app.get("/reset")
  509. def reset(user=Depends(get_admin_user)) -> bool:
  510. folder = f"{UPLOAD_DIR}"
  511. for filename in os.listdir(folder):
  512. file_path = os.path.join(folder, filename)
  513. try:
  514. if os.path.isfile(file_path) or os.path.islink(file_path):
  515. os.unlink(file_path)
  516. elif os.path.isdir(file_path):
  517. shutil.rmtree(file_path)
  518. except Exception as e:
  519. log.error("Failed to delete %s. Reason: %s" % (file_path, e))
  520. try:
  521. CHROMA_CLIENT.reset()
  522. except Exception as e:
  523. log.exception(e)
  524. return True