main.py 17 KB

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