Interface System
GUI & Emotional Avatar
RAFIQ's emotional interface layer: a state-machine-driven avatar that reflects AI emotional states through synchronized facial animation, voice tone modulation, and visual cues. Current 2D implementation in Pygame/Electron with a 3D Three.js roadmap.
Speaking States Pipeline
Core Components · 5 subsystems
Emotion Engine
Sentiment → State · AI-driven
Analyzes AI response sentiment scores and emergency flags to drive avatar emotional state. Runs post-inference, adds < 2ms overhead to each response cycle.
Avatar Renderer
Pygame 2D · CSS sprites · Canvas
Current 2D renderer using Pygame for desktop and CSS animations for web. Each emotional state maps to a sprite sheet sequence with smooth interpolation between frames.
Voice Sync
TTS waveform → viseme morphing
Analyzes TTS audio chunks in real-time using FFT amplitude and phoneme detection to drive mouth animation at 30fps. Synchronized with audio playback to avoid lip-sync drift.
State Machine
Finite state machine · async transitions
Enforces valid state transitions, preventing illegal emotional jumps (e.g. emergency → listening). Notifies all registered listeners on each transition for decoupled rendering.
TTS Bridge
Piper TTS · audio streaming · sync
Bridges the text-to-speech engine with the avatar renderer. Streams audio chunks through FFT analysis pipeline, controls playback timing, and signals end-of-speech to state machine.
Emotional States Reference
Emotional State Matrix
Maps AI output classification to avatar animation and TTS voice modulation
| State | Trigger Condition | Avatar Animation | Voice Tone | Duration |
|---|---|---|---|---|
| calm | Idle / normal vitals | Slow breathe, neutral expression | Soft, measured tone | Sustained |
| listening | Wake-word detected | Ears perk, eyes widen slightly | Silent / receptive | ≤ 5s |
| thinking | AI inference in progress | Eyes roll up, brow furrow pulse | Thinking hum (subtle) | Inference time |
| concerned | Anomaly / mild risk detected | Brow tilt, head tilt, amber glow | Lower, empathetic tone | Until resolved |
| alert | Threshold breach | Rapid blink, red pulse ring | Elevated, clear diction | ≥ 10s |
| emergency | Emergency classification fired | Full-red flash, urgent shake | Commanding, fast cadence | Until cleared |
| sleeping | System idle > 10 min, night mode | Eyes closed, slow chest rise | Silent | Night window |
State Machine Definition
# RAFIQ Emotional State Machine (Python pseudocode)
from enum import Enum
from dataclasses import dataclass
import asyncio
class EmotionState(Enum):
CALM = "calm"
LISTENING = "listening"
THINKING = "thinking"
CONCERNED = "concerned"
ALERT = "alert"
EMERGENCY = "emergency"
SLEEPING = "sleeping"
@dataclass
class StateTransition:
from_state: EmotionState
to_state: EmotionState
trigger: str
animation: str
voice_tone: str
# Valid state transition matrix
TRANSITIONS = {
EmotionState.CALM: [EmotionState.LISTENING, EmotionState.CONCERNED, EmotionState.SLEEPING],
EmotionState.LISTENING: [EmotionState.THINKING, EmotionState.CALM],
EmotionState.THINKING: [EmotionState.CALM, EmotionState.CONCERNED, EmotionState.ALERT],
EmotionState.CONCERNED: [EmotionState.ALERT, EmotionState.CALM],
EmotionState.ALERT: [EmotionState.EMERGENCY, EmotionState.CALM],
EmotionState.EMERGENCY: [EmotionState.CALM], # Only cleared by operator
EmotionState.SLEEPING: [EmotionState.CALM, EmotionState.LISTENING],
}
class EmotionalStateMachine:
def __init__(self):
self.state = EmotionState.CALM
self._listeners = []
async def transition(self, new_state: EmotionState, reason: str = "") -> bool:
if new_state not in TRANSITIONS.get(self.state, []):
return False # Invalid transition
prev = self.state
self.state = new_state
await self._notify(prev, new_state, reason)
return True
async def _notify(self, prev, curr, reason):
for listener in self._listeners:
await listener(prev, curr, reason)
def from_sentiment(self, sentiment_score: float, emergency: bool) -> EmotionState:
if emergency: return EmotionState.EMERGENCY
if sentiment_score < -0.7: return EmotionState.ALERT
if sentiment_score < -0.3: return EmotionState.CONCERNED
if sentiment_score > 0.5: return EmotionState.CALM
return EmotionState.CALMAudio → Avatar Sync
TTS Audio Stream
Piper generates WAV chunks at 22kHz as RAFIQ speaks
FFT Analysis
RMS amplitude + dominant frequency per 512-sample chunk
Phoneme Detection
Neural phoneme classifier maps audio to IPA symbols
Viseme Mapping
7 mouth shapes: A, E, I, O, U, M/B, Neutral
Avatar Morph Target
Renderer blends between mouth shapes at 30fps
# Audio → Avatar Sync Pipeline
# TTS audio stream → waveform analysis → viseme mapping → avatar morph
async def audio_avatar_sync(tts_stream: AsyncIterator[bytes]):
async for chunk in tts_stream:
amplitude = compute_rms(chunk) # Root mean square amplitude
frequency = fft_dominant(chunk) # Dominant frequency band
viseme = phoneme_to_viseme(chunk) # Phoneme detection → viseme code
await avatar_renderer.update({
"mouth_open": amplitude * 0.8, # 0.0–1.0 openness
"mouth_shape": viseme, # 'A', 'E', 'I', 'O', 'U', 'M', 'B'
"expression": "speaking",
})
await asyncio.sleep(1 / 30) # 30fps sync rateRenderer Comparison
Renderer Comparison Matrix
2D current implementation vs 3D roadmap
| Renderer | Platform | 3D Capable | Latency | Complexity | Status |
|---|---|---|---|---|---|
| Pygame | Desktop (Linux/Win) | No | < 5ms | Low | Current |
| Electron | Desktop + Web hybrid | No | < 15ms | Medium | Current |
| Three.js | Web / Browser | Yes | < 16ms | High | Planned |
| Tauri | Desktop (Rust) | Yes | < 8ms | High | Evaluated |
Pygame Desktop
Sprite-based 2D avatar on dedicated display or fullscreen overlay. 30fps sprite animation with state-driven frame selection.
Low CPU Usage
< 5% CPU at idle, < 15% during speaking animation on base MiniPC hardware.
Electron Shell
Web-embedded version of the 2D avatar for kiosk mode on touch displays using Canvas 2D API.
Three.js Avatar
Full 3D rigged character with blend shape morphing. glTF model with 52 facial action units for hyper-realistic expressions.
Shader-driven Glow
Real-time post-processing: emotional state drives ambient light color, bloom intensity, and chromatic aberration.
WebXR Ready
Planned WebXR support for AR overlay on smart glasses. Avatar projected into physical space for immersive care assistant.