MCPcopy Index your code
hub / github.com/showlab/Code2Video / generate_section_code

Method generate_section_code

src/agent.py:295–354  ·  view source on GitHub ↗

Generate Manim code for a single section

(self, section: Section, attempt: int = 1, feedback_improvements=None)

Source from the content-addressed store, hash-verified

293 return storyboard_data
294
295 def generate_section_code(self, section: Section, attempt: int = 1, feedback_improvements=None) -> str:
296 """Generate Manim code for a single section"""
297 code_file = self.output_dir / f"{section.id}.py"
298
299 if attempt == 1 and code_file.exists() and not feedback_improvements:
300 print(f"📂 Found existing code for {section.id}, reading...")
301 with open(code_file, "r", encoding="utf-8") as f:
302 code = f.read()
303 self.section_codes[section.id] = code
304 return code
305 # print(f"💻 Generating Manim code for {section.id} (attempt {attempt}/{self.max_regenerate_tries})...")
306 regenerate_note = ""
307 if attempt > 1:
308 regenerate_note = get_regenerate_note(attempt, MAX_REGENERATE_TRIES=self.max_regenerate_tries)
309
310 # Add MLLM feedback and improvement suggestions
311 if feedback_improvements:
312 current_code = self.section_codes.get(section.id, "")
313 try:
314 modifier = GridCodeModifier(current_code)
315 modified_code = modifier.parse_feedback_and_modify(feedback_improvements)
316 with open(code_file, "w", encoding="utf-8") as f:
317 f.write(modified_code)
318
319 self.section_codes[section.id] = modified_code
320 return modified_code
321 except Exception as e:
322 print(f"⚠️ GridCodeModifier failed, falling back to original code: {e}")
323 code_gen_prompt = get_feedback_improve_code(
324 feedback=get_feedback_list_prefix(feedback_improvements), code=current_code
325 )
326
327 else:
328 code_gen_prompt = get_prompt3_code(regenerate_note=regenerate_note, section=section, base_class=base_class)
329
330 response = self._request_api_and_track_tokens(code_gen_prompt, max_tokens=self.max_code_token_length)
331 if response is None:
332 print(f"❌ Failed to generate code for {section.id} via API call.")
333 return ""
334
335 try:
336 code = response.candidates[0].content.parts[0].text
337 except Exception:
338 try:
339 code = response.choices[0].message.content
340 except Exception:
341 code = str(response)
342 if "```python" in code:
343 code = code.split("```python")[1].split("```")[0].strip()
344 elif "```" in code:
345 code = code.split("```")[1].strip()
346
347 # Replace base class
348 code = replace_base_class(code, base_class)
349
350 with open(code_file, "w", encoding="utf-8") as f:
351 f.write(code)
352

Callers 3

taskMethod · 0.95
render_sectionMethod · 0.95

Calls 8

get_regenerate_noteFunction · 0.85
GridCodeModifierClass · 0.85
get_feedback_list_prefixFunction · 0.85
get_prompt3_codeFunction · 0.85
replace_base_classFunction · 0.85

Tested by

no test coverage detected