main.py 17 KB

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