Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198import pandas as pdimport numpy as npimport gradio as grfrom sklearn.tree import DecisionTreeClassifierfrom PyPDF2 import PdfReaderimport ioimport joblibimport 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ículoresume_text = extract_text_from_pdf(curriculo) if curriculo else ""resume_analysis = analyze_resume_content(resume_text)# Prepara dados para o modeloinput_data = np.array([[tempo_exp,conhecimento_crm,ingles,1 if graduacao == "Cursando" else 0]])# Prediçãoproba = 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import gradio as grfrom pdfminer.high_level import extract_textimport re# Função para extrair texto do PDFdef extrair_texto(pdf_path):try:texto = extract_text(pdf_path)return textoexcept Exception as e:raise gr.Error(f"Erro ao ler PDF: {str(e)}")# Função de análise do currículodef analisar_curriculo(pdf_file, texto_colado, tem_projeto):try:if pdf_file is not None:# Extrair texto do PDFtexto = extrair_texto(pdf_file.name)elif texto_colado:# Usar o texto coladotexto = texto_coladoelse:raise gr.Error("Por favor, forneça um currículo (carregado ou colado).")if tem_projeto is None:raise gr.Error("Por favor, selecione se você tem projeto de pesquisa.")# Análisefeatures = {'publicacoes': len(re.findall(r'(publicação|artigo|paper)', texto, re.I)),'ingles': 1 if re.search(r'(inglês|TOEFL|IELTS)', texto, re.I) else 0,'projeto': 1 if tem_projeto == 'Sim' else 0,'quant': 1 if re.search(r'(estatística|matemática)', texto, re.I) else 0,'programacao': 1 if re.search(r'(python|R|programação)', texto, re.I) else 0}# Simulação de Resultadopontuacao = min(100, 60 + features['publicacoes'] * 10 + features['ingles'] * 15 +features['projeto'] * 10 + features['quant'] * 5 + features['programacao'] * 10)# Resultado formatado com HTMLresultado = f"""<div style="background: #f0f8ff; padding: 20px; border-radius: 15px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); font-size: 16px; color: #333;"><h3 style="color: #004aad;">📋 Resultado da Análise</h3><p><strong>Pontuação: </strong> {pontuacao} /100</p><p><strong>Publicações: </strong> {features['publicacoes']}</p><p><strong>Inglês: </strong> { "✅ Sim" if features['ingles'] else "❌ Não" }</p><p><strong>Projeto: </strong> { "✅ Sim" if features['projeto'] else "❌ Não" }</p><p><strong>Quantitativo (Estatística/Matemática): </strong> { "✅ Sim" if features['quant'] else "❌ Não" }</p><p><strong>Programação (Python/R): </strong> { "✅ Sim" if features['programacao'] else "❌ Não" }</p></div>"""return resultadoexcept Exception as e:raise gr.Error(f"Erro na análise: {str(e)}")# Interface do Gradiowith gr.Blocks() as app:# Adicionando uma estrutura de layout mais sofisticadawith gr.Row():with gr.Column(scale=1):gr.Markdown("""<div style="text-align:center; background: linear-gradient(135deg, #004aad 0%, #0066cc 100%); color: white; padding: 30px; border-radius: 15px;"><h1>🎓 ANÁLISE DE PERFIL ACADÊMICO</h1><p>Especialização em Ciência de Dados | Inteligência Artificial</p></div>""")# Definindo o formulário de entradawith gr.Row():with gr.Column(scale=1):gr.Markdown("### 📤 Envie seu currículo completo")pdf_input = gr.File(label="Carregar currículo (PDF)", file_types=[".pdf"], type="filepath", elem_id="pdf_input")texto_input = gr.Textbox(label="Ou cole o texto do currículo aqui", placeholder="Cole o conteúdo do currículo...", lines=8, elem_id="texto_input")projeto_input = gr.Radio(["Sim", "Não"],label="Você tem projeto de pesquisa?",value=None,elem_id="projeto_input")btn = gr.Button("Analisar Perfil", variant="primary", elem_id="blue_button")with gr.Column(scale=1):gr.Markdown("### 📊 Resultado da Análise")output_result = gr.HTML(label="Detalhes da Análise", show_label=True)# Aplique a ação de clique no botãobtn.click(fn=analisar_curriculo,inputs=[pdf_input, texto_input, projeto_input],outputs=[output_result])# Execução da aplicaçãoif __name__ == "__main__":app.launch()
app.py+82-181