Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import torch
|
| 5 |
+
import gradio as gr
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
|
| 8 |
+
# --- Funções de contexto ---
|
| 9 |
+
def create_context(context_path='juca_context.json'):
|
| 10 |
+
"""
|
| 11 |
+
Cria o arquivo de contexto com informações sobre Juca.
|
| 12 |
+
"""
|
| 13 |
+
main_info = {
|
| 14 |
+
"nome_completo": "Julio Cesar Gomes do Nascimento", "nome_social": "Juca", "idade": 17, "altura": "1,77m",
|
| 15 |
+
"pais_nomes": "Cesar e Fabíola do Nascimento", "cidade": "Carapicuíba", "estado": "São Paulo", "pais": "Brasil",
|
| 16 |
+
"idiomas": ["Português (nativo)", "Inglês (básico)"],
|
| 17 |
+
"conhecimentos_tecnicos": ["Python", "C++", "Desenvolvimento de IA", "Visão Computacional"]
|
| 18 |
+
}
|
| 19 |
+
certificacoes = [
|
| 20 |
+
{"nome": "Python Fundamentos para Análise de Dados 3.0", "instituicao": "Data Science Academy", "concluido": True},
|
| 21 |
+
{"nome": "Fundamentos de Engenharia de Dados", "instituicao": "Data Science Academy", "carga_horaria": "24h", "aproveitamento": "85%", "data_conclusao": "05/05/2023", "concluido": True},
|
| 22 |
+
{"nome": "IA Generativa e LLMs para Processamento de Linguagem Natural", "instituicao": "Data Science Academy", "carga_horaria": "96h", "aproveitamento": "78%", "data_conclusao": "13/04/2025", "concluido": True},
|
| 23 |
+
{"nome": "Deep Learning para Aplicações de Inteligência Artificial com Python e C++", "instituicao": "Data Science Academy", "carga_horaria": "96h", "aproveitamento": "88%", "data_conclusao": "12/02/2025", "concluido": True}
|
| 24 |
+
]
|
| 25 |
+
formacao_atual = {
|
| 26 |
+
"nome": "Formação Engenheiro de Inteligência Artificial 4.0", "instituicao": "Data Science Academy", "status": "Em andamento",
|
| 27 |
+
"cursos_incluidos": ["Deep Learning para Aplicações de Inteligência Artificial com Python e C++", "IA Generativa e LLMs para Processamento de Linguagem Natural", "Inteligência Artificial para Visão Computacional", "Engenharia Financeira com Inteligência Artificial", "Machine Learning com JavaScript e Go", "Data Science e Machine Learning com Linguagem Julia"]
|
| 28 |
+
}
|
| 29 |
+
experiencia = {
|
| 30 |
+
"periodo": "2023-2024", "instituicao": "Projov", "local": "Barueri", "tipo": "Associação",
|
| 31 |
+
"descricao": "Participação em dinâmicas para aprimorar habilidades como oratória, trabalho em equipe, liderança, investimentos e conhecimento sobre o mercado de trabalho",
|
| 32 |
+
"experiencia_trabalho": {"cargo": "Jovem Aprendiz", "area": "Administrativa", "empresa": "Nissha Metallizing Solutions", "tipo_contrato": "Terceirizado", "responsabilidades": "Organização e gerenciamento dos documentos da empresa"}
|
| 33 |
+
}
|
| 34 |
+
context = {"informacoes_pessoais": main_info, "certificacoes": certificacoes, "formacao_atual": formacao_atual, "experiencia_profissional": experiencia}
|
| 35 |
+
|
| 36 |
+
with open(context_path, 'w', encoding='utf-8') as f:
|
| 37 |
+
json.dump(context, f, ensure_ascii=False, indent=4)
|
| 38 |
+
return context
|
| 39 |
+
|
| 40 |
+
def load_context_from_json(context_path="juca_context.json"):
|
| 41 |
+
if not os.path.exists(context_path):
|
| 42 |
+
context_data = create_context(context_path)
|
| 43 |
+
else:
|
| 44 |
+
with open(context_path, 'r', encoding='utf-8') as f:
|
| 45 |
+
context_data = json.load(f)
|
| 46 |
+
|
| 47 |
+
info = context_data.get("informacoes_pessoais", {})
|
| 48 |
+
certificacoes = context_data.get("certificacoes", [])
|
| 49 |
+
formacao = context_data.get("formacao_atual", {})
|
| 50 |
+
experiencia = context_data.get("experiencia_profissional", {})
|
| 51 |
+
exp_trabalho = experiencia.get("experiencia_trabalho", {})
|
| 52 |
+
|
| 53 |
+
context_text = (
|
| 54 |
+
f"Nome completo: {info.get('nome_completo', '')}. Nome social: {info.get('nome_social', '')}. Idade: {info.get('idade', '')} anos. "
|
| 55 |
+
f"Altura: {info.get('altura', '')}. Pais: {info.get('pais_nomes', '')}. Localização: {info.get('cidade', '')}, {info.get('estado', '')}, {info.get('pais', '')}. "
|
| 56 |
+
f"Idiomas: {', '.join(info.get('idiomas', []))}. Conhecimentos técnicos: {', '.join(info.get('conhecimentos_tecnicos', []))}. "
|
| 57 |
+
f"Certificações: {'; '.join([c['nome'] for c in certificacoes])}. "
|
| 58 |
+
f"Formação: {formacao.get('nome', '')} ({formacao.get('instituicao', '')}), Status: {formacao.get('status', '')}. "
|
| 59 |
+
f"Cursos incluídos: {', '.join(formacao.get('cursos_incluidos', []))}. "
|
| 60 |
+
f"Experiência Profissional: {experiencia.get('descricao', '')}. "
|
| 61 |
+
f"Cargo: {exp_trabalho.get('cargo', '')}, Empresa: {exp_trabalho.get('empresa', '')}."
|
| 62 |
+
)
|
| 63 |
+
return context_data, context_text
|
| 64 |
+
|
| 65 |
+
# --- Carregamento do modelo ---
|
| 66 |
+
MODEL_NAME = "pierreguillou/bert-base-cased-squad-v1.1-portuguese"
|
| 67 |
+
context_data, context_text = load_context_from_json()
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
device_num = 0 if torch.cuda.is_available() else -1
|
| 71 |
+
qa_pipeline = pipeline("question-answering", model=MODEL_NAME, tokenizer=MODEL_NAME, device=device_num)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Erro ao carregar o modelo: {e}")
|
| 74 |
+
qa_pipeline = None
|
| 75 |
+
|
| 76 |
+
# --- Função de resposta ---
|
| 77 |
+
def responder_pergunta(pergunta):
|
| 78 |
+
if not pergunta:
|
| 79 |
+
return "Por favor, digite uma pergunta."
|
| 80 |
+
if not context_text:
|
| 81 |
+
return "Erro: contexto não carregado."
|
| 82 |
+
if not qa_pipeline:
|
| 83 |
+
return "Erro: modelo não carregado."
|
| 84 |
+
try:
|
| 85 |
+
result = qa_pipeline(question=pergunta, context=context_text)
|
| 86 |
+
return result['answer']
|
| 87 |
+
except Exception as e:
|
| 88 |
+
return f"Erro durante a inferência: {e}"
|
| 89 |
+
|
| 90 |
+
# --- Interface Gradio ---
|
| 91 |
+
description = """
|
| 92 |
+
# Pergunte sobre Juca!
|
| 93 |
+
Este é um sistema de QA com BERT em português baseado em contexto personalizado.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
context_display = json.dumps(context_data, indent=2, ensure_ascii=False) if context_data else "Contexto indisponível."
|
| 97 |
+
|
| 98 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 99 |
+
gr.Markdown(description)
|
| 100 |
+
with gr.Row():
|
| 101 |
+
with gr.Column(scale=2):
|
| 102 |
+
question_input = gr.Textbox(label="Digite sua pergunta:", placeholder="Ex: Qual a idade de Juca?")
|
| 103 |
+
answer_output = gr.Textbox(label="Resposta:", interactive=False)
|
| 104 |
+
submit_button = gr.Button("Perguntar")
|
| 105 |
+
|
| 106 |
+
submit_button.click(fn=responder_pergunta, inputs=question_input, outputs=answer_output)
|
| 107 |
+
question_input.submit(fn=responder_pergunta, inputs=question_input, outputs=answer_output)
|
| 108 |
+
|
| 109 |
+
demo.queue().launch()
|