Spaces:
Sleeping
Sleeping
File size: 9,152 Bytes
9bed109 | 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 | from __future__ import annotations
import logging
from datetime import UTC, datetime
from pathlib import Path
from uuid import UUID, uuid4
import httpx
from ai_engine.config import default_agent_models_path, load_agent_models_yaml, load_runtime_limits
from backend.core.config import settings
from backend.services.job_store import RedisRenderJobStore
from backend.services.redis_client import get_redis
from backend.services.supabase_pipeline_rest import insert_worker_service_audit_row
from shared.pipeline_log import (
get_pipeline_trace_id,
pipeline_error,
pipeline_event,
)
from worker.renderer import render_manim_scene_to_disk
from worker.supabase_storage import upload_render_artifact_if_configured
logger = logging.getLogger(__name__)
def execute_render_job(job_id: UUID) -> None:
tid = get_pipeline_trace_id()
logger.info("Worker: execute_render_job started job_id=%s trace_id=%s", job_id, tid)
pipeline_event(
"worker.render",
"execute_start",
"Worker starting render execution logic",
job_id=str(job_id),
trace_id=tid,
)
store = RedisRenderJobStore(get_redis())
job = store.get(job_id)
if job is None:
logger.error("render job missing: %s", job_id)
pipeline_event(
"worker.render",
"job_missing",
"Render job not found in Redis",
job_id=str(job_id),
trace_id=tid,
)
return
pipeline_event(
"worker.render",
"job_loaded",
"Loaded render job; starting pipeline",
job_id=str(job_id),
trace_id=tid,
project_id=str(job.project_id),
scene_id=str(job.scene_id) if job.scene_id else None,
details={"job_type": job.job_type, "render_quality": job.render_quality},
)
store.update(
job_id,
status="rendering",
started_at=datetime.now(tz=UTC),
progress=5,
logs="Starting Manim render...",
)
job_dir: Path | None = None
result = None
job_dir = None
try:
quality = job.render_quality or "720p"
pipeline_event(
"worker.render",
"manim_start",
"Invoking Manim render",
job_id=str(job_id),
trace_id=tid,
details={"quality": quality, "job_type": job.job_type},
)
yaml_path = (
Path(settings.agent_models_yaml).expanduser()
if settings.agent_models_yaml
else default_agent_models_path()
)
yaml_data = load_agent_models_yaml(yaml_path)
rt = load_runtime_limits(yaml_data)
manim_timeout = rt.worker_man_render_timeout_seconds
result = render_manim_scene_to_disk(
job_id=job_id,
job_type=job.job_type,
quality=quality,
timeout=manim_timeout,
)
video_path = result.video_path
job_dir = result.job_dir
pipeline_event(
"worker.render",
"manim_done",
"Manim finished",
job_id=str(job_id),
trace_id=tid,
details={"video_path": str(video_path), "returncode_ok": True},
)
remote_url = upload_render_artifact_if_configured(
video_path=video_path,
project_id=job.project_id,
job_id=job_id,
)
asset_url = remote_url if remote_url else f"file://{video_path}"
pipeline_event(
"worker.render",
"artifact_ready",
"Upload/local asset URL resolved",
job_id=str(job_id),
trace_id=tid,
details={"has_remote_url": bool(remote_url)},
)
video_duration = 0.0
try:
from worker.tts_runtime import _ffprobe_duration_seconds
video_duration = _ffprobe_duration_seconds(video_path)
except Exception:
logger.warning("Failed to calculate video duration for job_id=%s", job_id)
store.update(
job_id,
status="completed",
progress=100,
asset_url=asset_url,
completed_at=datetime.now(tz=UTC),
logs="Render completed.",
metadata={"video_duration": video_duration},
)
pipeline_event(
"worker.render",
"job_completed",
"Render job marked completed in Redis",
job_id=str(job_id),
trace_id=tid,
)
try:
insert_worker_service_audit_row(
audit_id=uuid4(),
project_id=job.project_id,
scene_id=job.scene_id,
worker_kind="manim",
worker_name=settings.worker_name,
render_job_id=job_id,
payload={
"status": "completed",
"command": result.command,
"stdout_tail": result.stdout_tail,
"stderr_tail": result.stderr_tail,
"asset_url": asset_url,
"video_path": str(video_path),
},
)
except Exception:
logger.exception("Audit insertion failed for job_id=%s (non-fatal)", job_id)
if job.webhook_url:
try:
_post_webhook(
job.webhook_url,
job_id=job_id,
job_status="completed",
asset_url=asset_url,
error=None,
)
except Exception:
logger.exception("Webhook failed for job_id=%s (non-fatal)", job_id)
except Exception as exc: # noqa: BLE001 — surface failure to job record
logger.exception("Render failed job_id=%s", job_id)
pipeline_error(
"worker.render",
"job_failed",
"Render pipeline raised",
job_id=str(job_id),
trace_id=tid,
details={"error": str(exc)[:2000]},
)
store.update(
job_id,
status="failed",
error_code="render_failed",
completed_at=datetime.now(tz=UTC),
logs=str(exc),
)
insert_worker_service_audit_row(
audit_id=uuid4(),
project_id=job.project_id,
scene_id=job.scene_id,
worker_kind="manim",
worker_name=settings.worker_name,
render_job_id=job_id,
payload={"status": "failed", "error": str(exc)},
)
if job.webhook_url:
_post_webhook(
job.webhook_url,
job_id=job_id,
job_status="failed",
asset_url=None,
error=str(exc),
)
finally:
if job_dir and job_dir.exists():
import shutil
try:
# New Structured Storage: storage/outputs/<project_id>/<scene_id>/
project_dir = Path(settings.output_dir) / str(job.project_id)
scene_dir = project_dir / (str(job.scene_id) if job.scene_id else "misc")
scene_dir.mkdir(parents=True, exist_ok=True)
# 1. Final Combined (result.video_path)
if result and result.video_path and result.video_path.exists():
shutil.copy2(result.video_path, scene_dir / "final_combined.mp4")
# 2. Silent Manim (result.silent_video_path)
if result and result.silent_video_path and result.silent_video_path.exists():
shutil.copy2(result.silent_video_path, scene_dir / "manim_silent.mp4")
# 3. Voice Audio (result.audio_path)
if result and result.audio_path and result.audio_path.exists():
shutil.copy2(result.audio_path, scene_dir / "voice_audio.wav")
# Intermediates in sub-folder
intermediates_dir = scene_dir / "intermediates"
intermediates_dir.mkdir(parents=True, exist_ok=True)
# Copy logs and generated script
for file in job_dir.glob("*"):
if file.is_file() and file.suffix != ".mp4" and file.suffix != ".wav":
shutil.copy2(file, intermediates_dir / file.name)
logger.info("Structured outputs saved to %s", scene_dir)
except Exception as local_err:
logger.warning("Failed to save structured outputs: %s", local_err)
logger.info("Cleaning up job_dir: %s", job_dir)
shutil.rmtree(job_dir, ignore_errors=True)
def _post_webhook(
url: str,
*,
job_id: UUID,
job_status: str,
asset_url: str | None,
error: str | None,
) -> None:
payload: dict[str, object] = {
"job_id": str(job_id),
"status": job_status,
"asset_url": asset_url,
"metadata": {"error": error, "worker": settings.worker_name},
}
try:
httpx.post(url, json=payload, timeout=10.0)
except Exception:
logger.exception("Webhook POST failed job_id=%s url=%s", job_id, url)
|