Online
Interface Layerv1.3.0
Emotional States7
State Transition< 50ms
Voice Sync30 fps

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.

Emotional State OverviewAI output → sentiment → state → animation → voice tone
😌calm
👂listening
🤔thinking
😟concerned
⚠️alert
🚨emergency
😴sleeping

Speaking States Pipeline

○idle
→
◎wake-word-detected
→
◌processing
→
●speaking
→
○done

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.

States
7
Latency
< 2ms
Model
Sentiment NLP
VADERTextBlobRule-based

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.

FPS
30
States
7 anims
Mode
2D sprites
PygameCSSSprite sheets

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.

Sync rate
30 fps
Drift
< 33ms
Phonemes
7 visemes
FFTPhoneme mapPiper TTS

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.

Transition
< 50ms
States
7
Edges
11 valid
FSMasyncioObserver pattern

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.

Engine
Piper
Format
WAV 22kHz
Buffer
512 samples
PiperWAVasyncioFFT

Emotional States Reference

Emotional State Matrix

Maps AI output classification to avatar animation and TTS voice modulation

StateTrigger ConditionAvatar AnimationVoice ToneDuration
calmIdle / normal vitalsSlow breathe, neutral expressionSoft, measured toneSustained
listeningWake-word detectedEars perk, eyes widen slightlySilent / receptive≤ 5s
thinkingAI inference in progressEyes roll up, brow furrow pulseThinking hum (subtle)Inference time
concernedAnomaly / mild risk detectedBrow tilt, head tilt, amber glowLower, empathetic toneUntil resolved
alertThreshold breachRapid blink, red pulse ringElevated, clear diction≥ 10s
emergencyEmergency classification firedFull-red flash, urgent shakeCommanding, fast cadenceUntil cleared
sleepingSystem idle > 10 min, night modeEyes closed, slow chest riseSilentNight window

State Machine Definition

gui/emotion_state_machine.py
python
# 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.CALM

Audio → Avatar Sync

Audio → Viseme PipelineTTS stream → FFT → mouth morph
01

TTS Audio Stream

Piper generates WAV chunks at 22kHz as RAFIQ speaks

02

FFT Analysis

RMS amplitude + dominant frequency per 512-sample chunk

03

Phoneme Detection

Neural phoneme classifier maps audio to IPA symbols

04

Viseme Mapping

7 mouth shapes: A, E, I, O, U, M/B, Neutral

05

Avatar Morph Target

Renderer blends between mouth shapes at 30fps

gui/voice_sync.py
python
# 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 rate

Renderer Comparison

Renderer Comparison Matrix

2D current implementation vs 3D roadmap

RendererPlatform3D CapableLatencyComplexityStatus
PygameDesktop (Linux/Win)No< 5msLowCurrent
ElectronDesktop + Web hybridNo< 15msMediumCurrent
Three.jsWeb / BrowserYes< 16msHighPlanned
TauriDesktop (Rust)Yes< 8msHighEvaluated
2D GUI — CurrentPygame + Electron · Active

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.

3D GUI — RoadmapThree.js + WebGL · Planned

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.