main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. ):
  406. collection.add(*batch)
  407. return True
  408. except Exception as e:
  409. log.exception(e)
  410. if e.__class__.__name__ == "UniqueConstraintError":
  411. return True
  412. return False
  413. def get_loader(filename: str, file_content_type: str, file_path: str):
  414. file_ext = filename.split(".")[-1].lower()
  415. known_type = True
  416. known_source_ext = [
  417. "go",
  418. "py",
  419. "java",
  420. "sh",
  421. "bat",
  422. "ps1",
  423. "cmd",
  424. "js",
  425. "ts",
  426. "css",
  427. "cpp",
  428. "hpp",
  429. "h",
  430. "c",
  431. "cs",
  432. "sql",
  433. "log",
  434. "ini",
  435. "pl",
  436. "pm",
  437. "r",
  438. "dart",
  439. "dockerfile",
  440. "env",
  441. "php",
  442. "hs",
  443. "hsc",
  444. "lua",
  445. "nginxconf",
  446. "conf",
  447. "m",
  448. "mm",
  449. "plsql",
  450. "perl",
  451. "rb",
  452. "rs",
  453. "db2",
  454. "scala",
  455. "bash",
  456. "swift",
  457. "vue",
  458. "svelte",
  459. ]
  460. if file_ext == "pdf":
  461. loader = PyPDFLoader(file_path, extract_images=app.state.PDF_EXTRACT_IMAGES)
  462. elif file_ext == "csv":
  463. loader = CSVLoader(file_path)
  464. elif file_ext == "rst":
  465. loader = UnstructuredRSTLoader(file_path, mode="elements")
  466. elif file_ext == "xml":
  467. loader = UnstructuredXMLLoader(file_path)
  468. elif file_ext in ["htm", "html"]:
  469. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  470. elif file_ext == "md":
  471. loader = UnstructuredMarkdownLoader(file_path)
  472. elif file_content_type == "application/epub+zip":
  473. loader = UnstructuredEPubLoader(file_path)
  474. elif (
  475. file_content_type
  476. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  477. or file_ext in ["doc", "docx"]
  478. ):
  479. loader = Docx2txtLoader(file_path)
  480. elif file_content_type in [
  481. "application/vnd.ms-excel",
  482. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  483. ] or file_ext in ["xls", "xlsx"]:
  484. loader = UnstructuredExcelLoader(file_path)
  485. elif file_ext in known_source_ext or (
  486. file_content_type and file_content_type.find("text/") >= 0
  487. ):
  488. loader = TextLoader(file_path, autodetect_encoding=True)
  489. else:
  490. loader = TextLoader(file_path, autodetect_encoding=True)
  491. known_type = False
  492. return loader, known_type
  493. @app.post("/doc")
  494. def store_doc(
  495. collection_name: Optional[str] = Form(None),
  496. file: UploadFile = File(...),
  497. user=Depends(get_current_user),
  498. ):
  499. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  500. log.info(f"file.content_type: {file.content_type}")
  501. try:
  502. unsanitized_filename = file.filename
  503. filename = os.path.basename(unsanitized_filename)
  504. file_path = f"{UPLOAD_DIR}/{filename}"
  505. contents = file.file.read()
  506. with open(file_path, "wb") as f:
  507. f.write(contents)
  508. f.close()
  509. f = open(file_path, "rb")
  510. if collection_name == None:
  511. collection_name = calculate_sha256(f)[:63]
  512. f.close()
  513. loader, known_type = get_loader(filename, file.content_type, file_path)
  514. data = loader.load()
  515. try:
  516. result = store_data_in_vector_db(data, collection_name)
  517. if result:
  518. return {
  519. "status": True,
  520. "collection_name": collection_name,
  521. "filename": filename,
  522. "known_type": known_type,
  523. }
  524. except Exception as e:
  525. raise HTTPException(
  526. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  527. detail=e,
  528. )
  529. except Exception as e:
  530. log.exception(e)
  531. if "No pandoc was found" in str(e):
  532. raise HTTPException(
  533. status_code=status.HTTP_400_BAD_REQUEST,
  534. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  535. )
  536. else:
  537. raise HTTPException(
  538. status_code=status.HTTP_400_BAD_REQUEST,
  539. detail=ERROR_MESSAGES.DEFAULT(e),
  540. )
  541. class TextRAGForm(BaseModel):
  542. name: str
  543. content: str
  544. collection_name: Optional[str] = None
  545. @app.post("/text")
  546. def store_text(
  547. form_data: TextRAGForm,
  548. user=Depends(get_current_user),
  549. ):
  550. collection_name = form_data.collection_name
  551. if collection_name == None:
  552. collection_name = calculate_sha256_string(form_data.content)
  553. result = store_text_in_vector_db(
  554. form_data.content,
  555. metadata={"name": form_data.name, "created_by": user.id},
  556. collection_name=collection_name,
  557. )
  558. if result:
  559. return {"status": True, "collection_name": collection_name}
  560. else:
  561. raise HTTPException(
  562. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  563. detail=ERROR_MESSAGES.DEFAULT(),
  564. )
  565. @app.get("/scan")
  566. def scan_docs_dir(user=Depends(get_admin_user)):
  567. for path in Path(DOCS_DIR).rglob("./**/*"):
  568. try:
  569. if path.is_file() and not path.name.startswith("."):
  570. tags = extract_folders_after_data_docs(path)
  571. filename = path.name
  572. file_content_type = mimetypes.guess_type(path)
  573. f = open(path, "rb")
  574. collection_name = calculate_sha256(f)[:63]
  575. f.close()
  576. loader, known_type = get_loader(
  577. filename, file_content_type[0], str(path)
  578. )
  579. data = loader.load()
  580. try:
  581. result = store_data_in_vector_db(data, collection_name)
  582. if result:
  583. sanitized_filename = sanitize_filename(filename)
  584. doc = Documents.get_doc_by_name(sanitized_filename)
  585. if doc == None:
  586. doc = Documents.insert_new_doc(
  587. user.id,
  588. DocumentForm(
  589. **{
  590. "name": sanitized_filename,
  591. "title": filename,
  592. "collection_name": collection_name,
  593. "filename": filename,
  594. "content": (
  595. json.dumps(
  596. {
  597. "tags": list(
  598. map(
  599. lambda name: {"name": name},
  600. tags,
  601. )
  602. )
  603. }
  604. )
  605. if len(tags)
  606. else "{}"
  607. ),
  608. }
  609. ),
  610. )
  611. except Exception as e:
  612. log.exception(e)
  613. pass
  614. except Exception as e:
  615. log.exception(e)
  616. return True
  617. @app.get("/reset/db")
  618. def reset_vector_db(user=Depends(get_admin_user)):
  619. CHROMA_CLIENT.reset()
  620. @app.get("/reset")
  621. def reset(user=Depends(get_admin_user)) -> bool:
  622. folder = f"{UPLOAD_DIR}"
  623. for filename in os.listdir(folder):
  624. file_path = os.path.join(folder, filename)
  625. try:
  626. if os.path.isfile(file_path) or os.path.islink(file_path):
  627. os.unlink(file_path)
  628. elif os.path.isdir(file_path):
  629. shutil.rmtree(file_path)
  630. except Exception as e:
  631. log.error("Failed to delete %s. Reason: %s" % (file_path, e))
  632. try:
  633. CHROMA_CLIENT.reset()
  634. except Exception as e:
  635. log.exception(e)
  636. return True