main.py 16 KB

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