diff --git a/openevolve/controller.py b/openevolve/controller.py index c80e9266a..03054f712 100644 --- a/openevolve/controller.py +++ b/openevolve/controller.py @@ -151,7 +151,7 @@ def __init__( f"Initial program for island {island_idx} '{seed_path}' has a different " f"extension than '{initial_program_path}'" ) - with open(seed_path, "r") as f: + with open(seed_path, "r", encoding="utf-8") as f: self.island_initial_program_codes[island_idx] = f.read() # Set the file_suffix in config (can be overridden in YAML) @@ -331,7 +331,7 @@ def _setup_manual_mode_queue(self) -> None: def _load_initial_program(self) -> str: """Load the initial program from file""" - with open(self.initial_program_path, "r") as f: + with open(self.initial_program_path, "r", encoding="utf-8") as f: return f.read() async def _add_initial_program( @@ -614,7 +614,7 @@ def _save_checkpoint(self, iteration: int) -> None: if best_program: # Save the best program at this checkpoint best_program_path = os.path.join(checkpoint_path, f"best_program{self.file_extension}") - with open(best_program_path, "w") as f: + with open(best_program_path, "w", encoding="utf-8") as f: f.write(best_program.code) # Save metrics @@ -706,7 +706,7 @@ def _save_best_program(self, program: Optional[Program] = None) -> None: filename = f"best_program{self.file_extension}" code_path = os.path.join(best_dir, filename) - with open(code_path, "w") as f: + with open(code_path, "w", encoding="utf-8") as f: f.write(program.code) # Save complete program info including metrics diff --git a/openevolve/prompt/templates.py b/openevolve/prompt/templates.py index deac051c2..de872f3b6 100644 --- a/openevolve/prompt/templates.py +++ b/openevolve/prompt/templates.py @@ -204,13 +204,13 @@ def _load_from_directory(self, directory: Path) -> None: # Load .txt templates for txt_file in directory.glob("*.txt"): template_name = txt_file.stem - with open(txt_file, "r") as f: + with open(txt_file, "r", encoding="utf-8") as f: self.templates[template_name] = f.read() # Load fragments.json if exists fragments_file = directory / "fragments.json" if fragments_file.exists(): - with open(fragments_file, "r") as f: + with open(fragments_file, "r", encoding="utf-8") as f: loaded_fragments = json.load(f) self.fragments.update(loaded_fragments) diff --git a/tests/test_controller_utf8_programs.py b/tests/test_controller_utf8_programs.py new file mode 100644 index 000000000..252d481a5 --- /dev/null +++ b/tests/test_controller_utf8_programs.py @@ -0,0 +1,76 @@ +"""Program source is UTF-8 on disk whatever the locale, as the evaluator writes it.""" + +import os +import subprocess +import sys +import unittest + +CHECK_CONTROLLER = r""" +import locale +import os +import sys +import tempfile + +if locale.getpreferredencoding(False).lower().replace('-', '') == 'utf8': + sys.exit(77) + +from openevolve.config import Config +from openevolve.controller import OpenEvolve +from openevolve.database import Program + +text = chr(0x4E2D) + chr(0x6587) + chr(0x1F9EA) +initial_code = '# ' + text + chr(10) + 'x = 1' + chr(10) +evolved_code = '# evolved ' + text + chr(10) + 'x = 2' + chr(10) + +with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as root: + paths = {name: os.path.join(root, name) for name in ('initial.py', 'seed.py', 'evaluator.py')} + for name in ('initial.py', 'seed.py'): + with open(paths[name], 'wb') as f: + f.write(initial_code.encode('utf-8')) + with open(paths['evaluator.py'], 'wb') as f: + f.write(b'def evaluate(program_path):' + bytes([10]) + b' return {}' + bytes([10])) + + config = Config() + config.database.island_initial_programs = [None, paths['seed.py']] + controller = OpenEvolve( + paths['initial.py'], paths['evaluator.py'], config, os.path.join(root, 'output') + ) + assert controller.initial_program_code == initial_code, ascii(controller.initial_program_code) + seed_code = controller.island_initial_program_codes[1] + assert seed_code == initial_code, ascii(seed_code) + + best = Program(id='best', code=evolved_code, metrics={'combined_score': 1.0}) + controller.database.add(best) + controller._save_best_program(best) + controller._save_checkpoint(1) + for folder in ('best', os.path.join('checkpoints', 'checkpoint_1')): + with open(os.path.join(controller.output_dir, folder, 'best_program.py'), 'rb') as f: + saved = f.read().decode('utf-8') + assert saved.replace(chr(13), '') == evolved_code, (folder, ascii(saved)) +""" + + +class TestControllerUtf8Programs(unittest.TestCase): + def test_programs_round_trip_under_non_utf8_locale(self): + env = dict( + os.environ, + LC_ALL="C", + PYTHONUTF8="0", + PYTHONCOERCECLOCALE="0", + OPENAI_API_KEY="test", + ) + result = subprocess.run( + [sys.executable, "-c", CHECK_CONTROLLER], + capture_output=True, + encoding="utf-8", + errors="replace", + timeout=120, + env=env, + ) + if result.returncode == 77: + self.skipTest("This platform retains a UTF-8 default locale") + self.assertEqual(result.returncode, 0, result.stderr) + + +if __name__ == "__main__": + unittest.main()