main.py 19 KB

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