0% found this document useful (0 votes)
21 views5 pages

Content

keys

Uploaded by

wadoda3463
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views5 pages

Content

keys

Uploaded by

wadoda3463
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

// Função principal que extrai questões e processa

async function analyzeQuestions() {


try {
// Extrai questões da página UniCesumar
const questions = extractQuestions();

if (questions.length === 0) {
showStatus('❌ Nenhuma questão encontrada');
return;
}

showStatus(`🔍 Encontradas ${questions.length} questões. Processando...`);

// Processa cada questão


for (let i = 0; i < questions.length; i++) {
const question = questions[i];
showStatus(`🤖 Analisando questão ${i + 1}/${questions.length}...`);

const answer = await getAIAnswer(question);


if (answer) {
highlightCorrectAnswer(question, answer);
}

// Delay entre questões para não sobrecarregar a API


await new Promise(resolve => setTimeout(resolve, 1000));
}

showStatus('✅ Análise concluída!');

} catch (error) {
console.error('Erro:', error);
showStatus('❌ Erro na análise: ' + error.message);
}
}

// Extrai questões e alternativas da página


function extractQuestions() {
const questions = [];

// Seletores específicos para UniCesumar (mais genéricos)


const possibleQuestionSelectors = [
'.questao',
'.question',
'.pergunta',
'[class*="questao"]',
'[class*="question"]',
'div:has(input[type="radio"])',
'fieldset'
];

let questionElements = [];

// Tenta diferentes seletores


for (const selector of possibleQuestionSelectors) {
try {
questionElements = document.querySelectorAll(selector);
if (questionElements.length > 0) {
console.log(`Encontradas questões com seletor: ${selector}`);
break;
}
} catch (e) {
continue;
}
}

// Se não encontrou, procura por grupos de radio buttons


if (questionElements.length === 0) {
const radioGroups = {};
const radios = document.querySelectorAll('input[type="radio"]');

radios.forEach(radio => {
const name = radio.name;
if (!radioGroups[name]) {
radioGroups[name] = [];
}
radioGroups[name].push(radio);
});

Object.keys(radioGroups).forEach((groupName, index) => {


const radios = radioGroups[groupName];

// Busca o texto da questão próximo aos radios


let questionText = '';
const firstRadio = radios[0];
let parent = firstRadio.closest('div, fieldset, section');

if (parent) {
// Procura por texto da questão
const textNodes = parent.querySelectorAll('p, div, span, h1, h2, h3, h4,
h5, h6');
for (const node of textNodes) {
if (node.textContent.trim().length > 20) {
questionText = node.textContent.trim();
break;
}
}
}

// Coleta alternativas
const alternatives = [];
radios.forEach(radio => {
let altText = '';

const label = document.querySelector(`label[for="${radio.id}"]`) ||


radio.closest('label');
if (label) {
altText = label.textContent.trim();
} else if (radio.nextSibling) {
altText = radio.nextSibling.textContent?.trim() || '';
}

if (altText) {
alternatives.push({
element: radio,
text: altText,
value: radio.value
});
}
});

if (questionText && alternatives.length > 0) {


questions.push({
index: index,
text: questionText,
alternatives: alternatives,
element: parent
});
}
});
}

console.log(`Total de questões encontradas: ${questions.length}`);


return questions;
}

// Envia questão para a IA Perplexity (CORRIGIDO)


async function getAIAnswer(question) {
try {
// Busca a API key
const result = await chrome.storage.sync.get(['perplexityApiKey']);
const apiKey = result.perplexityApiKey;

if (!apiKey) {
showStatus('❌ Configure a API Key da Perplexity primeiro');
return null;
}

// Formata a pergunta
const prompt = `Questão: ${question.text}

Alternativas:
${question.alternatives.map((alt, i) =>
`${String.fromCharCode(65 + i)}. ${alt.text}`
).join('\n')}

Responda apenas com a letra da alternativa correta (A, B, C, D ou E):`;

console.log('Enviando prompt:', prompt);

// Chama a API da Perplexity (FORMATO CORRETO)


const response = await fetch('https://api.perplexity.ai/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'llama-3.1-sonar-small-128k-online', // Modelo correto
messages: [
{
role: 'user',
content: prompt
}
],
max_tokens: 10,
temperature: 0.1
})
});

console.log('Status da resposta:', response.status);

if (!response.ok) {
const errorText = await response.text();
console.error('Erro da API:', errorText);
throw new Error(`API Error: ${response.status} - ${errorText}`);
}

const data = await response.json();


console.log('Resposta da API:', data);

const answer = data.choices[0].message.content.trim().toUpperCase();

// Extrai apenas a letra (A, B, C, D, E)


const match = answer.match(/[A-E]/);
const finalAnswer = match ? match : null;

console.log('Resposta processada:', finalAnswer);


return finalAnswer;

} catch (error) {
console.error('Erro na API:', error);
showStatus(`❌ Erro na API: ${error.message}`);
return null;
}
}

// Destaca a resposta correta


function highlightCorrectAnswer(question, answerLetter) {
const answerIndex = answerLetter.charCodeAt(0) - 65; // A=0, B=1, etc.

if (answerIndex >= 0 && answerIndex < question.alternatives.length) {


const correctAlternative = question.alternatives[answerIndex];

// Adiciona destaque visual


correctAlternative.element.style.cssText = `
background: #4CAF50 !important;
transform: scale(1.05) !important;
box-shadow: 0 0 15px #4CAF50 !important;
border: 3px solid #2E7D32 !important;
border-radius: 8px !important;
`;

// Adiciona ícone de sugestão


const suggestion = document.createElement('span');
suggestion.innerHTML = ' 🤖✨ SUGERIDO';
suggestion.style.cssText = `
color: #4CAF50 !important;
font-weight: bold !important;
font-size: 14px !important;
margin-left: 10px !important;
`;

const label = correctAlternative.element.closest('label') ||


document.querySelector(`label[for="$
{correctAlternative.element.id}"]`);
if (label && !label.querySelector('.ai-suggestion')) {
suggestion.className = 'ai-suggestion';
label.appendChild(suggestion);
}

console.log(`Destacada alternativa ${answerLetter} para questão $


{question.index + 1}`);
}
}

// Mostra status na página


function showStatus(message) {
let statusDiv = document.getElementById('ai-helper-status');

if (!statusDiv) {
statusDiv = document.createElement('div');
statusDiv.id = 'ai-helper-status';
statusDiv.style.cssText = `
position: fixed !important;
top: 20px !important;
right: 20px !important;
background: #333 !important;
color: white !important;
padding: 15px 20px !important;
border-radius: 8px !important;
z-index: 999999 !important;
font-family: Arial, sans-serif !important;
font-size: 14px !important;
box-shadow: 0 4px 12px rgba(0,0,0,0.5) !important;
max-width: 300px !important;
word-wrap: break-word !important;
`;
document.body.appendChild(statusDiv);
}

statusDiv.textContent = message;
console.log('Status:', message);

// Remove depois de 5 segundos se for mensagem de sucesso/erro


if (message.includes('✅') || message.includes('❌')) {
setTimeout(() => {
if (statusDiv.parentNode) {
statusDiv.parentNode.removeChild(statusDiv);
}
}, 5000);
}
}

// Escuta mensagens do popup


chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "analyzeQuestions") {
analyzeQuestions();
sendResponse({status: "Iniciando análise..."});
}
});

console.log('UniCesumar AI Helper carregado!');

You might also like