main.py 5.5 KB

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