Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131144 unmodified linesfrom PyPDF2 import PdfReaderimport ioimport joblib# --- 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 ""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áriaskeywords = {'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}text = text.lower()found_keywords = []total_score = 0for keyword, score in keywords.items():if keyword in text:total_score += scorefound_keywords.append(keyword)return {"pontuacao": min(total_score, 10),"keywords": found_keywords}# --- 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ículoresume_text = extract_text_from_pdf(curriculo) if curriculo else ""resume_analysis = analyze_resume_content(resume_text)# Preparar inputsinput_data = np.array([[tempo_exp,conhecimento_crm,ingles,1 if graduacao == "Cursando" else 0]])# Previsãoproba = model.predict_proba(input_data)[0][1] * 100proba_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)}# --- CONFIGURAÇÃO DA UI ---with gr.Blocks(title="Analisador de Estágio CS") as app:gr.Markdown("# 🔍 Analisador para Estágio em Customer Success")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"])with gr.Column():gr.Markdown("### 📊 Resultado")output = gr.JSON(label="Análise")btn = gr.Button("Analisar", variant="primary")btn.click(fn=predict_aderencia,inputs=[tempo_exp, conhecimento_crm, ingles, graduacao, curriculo],outputs=output)app.launch()4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132144 unmodified linesfrom PyPDF2 import PdfReaderimport ioimport joblibimport 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í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)# 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)
app.py+187-87