File size: 7,920 Bytes
eca7f7a 83003f5 2c65a29 83003f5 eca7f7a 1e8f4c6 ddf672c 1e8f4c6 ddf672c 1e8f4c6 ddf672c 1e8f4c6 ddf672c eca7f7a 83003f5 eca7f7a 83003f5 eca7f7a 83003f5 eca7f7a 83003f5 eca7f7a ddf672c 83003f5 eca7f7a 83003f5 eca7f7a 83003f5 eca7f7a 1e8f4c6 eca7f7a ddf672c 1e8f4c6 ddf672c 1e8f4c6 83003f5 1e8f4c6 83003f5 1e8f4c6 ddf672c 1e8f4c6 ddf672c 1e8f4c6 eca7f7a 1e8f4c6 ddf672c 1e8f4c6 eca7f7a ddf672c eca7f7a 1e8f4c6 ddf672c eca7f7a 83003f5 1e8f4c6 83003f5 eca7f7a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 |
import axios from "axios";
import { getDefaultHeaders } from "./session";
// Get API URL from environment or default to localhost in development
const isHFSpace = window.location.hostname.includes("hf.space");
const API_URL = isHFSpace
? "" // URL relative pour HF Spaces
: import.meta.env.VITE_API_URL || "http://localhost:8000";
// Create axios instance with default config
const api = axios.create({
baseURL: API_URL,
...(isHFSpace && {
baseURL: window.location.origin,
}),
});
// Add request interceptor to handle headers
api.interceptors.request.use((config) => {
// Routes qui ne nécessitent pas de session_id
const noSessionRoutes = [
"/api/universe/generate",
"/api/generate-image",
"/api/text-to-speech",
];
if (noSessionRoutes.includes(config.url)) {
return config;
}
// Pour toutes les autres requêtes, s'assurer qu'on a un session_id
if (!config.headers["x-session-id"]) {
throw new Error("Session ID is required for this request");
}
return config;
});
// Error handling middleware
const handleApiError = (error) => {
console.error("API Error:", {
status: error.response?.status,
statusText: error.response?.statusText,
data: error.response?.data,
config: {
method: error.config?.method,
url: error.config?.url,
data: error.config?.data,
},
});
if (error.response) {
// La requête a été faite et le serveur a répondu avec un code d'erreur
throw new Error(
error.response.data?.message ||
`Erreur ${error.response.status}: ${error.response.statusText}`
);
} else if (error.request) {
// La requête a été faite mais aucune réponse n'a été reçue
throw new Error("Aucune réponse du serveur");
} else {
// Une erreur s'est produite lors de la configuration de la requête
throw new Error(
"Une erreur est survenue lors de la configuration de la requête"
);
}
};
// Audio context for narration
let audioContext = null;
let audioSource = null;
let isSoundEnabled = true;
let hasUserInteraction = false;
// Initialize audio context on user interaction
const initAudioContext = () => {
if (!hasUserInteraction) {
console.warn("Audio context cannot be initialized before user interaction");
return null;
}
if (!audioContext) {
try {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
if (audioContext.state === "suspended") {
audioContext.resume();
}
} catch (error) {
console.error("Failed to initialize audio context:", error);
return null;
}
}
return audioContext;
};
// Function to call when user interacts with the page
const handleUserInteraction = () => {
hasUserInteraction = true;
if (audioContext && audioContext.state === "suspended") {
audioContext.resume();
}
};
// Nouvelle fonction pour gérer l'état du son
const setSoundEnabled = (enabled) => {
isSoundEnabled = enabled;
if (!enabled && audioSource) {
audioSource.stop();
audioSource = null;
}
if (!enabled && audioContext) {
audioContext.suspend();
}
};
// Story related API calls
export const storyApi = {
start: async (sessionId) => {
try {
const response = await api.post(
"/api/chat",
{
message: "restart",
},
{
headers: getDefaultHeaders(sessionId),
}
);
return response.data;
} catch (error) {
return handleApiError(error);
}
},
makeChoice: async (choiceId, sessionId) => {
try {
const response = await api.post(
"/api/chat",
{
message: "choice",
choice_id: choiceId,
},
{
headers: getDefaultHeaders(sessionId),
}
);
return response.data;
} catch (error) {
return handleApiError(error);
}
},
makeCustomChoice: async (customText, sessionId) => {
try {
const response = await api.post(
"/api/chat",
{
message: "custom_choice",
custom_text: customText,
},
{
headers: getDefaultHeaders(sessionId),
}
);
return response.data;
} catch (error) {
return handleApiError(error);
}
},
generateImage: async (
prompt,
width = 512,
height = 512,
sessionId = null
) => {
try {
const config = {
prompt,
width,
height,
};
const options = {};
if (sessionId) {
options.headers = getDefaultHeaders(sessionId);
}
const response = await api.post("/api/generate-image", config, options);
return response.data;
} catch (error) {
return handleApiError(error);
}
},
// Narration related API calls
playNarration: async (text, sessionId) => {
try {
// Ne rien faire si le son est désactivé ou si pas d'interaction utilisateur
if (!isSoundEnabled || !hasUserInteraction) {
return;
}
// Stop any existing narration
if (audioSource) {
audioSource.stop();
audioSource = null;
}
// Initialize audio context if needed
audioContext = initAudioContext();
if (!audioContext) {
return;
}
const response = await api.post(
"/api/text-to-speech",
{
text,
voice_id: "21m00Tcm4TlvDq8ikWAM", // Rachel voice
},
{
headers: getDefaultHeaders(sessionId),
}
);
if (!response.data.success) {
throw new Error("Failed to generate audio");
}
// Ne pas continuer si le son a été désactivé pendant la requête
if (!isSoundEnabled) {
return;
}
// Convert base64 to audio buffer
const audioData = atob(response.data.audio_base64);
const arrayBuffer = new ArrayBuffer(audioData.length);
const view = new Uint8Array(arrayBuffer);
for (let i = 0; i < audioData.length; i++) {
view[i] = audioData.charCodeAt(i);
}
// Decode audio data
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
// Ne pas continuer si le son a été désactivé pendant le décodage
if (!isSoundEnabled) {
return;
}
// Create and play audio source
audioSource = audioContext.createBufferSource();
audioSource.buffer = audioBuffer;
audioSource.connect(audioContext.destination);
audioSource.start(0);
// Return a promise that resolves when the audio finishes playing
return new Promise((resolve) => {
audioSource.onended = () => {
audioSource = null;
resolve();
};
});
} catch (error) {
console.error("Error playing narration:", error);
throw error;
}
},
stopNarration: () => {
if (audioSource) {
try {
audioSource.stop();
} catch (error) {
console.warn("Error stopping narration:", error);
}
audioSource = null;
}
if (audioContext) {
try {
audioContext.suspend();
} catch (error) {
console.warn("Error suspending audio context:", error);
}
}
},
initAudioContext,
handleUserInteraction,
setSoundEnabled, // Exporter la nouvelle fonction
};
// WebSocket URL
export const WS_URL = import.meta.env.VITE_WS_URL || "ws://localhost:8000/ws";
export const universeApi = {
generate: async () => {
try {
const response = await api.post("/api/universe/generate");
return response.data;
} catch (error) {
return handleApiError(error);
}
},
getStyles: async () => {
try {
const response = await api.get("/api/universe/styles");
return response.data;
} catch (error) {
return handleApiError(error);
}
},
};
// Export the base API instance for other uses
export default api;
|