Spaces:
Sleeping
Sleeping
Download src/hooks/useRealtimeWebSocket.js from Aya07/emotion-ui: direct link, hf CLI and curl.
- Browser
- Download file 7.18 kB
-
https://huggingface.co/spaces/Aya07/emotion-ui/resolve/main/src/hooks/useRealtimeWebSocket.js
- Command line
-
hf download hf://spaces/Aya07/emotion-ui/src/hooks/useRealtimeWebSocket.js
-
curl -L -o useRealtimeWebSocket.js https://huggingface.co/spaces/Aya07/emotion-ui/resolve/main/src/hooks/useRealtimeWebSocket.js
7.18 kB
| // hooks/useRealtimeWebSocket.js | |
| import { useState, useRef, useCallback, useEffect } from 'react'; | |
| const WS_URL = 'ws://localhost:8000/ws/realtime'; | |
| const SAMPLE_RATE = 16000; | |
| const CHUNK_SIZE = SAMPLE_RATE * 3; // 3 secondes | |
| export const useRealtimeWebSocket = () => { | |
| const [isConnected, setIsConnected] = useState(false); | |
| const [isRecording, setIsRecording] = useState(false); | |
| const [currentPrediction, setCurrentPrediction] = useState(null); | |
| const [history, setHistory] = useState([]); | |
| const [error, setError] = useState(null); | |
| const [bufferingProgress, setBufferingProgress] = useState(0); | |
| // Utiliser des refs pour les valeurs qui changent souvent | |
| const wsRef = useRef(null); | |
| const audioContextRef = useRef(null); | |
| const sourceRef = useRef(null); | |
| const processorRef = useRef(null); | |
| const streamRef = useRef(null); | |
| const audioBufferRef = useRef([]); | |
| const isRecordingRef = useRef(false); // ✅ Ref pour éviter les problèmes de closure | |
| // Connexion WebSocket | |
| const connect = useCallback(() => { | |
| return new Promise((resolve, reject) => { | |
| try { | |
| if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { | |
| resolve(); | |
| return; | |
| } | |
| console.log('🔌 Connexion WebSocket...'); | |
| wsRef.current = new WebSocket(WS_URL); | |
| wsRef.current.onopen = () => { | |
| console.log('✅ WebSocket connecté'); | |
| setIsConnected(true); | |
| setError(null); | |
| resolve(); | |
| }; | |
| wsRef.current.onmessage = (event) => { | |
| const data = JSON.parse(event.data); | |
| console.log('📥 Reçu dans le hook:', data); // ✅ Doit apparaître ! | |
| if (data.type === 'buffering') { | |
| setBufferingProgress(data.progress); | |
| } | |
| else if (data.type === 'prediction') { | |
| console.log('🎯 NOUVELLE PRÉDICTION:', data.emotion, data.confidence); | |
| const prediction = { | |
| emotion: data.emotion, | |
| confidence: data.confidence, | |
| details: data.all_probabilities, | |
| timestamp: new Date().toLocaleTimeString() | |
| }; | |
| setCurrentPrediction(prediction); | |
| setHistory(prev => [prediction, ...prev].slice(0, 10)); | |
| setBufferingProgress(0); | |
| } | |
| else if (data.type === 'error') { | |
| setError(data.error); | |
| } | |
| }; | |
| wsRef.current.onerror = (error) => { | |
| console.error('❌ WebSocket error:', error); | |
| setError('WebSocket connection error'); | |
| reject(error); | |
| }; | |
| wsRef.current.onclose = () => { | |
| console.log('🔌 WebSocket déconnecté'); | |
| setIsConnected(false); | |
| }; | |
| } catch (err) { | |
| setError(err.message); | |
| reject(err); | |
| } | |
| }); | |
| }, []); | |
| // Déconnexion | |
| const disconnect = useCallback(() => { | |
| if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { | |
| wsRef.current.close(); | |
| } | |
| wsRef.current = null; | |
| setIsConnected(false); | |
| }, []); | |
| // Démarrer l'enregistrement | |
| const startRealtime = useCallback(async () => { | |
| try { | |
| console.log('🎤 Démarrage...'); | |
| // 1. Vérifier la connexion WebSocket | |
| if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { | |
| setError("Connexion en cours..."); | |
| await connect(); | |
| } | |
| if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { | |
| setError("Impossible de se connecter"); | |
| return; | |
| } | |
| // 2. Demander le microphone | |
| console.log('🎤 Demande microphone...'); | |
| const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
| streamRef.current = stream; | |
| console.log('✅ Microphone obtenu'); | |
| // 3. Créer AudioContext | |
| audioContextRef.current = new (window.AudioContext || window.webkitAudioContext)(); | |
| console.log('✅ AudioContext créé, sampleRate:', audioContextRef.current.sampleRate); | |
| // 4. Créer la source | |
| sourceRef.current = audioContextRef.current.createMediaStreamSource(stream); | |
| // 5. Créer le processeur | |
| const bufferSize = 4096; | |
| processorRef.current = audioContextRef.current.createScriptProcessor(bufferSize, 1, 1); | |
| console.log('✅ Processeur créé'); | |
| // 6. Réinitialiser le buffer | |
| audioBufferRef.current = []; | |
| // 7. Définir le traitement audio (utilise la ref pour isRecording) | |
| processorRef.current.onaudioprocess = (event) => { | |
| if (!isRecordingRef.current) return; // ✅ Utilise la ref | |
| const inputData = event.inputBuffer.getChannelData(0); | |
| // Copier les samples | |
| const samples = new Float32Array(inputData.length); | |
| samples.set(inputData); | |
| audioBufferRef.current.push(...samples); | |
| // Envoyer quand on a assez (3 secondes) | |
| if (audioBufferRef.current.length >= CHUNK_SIZE) { | |
| const chunk = new Float32Array(audioBufferRef.current.slice(0, CHUNK_SIZE)); | |
| audioBufferRef.current = []; | |
| if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { | |
| console.log(`📤 Envoi chunk: ${chunk.length} samples`); | |
| wsRef.current.send(chunk.buffer); | |
| } | |
| } | |
| }; | |
| // 8. Connecter les nœuds | |
| sourceRef.current.connect(processorRef.current); | |
| processorRef.current.connect(audioContextRef.current.destination); | |
| // 9. Démarrer l'AudioContext | |
| await audioContextRef.current.resume(); | |
| // ✅ Mettre à jour les states ET les refs | |
| isRecordingRef.current = true; | |
| setIsRecording(true); | |
| setHistory([]); | |
| setCurrentPrediction(null); | |
| setError(null); | |
| console.log('🎤 ENREGISTREMENT DÉMARRÉ - Parlez !'); | |
| } catch (err) { | |
| console.error('❌ Erreur:', err); | |
| setError(err.message); | |
| } | |
| }, [connect]); | |
| // Arrêter l'enregistrement | |
| const stopRealtime = useCallback(() => { | |
| console.log('⏹️ Arrêt...'); | |
| if (processorRef.current) { | |
| processorRef.current.disconnect(); | |
| processorRef.current = null; | |
| } | |
| if (sourceRef.current) { | |
| sourceRef.current.disconnect(); | |
| sourceRef.current = null; | |
| } | |
| if (audioContextRef.current) { | |
| audioContextRef.current.close(); | |
| audioContextRef.current = null; | |
| } | |
| if (streamRef.current) { | |
| streamRef.current.getTracks().forEach(track => track.stop()); | |
| streamRef.current = null; | |
| } | |
| isRecordingRef.current = false; | |
| setIsRecording(false); | |
| audioBufferRef.current = []; | |
| console.log('⏹️ Enregistrement arrêté'); | |
| }, []); | |
| // Auto-connexion au montage | |
| useEffect(() => { | |
| connect(); | |
| return () => { | |
| stopRealtime(); | |
| disconnect(); | |
| }; | |
| }, [connect, stopRealtime, disconnect]); | |
| return { | |
| isConnected, | |
| isRecording, | |
| currentPrediction, | |
| history, | |
| error, | |
| bufferingProgress, | |
| startRealtime, | |
| stopRealtime | |
| }; | |
| }; |