main.py 7.3 KB

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