main.py 18 KB

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