main.py 16 KB

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