main.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. UnstructuredEPubLoader,
  21. UnstructuredWordDocumentLoader,
  22. UnstructuredMarkdownLoader,
  23. UnstructuredXMLLoader,
  24. UnstructuredRSTLoader,
  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. file_ext=file.filename.split(".")[-1].lower()
  131. known_type=True
  132. try:
  133. filename = file.filename
  134. file_path = f"{UPLOAD_DIR}/{filename}"
  135. contents = file.file.read()
  136. with open(file_path, "wb") as f:
  137. f.write(contents)
  138. f.close()
  139. f = open(file_path, "rb")
  140. if collection_name == None:
  141. collection_name = calculate_sha256(f)[:63]
  142. f.close()
  143. if file_ext=="pdf":
  144. loader = PyPDFLoader(file_path)
  145. elif (file.content_type ==docx_type or file_ext in known_doc_ext):
  146. loader = Docx2txtLoader(file_path)
  147. elif file_ext=="csv":
  148. loader = CSVLoader(file_path)
  149. elif file_ext=="rst":
  150. loader = UnstructuredRSTLoader(file_path, mode="elements")
  151. elif file_ext in text_xml:
  152. loader=UnstructuredXMLLoader(file_path)
  153. elif file_ext in known_source_ext or file.content_type.find("text/")>=0:
  154. loader = TextLoader(file_path)
  155. elif file_ext in octet_markdown:
  156. loader = UnstructuredMarkdownLoader(file_path)
  157. elif file.content_type == "application/epub+zip":
  158. loader = UnstructuredEPubLoader(file_path)
  159. else:
  160. loader = TextLoader(file_path)
  161. known_type=False
  162. data = loader.load()
  163. result = store_data_in_vector_db(data, collection_name)
  164. if result:
  165. return {
  166. "status": True,
  167. "collection_name": collection_name,
  168. "filename": filename,
  169. "known_type":known_type,
  170. }
  171. else:
  172. raise HTTPException(
  173. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  174. detail=ERROR_MESSAGES.DEFAULT(),
  175. )
  176. except Exception as e:
  177. print(e)
  178. if "No pandoc was found" in str(e):
  179. raise HTTPException(
  180. status_code=status.HTTP_400_BAD_REQUEST,
  181. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  182. )
  183. else:
  184. raise HTTPException(
  185. status_code=status.HTTP_400_BAD_REQUEST,
  186. detail=ERROR_MESSAGES.DEFAULT(e),
  187. )
  188. @app.get("/reset/db")
  189. def reset_vector_db(user=Depends(get_current_user)):
  190. if user.role == "admin":
  191. CHROMA_CLIENT.reset()
  192. else:
  193. raise HTTPException(
  194. status_code=status.HTTP_403_FORBIDDEN,
  195. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  196. )
  197. @app.get("/reset")
  198. def reset(user=Depends(get_current_user)) -> bool:
  199. if user.role == "admin":
  200. folder = f"{UPLOAD_DIR}"
  201. for filename in os.listdir(folder):
  202. file_path = os.path.join(folder, filename)
  203. try:
  204. if os.path.isfile(file_path) or os.path.islink(file_path):
  205. os.unlink(file_path)
  206. elif os.path.isdir(file_path):
  207. shutil.rmtree(file_path)
  208. except Exception as e:
  209. print("Failed to delete %s. Reason: %s" % (file_path, e))
  210. try:
  211. CHROMA_CLIENT.reset()
  212. except Exception as e:
  213. print(e)
  214. return True
  215. else:
  216. raise HTTPException(
  217. status_code=status.HTTP_403_FORBIDDEN,
  218. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  219. )