Spaces:
Sleeping
Sleeping
Download app.py from ExcelenciaSC/Mentor-PCE: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/spaces/ExcelenciaSC/Mentor-PCE/resolve/main/app.py
- Command line
-
hf download hf://spaces/ExcelenciaSC/Mentor-PCE/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ExcelenciaSC/Mentor-PCE/resolve/main/app.py
7.8 kB
| import os | |
| import gradio as gr | |
| from langchain_community.document_loaders import TextLoader | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| from langchain_community.vectorstores import FAISS | |
| from langchain_community.embeddings import HuggingFaceEmbeddings | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| from langchain_core.prompts import PromptTemplate | |
| from langchain_core.runnables import RunnablePassthrough | |
| from langchain_core.output_parsers import StrOutputParser | |
| # 1. SEGURANÇA E CONFIGURAÇÃO | |
| api_key = os.getenv("GOOGLE_API_KEY") | |
| LOGO_URL = "https://static.wixstatic.com/media/079714_ebe1ed3afbe24a3084883e0dfb0d01e8~mv2.png/v1/fill/w_295,h_62,al_c,q_85,usm_0.66_1.00_0.01,enc_avif,quality_auto/079714_ebe1ed3afbe24a3084883e0dfb0d01e8~mv2.png" # COLOQUE O LINK DA SUA LOGO AQUI | |
| # Dados de acesso (Pode adicionar quantos quiser) | |
| CREDENCIAIS = { | |
| "diretoria": "pce2026", | |
| "avaliador": "pce2026" | |
| } | |
| ## 2. CONFIGURAÇÃO - INSIRA SUA CHAVE | |
| api_key = "AIzaSyATTsTcxU4LiLLnAPTLSbCM_i5VrzuxbDA" | |
| # PROMPT FOCADO EM VARRER GRANDES VOLUMES (5.000 PÁGINAS) | |
| template = """Você é o Especialista PCE 2026". | |
| Você está analisando manuais técnicos extensos. | |
| INSTRUÇÕES DE RESPOSTA: | |
| 1. O contexto abaixo contém trechos dos manuais técnicos. A informação pode aparecer repetida, mas você deve consolidar uma resposta clara. | |
| 2. Pesquise detalhadamente por termos como "Fundamentos", "Processos", "detalhamentos" ou o tema específico da pergunta. | |
| 3. Responda APENAS com base nos documentos fornecidos. Se não encontrar, informe que o dado não consta nos manuais do {nivel_selecionado}. | |
| 4. Use uma linguagem formal e organize em tópicos. | |
| NÍVEL SELECIONADO: {nivel_selecionado} | |
| CONTEXTO RECUPERADO: | |
| {context} | |
| PERGUNTA: {question} | |
| RESPOSTA TÉCNICA DETALHADA:""" | |
| PROMPT = PromptTemplate.from_template(template) | |
| vector_db = None | |
| # 3. FUNÇÃO DE SINCRONIZAÇÃO (OTIMIZADA PARA VOLUME MASSIVO) | |
| def atualizar_documentos(forçar=False): | |
| global vector_db | |
| caminho_base = "documentos" | |
| pasta_db = "faiss_index" | |
| try: | |
| embeddings = HuggingFaceEmbeddings( | |
| model_name="sentence-transformers/all-MiniLM-L6-v2", | |
| model_kwargs={'device': 'cpu'} | |
| ) | |
| if os.path.exists(os.path.join(pasta_db, "index.faiss")) and not forçar: | |
| vector_db = FAISS.load_local(pasta_db, embeddings, allow_dangerous_deserialization=True) | |
| return "⚡ Conectado ao Cache!" | |
| if not os.path.exists(caminho_base): | |
| return f"❌ Pasta '{caminho_base}' não encontrada." | |
| documentos = [] | |
| arquivos = [f for f in os.listdir(caminho_base) if f.endswith(".txt")] | |
| if not arquivos: | |
| return "⚠️ Nenhum .txt encontrado." | |
| for arq in arquivos: | |
| loader = TextLoader(os.path.join(caminho_base, arq), encoding='utf-8') | |
| documentos.extend(loader.load()) | |
| # CHUNKS GRANDES PARA NÃO PERDER O CONTEXTO EM 5 MIL PÁGINAS | |
| splitter = RecursiveCharacterTextSplitter(chunk_size=4000, chunk_overlap=200) | |
| chunks = splitter.split_documents(documentos) | |
| vector_db = FAISS.from_documents(chunks, embeddings) | |
| if not os.path.exists(pasta_db): | |
| os.makedirs(pasta_db) | |
| vector_db.save_local(pasta_db) | |
| return f"✅ Sincronizado: {len(chunks)} blocos de texto processados." | |
| except Exception as e: | |
| return f"❌ Erro: {str(e)}" | |
| def format_docs(docs): | |
| return "\n\n".join(doc.page_content for doc in docs) | |
| # 4. FUNÇÃO DE RESPOSTA (BUSCA PROFUNDA K=20) | |
| def responder(message, history, nivel): | |
| global vector_db | |
| if vector_db is None: | |
| atualizar_documentos() | |
| if vector_db is None: | |
| return "Banco de dados vazio. Clique em Sincronizar." | |
| try: | |
| # Usando 1.5-flash que é mais robusto para contextos longos | |
| llm = ChatGoogleGenerativeAI(model="gemini-flash-latest", temperature=0.1, google_api_key=api_key) | |
| # K=10 para garantir que ele "atropele" a introdução e chegue no conteúdo técnico | |
| retriever = vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 7}) | |
| chain = ( | |
| {"context": retriever | format_docs, "question": RunnablePassthrough(), "nivel_selecionado": lambda x: nivel} | |
| | PROMPT | |
| | llm | |
| | StrOutputParser() | |
| ) | |
| return chain.invoke(message) | |
| except Exception as e: | |
| return f"⚠️ Erro: {str(e)}" | |
| # 5. INTERFACE | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 🛡️ Consultor Sênior PCE 2026") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| nivel = gr.Radio(["Nível I", "Nível II", "Nível III"], label="Nível", value="Nível I") | |
| btn = gr.Button("🔄 Sincronizar Manuais", variant="primary") | |
| status = gr.Markdown("Status: Pronto") | |
| with gr.Column(scale=3): | |
| chat = gr.ChatInterface(fn=responder, additional_inputs=[nivel]) | |
| btn.click(lambda: atualizar_documentos(forçar=True), outputs=status) | |
| # 6. INTERFACE COM CSS CUSTOMIZADO | |
| with gr.Blocks(theme=gr.themes.Soft(), title="PCE 2026 - Consultor") as demo: | |
| # Estado para controlar se o usuário está logado | |
| logged_in = gr.State(False) | |
| # TELA DE LOGIN | |
| with gr.Column(visible=True) as login_screen: | |
| gr.HTML(f""" | |
| <div style="text-align: center; padding: 40px;"> | |
| <img src="{LOGO_URL}" style="max-width: 200px; margin-bottom: 20px;"> | |
| <h1 style="color: #2d3436;">Sistema de ExcelênciaSC PCE 2026</h1> | |
| <p style="color: #636e72;">Área Restrita aos Consultores e Avaliadores</p> | |
| </div> | |
| """) | |
| with gr.Row(variant="compact"): | |
| with gr.Column(scale=1): | |
| pass # Espaçador | |
| with gr.Column(scale=2): | |
| user_input = gr.Textbox(label="Usuário", placeholder="Digite seu usuário...") | |
| pass_input = gr.Textbox(label="Senha", type="password", placeholder="Digite sua senha...") | |
| login_btn = gr.Button("Acessar Consultor", variant="primary") | |
| login_error = gr.Markdown("", visible=False) | |
| with gr.Column(scale=1): | |
| pass # Espaçador | |
| # TELA DO CONSULTOR (ESCONDIDA POR PADRÃO) | |
| with gr.Column(visible=False) as main_screen: | |
| gr.HTML(f""" | |
| <div style="display: flex; align-items: center; gap: 20px; border-bottom: 2px solid #eee; padding-bottom: 10px;"> | |
| <img src="{LOGO_URL}" style="max-height: 50px;"> | |
| <h2 style="margin: 0;">Instrutor Sênior PCE 2026</h2> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| nivel = gr.Radio(["Nível I", "Nível II", "Nível III"], label="Filtro de Nível", value="Nível I") | |
| status = gr.Markdown("Status: Conectado") | |
| with gr.Column(scale=3): | |
| chat = gr.ChatInterface(fn=responder, additional_inputs=[nivel]) | |
| # LÓGICA DE TRANSIÇÃO DE TELAS | |
| def realizar_login(user, pwd): | |
| if user in CREDENCIAIS and CREDENCIAIS[user] == pwd: | |
| # Esconde login, mostra chat e define estado como logado | |
| return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False) | |
| else: | |
| return gr.update(visible=True), gr.update(visible=False), gr.update(value="❌ Credenciais inválidas!", visible=True) | |
| login_btn.click( | |
| realizar_login, | |
| inputs=[user_input, pass_input], | |
| outputs=[login_screen, main_screen, login_error] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |