MCPcopy Create free account
hub / github.com/Speakn0w/RealChart2Code / execute_and_save_plot

Function execute_and_save_plot

RealChart2Code_eval/evaluate_task3.py:435–489  ·  view source on GitHub ↗
(code: str, task_info: Dict, results_dir: Path, timeout: int)

Source from the content-addressed store, hash-verified

433
434
435def execute_and_save_plot(code: str, task_info: Dict, results_dir: Path, timeout: int) -> Tuple[bool, str, Optional[Path]]:
436
437 if not code:
438 return False, "No code generated", None
439
440
441 task_dir = task_info['data_directory'].name
442 difficulty = task_info['difficulty']
443 is_multi = task_info['is_multi']
444
445 task_result_dir = results_dir / task_dir
446 task_result_dir.mkdir(exist_ok=True)
447
448
449 code_filename = f"generated_code_{difficulty}_mul.py" if is_multi else f"generated_code_{difficulty}.py"
450 code_file = task_result_dir / code_filename
451
452 with open(code_file, 'w', encoding='utf-8') as f:
453 f.write(code)
454
455 raw_response = task_info['raw_generation_response']
456 raw_response_filename = f"raw_response_{difficulty}_mul.txt" if is_multi else f"raw_response_{difficulty}.txt"
457 raw_response_file = task_result_dir / raw_response_filename
458 with open(raw_response_file, 'w', encoding='utf-8') as f:
459 f.write(raw_response)
460
461
462 processed_code = preprocess_code_paths(code, task_info['data_directory'])
463
464
465 plot_filename = f"generated_plot_{difficulty}_mul.png" if is_multi else f"generated_plot_{difficulty}.png"
466 plot_file = task_result_dir / plot_filename
467
468 if 'plt.savefig' not in processed_code and 'plt.show' not in processed_code:
469 processed_code += f"\nplt.tight_layout()\nplt.savefig(r'{plot_file}', dpi=300, bbox_inches='tight')\nplt.close()"
470 elif 'plt.show' in processed_code:
471 processed_code = processed_code.replace('plt.show()',
472 f"plt.tight_layout()\nplt.savefig(r'{plot_file}', dpi=300, bbox_inches='tight')\nplt.close()")
473 elif 'plt.savefig' in processed_code:
474 pattern = re.compile(r"plt\.savefig\s*\((.*?)\)")
475 replacement_string = f"plt.savefig(r'{plot_file}', dpi=300, bbox_inches='tight')\nplt.close()"
476 processed_code = pattern.sub(replacement_string, processed_code)
477
478
479 try:
480 execute_code_with_timeout(processed_code, task_info['data_directory'], timeout)
481
482
483 if plot_file.exists():
484 return True, "Code executed successfully", plot_file
485 else:
486 return False, "Code execution completed but no plot file was generated", None
487
488 except Exception as e:
489 return False, f"Code execution failed: {str(e)}", None
490
491def compress_image_if_needed(image_path: Path, max_size_bytes: int = 5 * 1024 * 1024) -> bytes:
492

Callers 1

Calls 2

preprocess_code_pathsFunction · 0.70

Tested by

no test coverage detected