andstor's picture
Upload process.py
8c469fe verified
#!/usr/bin/env python3
"""Build source/target training pairs from andstor/defects4j_fixed."""
import argparse
import json
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, Iterable, List, Tuple
from datasets import Dataset, load_dataset
Record = Dict[str, Any]
def normalize_line_endings(text: str) -> str:
return text.replace("\r\n", "\n").replace("\r", "\n")
def collapse_whitespace(text: str) -> str:
return " ".join((text or "").split())
def class_declaration(class_info: Dict[str, Any]) -> str:
class_name = class_info.get("identifier", "UnknownClass")
superclass = (class_info.get("superclass") or "").strip()
interfaces = collapse_whitespace(class_info.get("interfaces", ""))
declaration = f"public class {class_name}"
if superclass:
declaration += f" extends {superclass}"
if interfaces:
declaration += f" implements {interfaces}"
return declaration + " {"
def field_lines(class_info: Dict[str, Any]) -> List[str]:
fields = class_info.get("fields") or []
lines: List[str] = []
for field in fields:
original = (field.get("original_string") or "").strip()
if original:
lines.append(original)
return lines
def method_signature(method_info: Dict[str, Any]) -> str:
signature = (method_info.get("full_signature") or "").strip()
if signature:
return collapse_whitespace(signature)
modifiers = collapse_whitespace(method_info.get("modifiers", ""))
return_type = collapse_whitespace(method_info.get("return", ""))
identifier = method_info.get("identifier", "unknownMethod")
parameters = collapse_whitespace(method_info.get("parameters", "()"))
pieces = [part for part in [modifiers, return_type, f"{identifier}{parameters}"] if part]
return " ".join(pieces)
def class_key(record: Record) -> Tuple[str, str, str]:
class_info = record.get("class", {})
return (
str(record.get("project_id", "")),
str(record.get("bug_id", "")),
str(class_info.get("file", class_info.get("identifier", ""))),
)
def method_key(method_info: Dict[str, Any]) -> str:
return method_signature(method_info)
def strip_first_signature_line(method_body: str) -> str:
body = normalize_line_endings(method_body)
brace_index = body.find("{")
if brace_index == -1:
return body.strip("\n")
return body[brace_index + 1 :].lstrip("\n").rstrip("\n")
def indent_lines(lines: Iterable[str], spaces: int = 4) -> List[str]:
prefix = " " * spaces
return [f"{prefix}{line}" if line else "" for line in lines]
def with_final_class_brace(target: str) -> str:
cleaned = target.rstrip("\n")
if not cleaned:
return "}"
return f"{cleaned}\n}}"
def build_source(
class_info: Dict[str, Any],
constructors: Iterable[str],
other_methods: Iterable[str],
focal_signature: str,
) -> str:
parts: List[str] = [class_declaration(class_info)]
fields = field_lines(class_info)
if fields:
parts.append("\n".join(indent_lines(fields)))
ctor_lines = [f"{sig};" for sig in constructors if sig]
if ctor_lines:
parts.append("\n".join(indent_lines(ctor_lines)))
method_lines = [f"{sig};" for sig in other_methods if sig]
if method_lines:
parts.append("\n".join(indent_lines(method_lines)))
parts.append(f" {focal_signature} {{")
return "\n\n".join(parts)
def build_examples(records: List[Record]) -> List[Dict[str, Any]]:
grouped: Dict[Tuple[str, str, str], List[Record]] = defaultdict(list)
for record in records:
grouped[class_key(record)].append(record)
examples: List[Dict[str, Any]] = []
for record in records:
method_info = record.get("method", {})
class_info = record.get("class", {})
body = method_info.get("body", "")
focal_signature = method_signature(method_info)
cls_records = grouped[class_key(record)]
constructors = sorted(
{
method_signature(r.get("method", {}))
for r in cls_records
if r.get("method", {}).get("constructor")
}
)
focal_sig_key = method_key(method_info)
other_method_sigs = sorted(
{
method_signature(r.get("method", {}))
for r in cls_records
if not r.get("method", {}).get("constructor")
and method_key(r.get("method", {})) != focal_sig_key
}
)
source = build_source(class_info, constructors, other_method_sigs, focal_signature)
target = with_final_class_brace(strip_first_signature_line(body))
examples.append(
{
"id": record.get("id"),
"project_id": record.get("project_id"),
"bug_id": record.get("bug_id"),
"class_file": class_info.get("file"),
"method": method_info.get("identifier"),
"source": source,
"target": target,
}
)
return examples
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--split",
default="train",
help="Dataset split to load (default: train).",
)
parser.add_argument(
"--hub-repo",
default="defects4j_fixed_runnable",
help="Hugging Face dataset repo to upload to.",
)
parser.add_argument(
"--output",
default=None,
help="Optional output JSONL file path.",
)
parser.add_argument(
"--max-records",
type=int,
default=None,
help="Optional limit for quick smoke tests.",
)
args = parser.parse_args()
ds = load_dataset("andstor/defects4j_fixed", split=args.split)
records: List[Record] = list(ds)
if args.max_records is not None:
records = records[: args.max_records]
examples = build_examples(records)
hf_dataset = Dataset.from_list(examples)
hf_dataset.push_to_hub(args.hub_repo)
print(f"Uploaded {len(examples)} examples to {args.hub_repo}")
if args.output:
output_path = Path(args.output)
with output_path.open("w", encoding="utf-8") as f:
for example in examples:
f.write(json.dumps(example, ensure_ascii=False) + "\n")
print(f"Wrote {len(examples)} examples to {output_path}")
if __name__ == "__main__":
main()