main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. from fastapi import (
  2. FastAPI,
  3. Depends,
  4. HTTPException,
  5. status,
  6. UploadFile,
  7. File,
  8. Form,
  9. )
  10. from fastapi.middleware.cors import CORSMiddleware
  11. import os, shutil
  12. from pathlib import Path
  13. from typing import List
  14. from sentence_transformers import SentenceTransformer
  15. from chromadb.utils import embedding_functions
  16. from langchain_community.document_loaders import (
  17. WebBaseLoader,
  18. TextLoader,
  19. PyPDFLoader,
  20. CSVLoader,
  21. Docx2txtLoader,
  22. UnstructuredEPubLoader,
  23. UnstructuredWordDocumentLoader,
  24. UnstructuredMarkdownLoader,
  25. UnstructuredXMLLoader,
  26. UnstructuredRSTLoader,
  27. UnstructuredExcelLoader,
  28. )
  29. from langchain.text_splitter import RecursiveCharacterTextSplitter
  30. from pydantic import BaseModel
  31. from typing import Optional
  32. import mimetypes
  33. import uuid
  34. import json
  35. from apps.web.models.documents import (
  36. Documents,
  37. DocumentForm,
  38. DocumentResponse,
  39. )
  40. from apps.rag.utils import query_doc, query_collection
  41. from utils.misc import (
  42. calculate_sha256,
  43. calculate_sha256_string,
  44. sanitize_filename,
  45. extract_folders_after_data_docs,
  46. )
  47. from utils.utils import get_current_user, get_admin_user
  48. from config import (
  49. UPLOAD_DIR,
  50. DOCS_DIR,
  51. RAG_EMBEDDING_MODEL,
  52. RAG_EMBEDDING_MODEL_DEVICE_TYPE,
  53. CHROMA_CLIENT,
  54. CHUNK_SIZE,
  55. CHUNK_OVERLAP,
  56. RAG_TEMPLATE,
  57. )
  58. from constants import ERROR_MESSAGES
  59. #
  60. # if RAG_EMBEDDING_MODEL:
  61. # sentence_transformer_ef = SentenceTransformer(
  62. # model_name_or_path=RAG_EMBEDDING_MODEL,
  63. # cache_folder=RAG_EMBEDDING_MODEL_DIR,
  64. # device=RAG_EMBEDDING_MODEL_DEVICE_TYPE,
  65. # )
  66. app = FastAPI()
  67. app.state.CHUNK_SIZE = CHUNK_SIZE
  68. app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
  69. app.state.RAG_TEMPLATE = RAG_TEMPLATE
  70. app.state.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  71. app.state.TOP_K = 4
  72. app.state.sentence_transformer_ef = (
  73. embedding_functions.SentenceTransformerEmbeddingFunction(
  74. model_name=app.state.RAG_EMBEDDING_MODEL,
  75. device=RAG_EMBEDDING_MODEL_DEVICE_TYPE,
  76. )
  77. )
  78. origins = ["*"]
  79. app.add_middleware(
  80. CORSMiddleware,
  81. allow_origins=origins,
  82. allow_credentials=True,
  83. allow_methods=["*"],
  84. allow_headers=["*"],
  85. )
  86. class CollectionNameForm(BaseModel):
  87. collection_name: Optional[str] = "test"
  88. class StoreWebForm(CollectionNameForm):
  89. url: str
  90. def store_data_in_vector_db(data, collection_name, overwrite: bool = False) -> bool:
  91. text_splitter = RecursiveCharacterTextSplitter(
  92. chunk_size=app.state.CHUNK_SIZE, chunk_overlap=app.state.CHUNK_OVERLAP
  93. )
  94. docs = text_splitter.split_documents(data)
  95. texts = [doc.page_content for doc in docs]
  96. metadatas = [doc.metadata for doc in docs]
  97. try:
  98. if overwrite:
  99. for collection in CHROMA_CLIENT.list_collections():
  100. if collection_name == collection.name:
  101. print(f"deleting existing collection {collection_name}")
  102. CHROMA_CLIENT.delete_collection(name=collection_name)
  103. collection = CHROMA_CLIENT.create_collection(
  104. name=collection_name,
  105. embedding_function=app.state.sentence_transformer_ef,
  106. )
  107. collection.add(
  108. documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
  109. )
  110. return True
  111. except Exception as e:
  112. print(e)
  113. if e.__class__.__name__ == "UniqueConstraintError":
  114. return True
  115. return False
  116. @app.get("/")
  117. async def get_status():
  118. return {
  119. "status": True,
  120. "chunk_size": app.state.CHUNK_SIZE,
  121. "chunk_overlap": app.state.CHUNK_OVERLAP,
  122. "template": app.state.RAG_TEMPLATE,
  123. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  124. }
  125. @app.get("/embedding/model")
  126. async def get_embedding_model(user=Depends(get_admin_user)):
  127. return {
  128. "status": True,
  129. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  130. }
  131. class EmbeddingModelUpdateForm(BaseModel):
  132. embedding_model: str
  133. @app.post("/embedding/model/update")
  134. async def update_embedding_model(
  135. form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
  136. ):
  137. app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
  138. app.state.sentence_transformer_ef = (
  139. embedding_functions.SentenceTransformerEmbeddingFunction(
  140. model_name=app.state.RAG_EMBEDDING_MODEL,
  141. device=RAG_EMBEDDING_MODEL_DEVICE_TYPE,
  142. )
  143. )
  144. return {
  145. "status": True,
  146. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  147. }
  148. @app.get("/chunk")
  149. async def get_chunk_params(user=Depends(get_admin_user)):
  150. return {
  151. "status": True,
  152. "chunk_size": app.state.CHUNK_SIZE,
  153. "chunk_overlap": app.state.CHUNK_OVERLAP,
  154. }
  155. class ChunkParamUpdateForm(BaseModel):
  156. chunk_size: int
  157. chunk_overlap: int
  158. @app.post("/chunk/update")
  159. async def update_chunk_params(
  160. form_data: ChunkParamUpdateForm, user=Depends(get_admin_user)
  161. ):
  162. app.state.CHUNK_SIZE = form_data.chunk_size
  163. app.state.CHUNK_OVERLAP = form_data.chunk_overlap
  164. return {
  165. "status": True,
  166. "chunk_size": app.state.CHUNK_SIZE,
  167. "chunk_overlap": app.state.CHUNK_OVERLAP,
  168. }
  169. @app.get("/template")
  170. async def get_rag_template(user=Depends(get_current_user)):
  171. return {
  172. "status": True,
  173. "template": app.state.RAG_TEMPLATE,
  174. }
  175. @app.get("/query/settings")
  176. async def get_query_settings(user=Depends(get_admin_user)):
  177. return {
  178. "status": True,
  179. "template": app.state.RAG_TEMPLATE,
  180. "k": app.state.TOP_K,
  181. }
  182. class QuerySettingsForm(BaseModel):
  183. k: Optional[int] = None
  184. template: Optional[str] = None
  185. @app.post("/query/settings/update")
  186. async def update_query_settings(
  187. form_data: QuerySettingsForm, user=Depends(get_admin_user)
  188. ):
  189. app.state.RAG_TEMPLATE = form_data.template if form_data.template else RAG_TEMPLATE
  190. app.state.TOP_K = form_data.k if form_data.k else 4
  191. return {"status": True, "template": app.state.RAG_TEMPLATE}
  192. class QueryDocForm(BaseModel):
  193. collection_name: str
  194. query: str
  195. k: Optional[int] = None
  196. @app.post("/query/doc")
  197. def query_doc_handler(
  198. form_data: QueryDocForm,
  199. user=Depends(get_current_user),
  200. ):
  201. try:
  202. return query_doc(
  203. collection_name=form_data.collection_name,
  204. query=form_data.query,
  205. k=form_data.k if form_data.k else app.state.TOP_K,
  206. embedding_function=app.state.sentence_transformer_ef,
  207. )
  208. except Exception as e:
  209. print(e)
  210. raise HTTPException(
  211. status_code=status.HTTP_400_BAD_REQUEST,
  212. detail=ERROR_MESSAGES.DEFAULT(e),
  213. )
  214. class QueryCollectionsForm(BaseModel):
  215. collection_names: List[str]
  216. query: str
  217. k: Optional[int] = None
  218. @app.post("/query/collection")
  219. def query_collection_handler(
  220. form_data: QueryCollectionsForm,
  221. user=Depends(get_current_user),
  222. ):
  223. return query_collection(
  224. collection_names=form_data.collection_names,
  225. query=form_data.query,
  226. k=form_data.k if form_data.k else app.state.TOP_K,
  227. embedding_function=app.state.sentence_transformer_ef,
  228. )
  229. @app.post("/web")
  230. def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
  231. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  232. try:
  233. loader = WebBaseLoader(form_data.url)
  234. data = loader.load()
  235. collection_name = form_data.collection_name
  236. if collection_name == "":
  237. collection_name = calculate_sha256_string(form_data.url)[:63]
  238. store_data_in_vector_db(data, collection_name, overwrite=True)
  239. return {
  240. "status": True,
  241. "collection_name": collection_name,
  242. "filename": form_data.url,
  243. }
  244. except Exception as e:
  245. print(e)
  246. raise HTTPException(
  247. status_code=status.HTTP_400_BAD_REQUEST,
  248. detail=ERROR_MESSAGES.DEFAULT(e),
  249. )
  250. def get_loader(filename: str, file_content_type: str, file_path: str):
  251. file_ext = filename.split(".")[-1].lower()
  252. known_type = True
  253. known_source_ext = [
  254. "go",
  255. "py",
  256. "java",
  257. "sh",
  258. "bat",
  259. "ps1",
  260. "cmd",
  261. "js",
  262. "ts",
  263. "css",
  264. "cpp",
  265. "hpp",
  266. "h",
  267. "c",
  268. "cs",
  269. "sql",
  270. "log",
  271. "ini",
  272. "pl",
  273. "pm",
  274. "r",
  275. "dart",
  276. "dockerfile",
  277. "env",
  278. "php",
  279. "hs",
  280. "hsc",
  281. "lua",
  282. "nginxconf",
  283. "conf",
  284. "m",
  285. "mm",
  286. "plsql",
  287. "perl",
  288. "rb",
  289. "rs",
  290. "db2",
  291. "scala",
  292. "bash",
  293. "swift",
  294. "vue",
  295. "svelte",
  296. ]
  297. if file_ext == "pdf":
  298. loader = PyPDFLoader(file_path, extract_images=True)
  299. elif file_ext == "csv":
  300. loader = CSVLoader(file_path)
  301. elif file_ext == "rst":
  302. loader = UnstructuredRSTLoader(file_path, mode="elements")
  303. elif file_ext == "xml":
  304. loader = UnstructuredXMLLoader(file_path)
  305. elif file_ext == "md":
  306. loader = UnstructuredMarkdownLoader(file_path)
  307. elif file_content_type == "application/epub+zip":
  308. loader = UnstructuredEPubLoader(file_path)
  309. elif (
  310. file_content_type
  311. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  312. or file_ext in ["doc", "docx"]
  313. ):
  314. loader = Docx2txtLoader(file_path)
  315. elif file_content_type in [
  316. "application/vnd.ms-excel",
  317. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  318. ] or file_ext in ["xls", "xlsx"]:
  319. loader = UnstructuredExcelLoader(file_path)
  320. elif file_ext in known_source_ext or (
  321. file_content_type and file_content_type.find("text/") >= 0
  322. ):
  323. loader = TextLoader(file_path)
  324. else:
  325. loader = TextLoader(file_path)
  326. known_type = False
  327. return loader, known_type
  328. @app.post("/doc")
  329. def store_doc(
  330. collection_name: Optional[str] = Form(None),
  331. file: UploadFile = File(...),
  332. user=Depends(get_current_user),
  333. ):
  334. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  335. print(file.content_type)
  336. try:
  337. filename = file.filename
  338. file_path = f"{UPLOAD_DIR}/{filename}"
  339. contents = file.file.read()
  340. with open(file_path, "wb") as f:
  341. f.write(contents)
  342. f.close()
  343. f = open(file_path, "rb")
  344. if collection_name == None:
  345. collection_name = calculate_sha256(f)[:63]
  346. f.close()
  347. loader, known_type = get_loader(file.filename, file.content_type, file_path)
  348. data = loader.load()
  349. result = store_data_in_vector_db(data, collection_name)
  350. if result:
  351. return {
  352. "status": True,
  353. "collection_name": collection_name,
  354. "filename": filename,
  355. "known_type": known_type,
  356. }
  357. else:
  358. raise HTTPException(
  359. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  360. detail=ERROR_MESSAGES.DEFAULT(),
  361. )
  362. except Exception as e:
  363. print(e)
  364. if "No pandoc was found" in str(e):
  365. raise HTTPException(
  366. status_code=status.HTTP_400_BAD_REQUEST,
  367. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  368. )
  369. else:
  370. raise HTTPException(
  371. status_code=status.HTTP_400_BAD_REQUEST,
  372. detail=ERROR_MESSAGES.DEFAULT(e),
  373. )
  374. @app.get("/scan")
  375. def scan_docs_dir(user=Depends(get_admin_user)):
  376. for path in Path(DOCS_DIR).rglob("./**/*"):
  377. try:
  378. if path.is_file() and not path.name.startswith("."):
  379. tags = extract_folders_after_data_docs(path)
  380. filename = path.name
  381. file_content_type = mimetypes.guess_type(path)
  382. f = open(path, "rb")
  383. collection_name = calculate_sha256(f)[:63]
  384. f.close()
  385. loader, known_type = get_loader(
  386. filename, file_content_type[0], str(path)
  387. )
  388. data = loader.load()
  389. result = store_data_in_vector_db(data, collection_name)
  390. if result:
  391. sanitized_filename = sanitize_filename(filename)
  392. doc = Documents.get_doc_by_name(sanitized_filename)
  393. if doc == None:
  394. doc = Documents.insert_new_doc(
  395. user.id,
  396. DocumentForm(
  397. **{
  398. "name": sanitized_filename,
  399. "title": filename,
  400. "collection_name": collection_name,
  401. "filename": filename,
  402. "content": (
  403. json.dumps(
  404. {
  405. "tags": list(
  406. map(
  407. lambda name: {"name": name},
  408. tags,
  409. )
  410. )
  411. }
  412. )
  413. if len(tags)
  414. else "{}"
  415. ),
  416. }
  417. ),
  418. )
  419. except Exception as e:
  420. print(e)
  421. return True
  422. @app.get("/reset/db")
  423. def reset_vector_db(user=Depends(get_admin_user)):
  424. CHROMA_CLIENT.reset()
  425. @app.get("/reset")
  426. def reset(user=Depends(get_admin_user)) -> bool:
  427. folder = f"{UPLOAD_DIR}"
  428. for filename in os.listdir(folder):
  429. file_path = os.path.join(folder, filename)
  430. try:
  431. if os.path.isfile(file_path) or os.path.islink(file_path):
  432. os.unlink(file_path)
  433. elif os.path.isdir(file_path):
  434. shutil.rmtree(file_path)
  435. except Exception as e:
  436. print("Failed to delete %s. Reason: %s" % (file_path, e))
  437. try:
  438. CHROMA_CLIENT.reset()
  439. except Exception as e:
  440. print(e)
  441. return True