Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206import gradio as grimport requestsfrom bs4 import BeautifulSoupimport fitz # PyMuPDFimport spacyfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics.pairwise import cosine_similarityimport numpy as npimport re
# Carregar modelo de linguagem para NLPnlp = spacy.load("pt_core_news_sm")
# Configuração de coresTHEME = { "primary": "#1a1a2e", # Azul escuro "secondary": "#4e148c", # Roxo "accent": "#e94560", # Destaque "text": "#f1f1f1", # Texto claro "background": "#0f0e17" # Fundo escuro}
# Função para extrair texto de vaga do LinkedIndef extract_job_description(url): try: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') # Tentativa de encontrar a descrição da vaga description = soup.find('div', {'class': 'description__text'}) if not description: description = soup.find('div', {'class': 'show-more-less-html__markup'}) return description.get_text(separator='\n') if description else "Não foi possível extrair a descrição da vaga." except Exception as e: return f"Erro ao extrair descrição da vaga: {str(e)}"
# Função para extrair texto do PDFdef extract_pdf_text(pdf_path): try: doc = fitz.open(pdf_path) text = "" for page in doc: text += page.get_text() return text except Exception as e: return f"Erro ao extrair texto do PDF: {str(e)}"
# Função para calcular similaridadedef calculate_match(job_text, resume_text): # Pré-processamento job_doc = nlp(job_text.lower()) resume_doc = nlp(resume_text.lower()) # Extrair palavras-chave job_keywords = [token.text for token in job_doc if not token.is_stop and not token.is_punct and token.is_alpha] resume_keywords = [token.text for token in resume_doc if not token.is_stop and not token.is_punct and token.is_alpha] # Vetorização e cálculo de similaridade vectorizer = TfidfVectorizer().fit_transform([' '.join(job_keywords), ' '.join(resume_keywords)]) similarity = cosine_similarity(vectorizer[0:1], vectorizer[1:2])[0][0] return round(similarity * 100, 2)
# Função para análise detalhadadef detailed_analysis(job_text, resume_text): job_doc = nlp(job_text.lower()) resume_doc = nlp(resume_text.lower()) # Extrair requisitos da vaga requirements = [] for sent in job_doc.sents: if "requisito" in sent.text or "necessário" in sent.text or "desejável" in sent.text: requirements.append(sent.text) # Verificar correspondências matches = [] non_matches = [] for req in requirements: req_doc = nlp(req) found = False for token in req_doc: if token.text in resume_text.lower(): matches.append(req) found = True break if not found: non_matches.append(req) return matches, non_matches
# Função principaldef analyze_match(job_url, resume_file): if not job_url or not resume_file: return "⚠️ Por favor, forneça a URL da vaga e seu currículo." try: # Extrair textos job_text = extract_job_description(job_url) resume_text = extract_pdf_text(resume_file) if "Erro" in job_text or "Erro" in resume_text: return f"❌ Erro no processamento:\nVaga: {job_text}\nCurrículo: {resume_text}" # Calcular match match_percentage = calculate_match(job_text, resume_text) # Análise detalhada matches, non_matches = detailed_analysis(job_text, resume_text) # Formatar resultados status = "✅ **Aderente**" if match_percentage >= 70 else "❌ **Não Aderente**" status_color = "#4CAF50" if match_percentage >= 70 else "#F44336" result = f"""<div style='background-color: {THEME["primary"]}; padding: 20px; border-radius: 10px; color: {THEME["text"]};'> <h1 style='color: {THEME["secondary"]}; text-align: center;'>🌌 MatchCraft - Resultado da Análise</h1> <div style='background-color: {THEME["background"]}; padding: 15px; border-radius: 8px; margin: 15px 0;'> <h2 style='color: {status_color};'>Status: {status}</h2> <h3 style='color: {THEME["accent"]};'>📊 Percentual de Aderência: <span style='font-size: 1.5em;'>{match_percentage}%</span></h3> </div> <div style='display: flex; justify-content: space-between; gap: 20px;'> <div style='flex: 1; background-color: {THEME["background"]}; padding: 15px; border-radius: 8px;'> <h3 style='color: {THEME["secondary"]};'>��️ Correspondências Encontradas</h3> <ul> {''.join([f"<li style='margin-bottom: 8px;'>{match}</li>" for match in matches[:5]])} </ul> {f"<p>+ {len(matches)-5} outras correspondências...</p>" if len(matches) > 5 else ""} </div> <div style='flex: 1; background-color: {THEME["background"]}; padding: 15px; border-radius: 8px;'> <h3 style='color: {THEME["secondary"]};'>✖️ Requisitos Não Atendidos</h3> <ul> {''.join([f"<li style='margin-bottom: 8px;'>{non_match}</li>" for non_match in non_matches[:5]])} </ul> {f"<p>+ {len(non_matches)-5} outros requisitos não atendidos...</p>" if len(non_matches) > 5 else ""} </div> </div> <div style='margin-top: 20px; background-color: {THEME["background"]}; padding: 15px; border-radius: 8px;'> <h3 style='color: {THEME["secondary"]};'>💡 Recomendações</h3> {f"<p style='color: #4CAF50;'>🎯 Você atende a maioria dos requisitos! Considere destacar {min(3, len(matches))} habilidades principais no topo do seu currículo.</p>" if match_percentage >= 70 else f"<p style='color: #F44336;'>🔍 Foque em desenvolver: {', '.join([nm.split()[0] for nm in non_matches[:3]])}</p>"} </div></div>""" return result except Exception as e: return f"❌ Ocorreu um erro durante a análise: {str(e)}"
# Interface Gradio com tema personalizadocss = f"""body {{ background-color: {THEME["primary"]} !important; color: {THEME["text"]} !important;}}.gradio-container {{ background-color: {THEME["primary"]} !important;}}"""
with gr.Blocks(css=css, theme=gr.themes.Default(primary_hue="purple")) as app: gr.Markdown(f""" <div style='text-align: center; padding: 20px; background-color: {THEME["primary"]}; border-radius: 10px;'> <h1 style='color: {THEME["secondary"]}; font-size: 2.5em;'>🌌 MatchCraft</h1> <p style='color: {THEME["text"]}; font-size: 1.2em;'>O Analisador Inteligente de Vagas e Currículos</p> <p style='color: {THEME["accent"]};'>Descubra seu nível de compatibilidade com qualquer vaga do LinkedIn!</p> </div> """) with gr.Row(): with gr.Column(): job_url = gr.Textbox(label="🔗 Cole a URL da vaga do LinkedIn", placeholder="https://www.linkedin.com/jobs/view/...") resume_pdf = gr.File(label="📄 Envie seu currículo (PDF)", file_types=[".pdf"]) analyze_btn = gr.Button("✨ Analisar Compatibilidade", variant="primary") with gr.Column(): result = gr.HTML(label="📊 Resultado da Análise") gr.Markdown(f""" <div style='margin-top: 30px; padding: 15px; background-color: {THEME["background"]}; border-radius: 8px;'> <h3 style='color: {THEME["secondary"]};'>ℹ️ Como funciona?</h3> <ol> <li>Copie a URL de qualquer vaga do LinkedIn</li> <li>Envie seu currículo em PDF</li> <li>Clique em "Analisar Compatibilidade"</li> <li>Veja seu percentual de aderência e recomendações personalizadas</li> </ol> <p style='color: {THEME["accent"]};'>💡 Dica: Vagas com descrições detalhadas geram análises mais precisas!</p> </div> """) analyze_btn.click( fn=analyze_match, inputs=[job_url, resume_pdf], outputs=result )
app.launch()app.pyAdded+206