main.py 7.5 KB

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