Spaces:
Running on Zero
Running on Zero
ui upgrade
Browse filesFiles changed (13)
- .gitignore+6
- app.py+3-3
- app/globals.css+99-2
- app/page.tsx+15-17
- backend/__pycache__/server.cpython-314.pyc
- backend/server.py+8-8
- src/components/GameCharacterAvatar.tsx+447-124
- src/components/MessageItem.tsx+1-1
- src/components/SonicCharacter.tsx+17-12
- src/components/SonicSplashIntro.tsxAdded+55
- src/hooks/useVoiceRAG.ts+1-1
- src/lib/soundEffects.ts+147
- src/lib/ttsEngine.ts+1-1
22 unmodified lines2324252627282 unmodified lines31323322 unmodified lines# Private Session CheckpointsCHAT_SESSION_CHECKPOINT.md# Misc & Logs.DS_Store*.pem2 unmodified linesyarn-debug.log*yarn-error.log*.vercel22 unmodified lines23242526272829303132332 unmodified lines3637383922 unmodified lines# Private Session CheckpointsCHAT_SESSION_CHECKPOINT.md# Python Cache__pycache__/*.py[cod]*$py.class# Misc & Logs.DS_Store*.pem2 unmodified linesyarn-debug.log*yarn-error.log*.vercel
61 unmodified lines626364656667686914 unmodified lines84858687888990114 unmodified lines20520620720820921021161 unmodified lines)LANGUAGES = [("🇮🇳 Hindi (हिन्दी)", "hi-IN"),("🌐 English (Indian)", "en-IN"),("🇮🇳 Tamil (தமிழ்)", "ta-IN"),("🇮🇳 Telugu (తెలుగు)", "te-IN"),("🇮🇳 Bengali (বাংলা)", "bn-IN"),14 unmodified lineslanguage_label: str):"""Gradio handler for text or voice queries with ZeroGPU acceleration."""lang_code = LANG_MAP.get(language_label, "hi-IN")# 1. Process Voice if providedtranscript = query_text.strip() if query_text else ""114 unmodified lineswith gr.Column(scale=1):lang_dropdown = gr.Dropdown(choices=[label for label, _ in LANGUAGES],value="🇮🇳 Hindi (हिन्दी)",label="Select Indic Language")text_input = gr.Textbox(61 unmodified lines626364656667686914 unmodified lines84858687888990114 unmodified lines20520620720820921021161 unmodified lines)LANGUAGES = [("🌐 English (Indian)", "en-IN"),("🇮🇳 Hindi (हिन्दी)", "hi-IN"),("🇮🇳 Tamil (தமிழ்)", "ta-IN"),("🇮🇳 Telugu (తెలుగు)", "te-IN"),("🇮🇳 Bengali (বাংলা)", "bn-IN"),14 unmodified lineslanguage_label: str):"""Gradio handler for text or voice queries with ZeroGPU acceleration."""lang_code = LANG_MAP.get(language_label, "en-IN")# 1. Process Voice if providedtranscript = query_text.strip() if query_text else ""114 unmodified lineswith gr.Column(scale=1):lang_dropdown = gr.Dropdown(choices=[label for label, _ in LANGUAGES],value="🌐 English (Indian)",label="Select Indic Language")text_input = gr.Textbox(
84 unmodified lines8586878889909192939430 unmodified lines12512612712812913022 unmodified lines15315415515615715884 unmodified lines@keyframes scanline {0% {transform: translateY(-100%);}100% {transform: translateY(200%);}}30 unmodified lines}}.animate-float {animation: float 4s ease-in-out infinite;}22 unmodified linesanimation: eyeBlink 3.5s infinite;}/* Glassmorphism & High-tech Borders */.glass-panel {background: rgba(15, 17, 23, 0.7);84 unmodified lines85868788899091929394959697989910010110230 unmodified lines13313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021122 unmodified lines23423523623723823924024124224324424524624724824925025125225325425584 unmodified lines@keyframes scanline {0% {transform: translateY(0px);opacity: 0.1;}20% {opacity: 0.95;}80% {opacity: 0.95;}100% {transform: translateY(64px);opacity: 0.1;}}30 unmodified lines}}@keyframes cyberDance {0%, 100% {transform: translateY(0px) rotate(0deg) scale(1);}20% {transform: translateY(-12px) rotate(-8deg) scale(1.05);}40% {transform: translateY(2px) rotate(6deg) scale(0.98);}60% {transform: translateY(-10px) rotate(8deg) scale(1.05);}80% {transform: translateY(1px) rotate(-6deg) scale(0.98);}}@keyframes turboSpin {0% {transform: rotate(0deg) scale(1);}50% {transform: rotate(180deg) scale(1.2);}100% {transform: rotate(360deg) scale(1);}}@keyframes hyperCharge {0%, 100% {transform: scale(1);filter: drop-shadow(0 0 10px rgba(16, 185, 129, 0.4));}25% {transform: scale(1.06) translate(-2px, 1px);filter: drop-shadow(0 0 25px rgba(6, 182, 212, 0.8));}50% {transform: scale(1.08) translate(2px, -1px);filter: drop-shadow(0 0 35px rgba(245, 158, 11, 0.9));}75% {transform: scale(1.06) translate(-1px, -2px);filter: drop-shadow(0 0 25px rgba(16, 185, 129, 0.8));}}@keyframes soundwaveBar {0%, 100% {transform: scaleY(0.3);}50% {transform: scaleY(1.2);}}@keyframes bubblePop {0% {opacity: 0;transform: translateY(10px) scale(0.85);}70% {opacity: 1;transform: translateY(-3px) scale(1.03);}100% {opacity: 1;transform: translateY(0) scale(1);}}.animate-float {animation: float 4s ease-in-out infinite;}22 unmodified linesanimation: eyeBlink 3.5s infinite;}.animate-cyber-dance {animation: cyberDance 0.85s ease-in-out infinite;}.animate-turbo-spin {animation: turboSpin 0.75s cubic-bezier(0.34, 1.56, 0.64, 1);}.animate-hyper-charge {animation: hyperCharge 0.4s ease-in-out infinite;}.animate-bubble-pop {animation: bubblePop 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards;}/* Glassmorphism & High-tech Borders */.glass-panel {background: rgba(15, 17, 23, 0.7);
10 unmodified lines1112131415167 unmodified lines242526272829303118 unmodified lines505152535455565780 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016120 unmodified lines18218318418518618718811 unmodified lines20020120220320420544 unmodified lines25025125225325425510 unmodified linesimport { CyberBackground } from '@/src/components/CyberBackground';import { CharacterState } from '@/src/components/SonicCharacter';import { SonicLogo } from '@/src/components/SonicLogo';import { sounds } from '@/src/lib/soundEffects';import { ttsEngine } from '@/src/lib/ttsEngine';import {7 unmodified lines} from 'lucide-react';const SUPPORTED_LANGUAGES = [{ code: 'hi-IN', label: '🇮🇳 Hindi (हिन्दी)' },{ code: 'en-IN', label: '🌐 English (Indian)' },{ code: 'ta-IN', label: '🇮🇳 Tamil (தமிழ்)' },{ code: 'te-IN', label: '🇮🇳 Telugu (తెలుగు)' },{ code: 'bn-IN', label: '🇮🇳 Bengali (বাংলা)' },18 unmodified lines}}, []);const [selectedLanguage, setSelectedLanguage] = useState('hi-IN');const [mounted, setMounted] = useState(false);const [isSidebarOpen, setIsSidebarOpen] = useState(true);const [isAudioEnabled, setIsAudioEnabled] = useState(true);const [activeCitationModal, setActiveCitationModal] = useState<{80 unmodified linesconst selectedLangObj = SUPPORTED_LANGUAGES.find((l) => l.code === selectedLanguage);if (!mounted) {return (<main className="min-h-screen bg-zinc-950 text-zinc-100 flex flex-col items-center justify-center gap-4 selection:bg-emerald-500 selection:text-black"><div className="relative flex items-center justify-center"><div className="absolute inset-0 rounded-2xl bg-emerald-500/20 blur-xl animate-pulse" /><SonicLogo size={48} glow={true} /></div><div className="flex items-center gap-2">{/* <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" /> */}<span className="text-[11px] font-semibold tracking-widest text-zinc-400 uppercase font-sans">Sonic</span></div></main>);}return (<div className="h-screen w-screen flex bg-zinc-950 text-zinc-100 overflow-hidden font-sans selection:bg-emerald-500 selection:text-black">{/* 60 FPS Ambient Cyber Background */}<CyberBackground isListening={isRecording} isProcessing={isProcessing} />20 unmodified linesonToggleSidebar={() => setIsSidebarOpen((prev) => !prev)}isAudioEnabled={isAudioEnabled}onToggleAudio={() => setIsAudioEnabled((prev) => !prev)}selectedLanguageLabel={selectedLangObj?.label || 'Hindi'}/>{/* Scrollable Main Conversational Canvas */}11 unmodified lineslanguageCode={selectedLanguage}isAudioPlaying={isAudioEnabled}onAudioToggle={() => setIsAudioEnabled((prev) => !prev)}/></div>44 unmodified lineslanguageCode={selectedLanguage}isAudioPlaying={isAudioEnabled}onAudioToggle={() => setIsAudioEnabled((prev) => !prev)}/></div></div>10 unmodified lines111213141516177 unmodified lines252627282930313218 unmodified lines51525354555657585980 unmodified lines14014114214314414514614714814915015115215315415520 unmodified lines17617717817918018118211 unmodified lines19419519619719819920020144 unmodified lines24624724824925025125225310 unmodified linesimport { CyberBackground } from '@/src/components/CyberBackground';import { CharacterState } from '@/src/components/SonicCharacter';import { SonicLogo } from '@/src/components/SonicLogo';import { SonicSplashIntro } from '@/src/components/SonicSplashIntro';import { sounds } from '@/src/lib/soundEffects';import { ttsEngine } from '@/src/lib/ttsEngine';import {7 unmodified lines} from 'lucide-react';const SUPPORTED_LANGUAGES = [{ code: 'en-IN', label: '🌐 English (Indian)' },{ code: 'hi-IN', label: '🇮🇳 Hindi (हिन्दी)' },{ code: 'ta-IN', label: '🇮🇳 Tamil (தமிழ்)' },{ code: 'te-IN', label: '🇮🇳 Telugu (తెలుగు)' },{ code: 'bn-IN', label: '🇮🇳 Bengali (বাংলা)' },18 unmodified lines}}, []);const [selectedLanguage, setSelectedLanguage] = useState('en-IN');const [mounted, setMounted] = useState(false);const [showIntro, setShowIntro] = useState(true);const [isSidebarOpen, setIsSidebarOpen] = useState(true);const [isAudioEnabled, setIsAudioEnabled] = useState(true);const [activeCitationModal, setActiveCitationModal] = useState<{80 unmodified linesconst selectedLangObj = SUPPORTED_LANGUAGES.find((l) => l.code === selectedLanguage);if (!mounted) {return <SonicSplashIntro onComplete={() => {}} />;}return (<div className="h-screen w-screen flex bg-zinc-950 text-zinc-100 overflow-hidden font-sans selection:bg-emerald-500 selection:text-black">{/* Dynamic Animated Startup Logo Intro */}{showIntro && (<SonicSplashIntro onComplete={() => setShowIntro(false)} />)}{/* 60 FPS Ambient Cyber Background */}<CyberBackground isListening={isRecording} isProcessing={isProcessing} />20 unmodified linesonToggleSidebar={() => setIsSidebarOpen((prev) => !prev)}isAudioEnabled={isAudioEnabled}onToggleAudio={() => setIsAudioEnabled((prev) => !prev)}selectedLanguageLabel={selectedLangObj?.label || '🌐 English (Indian)'}/>{/* Scrollable Main Conversational Canvas */}11 unmodified lineslanguageCode={selectedLanguage}isAudioPlaying={isAudioEnabled}onAudioToggle={() => setIsAudioEnabled((prev) => !prev)}onTriggerQuery={(q) => sendTextQuery(q)}onStartVoice={startRecording}/></div>44 unmodified lineslanguageCode={selectedLanguage}isAudioPlaying={isAudioEnabled}onAudioToggle={() => setIsAudioEnabled((prev) => !prev)}onTriggerQuery={(q) => sendTextQuery(q)}onStartVoice={startRecording}/></div></div>
75 unmodified lines767778798081828384858687129 unmodified lines217218219220221222223158 unmodified lines38238338438538638738828 unmodified lines4174184194204214224234245 unmodified lines4304314324334344354367 unmodified lines44444544644744844945045145245345445545675 unmodified linesclass QueryRequest(BaseModel):text: strlanguage_code: Optional[str] = "hi-IN"bypass_stt: bool = Trueclass TTSRequest(BaseModel):text: strlanguage_code: Optional[str] = "hi-IN"class QueryDetailItem(BaseModel):query: str129 unmodified linesreturn None@async_retry(max_attempts=2, delay=0.1)async def call_sarvam_stt_harness(audio_bytes: bytes, language_code: str = "hi-IN") -> str:"""Harnessed STT with retries and structured error handling."""if not SARVAM_API_KEY or SARVAM_API_KEY == "YOUR_SARVAM_KEY":return "what is the capital of india"158 unmodified linesreturn await execute_rag_pipeline(req.text, stt_ms=0.0)@app.post("/api/voice", response_model=StructuredRAGResponse)async def voice_endpoint(file: UploadFile = File(...), language_code: str = Form("hi-IN")):"""Direct voice audio upload endpoint with Sarvam STT & sub-200ms RAG."""audio_bytes = await file.read()if not audio_bytes:28 unmodified lines# Map Indic language codes to standard codeslang_map = {"hi-IN": "hi", "hi": "hi","en-IN": "en", "en-US": "en", "en": "en","ta-IN": "ta", "ta": "ta","te-IN": "te", "te": "te","bn-IN": "bn", "bn": "bn",5 unmodified lines"od-IN": "hi",}target_lang = lang_map.get(req.language_code, "hi")def _generate_audio(text: str, lang: str) -> bytes:tts = gTTS(text=text, lang=lang, slow=False)7 unmodified linesreturn Response(content=audio_content, media_type="audio/mpeg")except Exception as e:try:audio_content = await asyncio.to_thread(_generate_audio, req.text, "hi")return Response(content=audio_content, media_type="audio/mpeg")except Exception as e2:raise HTTPException(status_code=500, detail=f"TTS synthesis error: {str(e2)}")@app.websocket("/ws/rag")async def websocket_rag_endpoint(websocket: WebSocket, language_code: str = "hi-IN"):"""Real-time sub-200ms voice streaming WebSocket endpoint supporting 10+ Indic languages."""await websocket.accept()print(f"--> WebSocket Client Connected (Language: {language_code})")75 unmodified lines767778798081828384858687129 unmodified lines217218219220221222223158 unmodified lines38238338438538638738828 unmodified lines4174184194204214224234245 unmodified lines4304314324334344354367 unmodified lines44444544644744844945045145245345445545675 unmodified linesclass QueryRequest(BaseModel):text: strlanguage_code: Optional[str] = "en-IN"bypass_stt: bool = Trueclass TTSRequest(BaseModel):text: strlanguage_code: Optional[str] = "en-IN"class QueryDetailItem(BaseModel):query: str129 unmodified linesreturn None@async_retry(max_attempts=2, delay=0.1)async def call_sarvam_stt_harness(audio_bytes: bytes, language_code: str = "en-IN") -> str:"""Harnessed STT with retries and structured error handling."""if not SARVAM_API_KEY or SARVAM_API_KEY == "YOUR_SARVAM_KEY":return "what is the capital of india"158 unmodified linesreturn await execute_rag_pipeline(req.text, stt_ms=0.0)@app.post("/api/voice", response_model=StructuredRAGResponse)async def voice_endpoint(file: UploadFile = File(...), language_code: str = Form("en-IN")):"""Direct voice audio upload endpoint with Sarvam STT & sub-200ms RAG."""audio_bytes = await file.read()if not audio_bytes:28 unmodified lines# Map Indic language codes to standard codeslang_map = {"en-IN": "en", "en-US": "en", "en": "en","hi-IN": "hi", "hi": "hi","ta-IN": "ta", "ta": "ta","te-IN": "te", "te": "te","bn-IN": "bn", "bn": "bn",5 unmodified lines"od-IN": "hi",}target_lang = lang_map.get(req.language_code, "en")def _generate_audio(text: str, lang: str) -> bytes:tts = gTTS(text=text, lang=lang, slow=False)7 unmodified linesreturn Response(content=audio_content, media_type="audio/mpeg")except Exception as e:try:audio_content = await asyncio.to_thread(_generate_audio, req.text, "en")return Response(content=audio_content, media_type="audio/mpeg")except Exception as e2:raise HTTPException(status_code=500, detail=f"TTS synthesis error: {str(e2)}")@app.websocket("/ws/rag")async def websocket_rag_endpoint(websocket: WebSocket, language_code: str = "en-IN"):"""Real-time sub-200ms voice streaming WebSocket endpoint supporting 10+ Indic languages."""await websocket.accept()print(f"--> WebSocket Client Connected (Language: {language_code})")
1234567891011121314151617181920213 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061625 unmodified lines68697071727374757677787980811 unmodified line838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818922 unmodified lines21221321421521621712 unmodified lines2302312322332342352362372382392402412422432442452462472487 unmodified lines2562572582592602612628 unmodified lines2712722732742752764 unmodified lines2812822832842852862878 unmodified lines2962972982993003011 unmodified line3033043053063073081 unmodified line3103113123133143153163173183193203 unmodified lines32432532632732832933033133233333413 unmodified lines3483493503513523533549 unmodified lines36436536636736836937037137237337437537637737837938038136 unmodified lines41841942042142242342442525 unmodified lines4514524534544554565 unmodified lines4624634644654664674684694704714727 unmodified lines480481482483484485'use client';import React, { useState, useEffect, useRef } from 'react';import { CharacterState } from './SonicCharacter';import { sounds } from '@/src/lib/soundEffects';import {Volume2,VolumeX,Sparkles,ShieldAlert,Mic,Zap,Bot,Heart,Music} from 'lucide-react';import { ttsEngine } from '@/src/lib/ttsEngine';interface GameCharacterAvatarProps {state: CharacterState;3 unmodified linesisAudioPlaying?: boolean;onAudioToggle?: () => void;onCharacterPoke?: () => void;}export function GameCharacterAvatar({state,transcript,responseAnswer,languageCode = 'hi-IN',isAudioPlaying = true,onAudioToggle,onCharacterPoke,}: GameCharacterAvatarProps) {// Cursor tracking for interactive gazeconst [eyeOffset, setEyeOffset] = useState({ x: 0, y: 0 });const [headTilt, setHeadTilt] = useState(0);const [isPetted, setIsPetted] = useState(false);const [hearts, setHearts] = useState<Array<{ id: number; x: number; y: number }>>([]);const [micVolumeLevel, setMicVolumeLevel] = useState(0);const containerRef = useRef<HTMLDivElement | null>(null);// SFX triggers on state transitionsuseEffect(() => {if (state === 'listening') {sounds.playListenStart();} else if (state === 'speaking') {sounds.playSuccess();} else if (state === 'refusal') {sounds.playRefusal();}}, [state]);// Mouse cursor tracking: eyes follow the pointer around the screenuseEffect(() => {const handleMouseMove = (e: MouseEvent) => {if (!containerRef.current) return;5 unmodified linesconst dy = e.clientY - charCenterY;const distance = Math.sqrt(dx * dx + dy * dy);const maxOffset = 7; // Max eye shift in pxif (distance > 0) {const factor = Math.min(1, distance / 400);const offsetX = (dx / distance) * maxOffset * factor;const offsetY = (dy / distance) * maxOffset * factor;setEyeOffset({ x: offsetX, y: offsetY });setHeadTilt((dx / window.innerWidth) * 12);}};1 unmodified linereturn () => window.removeEventListener('mousemove', handleMouseMove);}, []);// Handle petting / clicking Sonicconst handlePetCharacter = (e: React.MouseEvent) => {sounds.playPoke();setIsPetted(true);if (onCharacterPoke) onCharacterPoke();const rect = containerRef.current?.getBoundingClientRect();if (rect) {const clickX = e.clientX - rect.left;const clickY = e.clientY - rect.top;const newHeart = { id: Date.now(), x: clickX, y: clickY };setHearts((prev) => [...prev, newHeart]);setTimeout(() => {setHearts((prev) => prev.filter((h) => h.id !== newHeart.id));}, 1000);}setTimeout(() => setIsPetted(false), 900);};return (<divref={containerRef}className="relative flex flex-col items-center justify-center select-none py-2">{/* Floating Hearts when petted */}{hearts.map((h) => (<divkey={h.id}className="absolute z-50 pointer-events-none text-rose-400 animate-in fade-in zoom-in slide-out-to-top-8 duration-700"style={{ left: `${h.x}px`, top: `${h.y}px` }}><Heart className="w-6 h-6 fill-rose-500 text-rose-400 drop-shadow-lg animate-bounce" /></div>))}{/* Dynamic Status Pill with Sound Controls */}<div className="flex items-center gap-2 mb-3 z-20"><divclassName={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-mono font-bold tracking-wider border shadow-xl backdrop-blur-md transition-all duration-300 ${state === 'listening'? 'bg-emerald-500/15 border-emerald-500/40 text-emerald-300 shadow-emerald-500/20': state === 'thinking'? 'bg-cyan-500/15 border-cyan-500/40 text-cyan-300 shadow-cyan-500/20': state === 'speaking'? 'bg-amber-500/15 border-amber-500/40 text-amber-300 shadow-amber-500/20': state === 'refusal'? 'bg-rose-500/15 border-rose-500/40 text-rose-300 shadow-rose-500/20': 'bg-zinc-900/90 border-zinc-800 text-zinc-300'}`}>{state === 'listening' ? (<><Mic className="w-3.5 h-3.5 animate-bounce text-emerald-400" /><span>LISTENING (AUDIO DETECTED)</span></>) : state === 'thinking' ? (<><Sparkles className="w-3.5 h-3.5 animate-spin text-cyan-400" /><span>SEARCHING MSMARCO-XI INDEX</span></>) : state === 'speaking' ? (<><Zap className="w-3.5 h-3.5 text-amber-400 animate-pulse" /><span>SYNTHESIZING ANSWER</span></>) : state === 'refusal' ? (<><ShieldAlert className="w-3.5 h-3.5 text-rose-400" /><span>GUARDRAIL RESTRICTION</span></>) : (<><Bot className="w-3.5 h-3.5 text-emerald-400" /><span>SONIC AI (IDLE & READY)</span></>)}</div>{onAudioToggle && (<buttontype="button"onClick={onAudioToggle}className={`p-1.5 rounded-full border text-xs transition-all shadow-md ${isAudioPlaying? 'bg-emerald-500/20 text-emerald-400 border-emerald-500/40': 'bg-zinc-900 text-zinc-500 border-zinc-800 hover:text-zinc-300'}`}title={isAudioPlaying ? 'Mute SFX & Voice' : 'Unmute SFX & Voice'}>{isAudioPlaying ? <Volume2 className="w-3.5 h-3.5" /> : <VolumeX className="w-3.5 h-3.5" />}</button>)}</div>{/* Main Character Stage */}<divonClick={handlePetCharacter}title="Click to interact with Sonic!"className={`relative w-52 h-52 md:w-60 md:h-60 flex items-center justify-center cursor-pointer transition-transform duration-300 ${isPetted ? 'scale-110' : 'hover:scale-105 active:scale-95'}`}>{/* Holographic Radar Waves during Listening */}22 unmodified lines</div>)}{/* Hexagonal Shield Barrier during Refusal */}{state === 'refusal' && (<div className="absolute -inset-2 rounded-3xl border-2 border-rose-500/70 bg-rose-500/10 backdrop-blur-xs animate-pulse pointer-events-none shadow-2xl shadow-rose-500/30 flex items-center justify-center">12 unmodified lines? 'bg-amber-500/30 scale-105': state === 'refusal'? 'bg-rose-500/40 scale-110': 'bg-emerald-500/20'}`}/>{/* Animated Robot SVG Body */}<divclassName={`w-full h-full relative transition-transform duration-300 ${state === 'listening'? 'animate-ear-wiggle': state === 'speaking'? 'animate-float-slow': isPetted? 'animate-bounce': 'animate-float'}`}style={{ transform: `rotate(${headTilt}deg)` }}7 unmodified lines{/* Left Robotic Ear / Antenna */}<gclassName={`transition-transform duration-300 origin-center ${state === 'listening' ? 'rotate-[-12deg]' : isPetted ? 'rotate-[-15deg]' : ''}`}><rect x="22" y="78" width="16" height="32" rx="8" fill="#18181b" stroke="#3f3f46" strokeWidth="2" />8 unmodified lines? '#06b6d4': state === 'refusal'? '#f43f5e': '#10b981'}className="animate-pulse"4 unmodified lines{/* Right Robotic Ear / Antenna */}<gclassName={`transition-transform duration-300 origin-center ${state === 'listening' ? 'rotate-[12deg]' : isPetted ? 'rotate-[15deg]' : ''}`}><rect x="162" y="78" width="16" height="32" rx="8" fill="#18181b" stroke="#3f3f46" strokeWidth="2" />8 unmodified lines? '#06b6d4': state === 'refusal'? '#f43f5e': '#10b981'}className="animate-pulse"1 unmodified line<line x1="170" y1="70" x2="170" y2="78" stroke="#71717a" strokeWidth="2.5" /></g>{/* Floating Torso */}<pathd="M70 144 C70 136 130 136 130 144 L138 174 C138 184 62 184 62 174 Z"1 unmodified linestroke="#27272a"strokeWidth="2.5"/>{/* Chest Arc Reactor */}<circlecx="100"cy="158"r="8"fill={state === 'listening'? '#10b981'3 unmodified lines? '#f59e0b': state === 'refusal'? '#f43f5e': '#10b981'}className="animate-pulse"/><circle cx="100" cy="158" r="12" stroke="#3f3f46" strokeWidth="1.5" strokeDasharray="3 3" />{/* Main Robot Helmet */}<rect13 unmodified linescx="100"cy="33"r="4"fill={state === 'thinking' ? '#06b6d4' : '#10b981'}className="animate-pulse"/>9 unmodified linesstrokeWidth="2"/>{/* Scanline Sweep in Visor */}{state === 'thinking' && (<linex1="46"y1="58"x2="154"y2="58"stroke="#06b6d4"strokeWidth="2.5"opacity="0.9"className="animate-scanline"/>)}{/* Visor Glare Curve */}36 unmodified lines<circle cx="74" cy="85" r="4.5" fill="#ffffff" /><circle cx="126" cy="85" r="4.5" fill="#ffffff" /></>) : state === 'speaking' || isPetted ? (/* Joyful / Happy Cheerful Eyes */<><path d="M62 88 C67 78 81 78 86 88" stroke="#10b981" strokeWidth="4.5" strokeLinecap="round" /><path d="M114 88 C119 78 133 78 138 88" stroke="#10b981" strokeWidth="4.5" strokeLinecap="round" />25 unmodified lines<circle cx="100" cy="111" r="4.5" fill="#10b981" />) : state === 'refusal' ? (<line x1="88" y1="111" x2="112" y2="111" stroke="#f43f5e" strokeWidth="3.5" strokeLinecap="round" />) : (<pathd="M86 108 C92 116 108 116 114 108"5 unmodified lines</g>{/* Cheeks Blush Aura */}<circle cx="58" cy="103" r="6" fill="#10b981" fillOpacity={state === 'listening' || state === 'speaking' || isPetted ? '0.4' : '0.15'} /><circle cx="142" cy="103" r="6" fill="#10b981" fillOpacity={state === 'listening' || state === 'speaking' || isPetted ? '0.4' : '0.15'} />{/* Gradients */}<defs><linearGradient id="helmetGradient" x1="100" y1="40" x2="100" y2="142" gradientUnits="userSpaceOnUse"><stop stopColor="#27272a" /><stop offset="1" stopColor="#18181b" />7 unmodified lines</div></div>{/* Real-time Frequency Visualizer Sound Waves */}{(state === 'listening' || state === 'speaking') && (<div className="flex items-center gap-1 mt-2 h-7">12345678910111213141516171819202122232425262728293031323334353637383 unmodified lines424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141155 unmodified lines1211221231241251261271281291301311321331341 unmodified line13613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330422 unmodified lines32732832933033133233333433533633733833934012 unmodified lines3533543553563573583593603613623633643653663673683693703713723733743753763773783793803817 unmodified lines3893903913923933943953963973983998 unmodified lines4084094104114124134144154164174 unmodified lines4224234244254264274284294304314328 unmodified lines4414424434444454464474484494501 unmodified line4524534544554564574584594604614624634644654664674684691 unmodified line4714724734744754764774784794804814823 unmodified lines48648748848949049149249349449549649749849950050150250350450550650750850913 unmodified lines5235245255265275285295305315325335345359 unmodified lines54554654754854955055155255355455555655755855956056156256356436 unmodified lines60160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165225 unmodified lines6786796806816826836846856866876886896906916926936946956966976986995 unmodified lines7057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387 unmodified lines746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808'use client';import React, { useState, useEffect, useRef, useCallback } from 'react';import { CharacterState } from './SonicCharacter';import { sounds } from '@/src/lib/soundEffects';import {Sparkles,ShieldAlert,Mic,Heart,Music,Zap,Dices,PartyPopper,RefreshCw} from 'lucide-react';type ActionMode =| 'idle'| 'spin'| 'dance'| 'hyper'| 'wink'| 'curious'| 'love'| 'matrix'| 'tickle';interface FloatingParticle {id: number;x: number;y: number;type: 'heart' | 'star' | 'music' | 'bolt' | 'spark' | 'ring';color: string;}interface GameCharacterAvatarProps {state: CharacterState;3 unmodified linesisAudioPlaying?: boolean;onAudioToggle?: () => void;onCharacterPoke?: () => void;onTriggerQuery?: (query: string) => void;onStartVoice?: () => void;}const SAMPLE_INTERACTIVE_QUERIES: Record<string, string[]> = {'hi-IN': ['भारत की राजधानी क्या है?','निगम क्या है और यह कैसे काम करता है?','पौधों में प्रकाश संश्लेषण कैसे होता है?','उच्च रक्तचाप के मुख्य लक्षण क्या हैं?'],'en-IN': ['what is a corporation?','what is the capital of india','how does photosynthesis work in plants','symptoms of malaria and dengue fever'],'gu-IN': ['ભારતની રાજધાની કઈ છે?','સૂર્યપ્રકાશમાંથી વીજળી કેવી રીતે બને છે?'],'mr-IN': ['भारताची राजधानी कोणती आहे?','रक्तदाब वाढण्याची कारणे काय आहेत?'],'ta-IN': ['இந்தியாவின் தலைநகரம் எது?']};export function GameCharacterAvatar({state,transcript,responseAnswer,languageCode = 'en-IN',isAudioPlaying = true,onAudioToggle,onCharacterPoke,onTriggerQuery,onStartVoice,}: GameCharacterAvatarProps) {// Eye tracking & 3D tiltconst [eyeOffset, setEyeOffset] = useState({ x: 0, y: 0 });const [headTilt, setHeadTilt] = useState(0);const [isHovered, setIsHovered] = useState(false);// Dynamic Action Modeconst [actionMode, setActionMode] = useState<ActionMode>('idle');const [particles, setParticles] = useState<FloatingParticle[]>([]);const containerRef = useRef<HTMLDivElement | null>(null);const actionTimerRef = useRef<NodeJS.Timeout | null>(null);// SFX triggers on state transitionsuseEffect(() => {if (state === 'listening') {sounds.playListenStart();setActionMode('idle');} else if (state === 'speaking') {sounds.playSuccess();setActionMode('idle');} else if (state === 'refusal') {sounds.playRefusal();setActionMode('idle');}}, [state]);// Smooth mouse cursor tracking: robot eyes and head follow the pointeruseEffect(() => {const handleMouseMove = (e: MouseEvent) => {if (!containerRef.current) return;5 unmodified linesconst dy = e.clientY - charCenterY;const distance = Math.sqrt(dx * dx + dy * dy);const maxOffset = 8;if (distance > 0) {const factor = Math.min(1, distance / 350);const offsetX = (dx / distance) * maxOffset * factor;const offsetY = (dy / distance) * maxOffset * factor;setEyeOffset({ x: offsetX, y: offsetY });setHeadTilt((dx / (window.innerWidth || 1000)) * 14);}};1 unmodified linereturn () => window.removeEventListener('mousemove', handleMouseMove);}, []);// Spawn visual particles at positionconst spawnParticles = useCallback((clickX: number,clickY: number,type: FloatingParticle['type'] = 'spark',count = 5,color = '#10b981') => {const newItems: FloatingParticle[] = [];for (let i = 0; i < count; i++) {const angle = (Math.PI * 2 * i) / count + (Math.random() * 0.4 - 0.2);const dist = 30 + Math.random() * 40;newItems.push({id: Date.now() + Math.random() * 10000 + i,x: clickX + Math.cos(angle) * dist,y: clickY + Math.sin(angle) * dist,type,color,});}setParticles((prev) => [...prev, ...newItems]);setTimeout(() => {setParticles((prev) =>prev.filter((p) => !newItems.some((item) => item.id === p.id)));}, 1000);},[]);// Trigger an interactive action sequenceconst triggerAction = useCallback((mode: ActionMode) => {if (actionTimerRef.current) clearTimeout(actionTimerRef.current);setActionMode(mode);// Sound and particle mappingconst rect = containerRef.current?.getBoundingClientRect();const centerX = (rect?.width || 240) / 2;const centerY = (rect?.height || 240) / 2;switch (mode) {case 'spin':sounds.playSpin();spawnParticles(centerX, centerY, 'ring', 6, '#06b6d4');break;case 'dance':sounds.playDanceBeat();spawnParticles(centerX, centerY, 'music', 6, '#f59e0b');break;case 'hyper':sounds.playPowerUp();spawnParticles(centerX, centerY, 'bolt', 7, '#10b981');break;case 'wink':sounds.playChirp();spawnParticles(centerX, centerY, 'star', 6, '#fbbf24');break;case 'love':sounds.playGiggle();spawnParticles(centerX, centerY, 'heart', 6, '#f43f5e');break;case 'matrix':sounds.playTypeTick();spawnParticles(centerX, centerY, 'spark', 8, '#10b981');break;case 'tickle':sounds.playGiggle();spawnParticles(centerX, centerY, 'heart', 4, '#34d399');break;default:sounds.playPoke();spawnParticles(centerX, centerY, 'spark', 4, '#10b981');break;}// Auto-reset actionconst duration = mode === 'spin' ? 800 : mode === 'dance' ? 2200 : mode === 'hyper' ? 1800 : 1200;actionTimerRef.current = setTimeout(() => {setActionMode('idle');}, duration);},[spawnParticles]);// Main click handler on Sonicconst handleCharacterClick = (e: React.MouseEvent) => {e.stopPropagation();if (onCharacterPoke) onCharacterPoke();const rect = containerRef.current?.getBoundingClientRect();const clickX = rect ? e.clientX - rect.left : 100;const clickY = rect ? e.clientY - rect.top : 100;const modes: ActionMode[] = ['spin', 'dance', 'love', 'wink', 'hyper', 'matrix', 'tickle'];const nextMode = modes[Math.floor(Math.random() * modes.length)];triggerAction(nextMode);spawnParticles(clickX, clickY, nextMode === 'love' ? 'heart' : 'star', 5);};// Quick action: Trigger a random sample queryconst handleRandomQuery = (e: React.MouseEvent) => {e.stopPropagation();const list = SAMPLE_INTERACTIVE_QUERIES[languageCode] || SAMPLE_INTERACTIVE_QUERIES['en-IN'];const randomQ = list[Math.floor(Math.random() * list.length)];triggerAction('spin');if (onTriggerQuery) {setTimeout(() => onTriggerQuery(randomQ), 400);}};return (<divref={containerRef}className="relative flex flex-col items-center justify-center select-none py-2"onMouseEnter={() => setIsHovered(true)}onMouseLeave={() => setIsHovered(false)}>{/* Floating Particles Overlay */}{particles.map((p) => (<divkey={p.id}className="absolute z-50 pointer-events-none animate-in fade-in zoom-in slide-out-to-top-12 duration-700"style={{ left: `${p.x}px`, top: `${p.y}px` }}>{p.type === 'heart' && (<Heart className="w-5 h-5 fill-rose-500 text-rose-400 drop-shadow-md animate-bounce" />)}{p.type === 'star' && (<Sparkles className="w-5 h-5 text-amber-300 drop-shadow-md animate-spin duration-700" />)}{p.type === 'music' && (<Music className="w-5 h-5 text-cyan-400 drop-shadow-md animate-bounce" />)}{p.type === 'bolt' && (<Zap className="w-5 h-5 fill-amber-400 text-amber-300 drop-shadow-md animate-pulse" />)}{p.type === 'ring' && (<div className="w-6 h-6 rounded-full border-2 border-cyan-400 animate-ping" />)}{p.type === 'spark' && (<div className="w-3 h-3 rounded-full bg-emerald-400 shadow-lg shadow-emerald-400/80 animate-ping" />)}</div>))}{/* Main Character Stage */}<divonClick={handleCharacterClick}title="Tap Sonic to trigger dances, spins, reactions & sounds!"className={`relative w-52 h-52 md:w-60 md:h-60 flex items-center justify-center cursor-pointer transition-all duration-300 ${actionMode === 'spin'? 'animate-turbo-spin': actionMode === 'dance'? 'animate-cyber-dance': actionMode === 'hyper'? 'animate-hyper-charge scale-110': isHovered? 'scale-105': 'hover:scale-105 active:scale-95'}`}>{/* Holographic Radar Waves during Listening */}22 unmodified lines</div>)}{/* Turbo Spin Shockwave Burst */}{actionMode === 'spin' && (<div className="absolute inset-0 flex items-center justify-center pointer-events-none"><div className="w-56 h-56 rounded-full border-2 border-cyan-400 animate-ping opacity-60" /><div className="w-64 h-64 rounded-full border border-emerald-400 animate-ping opacity-40" /></div>)}{/* Hexagonal Shield Barrier during Refusal */}{state === 'refusal' && (<div className="absolute -inset-2 rounded-3xl border-2 border-rose-500/70 bg-rose-500/10 backdrop-blur-xs animate-pulse pointer-events-none shadow-2xl shadow-rose-500/30 flex items-center justify-center">12 unmodified lines? 'bg-amber-500/30 scale-105': state === 'refusal'? 'bg-rose-500/40 scale-110': actionMode === 'hyper'? 'bg-amber-500/50 scale-125': actionMode === 'dance'? 'bg-purple-500/40 scale-115': actionMode === 'spin'? 'bg-cyan-500/45 scale-120': actionMode === 'love'? 'bg-rose-500/40 scale-110': 'bg-emerald-500/20'}`}/>{/* Animated Robot SVG Body with 3D Tilt */}<divclassName={`w-full h-full relative transition-transform duration-300 ${state === 'listening'? 'animate-ear-wiggle': state === 'speaking'? 'animate-float-slow': actionMode === 'dance'? 'animate-cyber-dance': actionMode === 'hyper'? 'animate-hyper-charge': 'animate-float'}`}style={{ transform: `rotate(${headTilt}deg)` }}7 unmodified lines{/* Left Robotic Ear / Antenna */}<gclassName={`transition-transform duration-300 origin-center ${state === 'listening' || actionMode === 'dance'? 'rotate-[-14deg]': actionMode === 'spin'? 'rotate-[-20deg]': ''}`}><rect x="22" y="78" width="16" height="32" rx="8" fill="#18181b" stroke="#3f3f46" strokeWidth="2" />8 unmodified lines? '#06b6d4': state === 'refusal'? '#f43f5e': actionMode === 'hyper'? '#fbbf24': actionMode === 'dance'? '#c084fc': '#10b981'}className="animate-pulse"4 unmodified lines{/* Right Robotic Ear / Antenna */}<gclassName={`transition-transform duration-300 origin-center ${state === 'listening' || actionMode === 'dance'? 'rotate-[14deg]': actionMode === 'spin'? 'rotate-[20deg]': ''}`}><rect x="162" y="78" width="16" height="32" rx="8" fill="#18181b" stroke="#3f3f46" strokeWidth="2" />8 unmodified lines? '#06b6d4': state === 'refusal'? '#f43f5e': actionMode === 'hyper'? '#fbbf24': actionMode === 'dance'? '#c084fc': '#10b981'}className="animate-pulse"1 unmodified line<line x1="170" y1="70" x2="170" y2="78" stroke="#71717a" strokeWidth="2.5" /></g>{/* DJ Headphones Ring during Dance Mode */}{actionMode === 'dance' && (<pathd="M28 80 C28 20 172 20 172 80"stroke="#c084fc"strokeWidth="4"strokeLinecap="round"fill="none"className="animate-pulse"/>)}{/* Floating Torso */}<pathd="M70 144 C70 136 130 136 130 144 L138 174 C138 184 62 184 62 174 Z"1 unmodified linestroke="#27272a"strokeWidth="2.5"/>{/* Chest Arc Reactor */}<circlecx="100"cy="158"r={actionMode === 'hyper' ? '10' : '8'}fill={state === 'listening'? '#10b981'3 unmodified lines? '#f59e0b': state === 'refusal'? '#f43f5e': actionMode === 'hyper'? '#fbbf24': actionMode === 'dance'? '#c084fc': actionMode === 'love'? '#f43f5e': '#10b981'}className="animate-pulse"/><circlecx="100"cy="158"r="12"stroke={actionMode === 'hyper' ? '#fbbf24' : '#3f3f46'}strokeWidth="1.5"strokeDasharray="3 3"/>{/* Main Robot Helmet */}<rect13 unmodified linescx="100"cy="33"r="4"fill={state === 'thinking'? '#06b6d4': actionMode === 'hyper'? '#fbbf24': '#10b981'}className="animate-pulse"/>9 unmodified linesstrokeWidth="2"/>{/* Scanline Sweep in Visor - Strictly clipped inside robot visor */}{(state === 'thinking' || actionMode === 'curious') && (<g clipPath="url(#visorClip)"><linex1="46"y1="58"x2="154"y2="58"stroke="#06b6d4"strokeWidth="2.5"opacity="0.9"className="animate-scanline"/></g>)}{/* Visor Glare Curve */}36 unmodified lines<circle cx="74" cy="85" r="4.5" fill="#ffffff" /><circle cx="126" cy="85" r="4.5" fill="#ffffff" /></>) : actionMode === 'love' ? (/* Heart Eyes LED */<><pathd="M74 80 C70 74 62 76 62 82 C62 88 74 94 74 94 C74 94 86 88 86 82 C86 76 78 74 74 80 Z"fill="#f43f5e"className="animate-pulse"/><pathd="M126 80 C122 74 114 76 114 82 C114 88 126 94 126 94 C126 94 138 88 138 82 C138 76 130 74 126 80 Z"fill="#f43f5e"className="animate-pulse"/></>) : actionMode === 'hyper' ? (/* Lightning Bolt Eyes */<><path d="M78 74 L68 86 L74 86 L70 96 L80 84 L74 84 Z" fill="#fbbf24" className="animate-pulse" /><path d="M130 74 L120 86 L126 86 L122 96 L132 84 L126 84 Z" fill="#fbbf24" className="animate-pulse" /></>) : actionMode === 'wink' ? (/* Winking Eye */<><path d="M62 88 C67 80 81 80 86 88" stroke="#fbbf24" strokeWidth="4.5" strokeLinecap="round" /><ellipse cx="126" cy="85" rx="12" ry="14" fill="#fbbf24" /><circle cx="129" cy="81" r="4" fill="#ffffff" /></>) : actionMode === 'dance' ? (/* Equalizer DJ Eyes */<><rect x="64" y="78" width="5" height="16" rx="2" fill="#c084fc" className="animate-pulse" /><rect x="72" y="72" width="5" height="22" rx="2" fill="#c084fc" className="animate-pulse" /><rect x="80" y="80" width="5" height="14" rx="2" fill="#c084fc" className="animate-pulse" /><rect x="116" y="80" width="5" height="14" rx="2" fill="#c084fc" className="animate-pulse" /><rect x="124" y="72" width="5" height="22" rx="2" fill="#c084fc" className="animate-pulse" /><rect x="132" y="78" width="5" height="16" rx="2" fill="#c084fc" className="animate-pulse" /></>) : actionMode === 'spin' ? (/* Fast Streamlines >> >> */<><path d="M66 80 L76 86 L66 92 M78 80 L88 86 L78 92" stroke="#06b6d4" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" /><path d="M118 80 L128 86 L118 92 M130 80 L140 86 L130 92" stroke="#06b6d4" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" /></>) : state === 'speaking' ? (/* Joyful Cheerful Eyes */<><path d="M62 88 C67 78 81 78 86 88" stroke="#10b981" strokeWidth="4.5" strokeLinecap="round" /><path d="M114 88 C119 78 133 78 138 88" stroke="#10b981" strokeWidth="4.5" strokeLinecap="round" />25 unmodified lines<circle cx="100" cy="111" r="4.5" fill="#10b981" />) : state === 'refusal' ? (<line x1="88" y1="111" x2="112" y2="111" stroke="#f43f5e" strokeWidth="3.5" strokeLinecap="round" />) : actionMode === 'love' || actionMode === 'tickle' ? (<pathd="M84 107 C90 119 110 119 116 107"stroke="#f43f5e"strokeWidth="3.5"strokeLinecap="round"fill="#f43f5e"fillOpacity="0.2"/>) : actionMode === 'hyper' ? (<pathd="M86 108 C92 118 108 118 114 108 Z"fill="#fbbf24"stroke="#fbbf24"strokeWidth="2"/>) : (<pathd="M86 108 C92 116 108 116 114 108"5 unmodified lines</g>{/* Cheeks Blush Aura */}<circlecx="58"cy="103"r="6"fill={actionMode === 'love' ? '#f43f5e' : '#10b981'}fillOpacity={state === 'listening' || state === 'speaking' || actionMode !== 'idle' || isHovered? '0.5': '0.15'}/><circlecx="142"cy="103"r="6"fill={actionMode === 'love' ? '#f43f5e' : '#10b981'}fillOpacity={state === 'listening' || state === 'speaking' || actionMode !== 'idle' || isHovered? '0.5': '0.15'}/>{/* Gradients & Clip Paths */}<defs><clipPath id="visorClip"><rect x="46" y="54" width="108" height="74" rx="22" /></clipPath><linearGradient id="helmetGradient" x1="100" y1="40" x2="100" y2="142" gradientUnits="userSpaceOnUse"><stop stopColor="#27272a" /><stop offset="1" stopColor="#18181b" />7 unmodified lines</div></div>{/* Interactive Quick-Action Toolbar below Sonic */}{state === 'idle' && (<div className="flex items-center gap-1.5 mt-2 transition-all duration-300 z-20"><buttontype="button"onClick={handleRandomQuery}className="px-2.5 py-1 rounded-xl bg-zinc-900/90 hover:bg-emerald-500/20 border border-zinc-800 hover:border-emerald-500/40 text-zinc-400 hover:text-emerald-300 text-[11px] font-mono flex items-center gap-1.5 transition-all shadow-sm"title="Ask Sonic a random question from the dataset"><Dices className="w-3.5 h-3.5 text-emerald-400" /><span>Surprise Query</span></button><buttontype="button"onClick={(e) => {e.stopPropagation();triggerAction('dance');}}className="px-2.5 py-1 rounded-xl bg-zinc-900/90 hover:bg-purple-500/20 border border-zinc-800 hover:border-purple-500/40 text-zinc-400 hover:text-purple-300 text-[11px] font-mono flex items-center gap-1.5 transition-all shadow-sm"title="Make Sonic dance!"><PartyPopper className="w-3.5 h-3.5 text-purple-400" /><span>Dance</span></button><buttontype="button"onClick={(e) => {e.stopPropagation();triggerAction('spin');}}className="px-2.5 py-1 rounded-xl bg-zinc-900/90 hover:bg-cyan-500/20 border border-zinc-800 hover:border-cyan-500/40 text-zinc-400 hover:text-cyan-300 text-[11px] font-mono flex items-center gap-1.5 transition-all shadow-sm"title="Sonic 360 Spin Dash!"><RefreshCw className="w-3.5 h-3.5 text-cyan-400" /><span>Spin</span></button>{onStartVoice && (<buttontype="button"onClick={(e) => {e.stopPropagation();sounds.playListenStart();onStartVoice();}}className="px-2.5 py-1 rounded-xl bg-emerald-500/15 hover:bg-emerald-500/30 border border-emerald-500/40 text-emerald-300 text-[11px] font-mono font-semibold flex items-center gap-1.5 transition-all shadow-sm"title="Start speaking"><Mic className="w-3.5 h-3.5 text-emerald-400 animate-pulse" /><span>Voice</span></button>)}</div>)}{/* Real-time Frequency Visualizer Sound Waves */}{(state === 'listening' || state === 'speaking') && (<div className="flex items-center gap-1 mt-2 h-7">
36 unmodified lines3738394041424336 unmodified linesexport function MessageItem({response,languageCode = 'hi-IN',onOpenSourceModal,isLatest,isAudioPlaying,36 unmodified lines3738394041424336 unmodified linesexport function MessageItem({response,languageCode = 'en-IN',onOpenSourceModal,isLatest,isAudioPlaying,
309 unmodified lines31031131231331431531631731831932032132232332432532632782 unmodified lines410411412413414415416417309 unmodified linesstrokeWidth="2"/>{/* Visor Scanline Sweep Effect */}{state === 'thinking' && (<linex1="46"y1="60"x2="154"y2="60"stroke="#06b6d4"strokeWidth="2"opacity="0.8"className="animate-scanline"/>)}{/* Visor Gloss Reflection */}82 unmodified lines<circle cx="60" cy="104" r="5" fill="#10b981" fillOpacity={state === 'listening' || state === 'speaking' ? '0.35' : '0.15'} /><circle cx="140" cy="104" r="5" fill="#10b981" fillOpacity={state === 'listening' || state === 'speaking' ? '0.35' : '0.15'} />{/* Gradients */}<defs><linearGradient id="helmetGradient" x1="100" y1="42" x2="100" y2="142" gradientUnits="userSpaceOnUse"><stop stopColor="#27272a" /><stop offset="1" stopColor="#18181b" />309 unmodified lines31031131231331431531631731831932032132232332432532632732832982 unmodified lines412413414415416417418419420421422309 unmodified linesstrokeWidth="2"/>{/* Visor Scanline Sweep Effect - Strictly clipped inside robot visor */}{state === 'thinking' && (<g clipPath="url(#sonicVisorClip)"><linex1="46"y1="60"x2="154"y2="60"stroke="#06b6d4"strokeWidth="2"opacity="0.8"className="animate-scanline"/></g>)}{/* Visor Gloss Reflection */}82 unmodified lines<circle cx="60" cy="104" r="5" fill="#10b981" fillOpacity={state === 'listening' || state === 'speaking' ? '0.35' : '0.15'} /><circle cx="140" cy="104" r="5" fill="#10b981" fillOpacity={state === 'listening' || state === 'speaking' ? '0.35' : '0.15'} />{/* Gradients & Clip Paths */}<defs><clipPath id="sonicVisorClip"><rect x="46" y="56" width="108" height="72" rx="20" /></clipPath><linearGradient id="helmetGradient" x1="100" y1="42" x2="100" y2="142" gradientUnits="userSpaceOnUse"><stop stopColor="#27272a" /><stop offset="1" stopColor="#18181b" />
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455'use client';
import React, { useState, useEffect } from 'react';import { SonicLogo } from './SonicLogo';import { sounds } from '@/src/lib/soundEffects';
interface SonicSplashIntroProps { onComplete: () => void;}
export function SonicSplashIntro({ onComplete }: SonicSplashIntroProps) { const [isFadingOut, setIsFadingOut] = useState(false);
useEffect(() => { // Play boot sound chime on load sounds.playBootSound();
// After full animation cycle plays (S draws in, then speed lines oscillate), fade out smoothly const timerFade = setTimeout(() => { setIsFadingOut(true); }, 3200);
// Complete handoff to active AI const timerDone = setTimeout(() => { onComplete(); }, 3750);
return () => { clearTimeout(timerFade); clearTimeout(timerDone); }; }, [onComplete]);
return ( <div className={`fixed inset-0 z-[9999] flex flex-col items-center justify-center bg-zinc-950 px-4 transition-all duration-700 select-none ${ isFadingOut ? 'opacity-0 scale-105 pointer-events-none' : 'opacity-100 scale-100' }`} > {/* Ambient subtle glow */} <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(16,185,129,0.12),transparent_65%)] pointer-events-none" />
{/* Centered Minimalist Logo & Brand */} <div className="relative flex flex-col items-center z-10 space-y-5 animate-in fade-in zoom-in-95 duration-500"> <SonicLogo size={90} glow={true} animated={true} />
<h1 className="text-3xl md:text-4xl font-black font-mono tracking-[0.3em] uppercase bg-clip-text text-transparent bg-gradient-to-r from-emerald-400 via-teal-300 to-cyan-400"> SONIC </h1> </div> </div> );}32 unmodified lines3334353637383932 unmodified linesexport function useVoiceRAG(backendWsUrl?: string,httpBackendUrl: string = '',languageCode: string = 'hi-IN') {const [isRecording, setIsRecording] = useState(false);const [isProcessing, setIsProcessing] = useState(false);32 unmodified lines3334353637383932 unmodified linesexport function useVoiceRAG(backendWsUrl?: string,httpBackendUrl: string = '',languageCode: string = 'en-IN') {const [isRecording, setIsRecording] = useState(false);const [isProcessing, setIsProcessing] = useState(false);
162 unmodified lines16316416516616716815 unmodified lines184185186187188189162 unmodified lines} catch {}}public playTypeTick() {if (this.muted) return;try {15 unmodified linesosc.stop(this.ctx.currentTime + 0.015);} catch {}}}export const sounds = new SoundEngine();162 unmodified lines16316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428515 unmodified lines301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336162 unmodified lines} catch {}}public playSpin() {if (this.muted) return;try {this.init();if (!this.ctx) return;const now = this.ctx.currentTime;const osc = this.ctx.createOscillator();const gain = this.ctx.createGain();osc.type = 'sine';osc.frequency.setValueAtTime(300, now);osc.frequency.exponentialRampToValueAtTime(1800, now + 0.35);gain.gain.setValueAtTime(0.08, now);gain.gain.exponentialRampToValueAtTime(0.001, now + 0.4);osc.connect(gain);gain.connect(this.ctx.destination);osc.start(now);osc.stop(now + 0.4);} catch {}}public playPowerUp() {if (this.muted) return;try {this.init();if (!this.ctx) return;const now = this.ctx.currentTime;const notes = [440, 554.37, 659.25, 880, 1108.73, 1318.51];notes.forEach((freq, i) => {if (!this.ctx) return;const osc = this.ctx.createOscillator();const gain = this.ctx.createGain();osc.type = 'triangle';osc.frequency.setValueAtTime(freq, now + i * 0.05);gain.gain.setValueAtTime(0.06, now + i * 0.05);gain.gain.exponentialRampToValueAtTime(0.001, now + i * 0.05 + 0.09);osc.connect(gain);gain.connect(this.ctx.destination);osc.start(now + i * 0.05);osc.stop(now + i * 0.05 + 0.09);});} catch {}}public playChirp() {if (this.muted) return;try {this.init();if (!this.ctx) return;const now = this.ctx.currentTime;const osc = this.ctx.createOscillator();const gain = this.ctx.createGain();osc.type = 'sine';osc.frequency.setValueAtTime(900, now);osc.frequency.linearRampToValueAtTime(1600, now + 0.06);osc.frequency.linearRampToValueAtTime(1200, now + 0.12);gain.gain.setValueAtTime(0.07, now);gain.gain.exponentialRampToValueAtTime(0.001, now + 0.14);osc.connect(gain);gain.connect(this.ctx.destination);osc.start(now);osc.stop(now + 0.14);} catch {}}public playGiggle() {if (this.muted) return;try {this.init();if (!this.ctx) return;const now = this.ctx.currentTime;[800, 1000, 1200, 1000, 1300].forEach((freq, idx) => {if (!this.ctx) return;const osc = this.ctx.createOscillator();const gain = this.ctx.createGain();osc.type = 'triangle';osc.frequency.setValueAtTime(freq, now + idx * 0.04);gain.gain.setValueAtTime(0.05, now + idx * 0.04);gain.gain.exponentialRampToValueAtTime(0.001, now + idx * 0.04 + 0.05);osc.connect(gain);gain.connect(this.ctx.destination);osc.start(now + idx * 0.04);osc.stop(now + idx * 0.04 + 0.05);});} catch {}}public playDanceBeat() {if (this.muted) return;try {this.init();if (!this.ctx) return;const now = this.ctx.currentTime;const notes = [523.25, 659.25, 783.99, 1046.50, 783.99, 1046.50, 1318.51];notes.forEach((freq, idx) => {if (!this.ctx) return;const osc = this.ctx.createOscillator();const gain = this.ctx.createGain();osc.type = 'sine';osc.frequency.setValueAtTime(freq, now + idx * 0.08);gain.gain.setValueAtTime(0.07, now + idx * 0.08);gain.gain.exponentialRampToValueAtTime(0.001, now + idx * 0.08 + 0.1);osc.connect(gain);gain.connect(this.ctx.destination);osc.start(now + idx * 0.08);osc.stop(now + idx * 0.08 + 0.1);});} catch {}}public playTypeTick() {if (this.muted) return;try {15 unmodified linesosc.stop(this.ctx.currentTime + 0.015);} catch {}}public playBootSound() {if (this.muted) return;try {this.init();if (!this.ctx) return;const now = this.ctx.currentTime;const chords = [{ freq: 261.63, delay: 0.0 },{ freq: 329.63, delay: 0.09 },{ freq: 392.00, delay: 0.18 },{ freq: 523.25, delay: 0.27 },{ freq: 659.25, delay: 0.36 },{ freq: 1046.50, delay: 0.45 },];chords.forEach(({ freq, delay }) => {if (!this.ctx) return;const osc = this.ctx.createOscillator();const gain = this.ctx.createGain();osc.type = 'sine';osc.frequency.setValueAtTime(freq, now + delay);gain.gain.setValueAtTime(0.06, now + delay);gain.gain.exponentialRampToValueAtTime(0.0001, now + delay + 0.4);osc.connect(gain);gain.connect(this.ctx.destination);osc.start(now + delay);osc.stop(now + delay + 0.4);});} catch {}}}export const sounds = new SoundEngine();
49 unmodified lines5051525354555649 unmodified linespublic async speak(text: string,langCode: string = 'hi-IN',onEnd?: () => void,onError?: () => void,force: boolean = false49 unmodified lines5051525354555649 unmodified linespublic async speak(text: string,langCode: string = 'en-IN',onEnd?: () => void,onError?: () => void,force: boolean = false
.gitignore+6
app.py+3-3
app/globals.css+99-2
app/page.tsx+15-17
backend/__pycache__/server.cpython-314.pyc
backend/server.py+8-8
src/components/GameCharacterAvatar.tsx+447-124
src/components/MessageItem.tsx+1-1
src/components/SonicCharacter.tsx+17-12
src/components/SonicSplashIntro.tsxAdded+55
src/hooks/useVoiceRAG.ts+1-1
src/lib/soundEffects.ts+147
src/lib/ttsEngine.ts+1-1