main.py 7.7 KB

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