main.py 16 KB

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