Spaces:
Sleeping

File size: 7,800 Bytes
4163472
 
 
 
 
 
 
 
 
 
 
c0039da
 
 
 
 
 
 
fc667f6
c0039da
 
 
4163472
 
 
 
 
9941a48
 
 
 
 
208225e
 
 
 
 
0caf71c
c996980
c8540db
29da96d
c0039da
5501c1e
 
 
 
 
db4fae0
7040141
 
 
 
 
9941a48
7040141
208225e
7040141
971015b
5501c1e
b5308fd
5501c1e
208225e
e334f31
208225e
 
5501c1e
208225e
 
5501c1e
 
208225e
432fcc6
208225e
971015b
d13b0de
7040141
9941a48
 
7040141
 
208225e
7040141
db4fae0
208225e
da5587e
9941a48
 
aa92ea1
c0039da
aa92ea1
 
 
 
b5308fd
c8540db
208225e
7040141
 
208225e
08dc6a8
208225e
9ca2988
432fcc6
208225e
e334f31
 
b5308fd
 
 
c996980
e334f31
447486e
5501c1e
aa92ea1
c0039da
ed9f29d
208225e
971015b
e334f31
208225e
 
 
e334f31
208225e
971015b
208225e
75beb5f
c0039da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75beb5f
c0039da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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()