Spaces:
Running
Running
File size: 19,829 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 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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 |
"""
LangGraph Agent Nodes for NeuroAnim Pipeline
This module contains all the node functions used in the LangGraph workflow.
Each node represents a step in the animation generation pipeline and
communicates with the Manim MCP server to perform its task.
"""
import ast
import json
import logging
import re
import tempfile
import time
from pathlib import Path
from typing import Any, Dict
from mcp import ClientSession
from neuroanim.graph.state import AnimationState
from utils.tts import TTSGenerator
logger = logging.getLogger(__name__)
class AnimationNodes:
"""Container for all animation pipeline nodes."""
def __init__(
self,
mcp_session: ClientSession,
tts_generator: TTSGenerator,
work_dir: Path,
output_dir: Path,
):
"""
Initialize the animation nodes.
Args:
mcp_session: MCP client session for tool calls
tts_generator: TTS generator instance
work_dir: Working directory for temporary files
output_dir: Output directory for final files
"""
self.mcp_session = mcp_session
self.tts_generator = tts_generator
self.work_dir = work_dir
self.output_dir = output_dir
async def call_mcp_tool(
self, tool_name: str, arguments: Dict[str, Any]
) -> Dict[str, Any]:
"""
Call an MCP tool and return the result.
Args:
tool_name: Name of the tool to call
arguments: Arguments to pass to the tool
Returns:
Dictionary with 'text' and 'isError' keys
"""
try:
result = await self.mcp_session.call_tool(tool_name, arguments)
if hasattr(result, "content") and result.content:
content = result.content[0]
if hasattr(content, "text"):
return {
"text": content.text,
"isError": getattr(result, "isError", False),
}
return {"text": str(result), "isError": False}
except Exception as e:
logger.error(f"MCP tool call failed for {tool_name}: {e}")
return {"text": f"Tool call failed: {str(e)}", "isError": True}
async def initialize_node(self, state: AnimationState) -> AnimationState:
"""
Initialize the pipeline state and working directories.
Args:
state: Current animation state
Returns:
Updated state with initialized paths and metadata
"""
logger.info("π Initializing animation pipeline")
state["start_time"] = time.time()
state["work_dir"] = str(self.work_dir)
state["output_dir"] = str(self.output_dir)
state["current_step"] = "initialization"
state["completed_steps"].append("initialization")
logger.info(f"Working directory: {self.work_dir}")
logger.info(f"Output directory: {self.output_dir}")
return state
async def plan_concept_node(self, state: AnimationState) -> AnimationState:
"""
Plan the animation concept using AI.
Args:
state: Current animation state
Returns:
Updated state with concept plan
"""
logger.info("π Planning concept...")
state["current_step"] = "concept_planning"
try:
result = await self.call_mcp_tool(
"plan_concept",
{
"topic": state["topic"],
"target_audience": state["target_audience"],
"animation_length_minutes": state["animation_length_minutes"],
},
)
if result["isError"]:
state["errors"].append(f"Concept planning failed: {result['text']}")
return state
concept_plan = result["text"]
state["concept_plan"] = concept_plan
# Try to parse JSON from the concept plan
try:
# Extract JSON if it's embedded in the response
json_match = re.search(r"\{.*\}", concept_plan, re.DOTALL)
if json_match:
plan_data = json.loads(json_match.group())
state["learning_objectives"] = plan_data.get(
"learning_objectives", []
)
state["visual_metaphors"] = plan_data.get("visual_metaphors", [])
state["scene_flow"] = plan_data.get("scene_flow", [])
except json.JSONDecodeError:
logger.warning("Could not parse concept plan as JSON")
state["completed_steps"].append("concept_planning")
logger.info("β
Concept planning completed")
except Exception as e:
logger.error(f"Concept planning failed: {e}")
state["errors"].append(f"Concept planning error: {str(e)}")
return state
async def generate_narration_node(self, state: AnimationState) -> AnimationState:
"""
Generate narration script for the animation.
Args:
state: Current animation state
Returns:
Updated state with narration text
"""
logger.info("ποΈ Generating narration...")
state["current_step"] = "narration_generation"
try:
duration_seconds = int(state["animation_length_minutes"] * 60)
result = await self.call_mcp_tool(
"generate_narration",
{
"concept": state["topic"],
"scene_description": state.get("concept_plan", ""),
"target_audience": state["target_audience"],
"duration_seconds": duration_seconds,
},
)
if result["isError"]:
state["errors"].append(f"Narration generation failed: {result['text']}")
return state
# Extract narration text from response
narration_text = result["text"]
if "Narration Script:" in narration_text:
narration_text = narration_text.split("Narration Script:")[-1].strip()
state["narration_text"] = narration_text
state["narration_duration"] = duration_seconds
state["completed_steps"].append("narration_generation")
logger.info("β
Narration generation completed")
except Exception as e:
logger.error(f"Narration generation failed: {e}")
state["errors"].append(f"Narration generation error: {str(e)}")
return state
async def generate_code_node(self, state: AnimationState) -> AnimationState:
"""
Generate Manim code for the animation.
Args:
state: Current animation state
Returns:
Updated state with generated code
"""
logger.info("π» Generating Manim code...")
state["current_step"] = "code_generation"
try:
# Check if this is a retry
previous_code = None
error_message = None
if state["code_generation_attempts"] > 0:
previous_code = state.get("manim_code")
if state.get("previous_code_errors"):
error_message = state["previous_code_errors"][-1]
state["code_generation_attempts"] += 1
arguments = {
"concept": state["topic"],
"scene_description": state.get("concept_plan", ""),
"visual_elements": ["text", "shapes", "animations"],
}
if previous_code and error_message:
arguments["previous_code"] = previous_code
arguments["error_message"] = error_message
logger.info(
f"Retrying code generation (attempt {state['code_generation_attempts']})"
)
result = await self.call_mcp_tool("generate_manim_code", arguments)
if result["isError"]:
state["errors"].append(f"Code generation failed: {result['text']}")
return state
# Extract Python code from response
code_text = result["text"]
manim_code = self._extract_python_code(code_text)
# Validate syntax
validation_error = self._validate_python_syntax(manim_code)
if validation_error:
logger.warning(f"Code validation failed: {validation_error}")
if not state.get("previous_code_errors"):
state["previous_code_errors"] = []
state["previous_code_errors"].append(validation_error)
state["warnings"].append(f"Code validation issue: {validation_error}")
else:
logger.info("β
Code validation passed")
state["manim_code"] = manim_code
state["scene_name"] = self._extract_scene_name(manim_code)
state["completed_steps"].append("code_generation")
logger.info(f"β
Code generation completed (scene: {state['scene_name']})")
except Exception as e:
logger.error(f"Code generation failed: {e}")
state["errors"].append(f"Code generation error: {str(e)}")
return state
async def write_file_node(self, state: AnimationState) -> AnimationState:
"""
Write the Manim code to a file.
Args:
state: Current animation state
Returns:
Updated state with file path
"""
logger.info("π Writing Manim file...")
state["current_step"] = "file_writing"
try:
manim_file = Path(state["work_dir"]) / "animation.py"
state["manim_file_path"] = str(manim_file)
result = await self.call_mcp_tool(
"write_manim_file",
{"filepath": str(manim_file), "code": state["manim_code"]},
)
if result["isError"]:
state["errors"].append(f"File writing failed: {result['text']}")
return state
state["completed_steps"].append("file_writing")
logger.info(f"β
Manim file written to {manim_file}")
except Exception as e:
logger.error(f"File writing failed: {e}")
state["errors"].append(f"File writing error: {str(e)}")
return state
async def render_animation_node(self, state: AnimationState) -> AnimationState:
"""
Render the Manim animation.
Args:
state: Current animation state
Returns:
Updated state with rendered video path
"""
logger.info("π¬ Rendering animation...")
state["current_step"] = "rendering"
try:
result = await self.call_mcp_tool(
"render_manim_animation",
{
"scene_name": state["scene_name"],
"file_path": state["manim_file_path"],
"output_dir": state["work_dir"],
"quality": state["rendering_quality"],
"format": state["rendering_format"],
"frame_rate": state["frame_rate"],
},
)
if result["isError"]:
state["errors"].append(f"Rendering failed: {result['text']}")
return state
# Find the rendered video file
video_file = (
Path(state["work_dir"])
/ f"{state['scene_name']}.{state['rendering_format']}"
)
if not video_file.exists():
state["errors"].append(f"Rendered video not found at {video_file}")
return state
state["video_file_path"] = str(video_file)
state["completed_steps"].append("rendering")
logger.info(f"β
Animation rendered: {video_file}")
except Exception as e:
logger.error(f"Rendering failed: {e}")
state["errors"].append(f"Rendering error: {str(e)}")
return state
async def generate_audio_node(self, state: AnimationState) -> AnimationState:
"""
Generate speech audio from narration text.
Args:
state: Current animation state
Returns:
Updated state with audio file path
"""
logger.info("π Generating speech audio...")
state["current_step"] = "audio_generation"
try:
audio_file = Path(state["work_dir"]) / "narration.mp3"
state["audio_file_path"] = str(audio_file)
# Use TTS generator with automatic fallback
tts_result = await self.tts_generator.generate_speech(
text=state["narration_text"], output_path=audio_file, voice="rachel"
)
logger.info(f"Audio generated with {tts_result['provider']}")
# Validate audio file
validation = self.tts_generator.validate_audio_file(audio_file)
if not validation["valid"]:
state["warnings"].append(
f"Audio validation warning: {validation.get('error', 'Unknown issue')}"
)
else:
logger.info(
f"Audio validated: {validation.get('duration', 'N/A')}s, {validation.get('size', 0)} bytes"
)
state["completed_steps"].append("audio_generation")
logger.info(f"β
Audio generated: {audio_file}")
except Exception as e:
logger.error(f"Audio generation failed: {e}")
state["errors"].append(f"Audio generation error: {str(e)}")
return state
async def merge_video_audio_node(self, state: AnimationState) -> AnimationState:
"""
Merge video and audio into final output.
Args:
state: Current animation state
Returns:
Updated state with final output path
"""
logger.info("ποΈ Merging video and audio...")
state["current_step"] = "video_audio_merge"
try:
final_output = Path(state["output_dir"]) / state["output_filename"]
state["final_output_path"] = str(final_output)
result = await self.call_mcp_tool(
"merge_video_audio",
{
"video_file": state["video_file_path"],
"audio_file": state["audio_file_path"],
"output_file": str(final_output),
},
)
if result["isError"]:
state["errors"].append(f"Video/audio merge failed: {result['text']}")
return state
state["completed_steps"].append("video_audio_merge")
logger.info(f"β
Video and audio merged: {final_output}")
except Exception as e:
logger.error(f"Video/audio merge failed: {e}")
state["errors"].append(f"Merge error: {str(e)}")
return state
async def generate_quiz_node(self, state: AnimationState) -> AnimationState:
"""
Generate quiz questions for the topic.
Args:
state: Current animation state
Returns:
Updated state with quiz content
"""
logger.info("β Generating quiz...")
state["current_step"] = "quiz_generation"
try:
result = await self.call_mcp_tool(
"generate_quiz",
{
"concept": state["topic"],
"difficulty": "medium",
"num_questions": 3,
"question_types": ["multiple_choice"],
},
)
if result["isError"]:
state["warnings"].append(f"Quiz generation failed: {result['text']}")
state["quiz_content"] = "Quiz generation failed"
else:
state["quiz_content"] = result["text"]
# Try to parse quiz questions
try:
json_match = re.search(r"\[.*\]", result["text"], re.DOTALL)
if json_match:
state["quiz_questions"] = json.loads(json_match.group())
except json.JSONDecodeError:
logger.warning("Could not parse quiz as JSON")
state["completed_steps"].append("quiz_generation")
logger.info("β
Quiz generation completed")
except Exception as e:
logger.error(f"Quiz generation failed: {e}")
state["warnings"].append(f"Quiz generation error: {str(e)}")
state["quiz_content"] = "Quiz generation failed"
return state
async def finalize_node(self, state: AnimationState) -> AnimationState:
"""
Finalize the pipeline and compute metadata.
Args:
state: Current animation state
Returns:
Final state with metadata
"""
logger.info("π Finalizing pipeline...")
state["current_step"] = "finalization"
state["end_time"] = time.time()
state["total_duration"] = state["end_time"] - state["start_time"]
# Check if pipeline succeeded
if not state["errors"] and state.get("final_output_path"):
state["success"] = True
logger.info(
f"β
Pipeline completed successfully in {state['total_duration']:.2f}s"
)
else:
state["success"] = False
logger.error(f"β Pipeline failed with {len(state['errors'])} error(s)")
state["completed_steps"].append("finalization")
return state
# Helper methods
def _extract_python_code(self, response_text: str) -> str:
"""Extract Python code from markdown response."""
if "```python" in response_text:
start = response_text.find("```python") + 9
end = response_text.find("```", start)
if end == -1:
end = len(response_text)
return response_text[start:end].strip()
elif "```" in response_text:
start = response_text.find("```") + 3
end = response_text.find("```", start)
if end == -1:
end = len(response_text)
return response_text[start:end].strip()
else:
return response_text.strip()
def _extract_scene_name(self, code: str) -> str:
"""Extract the scene class name from Manim code."""
try:
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
# Check if it inherits from Scene or MovingCameraScene
for base in node.bases:
if isinstance(base, ast.Name) and base.id in [
"Scene",
"MovingCameraScene",
"ThreeDScene",
]:
return node.name
except SyntaxError:
pass
# Fallback: use regex
match = re.search(r"class\s+(\w+)\s*\(.*Scene.*\):", code)
if match:
return match.group(1)
return "GenScene"
def _validate_python_syntax(self, code: str) -> str | None:
"""
Validate Python code syntax.
Returns:
Error message if validation fails, None if valid
"""
try:
ast.parse(code)
return None
except SyntaxError as e:
return f"Syntax error at line {e.lineno}: {e.msg}"
except Exception as e:
return f"Validation error: {str(e)}"
|