main.py 6.8 KB

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