|
| 1 | +import logging |
| 2 | +import shutil |
| 3 | +from abc import ABC, abstractmethod |
| 4 | +from pathlib import Path |
| 5 | +from typing import ClassVar |
| 6 | + |
| 7 | +from utils import ( |
| 8 | + AlgoTuneData, |
| 9 | + extract_function_source, |
| 10 | + get_instruction, |
| 11 | + prepare_solver_code_from_task_file, |
| 12 | + replace_class_name_and_save, |
| 13 | +) |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +# Assumes a 'template' directory exists alongside this adapter.py file |
| 18 | +TEMPLATE_DIR = Path(__file__).parent / 'template' |
| 19 | + |
| 20 | + |
| 21 | +class BaseAdapter(ABC): |
| 22 | + """Abstract Base Class for adapters.""" |
| 23 | + |
| 24 | + NAME: ClassVar[str] |
| 25 | + |
| 26 | + def __init__(self, **kwargs): |
| 27 | + super().__init__() |
| 28 | + |
| 29 | + @abstractmethod |
| 30 | + def generate_task(self, **kwargs) -> None: |
| 31 | + raise NotImplementedError('Adapter must implement this method.') |
| 32 | + |
| 33 | + |
| 34 | +class AlgoTuneAdapter(BaseAdapter): |
| 35 | + NAME = 'ALGOTUNE' |
| 36 | + |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + task_dir: Path, |
| 40 | + cloned_repo_root: Path, |
| 41 | + template_dir: Path = TEMPLATE_DIR, |
| 42 | + **kwargs, |
| 43 | + ): |
| 44 | + super().__init__(**kwargs) |
| 45 | + self.task_dir = task_dir |
| 46 | + self.template_dir = template_dir |
| 47 | + |
| 48 | + # Encapsulate all data source interactions in a helper class |
| 49 | + self.algotune_data = AlgoTuneData(cloned_repo_root) |
| 50 | + |
| 51 | + logger.info( |
| 52 | + f'AlgoTuneAdapter initialized. Outputting tasks to: {self.task_dir.resolve()}' |
| 53 | + ) |
| 54 | + if not self.template_dir.exists(): |
| 55 | + raise FileNotFoundError( |
| 56 | + f'Template directory not found at {self.template_dir}' |
| 57 | + ) |
| 58 | + |
| 59 | + def _prepare_task_from_template( |
| 60 | + self, output_dir: Path, task_name: str, task_py_path: Path |
| 61 | + ): |
| 62 | + """Copies the template and populates all placeholder files.""" |
| 63 | + # 1. Copy the entire template directory |
| 64 | + if output_dir.exists(): |
| 65 | + shutil.rmtree(output_dir) |
| 66 | + shutil.copytree(self.template_dir, output_dir) |
| 67 | + |
| 68 | + # 2. Extract all necessary content |
| 69 | + description_content = ( |
| 70 | + (task_py_path.parent / 'description.txt').read_text().strip() |
| 71 | + ) |
| 72 | + ref_solver_content = extract_function_source(task_py_path, 'solve') |
| 73 | + is_solution_content = extract_function_source(task_py_path, 'is_solution') |
| 74 | + |
| 75 | + # Get the path to the best solver (can be a file or a directory) |
| 76 | + best_solver_path = self.algotune_data.get_reference_solver(task_name) |
| 77 | + |
| 78 | + if not all([description_content, ref_solver_content, is_solution_content]): |
| 79 | + logger.error( |
| 80 | + f"Failed to extract necessary source code/text for '{task_name}'. Skipping." |
| 81 | + ) |
| 82 | + return False |
| 83 | + |
| 84 | + # 3. Populate task.yaml |
| 85 | + instruction = get_instruction( |
| 86 | + description_content, ref_solver_content, is_solution_content |
| 87 | + ) |
| 88 | + |
| 89 | + problem_path = output_dir / 'problem_statement.txt' |
| 90 | + problem_path.write_text(instruction) |
| 91 | + |
| 92 | + # 4. Dynamically generate shell command content for the solver |
| 93 | + sh_commands = '' |
| 94 | + if best_solver_path: |
| 95 | + if best_solver_path.is_dir(): |
| 96 | + # Case 1: Best solver is a directory with multiple files. |
| 97 | + files_to_copy = [f for f in best_solver_path.iterdir() if f.is_file()] |
| 98 | + if files_to_copy: |
| 99 | + command_parts = [ |
| 100 | + f"cat > /workspace/{item.name} << 'EOF'\n{item.read_text(encoding='utf-8')}\nEOF" |
| 101 | + for item in sorted(files_to_copy) |
| 102 | + ] |
| 103 | + if len(command_parts) > 1: |
| 104 | + command_parts.append('/usr/local/bin/pip install .') |
| 105 | + sh_commands = '\n\n'.join(command_parts) |
| 106 | + elif best_solver_path.is_file(): |
| 107 | + # Case 2: Best solver is a single file. |
| 108 | + content = best_solver_path.read_text(encoding='utf-8') |
| 109 | + sh_commands = ( |
| 110 | + f"cat > /workspace/{best_solver_path.name} << 'EOF'\n{content}\nEOF" |
| 111 | + ) |
| 112 | + |
| 113 | + # Case 3: Fallback if no solver path was found or the directory was empty. |
| 114 | + if not sh_commands: |
| 115 | + logger.warning( |
| 116 | + f"No valid solver found for '{task_name}'. Using reference implementation as fallback." |
| 117 | + ) |
| 118 | + fallback_code = prepare_solver_code_from_task_file(task_py_path) |
| 119 | + if not fallback_code: |
| 120 | + logger.error( |
| 121 | + f"Failed to generate fallback solver for '{task_name}'. Skipping." |
| 122 | + ) |
| 123 | + return False |
| 124 | + sh_commands = f"cat > /workspace/solver.py << 'EOF'\n{fallback_code}\nEOF" |
| 125 | + |
| 126 | + # 5. Populate solution.sh |
| 127 | + solution_sh_path = output_dir / 'solution.sh' |
| 128 | + solution_script_content = f"""#!/bin/bash |
| 129 | +
|
| 130 | +{sh_commands} |
| 131 | +""" |
| 132 | + solution_sh_path.write_text(solution_script_content) |
| 133 | + |
| 134 | + # 6. Create tests/evaluator.py |
| 135 | + evaluator_dest_path = output_dir / 'evaluator.py' |
| 136 | + replace_class_name_and_save(task_py_path, evaluator_dest_path, new_name='Task') |
| 137 | + |
| 138 | + # 7. Get task difficulty |
| 139 | + n_value = self.algotune_data.get_task_difficulty(task_name) |
| 140 | + |
| 141 | + # 8. Update tests/test_outputs.py |
| 142 | + test_outputs_path = output_dir / 'test_outputs.py' |
| 143 | + test_content = test_outputs_path.read_text() |
| 144 | + test_content = test_content.replace( |
| 145 | + 'PROBLEM_SIZE = 100', f'PROBLEM_SIZE = {n_value}' |
| 146 | + ) |
| 147 | + test_outputs_path.write_text(test_content) |
| 148 | + |
| 149 | + # 9. Update run-tests.sh |
| 150 | + run_test_path = output_dir / 'run-tests.sh' |
| 151 | + run_test_content = run_test_path.read_text() |
| 152 | + run_test_content = run_test_content.replace( |
| 153 | + '{test_output_content}', test_content |
| 154 | + ) |
| 155 | + run_test_content = run_test_content.replace( |
| 156 | + '{solution_code_command}', sh_commands |
| 157 | + ) |
| 158 | + run_test_path.write_text(run_test_content) |
| 159 | + |
| 160 | + return True |
| 161 | + |
| 162 | + def generate_task(self, task_name: str, task_py_path: Path) -> None: |
| 163 | + if not task_py_path.is_file() or task_py_path.suffix != '.py': |
| 164 | + logger.warning(f'Skipping non-Python file: {task_py_path}') |
| 165 | + return |
| 166 | + |
| 167 | + t_bench_task_id = f'algotune-{task_name.lower()}'.replace('_', '-') |
| 168 | + logger.info(f'--- Generating task: {t_bench_task_id} ---') |
| 169 | + |
| 170 | + output_dir = self.task_dir / t_bench_task_id |
| 171 | + |
| 172 | + success = self._prepare_task_from_template(output_dir, task_name, task_py_path) |
| 173 | + if success: |
| 174 | + logger.info(f'Successfully generated task at {output_dir}') |
| 175 | + else: |
| 176 | + # Clean up partially generated directory on failure |
| 177 | + if output_dir.exists(): |
| 178 | + shutil.rmtree(output_dir) |
0 commit comments