main.py 29 KB

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