main.py 8.0 KB

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