AdryanAzul's picture
feat: deploy DocuMind AI (RAG + BYOK + local embeddings)
68e8c03 verified
Raw History Blame Contribute Delete
10.6 kB
"""Interface web BYOK do DocuMind AI utilizando Streamlit com isolamento por sessão."""
import os
import secrets
import tempfile
from pathlib import Path
import streamlit as st
from dotenv import load_dotenv
from src.document_loader import DocumentLoadError
from src.embeddings import EmbeddingLoadError, EmbeddingModel
from src.llm import BYOKLLM, LLMConfigError, LLMMode, sanitize_sensitive_text
from src.rag_pipeline import RAGPipeline
load_dotenv()
st.set_page_config(
page_title="DocuMind AI",
page_icon="📄",
layout="wide",
)
MODE_LABELS: dict[str, LLMMode] = {
"Modo Gemini": "gemini",
"Modo Groq": "groq",
"Modo Gemini + fallback Groq": "gemini_groq",
}
@st.cache_resource(show_spinner="Carregando modelo local de embeddings (all-MiniLM-L6-v2)...")
def get_embedding_model() -> EmbeddingModel:
"""Carrega o modelo SentenceTransformer uma única vez por processo."""
return EmbeddingModel()
def _resolve_session_storage(session_id: str) -> tuple[Path, str]:
"""Define diretório e coleção isolados por sessão em ambiente multiusuário."""
if os.getenv("SPACE_ID"):
base_dir = Path(tempfile.gettempdir()) / "documind_sessions" / session_id
return base_dir, f"session_{session_id[:16]}"
persist_dir = Path(os.getenv("CHROMA_PERSIST_DIR", "data/chroma_db"))
return persist_dir, f"session_{session_id[:16]}"
def init_session_state() -> None:
"""Inicializa estado isolado da sessão atual."""
if "session_id" not in st.session_state:
st.session_state.session_id = secrets.token_urlsafe(24)
if "messages" not in st.session_state:
st.session_state.messages = []
if "byok_mode_label" not in st.session_state:
st.session_state.byok_mode_label = "Modo Gemini"
if "byok_gemini_key" not in st.session_state:
st.session_state.byok_gemini_key = ""
if "byok_groq_key" not in st.session_state:
st.session_state.byok_groq_key = ""
def get_pipeline() -> RAGPipeline:
"""Obtém ou cria o pipeline RAG exclusivo da sessão atual."""
if "pipeline" not in st.session_state:
persist_dir, collection_name = _resolve_session_storage(st.session_state.session_id)
st.session_state.pipeline = RAGPipeline(
persist_directory=persist_dir,
collection_name=collection_name,
embedding_model=get_embedding_model(),
)
return st.session_state.pipeline
def clear_session_credentials(pipeline: RAGPipeline) -> None:
"""Remove credenciais da sessão atual em memória."""
st.session_state.byok_gemini_key = ""
st.session_state.byok_groq_key = ""
pipeline.set_llm(None)
def render_sources(sources: list[dict[str, object]]) -> None:
"""Exibe as fontes (documento, página e trecho) em um bloco expansível."""
if not sources:
return
with st.expander(f"📚 Fontes consultadas ({len(sources)})", expanded=False):
for src in sources:
st.markdown(f"**{src['source']}** — Página `{src['page']}`")
st.caption(str(src["excerpt"]))
def main() -> None:
init_session_state()
try:
pipeline = get_pipeline()
except EmbeddingLoadError as exc:
st.error(f"Erro ao inicializar o modelo local de embeddings: {exc}")
st.stop()
with st.sidebar:
st.title("📄 DocuMind AI")
st.caption("RAG com embeddings locais e arquitetura BYOK (suas próprias chaves).")
st.divider()
# Configuração BYOK (sem uso de chaves do proprietário)
st.subheader("🔑 Credenciais (BYOK)")
mode_label = st.radio(
"Modo de geração",
options=list(MODE_LABELS.keys()),
key="byok_mode_label",
)
selected_mode: LLMMode = MODE_LABELS[mode_label]
if selected_mode in ("gemini", "gemini_groq"):
st.text_input(
"GEMINI_API_KEY",
type="password",
key="byok_gemini_key",
placeholder="Cole sua chave da Google Gemini API",
)
if selected_mode in ("groq", "gemini_groq"):
st.text_input(
"GROQ_API_KEY",
type="password",
key="byok_groq_key",
placeholder="Cole sua chave da Groq API",
)
if st.button("Limpar credenciais", use_container_width=True):
clear_session_credentials(pipeline)
st.rerun()
st.divider()
# Upload e indexação de PDFs
uploaded_files = st.file_uploader(
"Envie seus arquivos PDF (máx. 20 MB cada)",
type=["pdf"],
accept_multiple_files=True,
help="Os documentos são processados localmente e isolados na sua sessão.",
)
if st.button(
"Processar documentos",
type="primary",
use_container_width=True,
disabled=not uploaded_files,
):
total_chunks = 0
errors: list[str] = []
with st.status("Processando PDFs com embeddings locais...", expanded=True) as status:
for uploaded_file in uploaded_files or []:
st.write(f"Indexando `{uploaded_file.name}`...")
try:
uploaded_file.seek(0)
chunks_added = pipeline.index_pdf(uploaded_file, filename=uploaded_file.name)
total_chunks += chunks_added
st.write(f"✅ `{uploaded_file.name}` ({chunks_added} trechos)")
except DocumentLoadError as exc:
errors.append(str(exc))
st.write(f"⚠️ {exc}")
except Exception as exc:
errors.append(f"Erro inesperado ao processar '{uploaded_file.name}': {exc}")
st.write(f"❌ Erro em `{uploaded_file.name}`")
if total_chunks > 0 and not errors:
status.update(label=f"Concluído! {total_chunks} trechos indexados.", state="complete")
elif total_chunks > 0:
status.update(label=f"Finalizado com avisos ({total_chunks} trechos).", state="complete")
else:
status.update(label="Nenhum trecho foi indexado.", state="error")
st.divider()
indexed_sources = pipeline.list_indexed_sources()
st.subheader("Documentos da sessão")
if indexed_sources:
for source_name in indexed_sources:
st.markdown(f"- `{source_name}`")
else:
st.caption("Nenhum documento indexado nesta sessão.")
if os.getenv("SPACE_ID"):
st.caption(
"ℹ️ Sessão isolada em armazenamento temporário no Hugging Face Spaces."
)
top_k = st.slider(
"Trechos recuperados por pergunta",
min_value=3,
max_value=5,
value=4,
help="Quantidade de trechos mais relevantes enviados como contexto para a LLM.",
)
st.divider()
col_clear_chat, col_clear_db = st.columns(2)
with col_clear_chat:
if st.button("Limpar conversa", use_container_width=True):
st.session_state.messages = []
st.rerun()
with col_clear_db:
if st.button("Limpar base", use_container_width=True, disabled=not indexed_sources):
pipeline.clear_index()
st.rerun()
# Área principal: Chat
st.header("💬 Converse com seus documentos")
st.caption(
"Os embeddings são gerados localmente (`all-MiniLM-L6-v2`). "
"Suas chaves de API ficam apenas na memória da sua sessão."
)
if not st.session_state.messages:
st.info(
"1) Selecione o modo e informe sua chave de API na barra lateral. "
"2) Envie e processe ao menos um PDF. 3) Faça sua pergunta abaixo."
)
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if message.get("used_fallback"):
st.caption("⚡ Resposta gerada via fallback Groq (Gemini temporariamente indisponível).")
if message["role"] == "assistant" and message.get("sources"):
render_sources(message["sources"])
if prompt := st.chat_input("Digite sua pergunta sobre os documentos..."):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
gemini_key = st.session_state.byok_gemini_key if selected_mode in ("gemini", "gemini_groq") else None
groq_key = st.session_state.byok_groq_key if selected_mode in ("groq", "gemini_groq") else None
with st.chat_message("assistant"):
used_fallback = False
sources_payload: list[dict[str, object]] = []
with st.spinner("Buscando trechos relevantes e gerando resposta..."):
try:
llm_client = BYOKLLM(
mode=selected_mode,
gemini_api_key=gemini_key,
groq_api_key=groq_key,
)
pipeline.set_llm(llm_client)
rag_response = pipeline.ask(question=prompt, top_k=top_k)
answer_text = rag_response.answer
used_fallback = rag_response.used_fallback
sources_payload = [
{"source": s.source, "page": s.page, "excerpt": s.excerpt}
for s in rag_response.sources
]
except LLMConfigError as exc:
answer_text = f"⚠️ **Configuração necessária:** {exc}"
except Exception as exc:
safe_err = sanitize_sensitive_text(str(exc), [gemini_key or "", groq_key or ""])
answer_text = f"❌ **Erro na geração da resposta:** {safe_err}"
st.markdown(answer_text)
if used_fallback:
st.caption("⚡ Resposta gerada via fallback Groq (Gemini temporariamente indisponível).")
render_sources(sources_payload)
st.session_state.messages.append(
{
"role": "assistant",
"content": answer_text,
"sources": sources_payload,
"used_fallback": used_fallback,
}
)
if __name__ == "__main__":
main()