Spaces:
Sleeping
Sleeping
Download app.py from Crislene/TalentScopeCS: direct link, hf CLI and curl.
- Browser
- Download file 7.5 kB
-
https://huggingface.co/spaces/Crislene/TalentScopeCS/resolve/main/app.py
- Command line
-
hf download hf://spaces/Crislene/TalentScopeCS/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Crislene/TalentScopeCS/resolve/main/app.py
7.5 kB
| 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() | |