main.py 20 KB

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