main.py 15 KB

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