main.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 chromadb.utils import embedding_functions
  15. from langchain_community.document_loaders import (
  16. WebBaseLoader,
  17. TextLoader,
  18. PyPDFLoader,
  19. CSVLoader,
  20. Docx2txtLoader,
  21. UnstructuredEPubLoader,
  22. UnstructuredWordDocumentLoader,
  23. UnstructuredMarkdownLoader,
  24. UnstructuredXMLLoader,
  25. UnstructuredRSTLoader,
  26. UnstructuredExcelLoader,
  27. )
  28. from langchain.text_splitter import RecursiveCharacterTextSplitter
  29. from pydantic import BaseModel
  30. from typing import Optional
  31. import mimetypes
  32. import uuid
  33. from apps.web.models.documents import (
  34. Documents,
  35. DocumentForm,
  36. DocumentResponse,
  37. )
  38. from utils.misc import (
  39. calculate_sha256,
  40. calculate_sha256_string,
  41. sanitize_filename,
  42. extract_folders_after_data_docs,
  43. )
  44. from utils.utils import get_current_user, get_admin_user
  45. from config import (
  46. UPLOAD_DIR,
  47. DOCS_DIR,
  48. RAG_EMBEDDING_MODEL,
  49. CHROMA_CLIENT,
  50. CHUNK_SIZE,
  51. CHUNK_OVERLAP,
  52. RAG_TEMPLATE,
  53. )
  54. from constants import ERROR_MESSAGES
  55. if RAG_EMBEDDING_MODEL:
  56. sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(
  57. model_name=RAG_EMBEDDING_MODEL
  58. )
  59. app = FastAPI()
  60. app.state.CHUNK_SIZE = CHUNK_SIZE
  61. app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
  62. app.state.RAG_TEMPLATE = RAG_TEMPLATE
  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=app.state.CHUNK_SIZE, chunk_overlap=app.state.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. if RAG_EMBEDDING_MODEL:
  84. # if you use docker use the model from the environment variable
  85. collection = CHROMA_CLIENT.create_collection(
  86. name=collection_name, embedding_function=sentence_transformer_ef
  87. )
  88. else:
  89. # for local development use the default model
  90. collection = CHROMA_CLIENT.create_collection(name=collection_name)
  91. collection.add(
  92. documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
  93. )
  94. return True
  95. except Exception as e:
  96. print(e)
  97. if e.__class__.__name__ == "UniqueConstraintError":
  98. return True
  99. return False
  100. @app.get("/")
  101. async def get_status():
  102. return {
  103. "status": True,
  104. "chunk_size": app.state.CHUNK_SIZE,
  105. "chunk_overlap": app.state.CHUNK_OVERLAP,
  106. }
  107. @app.get("/chunk")
  108. async def get_chunk_params(user=Depends(get_admin_user)):
  109. return {
  110. "status": True,
  111. "chunk_size": app.state.CHUNK_SIZE,
  112. "chunk_overlap": app.state.CHUNK_OVERLAP,
  113. }
  114. class ChunkParamUpdateForm(BaseModel):
  115. chunk_size: int
  116. chunk_overlap: int
  117. @app.post("/chunk/update")
  118. async def update_chunk_params(
  119. form_data: ChunkParamUpdateForm, user=Depends(get_admin_user)
  120. ):
  121. app.state.CHUNK_SIZE = form_data.chunk_size
  122. app.state.CHUNK_OVERLAP = form_data.chunk_overlap
  123. return {
  124. "status": True,
  125. "chunk_size": app.state.CHUNK_SIZE,
  126. "chunk_overlap": app.state.CHUNK_OVERLAP,
  127. }
  128. @app.get("/template")
  129. async def get_rag_template(user=Depends(get_current_user)):
  130. return {
  131. "status": True,
  132. "template": app.state.RAG_TEMPLATE,
  133. }
  134. class RAGTemplateForm(BaseModel):
  135. template: str
  136. @app.post("/template/update")
  137. async def update_rag_template(form_data: RAGTemplateForm, user=Depends(get_admin_user)):
  138. # TODO: check template requirements
  139. app.state.RAG_TEMPLATE = (
  140. form_data.template if form_data.template != "" else RAG_TEMPLATE
  141. )
  142. return {"status": True, "template": app.state.RAG_TEMPLATE}
  143. class QueryDocForm(BaseModel):
  144. collection_name: str
  145. query: str
  146. k: Optional[int] = 4
  147. @app.post("/query/doc")
  148. def query_doc(
  149. form_data: QueryDocForm,
  150. user=Depends(get_current_user),
  151. ):
  152. try:
  153. if RAG_EMBEDDING_MODEL:
  154. # if you use docker use the model from the environment variable
  155. collection = CHROMA_CLIENT.get_collection(
  156. name=form_data.collection_name,
  157. embedding_function=sentence_transformer_ef,
  158. )
  159. else:
  160. # for local development use the default model
  161. collection = CHROMA_CLIENT.get_collection(
  162. name=form_data.collection_name,
  163. )
  164. result = collection.query(query_texts=[form_data.query], n_results=form_data.k)
  165. return result
  166. except Exception as e:
  167. print(e)
  168. raise HTTPException(
  169. status_code=status.HTTP_400_BAD_REQUEST,
  170. detail=ERROR_MESSAGES.DEFAULT(e),
  171. )
  172. class QueryCollectionsForm(BaseModel):
  173. collection_names: List[str]
  174. query: str
  175. k: Optional[int] = 4
  176. def merge_and_sort_query_results(query_results, k):
  177. # Initialize lists to store combined data
  178. combined_ids = []
  179. combined_distances = []
  180. combined_metadatas = []
  181. combined_documents = []
  182. # Combine data from each dictionary
  183. for data in query_results:
  184. combined_ids.extend(data["ids"][0])
  185. combined_distances.extend(data["distances"][0])
  186. combined_metadatas.extend(data["metadatas"][0])
  187. combined_documents.extend(data["documents"][0])
  188. # Create a list of tuples (distance, id, metadata, document)
  189. combined = list(
  190. zip(combined_distances, combined_ids, combined_metadatas, combined_documents)
  191. )
  192. # Sort the list based on distances
  193. combined.sort(key=lambda x: x[0])
  194. # Unzip the sorted list
  195. sorted_distances, sorted_ids, sorted_metadatas, sorted_documents = zip(*combined)
  196. # Slicing the lists to include only k elements
  197. sorted_distances = list(sorted_distances)[:k]
  198. sorted_ids = list(sorted_ids)[:k]
  199. sorted_metadatas = list(sorted_metadatas)[:k]
  200. sorted_documents = list(sorted_documents)[:k]
  201. # Create the output dictionary
  202. merged_query_results = {
  203. "ids": [sorted_ids],
  204. "distances": [sorted_distances],
  205. "metadatas": [sorted_metadatas],
  206. "documents": [sorted_documents],
  207. "embeddings": None,
  208. "uris": None,
  209. "data": None,
  210. }
  211. return merged_query_results
  212. @app.post("/query/collection")
  213. def query_collection(
  214. form_data: QueryCollectionsForm,
  215. user=Depends(get_current_user),
  216. ):
  217. results = []
  218. for collection_name in form_data.collection_names:
  219. try:
  220. if RAG_EMBEDDING_MODEL:
  221. # if you use docker use the model from the environment variable
  222. collection = CHROMA_CLIENT.get_collection(
  223. name=collection_name,
  224. embedding_function=sentence_transformer_ef,
  225. )
  226. else:
  227. # for local development use the default model
  228. collection = CHROMA_CLIENT.get_collection(
  229. name=collection_name,
  230. )
  231. result = collection.query(
  232. query_texts=[form_data.query], n_results=form_data.k
  233. )
  234. results.append(result)
  235. except:
  236. pass
  237. return merge_and_sort_query_results(results, form_data.k)
  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)
  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)
  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 file_content_type.find("text/") >= 0:
  330. loader = TextLoader(file_path)
  331. else:
  332. loader = TextLoader(file_path)
  333. known_type = False
  334. return loader, known_type
  335. @app.post("/doc")
  336. def store_doc(
  337. collection_name: Optional[str] = Form(None),
  338. file: UploadFile = File(...),
  339. user=Depends(get_current_user),
  340. ):
  341. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  342. print(file.content_type)
  343. try:
  344. filename = file.filename
  345. file_path = f"{UPLOAD_DIR}/{filename}"
  346. contents = file.file.read()
  347. with open(file_path, "wb") as f:
  348. f.write(contents)
  349. f.close()
  350. f = open(file_path, "rb")
  351. if collection_name == None:
  352. collection_name = calculate_sha256(f)[:63]
  353. f.close()
  354. loader, known_type = get_loader(file.filename, file.content_type, file_path)
  355. data = loader.load()
  356. result = store_data_in_vector_db(data, collection_name)
  357. if result:
  358. return {
  359. "status": True,
  360. "collection_name": collection_name,
  361. "filename": filename,
  362. "known_type": known_type,
  363. }
  364. else:
  365. raise HTTPException(
  366. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  367. detail=ERROR_MESSAGES.DEFAULT(),
  368. )
  369. except Exception as e:
  370. print(e)
  371. if "No pandoc was found" in str(e):
  372. raise HTTPException(
  373. status_code=status.HTTP_400_BAD_REQUEST,
  374. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  375. )
  376. else:
  377. raise HTTPException(
  378. status_code=status.HTTP_400_BAD_REQUEST,
  379. detail=ERROR_MESSAGES.DEFAULT(e),
  380. )
  381. @app.get("/scan")
  382. def scan_docs_dir(user=Depends(get_admin_user)):
  383. try:
  384. for path in Path(DOCS_DIR).rglob("./**/*"):
  385. if path.is_file() and not path.name.startswith("."):
  386. tags = extract_folders_after_data_docs(path)
  387. filename = path.name
  388. file_content_type = mimetypes.guess_type(path)
  389. f = open(path, "rb")
  390. collection_name = calculate_sha256(f)[:63]
  391. f.close()
  392. loader, known_type = get_loader(
  393. filename, file_content_type[0], str(path)
  394. )
  395. data = loader.load()
  396. result = store_data_in_vector_db(data, collection_name)
  397. if result:
  398. sanitized_filename = sanitize_filename(filename)
  399. doc = Documents.get_doc_by_name(sanitized_filename)
  400. if doc == None:
  401. doc = Documents.insert_new_doc(
  402. user.id,
  403. DocumentForm(
  404. **{
  405. "name": sanitized_filename,
  406. "title": filename,
  407. "collection_name": collection_name,
  408. "filename": filename,
  409. "content": (
  410. json.dumps(
  411. {
  412. "tags": list(
  413. map(
  414. lambda name: {"name": name},
  415. tags,
  416. )
  417. )
  418. }
  419. )
  420. if len(tags)
  421. else "{}"
  422. ),
  423. }
  424. ),
  425. )
  426. except Exception as e:
  427. print(e)
  428. return True
  429. @app.get("/reset/db")
  430. def reset_vector_db(user=Depends(get_admin_user)):
  431. CHROMA_CLIENT.reset()
  432. @app.get("/reset")
  433. def reset(user=Depends(get_admin_user)) -> bool:
  434. folder = f"{UPLOAD_DIR}"
  435. for filename in os.listdir(folder):
  436. file_path = os.path.join(folder, filename)
  437. try:
  438. if os.path.isfile(file_path) or os.path.islink(file_path):
  439. os.unlink(file_path)
  440. elif os.path.isdir(file_path):
  441. shutil.rmtree(file_path)
  442. except Exception as e:
  443. print("Failed to delete %s. Reason: %s" % (file_path, e))
  444. try:
  445. CHROMA_CLIENT.reset()
  446. except Exception as e:
  447. print(e)
  448. return True