main.py 7.7 KB

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