main.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 {"status": True, "collection_name": form_data.collection_name}
  96. except Exception as e:
  97. print(e)
  98. raise HTTPException(
  99. status_code=status.HTTP_400_BAD_REQUEST,
  100. detail=ERROR_MESSAGES.DEFAULT(e),
  101. )
  102. @app.post("/doc")
  103. def store_doc(
  104. collection_name: Optional[str] = Form(None),
  105. file: UploadFile = File(...),
  106. user=Depends(get_current_user),
  107. ):
  108. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  109. if file.content_type not in [
  110. "application/pdf",
  111. "text/plain",
  112. "text/csv",
  113. "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  114. ]:
  115. raise HTTPException(
  116. status_code=status.HTTP_400_BAD_REQUEST,
  117. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  118. )
  119. try:
  120. filename = file.filename
  121. file_path = f"{UPLOAD_DIR}/{filename}"
  122. contents = file.file.read()
  123. with open(file_path, "wb") as f:
  124. f.write(contents)
  125. f.close()
  126. f = open(file_path, "rb")
  127. if collection_name == None:
  128. collection_name = calculate_sha256(f)[:63]
  129. f.close()
  130. if file.content_type == "application/pdf":
  131. loader = PyPDFLoader(file_path)
  132. elif (
  133. file.content_type
  134. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  135. ):
  136. loader = Docx2txtLoader(file_path)
  137. elif file.content_type == "text/plain":
  138. loader = TextLoader(file_path)
  139. elif file.content_type == "text/csv":
  140. loader = CSVLoader(file_path)
  141. data = loader.load()
  142. result = store_data_in_vector_db(data, collection_name)
  143. if result:
  144. return {"status": True, "collection_name": collection_name}
  145. else:
  146. raise HTTPException(
  147. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  148. detail=ERROR_MESSAGES.DEFAULT(),
  149. )
  150. except Exception as e:
  151. print(e)
  152. raise HTTPException(
  153. status_code=status.HTTP_400_BAD_REQUEST,
  154. detail=ERROR_MESSAGES.DEFAULT(e),
  155. )
  156. @app.get("/reset/db")
  157. def reset_vector_db(user=Depends(get_current_user)):
  158. if user.role == "admin":
  159. CHROMA_CLIENT.reset()
  160. else:
  161. raise HTTPException(
  162. status_code=status.HTTP_403_FORBIDDEN,
  163. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  164. )
  165. @app.get("/reset")
  166. def reset(user=Depends(get_current_user)) -> bool:
  167. if user.role == "admin":
  168. folder = f"{UPLOAD_DIR}"
  169. for filename in os.listdir(folder):
  170. file_path = os.path.join(folder, filename)
  171. try:
  172. if os.path.isfile(file_path) or os.path.islink(file_path):
  173. os.unlink(file_path)
  174. elif os.path.isdir(file_path):
  175. shutil.rmtree(file_path)
  176. except Exception as e:
  177. print("Failed to delete %s. Reason: %s" % (file_path, e))
  178. try:
  179. CHROMA_CLIENT.reset()
  180. except Exception as e:
  181. print(e)
  182. return True
  183. else:
  184. raise HTTPException(
  185. status_code=status.HTTP_403_FORBIDDEN,
  186. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  187. )