main.py 5.7 KB

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