File size: 8,581 Bytes
8374119 48b92eb 8374119 |
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 |
"""
Gradio UI for Chloe's Voice Komentle Game
Connects to FastAPI backend for voice analysis
"""
import os
# Set Gradio temp directory BEFORE importing gradio
_upload_dir = os.path.join(os.path.dirname(__file__), "gradio_uploads")
os.makedirs(_upload_dir, exist_ok=True)
os.environ["GRADIO_TEMP_DIR"] = _upload_dir
import gradio as gr
from datetime import datetime
import uuid
import asyncio
from sqlalchemy import create_engine, text
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Import backend functions
from backend import (
analyze_voice_logic,
get_puzzle_by_date,
lifespan,
app as backend_app,
)
# Database connection
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(
DATABASE_URL,
pool_size=10, # κΈ°λ³Έ μ°κ²° ν ν¬κΈ°
max_overflow=20, # μ΅λ μΆκ° μ°κ²° μ
pool_pre_ping=True, # μ°κ²° μ¬μ© μ μ ν¨μ± κ²μ¬
pool_recycle=3600, # 1μκ°λ§λ€ μ°κ²° μ¬μμ±
connect_args={
"connect_timeout": 10, # μ°κ²° νμμμ 10μ΄
"options": "-c statement_timeout=30000" # 쿼리 νμμμ 30μ΄
}
)
# Session ID (persistent across attempts)
session_id = str(uuid.uuid4())
# Backend initialization flag
backend_initialized = False
async def analyze_voice_async(audio_file, date_str):
"""
Analyze voice using backend logic directly
Args:
audio_file: Path to recorded audio file
date_str: Date string for puzzle lookup
Returns:
tuple: (result_text, scores_text, hint_text, image_path)
"""
if audio_file is None:
return "β μ€λμ€λ₯Ό λ¨Όμ λ
Ήμν΄μ£ΌμΈμ!", "", "", None
try:
# Read audio file
with open(audio_file, "rb") as f:
audio_bytes = f.read()
# Call backend logic directly
result = await analyze_voice_logic(audio_bytes, date_str, session_id)
# Handle errors
if result.get("status") == "error":
return f"β {result.get('message', 'Unknown error')}", "", "", None
# Parse response (already in 0-100 range from backend)
category = result.get("category", "unknown")
pitch = result.get("pitch", 0.0)
rhythm = result.get("rhythm", 0.0)
energy = result.get("energy", 0.0)
pronunciation = result.get("pronunciation", 0.0)
transcript = result.get("transcript", 0.0)
overall = result.get("overall", 0.0)
advice = result.get("advice", "")
is_correct = result.get("is_correct", False)
hints = {} # hints are embedded in advice now
# Format result message
if is_correct:
result_msg = f"π μ λ΅μ
λλ€! μ 체 μ μ: {overall:.1f}/100"
else:
result_msg = f"π μ 체 μ μ: {overall:.1f}/100 - λ€μ μλν΄λ³΄μΈμ!"
# Format scores
scores_text = f"""
### π μ μ μμΈ
**μΉ΄ν
κ³ λ¦¬:** {category.upper()}
- **λ°μ (Pronunciation):** {pronunciation:.1f}/100
- **μλμ΄ (Pitch):** {pitch:.1f}/100
- **λ¦¬λ¬ (Rhythm):** {rhythm:.1f}/100
- **μλμ§ (Energy):** {energy:.1f}/100
- **μ μ¬ (Transcript):** {transcript:.1f}/100
- **μ 체 (Overall):** {overall:.1f}/100
"""
# Format hints
hint_text = ""
hint_image = None
if hints and "answer" in hints:
hint_type = hints.get("type", "hint")
hint_items = hints.get("answer", [])
if hint_type == "hint":
hint_text = "π‘ **ννΈ:**\n\n"
else:
hint_text = "π― **λ°μ μ‘°μΈ:**\n\n"
for item in hint_items:
hint_text += f"{item.get('text', '')}\n\n"
# Get image path if exists
img_path = item.get("path", "")
if img_path and os.path.exists(img_path):
hint_image = img_path
# Add advice if no hints
if not hint_text and advice:
hint_text = f"π¬ **μ‘°μΈ:**\n\n{advice}"
return result_msg, scores_text, hint_text, hint_image
except Exception as e:
return f"β μ€λ₯ λ°μ: {str(e)}", "", "", None
def analyze_voice(audio_file, date_str):
"""Synchronous wrapper for async analyze_voice_async"""
return asyncio.run(analyze_voice_async(audio_file, date_str))
def get_today_puzzle():
"""Get today's puzzle information from database"""
try:
today = datetime.now().strftime("%Y-%m-%d")
# Use backend function to get puzzle
puzzle = get_puzzle_by_date(today)
# print(puzzle)
if puzzle:
return f"""
### π
μ€λμ νΌμ¦
**λ μ§:** {puzzle.get('puzzle_date', 'N/A')}
**νΌμ¦ λ²νΈ:** #{puzzle.get('puzzle_number', 'N/A')}
**μΉ΄ν
κ³ λ¦¬:** {puzzle.get('category', 'N/A').upper()}
**λμ΄λ:** {puzzle.get('difficulty', 'N/A')}
μ λ΅ λ¨μ΄λ₯Ό λ°μν΄λ³΄μΈμ! (μ΅λ 6ν μλ)
"""
else:
return "β μ€λμ νΌμ¦μ μ°Ύμ μ μμ΅λλ€."
except Exception as e:
return f"β νΌμ¦ μ 보λ₯Ό κ°μ Έμ¬ μ μμ΅λλ€: {str(e)}"
def reset_session():
"""Reset session for new game"""
global session_id
session_id = str(uuid.uuid4())
return "β
μ κ²μ μμ! μ€λμ€λ₯Ό λ
Ήμν΄μ£ΌμΈμ.", "", "", None
# Create Gradio Interface
with gr.Blocks(title="Chloe's Voice Komentle") as demo:
gr.Markdown("# π€ Chloe's Voice Komentle")
# Puzzle info section
with gr.Row():
puzzle_info = gr.Markdown(value=get_today_puzzle())
refresh_btn = gr.Button("π νΌμ¦ μ 보 μλ‘κ³ μΉ¨", size="sm")
with gr.Row():
with gr.Column(scale=1):
# Audio recording
gr.Markdown("### ποΈ μμ± λ
Ήμ")
audio_input = gr.Audio(
sources=["microphone"],
type="filepath",
label="λ§μ΄ν¬λ‘ λ
Ήμ",
format="wav",
)
# Date input (auto-filled with today)
date_input = gr.Textbox(
label="λ μ§ (YYYY-MM-DD)",
value=datetime.now().strftime("%Y-%m-%d"),
interactive=True,
)
# Submit button
submit_btn = gr.Button("π― λΆμνκΈ°", variant="primary", size="lg")
reset_btn = gr.Button("π μ κ²μ μμ", variant="secondary")
with gr.Column(scale=1):
# Results
gr.Markdown("### π κ²°κ³Ό")
result_output = gr.Markdown(label="κ²°κ³Ό")
scores_output = gr.Markdown(label="μ μ μμΈ")
# Hints section
with gr.Row():
with gr.Column():
hint_output = gr.Markdown(label="ννΈ λ° μ‘°μΈ")
with gr.Column():
hint_image = gr.Image(label="ννΈ μ΄λ―Έμ§", show_label=True)
# Event handlers
submit_btn.click(
fn=analyze_voice,
inputs=[audio_input, date_input],
outputs=[result_output, scores_output, hint_output, hint_image],
)
reset_btn.click(
fn=reset_session,
inputs=[],
outputs=[result_output, scores_output, hint_output, hint_image],
)
refresh_btn.click(fn=get_today_puzzle, inputs=[], outputs=[puzzle_info])
# Footer
gr.Markdown("---\n**Powered by:** VoiceKit MCP + Gemini AI")
# Launch configuration
if __name__ == "__main__":
# Initialize backend (VoiceKit MCP session)
print("β³ Initializing VoiceKit MCP...")
async def init_backend():
"""Initialize backend resources"""
async with lifespan(backend_app):
print("β VoiceKit MCP initialized")
# Keep the lifespan context active
await asyncio.Event().wait() # Wait forever
# Run backend initialization in background
import threading
def run_backend_init():
asyncio.run(init_backend())
backend_thread = threading.Thread(target=run_backend_init, daemon=True)
backend_thread.start()
# Wait a bit for initialization
import time
time.sleep(5)
print("β Backend initialized")
# Launch Gradio
server_host = os.getenv("SERVER_HOST")
frontend_port = int(os.getenv("FRONTEND_PORT"))
demo.launch(
server_name=server_host, # Listen on all interfaces
server_port=frontend_port, # Default Gradio port
share=False, # Set to True for public link
show_error=True,
allowed_paths=[os.path.join(os.path.dirname(__file__), "hints", "audio")], # Allow serving TTS audio hints
)
|