main.py 15 KB

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