main.py 22 KB

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