main.py 27 KB

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