aarnal80 commited on
Commit
f1602bc
verified
1 Parent(s): 417182d

Upload 7 files

Browse files
config/providers.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [
2
+ { "name": "Proveedor 1", "url": "https://api.proveedor1.com" },
3
+ { "name": "Proveedor 2", "url": "https://api.proveedor2.com" }
4
+ ]
js/analysisModule.js ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { llmProviders } from './iaConfigModule.js';
2
+
3
+ // M贸dulo de an谩lisis m茅dico con LLM configurado (llamadas front-end)
4
+ export async function analyzeMedical(text) {
5
+ if (!text) return '';
6
+ const cfg = JSON.parse(localStorage.getItem('iaConfig')) || {};
7
+ const provider = cfg.llm.provider;
8
+ const provObj = llmProviders.find(p => p.value === provider) || {};
9
+ // Obtener API key adecuada del proveedor
10
+ const apiKey = cfg.llm.apiKeys?.[provider] ?? cfg.llm.apiKey;
11
+ const model = cfg.llm.model;
12
+ const url = `${provObj.url}/v1/chat/completions`;
13
+ const systemMessage = 'Eres un m茅dico experto especializado en generar informes cl铆nicos concisos y estructurados.';
14
+ const userPrompt = `Te dar茅 la transcripci贸n detallada de mi conversaci贸n con la paciente y t煤 escribe una descripci贸n detallada de la enfermedad actual y la exploraci贸n f铆sica de un paciente en contexto cl铆nico, siguiendo estas caracter铆sticas:\n
15
+ Enfermedad actual:\n- Incluye la edad, el g茅nero y el motivo de consulta del paciente. (si no te doy el dato, omite).\n- Detalla evoluci贸n de s铆ntomas y su progresi贸n.\n- Describe signos y antecedentes relevantes con lenguaje t茅cnico comprensible.\n
16
+ Exploraci贸n f铆sica:\n- Describe hallazgos objetivos observados en la exploraci贸n.\n- Usa t茅rminos m茅dicos precisos, sin juicios diagn贸sticos.\n
17
+ Tareas del modelo:\n- Responde en dos p谩rrafos, sin t铆tulos 'Enfermedad actual:' ni 'Exploraci贸n f铆sica:'.\n- El primero para la enfermedad actual.\n- El segundo para la exploraci贸n.\n
18
+ Transcripci贸n: ${text}`;
19
+ let messages;
20
+ if (provider === 'openai') {
21
+ // Some OpenAI models don't support 'system' role
22
+ messages = [
23
+ { role: 'user', content: `${systemMessage}\n\n${userPrompt}` }
24
+ ];
25
+ } else {
26
+ messages = [
27
+ { role: 'system', content: systemMessage },
28
+ { role: 'user', content: userPrompt }
29
+ ];
30
+ }
31
+ // Construir payload, omitir temperature para mini-modelos OpenAI
32
+ const payload = { model, messages };
33
+ if (!(provider === 'openai' && model.includes('-mini-'))) {
34
+ payload.temperature = 0.5;
35
+ }
36
+ const res = await fetch(url, {
37
+ method: 'POST',
38
+ headers: {
39
+ 'Authorization': `Bearer ${apiKey}`,
40
+ 'Content-Type': 'application/json'
41
+ },
42
+ body: JSON.stringify(payload)
43
+ });
44
+ if (!res.ok) {
45
+ const err = await res.text();
46
+ throw new Error(`Error en an谩lisis m茅dico: ${res.status} ${err}`);
47
+ }
48
+ const data = await res.json();
49
+ return data.choices?.[0]?.message?.content || '';
50
+ }
js/clipboardModule.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // js/clipboardModule.js
2
+ // Funciones para copiar texto al portapapeles
3
+ export async function copyText(text) {
4
+ if (navigator.clipboard && navigator.clipboard.writeText) {
5
+ return navigator.clipboard.writeText(text);
6
+ }
7
+ // Fallback para navegadores antiguos
8
+ const textarea = document.createElement('textarea');
9
+ textarea.value = text;
10
+ textarea.setAttribute('readonly', '');
11
+ textarea.style.position = 'absolute';
12
+ textarea.style.left = '-9999px';
13
+ document.body.appendChild(textarea);
14
+ textarea.select();
15
+ try {
16
+ document.execCommand('copy');
17
+ } catch (err) {
18
+ console.error('Fallback: error copiando al portapapeles', err);
19
+ throw err;
20
+ } finally {
21
+ document.body.removeChild(textarea);
22
+ }
23
+ }
js/iaConfigModule.js ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // js/iaConfigModule.js
2
+ const defaultConfig = {
3
+ llm: {
4
+ provider: "deepseek",
5
+ apiKeys: { deepseek: "", openai: "" },
6
+ model: "deepseek-chat"
7
+ },
8
+ transcription: {
9
+ provider: "openai",
10
+ apiKeys: { openai: "", deepgram: "" },
11
+ models: { openai: "whisper-1", deepgram: "nova-2" }
12
+ }
13
+ };
14
+
15
+ // Lista de modelos actualizada (2024)
16
+ export const llmProviders = [
17
+ { name: "OpenAI", value: "openai", models: ["gpt-4o-mini-2024-07-18","chatgpt-4o-latest","o1-mini-2024-09-12","o4-mini-2025-04-16"], url: "https://api.openai.com" },
18
+ { name: "Gemini", value: "gemini", models: [
19
+ "gemini-2.5-flash-preview-04-17", // Versi贸n preliminar de Gemini 2.5 Flash 04-17
20
+ "gemini-2.0-flash", // Gemini 2.0 Flash
21
+ "gemini-2.0-flash-lite", // Gemini 2.0 Flash-Lite
22
+ "gemini-1.5-flash" // Gemini 1.5 Flash
23
+ ], url: "https://generativelanguage.googleapis.com" },
24
+ { name: "DeepSeek", value: "deepseek", models: ["deepseek-chat", "deepseek-reasoner"], url: "https://api.deepseek.com" }
25
+ ];
26
+ export const transcriptionProviders = [
27
+ { name: "OpenAI Whisper", value: "openai", models: ["whisper-1"], url: "https://api.openai.com" },
28
+ { name: "Deepgram", value: "deepgram", models: ["nova-2", "whisper-large"], url: "https://api.deepgram.com" }
29
+ ];
30
+
31
+ function saveConfig(config) {
32
+ localStorage.setItem("iaConfig", JSON.stringify(config));
33
+ }
34
+ function loadConfig() {
35
+ const config = JSON.parse(localStorage.getItem("iaConfig")) || defaultConfig;
36
+ // Migrar configuraci贸n antigua de transcription
37
+ if (config.transcription.apiKey !== undefined) {
38
+ const oldKey = config.transcription.apiKey;
39
+ const oldModel = config.transcription.model;
40
+ config.transcription.apiKeys = { [config.transcription.provider]: oldKey, deepgram: "" };
41
+ config.transcription.models = { [config.transcription.provider]: oldModel, deepgram: "nova-2" };
42
+ delete config.transcription.apiKey;
43
+ delete config.transcription.model;
44
+ saveConfig(config);
45
+ }
46
+ // Migrar configuraci贸n antigua de LLM apiKey a apiKeys
47
+ if (config.llm.apiKey !== undefined) {
48
+ const old = config.llm.apiKey;
49
+ config.llm.apiKeys = { ...defaultConfig.llm.apiKeys, [config.llm.provider]: old };
50
+ delete config.llm.apiKey;
51
+ saveConfig(config);
52
+ }
53
+ // Migrar modelos obsoletos de DeepSeek a 'deepseek-chat'
54
+ if (config.llm.provider === 'deepseek' && (config.llm.model === 'deepseek-v3' || config.llm.model === 'deepseek-llm')) {
55
+ config.llm.model = 'deepseek-chat';
56
+ console.log('[iaConfigModule] Migrado modelo DeepSeek a deepseek-chat');
57
+ saveConfig(config);
58
+ }
59
+ return config;
60
+ }
61
+ export function getIaConfig() {
62
+ return loadConfig();
63
+ }
64
+
65
+ export function renderIaConfigForm(containerId) {
66
+ let config = loadConfig();
67
+ const container = document.getElementById(containerId);
68
+ if (!container) {
69
+ console.error(`[iaConfigModule] No se encontr贸 el contenedor '${containerId}'`);
70
+ document.body.insertAdjacentHTML('beforeend', `<div style='color:red'>[Error] No se encontr贸 el contenedor '${containerId}' para la configuraci贸n IA.</div>`);
71
+ return;
72
+ }
73
+
74
+ function maskApiKey(key) {
75
+ if (!key) return '';
76
+ if (key.length <= 8) return '*'.repeat(key.length);
77
+ return key.substring(0, 3) + '-****' + key.slice(-4);
78
+ }
79
+
80
+ container.innerHTML = `
81
+ <div class="flex justify-between items-center mb-6 border-b pb-2 border-blue-100">
82
+ <h2 class="text-xl font-bold text-blue-700 flex items-center">
83
+ <i class='fas fa-cogs mr-2'></i>Configurar Proveedores IA
84
+ </h2>
85
+ <button id="btnCloseConfig" type="button" class="text-gray-500 hover:text-blue-600 text-2xl focus:outline-none" aria-label="Cerrar">
86
+ <i class="fas fa-times"></i>
87
+ </button>
88
+ </div>
89
+ <form id="iaConfigForm" class="space-y-6">
90
+ <div class="bg-blue-50 p-4 rounded-lg border border-blue-100 mb-2">
91
+ <label class="block font-semibold text-blue-800 mb-2">Proveedor LLM</label>
92
+ <select id="llmProvider" class="w-full mb-3 p-2 rounded border border-gray-300 focus:ring-2 focus:ring-blue-300">
93
+ ${llmProviders.map(p => `<option value="${p.value}">${p.name}</option>`).join("")}
94
+ </select>
95
+ <div class="flex items-center mb-3">
96
+ <input type="password" id="llmApiKey" class="flex-1 p-2 rounded border border-gray-300 mr-2 bg-gray-100" placeholder="API Key LLM" autocomplete="off">
97
+ <button class="text-blue-700 hover:text-blue-900 px-3 py-2 rounded focus:outline-none border border-blue-200 bg-white" type="button" id="toggleLlmApiKey">
98
+ <i class="fas fa-eye"></i>
99
+ </button>
100
+ </div>
101
+ <select id="llmModel" class="w-full p-2 rounded border border-gray-300 focus:ring-2 focus:ring-blue-300"></select>
102
+ </div>
103
+ <div class="bg-purple-50 p-4 rounded-lg border border-purple-100 mb-2">
104
+ <label class="block font-semibold text-purple-800 mb-2">Proveedor Transcripci贸n</label>
105
+ <select id="transProvider" class="w-full mb-3 p-2 rounded border border-gray-300 focus:ring-2 focus:ring-purple-300">
106
+ ${transcriptionProviders.map(p => `<option value="${p.value}">${p.name}</option>`).join("")}
107
+ </select>
108
+ <div class="flex items-center mb-3">
109
+ <input type="password" id="transApiKey" class="flex-1 p-2 rounded border border-gray-300 mr-2 bg-gray-100" placeholder="API Key Transcripci贸n" autocomplete="off">
110
+ <button class="text-purple-700 hover:text-purple-900 px-3 py-2 rounded focus:outline-none border border-purple-200 bg-white" type="button" id="toggleTransApiKey">
111
+ <i class="fas fa-eye"></i>
112
+ </button>
113
+ </div>
114
+ <select id="transModel" class="w-full p-2 rounded border border-gray-300 focus:ring-2 focus:ring-purple-300"></select>
115
+ </div>
116
+ <button type="submit" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-semibold py-3 rounded-lg shadow transition-colors flex items-center justify-center text-lg">
117
+ <i class="fas fa-save mr-2"></i>Guardar configuraci贸n
118
+ </button>
119
+ </form>
120
+ `;
121
+
122
+ // Bot贸n de cerrar modal
123
+ const closeBtn = document.getElementById("btnCloseConfig");
124
+ if (closeBtn) {
125
+ closeBtn.addEventListener("click", () => {
126
+ const modal = document.getElementById("configModal");
127
+ if (modal) modal.classList.remove("active");
128
+ });
129
+ }
130
+
131
+ // Set initial values
132
+ document.getElementById("llmProvider").value = config.llm.provider;
133
+ document.getElementById("llmApiKey").value = maskApiKey(config.llm.apiKeys[config.llm.provider] || '');
134
+ document.getElementById("transProvider").value = config.transcription.provider;
135
+ document.getElementById("transApiKey").value = maskApiKey(config.transcription.apiKeys[config.transcription.provider] || '');
136
+
137
+ // API Key toggle (ver/ocultar)
138
+ document.getElementById("toggleLlmApiKey").addEventListener("click", () => {
139
+ const input = document.getElementById("llmApiKey");
140
+ input.type = input.type === "password" ? "text" : "password";
141
+ });
142
+ document.getElementById("toggleTransApiKey").addEventListener("click", () => {
143
+ const input = document.getElementById("transApiKey");
144
+ input.type = input.type === "password" ? "text" : "password";
145
+ });
146
+
147
+ // Populate models
148
+ function updateLlmModels() {
149
+ const prov = document.getElementById("llmProvider").value;
150
+ const providerObj = llmProviders.find(p => p.value === prov);
151
+ const models = providerObj.models;
152
+ const sel = document.getElementById("llmModel");
153
+ sel.innerHTML = models.map(m => `<option value="${m}">${m}</option>`).join("");
154
+ sel.value = config.llm.model;
155
+ }
156
+ function updateTransModels() {
157
+ const prov = document.getElementById("transProvider").value;
158
+ const providerObj = transcriptionProviders.find(p => p.value === prov);
159
+ const models = providerObj.models;
160
+ const sel = document.getElementById("transModel");
161
+ sel.innerHTML = models.map(m => `<option value="${m}">${m}</option>`).join("");
162
+ sel.value = config.transcription.models[prov] || models[0];
163
+ // Actualizar API Key input al cambiar proveedor
164
+ document.getElementById("transApiKey").value = maskApiKey(config.transcription.apiKeys[prov] || '');
165
+ }
166
+ document.getElementById("llmProvider").addEventListener("change", () => {
167
+ const p = document.getElementById("llmProvider").value;
168
+ updateLlmModels();
169
+ // Refrescar config con todas las llaves y mostrar la del proveedor seleccionado
170
+ const fresh = loadConfig();
171
+ const keyEl = document.getElementById("llmApiKey");
172
+ if (keyEl) keyEl.value = maskApiKey(fresh.llm.apiKeys[p] || '');
173
+ });
174
+ document.getElementById("transProvider").addEventListener("change", updateTransModels);
175
+ updateLlmModels();
176
+ updateTransModels();
177
+
178
+ // Save on submit
179
+ document.getElementById("iaConfigForm").addEventListener("submit", e => {
180
+ e.preventDefault();
181
+ // Persistir configuraci贸n por proveedor
182
+ const prev = config;
183
+ const newConfig = { ...prev };
184
+ // LLM: provider, apiKeys y model
185
+ const llProv = document.getElementById("llmProvider").value;
186
+ const rawKey = document.getElementById("llmApiKey").value;
187
+ const oldKey = prev.llm.apiKeys[llProv] || '';
188
+ const newKey = rawKey === maskApiKey(oldKey) ? oldKey : rawKey;
189
+ newConfig.llm = { ...prev.llm, provider: llProv, model: document.getElementById("llmModel").value };
190
+ newConfig.llm.apiKeys = { ...prev.llm.apiKeys, [llProv]: newKey };
191
+ // Transcription: provider, apiKeys y models por proveedor
192
+ const tp = document.getElementById("transProvider").value;
193
+ const rawKeyTrans = document.getElementById("transApiKey").value;
194
+ const existingKeyTrans = prev.transcription.apiKeys[tp] || '';
195
+ const actualKeyTrans = rawKeyTrans === maskApiKey(existingKeyTrans) ? existingKeyTrans : rawKeyTrans;
196
+ newConfig.transcription.provider = tp;
197
+ newConfig.transcription.apiKeys = { ...prev.transcription.apiKeys, [tp]: actualKeyTrans };
198
+ newConfig.transcription.models = { ...prev.transcription.models, [tp]: document.getElementById("transModel").value };
199
+ console.log('[iaConfigModule] Configuraci贸n guardada:', newConfig);
200
+ saveConfig(newConfig);
201
+ // Actualizar config local despu茅s de guardar
202
+ config = newConfig;
203
+ // Actualizar labels de modelo en la UI
204
+ document.dispatchEvent(new CustomEvent('iaConfigChanged'));
205
+ // Ofusca los campos API Key
206
+ document.getElementById("llmApiKey").value = maskApiKey(newConfig.llm.apiKeys[newConfig.llm.provider] || '');
207
+ document.getElementById("transApiKey").value = maskApiKey(newConfig.transcription.apiKeys[tp] || '');
208
+ document.getElementById("llmApiKey").type = "password";
209
+ document.getElementById("transApiKey").type = "password";
210
+ // Mensaje de 茅xito discreto
211
+ let msg = document.getElementById('iaConfigSavedMsg');
212
+ if (!msg) {
213
+ msg = document.createElement('div');
214
+ msg.id = 'iaConfigSavedMsg';
215
+ msg.className = 'fixed left-1/2 top-6 -translate-x-1/2 bg-green-500 text-white px-6 py-3 rounded shadow text-lg z-50';
216
+ msg.innerHTML = '<i class="fas fa-check-circle mr-2"></i>隆Configuraci贸n guardada!';
217
+ document.body.appendChild(msg);
218
+ } else {
219
+ msg.style.display = 'block';
220
+ }
221
+ setTimeout(() => { msg.style.display = 'none'; }, 2000);
222
+ // Cierra el modal
223
+ const modal = document.getElementById("configModal");
224
+ if (modal) modal.classList.remove("active");
225
+ });
226
+ }
js/main.js ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // js/main.js
2
+ import { renderIaConfigForm, transcriptionProviders } from './iaConfigModule.js';
3
+ import { initRecorder } from './recordingModule.js';
4
+ import { analyzeMedical } from './analysisModule.js';
5
+ import { copyText } from './clipboardModule.js';
6
+
7
+ window.addEventListener('DOMContentLoaded', () => {
8
+ function updateModelLabels() {
9
+ const cfg = JSON.parse(localStorage.getItem('iaConfig'));
10
+ const transModel = cfg?.transcription?.models?.[cfg.transcription.provider] || '';
11
+ const llmModel = cfg?.llm?.model || '';
12
+ const transLabel = document.getElementById('trans-model-label');
13
+ if (transLabel) transLabel.textContent = transModel ? `(${transModel})` : '';
14
+ const analysisLabel = document.getElementById('analysis-model-label');
15
+ if (analysisLabel) analysisLabel.textContent = llmModel ? `(${llmModel})` : '';
16
+ }
17
+ updateModelLabels();
18
+ document.addEventListener('iaConfigChanged', updateModelLabels);
19
+
20
+ // Elements
21
+ const btnConfig = document.getElementById('btnConfig');
22
+ const modal = document.getElementById('configModal');
23
+ const transcriptEl = document.getElementById('transcript');
24
+ const outputEnfermedadEl = document.getElementById('output-enfermedad');
25
+ const outputExploracionEl = document.getElementById('output-exploracion');
26
+ let iaConfig = renderIaConfigForm('iaConfigContainer'); // render initial form, returns config if modified
27
+
28
+ // Open modal and render form
29
+ btnConfig.addEventListener('click', () => {
30
+ renderIaConfigForm('iaConfigContainer');
31
+ modal.classList.add('active');
32
+ });
33
+ // Close modal clicking outside or on close button (handled in module)
34
+ modal.addEventListener('mousedown', e => {
35
+ if (e.target === modal) modal.classList.remove('active');
36
+ });
37
+
38
+ // An谩lisis m茅dico autom谩tico tras recibir transcripci贸n usando m贸dulo local
39
+ document.addEventListener('transcriptionReady', async e => {
40
+ try {
41
+ const result = await analyzeMedical(e.detail);
42
+ // Dividir en dos p谩rrafos y mostrar en UI
43
+ const sections = result.split(/\n\s*\n/);
44
+ outputEnfermedadEl.textContent = sections[0] || '';
45
+ outputExploracionEl.textContent = sections[1] || '';
46
+ } catch (err) {
47
+ console.error(err);
48
+ alert('Error en an谩lisis m茅dico');
49
+ }
50
+ });
51
+
52
+ // Initialize recorder
53
+ const btnStart = document.getElementById('btnStart');
54
+ const btnStop = document.getElementById('btnStop');
55
+ const transcript = transcriptEl;
56
+ function getProvider() {
57
+ const cfg = JSON.parse(localStorage.getItem('iaConfig'));
58
+ if (cfg && cfg.transcription && cfg.transcription.provider) {
59
+ const prov = transcriptionProviders.find(p => p.value === cfg.transcription.provider);
60
+ if (prov && prov.url) return prov.url;
61
+ }
62
+ alert('Debes configurar un proveedor de transcripci贸n primero.');
63
+ return '';
64
+ }
65
+ initRecorder({ btnStart, btnStop, transcriptEl: transcript, getProvider });
66
+
67
+ // Copiar transcripci贸n
68
+ const btnCopyTranscript = document.getElementById('btnCopyTranscript');
69
+ if (btnCopyTranscript) {
70
+ btnCopyTranscript.addEventListener('click', async () => {
71
+ try {
72
+ await copyText(transcriptEl.value);
73
+ console.log('Transcripci贸n copiada al portapapeles');
74
+ } catch {
75
+ console.error('Error al copiar transcripci贸n');
76
+ }
77
+ });
78
+ }
79
+ // Copiar an谩lisis m茅dico
80
+ const btnCopyAnalysis = document.getElementById('btnCopyAnalysis');
81
+ if (btnCopyAnalysis) {
82
+ btnCopyAnalysis.addEventListener('click', async () => {
83
+ try {
84
+ const text = `${outputEnfermedadEl.textContent}\n\n${outputExploracionEl.textContent}`;
85
+ await copyText(text);
86
+ console.log('An谩lisis m茅dico copiado al portapapeles');
87
+ } catch {
88
+ console.error('Error al copiar an谩lisis m茅dico');
89
+ }
90
+ });
91
+ }
92
+ });
js/recordingModule.js ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // js/recordingModule.js
2
+ export function initRecorder({ btnStart, btnStop, transcriptEl, getProvider }) {
3
+ let mediaRecorder, audioChunks = [], transcriptText = '';
4
+
5
+ btnStart.addEventListener('click', async () => {
6
+ console.log('[Recorder] Bot贸n Iniciar pulsado');
7
+ const aiProvider = getProvider();
8
+ if (!aiProvider) { alert('Selecciona un proveedor IA primero.'); return; }
9
+ try {
10
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
11
+ console.log('[Recorder] Acceso a micr贸fono concedido');
12
+ // No especificar mimeType, dejar MediaRecorder por defecto (como en AppConsultaPro)
13
+ mediaRecorder = new MediaRecorder(stream);
14
+ // Assign onstop handler immediately so onStop executes when recording stops
15
+ mediaRecorder.onstop = onStop;
16
+ console.log('[Recorder] MediaRecorder creado:', mediaRecorder);
17
+ audioChunks = [];
18
+ mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
19
+ mediaRecorder.start();
20
+ btnStart.disabled = true;
21
+ btnStop.disabled = false;
22
+ transcriptEl.value = '';
23
+ // Estado visual
24
+ const status = document.getElementById('recorder-status');
25
+ if (status) {
26
+ status.innerHTML = '<i class="fas fa-circle text-red-500 animate-pulse mr-2"></i>Consulta en progreso...';
27
+ }
28
+ } catch (err) {
29
+ console.error('[Recorder] Error al acceder al micr贸fono:', err);
30
+ alert('No se pudo acceder al micr贸fono.');
31
+ }
32
+ });
33
+
34
+ btnStop.addEventListener('click', () => {
35
+ console.log('[Recorder] Bot贸n Detener pulsado');
36
+ if (mediaRecorder) mediaRecorder.stop();
37
+ btnStop.disabled = true;
38
+ // Estado visual
39
+ const status = document.getElementById('recorder-status');
40
+ if (status) {
41
+ status.innerHTML = '<i class="fas fa-circle text-green-500 mr-2"></i>Consulta finalizada.';
42
+ }
43
+ });
44
+
45
+ async function onStop() {
46
+ console.log('[Recorder] Grabaci贸n detenida, procesando audio...');
47
+ // Obtener proveedor, API key y modelo desde config
48
+ const cfg = JSON.parse(localStorage.getItem('iaConfig'));
49
+ const transProvider = cfg.transcription.provider;
50
+ const apiKey = cfg.transcription.apiKeys[transProvider];
51
+ const transModel = cfg.transcription.models[transProvider];
52
+ // Usar solo el primer chunk si hay m谩s de uno (como en AppConsultaPro)
53
+ console.log('[Recorder] Cantidad de audioChunks:', audioChunks.length);
54
+ audioChunks.forEach((chunk, idx) => {
55
+ console.log(`[Recorder] audioChunk[${idx}]: type=${chunk.type}, size=${chunk.size}`);
56
+ });
57
+ let blobType = (audioChunks[0] && audioChunks[0].type) ? audioChunks[0].type : 'audio/webm';
58
+ let blob;
59
+ if (audioChunks.length > 0) {
60
+ // Combine all chunks into one blob to send complete audio
61
+ blob = new Blob(audioChunks, { type: blobType });
62
+ } else {
63
+ alert('No se grab贸 audio.');
64
+ return;
65
+ }
66
+ console.log('[Recorder] Tipo real del blob:', blob.type);
67
+ let transcript = '';
68
+ try {
69
+ if (cfg && cfg.transcription && cfg.transcription.provider === 'deepgram') {
70
+ // Deepgram integration
71
+ // Construir URL Deepgram con idioma, modelo y smart_format
72
+ const providerUrl = getProvider();
73
+ const deepgramUrl = `${providerUrl}/v1/listen?language=es&model=${transModel}&smart_format=true`;
74
+ console.log('[Recorder] Deepgram URL:', deepgramUrl);
75
+ console.log('[Recorder] Content-Type enviado a Deepgram:', blob.type);
76
+ const res = await fetch(deepgramUrl, {
77
+ method: 'POST',
78
+ headers: {
79
+ 'Authorization': 'Token ' + apiKey,
80
+ 'Content-Type': blob.type || 'audio/webm'
81
+ },
82
+ body: blob
83
+ });
84
+ if (!res.ok) throw new Error('Error en transcripci贸n');
85
+ const data = await res.json();
86
+ console.log('[Deepgram] Respuesta completa:', data);
87
+ transcript = data.results?.channels?.[0]?.alternatives?.[0]?.transcript || '';
88
+ console.log('[Deepgram] Transcript extra铆do:', transcript);
89
+ } else if (cfg.transcription.provider === 'openai') {
90
+ // OpenAI Whisper integration
91
+ // Reutilizar apiKey y modelo obtenidos antes
92
+ const apiKeyOA = apiKey;
93
+ const modelOA = transModel;
94
+ const fd = new FormData();
95
+ fd.append('model', modelOA);
96
+ fd.append('file', blob, 'consulta.wav');
97
+ const respOA = await fetch(`${getProvider()}/v1/audio/transcriptions`, {
98
+ method: 'POST',
99
+ headers: { 'Authorization': 'Bearer ' + apiKeyOA },
100
+ body: fd
101
+ });
102
+ if (!respOA.ok) {
103
+ const errTxt = await respOA.text();
104
+ throw new Error(`Error OpenAI transcripci贸n (${respOA.status}): ${errTxt}`);
105
+ }
106
+ const dataOA = await respOA.json();
107
+ console.log('[OpenAI Whisper] Respuesta completa:', dataOA);
108
+ transcript = dataOA.text || '';
109
+ console.log('[OpenAI Whisper] Transcript extra铆do:', transcript);
110
+ } else {
111
+ // Otros proveedores (fallback)
112
+ const formDataFB = new FormData();
113
+ formDataFB.append('file', blob, 'consulta.wav');
114
+ const respFB = await fetch(`${getProvider()}/transcribe`, { method: 'POST', body: formDataFB });
115
+ if (!respFB.ok) throw new Error('Error en transcripci贸n');
116
+ const dataFB = await respFB.json();
117
+ console.log('[Transcripci贸n otro proveedor] Respuesta completa:', dataFB);
118
+ transcript = dataFB.text || '';
119
+ console.log('[Transcripci贸n otro proveedor] Transcript extra铆do:', transcript);
120
+ }
121
+ transcriptText = transcript;
122
+ transcriptEl.value = transcriptText;
123
+ document.dispatchEvent(new CustomEvent('transcriptionReady', { detail: transcriptText }));
124
+ } catch (e) {
125
+ alert('Error en transcripci贸n');
126
+ console.error(e);
127
+ } finally {
128
+ btnStart.disabled = false;
129
+ // Estado visual
130
+ const status = document.getElementById('recorder-status');
131
+ if (status) {
132
+ status.innerHTML = '<i class="fas fa-circle text-gray-400 mr-2"></i>No hay consulta en progreso';
133
+ }
134
+ }
135
+ }
136
+ }
server.js ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // server.js
2
+ // Backend proxy para an谩lisis m茅dico y evitar CORS
3
+ require('dotenv').config();
4
+ const express = require('express');
5
+ const cors = require('cors');
6
+ const { Configuration, OpenAIApi } = require('openai');
7
+
8
+ const app = express();
9
+ const port = process.env.PORT || 3000;
10
+
11
+ app.use(cors());
12
+ app.use(express.json());
13
+
14
+ app.post('/medical-analyze', async (req, res) => {
15
+ try {
16
+ const { provider, model, apiKey, text } = req.body;
17
+ // Prompts
18
+ const systemMessage = 'Eres un m茅dico experto especializado en generar informes cl铆nicos concisos y estructurados.';
19
+ const userPrompt = `Te dar茅 la transcripci贸n detallada de mi conversaci贸n con la paciente y t煤 escribe una descripci贸n detallada de la enfermedad actual y la exploraci贸n f铆sica de un paciente en contexto cl铆nico, siguiendo estas caracter铆sticas:\n
20
+ Enfermedad actual:\n- Incluye la edad, el g茅nero y el motivo de consulta del paciente. (si no te doy el dato, omite).\n- Detalla evoluci贸n de s铆ntomas y su progresi贸n.\n- Describe signos y antecedentes relevantes con lenguaje t茅cnico comprensible.\n
21
+ Exploraci贸n f铆sica:\n- Describe hallazgos objetivos observados en la exploraci贸n.\n- Usa t茅rminos m茅dicos precisos, sin juicios diagn贸sticos.\n
22
+ Tareas del modelo:\n- Responde en dos p谩rrafos, sin t铆tulos 'Enfermedad actual:' ni 'Exploraci贸n f铆sica:'.\n- El primero para la enfermedad actual.\n- El segundo para la exploraci贸n.\n
23
+ Transcripci贸n: ${text}`;
24
+ const messages = [
25
+ { role: 'system', content: systemMessage },
26
+ { role: 'user', content: userPrompt }
27
+ ];
28
+ let analysis;
29
+ if (provider === 'openai') {
30
+ const configuration = new Configuration({ apiKey });
31
+ const openai = new OpenAIApi(configuration);
32
+ const response = await openai.createChatCompletion({ model, messages, temperature: 0.5 });
33
+ analysis = response.data.choices[0].message.content;
34
+ } else if (provider === 'deepseek' || provider === 'gemini') {
35
+ // Definir URLs por proveedor
36
+ const urls = { deepseek: 'https://api.deepseek.com/v1/chat/completions', gemini: 'https://generativelanguage.googleapis.com/v1/chat/completions' };
37
+ const url = urls[provider];
38
+ const resp = await fetch(url, {
39
+ method: 'POST', headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
40
+ body: JSON.stringify({ model, messages, temperature: 0.5 })
41
+ });
42
+ if (!resp.ok) throw new Error(`Error ${provider}: ${resp.status}`);
43
+ const data = await resp.json();
44
+ analysis = data.choices?.[0]?.message?.content;
45
+ } else {
46
+ throw new Error('Proveedor no soportado: ' + provider);
47
+ }
48
+ res.json({ analysis });
49
+ } catch (error) {
50
+ console.error('Error /medical-analyze:', error);
51
+ res.status(500).json({ error: error.message });
52
+ }
53
+ });
54
+
55
+ app.listen(port, () => {
56
+ console.log(`Backend listening on http://localhost:${port}`);
57
+ });