main.py 17 KB

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