main.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. from fastapi import (
  2. FastAPI,
  3. Request,
  4. Depends,
  5. HTTPException,
  6. status,
  7. UploadFile,
  8. File,
  9. Form,
  10. )
  11. from fastapi.middleware.cors import CORSMiddleware
  12. import os, shutil
  13. # from chromadb.utils import embedding_functions
  14. from langchain_community.document_loaders import (
  15. WebBaseLoader,
  16. TextLoader,
  17. PyPDFLoader,
  18. CSVLoader,
  19. Docx2txtLoader,
  20. )
  21. from langchain.text_splitter import RecursiveCharacterTextSplitter
  22. from langchain_community.vectorstores import Chroma
  23. from langchain.chains import RetrievalQA
  24. from pydantic import BaseModel
  25. from typing import Optional
  26. import uuid
  27. import time
  28. from utils.misc import calculate_sha256
  29. from utils.utils import get_current_user
  30. from config import UPLOAD_DIR, EMBED_MODEL, CHROMA_CLIENT, CHUNK_SIZE, CHUNK_OVERLAP
  31. from constants import ERROR_MESSAGES
  32. # EMBEDDING_FUNC = embedding_functions.SentenceTransformerEmbeddingFunction(
  33. # model_name=EMBED_MODEL
  34. # )
  35. app = FastAPI()
  36. origins = ["*"]
  37. app.add_middleware(
  38. CORSMiddleware,
  39. allow_origins=origins,
  40. allow_credentials=True,
  41. allow_methods=["*"],
  42. allow_headers=["*"],
  43. )
  44. class CollectionNameForm(BaseModel):
  45. collection_name: Optional[str] = "test"
  46. class StoreWebForm(CollectionNameForm):
  47. url: str
  48. def store_data_in_vector_db(data, collection_name) -> bool:
  49. text_splitter = RecursiveCharacterTextSplitter(
  50. chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP
  51. )
  52. docs = text_splitter.split_documents(data)
  53. texts = [doc.page_content for doc in docs]
  54. metadatas = [doc.metadata for doc in docs]
  55. try:
  56. collection = CHROMA_CLIENT.create_collection(name=collection_name)
  57. collection.add(
  58. documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
  59. )
  60. return True
  61. except Exception as e:
  62. print(e)
  63. if e.__class__.__name__ == "UniqueConstraintError":
  64. return True
  65. return False
  66. @app.get("/")
  67. async def get_status():
  68. return {"status": True}
  69. @app.get("/query/{collection_name}")
  70. def query_collection(
  71. collection_name: str,
  72. query: str,
  73. k: Optional[int] = 4,
  74. user=Depends(get_current_user),
  75. ):
  76. try:
  77. collection = CHROMA_CLIENT.get_collection(
  78. name=collection_name,
  79. )
  80. result = collection.query(query_texts=[query], n_results=k)
  81. return result
  82. except Exception as e:
  83. print(e)
  84. raise HTTPException(
  85. status_code=status.HTTP_400_BAD_REQUEST,
  86. detail=ERROR_MESSAGES.DEFAULT(e),
  87. )
  88. @app.post("/web")
  89. def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
  90. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  91. try:
  92. loader = WebBaseLoader(form_data.url)
  93. data = loader.load()
  94. store_data_in_vector_db(data, form_data.collection_name)
  95. return {
  96. "status": True,
  97. "collection_name": form_data.collection_name,
  98. "filename": form_data.url,
  99. }
  100. except Exception as e:
  101. print(e)
  102. raise HTTPException(
  103. status_code=status.HTTP_400_BAD_REQUEST,
  104. detail=ERROR_MESSAGES.DEFAULT(e),
  105. )
  106. @app.post("/doc")
  107. def store_doc(
  108. collection_name: Optional[str] = Form(None),
  109. file: UploadFile = File(...),
  110. user=Depends(get_current_user),
  111. ):
  112. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  113. if file.content_type not in [
  114. "application/pdf",
  115. "text/plain",
  116. "text/csv",
  117. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  118. ]:
  119. raise HTTPException(
  120. status_code=status.HTTP_400_BAD_REQUEST,
  121. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  122. )
  123. try:
  124. filename = file.filename
  125. file_path = f"{UPLOAD_DIR}/{filename}"
  126. contents = file.file.read()
  127. with open(file_path, "wb") as f:
  128. f.write(contents)
  129. f.close()
  130. f = open(file_path, "rb")
  131. if collection_name == None:
  132. collection_name = calculate_sha256(f)[:63]
  133. f.close()
  134. if file.content_type == "application/pdf":
  135. loader = PyPDFLoader(file_path)
  136. elif (
  137. file.content_type
  138. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  139. ):
  140. loader = Docx2txtLoader(file_path)
  141. elif file.content_type == "text/plain":
  142. loader = TextLoader(file_path)
  143. elif file.content_type == "text/csv":
  144. loader = CSVLoader(file_path)
  145. data = loader.load()
  146. result = store_data_in_vector_db(data, collection_name)
  147. if result:
  148. return {
  149. "status": True,
  150. "collection_name": collection_name,
  151. "filename": filename,
  152. }
  153. else:
  154. raise HTTPException(
  155. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  156. detail=ERROR_MESSAGES.DEFAULT(),
  157. )
  158. except Exception as e:
  159. print(e)
  160. raise HTTPException(
  161. status_code=status.HTTP_400_BAD_REQUEST,
  162. detail=ERROR_MESSAGES.DEFAULT(e),
  163. )
  164. @app.get("/reset/db")
  165. def reset_vector_db(user=Depends(get_current_user)):
  166. if user.role == "admin":
  167. CHROMA_CLIENT.reset()
  168. else:
  169. raise HTTPException(
  170. status_code=status.HTTP_403_FORBIDDEN,
  171. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  172. )
  173. @app.get("/reset")
  174. def reset(user=Depends(get_current_user)) -> bool:
  175. if user.role == "admin":
  176. folder = f"{UPLOAD_DIR}"
  177. for filename in os.listdir(folder):
  178. file_path = os.path.join(folder, filename)
  179. try:
  180. if os.path.isfile(file_path) or os.path.islink(file_path):
  181. os.unlink(file_path)
  182. elif os.path.isdir(file_path):
  183. shutil.rmtree(file_path)
  184. except Exception as e:
  185. print("Failed to delete %s. Reason: %s" % (file_path, e))
  186. try:
  187. CHROMA_CLIENT.reset()
  188. except Exception as e:
  189. print(e)
  190. return True
  191. else:
  192. raise HTTPException(
  193. status_code=status.HTTP_403_FORBIDDEN,
  194. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  195. )