main.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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.batch_utils import create_batches
  15. from langchain_community.document_loaders import (
  16. WebBaseLoader,
  17. TextLoader,
  18. PyPDFLoader,
  19. CSVLoader,
  20. BSHTMLLoader,
  21. Docx2txtLoader,
  22. UnstructuredEPubLoader,
  23. UnstructuredWordDocumentLoader,
  24. UnstructuredMarkdownLoader,
  25. UnstructuredXMLLoader,
  26. UnstructuredRSTLoader,
  27. UnstructuredExcelLoader,
  28. )
  29. from langchain.text_splitter import RecursiveCharacterTextSplitter
  30. from pydantic import BaseModel
  31. from typing import Optional
  32. import mimetypes
  33. import uuid
  34. import json
  35. import sentence_transformers
  36. from apps.web.models.documents import (
  37. Documents,
  38. DocumentForm,
  39. DocumentResponse,
  40. )
  41. from apps.rag.utils import (
  42. get_model_path,
  43. query_embeddings_doc,
  44. query_embeddings_function,
  45. query_embeddings_collection,
  46. )
  47. from utils.misc import (
  48. calculate_sha256,
  49. calculate_sha256_string,
  50. sanitize_filename,
  51. extract_folders_after_data_docs,
  52. )
  53. from utils.utils import get_current_user, get_admin_user
  54. from config import (
  55. SRC_LOG_LEVELS,
  56. UPLOAD_DIR,
  57. DOCS_DIR,
  58. RAG_TOP_K,
  59. RAG_RELEVANCE_THRESHOLD,
  60. RAG_EMBEDDING_ENGINE,
  61. RAG_EMBEDDING_MODEL,
  62. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  63. RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  64. RAG_RERANKING_MODEL,
  65. RAG_RERANKING_MODEL_AUTO_UPDATE,
  66. RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  67. RAG_OPENAI_API_BASE_URL,
  68. RAG_OPENAI_API_KEY,
  69. DEVICE_TYPE,
  70. CHROMA_CLIENT,
  71. CHUNK_SIZE,
  72. CHUNK_OVERLAP,
  73. RAG_TEMPLATE,
  74. )
  75. from constants import ERROR_MESSAGES
  76. log = logging.getLogger(__name__)
  77. log.setLevel(SRC_LOG_LEVELS["RAG"])
  78. app = FastAPI()
  79. app.state.TOP_K = RAG_TOP_K
  80. app.state.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
  81. app.state.CHUNK_SIZE = CHUNK_SIZE
  82. app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
  83. app.state.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
  84. app.state.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
  85. app.state.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
  86. app.state.RAG_TEMPLATE = RAG_TEMPLATE
  87. app.state.OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
  88. app.state.OPENAI_API_KEY = RAG_OPENAI_API_KEY
  89. app.state.PDF_EXTRACT_IMAGES = False
  90. def update_embedding_model(
  91. embedding_model: str,
  92. update_model: bool = False,
  93. ):
  94. if embedding_model and app.state.RAG_EMBEDDING_ENGINE == "":
  95. app.state.sentence_transformer_ef = sentence_transformers.SentenceTransformer(
  96. get_model_path(embedding_model, update_model),
  97. device=DEVICE_TYPE,
  98. trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
  99. )
  100. else:
  101. app.state.sentence_transformer_ef = None
  102. def update_reranking_model(
  103. reranking_model: str,
  104. update_model: bool = False,
  105. ):
  106. if reranking_model:
  107. app.state.sentence_transformer_rf = sentence_transformers.CrossEncoder(
  108. get_model_path(reranking_model, update_model),
  109. device=DEVICE_TYPE,
  110. trust_remote_code=RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
  111. )
  112. else:
  113. app.state.sentence_transformer_rf = None
  114. update_embedding_model(
  115. app.state.RAG_EMBEDDING_MODEL,
  116. RAG_EMBEDDING_MODEL_AUTO_UPDATE,
  117. )
  118. update_reranking_model(
  119. app.state.RAG_RERANKING_MODEL,
  120. RAG_RERANKING_MODEL_AUTO_UPDATE,
  121. )
  122. origins = ["*"]
  123. app.add_middleware(
  124. CORSMiddleware,
  125. allow_origins=origins,
  126. allow_credentials=True,
  127. allow_methods=["*"],
  128. allow_headers=["*"],
  129. )
  130. class CollectionNameForm(BaseModel):
  131. collection_name: Optional[str] = "test"
  132. class StoreWebForm(CollectionNameForm):
  133. url: str
  134. @app.get("/")
  135. async def get_status():
  136. return {
  137. "status": True,
  138. "chunk_size": app.state.CHUNK_SIZE,
  139. "chunk_overlap": app.state.CHUNK_OVERLAP,
  140. "template": app.state.RAG_TEMPLATE,
  141. "embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
  142. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  143. "reranking_model": app.state.RAG_RERANKING_MODEL,
  144. }
  145. @app.get("/embedding")
  146. async def get_embedding_config(user=Depends(get_admin_user)):
  147. return {
  148. "status": True,
  149. "embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
  150. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  151. "openai_config": {
  152. "url": app.state.OPENAI_API_BASE_URL,
  153. "key": app.state.OPENAI_API_KEY,
  154. },
  155. }
  156. @app.get("/reranking")
  157. async def get_reraanking_config(user=Depends(get_admin_user)):
  158. return {"status": True, "reranking_model": app.state.RAG_RERANKING_MODEL}
  159. class OpenAIConfigForm(BaseModel):
  160. url: str
  161. key: str
  162. class EmbeddingModelUpdateForm(BaseModel):
  163. openai_config: Optional[OpenAIConfigForm] = None
  164. embedding_engine: str
  165. embedding_model: str
  166. @app.post("/embedding/update")
  167. async def update_embedding_config(
  168. form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
  169. ):
  170. log.info(
  171. f"Updating embedding model: {app.state.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
  172. )
  173. try:
  174. app.state.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
  175. app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
  176. if app.state.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
  177. if form_data.openai_config != None:
  178. app.state.OPENAI_API_BASE_URL = form_data.openai_config.url
  179. app.state.OPENAI_API_KEY = form_data.openai_config.key
  180. update_embedding_model(app.state.RAG_EMBEDDING_MODEL, True)
  181. return {
  182. "status": True,
  183. "embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
  184. "embedding_model": app.state.RAG_EMBEDDING_MODEL,
  185. "openai_config": {
  186. "url": app.state.OPENAI_API_BASE_URL,
  187. "key": app.state.OPENAI_API_KEY,
  188. },
  189. }
  190. except Exception as e:
  191. log.exception(f"Problem updating embedding model: {e}")
  192. raise HTTPException(
  193. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  194. detail=ERROR_MESSAGES.DEFAULT(e),
  195. )
  196. class RerankingModelUpdateForm(BaseModel):
  197. reranking_model: str
  198. @app.post("/reranking/update")
  199. async def update_reranking_config(
  200. form_data: RerankingModelUpdateForm, user=Depends(get_admin_user)
  201. ):
  202. log.info(
  203. f"Updating reranking model: {app.state.RAG_RERANKING_MODEL} to {form_data.reranking_model}"
  204. )
  205. try:
  206. app.state.RAG_RERANKING_MODEL = form_data.reranking_model
  207. update_reranking_model(app.state.RAG_RERANKING_MODEL, True)
  208. return {
  209. "status": True,
  210. "reranking_model": app.state.RAG_RERANKING_MODEL,
  211. }
  212. except Exception as e:
  213. log.exception(f"Problem updating reranking model: {e}")
  214. raise HTTPException(
  215. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  216. detail=ERROR_MESSAGES.DEFAULT(e),
  217. )
  218. @app.get("/config")
  219. async def get_rag_config(user=Depends(get_admin_user)):
  220. return {
  221. "status": True,
  222. "pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
  223. "chunk": {
  224. "chunk_size": app.state.CHUNK_SIZE,
  225. "chunk_overlap": app.state.CHUNK_OVERLAP,
  226. },
  227. }
  228. class ChunkParamUpdateForm(BaseModel):
  229. chunk_size: int
  230. chunk_overlap: int
  231. class ConfigUpdateForm(BaseModel):
  232. pdf_extract_images: bool
  233. chunk: ChunkParamUpdateForm
  234. @app.post("/config/update")
  235. async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
  236. app.state.PDF_EXTRACT_IMAGES = form_data.pdf_extract_images
  237. app.state.CHUNK_SIZE = form_data.chunk.chunk_size
  238. app.state.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
  239. return {
  240. "status": True,
  241. "pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
  242. "chunk": {
  243. "chunk_size": app.state.CHUNK_SIZE,
  244. "chunk_overlap": app.state.CHUNK_OVERLAP,
  245. },
  246. }
  247. @app.get("/template")
  248. async def get_rag_template(user=Depends(get_current_user)):
  249. return {
  250. "status": True,
  251. "template": app.state.RAG_TEMPLATE,
  252. }
  253. @app.get("/query/settings")
  254. async def get_query_settings(user=Depends(get_admin_user)):
  255. return {
  256. "status": True,
  257. "template": app.state.RAG_TEMPLATE,
  258. "k": app.state.TOP_K,
  259. "r": app.state.RELEVANCE_THRESHOLD,
  260. }
  261. class QuerySettingsForm(BaseModel):
  262. k: Optional[int] = None
  263. r: Optional[float] = None
  264. template: Optional[str] = None
  265. @app.post("/query/settings/update")
  266. async def update_query_settings(
  267. form_data: QuerySettingsForm, user=Depends(get_admin_user)
  268. ):
  269. app.state.RAG_TEMPLATE = form_data.template if form_data.template else RAG_TEMPLATE
  270. app.state.TOP_K = form_data.k if form_data.k else 4
  271. app.state.RELEVANCE_THRESHOLD = form_data.r if form_data.r else 0.0
  272. return {"status": True, "template": app.state.RAG_TEMPLATE}
  273. class QueryDocForm(BaseModel):
  274. collection_name: str
  275. query: str
  276. k: Optional[int] = None
  277. r: Optional[float] = None
  278. @app.post("/query/doc")
  279. def query_doc_handler(
  280. form_data: QueryDocForm,
  281. user=Depends(get_current_user),
  282. ):
  283. try:
  284. embeddings_function = query_embeddings_function(
  285. app.state.RAG_EMBEDDING_ENGINE,
  286. app.state.RAG_EMBEDDING_MODEL,
  287. app.state.sentence_transformer_ef,
  288. app.state.OPENAI_API_KEY,
  289. app.state.OPENAI_API_BASE_URL,
  290. )
  291. return query_embeddings_doc(
  292. collection_name=form_data.collection_name,
  293. query=form_data.query,
  294. k=form_data.k if form_data.k else app.state.TOP_K,
  295. r=form_data.r if form_data.r else app.state.RELEVANCE_THRESHOLD,
  296. embeddings_function=embeddings_function,
  297. reranking_function=app.state.sentence_transformer_rf,
  298. )
  299. except Exception as e:
  300. log.exception(e)
  301. raise HTTPException(
  302. status_code=status.HTTP_400_BAD_REQUEST,
  303. detail=ERROR_MESSAGES.DEFAULT(e),
  304. )
  305. class QueryCollectionsForm(BaseModel):
  306. collection_names: List[str]
  307. query: str
  308. k: Optional[int] = None
  309. r: Optional[float] = None
  310. @app.post("/query/collection")
  311. def query_collection_handler(
  312. form_data: QueryCollectionsForm,
  313. user=Depends(get_current_user),
  314. ):
  315. try:
  316. embeddings_function = embeddings_function(
  317. app.state.RAG_EMBEDDING_ENGINE,
  318. app.state.RAG_EMBEDDING_MODEL,
  319. app.state.sentence_transformer_ef,
  320. app.state.OPENAI_API_KEY,
  321. app.state.OPENAI_API_BASE_URL,
  322. )
  323. return query_embeddings_collection(
  324. collection_names=form_data.collection_names,
  325. query=form_data.query,
  326. k=form_data.k if form_data.k else app.state.TOP_K,
  327. r=form_data.r if form_data.r else app.state.RELEVANCE_THRESHOLD,
  328. embeddings_function=embeddings_function,
  329. reranking_function=app.state.sentence_transformer_rf,
  330. )
  331. except Exception as e:
  332. log.exception(e)
  333. raise HTTPException(
  334. status_code=status.HTTP_400_BAD_REQUEST,
  335. detail=ERROR_MESSAGES.DEFAULT(e),
  336. )
  337. @app.post("/web")
  338. def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
  339. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  340. try:
  341. loader = WebBaseLoader(form_data.url)
  342. data = loader.load()
  343. collection_name = form_data.collection_name
  344. if collection_name == "":
  345. collection_name = calculate_sha256_string(form_data.url)[:63]
  346. store_data_in_vector_db(data, collection_name, overwrite=True)
  347. return {
  348. "status": True,
  349. "collection_name": collection_name,
  350. "filename": form_data.url,
  351. }
  352. except Exception as e:
  353. log.exception(e)
  354. raise HTTPException(
  355. status_code=status.HTTP_400_BAD_REQUEST,
  356. detail=ERROR_MESSAGES.DEFAULT(e),
  357. )
  358. def store_data_in_vector_db(data, collection_name, overwrite: bool = False) -> bool:
  359. text_splitter = RecursiveCharacterTextSplitter(
  360. chunk_size=app.state.CHUNK_SIZE,
  361. chunk_overlap=app.state.CHUNK_OVERLAP,
  362. add_start_index=True,
  363. )
  364. docs = text_splitter.split_documents(data)
  365. if len(docs) > 0:
  366. log.info(f"store_data_in_vector_db {docs}")
  367. return store_docs_in_vector_db(docs, collection_name, overwrite), None
  368. else:
  369. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  370. def store_text_in_vector_db(
  371. text, metadata, collection_name, overwrite: bool = False
  372. ) -> bool:
  373. text_splitter = RecursiveCharacterTextSplitter(
  374. chunk_size=app.state.CHUNK_SIZE,
  375. chunk_overlap=app.state.CHUNK_OVERLAP,
  376. add_start_index=True,
  377. )
  378. docs = text_splitter.create_documents([text], metadatas=[metadata])
  379. return store_docs_in_vector_db(docs, collection_name, overwrite)
  380. def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> bool:
  381. log.info(f"store_docs_in_vector_db {docs} {collection_name}")
  382. texts = [doc.page_content for doc in docs]
  383. metadatas = [doc.metadata for doc in docs]
  384. try:
  385. if overwrite:
  386. for collection in CHROMA_CLIENT.list_collections():
  387. if collection_name == collection.name:
  388. log.info(f"deleting existing collection {collection_name}")
  389. CHROMA_CLIENT.delete_collection(name=collection_name)
  390. collection = CHROMA_CLIENT.create_collection(name=collection_name)
  391. embedding_func = query_embeddings_function(
  392. app.state.RAG_EMBEDDING_ENGINE,
  393. app.state.RAG_EMBEDDING_MODEL,
  394. app.state.sentence_transformer_ef,
  395. app.state.OPENAI_API_KEY,
  396. app.state.OPENAI_API_BASE_URL,
  397. )
  398. embedding_texts = list(map(lambda x: x.replace("\n", " "), texts))
  399. embeddings = embedding_func(embedding_texts)
  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