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

Function execute_and_save_plot

RealChart2Code_eval/evaluate_task1.py:403–457  ·  view source on GitHub ↗
(code: str, task_info: Dict, results_dir: Path, timeout: int)

Source from the content-addressed store, hash-verified

401
402
403def execute_and_save_plot(code: str, task_info: Dict, results_dir: Path, timeout: int) -> Tuple[bool, str, Optional[Path]]:
404
405 if not code:
406 return False, "No code generated", None
407
408
409 task_dir = task_info['data_directory'].name
410 difficulty = task_info['difficulty']
411 is_multi = task_info['is_multi']
412
413 task_result_dir = results_dir / task_dir
414 task_result_dir.mkdir(exist_ok=True)
415
416
417 code_filename = f"generated_code_{difficulty}_mul.py" if is_multi else f"generated_code_{difficulty}.py"
418 code_file = task_result_dir / code_filename
419
420 with open(code_file, 'w', encoding='utf-8') as f:
421 f.write(code)
422
423 raw_response = task_info['raw_generation_response']
424 raw_response_filename = f"raw_response_{difficulty}_mul.txt" if is_multi else f"raw_response_{difficulty}.txt"
425 raw_response_file = task_result_dir / raw_response_filename
426 with open(raw_response_file, 'w', encoding='utf-8') as f:
427 f.write(raw_response)
428
429
430 processed_code = preprocess_code_paths(code, task_info['data_directory'])
431
432
433 plot_filename = f"generated_plot_{difficulty}_mul.png" if is_multi else f"generated_plot_{difficulty}.png"
434 plot_file = task_result_dir / plot_filename
435
436 if 'plt.savefig' not in processed_code and 'plt.show' not in processed_code:
437 processed_code += f"\nplt.tight_layout()\nplt.savefig(r'{plot_file}', dpi=300, bbox_inches='tight')\nplt.close()"
438 elif 'plt.show' in processed_code:
439 processed_code = processed_code.replace('plt.show()',
440 f"plt.tight_layout()\nplt.savefig(r'{plot_file}', dpi=300, bbox_inches='tight')\nplt.close()")
441 elif 'plt.savefig' in processed_code:
442 pattern = re.compile(r"plt\.savefig\s*\((.*?)\)")
443 replacement_string = f"plt.savefig(r'{plot_file}', dpi=300, bbox_inches='tight')\nplt.close()"
444 processed_code = pattern.sub(replacement_string, processed_code)
445
446
447 try:
448 execute_code_with_timeout(processed_code, task_info['data_directory'], timeout)
449
450
451 if plot_file.exists():
452 return True, "Code executed successfully", plot_file
453 else:
454 return False, "Code execution completed but no plot file was generated", None
455
456 except Exception as e:
457 return False, f"Code execution failed: {str(e)}", None
458
459def compress_image_if_needed(image_path: Path, max_size_bytes: int = 5 * 1024 * 1024) -> bytes:
460

Callers 1

Calls 2

preprocess_code_pathsFunction · 0.70

Tested by

no test coverage detected