main.py 25 KB

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