Spaces:
Sleeping
Sleeping
Update app.py
Browse files7 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415512 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132147 unmodified linesimport refrom collections import Counter# --- CONFIGURAÇÃO AVANÇADA ---CONFIG = {"keywords": {"Customer Success": {"terms": ["customer success", "cs", "sucesso do cliente"], "weight": 3, "color": "#4ECDC4"},"CRM": {"terms": ["crm", "salesforce", "hubspot", "zendesk"], "weight": 2.5, "color": "#FF6B6B"},"Atendimento": {"terms": ["atendimento", "suporte", "sac", "serviço ao cliente"], "weight": 2, "color": "#45B7D1"},"Técnicas": {"terms": ["churn", "nps", "onboarding", "retention"], "weight": 1.5, "color": "#A569BD"},"Soft Skills": {"terms": ["comunicação", "empatia", "proatividade", "trabalho em equipe"], "weight": 1, "color": "#F4D03F"}},"thresholds": {"Aderente": 70,"Potencial": 50}}# --- ANÁLISE INTELIGENTE DE CURRÍCULO ---def analyze_resume_content(text):if not text:return {"score": 0, "matches": []}text = text.lower()matches = []total_score = 0# Análise por categoriafor category, config in CONFIG["keywords"].items():for term in config["terms"]:if re.search(rf'\b{term}\b', text):count = len(re.findall(rf'\b{term}\b', text))total_score += config["weight"] * min(count, 3) # Limita repetiçõesmatches.append({"term": term,"category": category,"count": count,"weight": config["weight"]})# Normaliza score (0-10)normalized_score = min(total_score / 3, 10)# Rankeia termos mais relevantestop_matches = sorted(matches, key=lambda x: x["count"] * x["weight"], reverse=True)[:5]return {"score": round(normalized_score, 1),"matches": matches,"top_matches": top_matches,"missing_terms": find_missing_terms(matches)}def find_missing_terms(matches):found_categories = {m["category"] for m in matches}missing = []for category, config in CONFIG["keywords"].items():if category not in found_categories:missing.append({"category": category,"suggestion": f"Adicione termos como: {', '.join(config['terms'][:3])}..."})return missing# --- INTERFACE PREMIUM ---with gr.Blocks(theme=gr.themes.Soft(bg_color="#f5f7ff"), title="🔍 TalentScope CS") as app:# Cabeçalho Personalizadogr.HTML("""<div style="text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);padding: 25px; border-radius: 15px; color: white; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"><h1 style="margin: 0; font-size: 2.2em;">TalentScope CS</h1><p style="opacity: 0.9; font-size: 1.1em;">Análise Inteligente para Estágio em Customer Success</p></div>""")with gr.Row():# Seção de Inputswith gr.Column(scale=1, variant="panel"):gr.Markdown("### 📋 Perfil do Candidato")with gr.Group():tempo_exp = gr.Slider(0, 24, step=1, label="Experiência (meses)",interactive=True, info="Experiência relevante em meses")conhecimento_crm = gr.Slider(1, 5, step=1, label="Conhecimento de CRM",info="Escala de 1 (iniciante) a 5 (especialista)")ingles = gr.Slider(1, 5, step=1, label="Proficiência em Inglês",info="1=Básico, 3=Intermediário, 5=Fluente")graduacao = gr.Radio(["Cursando", "Completo"], label="Graduação",info="Status atual da formação acadêmica")gr.Markdown("### 📎 Análise de Currículo")with gr.Group():curriculo = gr.File(label="Envie seu currículo (PDF)",file_types=[".pdf"],file_count="single")submit_btn = gr.Button("Analisar Candidatura", variant="primary", size="lg")# Seção de Resultadoswith gr.Column(scale=2):with gr.Tab("📊 Resultado Completo"):with gr.Row():with gr.Column(min_width=120):status = gr.Label(label="Status", value="Aguardando análise...")gr.Examples(examples=[["Cursando"], ["Completo"]],inputs=[graduacao],label="Exemplos Rápidos")with gr.Column():with gr.Row():prob_final = gr.Number(label="Probabilidade Final (%)",interactive=False)bonus = gr.Number(label="Bônus do Currículo (%)",interactive=False)# Visualização de Keywordsgr.Markdown("### 🔍 Termos Relevantes Encontrados")keyword_chart = gr.BarPlot(x="category",y="score",title="Distribuição por Categoria",tooltip=["category", "score"],height=300,width=500)# Recomendaçõeswith gr.Accordion("💡 Como melhorar seu currículo", open=False):improvement_tips = gr.JSON(label="Termos Faltantes")# Detalhes Técnicoswith gr.Accordion("🔧 Detalhes da Análise", open=False):gr.Markdown("""**Métricas consideradas:**- Experiência profissional relevante- Conhecimento técnico em ferramentas de CRM- Proficiência em inglês- Adequação do currículo às vagas de CS""")# --- LÓGICA DE PROCESSAMENTO ---def predict_aderencia(tempo_exp, conhecimento_crm, ingles, graduacao, curriculo):try:# Processa currículo12 unmodified linesproba = model.predict_proba(input_data)[0][1] * 100proba_ajustada = min(100, proba + resume_analysis["score"] * 3)# Gera visualização de dadoskeyword_data = pd.DataFrame({"category": [m["category"] for m in resume_analysis["top_matches"]],"score": [m["count"] * m["weight"] for m in resume_analysis["top_matches"]],"color": [CONFIG["keywords"][m["category"]]["color"] for m in resume_analysis["top_matches"]]})# Determina statusif proba_ajustada >= CONFIG["thresholds"]["Aderente"]:status_label = "✅ Aderente"elif proba_ajustada >= CONFIG["thresholds"]["Potencial"]:status_label = "🌟 Potencial"else:status_label = "❌ Não Aderente"return {prob_final: round(proba_ajustada, 1),bonus: round(resume_analysis["score"] * 3, 1),status: status_label,keyword_chart: keyword_data,improvement_tips: resume_analysis["missing_terms"]}except Exception as e:print(f"Erro: {e}")return {status: "⚠️ Erro na análise"}# Conecta o botãosubmit_btn.click(fn=predict_aderencia,inputs=[tempo_exp, conhecimento_crm, ingles, graduacao, curriculo],outputs=[prob_final, bonus, status, keyword_chart, improvement_tips])# --- INICIALIZAÇÃO ---if __name__ == "__main__":try:model = joblib.load('modelo_estagio_cs.joblib')except:# Modelo fallback para desenvolvimentomodel = DecisionTreeClassifier(max_depth=2, random_state=42)model.fit(np.array([[0,0,0,0]]), [0])app.launch(favicon="🔍", server_port=7860)7 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813912 unmodified lines1521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971987 unmodified linesimport refrom collections import Counter# ============== CONFIGURAÇÃO ==============CONFIG = {"keywords": {"Customer Success": {"terms": ["customer success", "cs", "sucesso do cliente"], "weight": 3, "color": "#4ECDC4"},"CRM": {"terms": ["crm", "salesforce", "hubspot", "zendesk"], "weight": 2.5, "color": "#FF6B6B"},"Atendimento": {"terms": ["atendimento", "suporte", "sac", "serviço ao cliente"], "weight": 2, "color": "#45B7D1"},"Métricas": {"terms": ["churn", "nps", "onboarding", "retention"], "weight": 1.5, "color": "#A569BD"},"Soft Skills": {"terms": ["comunicação", "empatia", "proatividade"], "weight": 1, "color": "#F4D03F"}},"thresholds": {"Aderente": 75,"Potencial": 50}}# ============== FUNÇÕES ==============def extract_text_from_pdf(pdf_file):"""Extrai texto de PDFs de forma robusta"""try:if isinstance(pdf_file, bytes):pdf = PdfReader(io.BytesIO(pdf_file))return "\n".join([page.extract_text() or "" for page in pdf.pages])return str(pdf_file)except Exception as e:print(f"Erro ao extrair PDF: {str(e)}")return ""def analyze_resume_content(text):"""Analisa o currículo com pontuação inteligente"""if not text:return {"score": 0, "matches": [], "missing_terms": []}text = text.lower()matches = []# Detecta termos por categoriafor category, config in CONFIG["keywords"].items():for term in config["terms"]:count = len(re.findall(rf'\b{term}\b', text))if count > 0:matches.append({"term": term,"category": category,"count": count,"weight": config["weight"],"score": count * config["weight"]})# Calcula score total (limitado a 10)total_score = min(sum(m["score"] for m in matches) / 3, 10)# Identifica termos faltantesfound_categories = {m["category"] for m in matches}missing_terms = [{"category": cat, "suggestion": f"Adicione: {', '.join(CONFIG['keywords'][cat]['terms'][:2])}"}for cat in CONFIG["keywords"] if cat not in found_categories]return {"score": round(total_score, 1),"matches": matches,"missing_terms": missing_terms}# ============== TEMA E INTERFACE ==============# Tema customizado compatível com Hugging Facecustom_theme = gr.themes.Soft(primary_hue="indigo",secondary_hue="purple").set(body_background_fill="#f5f7ff", # Cor de fundoblock_background_fill="#ffffff", # Cor dos painéisbutton_primary_background_fill="#6e48aa" # Cor do botão)with gr.Blocks(theme=custom_theme, title="🔍 TalentScope CS") as app:# ===== CABEÇALHO =====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>""")# ===== LAYOUT PRINCIPAL =====with gr.Row():# --- COLUNA DE INPUTS ---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")# --- COLUNA DE RESULTADOS ---with gr.Column(scale=2):with gr.Tab("📊 Resultado"):with gr.Row():with gr.Column(min_width=150):status = 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="Probabilidade Base (%)")gr.Markdown("### 🔍 Termos Encontrados")with gr.Row():keyword_display = gr.HighlightedText(label="Palavras-chave",show_legend=True,color_map={cat: cfg["color"] for cat, cfg in CONFIG["keywords"].items()})with gr.Accordion("💡 Como melhorar", open=False):improvement_tips = gr.JSON(label="Termos Faltantes")# ===== LÓGICA DE PREDIÇÃO =====def predict_aderencia(tempo_exp, conhecimento_crm, ingles, graduacao, curriculo):try:# Processa currículo12 unmodified linesproba = model.predict_proba(input_data)[0][1] * 100proba_ajustada = min(100, proba + resume_analysis["score"] * 3)# Formata termos encontradoskeyword_data = [(f"{m['term']} (x{m['count']})", m["category"])for m in resume_analysis["matches"]]# Determina statusstatus_label = ("✅ Aderente" if proba_ajustada >= CONFIG["thresholds"]["Aderente"] else"🌟 Potencial" if proba_ajustada >= CONFIG["thresholds"]["Potencial"] else"❌ Não Aderente")return {status: status_label,prob_final: round(proba_ajustada, 1),prob_base: round(proba, 1),bonus: round(resume_analysis["score"] * 3, 1),keyword_display: keyword_data,improvement_tips: resume_analysis["missing_terms"]}except Exception as e:print(f"Erro: {str(e)}")return {status: "⚠️ Erro na análise"}# Conecta o botãosubmit_btn.click(fn=predict_aderencia,inputs=[tempo_exp, conhecimento_crm, ingles, graduacao, curriculo],outputs=[status, prob_final, prob_base, bonus, keyword_display, improvement_tips])# ============== INICIALIZAÇÃO ==============if __name__ == "__main__":# Carrega o modelo (com fallback para teste)try:model = joblib.load('modelo_estagio_cs.joblib')except:print("⚠️ Usando modelo dummy para teste")model = DecisionTreeClassifier(max_depth=2, random_state=42)model.fit(np.array([[0,0,0,0], [1,1,1,1]]), [0, 1])app.launch(server_port=7860)
app.py+95-111