main.py 29 KB

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