Spaces:
Sleeping
Sleeping
File size: 7,504 Bytes
7114b17 af8ff86 ac03555 af8ff86 ac03555 af8ff86 ae0316a af8ff86 a1ae1dc 93a02c7 a1ae1dc ac03555 af8ff86 a1ae1dc af8ff86 a1ae1dc 3d71964 a1ae1dc ac03555 af8ff86 ac03555 a1ae1dc af8ff86 ac03555 a1ae1dc af8ff86 193f689 a1ae1dc ac03555 af8ff86 1d89d02 ac03555 af8ff86 ac03555 af8ff86 692ff4b a1ae1dc 13b725d a1ae1dc af8ff86 a1ae1dc 13b725d a1ae1dc ac03555 af8ff86 a1ae1dc af8ff86 a1ae1dc 692ff4b a1ae1dc ac03555 a1ae1dc ac03555 a1ae1dc af8ff86 ac03555 a1ae1dc 41898d0 692ff4b a1ae1dc af8ff86 ac03555 a1ae1dc ac03555 a1ae1dc ac03555 af8ff86 ac03555 a1ae1dc af8ff86 1d89d02 ac03555 13b725d 41898d0 13b725d 41898d0 13b725d af8ff86 ac03555 a1ae1dc ac03555 cf675e6 a1ae1dc ac03555 af8ff86 a1ae1dc af8ff86 684788f | 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 | import pandas as pd
import numpy as np
import gradio as gr
from sklearn.tree import DecisionTreeClassifier
from PyPDF2 import PdfReader
import io
import joblib
import re
from collections import Counter
# ============== CONFIGURAÇÃO ==============
CONFIG = {
"palavras-chave": {
"Sucesso do Cliente": {"termos": ["sucesso do cliente", "cs"], "peso": 3, "cor": "#4ECDC4"},
"CRM": {"termos": ["crm", "salesforce", "hubspot", "zendesk"], "peso": 2.5, "cor": "#FF6B6B"},
"Atendimento": {"termos": ["atendimento", "suporte", "sac", "serviço ao cliente"], "peso": 2, "cor": "#45B7D1"},
"Métricas": {"termos": ["churn", "nps", "onboarding", "retention"], "peso": 1.5, "cor": "#A569BD"},
"Soft Skills": {"termos": ["comunicação", "empatia", "proatividade"], "peso": 1, "cor": "#F4D03F"}
},
"limiares": {
"Aderente": 75,
"Potencial": 50
}
}
# ============== FUNÇÕES ==============
def extrair_texto_de_pdf(arquivo_pdf):
try:
if isinstance(arquivo_pdf, bytes):
pdf = PdfReader(io.BytesIO(arquivo_pdf))
return "\n".join([page.extract_text() or "" for page in pdf.pages])
return str(arquivo_pdf)
except Exception as e:
print(f"Erro ao extrair PDF: {str(e)}")
return ""
def analisar_conteudo_do_curriculo(texto):
if not texto:
return {"pontuacao": 0, "correspondencias": [], "termos_ausentes": []}
texto = texto.lower()
correspondencias = []
for categoria, config in CONFIG["palavras-chave"].items():
for termo in config["termos"]:
contagem = len(re.findall(rf'\b{re.escape(termo.lower())}\b', texto.lower()))
if contagem > 0:
correspondencias.append({
"termo": termo,
"categoria": categoria,
"contagem": contagem,
"peso": config["peso"],
"pontuacao": contagem * config["peso"]
})
pontuacao_total = min(sum(m["pontuacao"] for m in correspondencias) / 3, 10)
found_categories = {m["categoria"] for m in correspondencias}
termos_ausentes = [
{"categoria": cat, "sugestao": f"Adição: {', '.join(CONFIG['palavras-chave'][cat]['termos'][:2])}"}
for cat in CONFIG["palavras-chave"] if cat not in found_categories
]
return {
"pontuacao": round(pontuacao_total, 1),
"correspondencias": correspondencias,
"termos_ausentes": termos_ausentes
}
# ============== INTERFACE ==============
tema_personalizado = gr.themes.Soft(
primary_hue="indigo",
secondary_hue="purple"
).set(
body_background_fill="#f5f7ff",
block_background_fill="#ffffff",
button_primary_background_fill="#6e48aa"
)
with gr.Blocks(theme=tema_personalizado, title="🔍 TalentScope CS") as app:
gr.HTML("""
<div style="text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 25px; border-radius: 15px; color: white; margin-bottom: 20px;">
<h1 style="margin: 0;">TalentScope CS</h1>
<p style="opacity: 0.9;">Análise Inteligente para Estágio em Customer Success</p>
</div>
""")
with gr.Row():
with gr.Column(scale=1):
with gr.Group():
gr.Markdown("### 📋 Perfil do Candidato")
tempo_exp = gr.Slider(0, 24, step=1, label="Experiência (meses)")
conhecimento_crm = gr.Slider(1, 5, step=1, label="Conhecimento de CRM")
ingles = gr.Slider(1, 5, step=1, label="Proficiência em Inglês")
graduacao = gr.Radio(["Cursando", "Completo"], label="Graduação")
with gr.Group():
gr.Markdown("### 📎 Currículo")
curriculo = gr.File(label="Envie seu PDF", file_types=[".pdf"])
submit_btn = gr.Button("Analisar", variant="primary")
with gr.Column(scale=2):
with gr.Tab("📊 Resultado"):
with gr.Row():
with gr.Column(min_width=150):
status_output = gr.Label(label="Status")
prob_final = gr.Number(label="Probabilidade Final (%)")
with gr.Column():
bonus = gr.Number(label="Bônus do Currículo (%)")
prob_base = gr.Number(label="Base de Probabilidade (%)")
gr.Markdown("### 🔍 Termos Encontrados")
with gr.Row():
palavra_chave_exibicao = gr.HighlightedText(
label="Palavras-chave",
show_legend=True,
color_map={cat: cfg["cor"] for cat, cfg in CONFIG["palavras-chave"].items()}
)
with gr.Accordion("💡 Como melhorar", open=False):
melhoria_tips = gr.HTML()
def predizer_aderencia(tempo_exp, conhecimento_crm, ingles, graduacao, curriculo):
try:
texto_curriculo = extrair_texto_de_pdf(curriculo) if curriculo else ""
analise_curriculo = analisar_conteudo_do_curriculo(texto_curriculo)
dados_entrada = np.array([[tempo_exp, conhecimento_crm, ingles, 1 if graduacao == "Cursando" else 0]])
proba = modelo.predict_proba(dados_entrada)[0][1] * 100
proba_ajustada = min(100, proba + analise_curriculo["pontuacao"] * 3)
dados_palavra_chave = [
(f"{m['termo']} (x{m['contagem']})", m["categoria"])
for m in analise_curriculo["correspondencias"]
]
rotulo_status = (
"✅ Aderente" if proba_ajustada >= CONFIG["limiares"]["Aderente"] else
"🌟 Potencial" if proba_ajustada >= CONFIG["limiares"]["Potencial"] else
"❌ Não Aderente"
)
melhorias_html = "<ul style='padding-left: 1.2em;'>"
for item in analise_curriculo["termos_ausentes"]:
melhorias_html += f"""
<li style='margin-bottom: 8px;'>
<strong style="color: {CONFIG['palavras-chave'][item['categoria']]['cor']};">
{item['categoria']}:
</strong> {item['sugestao']}
</li>
"""
melhorias_html += "</ul>"
return {
status_output: rotulo_status,
prob_final: round(proba_ajustada, 1),
prob_base: round(proba, 1),
bonus: round(analise_curriculo["pontuacao"] * 3, 1),
palavra_chave_exibicao: dados_palavra_chave,
melhoria_tips: melhorias_html
}
except Exception as e:
print(f"Erro: {str(e)}")
return {status_output: "⚠️ Erro na análise"}
submit_btn.click(
fn=predizer_aderencia,
inputs=[tempo_exp, conhecimento_crm, ingles, graduacao, curriculo],
outputs=[status_output, prob_final, prob_base, bonus, palavra_chave_exibicao, melhoria_tips]
)
# ============== INICIALIZAÇÃO ==============
if __name__ == "__main__":
try:
modelo = joblib.load('modelo_estagio_cs.joblib')
except:
print("⚠️ Usando modelo dummy para teste")
modelo = DecisionTreeClassifier(max_depth=2, random_state=42)
modelo.fit(np.array([[0, 0, 0, 0], [1, 1, 1, 1]]), [0, 1])
app.launch()
|