Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions openevolve/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions openevolve/prompt/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
76 changes: 76 additions & 0 deletions tests/test_controller_utf8_programs.py
Original file line number Diff line number Diff line change
@@ -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()
Loading