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

Function execute_and_save_plot

RealChart2Code_eval/evaluate_task2.py:395–449  ·  view source on GitHub ↗
(code: str, task_info: Dict, results_dir: Path, timeout: int)

Source from the content-addressed store, hash-verified

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

Callers 1

Calls 2

preprocess_code_pathsFunction · 0.70

Tested by

no test coverage detected