Spaces:
Sleeping
Sleeping
Update index.html
Browse files54 unmodified lines555657585960611 unmodified line63646566676869707172737475767778798081828384858634 unmodified lines12112212312412512612712812913033 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032041 unmodified line20620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840954 unmodified lines</div><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700">2. Estudo por Imagem</h2><input type="file" id="imageUploader" accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:font-semibold file:bg-violet-50 file:text-violet-700 hover:file:bg-violet-100"/><img id="imagePreview" src="" class="mt-4 rounded-lg hidden max-h-60 mx-auto" alt="Pré-visualização"/><div id="imageAnalysisResult" class="mt-4"></div>1 unmodified line<div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700">3. Prática de Conversação</h2><p class="text-sm text-gray-600 mb-4">Fale com o tutor de IA. A resposta dele será em áudio.</p><div id="chatDisplay" class="flex flex-col space-y-2 mb-4"></div><div class="flex gap-2"><input type="text" id="chatInput" class="flex-grow border rounded-lg px-3 py-2" placeholder="Digite ou fale no microfone..."><button id="chatSendButton" onclick="handleTextInput()" class="btn btn-secondary">Enviar</button><button id="micButton" onclick="handleVoiceInput()" class="btn btn-primary mic-button w-12 h-12 rounded-full">🎙️</button></div></div><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700">Configurações de IA</h2><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="modelSelector" class="block text-sm font-medium text-gray-700">Modelo de IA (Flashcards)</label><select id="modelSelector" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 rounded-md shadow-sm"><option value="gemini:gemini-1.5-flash-latest">Google Gemini 1.5 Flash</option><option value="groq:llama-3.1-8b-instant">Groq (Llama 3.1 8B)</option><option value="groq:mixtral-8x7b-32768">Groq (Mixtral 8x7b)</option></select></div><div>34 unmodified linesconst imageAnalysisResult = document.getElementById('imageAnalysisResult');const chatDisplay = document.getElementById('chatDisplay');const chatInput = document.getElementById('chatInput');const chatSendButton = document.getElementById('chatSendButton');const micButton = document.getElementById('micButton');const modelSelector = document.getElementById('modelSelector');const contextSelector = document.getElementById('contextSelector');let chatHistory = [];let recognition;33 unmodified lines}// --- LÓGICA DE CONVERSAÇÃO (VOZ E TEXTO) ---function initializeSpeechRecognition() {window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;if (!window.SpeechRecognition) {micButton.disabled = true;micButton.textContent = '❌';console.error('Speech Recognition not supported.');return;}recognition = new SpeechRecognition();recognition.lang = 'en-US';recognition.interimResults = false;recognition.onresult = (event) => {const transcript = event.results[0][0].transcript;chatInput.value = transcript;sendMessage(transcript);};recognition.onerror = (event) => console.error('Speech recognition error:', event.error);recognition.onend = () => {isRecording = false;micButton.classList.remove('is-recording');micButton.innerHTML = '🎙️';};}function handleVoiceInput() {if (isRecording) {recognition.stop();} else {isRecording = true;micButton.classList.add('is-recording');micButton.innerHTML = '<div class="spinner"></div>';recognition.start();}}function handleTextInput() {const message = chatInput.value.trim();sendMessage(message);1 unmodified line}chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') handleTextInput(); });async function sendMessage(message) {if (!message) return;appendMessage(message, 'user');chatHistory.push({ role: 'user', content: message });try {const response = await fetch('/chat-with-ai', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ history: chatHistory, message: message })});if (!response.ok) throw new Error((await response.json()).error);const data = await response.json();appendMessage(data.response, 'ai');chatHistory.push({ role: 'assistant', content: data.response });playAudio(data.response); // Toca a resposta da IA} catch (error) {appendMessage(`Erro no chat: ${error.message}`, 'ai');}}function appendMessage(text, sender) {const msg = document.createElement('div');msg.className = `chat-message ${sender}-message`;msg.textContent = text;chatDisplay.appendChild(msg);chatDisplay.scrollTop = chatDisplay.scrollHeight;}// --- LÓGICA DE ESTUDO POR IMAGEM ---imageUploader.addEventListener('change', (event) => {const file = event.target.files[0];if (!file) return;const reader = new FileReader();reader.onload = (e) => {imagePreview.src = e.target.result;imagePreview.classList.remove('hidden');analyzeImage(e.target.result);};reader.readAsDataURL(file);});async function analyzeImage(base64Image) {imageAnalysisResult.innerHTML = `<div class="flex items-center justify-center p-4"><div class="spinner !border-l-indigo-500 !border-gray-200"></div><p class="ml-3 text-gray-600">Analisando imagem...</p></div>`;try {const response = await fetch('/analyze-image', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ image: base64Image })});if (!response.ok) throw new Error((await response.json()).error);const vocabulary = await response.json();displayImageVocabulary(vocabulary);} catch (error) {imageAnalysisResult.innerHTML = `<p class="text-red-600 font-semibold">Erro: ${error.message}</p>`;}}function displayImageVocabulary(vocabulary) {if (!vocabulary || vocabulary.length === 0) {imageAnalysisResult.innerHTML = `<p class="text-gray-500">Nenhum vocabulário claro foi identificado.</p>`;return;}let html = '<h3 class="font-semibold mb-2">Vocabulário sugerido (clique para criar card):</h3><div class="flex flex-wrap gap-2">';vocabulary.forEach(item => {html += `<button onclick="createFlashcardFromSuggestion('${item.term.replace(/'/g, "\\'")}', '${item.definition.replace(/'/g, "\\'")}')" class="btn btn-secondary !text-sm">${item.term}</button>`;});html += '</div>';imageAnalysisResult.innerHTML = html;}// --- LÓGICA DE GERAÇÃO DE FLASHCARD ---async function createFlashcardFromSelection() {const selectedText = window.getSelection().toString().trim();if (!selectedText) return;createCardButton.disabled = true;createCardButton.innerHTML = '<div class="spinner mr-2"></div> Criando...';try {const response = await fetch('/explain-proxy', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({word: selectedText, context: textEditor.innerText, for_flashcard: true,model: modelSelector.value, context_focus: contextSelector.value})});if (!response.ok) throw new Error((await response.json()).error);const cardData = await response.json();renderFlashcard(cardData);} catch (error) {alert(`Falha ao criar flashcard: ${error.message}`);} finally {createCardButton.disabled = false;createCardButton.textContent = '+ Criar Flashcard';}}function createFlashcardFromSuggestion(term, definition) {const cardData = {term: term, definition: definition,translation: '(traduza-me)', context_sentence: `This is a ${term}.`, gapped_sentence: `This is a _______________.`};renderFlashcard(cardData);}function renderFlashcard(data) {noCardsMessage.classList.add('hidden');const cardId = `card-${Date.now()}`;const container = document.createElement('div');container.className = 'flashcard-container';container.id = cardId;const minHeight = 350;container.style.minHeight = `${minHeight}px`;container.innerHTML = `<div class="flashcard-inner" style="min-height: ${minHeight}px;"><div class="flashcard-front"><div><div class="text-sm text-gray-600 mb-2">Frase de Contexto:</div><p class="text-lg text-center text-gray-800">${data.gapped_sentence}</p></div><div class="border-t pt-4 mt-4 text-center"><strong class="text-indigo-600">Dica (PT):</strong> ${data.translation}</div><div class="text-xs text-center text-gray-400 mt-4">Clique para ver a resposta</div></div><div class="flashcard-back"><div><h3 class="text-xl font-bold text-center text-indigo-600 mb-2">${data.term}</h3><p class="flex items-center justify-center gap-2 text-gray-600 italic mb-3"><button class="audio-btn" onclick="playAudio('${data.context_sentence.replace(/'/g, "\\'")}', event)">🔊</button><span>${data.context_sentence}</span></p><p class="text-sm text-gray-800"><strong class="font-semibold">Definição:</strong> ${data.definition}</p></div><div class="border-t mt-3 pt-3"><h4 class="text-sm font-semibold text-center">Pratique sua Pronúncia</h4><div class="flex justify-center items-center gap-2 mt-2"><button class="btn btn-primary w-12 h-12 rounded-full" onclick="handlePronunciationPractice(this, '${data.context_sentence.replace(/'/g, "\\'")}', event)">🎙️</button></div><div class="text-xs text-gray-600 p-2 mt-2 bg-gray-50 rounded-md min-h-[40px]" data-feedback-area></div></div></div></div>`;flashcardList.prepend(container);container.addEventListener('click', () => container.classList.toggle('flipped'));}// --- LÓGICA DE PRÁTICA DE PRONÚNCIA ---async function handlePronunciationPractice(button, targetText, event) {event.stopPropagation();const feedbackArea = button.closest('.flashcard-back').querySelector('[data-feedback-area]');const practiceRec = new SpeechRecognition();practiceRec.lang = 'en-US';button.innerHTML = '<div class="spinner"></div>';button.disabled = true;feedbackArea.textContent = 'Ouvindo...';practiceRec.start();practiceRec.onresult = async (e) => {const userText = e.results[0][0].transcript;feedbackArea.textContent = `Você disse: "${userText}". Analisando...`;try {const response = await fetch('/pronunciation-feedback', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ target_text: targetText, user_text: userText })});if (!response.ok) throw new Error((await response.json()).error);const data = await response.json();feedbackArea.innerHTML = `<strong>Feedback:</strong> ${data.feedback}`;} catch (error) {feedbackArea.textContent = `Erro na análise: ${error.message}`;} finally {button.innerHTML = '🎙️';button.disabled = false;}};practiceRec.onerror = (e) => {feedbackArea.textContent = `Erro ao gravar: ${e.error}`;button.innerHTML = '🎙️';button.disabled = false;};}// --- FUNÇÕES AUXILIARES DE ÁUDIO ---async function fetchAudioBlob(text) {const response = await fetch('/tts-proxy', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ text: text })});if (!response.ok) throw new Error('Falha ao gerar áudio no backend.');return await response.blob();}async function playAudio(text, event) {if(event) event.stopPropagation();try {const audioBlob = await fetchAudioBlob(text);const audioUrl = URL.createObjectURL(audioBlob);const audio = new Audio(audioUrl);audio.play();audio.onended = () => URL.revokeObjectURL(audioUrl);} catch (error) { console.error('Erro ao tocar áudio:', error); }}// --- INICIALIZAÇÃO ---document.addEventListener('DOMContentLoaded', () => {54 unmodified lines555657585960611 unmodified line6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410534 unmodified lines14014114214314414514614714814915015133 unmodified lines1851861871881891901911921 unmodified line19419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824954 unmodified lines</div><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700">2. Estudo por Imagem (Análise)</h2><input type="file" id="imageUploader" accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:font-semibold file:bg-violet-50 file:text-violet-700 hover:file:bg-violet-100"/><img id="imagePreview" src="" class="mt-4 rounded-lg hidden max-h-60 mx-auto" alt="Pré-visualização"/><div id="imageAnalysisResult" class="mt-4"></div>1 unmodified line<div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700">3. Prática de Conversação</h2><div id="chatDisplay" class="flex flex-col space-y-2 mb-4"></div><div class="flex gap-2"><input type="text" id="chatInput" class="flex-grow border rounded-lg px-3 py-2" placeholder="Digite ou fale no microfone..."><button onclick="handleTextInput()" class="btn btn-secondary">Enviar</button><button id="micButton" onclick="handleVoiceInput()" class="btn btn-primary mic-button w-12 h-12 rounded-full">🎙️</button></div></div><!-- NOVO CARD: GERADOR DE IMAGEM --><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700">4. Gerador de Imagens (Nano Banana)</h2><p class="text-sm text-gray-600 mb-2">Descreva uma cena em inglês para a IA desenhar.</p><div class="flex gap-2"><input type="text" id="imagePromptInput" class="flex-grow border rounded-lg px-3 py-2" placeholder="Ex: a blue cat reading a book on the moon"><button id="generateImageBtn" onclick="generateImage()" class="btn btn-primary">Gerar</button></div><div id="imageResultContainer" class="mt-4 p-4 border rounded-lg bg-gray-50 min-h-[200px] flex items-center justify-center"><p class="text-gray-500 italic">Sua imagem aparecerá aqui.</p></div></div><div class="card"><h2 class="text-xl font-semibold mb-4 text-gray-700">Configurações de IA</h2><div class="grid grid-cols-1 md:grid-cols-2 gap-4"><div><label for="modelSelector" class="block text-sm font-medium text-gray-700">Modelo de IA (Flashcards)</label><select id="modelSelector" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 rounded-md shadow-sm"><optgroup label="Google Gemini"><option value="gemini:gemini-1.5-flash-latest">Gemini 1.5 Flash (Rápido)</option><option value="gemini:gemini-1.5-pro-latest">Gemini 1.5 Pro (Avançado)</option></optgroup><optgroup label="Groq (Ultra Rápido)"><option value="groq:llama-3.1-8b-instant">Llama 3.1 8B</option><option value="groq:llama-3.1-70b-versatile">Llama 3.1 70B (Poderoso)</option><option value="groq:gemma2-9b-it">Gemma2 9B (Novo)</option><option value="groq:mixtral-8x7b-32768">Mixtral 8x7b</option></optgroup></select></div><div>34 unmodified linesconst imageAnalysisResult = document.getElementById('imageAnalysisResult');const chatDisplay = document.getElementById('chatDisplay');const chatInput = document.getElementById('chatInput');const micButton = document.getElementById('micButton');const modelSelector = document.getElementById('modelSelector');const contextSelector = document.getElementById('contextSelector');const imagePromptInput = document.getElementById('imagePromptInput');const generateImageBtn = document.getElementById('generateImageBtn');const imageResultContainer = document.getElementById('imageResultContainer');let chatHistory = [];let recognition;33 unmodified lines}// --- LÓGICA DE CONVERSAÇÃO (VOZ E TEXTO) ---function initializeSpeechRecognition() { /* ... código existente, sem alterações ... */ }function handleVoiceInput() { /* ... código existente, sem alterações ... */ }function handleTextInput() {const message = chatInput.value.trim();sendMessage(message);1 unmodified line}chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') handleTextInput(); });async function sendMessage(message) { /* ... código existente, sem alterações ... */ }function appendMessage(text, sender) { /* ... código existente, sem alterações ... */ }// --- LÓGICA DE ESTUDO POR IMAGEM (ANÁLISE) ---imageUploader.addEventListener('change', (event) => { /* ... código existente, sem alterações ... */ });async function analyzeImage(base64Image) { /* ... código existente, sem alterações ... */ }function displayImageVocabulary(vocabulary) { /* ... código existente, sem alterações ... */ }// --- LÓGICA DE GERAÇÃO DE IMAGEM (NOVO) ---async function generateImage() {const prompt = imagePromptInput.value.trim();if (!prompt) {alert('Por favor, digite uma descrição para a imagem.');return;}generateImageBtn.disabled = true;generateImageBtn.innerHTML = '<div class="spinner mr-2"></div> Gerando...';imageResultContainer.innerHTML = `<div class="flex items-center justify-center p-4"><div class="spinner !border-l-indigo-500 !border-gray-200"></div><p class="ml-3 text-gray-600">Criando sua imagem...</p></div>`;try {const response = await fetch('/generate-image', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ prompt: prompt })});if (!response.ok) {const errData = await response.json();throw new Error(errData.error || 'Erro desconhecido no backend.');}const data = await response.json();imageResultContainer.innerHTML = `<img src="data:image/png;base64,${data.image_base64}" class="rounded-lg max-h-60 mx-auto" alt="Imagem gerada por IA"/>`;} catch (error) {imageResultContainer.innerHTML = `<p class="text-red-600 font-semibold">Falha ao gerar imagem: ${error.message}</p>`;} finally {generateImageBtn.disabled = false;generateImageBtn.textContent = 'Gerar';}}// --- LÓGICA DE GERAÇÃO DE FLASHCARD ---async function createFlashcardFromSelection() { /* ... código existente, sem alterações ... */ }function createFlashcardFromSuggestion(term, definition) { /* ... código existente, sem alterações ... */ }function renderFlashcard(data) { /* ... código existente, sem alterações ... */ }// --- LÓGICA DE PRÁTICA DE PRONÚNCIA ---async function handlePronunciationPractice(button, targetText, event) { /* ... código existente, sem alterações ... */ }// --- FUNÇÕES AUXILIARES DE ÁUDIO ---async function fetchAudioBlob(text) { /* ... código existente, sem alterações ... */ }async function playAudio(text, event) { /* ... código existente, sem alterações ... */ }// --- INICIALIZAÇÃO ---document.addEventListener('DOMContentLoaded', () => {
index.html+65-225