main.py 16 KB

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