main.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. def get_loader(file, file_path):
  113. file_ext = file.filename.split(".")[-1].lower()
  114. known_type = True
  115. known_source_ext = [
  116. "go",
  117. "py",
  118. "java",
  119. "sh",
  120. "bat",
  121. "ps1",
  122. "cmd",
  123. "js",
  124. "ts",
  125. "css",
  126. "cpp",
  127. "hpp",
  128. "h",
  129. "c",
  130. "cs",
  131. "sql",
  132. "log",
  133. "ini",
  134. "pl",
  135. "pm",
  136. "r",
  137. "dart",
  138. "dockerfile",
  139. "env",
  140. "php",
  141. "hs",
  142. "hsc",
  143. "lua",
  144. "nginxconf",
  145. "conf",
  146. "m",
  147. "mm",
  148. "plsql",
  149. "perl",
  150. "rb",
  151. "rs",
  152. "db2",
  153. "scala",
  154. "bash",
  155. "swift",
  156. "vue",
  157. "svelte",
  158. ]
  159. if file_ext == "pdf":
  160. loader = PyPDFLoader(file_path)
  161. elif file_ext == "csv":
  162. loader = CSVLoader(file_path)
  163. elif file_ext == "rst":
  164. loader = UnstructuredRSTLoader(file_path, mode="elements")
  165. elif file_ext == "xml":
  166. loader = UnstructuredXMLLoader(file_path)
  167. elif file_ext == "md":
  168. loader = UnstructuredMarkdownLoader(file_path)
  169. elif file.content_type == "application/epub+zip":
  170. loader = UnstructuredEPubLoader(file_path)
  171. elif (
  172. file.content_type
  173. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  174. or file_ext in ["doc", "docx"]
  175. ):
  176. loader = Docx2txtLoader(file_path)
  177. elif file.content_type in [
  178. "application/vnd.ms-excel",
  179. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  180. ] or file_ext in ["xls", "xlsx"]:
  181. loader = UnstructuredExcelLoader(file_path)
  182. elif file_ext in known_source_ext or file.content_type.find("text/") >= 0:
  183. loader = TextLoader(file_path)
  184. else:
  185. loader = TextLoader(file_path)
  186. known_type = False
  187. return loader, known_type
  188. @app.post("/doc")
  189. def store_doc(
  190. collection_name: Optional[str] = Form(None),
  191. file: UploadFile = File(...),
  192. user=Depends(get_current_user),
  193. ):
  194. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  195. print(file.content_type)
  196. try:
  197. filename = file.filename
  198. file_path = f"{UPLOAD_DIR}/{filename}"
  199. contents = file.file.read()
  200. with open(file_path, "wb") as f:
  201. f.write(contents)
  202. f.close()
  203. f = open(file_path, "rb")
  204. if collection_name == None:
  205. collection_name = calculate_sha256(f)[:63]
  206. f.close()
  207. loader, known_type = get_loader(file, file_path)
  208. data = loader.load()
  209. result = store_data_in_vector_db(data, collection_name)
  210. if result:
  211. return {
  212. "status": True,
  213. "collection_name": collection_name,
  214. "filename": filename,
  215. "known_type": known_type,
  216. }
  217. else:
  218. raise HTTPException(
  219. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  220. detail=ERROR_MESSAGES.DEFAULT(),
  221. )
  222. except Exception as e:
  223. print(e)
  224. if "No pandoc was found" in str(e):
  225. raise HTTPException(
  226. status_code=status.HTTP_400_BAD_REQUEST,
  227. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  228. )
  229. else:
  230. raise HTTPException(
  231. status_code=status.HTTP_400_BAD_REQUEST,
  232. detail=ERROR_MESSAGES.DEFAULT(e),
  233. )
  234. @app.get("/reset/db")
  235. def reset_vector_db(user=Depends(get_current_user)):
  236. if user.role == "admin":
  237. CHROMA_CLIENT.reset()
  238. else:
  239. raise HTTPException(
  240. status_code=status.HTTP_403_FORBIDDEN,
  241. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  242. )
  243. @app.get("/reset")
  244. def reset(user=Depends(get_current_user)) -> bool:
  245. if user.role == "admin":
  246. folder = f"{UPLOAD_DIR}"
  247. for filename in os.listdir(folder):
  248. file_path = os.path.join(folder, filename)
  249. try:
  250. if os.path.isfile(file_path) or os.path.islink(file_path):
  251. os.unlink(file_path)
  252. elif os.path.isdir(file_path):
  253. shutil.rmtree(file_path)
  254. except Exception as e:
  255. print("Failed to delete %s. Reason: %s" % (file_path, e))
  256. try:
  257. CHROMA_CLIENT.reset()
  258. except Exception as e:
  259. print(e)
  260. return True
  261. else:
  262. raise HTTPException(
  263. status_code=status.HTTP_403_FORBIDDEN,
  264. detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
  265. )