main.py 5.7 KB

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