main.py 18 KB

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