main.py 20 KB

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