main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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 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
  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. if len(docs) > 0:
  245. return store_docs_in_vector_db(docs, collection_name, overwrite), None
  246. else:
  247. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  248. def store_text_in_vector_db(
  249. text, metadata, collection_name, overwrite: bool = False
  250. ) -> bool:
  251. text_splitter = RecursiveCharacterTextSplitter(
  252. chunk_size=app.state.CHUNK_SIZE,
  253. chunk_overlap=app.state.CHUNK_OVERLAP,
  254. add_start_index=True,
  255. )
  256. docs = text_splitter.create_documents([text], metadatas=[metadata])
  257. return store_docs_in_vector_db(docs, collection_name, overwrite)
  258. def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> bool:
  259. texts = [doc.page_content for doc in docs]
  260. metadatas = [doc.metadata for doc in docs]
  261. try:
  262. if overwrite:
  263. for collection in CHROMA_CLIENT.list_collections():
  264. if collection_name == collection.name:
  265. log.info(f"deleting existing collection {collection_name}")
  266. CHROMA_CLIENT.delete_collection(name=collection_name)
  267. collection = CHROMA_CLIENT.create_collection(
  268. name=collection_name,
  269. embedding_function=app.state.sentence_transformer_ef,
  270. )
  271. collection.add(
  272. documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
  273. )
  274. return True
  275. except Exception as e:
  276. log.exception(e)
  277. if e.__class__.__name__ == "UniqueConstraintError":
  278. return True
  279. return False
  280. def get_loader(filename: str, file_content_type: str, file_path: str):
  281. file_ext = filename.split(".")[-1].lower()
  282. known_type = True
  283. known_source_ext = [
  284. "go",
  285. "py",
  286. "java",
  287. "sh",
  288. "bat",
  289. "ps1",
  290. "cmd",
  291. "js",
  292. "ts",
  293. "css",
  294. "cpp",
  295. "hpp",
  296. "h",
  297. "c",
  298. "cs",
  299. "sql",
  300. "log",
  301. "ini",
  302. "pl",
  303. "pm",
  304. "r",
  305. "dart",
  306. "dockerfile",
  307. "env",
  308. "php",
  309. "hs",
  310. "hsc",
  311. "lua",
  312. "nginxconf",
  313. "conf",
  314. "m",
  315. "mm",
  316. "plsql",
  317. "perl",
  318. "rb",
  319. "rs",
  320. "db2",
  321. "scala",
  322. "bash",
  323. "swift",
  324. "vue",
  325. "svelte",
  326. ]
  327. if file_ext == "pdf":
  328. loader = PyPDFLoader(file_path, extract_images=app.state.PDF_EXTRACT_IMAGES)
  329. elif file_ext == "csv":
  330. loader = CSVLoader(file_path)
  331. elif file_ext == "rst":
  332. loader = UnstructuredRSTLoader(file_path, mode="elements")
  333. elif file_ext == "xml":
  334. loader = UnstructuredXMLLoader(file_path)
  335. elif file_ext in ["htm", "html"]:
  336. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  337. elif file_ext == "md":
  338. loader = UnstructuredMarkdownLoader(file_path)
  339. elif file_content_type == "application/epub+zip":
  340. loader = UnstructuredEPubLoader(file_path)
  341. elif (
  342. file_content_type
  343. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  344. or file_ext in ["doc", "docx"]
  345. ):
  346. loader = Docx2txtLoader(file_path)
  347. elif file_content_type in [
  348. "application/vnd.ms-excel",
  349. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  350. ] or file_ext in ["xls", "xlsx"]:
  351. loader = UnstructuredExcelLoader(file_path)
  352. elif file_ext in known_source_ext or (
  353. file_content_type and file_content_type.find("text/") >= 0
  354. ):
  355. loader = TextLoader(file_path, autodetect_encoding=True)
  356. else:
  357. loader = TextLoader(file_path, autodetect_encoding=True)
  358. known_type = False
  359. return loader, known_type
  360. @app.post("/doc")
  361. def store_doc(
  362. collection_name: Optional[str] = Form(None),
  363. file: UploadFile = File(...),
  364. user=Depends(get_current_user),
  365. ):
  366. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  367. log.info(f"file.content_type: {file.content_type}")
  368. try:
  369. unsanitized_filename = file.filename
  370. filename = os.path.basename(unsanitized_filename)
  371. file_path = f"{UPLOAD_DIR}/{filename}"
  372. contents = file.file.read()
  373. with open(file_path, "wb") as f:
  374. f.write(contents)
  375. f.close()
  376. f = open(file_path, "rb")
  377. if collection_name == None:
  378. collection_name = calculate_sha256(f)[:63]
  379. f.close()
  380. loader, known_type = get_loader(filename, file.content_type, file_path)
  381. data = loader.load()
  382. try:
  383. result = store_data_in_vector_db(data, collection_name)
  384. if result:
  385. return {
  386. "status": True,
  387. "collection_name": collection_name,
  388. "filename": filename,
  389. "known_type": known_type,
  390. }
  391. except Exception as e:
  392. raise HTTPException(
  393. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  394. detail=e,
  395. )
  396. except Exception as e:
  397. log.exception(e)
  398. if "No pandoc was found" in str(e):
  399. raise HTTPException(
  400. status_code=status.HTTP_400_BAD_REQUEST,
  401. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  402. )
  403. else:
  404. raise HTTPException(
  405. status_code=status.HTTP_400_BAD_REQUEST,
  406. detail=ERROR_MESSAGES.DEFAULT(e),
  407. )
  408. class TextRAGForm(BaseModel):
  409. name: str
  410. content: str
  411. collection_name: Optional[str] = None
  412. @app.post("/text")
  413. def store_text(
  414. form_data: TextRAGForm,
  415. user=Depends(get_current_user),
  416. ):
  417. collection_name = form_data.collection_name
  418. if collection_name == None:
  419. collection_name = calculate_sha256_string(form_data.content)
  420. result = store_text_in_vector_db(
  421. form_data.content,
  422. metadata={"name": form_data.name, "created_by": user.id},
  423. collection_name=collection_name,
  424. )
  425. if result:
  426. return {"status": True, "collection_name": collection_name}
  427. else:
  428. raise HTTPException(
  429. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  430. detail=ERROR_MESSAGES.DEFAULT(),
  431. )
  432. @app.get("/scan")
  433. def scan_docs_dir(user=Depends(get_admin_user)):
  434. for path in Path(DOCS_DIR).rglob("./**/*"):
  435. try:
  436. if path.is_file() and not path.name.startswith("."):
  437. tags = extract_folders_after_data_docs(path)
  438. filename = path.name
  439. file_content_type = mimetypes.guess_type(path)
  440. f = open(path, "rb")
  441. collection_name = calculate_sha256(f)[:63]
  442. f.close()
  443. loader, known_type = get_loader(
  444. filename, file_content_type[0], str(path)
  445. )
  446. data = loader.load()
  447. try:
  448. result = store_data_in_vector_db(data, collection_name)
  449. if result:
  450. sanitized_filename = sanitize_filename(filename)
  451. doc = Documents.get_doc_by_name(sanitized_filename)
  452. if doc == None:
  453. doc = Documents.insert_new_doc(
  454. user.id,
  455. DocumentForm(
  456. **{
  457. "name": sanitized_filename,
  458. "title": filename,
  459. "collection_name": collection_name,
  460. "filename": filename,
  461. "content": (
  462. json.dumps(
  463. {
  464. "tags": list(
  465. map(
  466. lambda name: {"name": name},
  467. tags,
  468. )
  469. )
  470. }
  471. )
  472. if len(tags)
  473. else "{}"
  474. ),
  475. }
  476. ),
  477. )
  478. except Exception as e:
  479. log.exception(e)
  480. pass
  481. except Exception as e:
  482. log.exception(e)
  483. return True
  484. @app.get("/reset/db")
  485. def reset_vector_db(user=Depends(get_admin_user)):
  486. CHROMA_CLIENT.reset()
  487. @app.get("/reset")
  488. def reset(user=Depends(get_admin_user)) -> bool:
  489. folder = f"{UPLOAD_DIR}"
  490. for filename in os.listdir(folder):
  491. file_path = os.path.join(folder, filename)
  492. try:
  493. if os.path.isfile(file_path) or os.path.islink(file_path):
  494. os.unlink(file_path)
  495. elif os.path.isdir(file_path):
  496. shutil.rmtree(file_path)
  497. except Exception as e:
  498. log.error("Failed to delete %s. Reason: %s" % (file_path, e))
  499. try:
  500. CHROMA_CLIENT.reset()
  501. except Exception as e:
  502. log.exception(e)
  503. return True