main.py 15 KB

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