main.py 18 KB

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