main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. from fastapi import (
  2. FastAPI,
  3. Request,
  4. Depends,
  5. HTTPException,
  6. status,
  7. UploadFile,
  8. File,
  9. Form,
  10. )
  11. from fastapi.middleware.cors import CORSMiddleware
  12. import os, shutil
  13. from pathlib import Path
  14. from typing import List
  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 langchain.chains import RetrievalQA
  31. from langchain_community.vectorstores import Chroma
  32. from pydantic import BaseModel
  33. from typing import Optional
  34. import mimetypes
  35. import uuid
  36. import json
  37. import time
  38. from apps.web.models.documents import (
  39. Documents,
  40. DocumentForm,
  41. DocumentResponse,
  42. )
  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. UPLOAD_DIR,
  52. DOCS_DIR,
  53. EMBED_MODEL,
  54. CHROMA_CLIENT,
  55. CHUNK_SIZE,
  56. CHUNK_OVERLAP,
  57. RAG_TEMPLATE,
  58. )
  59. from constants import ERROR_MESSAGES
  60. # EMBEDDING_FUNC = embedding_functions.SentenceTransformerEmbeddingFunction(
  61. # model_name=EMBED_MODEL
  62. # )
  63. app = FastAPI()
  64. app.state.CHUNK_SIZE = CHUNK_SIZE
  65. app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
  66. app.state.RAG_TEMPLATE = RAG_TEMPLATE
  67. origins = ["*"]
  68. app.add_middleware(
  69. CORSMiddleware,
  70. allow_origins=origins,
  71. allow_credentials=True,
  72. allow_methods=["*"],
  73. allow_headers=["*"],
  74. )
  75. class CollectionNameForm(BaseModel):
  76. collection_name: Optional[str] = "test"
  77. class StoreWebForm(CollectionNameForm):
  78. url: str
  79. def store_data_in_vector_db(data, collection_name) -> bool:
  80. text_splitter = RecursiveCharacterTextSplitter(
  81. chunk_size=app.state.CHUNK_SIZE, chunk_overlap=app.state.CHUNK_OVERLAP
  82. )
  83. docs = text_splitter.split_documents(data)
  84. texts = [doc.page_content for doc in docs]
  85. metadatas = [doc.metadata for doc in docs]
  86. try:
  87. collection = CHROMA_CLIENT.create_collection(name=collection_name)
  88. collection.add(
  89. documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
  90. )
  91. return True
  92. except Exception as e:
  93. print(e)
  94. if e.__class__.__name__ == "UniqueConstraintError":
  95. return True
  96. return False
  97. @app.get("/")
  98. async def get_status():
  99. return {
  100. "status": True,
  101. "chunk_size": app.state.CHUNK_SIZE,
  102. "chunk_overlap": app.state.CHUNK_OVERLAP,
  103. }
  104. @app.get("/chunk")
  105. async def get_chunk_params(user=Depends(get_admin_user)):
  106. return {
  107. "status": True,
  108. "chunk_size": app.state.CHUNK_SIZE,
  109. "chunk_overlap": app.state.CHUNK_OVERLAP,
  110. }
  111. class ChunkParamUpdateForm(BaseModel):
  112. chunk_size: int
  113. chunk_overlap: int
  114. @app.post("/chunk/update")
  115. async def update_chunk_params(
  116. form_data: ChunkParamUpdateForm, user=Depends(get_admin_user)
  117. ):
  118. app.state.CHUNK_SIZE = form_data.chunk_size
  119. app.state.CHUNK_OVERLAP = form_data.chunk_overlap
  120. return {
  121. "status": True,
  122. "chunk_size": app.state.CHUNK_SIZE,
  123. "chunk_overlap": app.state.CHUNK_OVERLAP,
  124. }
  125. @app.get("/template")
  126. async def get_rag_template(user=Depends(get_current_user)):
  127. return {
  128. "status": True,
  129. "template": app.state.RAG_TEMPLATE,
  130. }
  131. class RAGTemplateForm(BaseModel):
  132. template: str
  133. @app.post("/template/update")
  134. async def update_rag_template(form_data: RAGTemplateForm, user=Depends(get_admin_user)):
  135. # TODO: check template requirements
  136. app.state.RAG_TEMPLATE = (
  137. form_data.template if form_data.template != "" else RAG_TEMPLATE
  138. )
  139. return {"status": True, "template": app.state.RAG_TEMPLATE}
  140. class QueryDocForm(BaseModel):
  141. collection_name: str
  142. query: str
  143. k: Optional[int] = 4
  144. @app.post("/query/doc")
  145. def query_doc(
  146. form_data: QueryDocForm,
  147. user=Depends(get_current_user),
  148. ):
  149. try:
  150. collection = CHROMA_CLIENT.get_collection(
  151. name=form_data.collection_name,
  152. )
  153. result = collection.query(query_texts=[form_data.query], n_results=form_data.k)
  154. return result
  155. except Exception as e:
  156. print(e)
  157. raise HTTPException(
  158. status_code=status.HTTP_400_BAD_REQUEST,
  159. detail=ERROR_MESSAGES.DEFAULT(e),
  160. )
  161. class QueryCollectionsForm(BaseModel):
  162. collection_names: List[str]
  163. query: str
  164. k: Optional[int] = 4
  165. def merge_and_sort_query_results(query_results, k):
  166. # Initialize lists to store combined data
  167. combined_ids = []
  168. combined_distances = []
  169. combined_metadatas = []
  170. combined_documents = []
  171. # Combine data from each dictionary
  172. for data in query_results:
  173. combined_ids.extend(data["ids"][0])
  174. combined_distances.extend(data["distances"][0])
  175. combined_metadatas.extend(data["metadatas"][0])
  176. combined_documents.extend(data["documents"][0])
  177. # Create a list of tuples (distance, id, metadata, document)
  178. combined = list(
  179. zip(combined_distances, combined_ids, combined_metadatas, combined_documents)
  180. )
  181. # Sort the list based on distances
  182. combined.sort(key=lambda x: x[0])
  183. # Unzip the sorted list
  184. sorted_distances, sorted_ids, sorted_metadatas, sorted_documents = zip(*combined)
  185. # Slicing the lists to include only k elements
  186. sorted_distances = list(sorted_distances)[:k]
  187. sorted_ids = list(sorted_ids)[:k]
  188. sorted_metadatas = list(sorted_metadatas)[:k]
  189. sorted_documents = list(sorted_documents)[:k]
  190. # Create the output dictionary
  191. merged_query_results = {
  192. "ids": [sorted_ids],
  193. "distances": [sorted_distances],
  194. "metadatas": [sorted_metadatas],
  195. "documents": [sorted_documents],
  196. "embeddings": None,
  197. "uris": None,
  198. "data": None,
  199. }
  200. return merged_query_results
  201. @app.post("/query/collection")
  202. def query_collection(
  203. form_data: QueryCollectionsForm,
  204. user=Depends(get_current_user),
  205. ):
  206. results = []
  207. for collection_name in form_data.collection_names:
  208. try:
  209. collection = CHROMA_CLIENT.get_collection(
  210. name=collection_name,
  211. )
  212. result = collection.query(
  213. query_texts=[form_data.query], n_results=form_data.k
  214. )
  215. results.append(result)
  216. except:
  217. pass
  218. return merge_and_sort_query_results(results, form_data.k)
  219. @app.post("/web")
  220. def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
  221. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  222. try:
  223. loader = WebBaseLoader(form_data.url)
  224. data = loader.load()
  225. collection_name = form_data.collection_name
  226. if collection_name == "":
  227. collection_name = calculate_sha256_string(form_data.url)[:63]
  228. store_data_in_vector_db(data, collection_name)
  229. return {
  230. "status": True,
  231. "collection_name": collection_name,
  232. "filename": form_data.url,
  233. }
  234. except Exception as e:
  235. print(e)
  236. raise HTTPException(
  237. status_code=status.HTTP_400_BAD_REQUEST,
  238. detail=ERROR_MESSAGES.DEFAULT(e),
  239. )
  240. def get_loader(filename: str, file_content_type: str, file_path: str):
  241. file_ext = filename.split(".")[-1].lower()
  242. known_type = True
  243. known_source_ext = [
  244. "go",
  245. "py",
  246. "java",
  247. "sh",
  248. "bat",
  249. "ps1",
  250. "cmd",
  251. "js",
  252. "ts",
  253. "css",
  254. "cpp",
  255. "hpp",
  256. "h",
  257. "c",
  258. "cs",
  259. "sql",
  260. "log",
  261. "ini",
  262. "pl",
  263. "pm",
  264. "r",
  265. "dart",
  266. "dockerfile",
  267. "env",
  268. "php",
  269. "hs",
  270. "hsc",
  271. "lua",
  272. "nginxconf",
  273. "conf",
  274. "m",
  275. "mm",
  276. "plsql",
  277. "perl",
  278. "rb",
  279. "rs",
  280. "db2",
  281. "scala",
  282. "bash",
  283. "swift",
  284. "vue",
  285. "svelte",
  286. ]
  287. if file_ext == "pdf":
  288. loader = PyPDFLoader(file_path)
  289. elif file_ext == "csv":
  290. loader = CSVLoader(file_path)
  291. elif file_ext == "rst":
  292. loader = UnstructuredRSTLoader(file_path, mode="elements")
  293. elif file_ext == "xml":
  294. loader = UnstructuredXMLLoader(file_path)
  295. elif file_ext == "md":
  296. loader = UnstructuredMarkdownLoader(file_path)
  297. elif file_content_type == "application/epub+zip":
  298. loader = UnstructuredEPubLoader(file_path)
  299. elif (
  300. file_content_type
  301. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  302. or file_ext in ["doc", "docx"]
  303. ):
  304. loader = Docx2txtLoader(file_path)
  305. elif file_content_type in [
  306. "application/vnd.ms-excel",
  307. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  308. ] or file_ext in ["xls", "xlsx"]:
  309. loader = UnstructuredExcelLoader(file_path)
  310. elif file_ext in known_source_ext or file_content_type.find("text/") >= 0:
  311. loader = TextLoader(file_path)
  312. else:
  313. loader = TextLoader(file_path)
  314. known_type = False
  315. return loader, known_type
  316. @app.post("/doc")
  317. def store_doc(
  318. collection_name: Optional[str] = Form(None),
  319. file: UploadFile = File(...),
  320. user=Depends(get_current_user),
  321. ):
  322. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  323. print(file.content_type)
  324. try:
  325. filename = file.filename
  326. file_path = f"{UPLOAD_DIR}/{filename}"
  327. contents = file.file.read()
  328. with open(file_path, "wb") as f:
  329. f.write(contents)
  330. f.close()
  331. f = open(file_path, "rb")
  332. if collection_name == None:
  333. collection_name = calculate_sha256(f)[:63]
  334. f.close()
  335. loader, known_type = get_loader(file.filename, file.content_type, file_path)
  336. data = loader.load()
  337. result = store_data_in_vector_db(data, collection_name)
  338. if result:
  339. return {
  340. "status": True,
  341. "collection_name": collection_name,
  342. "filename": filename,
  343. "known_type": known_type,
  344. }
  345. else:
  346. raise HTTPException(
  347. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  348. detail=ERROR_MESSAGES.DEFAULT(),
  349. )
  350. except Exception as e:
  351. print(e)
  352. if "No pandoc was found" in str(e):
  353. raise HTTPException(
  354. status_code=status.HTTP_400_BAD_REQUEST,
  355. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  356. )
  357. else:
  358. raise HTTPException(
  359. status_code=status.HTTP_400_BAD_REQUEST,
  360. detail=ERROR_MESSAGES.DEFAULT(e),
  361. )
  362. @app.get("/scan")
  363. def scan_docs_dir(user=Depends(get_admin_user)):
  364. try:
  365. for path in Path(DOCS_DIR).rglob("./**/*"):
  366. if path.is_file() and not path.name.startswith("."):
  367. tags = extract_folders_after_data_docs(path)
  368. filename = path.name
  369. file_content_type = mimetypes.guess_type(path)
  370. f = open(path, "rb")
  371. collection_name = calculate_sha256(f)[:63]
  372. f.close()
  373. loader, known_type = get_loader(
  374. filename, file_content_type[0], str(path)
  375. )
  376. data = loader.load()
  377. result = store_data_in_vector_db(data, collection_name)
  378. if result:
  379. sanitized_filename = sanitize_filename(filename)
  380. doc = Documents.get_doc_by_name(sanitized_filename)
  381. if doc == None:
  382. doc = Documents.insert_new_doc(
  383. user.id,
  384. DocumentForm(
  385. **{
  386. "name": sanitized_filename,
  387. "title": filename,
  388. "collection_name": collection_name,
  389. "filename": filename,
  390. "content": (
  391. json.dumps(
  392. {
  393. "tags": list(
  394. map(
  395. lambda name: {"name": name},
  396. tags,
  397. )
  398. )
  399. }
  400. )
  401. if len(tags)
  402. else "{}"
  403. ),
  404. }
  405. ),
  406. )
  407. except Exception as e:
  408. print(e)
  409. return True
  410. @app.get("/reset/db")
  411. def reset_vector_db(user=Depends(get_admin_user)):
  412. CHROMA_CLIENT.reset()
  413. @app.get("/reset")
  414. def reset(user=Depends(get_admin_user)) -> bool:
  415. folder = f"{UPLOAD_DIR}"
  416. for filename in os.listdir(folder):
  417. file_path = os.path.join(folder, filename)
  418. try:
  419. if os.path.isfile(file_path) or os.path.islink(file_path):
  420. os.unlink(file_path)
  421. elif os.path.isdir(file_path):
  422. shutil.rmtree(file_path)
  423. except Exception as e:
  424. print("Failed to delete %s. Reason: %s" % (file_path, e))
  425. try:
  426. CHROMA_CLIENT.reset()
  427. except Exception as e:
  428. print(e)
  429. return True