Spaces:
Build error
Build error
faizr206 commited on
Commit ·
32532ca
1
Parent(s): 6d2efe1
common mistakes
Browse files24 unmodified lines2526272829303132333433 unmodified lines6869707172737411 unmodified lines86878889909114 unmodified lines1061071081091101111121131141151161171181191201 unmodified line12212312412512612712812942 unmodified lines1721731741751761771781791801811822 unmodified lines18518618718818919019119219319419519619719819920020120220325 unmodified lines22923023123223323435 unmodified lines2702712722732742752762772782792802812 unmodified lines2842852862872882892902912927 unmodified lines30030130230330430530630730830931031131231331431531631731831932032132232332432532632732832919 unmodified lines34935035135235335435524 unmodified lines# -------- FastAPI app --------app = FastAPI(title="Manim Render API (error + visual refine)")app.add_middleware(CORSMiddleware,allow_origins=["*"], # tighten in prodallow_methods=["*"],allow_headers=["*"],)RUNS = Path("runs"); RUNS.mkdir(parents=True, exist_ok=True)33 unmodified linesconfig=types.GenerateContentConfig(system_instruction=system),contents=contents,)# response.text is the canonical place for text outputreturn getattr(resp, "text", str(resp))# ---------------- prompts ----------------11 unmodified lines- Right after `# CAPTURE_POINT`, call self.wait(0.75) and then END THE SCENE.- DO NOT add any outro animations, fades, or camera moves after `# CAPTURE_POINT`.- Ensure all intended elements are visible and legible at `# CAPTURE_POINT` (adequate margins, no overlaps, font ≥ 32 px at 854x480)."""DEFAULT_SCENE = """from manim import *14 unmodified lines# ---------------- helpers ----------------def _clean_code(text: str) -> str:"""Strip common Markdown fences like ```python ... ``` or ``` ..."""if not text:return ""text = re.sub(r"^```(?:\s*python)?\s*", "", text.strip(), flags=re.IGNORECASE)text = re.sub(r"\s*```$", "", text)return text.strip()def _run_manim(scene_code: str, run_id: Optional[str] = None) -> Tuple[bytes, Optional[Path]]:"""Render MP4 (fast) and also save a steady-state PNG (last frame)."""run_id = run_id or str(uuid.uuid4())[:8]1 unmodified linemedia = work / "media"; media.mkdir(parents=True, exist_ok=True)scene_path = work / "scene.py"# Write scene codescene_path.write_text(scene_code, encoding="utf-8")env = os.environ.copy()env["PYTHONPATH"] = str(work)42 unmodified linesenv=env,)if proc_p.returncode == 0:# Manim saves under media/images/<module>/AutoScene.png (or a hash name)cand = Nonefor p in media.rglob("*.png"):cand = ppng_path = cand # last found is fine in this run directoryreturn mp4.read_bytes(), png_path2 unmodified linesif not client or not png_path or not png_path.exists():return Nonelimiter.acquire()# The current SDK expects a positional argument, not a keyword.# You can pass either a file object or a string path.with open(png_path, "rb") as f:file_ref = client.files.upload(f)return file_refdef llm_generate_manim_code(prompt: str, previous_code: Optional[str] = None) -> str:"""First-pass generation (capture-aware)."""if not client:return DEFAULT_SCENEtry:contents = f"Create AutoScene for: {prompt}\nRemember the CAPTURE POLICY."response_text = gemini_call(system=SYSTEM_PROMPT, contents=contents)code = _clean_code(response_text)if "class AutoScene" not in code:25 unmodified lines- Fix the bug while preserving the math logic and planned animations.- Keep exactly one class AutoScene(Scene).- Keep the CAPTURE POLICY and ensure # CAPTURE_POINT is at the final steady layout.- Return ONLY the corrected Python code (no backticks)."""response_text = gemini_call(system=SYSTEM_PROMPT, contents=user_prompt)35 unmodified linesReturn ONLY the revised Python code (no backticks)."""# Send the image + instruction in one contents array# Official pattern: [file_ref, "text"] after client.files.upload(...)# (docs: Using files + Image understanding)response_text = gemini_call(system=SYSTEM_PROMPT, contents=[file_ref, visual_prompt])code = _clean_code(response_text)# Only accept if it still defines AutoSceneif "class AutoScene" not in code:return previous_codereturn code2 unmodified linestraceback.print_exc()return previous_codedef refine_loop(user_prompt: str, max_error_refines: int = 1, do_visual_refine: bool = True) -> bytes:"""Generate → render; on error, refine once from Manim traceback → re-render.If first render succeeds and do_visual_refine==True, run an image-based refinementusing the saved steady-state PNG, then re-render. Fallback to the best successful MP4."""7 unmodified linesprint("Render failed (iter0), attempting error-based refinement...", file=sys.stderr)if max_error_refines <= 0:raiserefined = llm_refine_from_error(previous_code=code, error_message=e.log or "", original_user_prompt=user_prompt)mp4_bytes, png_path = _run_manim(refined, run_id="iter1")# If that worked, optionally move into visual refine with the refined codecode = refinedexcept Exception:# Unexpected wrapper error: try to salvage via refineprint("Unexpected error path; refining from Python traceback...", file=sys.stderr)if max_error_refines <= 0:raiserefined = llm_refine_from_error(previous_code=code, error_message=traceback.format_exc(), original_user_prompt=user_prompt)mp4_bytes, png_path = _run_manim(refined, run_id="iter1")code = refined# 3) optional visual refinement loopif do_visual_refine and png_path and png_path.exists():refined2 = llm_visual_refine_from_image(original_user_prompt=user_prompt, previous_code=code, png_path=png_path)if refined2.strip() != code.strip():# try re-rendertry:mp4_bytes2, _ = _run_manim(refined2, run_id="iter2")return mp4_bytes2except Exception as e:print("Visual refine render failed; returning best known render.", file=sys.stderr)# fall back to first successful videoreturn mp4_bytesreturn mp4_bytes19 unmodified linesif not inp.prompt or not inp.prompt.strip():raise HTTPException(400, "Missing prompt")try:mp4 = refine_loop(inp.prompt.strip(), max_error_refines=1, do_visual_refine=True)except Exception:raise HTTPException(500, "Failed to produce video after refinement")return Response(24 unmodified lines252627282930313233343533 unmodified lines69707172737411 unmodified lines868788899091929394959614 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531 unmodified line15515615715815916016116216342 unmodified lines2062072082092102112122132142152 unmodified lines21821922022122222322422522622722822923023123223325 unmodified lines25926026126226326426526635 unmodified lines3023033043053063073083092 unmodified lines3123133143153163173183193207 unmodified lines32832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437519 unmodified lines39539639739839940040124 unmodified lines# -------- FastAPI app --------app = FastAPI(title="Manim Render API (error + visual refine)")app.add_middleware(CORSMiddleware(allow_origins=["*"], # tighten in prodallow_methods=["*"],allow_headers=["*"],))RUNS = Path("runs"); RUNS.mkdir(parents=True, exist_ok=True)33 unmodified linesconfig=types.GenerateContentConfig(system_instruction=system),contents=contents,)return getattr(resp, "text", str(resp))# ---------------- prompts ----------------11 unmodified lines- Right after `# CAPTURE_POINT`, call self.wait(0.75) and then END THE SCENE.- DO NOT add any outro animations, fades, or camera moves after `# CAPTURE_POINT`.- Ensure all intended elements are visible and legible at `# CAPTURE_POINT` (adequate margins, no overlaps, font ≥ 32 px at 854x480).# Common Manim CE 0.19 API constraints (must follow)- Do NOT use `vertex=` with RightAngle(...). Choose the corner by line ordering or set quadrant=(±1, ±1).- Do NOT call `.to_center()` (not a valid method). Use `.center()` or `.move_to(ORIGIN)`.- Prefer `.move_to()`, `.align_to()`, `.to_edge()`, `.scale()`, `.next_to()` for layout/placement."""DEFAULT_SCENE = """from manim import *14 unmodified lines# ---------------- helpers ----------------def _clean_code(text: str) -> str:"""Strip common Markdown fences like ```python ... ``` or ``` ..."""if not text:return ""text = re.sub(r"^```(?:\s*python)?\s*", "", text.strip(), flags=re.IGNORECASE)text = re.sub(r"\s*```$", "", text)return text.strip()def _preflight_sanitize(code: str) -> str:"""Auto-correct a few frequent Manim CE 0.19 mistakes to reduce trivial crashes.- .to_center() -> .center()- Remove vertex=... from RightAngle(...), then normalize commas."""c = code# 1) replace invalid methodc = re.sub(r"\.to_center\(\)", ".center()", c)# 2) remove vertex=... kwarg inside RightAngle(...)# Case A: middle of arg list with trailing commac = re.sub(r"(RightAngle\s*\([^)]*?),\s*vertex\s*=\s*[^,)\s]+(\s*,)",r"\1\2",c,flags=re.DOTALL,)# Case B: last kwarg before ')'c = re.sub(r"(RightAngle\s*\([^)]*?),\s*vertex\s*=\s*[^,)\s]+(\s*\))",r"\1\2",c,flags=re.DOTALL,)# Normalize doubled commas or commas before ')'c = re.sub(r",\s*,", ", ", c)c = re.sub(r",\s*\)", ")", c)return cdef _run_manim(scene_code: str, run_id: Optional[str] = None) -> Tuple[bytes, Optional[Path]]:"""Render MP4 (fast) and also save a steady-state PNG (last frame)."""run_id = run_id or str(uuid.uuid4())[:8]1 unmodified linemedia = work / "media"; media.mkdir(parents=True, exist_ok=True)scene_path = work / "scene.py"# Write scene code (after sanitizer)safe_code = _preflight_sanitize(scene_code)scene_path.write_text(safe_code, encoding="utf-8")env = os.environ.copy()env["PYTHONPATH"] = str(work)42 unmodified linesenv=env,)if proc_p.returncode == 0:cand = Nonefor p in media.rglob("*.png"):cand = ppng_path = candreturn mp4.read_bytes(), png_path2 unmodified linesif not client or not png_path or not png_path.exists():return Nonelimiter.acquire()with open(png_path, "rb") as f:file_ref = client.files.upload(f) # positional arg; no 'path=' kwreturn file_refdef llm_generate_manim_code(prompt: str, previous_code: Optional[str] = None) -> str:"""First-pass generation (capture-aware)."""if not client:return DEFAULT_SCENEtry:contents = f"Create AutoScene for: {prompt}\nRemember the CAPTURE POLICY and Common API constraints."response_text = gemini_call(system=SYSTEM_PROMPT, contents=contents)code = _clean_code(response_text)if "class AutoScene" not in code:25 unmodified lines- Fix the bug while preserving the math logic and planned animations.- Keep exactly one class AutoScene(Scene).- Keep the CAPTURE POLICY and ensure # CAPTURE_POINT is at the final steady layout.- Scan for nonexistent methods (e.g., `.to_center`) or invalid kwargs (e.g., `vertex=` on RightAngle) and replace with valid Manim CE 0.19 API.- Prefer `.center()`/`.move_to(ORIGIN)`, and `.move_to()`, `.align_to()`, `.to_edge()`, `.next_to()` for layout.- Return ONLY the corrected Python code (no backticks)."""response_text = gemini_call(system=SYSTEM_PROMPT, contents=user_prompt)35 unmodified linesReturn ONLY the revised Python code (no backticks)."""response_text = gemini_call(system=SYSTEM_PROMPT, contents=[file_ref, visual_prompt])code = _clean_code(response_text)if "class AutoScene" not in code:return previous_codereturn code2 unmodified linestraceback.print_exc()return previous_codedef refine_loop(user_prompt: str, max_error_refines: int = 3, do_visual_refine: bool = True) -> bytes:"""Generate → render; on error, refine up to N times from Manim traceback → re-render.If first render succeeds and do_visual_refine==True, run an image-based refinementusing the saved steady-state PNG, then re-render. Fallback to the best successful MP4."""7 unmodified linesprint("Render failed (iter0), attempting error-based refinement...", file=sys.stderr)if max_error_refines <= 0:raiseattempts = 0last_err = e.log or ""while attempts < max_error_refines:attempts += 1refined = llm_refine_from_error(previous_code=code, error_message=last_err, original_user_prompt=user_prompt)try:mp4_bytes, png_path = _run_manim(refined, run_id=f"iter_err_{attempts}")code = refinedbreakexcept RenderError as e2:last_err = e2.log or last_errif attempts >= max_error_refines:raiseexcept Exception:last_err = traceback.format_exc()if attempts >= max_error_refines:raiseexcept Exception:print("Unexpected error path; refining from Python traceback...", file=sys.stderr)attempts = 0last_err = traceback.format_exc()while attempts < max_error_refines:attempts += 1refined = llm_refine_from_error(previous_code=code, error_message=last_err, original_user_prompt=user_prompt)try:mp4_bytes, png_path = _run_manim(refined, run_id=f"iter_err_{attempts}")code = refinedbreakexcept Exception:last_err = traceback.format_exc()if attempts >= max_error_refines:raise# 3) optional visual refinement loopif do_visual_refine and png_path and png_path.exists():refined2 = llm_visual_refine_from_image(original_user_prompt=user_prompt, previous_code=code, png_path=png_path)if refined2.strip() != code.strip():try:mp4_bytes2, _ = _run_manim(refined2, run_id="iter2")return mp4_bytes2except Exception:print("Visual refine render failed; returning best known render.", file=sys.stderr)return mp4_bytesreturn mp4_bytes19 unmodified linesif not inp.prompt or not inp.prompt.strip():raise HTTPException(400, "Missing prompt")try:mp4 = refine_loop(inp.prompt.strip(), max_error_refines=3, do_visual_refine=True)except Exception:raise HTTPException(500, "Failed to produce video after refinement")return Response(
app/main.py+83-37