main.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. 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(collection_name: str, query: str, k: Optional[int] = 4):
  64. collection = CHROMA_CLIENT.get_collection(
  65. name=collection_name,
  66. )
  67. result = collection.query(query_texts=[query], n_results=k)
  68. return result
  69. @app.post("/web")
  70. def store_web(form_data: StoreWebForm):
  71. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  72. try:
  73. loader = WebBaseLoader(form_data.url)
  74. data = loader.load()
  75. store_data_in_vector_db(data, form_data.collection_name)
  76. return {"status": True, "collection_name": form_data.collection_name}
  77. except Exception as e:
  78. print(e)
  79. raise HTTPException(
  80. status_code=status.HTTP_400_BAD_REQUEST,
  81. detail=ERROR_MESSAGES.DEFAULT(e),
  82. )
  83. @app.post("/doc")
  84. def store_doc(collection_name: str = Form(...), file: UploadFile = File(...)):
  85. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  86. file.filename = f"{collection_name}-{file.filename}"
  87. if file.content_type not in ["application/pdf", "text/plain"]:
  88. raise HTTPException(
  89. status_code=status.HTTP_400_BAD_REQUEST,
  90. detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
  91. )
  92. try:
  93. filename = file.filename
  94. file_path = f"{UPLOAD_DIR}/{filename}"
  95. contents = file.file.read()
  96. with open(file_path, "wb") as f:
  97. f.write(contents)
  98. f.close()
  99. if file.content_type == "application/pdf":
  100. loader = PyPDFLoader(file_path)
  101. elif file.content_type == "text/plain":
  102. loader = TextLoader(file_path)
  103. data = loader.load()
  104. result = store_data_in_vector_db(data, collection_name)
  105. if result:
  106. return {"status": True, "collection_name": collection_name}
  107. else:
  108. raise HTTPException(
  109. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  110. detail=ERROR_MESSAGES.DEFAULT(),
  111. )
  112. except Exception as e:
  113. print(e)
  114. raise HTTPException(
  115. status_code=status.HTTP_400_BAD_REQUEST,
  116. detail=ERROR_MESSAGES.DEFAULT(e),
  117. )
  118. @app.get("/reset/db")
  119. def reset_vector_db():
  120. CHROMA_CLIENT.reset()
  121. @app.get("/reset")
  122. def reset():
  123. folder = f"{UPLOAD_DIR}"
  124. for filename in os.listdir(folder):
  125. file_path = os.path.join(folder, filename)
  126. try:
  127. if os.path.isfile(file_path) or os.path.islink(file_path):
  128. os.unlink(file_path)
  129. elif os.path.isdir(file_path):
  130. shutil.rmtree(file_path)
  131. except Exception as e:
  132. print("Failed to delete %s. Reason: %s" % (file_path, e))
  133. try:
  134. CHROMA_CLIENT.reset()
  135. except Exception as e:
  136. print(e)
  137. return {"status": True}