main.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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.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 config import UPLOAD_DIR, EMBED_MODEL, CHROMA_CLIENT, CHUNK_SIZE, CHUNK_OVERLAP
  22. from constants import ERROR_MESSAGES
  23. EMBEDDING_FUNC = embedding_functions.SentenceTransformerEmbeddingFunction(
  24. model_name=EMBED_MODEL
  25. )
  26. app = FastAPI()
  27. origins = ["*"]
  28. app.add_middleware(
  29. CORSMiddleware,
  30. allow_origins=origins,
  31. allow_credentials=True,
  32. allow_methods=["*"],
  33. allow_headers=["*"],
  34. )
  35. class CollectionNameForm(BaseModel):
  36. collection_name: Optional[str] = "test"
  37. class StoreWebForm(CollectionNameForm):
  38. url: str
  39. def store_data_in_vector_db(data, collection_name) -> bool:
  40. text_splitter = RecursiveCharacterTextSplitter(
  41. chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP
  42. )
  43. docs = text_splitter.split_documents(data)
  44. texts = [doc.page_content for doc in docs]
  45. metadatas = [doc.metadata for doc in docs]
  46. try:
  47. collection = CHROMA_CLIENT.create_collection(
  48. name=collection_name, embedding_function=EMBEDDING_FUNC
  49. )
  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. print(e.__class__.__name__)
  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(collection_name: str, query: str, k: Optional[int] = 4):
  65. collection = CHROMA_CLIENT.get_collection(
  66. name=collection_name,
  67. )
  68. result = collection.query(query_texts=[query], n_results=k)
  69. return result
  70. @app.post("/web")
  71. def store_web(form_data: StoreWebForm):
  72. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  73. try:
  74. loader = WebBaseLoader(form_data.url)
  75. data = loader.load()
  76. store_data_in_vector_db(data, form_data.collection_name)
  77. return {"status": True, "collection_name": form_data.collection_name}
  78. except Exception as e:
  79. print(e)
  80. raise HTTPException(
  81. status_code=status.HTTP_400_BAD_REQUEST,
  82. detail=ERROR_MESSAGES.DEFAULT(e),
  83. )
  84. @app.post("/doc")
  85. def store_doc(collection_name: str = Form(...), file: UploadFile = File(...)):
  86. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  87. file.filename = f"{uuid.uuid4()}-{file.filename}"
  88. print(dir(file))
  89. print(file.content_type)
  90. if file.content_type not in ["application/pdf", "text/plain"]:
  91. raise HTTPException(
  92. status_code=status.HTTP_400_BAD_REQUEST,
  93. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  94. )
  95. try:
  96. filename = file.filename
  97. file_path = f"{UPLOAD_DIR}/{filename}"
  98. contents = file.file.read()
  99. with open(file_path, "wb") as f:
  100. f.write(contents)
  101. f.close()
  102. if file.content_type == "application/pdf":
  103. loader = PyPDFLoader(file_path)
  104. elif file.content_type == "text/plain":
  105. loader = TextLoader(file_path)
  106. data = loader.load()
  107. result = store_data_in_vector_db(data, collection_name)
  108. if result:
  109. return {"status": True, "collection_name": collection_name}
  110. else:
  111. raise HTTPException(
  112. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  113. detail=ERROR_MESSAGES.DEFAULT(),
  114. )
  115. except Exception as e:
  116. print(e)
  117. raise HTTPException(
  118. status_code=status.HTTP_400_BAD_REQUEST,
  119. detail=ERROR_MESSAGES.DEFAULT(e),
  120. )
  121. @app.get("/reset/db")
  122. def reset_vector_db():
  123. CHROMA_CLIENT.reset()
  124. @app.get("/reset")
  125. def reset():
  126. folder = f"{UPLOAD_DIR}"
  127. for filename in os.listdir(folder):
  128. file_path = os.path.join(folder, filename)
  129. try:
  130. if os.path.isfile(file_path) or os.path.islink(file_path):
  131. os.unlink(file_path)
  132. elif os.path.isdir(file_path):
  133. shutil.rmtree(file_path)
  134. except Exception as e:
  135. print("Failed to delete %s. Reason: %s" % (file_path, e))
  136. try:
  137. CHROMA_CLIENT.reset()
  138. except Exception as e:
  139. print(e)
  140. return {"status": True}