main.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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(name=collection_name)
  49. collection.add(
  50. documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
  51. )
  52. return True
  53. except Exception as e:
  54. print(e)
  55. if e.__class__.__name__ == "UniqueConstraintError":
  56. return True
  57. return False
  58. @app.get("/")
  59. async def get_status():
  60. return {"status": True}
  61. @app.get("/query/{collection_name}")
  62. def query_collection(
  63. collection_name: str,
  64. query: str,
  65. k: Optional[int] = 4,
  66. user=Depends(get_current_user),
  67. ):
  68. try:
  69. collection = CHROMA_CLIENT.get_collection(
  70. name=collection_name,
  71. )
  72. result = collection.query(query_texts=[query], n_results=k)
  73. return result
  74. except Exception as e:
  75. print(e)
  76. raise HTTPException(
  77. status_code=status.HTTP_400_BAD_REQUEST,
  78. detail=ERROR_MESSAGES.DEFAULT(e),
  79. )
  80. @app.post("/web")
  81. def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
  82. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  83. try:
  84. loader = WebBaseLoader(form_data.url)
  85. data = loader.load()
  86. store_data_in_vector_db(data, form_data.collection_name)
  87. return {"status": True, "collection_name": form_data.collection_name}
  88. except Exception as e:
  89. print(e)
  90. raise HTTPException(
  91. status_code=status.HTTP_400_BAD_REQUEST,
  92. detail=ERROR_MESSAGES.DEFAULT(e),
  93. )
  94. @app.post("/doc")
  95. def store_doc(
  96. collection_name: str = Form(...),
  97. file: UploadFile = File(...),
  98. user=Depends(get_current_user),
  99. ):
  100. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  101. file.filename = f"{collection_name}-{file.filename}"
  102. if file.content_type not in ["application/pdf", "text/plain"]:
  103. raise HTTPException(
  104. status_code=status.HTTP_400_BAD_REQUEST,
  105. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  106. )
  107. try:
  108. filename = file.filename
  109. file_path = f"{UPLOAD_DIR}/{filename}"
  110. contents = file.file.read()
  111. with open(file_path, "wb") as f:
  112. f.write(contents)
  113. f.close()
  114. if file.content_type == "application/pdf":
  115. loader = PyPDFLoader(file_path)
  116. elif file.content_type == "text/plain":
  117. loader = TextLoader(file_path)
  118. data = loader.load()
  119. result = store_data_in_vector_db(data, collection_name)
  120. if result:
  121. return {"status": True, "collection_name": collection_name}
  122. else:
  123. raise HTTPException(
  124. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  125. detail=ERROR_MESSAGES.DEFAULT(),
  126. )
  127. except Exception as e:
  128. print(e)
  129. raise HTTPException(
  130. status_code=status.HTTP_400_BAD_REQUEST,
  131. detail=ERROR_MESSAGES.DEFAULT(e),
  132. )
  133. @app.get("/reset/db")
  134. def reset_vector_db(user=Depends(get_current_user)):
  135. if user.role == "admin":
  136. CHROMA_CLIENT.reset()
  137. else:
  138. raise HTTPException(
  139. status_code=status.HTTP_403_FORBIDDEN,
  140. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  141. )
  142. @app.get("/reset")
  143. def reset(user=Depends(get_current_user)):
  144. if user.role == "admin":
  145. folder = f"{UPLOAD_DIR}"
  146. for filename in os.listdir(folder):
  147. file_path = os.path.join(folder, filename)
  148. try:
  149. if os.path.isfile(file_path) or os.path.islink(file_path):
  150. os.unlink(file_path)
  151. elif os.path.isdir(file_path):
  152. shutil.rmtree(file_path)
  153. except Exception as e:
  154. print("Failed to delete %s. Reason: %s" % (file_path, e))
  155. try:
  156. CHROMA_CLIENT.reset()
  157. except Exception as e:
  158. print(e)
  159. return {"status": True}
  160. else:
  161. raise HTTPException(
  162. status_code=status.HTTP_403_FORBIDDEN,
  163. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  164. )