main.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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. continue_on_failure=True,
  482. )
  483. def validate_url(url: Union[str, Sequence[str]]):
  484. if isinstance(url, str):
  485. if isinstance(validators.url(url), validators.ValidationError):
  486. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  487. if not ENABLE_RAG_LOCAL_WEB_FETCH:
  488. # Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
  489. parsed_url = urllib.parse.urlparse(url)
  490. # Get IPv4 and IPv6 addresses
  491. ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
  492. # Check if any of the resolved addresses are private
  493. # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
  494. for ip in ipv4_addresses:
  495. if validators.ipv4(ip, private=True):
  496. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  497. for ip in ipv6_addresses:
  498. if validators.ipv6(ip, private=True):
  499. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  500. return True
  501. elif isinstance(url, Sequence):
  502. return all(validate_url(u) for u in url)
  503. else:
  504. return False
  505. def resolve_hostname(hostname):
  506. # Get address information
  507. addr_info = socket.getaddrinfo(hostname, None)
  508. # Extract IP addresses from address information
  509. ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
  510. ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
  511. return ipv4_addresses, ipv6_addresses
  512. @app.post("/websearch")
  513. def store_websearch(form_data: SearchForm, user=Depends(get_current_user)):
  514. try:
  515. try:
  516. web_results = search_web(form_data.query)
  517. except Exception as e:
  518. log.exception(e)
  519. raise HTTPException(
  520. status_code=status.HTTP_400_BAD_REQUEST,
  521. detail=ERROR_MESSAGES.WEB_SEARCH_ERROR,
  522. )
  523. urls = [result.link for result in web_results]
  524. loader = get_web_loader(urls)
  525. data = loader.aload()
  526. collection_name = form_data.collection_name
  527. if collection_name == "":
  528. collection_name = calculate_sha256_string(form_data.query)[:63]
  529. store_data_in_vector_db(data, collection_name, overwrite=True)
  530. return {
  531. "status": True,
  532. "collection_name": collection_name,
  533. "filenames": urls,
  534. }
  535. except Exception as e:
  536. log.exception(e)
  537. raise HTTPException(
  538. status_code=status.HTTP_400_BAD_REQUEST,
  539. detail=ERROR_MESSAGES.DEFAULT(e),
  540. )
  541. def store_data_in_vector_db(data, collection_name, overwrite: bool = False) -> bool:
  542. text_splitter = RecursiveCharacterTextSplitter(
  543. chunk_size=app.state.CHUNK_SIZE,
  544. chunk_overlap=app.state.CHUNK_OVERLAP,
  545. add_start_index=True,
  546. )
  547. docs = text_splitter.split_documents(data)
  548. if len(docs) > 0:
  549. log.info(f"store_data_in_vector_db {docs}")
  550. return store_docs_in_vector_db(docs, collection_name, overwrite), None
  551. else:
  552. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  553. def store_text_in_vector_db(
  554. text, metadata, collection_name, overwrite: bool = False
  555. ) -> bool:
  556. text_splitter = RecursiveCharacterTextSplitter(
  557. chunk_size=app.state.CHUNK_SIZE,
  558. chunk_overlap=app.state.CHUNK_OVERLAP,
  559. add_start_index=True,
  560. )
  561. docs = text_splitter.create_documents([text], metadatas=[metadata])
  562. return store_docs_in_vector_db(docs, collection_name, overwrite)
  563. def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> bool:
  564. log.info(f"store_docs_in_vector_db {docs} {collection_name}")
  565. texts = [doc.page_content for doc in docs]
  566. metadatas = [doc.metadata for doc in docs]
  567. try:
  568. if overwrite:
  569. for collection in CHROMA_CLIENT.list_collections():
  570. if collection_name == collection.name:
  571. log.info(f"deleting existing collection {collection_name}")
  572. CHROMA_CLIENT.delete_collection(name=collection_name)
  573. collection = CHROMA_CLIENT.create_collection(name=collection_name)
  574. embedding_func = get_embedding_function(
  575. app.state.RAG_EMBEDDING_ENGINE,
  576. app.state.RAG_EMBEDDING_MODEL,
  577. app.state.sentence_transformer_ef,
  578. app.state.OPENAI_API_KEY,
  579. app.state.OPENAI_API_BASE_URL,
  580. )
  581. embedding_texts = list(map(lambda x: x.replace("\n", " "), texts))
  582. embeddings = embedding_func(embedding_texts)
  583. for batch in create_batches(
  584. api=CHROMA_CLIENT,
  585. ids=[str(uuid.uuid4()) for _ in texts],
  586. metadatas=metadatas,
  587. embeddings=embeddings,
  588. documents=texts,
  589. ):
  590. collection.add(*batch)
  591. return True
  592. except Exception as e:
  593. log.exception(e)
  594. if e.__class__.__name__ == "UniqueConstraintError":
  595. return True
  596. return False
  597. def get_loader(filename: str, file_content_type: str, file_path: str):
  598. file_ext = filename.split(".")[-1].lower()
  599. known_type = True
  600. known_source_ext = [
  601. "go",
  602. "py",
  603. "java",
  604. "sh",
  605. "bat",
  606. "ps1",
  607. "cmd",
  608. "js",
  609. "ts",
  610. "css",
  611. "cpp",
  612. "hpp",
  613. "h",
  614. "c",
  615. "cs",
  616. "sql",
  617. "log",
  618. "ini",
  619. "pl",
  620. "pm",
  621. "r",
  622. "dart",
  623. "dockerfile",
  624. "env",
  625. "php",
  626. "hs",
  627. "hsc",
  628. "lua",
  629. "nginxconf",
  630. "conf",
  631. "m",
  632. "mm",
  633. "plsql",
  634. "perl",
  635. "rb",
  636. "rs",
  637. "db2",
  638. "scala",
  639. "bash",
  640. "swift",
  641. "vue",
  642. "svelte",
  643. ]
  644. if file_ext == "pdf":
  645. loader = PyPDFLoader(file_path, extract_images=app.state.PDF_EXTRACT_IMAGES)
  646. elif file_ext == "csv":
  647. loader = CSVLoader(file_path)
  648. elif file_ext == "rst":
  649. loader = UnstructuredRSTLoader(file_path, mode="elements")
  650. elif file_ext == "xml":
  651. loader = UnstructuredXMLLoader(file_path)
  652. elif file_ext in ["htm", "html"]:
  653. loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
  654. elif file_ext == "md":
  655. loader = UnstructuredMarkdownLoader(file_path)
  656. elif file_content_type == "application/epub+zip":
  657. loader = UnstructuredEPubLoader(file_path)
  658. elif (
  659. file_content_type
  660. == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  661. or file_ext in ["doc", "docx"]
  662. ):
  663. loader = Docx2txtLoader(file_path)
  664. elif file_content_type in [
  665. "application/vnd.ms-excel",
  666. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  667. ] or file_ext in ["xls", "xlsx"]:
  668. loader = UnstructuredExcelLoader(file_path)
  669. elif file_ext in known_source_ext or (
  670. file_content_type and file_content_type.find("text/") >= 0
  671. ):
  672. loader = TextLoader(file_path, autodetect_encoding=True)
  673. else:
  674. loader = TextLoader(file_path, autodetect_encoding=True)
  675. known_type = False
  676. return loader, known_type
  677. @app.post("/doc")
  678. def store_doc(
  679. collection_name: Optional[str] = Form(None),
  680. file: UploadFile = File(...),
  681. user=Depends(get_current_user),
  682. ):
  683. # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
  684. log.info(f"file.content_type: {file.content_type}")
  685. try:
  686. unsanitized_filename = file.filename
  687. filename = os.path.basename(unsanitized_filename)
  688. file_path = f"{UPLOAD_DIR}/{filename}"
  689. contents = file.file.read()
  690. with open(file_path, "wb") as f:
  691. f.write(contents)
  692. f.close()
  693. f = open(file_path, "rb")
  694. if collection_name == None:
  695. collection_name = calculate_sha256(f)[:63]
  696. f.close()
  697. loader, known_type = get_loader(filename, file.content_type, file_path)
  698. data = loader.load()
  699. try:
  700. result = store_data_in_vector_db(data, collection_name)
  701. if result:
  702. return {
  703. "status": True,
  704. "collection_name": collection_name,
  705. "filename": filename,
  706. "known_type": known_type,
  707. }
  708. except Exception as e:
  709. raise HTTPException(
  710. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  711. detail=e,
  712. )
  713. except Exception as e:
  714. log.exception(e)
  715. if "No pandoc was found" in str(e):
  716. raise HTTPException(
  717. status_code=status.HTTP_400_BAD_REQUEST,
  718. detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
  719. )
  720. else:
  721. raise HTTPException(
  722. status_code=status.HTTP_400_BAD_REQUEST,
  723. detail=ERROR_MESSAGES.DEFAULT(e),
  724. )
  725. class TextRAGForm(BaseModel):
  726. name: str
  727. content: str
  728. collection_name: Optional[str] = None
  729. @app.post("/text")
  730. def store_text(
  731. form_data: TextRAGForm,
  732. user=Depends(get_current_user),
  733. ):
  734. collection_name = form_data.collection_name
  735. if collection_name == None:
  736. collection_name = calculate_sha256_string(form_data.content)
  737. result = store_text_in_vector_db(
  738. form_data.content,
  739. metadata={"name": form_data.name, "created_by": user.id},
  740. collection_name=collection_name,
  741. )
  742. if result:
  743. return {"status": True, "collection_name": collection_name}
  744. else:
  745. raise HTTPException(
  746. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  747. detail=ERROR_MESSAGES.DEFAULT(),
  748. )
  749. @app.get("/scan")
  750. def scan_docs_dir(user=Depends(get_admin_user)):
  751. for path in Path(DOCS_DIR).rglob("./**/*"):
  752. try:
  753. if path.is_file() and not path.name.startswith("."):
  754. tags = extract_folders_after_data_docs(path)
  755. filename = path.name
  756. file_content_type = mimetypes.guess_type(path)
  757. f = open(path, "rb")
  758. collection_name = calculate_sha256(f)[:63]
  759. f.close()
  760. loader, known_type = get_loader(
  761. filename, file_content_type[0], str(path)
  762. )
  763. data = loader.load()
  764. try:
  765. result = store_data_in_vector_db(data, collection_name)
  766. if result:
  767. sanitized_filename = sanitize_filename(filename)
  768. doc = Documents.get_doc_by_name(sanitized_filename)
  769. if doc == None:
  770. doc = Documents.insert_new_doc(
  771. user.id,
  772. DocumentForm(
  773. **{
  774. "name": sanitized_filename,
  775. "title": filename,
  776. "collection_name": collection_name,
  777. "filename": filename,
  778. "content": (
  779. json.dumps(
  780. {
  781. "tags": list(
  782. map(
  783. lambda name: {"name": name},
  784. tags,
  785. )
  786. )
  787. }
  788. )
  789. if len(tags)
  790. else "{}"
  791. ),
  792. }
  793. ),
  794. )
  795. except Exception as e:
  796. log.exception(e)
  797. pass
  798. except Exception as e:
  799. log.exception(e)
  800. return True
  801. @app.get("/reset/db")
  802. def reset_vector_db(user=Depends(get_admin_user)):
  803. CHROMA_CLIENT.reset()
  804. @app.get("/reset")
  805. def reset(user=Depends(get_admin_user)) -> bool:
  806. folder = f"{UPLOAD_DIR}"
  807. for filename in os.listdir(folder):
  808. file_path = os.path.join(folder, filename)
  809. try:
  810. if os.path.isfile(file_path) or os.path.islink(file_path):
  811. os.unlink(file_path)
  812. elif os.path.isdir(file_path):
  813. shutil.rmtree(file_path)
  814. except Exception as e:
  815. log.error("Failed to delete %s. Reason: %s" % (file_path, e))
  816. try:
  817. CHROMA_CLIENT.reset()
  818. except Exception as e:
  819. log.exception(e)
  820. return True