main.py 15 KB

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