Skip to content

Commit ff5afea

Browse files
committed
working
1 parent be2961b commit ff5afea

File tree

5 files changed

+315
-54
lines changed

5 files changed

+315
-54
lines changed

src/pages/prototype/auth.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from sesame_ai import SesameAI, TokenManager
2+
3+
# Create API client
4+
client = SesameAI()
5+
6+
# Create an anonymous account
7+
signup_response = client.create_anonymous_account()
8+
print(f"ID Token: {signup_response.id_token}")
9+
10+
# Look up account information
11+
lookup_response = client.get_account_info(signup_response.id_token)
12+
print(f"User ID: {lookup_response.local_id}")
13+
14+
# For easier token management, use TokenManager
15+
token_manager = TokenManager(client, token_file="token.json")
16+
id_token = token_manager.get_valid_token()

src/pages/prototype/components/SesameAI.jsx

Lines changed: 117 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,13 @@ import {
1111
IconButton,
1212
skinVars,
1313
Spinner,
14+
Button,
15+
ButtonPrimary,
1416
} from "@telefonica/mistica";
1517

1618
/**
1719
* SesameAI component
18-
* Esta versión no intenta reproducir audio en el navegador, ya que el audio es manejado
19-
* directamente por el servidor Python usando los dispositivos de audio del sistema.
20+
* Versión con mejor conectividad y registro de eventos
2021
*/
2122
const SesameAI = ({
2223
onResponse,
@@ -30,37 +31,68 @@ const SesameAI = ({
3031
const [assistantResponse, setAssistantResponse] = useState("");
3132
const [error, setError] = useState(null);
3233
const [connectionStatus, setConnectionStatus] = useState("");
34+
const [logs, setLogs] = useState([]);
3335

34-
// Server URL
36+
// Server URL - Asegúrate de que esta URL es correcta
3537
const API_URL = "http://localhost:5000/api";
3638

39+
// Función para añadir logs
40+
const addLog = (message) => {
41+
console.log(message); // Loguear también en consola
42+
setLogs((prevLogs) =>
43+
[...prevLogs, `${new Date().toLocaleTimeString()}: ${message}`].slice(-10)
44+
);
45+
};
46+
3747
// Comprobar estado del servidor
3848
const checkServerStatus = async () => {
3949
try {
50+
addLog("Comprobando estado del servidor...");
4051
const response = await fetch("http://localhost:5000/health");
4152
if (!response.ok) {
4253
throw new Error(`Error de servidor: ${response.status}`);
4354
}
4455
const data = await response.json();
45-
console.log("Estado del servidor:", data);
56+
addLog(`Estado del servidor: ${JSON.stringify(data)}`);
4657

4758
setConnectionStatus(
4859
data.sesame_connected
49-
? "conectado"
60+
? data.sesame_initialized
61+
? "conectado y listo"
62+
: "conectado, inicializando"
5063
: "servidor activo, sesame desconectado"
5164
);
5265

5366
return data;
5467
} catch (err) {
5568
console.error("Error comprobando estado del servidor:", err);
56-
setConnectionStatus("error");
69+
addLog(`Error: ${err.message}`);
70+
setConnectionStatus(`error: ${err.message}`);
5771
return null;
5872
}
5973
};
6074

75+
// Reiniciar el servidor
76+
const restartServer = async () => {
77+
try {
78+
addLog("Solicitando reinicio del servidor...");
79+
const response = await fetch("http://localhost:5000/restart");
80+
const data = await response.json();
81+
addLog(`Respuesta: ${JSON.stringify(data)}`);
82+
83+
// Comprobar estado después del reinicio
84+
setTimeout(checkServerStatus, 2000);
85+
86+
return data.success;
87+
} catch (err) {
88+
addLog(`Error reiniciando: ${err.message}`);
89+
return false;
90+
}
91+
};
92+
6193
// Iniciar conversación
6294
const startConversation = async () => {
63-
console.log("Iniciando conversación...");
95+
addLog("Iniciando conversación...");
6496
setIsConnecting(true);
6597
setError(null);
6698

@@ -76,14 +108,16 @@ const SesameAI = ({
76108

77109
try {
78110
// Obtener mensaje de bienvenida
79-
console.log("Solicitando mensaje de bienvenida...");
111+
addLog("Solicitando mensaje de bienvenida...");
80112
const response = await fetch(`${API_URL}/welcome`);
81113
if (!response.ok) {
82114
throw new Error(`Error: ${response.status}`);
83115
}
84116

85117
const data = await response.json();
86-
console.log("Mensaje de bienvenida recibido:", data);
118+
addLog(
119+
`Mensaje de bienvenida recibido: ${data.text.substring(0, 30)}...`
120+
);
87121

88122
// Actualizar UI
89123
setAssistantResponse(data.text);
@@ -92,6 +126,7 @@ const SesameAI = ({
92126

93127
// Enviar planes al componente padre
94128
if (data.plans && data.plans.length > 0 && onResponse) {
129+
addLog(`Enviando ${data.plans.length} planes al componente padre`);
95130
onResponse(data.plans);
96131
}
97132

@@ -100,17 +135,25 @@ const SesameAI = ({
100135
onConversationStart();
101136
}
102137

103-
console.log("✅ Conversación iniciada correctamente");
138+
addLog("✅ Conversación iniciada correctamente");
139+
140+
// Enviar un "hola" automático para activar el saludo
141+
setTimeout(() => {
142+
if (transcript === "") {
143+
handleUserInput(null, "hola");
144+
}
145+
}, 1000);
104146
} catch (err) {
105147
console.error("❌ Error iniciando conversación:", err);
148+
addLog(`Error: ${err.message}`);
106149
setError(`Error de conexión: ${err.message}`);
107150
setIsConnecting(false);
108151
}
109152
};
110153

111154
// Finalizar conversación
112155
const endConversation = () => {
113-
console.log("Finalizando conversación...");
156+
addLog("Finalizando conversación...");
114157

115158
// Actualizar estado
116159
setIsListening(false);
@@ -121,23 +164,25 @@ const SesameAI = ({
121164
onConversationEnd();
122165
}
123166

124-
console.log("✅ Conversación finalizada");
167+
addLog("✅ Conversación finalizada");
125168
};
126169

127170
// Enviar texto
128-
const handleUserInput = (e) => {
129-
e.preventDefault();
130-
if (transcript.trim() === "") return;
171+
const handleUserInput = (e, textOverride = null) => {
172+
if (e) e.preventDefault();
131173

132-
console.log(`Enviando texto: "${transcript}"`);
174+
const textToSend = textOverride || transcript;
175+
if (textToSend.trim() === "") return;
176+
177+
addLog(`Enviando texto: "${textToSend}"`);
133178

134179
// Enviar al servidor
135180
fetch(`${API_URL}/query`, {
136181
method: "POST",
137182
headers: {
138183
"Content-Type": "application/json",
139184
},
140-
body: JSON.stringify({ text: transcript }),
185+
body: JSON.stringify({ text: textToSend }),
141186
})
142187
.then((response) => {
143188
if (!response.ok) {
@@ -146,36 +191,40 @@ const SesameAI = ({
146191
return response.json();
147192
})
148193
.then((data) => {
149-
console.log("Respuesta recibida:", data);
194+
addLog(`Respuesta recibida: ${data.text.substring(0, 30)}...`);
150195

151196
// Actualizar UI
152197
setAssistantResponse(data.text);
153198

154199
// Enviar planes
155200
if (data.plans && data.plans.length > 0 && onResponse) {
201+
addLog(`Enviando ${data.plans.length} planes al componente padre`);
156202
onResponse(data.plans);
157203
}
158204

159-
// Limpiar
160-
setTranscript("");
205+
// Limpiar si no era un textOverride
206+
if (!textOverride) {
207+
setTranscript("");
208+
}
161209
})
162210
.catch((err) => {
163211
console.error("❌ Error enviando texto:", err);
212+
addLog(`Error: ${err.message}`);
164213
setError(`Error: ${err.message}`);
165214
});
166215
};
167216

168217
// Auto-iniciar al montar el componente
169218
useEffect(() => {
170-
console.log("Componente montado, iniciando en 500ms...");
219+
addLog("Componente montado, iniciando en 1 segundo...");
171220
const timer = setTimeout(() => {
172221
startConversation();
173-
}, 500);
222+
}, 1000);
174223

175-
// Comprobar estado del servidor cada 5 segundos
224+
// Comprobar estado del servidor cada 10 segundos
176225
const statusInterval = setInterval(() => {
177226
checkServerStatus();
178-
}, 5000);
227+
}, 10000);
179228

180229
// Cleanup
181230
return () => {
@@ -188,20 +237,55 @@ const SesameAI = ({
188237
return (
189238
<Box>
190239
<Stack space={24}>
191-
{/* Indicador de estado */}
240+
{/* Indicador de estado y botones de acción */}
192241
<Box
193242
padding={8}
194243
borderRadius={8}
195244
backgroundColor={skinVars.colors.backgroundAlternative}
196245
>
197-
<Text3>Estado: {connectionStatus || "comprobando..."}</Text3>
198-
<Text3
199-
color={skinVars.colors.textSecondary}
200-
style={{ fontSize: "14px" }}
201-
>
202-
El audio se reproduce directamente en tu sistema, usando tus
203-
altavoces
204-
</Text3>
246+
<Stack space={8}>
247+
<Text3>
248+
Estado del servidor: {connectionStatus || "comprobando..."}
249+
</Text3>
250+
<Text3
251+
color={skinVars.colors.textSecondary}
252+
style={{ fontSize: "14px" }}
253+
>
254+
El audio se reproduce directamente a través de tus altavoces del
255+
sistema
256+
</Text3>
257+
<Box style={{ display: "flex", gap: "8px" }}>
258+
<ButtonPrimary
259+
small
260+
onPress={restartServer}
261+
style={{ alignSelf: "flex-start" }}
262+
>
263+
Reiniciar servidor
264+
</ButtonPrimary>
265+
<ButtonPrimary
266+
small
267+
onPress={() => handleUserInput(null, "hola")}
268+
style={{ alignSelf: "flex-start" }}
269+
>
270+
Decir "Hola"
271+
</ButtonPrimary>
272+
</Box>
273+
</Stack>
274+
</Box>
275+
276+
{/* Logs */}
277+
<Box
278+
padding={8}
279+
borderRadius={8}
280+
backgroundColor={skinVars.colors.backgroundBrandLow}
281+
style={{ display: logs.length > 0 ? "block" : "none" }}
282+
>
283+
<Text3 color={skinVars.colors.textSecondary}>Logs:</Text3>
284+
{logs.map((log, index) => (
285+
<Text3 key={index} style={{ fontSize: "12px", marginTop: "2px" }}>
286+
{log}
287+
</Text3>
288+
))}
205289
</Box>
206290

207291
{/* Avatar del asistente y respuesta */}

src/pages/prototype/index.jsx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ import {
3636
Chip,
3737
} from "@telefonica/mistica";
3838

39-
// Importar el componente mejorado
39+
// Importar el componente SesameAI
4040
import SesameAI from "./components/SesameAI";
4141

4242
const Prototype = () => {
@@ -47,17 +47,20 @@ const Prototype = () => {
4747

4848
// Handle recommendations from Sesame AI
4949
const handleRecommendations = (plans) => {
50+
console.log("Recibidos planes:", plans);
5051
setRecommendations(plans);
5152
};
5253

5354
// Handle conversation start
5455
const handleConversationStart = () => {
56+
console.log("Conversación iniciada");
5557
setConversationActive(true);
5658
setCallEnded(false);
5759
};
5860

5961
// Handle conversation end
6062
const handleConversationEnd = () => {
63+
console.log("Conversación finalizada");
6164
setConversationActive(false);
6265
};
6366

@@ -125,7 +128,7 @@ const Prototype = () => {
125128
<Box padding={40} paddingBottom={80}>
126129
<ResponsiveLayout>
127130
<Stack space={80}>
128-
{/* Usar el componente SesameAI en lugar de SesameAI */}
131+
{/* Usar el componente SesameAI */}
129132
<SesameAI
130133
onResponse={handleRecommendations}
131134
onConversationStart={handleConversationStart}

0 commit comments

Comments
 (0)