main.py 16 KB

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