main.py 16 KB

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