Spaces:
Running
Running
File size: 5,031 Bytes
0805c5b |
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 |
"""
Audio Tools for Manim MCP Server
This module provides tools for generating narration scripts and speech audio.
"""
import json
import logging
from typing import Any, Dict, Optional
from mcp.types import CallToolResult, TextContent
from utils.hf_wrapper import HFInferenceWrapper, ModelConfig
logger = logging.getLogger(__name__)
async def generate_narration(
hf_wrapper: HFInferenceWrapper, arguments: Dict[str, Any]
) -> CallToolResult:
"""
Generate a narration script for an educational animation.
Uses a text LLM to create an engaging, age-appropriate narration script
that aligns with the animation concept and scene description.
Args:
hf_wrapper: HuggingFace inference wrapper instance
arguments: Dictionary containing:
- concept (str): The animation concept
- scene_description (str): Description of the scene/animation
- target_audience (str): Target audience level
- duration_seconds (int, optional): Duration in seconds (default: 30)
- model (str, optional): Hugging Face model to use
Returns:
CallToolResult with the narration script
"""
concept = arguments["concept"]
scene_description = arguments["scene_description"]
target_audience = arguments["target_audience"]
duration = arguments.get("duration_seconds", 30)
model = arguments.get("model")
try:
model_config = ModelConfig()
selected_model = model or model_config.text_models[0]
prompt = f"""
Generate a narration script for an educational animation:
Concept: {concept}
Scene: {scene_description}
Target Audience: {target_audience}
Duration: {duration} seconds
Requirements:
1. Clear, engaging, and age-appropriate language
2. Educational value aligned with learning objectives
3. Natural speaking pace (approximately {duration / 150} words for {duration} seconds)
4. Include pauses and emphasis markers where appropriate
5. Make it interesting and memorable
Format as a clean script ready for text-to-speech.
"""
response = await hf_wrapper.text_generation(
model=selected_model,
prompt=prompt,
max_new_tokens=512,
temperature=0.6,
)
logger.info(f"Successfully generated narration for concept: {concept}")
return CallToolResult(
content=[
TextContent(
type="text",
text=f"Narration Script:\n\n{response}",
)
]
)
except Exception as e:
logger.error(f"Narration generation failed: {str(e)}")
return CallToolResult(
content=[
TextContent(
type="text",
text=f"Narration generation failed: {str(e)}",
)
],
isError=True,
)
async def generate_speech(
hf_wrapper: HFInferenceWrapper, arguments: Dict[str, Any]
) -> CallToolResult:
"""
Convert text to speech audio file.
Uses a TTS model to generate speech audio from text and saves it to a file.
Args:
hf_wrapper: HuggingFace inference wrapper instance
arguments: Dictionary containing:
- text (str): Text to convert to speech
- output_path (str): Path where to save the audio file
- voice (str, optional): Voice to use for TTS
- model (str, optional): Hugging Face TTS model to use
Returns:
CallToolResult with audio generation info
"""
text = arguments["text"]
output_path = arguments["output_path"]
voice = arguments.get("voice")
model = arguments.get("model")
try:
model_config = ModelConfig()
selected_model = model or model_config.tts_models[0]
# Generate audio
audio_bytes = await hf_wrapper.text_to_speech(
model=selected_model,
text=text,
voice=voice,
)
# Save to file
success = await hf_wrapper.save_audio_to_file(audio_bytes, output_path)
if not success:
raise Exception("Failed to save audio file")
# Return audio info
audio_info = {
"output_path": output_path,
"text_length": len(text),
"estimated_duration": len(text) / 150, # Rough estimate
"model_used": selected_model,
}
logger.info(f"Successfully generated speech audio at: {output_path}")
return CallToolResult(
content=[
TextContent(
type="text",
text=f"Speech generated successfully!\n\n{json.dumps(audio_info, indent=2)}",
)
]
)
except Exception as e:
logger.error(f"Speech generation failed: {str(e)}")
return CallToolResult(
content=[
TextContent(type="text", text=f"Speech generation failed: {str(e)}")
],
isError=True,
)
|