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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {
|
| 6 |
+
"id": "sQUrZsAglHQz"
|
| 7 |
+
},
|
| 8 |
+
"source": [
|
| 9 |
+
"# Import Module"
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "code",
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"metadata": {
|
| 16 |
+
"id": "ES1ES_GVlEha"
|
| 17 |
+
},
|
| 18 |
+
"outputs": [],
|
| 19 |
+
"source": [
|
| 20 |
+
"import os\n",
|
| 21 |
+
"import re\n",
|
| 22 |
+
"import shutil\n",
|
| 23 |
+
"import subprocess\n",
|
| 24 |
+
"import tempfile\n",
|
| 25 |
+
"import time\n",
|
| 26 |
+
"from pathlib import Path\n",
|
| 27 |
+
"from typing import List, Tuple\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"import pandas as pd\n",
|
| 30 |
+
"import torch\n",
|
| 31 |
+
"from tqdm import tqdm\n",
|
| 32 |
+
"from transformers import (\n",
|
| 33 |
+
" AutoTokenizer,\n",
|
| 34 |
+
" AutoModelForSeq2SeqLM,\n",
|
| 35 |
+
" AutoModelForCausalLM,\n",
|
| 36 |
+
" set_seed,\n",
|
| 37 |
+
" StoppingCriteria,\n",
|
| 38 |
+
" StoppingCriteriaList,\n",
|
| 39 |
+
")"
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "markdown",
|
| 44 |
+
"metadata": {
|
| 45 |
+
"id": "6husnAQMlMgS"
|
| 46 |
+
},
|
| 47 |
+
"source": [
|
| 48 |
+
"# Configuration"
|
| 49 |
+
]
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"metadata": {
|
| 55 |
+
"id": "4lvmEKJMlMM1"
|
| 56 |
+
},
|
| 57 |
+
"outputs": [],
|
| 58 |
+
"source": [
|
| 59 |
+
"from google.colab import drive\n",
|
| 60 |
+
"drive.mount('/content/drive')\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"DETAIL_PATH = \"/content/drive/MyDrive/DETAIL_PLBART.xlsx\"\n",
|
| 63 |
+
"STATS_PATH = \"/content/drive/MyDrive/Statistik_PLBART.xlsx\"\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"JUNIT_JAR = \"/content/junit-4.12.jar\"\n",
|
| 66 |
+
"HAMCREST_JAR = \"/content/hamcrest-core-1.3.jar\"\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"DATASET_PATH = \"/content/decoded_databaru.xlsx\"\n",
|
| 70 |
+
"MODEL_PATH = \"/content/drive/MyDrive/plbart-base-finetuned-apr-10k-final\"\n",
|
| 71 |
+
"# MODEL_SIZE = \"base\"\n",
|
| 72 |
+
"DEVICE = \"cuda\"\n",
|
| 73 |
+
"NUM_PATCHES = 10\n",
|
| 74 |
+
"TIMEOUT = 30\n",
|
| 75 |
+
"KEEP_TMP = False\n",
|
| 76 |
+
"OUTPUT_DIR = \"apr_results\"\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"os.makedirs(OUTPUT_DIR, exist_ok=True)\n",
|
| 79 |
+
"set_seed(42)"
|
| 80 |
+
]
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "markdown",
|
| 84 |
+
"metadata": {
|
| 85 |
+
"id": "Ev4mOgMSlYy_"
|
| 86 |
+
},
|
| 87 |
+
"source": [
|
| 88 |
+
"# Preprocessing"
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"cell_type": "code",
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"metadata": {
|
| 95 |
+
"id": "nXXKSeF8lcS-"
|
| 96 |
+
},
|
| 97 |
+
"outputs": [],
|
| 98 |
+
"source": [
|
| 99 |
+
"class StopOnTokens(StoppingCriteria):\n",
|
| 100 |
+
" def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n",
|
| 101 |
+
" return False\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"def extract_public_class_name(java_text: str) -> str:\n",
|
| 105 |
+
" m = re.search(r\"public\\s+class\\s+([A-Za-z_]\\w*)\", java_text)\n",
|
| 106 |
+
" if m:\n",
|
| 107 |
+
" return m.group(1)\n",
|
| 108 |
+
" m2 = re.search(r\"class\\s+([A-Za-z_]\\w*)\", java_text)\n",
|
| 109 |
+
" if m2:\n",
|
| 110 |
+
" return m2.group(1)\n",
|
| 111 |
+
" return \"PatchedClass\"\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"def get_package_dir(java_text: str, base_dir: str) -> Tuple[str, str]:\n",
|
| 115 |
+
" m = re.search(r\"package\\s+([a-zA-Z0-9_.]+)\\s*;\", java_text)\n",
|
| 116 |
+
" if m:\n",
|
| 117 |
+
" pkg = m.group(1)\n",
|
| 118 |
+
" pkg_dir = os.path.join(base_dir, *pkg.split(\".\"))\n",
|
| 119 |
+
" return pkg, pkg_dir\n",
|
| 120 |
+
" return None, base_dir"
|
| 121 |
+
]
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "markdown",
|
| 125 |
+
"metadata": {
|
| 126 |
+
"id": "h6uM0l6_ltnM"
|
| 127 |
+
},
|
| 128 |
+
"source": [
|
| 129 |
+
"# Fungsi Java"
|
| 130 |
+
]
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"metadata": {
|
| 136 |
+
"id": "TWwKlRkXluuG"
|
| 137 |
+
},
|
| 138 |
+
"outputs": [],
|
| 139 |
+
"source": [
|
| 140 |
+
"def save_java_file(java_text: str, base_tmp_dir: str) -> Tuple[str, str]:\n",
|
| 141 |
+
" class_name = extract_public_class_name(java_text)\n",
|
| 142 |
+
" pkg, pkg_dir = get_package_dir(java_text, base_tmp_dir)\n",
|
| 143 |
+
" os.makedirs(pkg_dir, exist_ok=True)\n",
|
| 144 |
+
" file_path = os.path.join(pkg_dir, f\"{class_name}.java\")\n",
|
| 145 |
+
" with open(file_path, \"w\", encoding=\"utf-8\") as f:\n",
|
| 146 |
+
" f.write(java_text)\n",
|
| 147 |
+
" if pkg:\n",
|
| 148 |
+
" full_classname = f\"{pkg}.{class_name}\"\n",
|
| 149 |
+
" else:\n",
|
| 150 |
+
" full_classname = class_name\n",
|
| 151 |
+
" return file_path, full_classname\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"def compile_all_java_files(tmp_dir: str, timeout: int = 30) -> Tuple[bool, str]:\n",
|
| 155 |
+
" java_files = []\n",
|
| 156 |
+
" for root, _, files in os.walk(tmp_dir):\n",
|
| 157 |
+
" for fn in files:\n",
|
| 158 |
+
" if fn.endswith(\".java\"):\n",
|
| 159 |
+
" java_files.append(os.path.join(root, fn))\n",
|
| 160 |
+
" if not java_files:\n",
|
| 161 |
+
" return False, \"NO_JAVA_FILES\"\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" classpath = f\".:{JUNIT_JAR}:{HAMCREST_JAR}\"\n",
|
| 164 |
+
" cmd = [\"javac\", \"-cp\", classpath, \"-d\", tmp_dir] + java_files\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" try:\n",
|
| 167 |
+
" proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, check=True)\n",
|
| 168 |
+
" return True, \"\"\n",
|
| 169 |
+
" except subprocess.CalledProcessError as e:\n",
|
| 170 |
+
" stderr = e.stderr.decode(\"utf-8\", errors=\"ignore\")\n",
|
| 171 |
+
" return False, f\"COMPILE_ERROR: {stderr}\"\n",
|
| 172 |
+
" except subprocess.TimeoutExpired:\n",
|
| 173 |
+
" return False, \"COMPILE_TIMEOUT\"\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"def run_test_main(tmp_dir: str, main_class: str, timeout: int = 30) -> Tuple[bool, str]:\n",
|
| 177 |
+
" classpath = f\"{tmp_dir}:{JUNIT_JAR}:{HAMCREST_JAR}\"\n",
|
| 178 |
+
" cmd = [\"java\", \"-cp\", classpath, main_class]\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" try:\n",
|
| 181 |
+
" proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout, check=True)\n",
|
| 182 |
+
" stdout = proc.stdout.decode(\"utf-8\", errors=\"ignore\").strip()\n",
|
| 183 |
+
" if \"PASS\" in stdout:\n",
|
| 184 |
+
" return True, \"PASS\"\n",
|
| 185 |
+
" else:\n",
|
| 186 |
+
" return False, f\"TEST_FAIL: {stdout or proc.stderr.decode('utf-8', errors='ignore')}\"\n",
|
| 187 |
+
" except subprocess.CalledProcessError as e:\n",
|
| 188 |
+
" stdout = e.stdout.decode(\"utf-8\", errors=\"ignore\")\n",
|
| 189 |
+
" stderr = e.stderr.decode(\"utf-8\", errors=\"ignore\")\n",
|
| 190 |
+
" return False, f\"RUNTIME_ERROR: stdout[{stdout}] stderr[{stderr}]\"\n",
|
| 191 |
+
" except subprocess.TimeoutExpired:\n",
|
| 192 |
+
" return False, \"RUN_TIMEOUT\""
|
| 193 |
+
]
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"metadata": {
|
| 199 |
+
"id": "I7Si63_cl699"
|
| 200 |
+
},
|
| 201 |
+
"outputs": [],
|
| 202 |
+
"source": [
|
| 203 |
+
"class APRWithCLM:\n",
|
| 204 |
+
" def __init__(self, device=\"cpu\"):\n",
|
| 205 |
+
" self.device = device if torch.cuda.is_available() and device == \"cuda\" else \"cpu\"\n",
|
| 206 |
+
" set_seed(42)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" self.model_id = MODEL_PATH\n",
|
| 209 |
+
" self.tokenizer = AutoTokenizer.from_pretrained(self.model_id, use_fast=True)\n",
|
| 210 |
+
" self.model = AutoModelForSeq2SeqLM.from_pretrained(\n",
|
| 211 |
+
" self.model_id,\n",
|
| 212 |
+
" device_map=\"auto\" if self.device == \"cuda\" else None,\n",
|
| 213 |
+
" torch_dtype=torch.float16 if self.device == \"cuda\" else None,\n",
|
| 214 |
+
" )\n",
|
| 215 |
+
" self.is_encoder_decoder = True\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" self.model.eval()\n",
|
| 218 |
+
" self.stop = StopOnTokens()\n",
|
| 219 |
+
" self.eos_token_id = getattr(self.tokenizer, \"eos_token_id\", None)\n",
|
| 220 |
+
" self.pad_token_id = getattr(self.tokenizer, \"pad_token_id\", self.eos_token_id)\n",
|
| 221 |
+
" self.bos_token_id = getattr(self.tokenizer, \"bos_token_id\", None)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
" def create_prompt(self, buggy_code: str, buggy_lines: str = None) -> str:\n",
|
| 224 |
+
" if buggy_lines:\n",
|
| 225 |
+
" return f\"Repair this Java code. The buggy lines are: {buggy_lines}\\n{buggy_code}\\nFixed version:\"\n",
|
| 226 |
+
" return f\"Repair this Java code:\\n{buggy_code}\\nFixed version:\"\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" def _clean_generated(self, text: str, prompt: str) -> str:\n",
|
| 229 |
+
" if prompt and prompt in text:\n",
|
| 230 |
+
" text = text.split(prompt, 1)[-1]\n",
|
| 231 |
+
" text = text.strip()\n",
|
| 232 |
+
" text = re.sub(r\"^.*?(public\\s+class\\s+)\", r\"\\1\", text, flags=re.S)\n",
|
| 233 |
+
" idx = text.find(\"public class\")\n",
|
| 234 |
+
" if idx != -1:\n",
|
| 235 |
+
" text = text[idx:]\n",
|
| 236 |
+
" m = re.search(r\"(public\\s+class\\s+\\w+\\s*\\{)\", text)\n",
|
| 237 |
+
" if m:\n",
|
| 238 |
+
" start = m.start()\n",
|
| 239 |
+
" brace_count = 0\n",
|
| 240 |
+
" for i in range(start, len(text)):\n",
|
| 241 |
+
" if text[i] == \"{\":\n",
|
| 242 |
+
" brace_count += 1\n",
|
| 243 |
+
" elif text[i] == \"}\":\n",
|
| 244 |
+
" brace_count -= 1\n",
|
| 245 |
+
" if brace_count == 0:\n",
|
| 246 |
+
" text = text[: i + 1]\n",
|
| 247 |
+
" break\n",
|
| 248 |
+
" return text.strip()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" def generate_single_patch(self, prompt: str, buggy_lines: str = None, max_length: int = 1024) -> str:\n",
|
| 251 |
+
" inputs = self.tokenizer(prompt, return_tensors=\"pt\", truncation=True, max_length=1024)\n",
|
| 252 |
+
" input_ids = inputs[\"input_ids\"].to(self.model.device)\n",
|
| 253 |
+
" attention_mask = inputs.get(\"attention_mask\")\n",
|
| 254 |
+
" if attention_mask is not None:\n",
|
| 255 |
+
" attention_mask = attention_mask.to(self.model.device)\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" generation_kwargs = {\n",
|
| 258 |
+
" \"max_length\": max_length,\n",
|
| 259 |
+
" \"do_sample\": True,\n",
|
| 260 |
+
" \"top_k\": 50,\n",
|
| 261 |
+
" \"top_p\": 0.95,\n",
|
| 262 |
+
" \"temperature\": 0.7,\n",
|
| 263 |
+
" \"eos_token_id\": self.eos_token_id,\n",
|
| 264 |
+
" \"pad_token_id\": self.pad_token_id,\n",
|
| 265 |
+
" }\n",
|
| 266 |
+
" if self.is_encoder_decoder:\n",
|
| 267 |
+
" decoder_start_id = None\n",
|
| 268 |
+
" try:\n",
|
| 269 |
+
" decoder_start_id = self.tokenizer.lang_code_to_id.get(\"java\")\n",
|
| 270 |
+
" except Exception:\n",
|
| 271 |
+
" decoder_start_id = None\n",
|
| 272 |
+
" if decoder_start_id is None:\n",
|
| 273 |
+
" decoder_start_id = self.bos_token_id or self.eos_token_id or 0\n",
|
| 274 |
+
" generation_kwargs.update({\"decoder_start_token_id\": decoder_start_id})\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" with torch.no_grad():\n",
|
| 277 |
+
" try:\n",
|
| 278 |
+
" outputs = self.model.generate(\n",
|
| 279 |
+
" input_ids=input_ids,\n",
|
| 280 |
+
" attention_mask=attention_mask,\n",
|
| 281 |
+
" num_return_sequences=1,\n",
|
| 282 |
+
" **generation_kwargs,\n",
|
| 283 |
+
" )\n",
|
| 284 |
+
" except Exception as e:\n",
|
| 285 |
+
" print(\"Generation failed, retrying greedy. Error:\", e)\n",
|
| 286 |
+
" outputs = self.model.generate(input_ids=input_ids, max_length=512, num_return_sequences=1)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" raw = self.tokenizer.decode(outputs[0], skip_special_tokens=False)\n",
|
| 289 |
+
" cleaned = self._clean_generated(raw, prompt)\n",
|
| 290 |
+
" return cleaned\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" def generate_patches_with_progress(self, buggy_code: str, num_patches: int = 5, buggy_lines: str = None) -> List[str]:\n",
|
| 293 |
+
" prompt = self.create_prompt(buggy_code, buggy_lines)\n",
|
| 294 |
+
" patches = []\n",
|
| 295 |
+
"\n",
|
| 296 |
+
" for _ in tqdm(range(num_patches), desc=\" Generating\", leave=False, unit=\"patch\"):\n",
|
| 297 |
+
" p = self.generate_single_patch(prompt, buggy_lines)\n",
|
| 298 |
+
" if p and \"class \" in p and \"{\" in p and \"}\" in p:\n",
|
| 299 |
+
" patches.append(p)\n",
|
| 300 |
+
" else:\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" patches.append(p)\n",
|
| 303 |
+
" return patches[:num_patches]"
|
| 304 |
+
]
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "markdown",
|
| 308 |
+
"metadata": {
|
| 309 |
+
"id": "69Fgzporl9uR"
|
| 310 |
+
},
|
| 311 |
+
"source": [
|
| 312 |
+
"# Fungsi Simpan Hasil"
|
| 313 |
+
]
|
| 314 |
+
},
|
| 315 |
+
{
|
| 316 |
+
"cell_type": "code",
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"metadata": {
|
| 319 |
+
"id": "ayWKeU46l_SH"
|
| 320 |
+
},
|
| 321 |
+
"outputs": [],
|
| 322 |
+
"source": [
|
| 323 |
+
"def save_results_and_stats(results: List[dict], dataset_path: str):\n",
|
| 324 |
+
"\n",
|
| 325 |
+
" try:\n",
|
| 326 |
+
" existing_results = pd.read_excel(DETAIL_PATH)\n",
|
| 327 |
+
" results_df = pd.concat([existing_results, pd.DataFrame(results)], ignore_index=True)\n",
|
| 328 |
+
" results_df = results_df.drop_duplicates(subset=[\"task_id\", \"patch_idx\"], keep=\"last\")\n",
|
| 329 |
+
" except:\n",
|
| 330 |
+
" df_original = pd.read_excel(dataset_path)\n",
|
| 331 |
+
" results_df = pd.DataFrame(results)\n",
|
| 332 |
+
" results_df = results_df.merge(\n",
|
| 333 |
+
" df_original[[\"title\", \"bug\", \"correct\"]].rename(columns={\"title\": \"task_id\"}),\n",
|
| 334 |
+
" on=\"task_id\", how=\"left\"\n",
|
| 335 |
+
" )\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" cols_order = [\"task_id\", \"patch_idx\", \"bug\", \"correct\", \"compiled\", \"passed\", \"validation_status\", \"message\", \"patch\"]\n",
|
| 339 |
+
" results_df = results_df[cols_order]\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"\n",
|
| 342 |
+
" results_df.to_excel(DETAIL_PATH, index=False)\n",
|
| 343 |
+
" print(f\"Saved DETAIL_HASILNYA.xlsx to {DETAIL_PATH}\")\n",
|
| 344 |
+
"\n",
|
| 345 |
+
" # ringkasan statistik\n",
|
| 346 |
+
" task_stats = {}\n",
|
| 347 |
+
" for _, row in results_df.iterrows():\n",
|
| 348 |
+
" task = row[\"task_id\"]\n",
|
| 349 |
+
" if task not in task_stats:\n",
|
| 350 |
+
" task_stats[task] = {\n",
|
| 351 |
+
" \"total_candidates\": 0,\n",
|
| 352 |
+
" \"compilable\": 0,\n",
|
| 353 |
+
" \"passed_test\": 0,\n",
|
| 354 |
+
" \"valid\": 0,\n",
|
| 355 |
+
" \"in_plausible\": 0,\n",
|
| 356 |
+
" \"fail\": 0\n",
|
| 357 |
+
" }\n",
|
| 358 |
+
" task_stats[task][\"total_candidates\"] += 1\n",
|
| 359 |
+
"\n",
|
| 360 |
+
" if row[\"compiled\"]:\n",
|
| 361 |
+
" task_stats[task][\"compilable\"] += 1\n",
|
| 362 |
+
" if row[\"passed\"]:\n",
|
| 363 |
+
" task_stats[task][\"passed_test\"] += 1\n",
|
| 364 |
+
" task_stats[task][\"valid\"] += 1\n",
|
| 365 |
+
" else:\n",
|
| 366 |
+
" task_stats[task][\"in_plausible\"] += 1\n",
|
| 367 |
+
" else:\n",
|
| 368 |
+
" task_stats[task][\"fail\"] += 1\n",
|
| 369 |
+
"\n",
|
| 370 |
+
" stats_df = pd.DataFrame.from_dict(task_stats, orient=\"index\")\n",
|
| 371 |
+
" stats_df[\"compilable_rate\"] = stats_df[\"compilable\"] / stats_df[\"total_candidates\"]\n",
|
| 372 |
+
" stats_df[\"pass_rate\"] = stats_df[\"passed_test\"] / stats_df[\"total_candidates\"]\n",
|
| 373 |
+
"\n",
|
| 374 |
+
" stats_df.to_excel(STATS_PATH)\n",
|
| 375 |
+
" print(f\"Saved BERAPA_YANG_BENAR.xlsx to {STATS_PATH}\")\n",
|
| 376 |
+
"\n",
|
| 377 |
+
" print(f\"\\nTotal tasks: {len(task_stats)}\")\n",
|
| 378 |
+
" print(f\"Total compilable candidates: {stats_df['compilable'].sum()}\")\n",
|
| 379 |
+
" print(f\"Total passed tests: {stats_df['passed_test'].sum()}\")\n",
|
| 380 |
+
" total_correct_fixes = sum(1 for task in task_stats.values() if task[\"passed_test\"] > 0)\n",
|
| 381 |
+
" print(\"*\" * 80)\n",
|
| 382 |
+
" print(f\"Total tasks with at least 1 passed test: {total_correct_fixes}\")\n",
|
| 383 |
+
"\n"
|
| 384 |
+
]
|
| 385 |
+
},
|
| 386 |
+
{
|
| 387 |
+
"cell_type": "markdown",
|
| 388 |
+
"metadata": {
|
| 389 |
+
"id": "sRX5Ln44mICR"
|
| 390 |
+
},
|
| 391 |
+
"source": [
|
| 392 |
+
"# Training"
|
| 393 |
+
]
|
| 394 |
+
},
|
| 395 |
+
{
|
| 396 |
+
"cell_type": "code",
|
| 397 |
+
"execution_count": null,
|
| 398 |
+
"metadata": {
|
| 399 |
+
"id": "XAal48chmH0t"
|
| 400 |
+
},
|
| 401 |
+
"outputs": [],
|
| 402 |
+
"source": [
|
| 403 |
+
"def run_dataset_and_eval(dataset_path: str,\n",
|
| 404 |
+
" apr: APRWithCLM,\n",
|
| 405 |
+
" num_patches: int = 5,\n",
|
| 406 |
+
" timeout: int = 30,\n",
|
| 407 |
+
" output_dir: str = OUTPUT_DIR,\n",
|
| 408 |
+
" keep_tmp: bool = False) -> pd.DataFrame:\n",
|
| 409 |
+
" df = pd.read_excel(dataset_path)\n",
|
| 410 |
+
" required_cols = {\"bug\", \"correct\", \"test\", \"title\"}\n",
|
| 411 |
+
" if not required_cols.issubset(set(df.columns)):\n",
|
| 412 |
+
" raise ValueError(f\"Excel harus punya kolom: {required_cols}\")\n",
|
| 413 |
+
"\n",
|
| 414 |
+
"\n",
|
| 415 |
+
" try:\n",
|
| 416 |
+
" existing_results = pd.read_excel(DETAIL_PATH)\n",
|
| 417 |
+
" completed_tasks = existing_results[\"task_id\"].unique()\n",
|
| 418 |
+
" except:\n",
|
| 419 |
+
" existing_results = None\n",
|
| 420 |
+
" completed_tasks = []\n",
|
| 421 |
+
"\n",
|
| 422 |
+
" results = []\n",
|
| 423 |
+
" start_ts = int(time.time())\n",
|
| 424 |
+
"\n",
|
| 425 |
+
" for idx, row in tqdm(df.iterrows(), total=len(df), desc=\"Tasks\", unit=\"task\"):\n",
|
| 426 |
+
" task_id = row[\"title\"]\n",
|
| 427 |
+
"\n",
|
| 428 |
+
" if task_id in completed_tasks:\n",
|
| 429 |
+
" print(f\"\\nSkipping already completed task: {task_id}\")\n",
|
| 430 |
+
" continue\n",
|
| 431 |
+
"\n",
|
| 432 |
+
" buggy_code = row[\"bug\"]\n",
|
| 433 |
+
" correct_code = row.get(\"correct\", \"\")\n",
|
| 434 |
+
" test_code = row[\"test\"]\n",
|
| 435 |
+
" tmp_dir = tempfile.mkdtemp(prefix=f\"apr_{task_id}_\")\n",
|
| 436 |
+
"\n",
|
| 437 |
+
" try:\n",
|
| 438 |
+
" pkg, pkg_dir = get_package_dir(buggy_code, tmp_dir)\n",
|
| 439 |
+
" os.makedirs(pkg_dir, exist_ok=True)\n",
|
| 440 |
+
" buggy_class_name = extract_public_class_name(buggy_code)\n",
|
| 441 |
+
" with open(os.path.join(pkg_dir, f\"{buggy_class_name}.java\"), \"w\", encoding=\"utf-8\") as f:\n",
|
| 442 |
+
" f.write(buggy_code)\n",
|
| 443 |
+
" except Exception:\n",
|
| 444 |
+
" pass\n",
|
| 445 |
+
"\n",
|
| 446 |
+
" patches = apr.generate_patches_with_progress(buggy_code, num_patches=num_patches)\n",
|
| 447 |
+
"\n",
|
| 448 |
+
" for p_idx, patch in enumerate(tqdm(patches, desc=\" Patches\", leave=False, unit=\"p\")):\n",
|
| 449 |
+
" if not patch or not patch.strip():\n",
|
| 450 |
+
" results.append({\n",
|
| 451 |
+
" \"task_id\": task_id,\n",
|
| 452 |
+
" \"patch_idx\": p_idx + 1,\n",
|
| 453 |
+
" \"compiled\": False,\n",
|
| 454 |
+
" \"passed\": False,\n",
|
| 455 |
+
" \"validation_status\": \"fail\",\n",
|
| 456 |
+
" \"message\": \"EMPTY_PATCH\",\n",
|
| 457 |
+
" \"patch\": \"\",\n",
|
| 458 |
+
" })\n",
|
| 459 |
+
" continue\n",
|
| 460 |
+
"\n",
|
| 461 |
+
" try:\n",
|
| 462 |
+
" patched_file, full_classname = save_java_file(patch, tmp_dir)\n",
|
| 463 |
+
" except Exception as e:\n",
|
| 464 |
+
" results.append({\n",
|
| 465 |
+
" \"task_id\": task_id,\n",
|
| 466 |
+
" \"patch_idx\": p_idx + 1,\n",
|
| 467 |
+
" \"compiled\": False,\n",
|
| 468 |
+
" \"passed\": False,\n",
|
| 469 |
+
" \"validation_status\": \"fail\",\n",
|
| 470 |
+
" \"message\": f\"SAVE_ERROR: {e}\",\n",
|
| 471 |
+
" \"patch\": patch[:500],\n",
|
| 472 |
+
" })\n",
|
| 473 |
+
" continue\n",
|
| 474 |
+
"\n",
|
| 475 |
+
" main_class, main_source = convert_junit_to_main(test_code, extract_public_class_name(patch))\n",
|
| 476 |
+
" main_path = os.path.join(tmp_dir, f\"{main_class}.java\")\n",
|
| 477 |
+
" with open(main_path, \"w\", encoding=\"utf-8\") as f:\n",
|
| 478 |
+
" f.write(main_source)\n",
|
| 479 |
+
"\n",
|
| 480 |
+
" compiled, compile_msg = compile_all_java_files(tmp_dir, timeout=timeout)\n",
|
| 481 |
+
" if not compiled:\n",
|
| 482 |
+
" results.append({\n",
|
| 483 |
+
" \"task_id\": task_id,\n",
|
| 484 |
+
" \"patch_idx\": p_idx + 1,\n",
|
| 485 |
+
" \"compiled\": False,\n",
|
| 486 |
+
" \"passed\": False,\n",
|
| 487 |
+
" \"validation_status\": \"fail\",\n",
|
| 488 |
+
" \"message\": compile_msg,\n",
|
| 489 |
+
" \"patch\": patch[:500],\n",
|
| 490 |
+
" })\n",
|
| 491 |
+
" continue\n",
|
| 492 |
+
"\n",
|
| 493 |
+
" passed, run_msg = run_test_main(tmp_dir, main_class, timeout=timeout)\n",
|
| 494 |
+
"\n",
|
| 495 |
+
" # Tentukan validation status\n",
|
| 496 |
+
" if not compiled:\n",
|
| 497 |
+
" val_status = \"fail\"\n",
|
| 498 |
+
" elif passed:\n",
|
| 499 |
+
" val_status = \"valid\"\n",
|
| 500 |
+
" else:\n",
|
| 501 |
+
" val_status = \"in-plausible\"\n",
|
| 502 |
+
"\n",
|
| 503 |
+
" results.append({\n",
|
| 504 |
+
" \"task_id\": task_id,\n",
|
| 505 |
+
" \"patch_idx\": p_idx + 1,\n",
|
| 506 |
+
" \"compiled\": True,\n",
|
| 507 |
+
" \"passed\": passed,\n",
|
| 508 |
+
" \"validation_status\": val_status,\n",
|
| 509 |
+
" \"message\": run_msg,\n",
|
| 510 |
+
" \"patch\": patch[:10000],\n",
|
| 511 |
+
" })\n",
|
| 512 |
+
"\n",
|
| 513 |
+
" save_results_and_stats(results, dataset_path)\n",
|
| 514 |
+
" results = []\n",
|
| 515 |
+
"\n",
|
| 516 |
+
" if not keep_tmp:\n",
|
| 517 |
+
" try:\n",
|
| 518 |
+
" shutil.rmtree(tmp_dir)\n",
|
| 519 |
+
" except Exception:\n",
|
| 520 |
+
" pass\n",
|
| 521 |
+
" else:\n",
|
| 522 |
+
" try:\n",
|
| 523 |
+
" dst = os.path.join(output_dir, f\"tmp_{task_id}_{start_ts}\")\n",
|
| 524 |
+
" if os.path.exists(dst):\n",
|
| 525 |
+
" shutil.rmtree(dst)\n",
|
| 526 |
+
" shutil.move(tmp_dir, dst)\n",
|
| 527 |
+
" except Exception:\n",
|
| 528 |
+
" pass\n",
|
| 529 |
+
"\n",
|
| 530 |
+
" return pd.DataFrame(results)"
|
| 531 |
+
]
|
| 532 |
+
},
|
| 533 |
+
{
|
| 534 |
+
"cell_type": "markdown",
|
| 535 |
+
"metadata": {
|
| 536 |
+
"id": "EOFOm_3YmLX4"
|
| 537 |
+
},
|
| 538 |
+
"source": [
|
| 539 |
+
"# Main"
|
| 540 |
+
]
|
| 541 |
+
},
|
| 542 |
+
{
|
| 543 |
+
"cell_type": "code",
|
| 544 |
+
"execution_count": null,
|
| 545 |
+
"metadata": {
|
| 546 |
+
"id": "aJSyllYBmL7l"
|
| 547 |
+
},
|
| 548 |
+
"outputs": [],
|
| 549 |
+
"source": [
|
| 550 |
+
"if __name__ == \"__main__\":\n",
|
| 551 |
+
" print(\"=\"*80)\n",
|
| 552 |
+
" print(f\"{'Loading model & tokenizer':^80}\")\n",
|
| 553 |
+
" print(\"=\"*80)\n",
|
| 554 |
+
" apr = APRWithCLM(device=DEVICE)\n",
|
| 555 |
+
" print(f\"\\nModel loaded: {apr.model_id} on device {apr.device}\\n\")\n",
|
| 556 |
+
"\n",
|
| 557 |
+
" print(\"=\"*80)\n",
|
| 558 |
+
" print(f\"{'Running dataset':^80}\")\n",
|
| 559 |
+
" print(\"=\"*80)\n",
|
| 560 |
+
"\n",
|
| 561 |
+
" # Buat progress bar utama untuk semua tasks\n",
|
| 562 |
+
" with tqdm(total=len(pd.read_excel(DATASET_PATH)), desc=\"Overall Progress\") as pbar_main:\n",
|
| 563 |
+
" res_df = run_dataset_and_eval(\n",
|
| 564 |
+
" DATASET_PATH,\n",
|
| 565 |
+
" apr,\n",
|
| 566 |
+
" num_patches=NUM_PATCHES,\n",
|
| 567 |
+
" timeout=TIMEOUT,\n",
|
| 568 |
+
" keep_tmp=KEEP_TMP,\n",
|
| 569 |
+
" )\n",
|
| 570 |
+
"\n",
|
| 571 |
+
" print(\"\\n\" + \"=\"*80)\n",
|
| 572 |
+
" print(f\"{'Selesai. Ringkasan:':^80}\")\n",
|
| 573 |
+
" print(\"=\"*80)\n",
|
| 574 |
+
" print(res_df.groupby([\"compiled\", \"passed\"]).size())\n",
|
| 575 |
+
" print(\"\\n\")"
|
| 576 |
+
]
|
| 577 |
+
}
|
| 578 |
+
],
|
| 579 |
+
"metadata": {
|
| 580 |
+
"colab": {
|
| 581 |
+
"provenance": []
|
| 582 |
+
},
|
| 583 |
+
"kernelspec": {
|
| 584 |
+
"display_name": "Python 3",
|
| 585 |
+
"name": "python3"
|
| 586 |
+
},
|
| 587 |
+
"language_info": {
|
| 588 |
+
"name": "python"
|
| 589 |
+
}
|
| 590 |
+
},
|
| 591 |
+
"nbformat": 4,
|
| 592 |
+
"nbformat_minor": 0
|
| 593 |
+
}
|
Finetuning Training.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
Foundational Model Evaluation.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|