Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891091011121314151617181911121314151617181920212223242526272228242526272829303132333435362930313932333442434445353637383940414243444546474849505152535448495556575859605253545556575859606162636465666768697071727374757677787980818283848586878861626364656667686970717273909192747576777879808182838485959697989910010186878889103104105106107108909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002011112022032041142052062072082092102112122132144 unmodified linesfrom PyPDF2 import PdfReaderimport ioimport joblibimport refrom collections import Counter
# --- FUNÇÕES DE PROCESSAMENTO ---def extract_text_from_pdf(pdf_file): """Extrai texto de PDFs""" 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 ""# --- 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): """Analisa o conteúdo do currículo com pontuação""" if not text: return {"pontuacao": 0, "keywords": []} # Palavras-chave prioritárias keywords = { 'customer success': 3, 'crm': 2, 'atendimento ao cliente': 2, 'gestão de clientes': 2, 'zendesk': 1.5, 'salesforce': 1.5, 'retenção': 1, 'nps': 1 } return {"score": 0, "matches": []} text = text.lower() found_keywords = [] matches = [] total_score = 0 for keyword, score in keywords.items(): if keyword in text: total_score += score found_keywords.append(keyword) # Análise por categoria for 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ções matches.append({ "term": term, "category": category, "count": count, "weight": config["weight"] }) # Normaliza score (0-10) normalized_score = min(total_score / 3, 10) # Rankeia termos mais relevantes top_matches = sorted(matches, key=lambda x: x["count"] * x["weight"], reverse=True)[:5] return { "pontuacao": min(total_score, 10), "keywords": found_keywords "score": round(normalized_score, 1), "matches": matches, "top_matches": top_matches, "missing_terms": find_missing_terms(matches) }
# --- CARREGAR MODELO ---try: model = joblib.load('modelo_estagio_cs.joblib')except Exception as e: print(f"⚠️ Erro ao carregar modelo: {e}") # Modelo de fallback (simples) model = DecisionTreeClassifier(max_depth=2, random_state=42) model.fit(np.array([[0,0,0,0]]), [0]) # Dummy data
# --- INTERFACE GRADIO ---def predict_aderencia(tempo_exp, conhecimento_crm, ingles, graduacao, curriculo): try: # Processar currículo resume_text = extract_text_from_pdf(curriculo) if curriculo else "" resume_analysis = analyze_resume_content(resume_text) # Preparar inputs input_data = np.array([[ tempo_exp, conhecimento_crm, ingles, 1 if graduacao == "Cursando" else 0 ]]) # Previsão proba = model.predict_proba(input_data)[0][1] * 100 proba_ajustada = min(100, proba + resume_analysis['pontuacao'] * 3) return { "Probabilidade Base": f"{proba:.1f}%", "Bônus do Currículo": f"+{resume_analysis['pontuacao'] * 3:.1f}%", "Probabilidade Final": f"{proba_ajustada:.1f}%", "Status": "✅ Aderente" if proba_ajustada >= 70 else "❌ Não Aderente", "Palavras-chave": resume_analysis['keywords'] or "Nenhuma relevante" } except Exception as e: return {"Erro": str(e)}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
# --- CONFIGURAÇÃO DA UI ---with gr.Blocks(title="Analisador de Estágio CS") as app: gr.Markdown("# 🔍 Analisador para Estágio em Customer Success")# --- INTERFACE PREMIUM ---with gr.Blocks(theme=gr.themes.Soft(bg_color="#f5f7ff"), title="🔍 TalentScope CS") as app: # Cabeçalho Personalizado gr.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(): with gr.Column(): gr.Markdown("### 📝 Informações do Candidato") tempo_exp = gr.Slider(0, 24, label="Experiência (meses)") conhecimento_crm = gr.Slider(1, 5, label="Conhecimento CRM (1-5)") ingles = gr.Slider(1, 5, label="Inglês (1-5)") graduacao = gr.Radio(["Cursando", "Completo"], label="Graduação") curriculo = gr.File(label="Currículo (PDF)", file_types=[".pdf"]) # Seção de Inputs with gr.Column(scale=1, variant="panel"): gr.Markdown("### 📋 Perfil do Candidato") with gr.Column(): gr.Markdown("### 📊 Resultado") output = gr.JSON(label="Análise") btn = gr.Button("Analisar", variant="primary") btn.click( 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 Resultados with 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 Keywords gr.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ções with gr.Accordion("💡 Como melhorar seu currículo", open=False): improvement_tips = gr.JSON(label="Termos Faltantes") # Detalhes Técnicos with 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ículo resume_text = extract_text_from_pdf(curriculo) if curriculo else "" resume_analysis = analyze_resume_content(resume_text) # Prepara dados para o modelo input_data = np.array([[ tempo_exp, conhecimento_crm, ingles, 1 if graduacao == "Cursando" else 0 ]]) # Predição proba = model.predict_proba(input_data)[0][1] * 100 proba_ajustada = min(100, proba + resume_analysis["score"] * 3) # Gera visualização de dados keyword_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 status if 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ão submit_btn.click( fn=predict_aderencia, inputs=[tempo_exp, conhecimento_crm, ingles, graduacao, curriculo], outputs=output outputs=[prob_final, bonus, status, keyword_chart, improvement_tips] )
app.launch()# --- INICIALIZAÇÃO ---if __name__ == "__main__": try: model = joblib.load('modelo_estagio_cs.joblib') except: # Modelo fallback para desenvolvimento model = DecisionTreeClassifier(max_depth=2, random_state=42) model.fit(np.array([[0,0,0,0]]), [0]) app.launch(favicon="🔍", server_port=7860)app.py+187-87