main.py 5.6 KB

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