main.py 12 KB

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