amauricunha commited on
Commit
ea769a5
·
verified ·
1 Parent(s): 378b3e3

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +288 -111
index.html CHANGED
@@ -9,24 +9,24 @@
9
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
10
  body { font-family: 'Inter', sans-serif; background-color: #f7f9fc; }
11
  .card { background-color: white; border-radius: 12px; box-shadow: 0 4px_12px rgba(0,0,0,0.08); padding: 24px; }
12
- .btn { padding: 0.5rem 1rem; border-radius: 8px; font-weight: 600; transition: all 0.2s; }
 
13
  .btn-primary { background-color: #4f46e5; color: white; }
14
- .btn-primary:hover { background-color: #4338ca; }
15
- #textEditor { border: 1px solid #ccc; padding: 1rem; min-height: 16rem; border-radius: 0.5rem; outline: none; }
16
- .spinner { border: 4px solid rgba(0, 0, 0, 0.1); width: 24px; height: 24px; border-radius: 50%; border-left-color: #4f46e5; animation: spin 1s ease infinite; }
17
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
18
- .flashcard-container { perspective: 1000px; margin-bottom: 1rem; }
19
  .flashcard-inner { position: relative; width: 100%; transition: transform 0.6s; transform-style: preserve-3d; }
20
  .flashcard-container.flipped .flashcard-inner { transform: rotateY(180deg); }
21
- .flashcard-front, .flashcard-back { position: absolute; width: 100%; height:100%; backface-visibility: hidden; -webkit-backface-visibility: hidden; border: 1px solid #e5e7eb; border-radius: 12px; padding: 20px; display: flex; flex-direction: column; justify-content: center; }
22
  .flashcard-front { background-color: #f9fafb; }
23
  .flashcard-back { background-color: #ffffff; transform: rotateY(180deg); }
24
- .audio-btn { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #4f46e5; }
25
- /* Estilos do Chat */
26
  #chatDisplay { height: 250px; overflow-y: auto; background-color: #f9fafb; border-radius: 8px; padding: 10px; border: 1px solid #e5e7eb; }
27
- .chat-message { max-width: 80%; padding: 8px 12px; border-radius: 12px; margin-bottom: 8px; word-wrap: break-word; }
28
- .user-message { background-color: #4f46e5; color: white; align-self: flex-end; margin-left: auto; }
29
- .ai-message { background-color: #e5e7eb; color: #1f2937; align-self: flex-start; }
 
30
  </style>
31
  </head>
32
  <body class="p-4 md:p-8">
@@ -34,53 +34,72 @@
34
  <div class="container mx-auto max-w-5xl">
35
  <header class="text-center mb-10">
36
  <h1 class="text-3xl lg:text-4xl font-bold text-gray-800">Dynamic English Study Studio</h1>
37
- <p class="text-gray-500 mt-2">Sua ferramenta de estudo com áudio, contexto, imagens e chat em tempo real.</p>
38
  </header>
39
 
40
  <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
41
  <!-- Coluna da Esquerda: Inputs -->
42
  <div class="flex flex-col gap-6">
43
  <div class="card">
44
- <h2 class="text-xl font-semibold mb-4 text-gray-700">1. Estude a partir de um Texto</h2>
45
- <div id="textEditor" contenteditable="true" spellcheck="true" lang="en" class="w-full p-4 focus:ring-2 focus:ring-indigo-500 text-gray-800"></div>
46
  <p class="text-sm text-right text-gray-500 mt-2">Caracteres: <span id="charCount">0</span>/10000</p>
47
- <div class="mt-4 border-t pt-4 flex justify-between items-center">
48
  <button id="createCardButton" onclick="createFlashcardFromSelection()" class="btn btn-primary bg-green-600 hover:bg-green-700 disabled:opacity-50" disabled>+ Criar Flashcard</button>
49
- <button id="playButton" onclick="handlePlay()" class="btn btn-primary flex items-center justify-center disabled:opacity-50">
50
  <span id="playText">Ouvir Texto</span>
51
- <div id="loadingSpinner" class="spinner ml-3 hidden"></div>
52
  </button>
53
  </div>
54
- <audio id="audioPlayer" controls class="w-full mt-4 hidden"></audio>
55
  </div>
56
 
57
  <div class="card">
58
- <h2 class="text-xl font-semibold mb-4 text-gray-700">2. Estude a partir de uma Imagem</h2>
59
- <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:text-sm file:font-semibold file:bg-violet-50 file:text-violet-700 hover:file:bg-violet-100"/>
60
  <img id="imagePreview" src="" class="mt-4 rounded-lg hidden max-h-60 mx-auto" alt="Pré-visualização"/>
61
  <div id="imageAnalysisResult" class="mt-4"></div>
62
  </div>
63
 
64
- <!-- NOVO: Card de Conversação com IA -->
65
- <div class="card">
66
- <h2 class="text-xl font-semibold mb-4 text-gray-700">3. Pratique Conversação (com Groq)</h2>
67
- <p class="text-sm text-gray-600 mb-4">Converse com um tutor de IA que responde instantaneamente. Comece dizendo "Hello!".</p>
68
- <div id="chatDisplay" class="flex flex-col space-y-2 mb-4">
69
- <!-- Mensagens do chat aparecerão aqui -->
70
- </div>
71
  <div class="flex gap-2">
72
- <input type="text" id="chatInput" class="flex-grow border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-500" placeholder="Digite sua mensagem em inglês...">
73
- <button id="chatSendButton" onclick="handleSendMessage()" class="btn btn-primary">Enviar</button>
 
74
  </div>
75
  </div>
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  </div>
78
 
79
  <!-- Coluna da Direita: Flashcards -->
80
  <div id="flashcardsPanel" class="card">
81
  <h2 class="text-xl font-semibold mb-4 text-gray-700">Sua Sessão de Estudo</h2>
82
- <div id="flashcardList" class="space-y-4">
83
- <p id="noCardsMessage" class="text-gray-500 italic">Nenhum flashcard criado ainda. Comece seus estudos!</p>
84
  </div>
85
  </div>
86
  </div>
@@ -89,149 +108,307 @@
89
  <script>
90
  // --- ELEMENTOS GLOBAIS ---
91
  const textEditor = document.getElementById('textEditor');
 
92
  const createCardButton = document.getElementById('createCardButton');
93
- const flashcardList = document.getElementById('flashcardList');
94
- const noCardsMessage = document.getElementById('noCardsMessage');
95
  const playButton = document.getElementById('playButton');
96
- const audioPlayer = document.getElementById('audioPlayer');
97
- const charCount = document.getElementById('charCount');
98
- const loadingSpinner = document.getElementById('loadingSpinner');
99
  const playText = document.getElementById('playText');
100
- const MAX_CHARS = 10000;
 
 
 
101
  const imageUploader = document.getElementById('imageUploader');
102
  const imagePreview = document.getElementById('imagePreview');
103
  const imageAnalysisResult = document.getElementById('imageAnalysisResult');
104
- // --- NOVO: ELEMENTOS DO CHAT ---
105
  const chatDisplay = document.getElementById('chatDisplay');
106
  const chatInput = document.getElementById('chatInput');
107
  const chatSendButton = document.getElementById('chatSendButton');
 
 
 
 
108
  let chatHistory = [];
 
 
109
 
110
-
111
- // --- LÓGICA DO EDITOR E ÁUDIO ---
112
  textEditor.addEventListener('input', () => {
113
  const len = textEditor.innerText.length;
114
- charCount.textContent = `${len}/${MAX_CHARS}`;
115
- playButton.disabled = len === 0 || len > MAX_CHARS;
116
  });
117
  textEditor.addEventListener('mouseup', () => {
118
  createCardButton.disabled = !window.getSelection().toString().trim();
119
  });
120
- // ... (função de áudio handlePlay e fetchAudio)
121
- async function handlePlay() { /* ... */ }
122
 
123
- // --- LÓGICA DE ANÁLISE DE IMAGEM ---
124
- imageUploader.addEventListener('change', (event) => {
125
- // ... (código existente sem alterações)
126
- const file = event.target.files[0]; if (!file) return;
127
- const reader = new FileReader();
128
- reader.onload = (e) => { imagePreview.src = e.target.result; imagePreview.classList.remove('hidden'); analyzeImage(e.target.result); };
129
- reader.readAsDataURL(file);
130
- });
131
- async function analyzeImage(base64Image) {
132
- // ... (código existente sem alterações)
133
- imageAnalysisResult.innerHTML = `<div class="flex items-center justify-center p-4"><div class="spinner"></div><p class="ml-3">Analisando imagem...</p></div>`;
134
  try {
135
- const response = await fetch('/analyze-image', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: base64Image }) });
136
- if (!response.ok) { const err = await response.json(); throw new Error(err.error); }
137
- const vocabulary = await response.json();
138
- displayImageVocabulary(vocabulary);
139
- } catch (error) { imageAnalysisResult.innerHTML = `<p class="text-red-600 font-semibold">Erro: ${error.message}</p>`; }
140
- }
141
- function displayImageVocabulary(vocabulary) {
142
- // ... (código existente sem alterações)
143
- if (!vocabulary || vocabulary.length === 0) { imageAnalysisResult.innerHTML = `<p>Nenhum vocabulário identificado.</p>`; return; }
144
- let html = '<h3 class="font-semibold mb-2">Vocabulário sugerido:</h3><div class="flex flex-wrap gap-2">';
145
- vocabulary.forEach(item => {
146
- const term = encodeURIComponent(item.term); const definition = encodeURIComponent(item.definition);
147
- html += `<button onclick="createFlashcardFromSuggestion('${term}', '${definition}')" class="btn btn-secondary text-sm">${item.term}</button>`;
148
- });
149
- html += '</div>'; imageAnalysisResult.innerHTML = html;
150
  }
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
- // --- LÓGICA DO CHAT (NOVO) ---
154
- chatInput.addEventListener('keypress', (e) => {
155
- if (e.key === 'Enter') handleSendMessage();
156
- });
 
 
 
 
 
 
157
 
158
- async function handleSendMessage() {
159
  const message = chatInput.value.trim();
160
- if (!message) return;
161
-
162
- appendMessage(message, 'user');
163
  chatInput.value = '';
164
- chatInput.disabled = true;
165
- chatSendButton.disabled = true;
166
 
167
- // Adiciona a mensagem do usuário ao histórico para enviar à API
 
 
168
  chatHistory.push({ role: 'user', content: message });
169
-
170
  try {
171
  const response = await fetch('/chat-with-ai', {
172
- method: 'POST',
173
- headers: { 'Content-Type': 'application/json' },
174
  body: JSON.stringify({ history: chatHistory, message: message })
175
  });
176
- if (!response.ok) {
177
- const errorData = await response.json();
178
- throw new Error(errorData.error || 'Falha na resposta do chat.');
179
- }
180
  const data = await response.json();
181
  appendMessage(data.response, 'ai');
182
- // Adiciona a resposta da IA ao histórico
183
  chatHistory.push({ role: 'assistant', content: data.response });
 
184
  } catch (error) {
185
- appendMessage(`Erro: ${error.message}`, 'ai');
186
- } finally {
187
- chatInput.disabled = false;
188
- chatSendButton.disabled = false;
189
- chatInput.focus();
190
  }
191
  }
192
 
193
  function appendMessage(text, sender) {
194
- const messageElement = document.createElement('div');
195
- messageElement.classList.add('chat-message', sender === 'user' ? 'user-message' : 'ai-message');
196
- messageElement.textContent = text;
197
- chatDisplay.appendChild(messageElement);
198
- // Rola para a mensagem mais recente
199
  chatDisplay.scrollTop = chatDisplay.scrollHeight;
200
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
- // --- GERAÇÃO DE FLASHCARD ---
204
- function createFlashcardFromSuggestion(encodedTerm, encodedDefinition) { /* ... */ }
205
- async function createFlashcardFromSelection() { /* ... */ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
 
 
 
 
 
 
 
 
207
  function renderFlashcard(data) {
208
  noCardsMessage.classList.add('hidden');
209
  const cardId = `card-${Date.now()}`;
210
  const container = document.createElement('div');
211
  container.className = 'flashcard-container';
212
  container.id = cardId;
213
- const minHeight = 280;
214
  container.style.minHeight = `${minHeight}px`;
215
-
216
  container.innerHTML = `
217
  <div class="flashcard-inner" style="min-height: ${minHeight}px;">
218
  <div class="flashcard-front">
219
- <!-- ... conteúdo da frente ... -->
 
 
 
 
 
 
 
220
  </div>
221
  <div class="flashcard-back">
222
- <!-- ... conteúdo do verso ... -->
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  </div>
224
  </div>`;
225
-
226
  flashcardList.prepend(container);
227
  container.addEventListener('click', () => container.classList.toggle('flipped'));
228
  }
229
-
230
- async function playWord(button, word) {
 
231
  event.stopPropagation();
232
- // ... (código para tocar a palavra)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
  }
234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  </script>
236
 
237
  </body>
 
9
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
10
  body { font-family: 'Inter', sans-serif; background-color: #f7f9fc; }
11
  .card { background-color: white; border-radius: 12px; box-shadow: 0 4px_12px rgba(0,0,0,0.08); padding: 24px; }
12
+ .btn { padding: 0.5rem 1rem; border-radius: 8px; font-weight: 600; transition: all 0.2s; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; }
13
+ .btn:disabled { cursor: not-allowed; opacity: 0.5; }
14
  .btn-primary { background-color: #4f46e5; color: white; }
15
+ .btn-primary:hover:not(:disabled) { background-color: #4338ca; }
16
+ .spinner { border: 2px solid rgba(255,255,255,0.3); width: 20px; height: 20px; border-radius: 50%; border-left-color: #fff; animation: spin 1s ease infinite; }
17
+ @keyframes spin { to { transform: rotate(360deg); } }
18
+ .flashcard-container { perspective: 1000px; }
 
19
  .flashcard-inner { position: relative; width: 100%; transition: transform 0.6s; transform-style: preserve-3d; }
20
  .flashcard-container.flipped .flashcard-inner { transform: rotateY(180deg); }
21
+ .flashcard-front, .flashcard-back { position: absolute; width: 100%; height:100%; backface-visibility: hidden; border: 1px solid #e5e7eb; border-radius: 12px; padding: 20px; display: flex; flex-direction: column; justify-content: space-between; }
22
  .flashcard-front { background-color: #f9fafb; }
23
  .flashcard-back { background-color: #ffffff; transform: rotateY(180deg); }
24
+ .audio-btn { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: #4f46e5; padding: 0; }
 
25
  #chatDisplay { height: 250px; overflow-y: auto; background-color: #f9fafb; border-radius: 8px; padding: 10px; border: 1px solid #e5e7eb; }
26
+ .chat-message { max-width: 80%; padding: 8px 12px; border-radius: 18px; margin-bottom: 8px; line-height: 1.4; word-wrap: break-word; }
27
+ .user-message { background-color: #4f46e5; color: white; align-self: flex-end; margin-left: auto; border-bottom-right-radius: 4px; }
28
+ .ai-message { background-color: #e5e7eb; color: #1f2937; align-self: flex-start; border-bottom-left-radius: 4px; }
29
+ .mic-button.is-recording { background-color: #ef4444; }
30
  </style>
31
  </head>
32
  <body class="p-4 md:p-8">
 
34
  <div class="container mx-auto max-w-5xl">
35
  <header class="text-center mb-10">
36
  <h1 class="text-3xl lg:text-4xl font-bold text-gray-800">Dynamic English Study Studio</h1>
37
+ <p class="text-gray-500 mt-2">Sua ferramenta de estudo com áudio, imagens, e prática de conversação e pronúncia.</p>
38
  </header>
39
 
40
  <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
41
  <!-- Coluna da Esquerda: Inputs -->
42
  <div class="flex flex-col gap-6">
43
  <div class="card">
44
+ <h2 class="text-xl font-semibold mb-4 text-gray-700">1. Estudo por Texto</h2>
45
+ <div id="textEditor" contenteditable="true" spellcheck="true" lang="en" class="w-full p-4 border rounded-md min-h-[150px]"></div>
46
  <p class="text-sm text-right text-gray-500 mt-2">Caracteres: <span id="charCount">0</span>/10000</p>
47
+ <div class="mt-4 border-t pt-4 flex flex-wrap gap-2 justify-between items-center">
48
  <button id="createCardButton" onclick="createFlashcardFromSelection()" class="btn btn-primary bg-green-600 hover:bg-green-700 disabled:opacity-50" disabled>+ Criar Flashcard</button>
49
+ <button id="playButton" onclick="handlePlay()" class="btn btn-primary" disabled>
50
  <span id="playText">Ouvir Texto</span>
51
+ <div id="playSpinner" class="spinner ml-2 hidden"></div>
52
  </button>
53
  </div>
54
+ <audio id="audioPlayer" controls class="w-full mt-4 hidden"></audio>
55
  </div>
56
 
57
  <div class="card">
58
+ <h2 class="text-xl font-semibold mb-4 text-gray-700">2. Estudo por Imagem</h2>
59
+ <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"/>
60
  <img id="imagePreview" src="" class="mt-4 rounded-lg hidden max-h-60 mx-auto" alt="Pré-visualização"/>
61
  <div id="imageAnalysisResult" class="mt-4"></div>
62
  </div>
63
 
64
+ <div class="card">
65
+ <h2 class="text-xl font-semibold mb-4 text-gray-700">3. Prática de Conversação</h2>
66
+ <p class="text-sm text-gray-600 mb-4">Fale com o tutor de IA. A resposta dele será em áudio.</p>
67
+ <div id="chatDisplay" class="flex flex-col space-y-2 mb-4"></div>
 
 
 
68
  <div class="flex gap-2">
69
+ <input type="text" id="chatInput" class="flex-grow border rounded-lg px-3 py-2" placeholder="Digite ou fale no microfone...">
70
+ <button id="chatSendButton" onclick="handleTextInput()" class="btn btn-secondary">Enviar</button>
71
+ <button id="micButton" onclick="handleVoiceInput()" class="btn btn-primary mic-button w-12 h-12 rounded-full">🎙️</button>
72
  </div>
73
  </div>
74
 
75
+ <div class="card">
76
+ <h2 class="text-xl font-semibold mb-4 text-gray-700">Configurações de IA</h2>
77
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
78
+ <div>
79
+ <label for="modelSelector" class="block text-sm font-medium text-gray-700">Modelo de IA (Flashcards)</label>
80
+ <select id="modelSelector" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 rounded-md shadow-sm">
81
+ <option value="gemini:gemini-1.5-flash-latest">Google Gemini 1.5 Flash</option>
82
+ <option value="groq:llama-3.1-8b-instant">Groq (Llama 3.1 8B)</option>
83
+ <option value="groq:mixtral-8x7b-32768">Groq (Mixtral 8x7b)</option>
84
+ </select>
85
+ </div>
86
+ <div>
87
+ <label for="contextSelector" class="block text-sm font-medium text-gray-700">Foco do Vocabulário</label>
88
+ <select id="contextSelector" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 rounded-md shadow-sm">
89
+ <option value="General/Social">Geral/Social</option>
90
+ <option value="Professional/Business">Profissional/Negócios</option>
91
+ <option value="Technical/IT">Técnico/TI</option>
92
+ </select>
93
+ </div>
94
+ </div>
95
+ </div>
96
  </div>
97
 
98
  <!-- Coluna da Direita: Flashcards -->
99
  <div id="flashcardsPanel" class="card">
100
  <h2 class="text-xl font-semibold mb-4 text-gray-700">Sua Sessão de Estudo</h2>
101
+ <div id="flashcardList" class="space-y-6">
102
+ <p id="noCardsMessage" class="text-gray-500 italic">Nenhum flashcard criado ainda.</p>
103
  </div>
104
  </div>
105
  </div>
 
108
  <script>
109
  // --- ELEMENTOS GLOBAIS ---
110
  const textEditor = document.getElementById('textEditor');
111
+ const charCount = document.getElementById('charCount');
112
  const createCardButton = document.getElementById('createCardButton');
 
 
113
  const playButton = document.getElementById('playButton');
 
 
 
114
  const playText = document.getElementById('playText');
115
+ const playSpinner = document.getElementById('playSpinner');
116
+ const audioPlayer = document.getElementById('audioPlayer');
117
+ const flashcardList = document.getElementById('flashcardList');
118
+ const noCardsMessage = document.getElementById('noCardsMessage');
119
  const imageUploader = document.getElementById('imageUploader');
120
  const imagePreview = document.getElementById('imagePreview');
121
  const imageAnalysisResult = document.getElementById('imageAnalysisResult');
 
122
  const chatDisplay = document.getElementById('chatDisplay');
123
  const chatInput = document.getElementById('chatInput');
124
  const chatSendButton = document.getElementById('chatSendButton');
125
+ const micButton = document.getElementById('micButton');
126
+ const modelSelector = document.getElementById('modelSelector');
127
+ const contextSelector = document.getElementById('contextSelector');
128
+
129
  let chatHistory = [];
130
+ let recognition;
131
+ let isRecording = false;
132
 
133
+ // --- LÓGICA PRINCIPAL DO EDITOR DE TEXTO ---
 
134
  textEditor.addEventListener('input', () => {
135
  const len = textEditor.innerText.length;
136
+ charCount.textContent = `${len}/10000`;
137
+ playButton.disabled = len === 0;
138
  });
139
  textEditor.addEventListener('mouseup', () => {
140
  createCardButton.disabled = !window.getSelection().toString().trim();
141
  });
 
 
142
 
143
+ // --- LÓGICA DE ÁUDIO DO TEXTO PRINCIPAL ---
144
+ async function handlePlay() {
145
+ const text = textEditor.innerText;
146
+ if (!text) return;
147
+ playButton.disabled = true;
148
+ playText.textContent = 'Gerando...';
149
+ playSpinner.classList.remove('hidden');
 
 
 
 
150
  try {
151
+ const audioBlob = await fetchAudioBlob(text);
152
+ const audioUrl = URL.createObjectURL(audioBlob);
153
+ audioPlayer.src = audioUrl;
154
+ audioPlayer.classList.remove('hidden');
155
+ audioPlayer.play();
156
+ audioPlayer.onended = () => URL.revokeObjectURL(audioUrl);
157
+ } catch (error) {
158
+ alert(`Erro ao gerar áudio: ${error.message}`);
159
+ } finally {
160
+ playButton.disabled = false;
161
+ playText.textContent = 'Ouvir Texto';
162
+ playSpinner.classList.add('hidden');
163
+ }
 
 
164
  }
165
 
166
+ // --- LÓGICA DE CONVERSAÇÃO (VOZ E TEXTO) ---
167
+ function initializeSpeechRecognition() {
168
+ window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
169
+ if (!window.SpeechRecognition) {
170
+ micButton.disabled = true;
171
+ micButton.textContent = '❌';
172
+ console.error('Speech Recognition not supported.');
173
+ return;
174
+ }
175
+ recognition = new SpeechRecognition();
176
+ recognition.lang = 'en-US';
177
+ recognition.interimResults = false;
178
+ recognition.onresult = (event) => {
179
+ const transcript = event.results[0][0].transcript;
180
+ chatInput.value = transcript;
181
+ sendMessage(transcript);
182
+ };
183
+ recognition.onerror = (event) => console.error('Speech recognition error:', event.error);
184
+ recognition.onend = () => {
185
+ isRecording = false;
186
+ micButton.classList.remove('is-recording');
187
+ micButton.innerHTML = '🎙️';
188
+ };
189
+ }
190
 
191
+ function handleVoiceInput() {
192
+ if (isRecording) {
193
+ recognition.stop();
194
+ } else {
195
+ isRecording = true;
196
+ micButton.classList.add('is-recording');
197
+ micButton.innerHTML = '<div class="spinner"></div>';
198
+ recognition.start();
199
+ }
200
+ }
201
 
202
+ function handleTextInput() {
203
  const message = chatInput.value.trim();
204
+ sendMessage(message);
 
 
205
  chatInput.value = '';
206
+ }
207
+ chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') handleTextInput(); });
208
 
209
+ async function sendMessage(message) {
210
+ if (!message) return;
211
+ appendMessage(message, 'user');
212
  chatHistory.push({ role: 'user', content: message });
 
213
  try {
214
  const response = await fetch('/chat-with-ai', {
215
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
 
216
  body: JSON.stringify({ history: chatHistory, message: message })
217
  });
218
+ if (!response.ok) throw new Error((await response.json()).error);
 
 
 
219
  const data = await response.json();
220
  appendMessage(data.response, 'ai');
 
221
  chatHistory.push({ role: 'assistant', content: data.response });
222
+ playAudio(data.response); // Toca a resposta da IA
223
  } catch (error) {
224
+ appendMessage(`Erro no chat: ${error.message}`, 'ai');
 
 
 
 
225
  }
226
  }
227
 
228
  function appendMessage(text, sender) {
229
+ const msg = document.createElement('div');
230
+ msg.className = `chat-message ${sender}-message`;
231
+ msg.textContent = text;
232
+ chatDisplay.appendChild(msg);
 
233
  chatDisplay.scrollTop = chatDisplay.scrollHeight;
234
  }
235
+
236
+ // --- LÓGICA DE ESTUDO POR IMAGEM ---
237
+ imageUploader.addEventListener('change', (event) => {
238
+ const file = event.target.files[0];
239
+ if (!file) return;
240
+ const reader = new FileReader();
241
+ reader.onload = (e) => {
242
+ imagePreview.src = e.target.result;
243
+ imagePreview.classList.remove('hidden');
244
+ analyzeImage(e.target.result);
245
+ };
246
+ reader.readAsDataURL(file);
247
+ });
248
 
249
+ async function analyzeImage(base64Image) {
250
+ 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>`;
251
+ try {
252
+ const response = await fetch('/analyze-image', {
253
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
254
+ body: JSON.stringify({ image: base64Image })
255
+ });
256
+ if (!response.ok) throw new Error((await response.json()).error);
257
+ const vocabulary = await response.json();
258
+ displayImageVocabulary(vocabulary);
259
+ } catch (error) {
260
+ imageAnalysisResult.innerHTML = `<p class="text-red-600 font-semibold">Erro: ${error.message}</p>`;
261
+ }
262
+ }
263
+
264
+ function displayImageVocabulary(vocabulary) {
265
+ if (!vocabulary || vocabulary.length === 0) {
266
+ imageAnalysisResult.innerHTML = `<p class="text-gray-500">Nenhum vocabulário claro foi identificado.</p>`;
267
+ return;
268
+ }
269
+ let html = '<h3 class="font-semibold mb-2">Vocabulário sugerido (clique para criar card):</h3><div class="flex flex-wrap gap-2">';
270
+ vocabulary.forEach(item => {
271
+ html += `<button onclick="createFlashcardFromSuggestion('${item.term.replace(/'/g, "\\'")}', '${item.definition.replace(/'/g, "\\'")}')" class="btn btn-secondary !text-sm">${item.term}</button>`;
272
+ });
273
+ html += '</div>';
274
+ imageAnalysisResult.innerHTML = html;
275
+ }
276
 
277
+ // --- LÓGICA DE GERAÇÃO DE FLASHCARD ---
278
+ async function createFlashcardFromSelection() {
279
+ const selectedText = window.getSelection().toString().trim();
280
+ if (!selectedText) return;
281
+ createCardButton.disabled = true;
282
+ createCardButton.innerHTML = '<div class="spinner mr-2"></div> Criando...';
283
+ try {
284
+ const response = await fetch('/explain-proxy', {
285
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
286
+ body: JSON.stringify({
287
+ word: selectedText, context: textEditor.innerText, for_flashcard: true,
288
+ model: modelSelector.value, context_focus: contextSelector.value
289
+ })
290
+ });
291
+ if (!response.ok) throw new Error((await response.json()).error);
292
+ const cardData = await response.json();
293
+ renderFlashcard(cardData);
294
+ } catch (error) {
295
+ alert(`Falha ao criar flashcard: ${error.message}`);
296
+ } finally {
297
+ createCardButton.disabled = false;
298
+ createCardButton.textContent = '+ Criar Flashcard';
299
+ }
300
+ }
301
 
302
+ function createFlashcardFromSuggestion(term, definition) {
303
+ const cardData = {
304
+ term: term, definition: definition,
305
+ translation: '(traduza-me)', context_sentence: `This is a ${term}.`, gapped_sentence: `This is a _______________.`
306
+ };
307
+ renderFlashcard(cardData);
308
+ }
309
+
310
  function renderFlashcard(data) {
311
  noCardsMessage.classList.add('hidden');
312
  const cardId = `card-${Date.now()}`;
313
  const container = document.createElement('div');
314
  container.className = 'flashcard-container';
315
  container.id = cardId;
316
+ const minHeight = 350;
317
  container.style.minHeight = `${minHeight}px`;
 
318
  container.innerHTML = `
319
  <div class="flashcard-inner" style="min-height: ${minHeight}px;">
320
  <div class="flashcard-front">
321
+ <div>
322
+ <div class="text-sm text-gray-600 mb-2">Frase de Contexto:</div>
323
+ <p class="text-lg text-center text-gray-800">${data.gapped_sentence}</p>
324
+ </div>
325
+ <div class="border-t pt-4 mt-4 text-center">
326
+ <strong class="text-indigo-600">Dica (PT):</strong> ${data.translation}
327
+ </div>
328
+ <div class="text-xs text-center text-gray-400 mt-4">Clique para ver a resposta</div>
329
  </div>
330
  <div class="flashcard-back">
331
+ <div>
332
+ <h3 class="text-xl font-bold text-center text-indigo-600 mb-2">${data.term}</h3>
333
+ <p class="flex items-center justify-center gap-2 text-gray-600 italic mb-3">
334
+ <button class="audio-btn" onclick="playAudio('${data.context_sentence.replace(/'/g, "\\'")}', event)">🔊</button>
335
+ <span>${data.context_sentence}</span>
336
+ </p>
337
+ <p class="text-sm text-gray-800"><strong class="font-semibold">Definição:</strong> ${data.definition}</p>
338
+ </div>
339
+ <div class="border-t mt-3 pt-3">
340
+ <h4 class="text-sm font-semibold text-center">Pratique sua Pronúncia</h4>
341
+ <div class="flex justify-center items-center gap-2 mt-2">
342
+ <button class="btn btn-primary w-12 h-12 rounded-full" onclick="handlePronunciationPractice(this, '${data.context_sentence.replace(/'/g, "\\'")}', event)">🎙️</button>
343
+ </div>
344
+ <div class="text-xs text-gray-600 p-2 mt-2 bg-gray-50 rounded-md min-h-[40px]" data-feedback-area></div>
345
+ </div>
346
  </div>
347
  </div>`;
 
348
  flashcardList.prepend(container);
349
  container.addEventListener('click', () => container.classList.toggle('flipped'));
350
  }
351
+
352
+ // --- LÓGICA DE PRÁTICA DE PRONÚNCIA ---
353
+ async function handlePronunciationPractice(button, targetText, event) {
354
  event.stopPropagation();
355
+ const feedbackArea = button.closest('.flashcard-back').querySelector('[data-feedback-area]');
356
+ const practiceRec = new SpeechRecognition();
357
+ practiceRec.lang = 'en-US';
358
+ button.innerHTML = '<div class="spinner"></div>';
359
+ button.disabled = true;
360
+ feedbackArea.textContent = 'Ouvindo...';
361
+ practiceRec.start();
362
+ practiceRec.onresult = async (e) => {
363
+ const userText = e.results[0][0].transcript;
364
+ feedbackArea.textContent = `Você disse: "${userText}". Analisando...`;
365
+ try {
366
+ const response = await fetch('/pronunciation-feedback', {
367
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
368
+ body: JSON.stringify({ target_text: targetText, user_text: userText })
369
+ });
370
+ if (!response.ok) throw new Error((await response.json()).error);
371
+ const data = await response.json();
372
+ feedbackArea.innerHTML = `<strong>Feedback:</strong> ${data.feedback}`;
373
+ } catch (error) {
374
+ feedbackArea.textContent = `Erro na análise: ${error.message}`;
375
+ } finally {
376
+ button.innerHTML = '🎙️';
377
+ button.disabled = false;
378
+ }
379
+ };
380
+ practiceRec.onerror = (e) => {
381
+ feedbackArea.textContent = `Erro ao gravar: ${e.error}`;
382
+ button.innerHTML = '🎙️';
383
+ button.disabled = false;
384
+ };
385
+ }
386
+
387
+ // --- FUNÇÕES AUXILIARES DE ÁUDIO ---
388
+ async function fetchAudioBlob(text) {
389
+ const response = await fetch('/tts-proxy', {
390
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
391
+ body: JSON.stringify({ text: text })
392
+ });
393
+ if (!response.ok) throw new Error('Falha ao gerar áudio no backend.');
394
+ return await response.blob();
395
  }
396
 
397
+ async function playAudio(text, event) {
398
+ if(event) event.stopPropagation();
399
+ try {
400
+ const audioBlob = await fetchAudioBlob(text);
401
+ const audioUrl = URL.createObjectURL(audioBlob);
402
+ const audio = new Audio(audioUrl);
403
+ audio.play();
404
+ audio.onended = () => URL.revokeObjectURL(audioUrl);
405
+ } catch (error) { console.error('Erro ao tocar áudio:', error); }
406
+ }
407
+
408
+ // --- INICIALIZAÇÃO ---
409
+ document.addEventListener('DOMContentLoaded', () => {
410
+ initializeSpeechRecognition();
411
+ });
412
  </script>
413
 
414
  </body>