Rishi-Jain-27's picture
Created data generator and data and finetune.py
da653f3
Raw
History Blame Contribute Delete
15.5 kB
"""Reusable building blocks: paraphrased conditions, return kinds, identifier
pools, and per-language syntax fragments.
Conditions carry both the literal source expression (Python and JS forms) and a
*plain-English paraphrase* used as the flowchart label, satisfying the strict
"no raw code/operators in labels" constraint.
"""
from __future__ import annotations
from dataclasses import dataclass
from engine import CodeBuilder
# --------------------------------------------------------------------------- #
# Conditions
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class Cond:
label: str # plain-English paraphrase (flowchart label)
py: str # python source template
js: str # javascript source template
def code(self, lang: str, **kw) -> str:
# The Python form (==, !=, % 2 == 0, &&-free) is valid C/C++ too; only
# JavaScript needs its === / !== form. So cpp/c map to the py form.
src = self.js if lang == "javascript" else self.py
return src.format(**kw)
# placeholder {x}: a numeric scalar
NUM1 = [
Cond("Number is positive?", "{x} > 0", "{x} > 0"),
Cond("Number is negative?", "{x} < 0", "{x} < 0"),
Cond("Value is zero?", "{x} == 0", "{x} === 0"),
Cond("Value is even?", "{x} % 2 == 0", "{x} % 2 === 0"),
Cond("Value is odd?", "{x} % 2 != 0", "{x} % 2 !== 0"),
]
# placeholders {x},{t}
NUM_T = [
Cond("Value above threshold?", "{x} > {t}", "{x} > {t}"),
Cond("Value meets threshold?", "{x} >= {t}", "{x} >= {t}"),
Cond("Value below limit?", "{x} < {t}", "{x} < {t}"),
Cond("Value exceeds maximum?", "{x} > {t}", "{x} > {t}"),
Cond("Value at or under limit?", "{x} <= {t}", "{x} <= {t}"),
]
# placeholder {c}: a collection
COLL = [
Cond("Collection is empty?", "len({c}) == 0", "{c}.length === 0"),
Cond("Collection has items?", "len({c}) > 0", "{c}.length > 0"),
]
# placeholders {c},{t}
COLL_T = [
Cond("Collection longer than limit?", "len({c}) > {t}", "{c}.length > {t}"),
Cond("Enough elements gathered?", "len({c}) >= {t}", "{c}.length >= {t}"),
]
# placeholder {v}: maybe-missing value
NULL = [
Cond("Value is missing?", "{v} is None", "{v} == null"),
Cond("Value is present?", "{v} is not None", "{v} != null"),
]
# placeholder {s}: a string
STR1 = [
Cond("Text is empty?", '{s} == ""', '{s} === ""'),
]
# placeholders {s},{t}
STR_T = [
Cond("Text longer than limit?", "len({s}) > {t}", "{s}.length > {t}"),
]
# placeholders {s},{p}
STR_P = [
Cond("Text starts with prefix?", "{s}.startswith({p})", "{s}.startsWith({p})"),
]
# placeholders {a},{b}
EQ = [
Cond("Values are equal?", "{a} == {b}", "{a} === {b}"),
Cond("Values differ?", "{a} != {b}", "{a} !== {b}"),
Cond("Matches target?", "{a} == {b}", "{a} === {b}"),
]
# placeholder {f}: a boolean flag
FLAG = [
Cond("Flag is set?", "{f}", "{f}"),
Cond("Input is invalid?", "not {f}", "!{f}"),
Cond("Condition holds?", "{f}", "{f}"),
]
# placeholders {c},{target}
CONTAINS = [
Cond("Item present in collection?", "{target} in {c}", "{c}.includes({target})"),
]
# placeholders {k},{c}
KEY_IN = [
Cond("Key exists in map?", "{k} in {c}", "{k} in {c}"),
Cond("Key is absent?", "{k} not in {c}", "!({k} in {c})"),
]
# --------------------------------------------------------------------------- #
# Return kinds
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class Ret:
py: str
js: str
label: str
def code(self, lang: str) -> str:
return self.py if lang == "python" else self.js
RET = {
"zero": Ret("return 0", "return 0;", "Return zero"),
"one": Ret("return 1", "return 1;", "Return one"),
"neg1": Ret("return -1", "return -1;", "Return not found"),
"true": Ret("return True", "return true;", "Return true"),
"false": Ret("return False", "return false;", "Return false"),
"none": Ret("return None", "return null;", "Return nothing"),
"total": Ret("return total", "return total;", "Return the total"),
"count": Ret("return count", "return count;", "Return the count"),
"result": Ret("return result", "return result;", "Return the result"),
"results": Ret("return results", "return results;", "Return collected results"),
"value": Ret("return value", "return value;", "Return the value"),
"index": Ret("return i", "return i;", "Return the index"),
"best": Ret("return best", "return best;", "Return the maximum"),
"current": Ret("return current", "return current;", "Return current value"),
"empty_list": Ret("return []", "return [];", "Return empty list"),
"average": Ret("return average", "return average;", "Return the average"),
"name": Ret("return name", "return name;", "Return the name"),
}
def ret_status(active: bool):
"""A pair of opposite plain-English status returns plus their literals."""
return active
STATUS_PAIRS = [
('"active"', '"inactive"', "Return active status", "Return inactive status"),
('"valid"', '"invalid"', "Return valid result", "Return invalid result"),
('"granted"', '"denied"', "Return access granted", "Return access denied"),
('"pass"', '"fail"', "Return passing grade", "Return failing grade"),
('"high"', '"low"', "Return high priority", "Return low priority"),
('"ok"', '"error"', "Return ok status", "Return error status"),
]
CLASSIFY_TRIPLES = [
('"high"', '"medium"', '"low"', "Return high band", "Return medium band", "Return low band"),
('"positive"', '"zero"', '"negative"', "Return positive sign", "Return zero sign", "Return negative sign"),
('"gold"', '"silver"', '"bronze"', "Return gold tier", "Return silver tier", "Return bronze tier"),
('"adult"', '"teen"', '"child"', "Return adult group", "Return teen group", "Return child group"),
]
# --------------------------------------------------------------------------- #
# Identifier pools
# --------------------------------------------------------------------------- #
FN_VALIDATE = ["validate_input", "check_status", "is_eligible", "verify_token",
"validate_age", "check_access", "is_valid_user", "validate_score",
"check_permission", "is_ready"]
FN_MATH = ["compute_total", "calculate_sum", "find_max", "compute_average",
"factorial", "running_total", "accumulate", "power_of", "clamp_value",
"tally"]
FN_SEARCH = ["find_item", "search_list", "locate_index", "find_first",
"contains_value", "lookup", "index_of", "first_match"]
FN_PROCESS = ["process_items", "filter_values", "transform_data", "normalize",
"aggregate", "summarize", "parse_records", "build_report",
"collect_valid", "scan_entries"]
FN_STRING = ["format_name", "parse_input", "sanitize", "truncate_text",
"slugify", "count_words", "trim_value", "label_for"]
FN_GAME = ["update_score", "apply_damage", "check_win", "next_level",
"move_player", "spawn_enemy", "resolve_turn"]
ALL_FN_GROUPS = {
"validate": FN_VALIDATE,
"math": FN_MATH,
"search": FN_SEARCH,
"process": FN_PROCESS,
"string": FN_STRING,
"game": FN_GAME,
}
def camel(name: str) -> str:
head, *rest = name.split("_")
return head + "".join(w.capitalize() for w in rest)
def fn_name(rng, group: str, lang: str) -> str:
name = rng.choice(ALL_FN_GROUPS[group])
return camel(name) if lang in ("javascript", "cpp") else name
COLLECTIONS = ["items", "nums", "values", "data", "records", "entries",
"scores", "elements", "rows", "tokens", "results", "arr"]
SCALARS = ["value", "n", "x", "amount", "score", "count", "level", "size",
"weight", "age", "balance", "qty"]
STRINGS = ["text", "name", "word", "line", "title", "label", "code", "key"]
FLAGS = ["valid", "ready", "active", "enabled", "found", "ok", "allowed"]
LOOPVARS = ["i", "idx", "j", "k"]
ITEMVARS = ["item", "entry", "row", "element", "node", "record", "value"]
TARGETS = ["target", "needle", "wanted", "goal", "query"]
KEYS = ["key", "name", "field", "user_id", "code"]
PREFIXES = ['"a"', '"x_"', '"tmp"', '"id_"', '"v"']
# filler text
COMMENTS = [
"early bail out on bad input",
"guard against invalid state",
"main processing path",
"accumulate the running figure",
"walk through every element",
"handle the edge case first",
"keep scanning until matched",
"fall through to the default",
"normalize before comparing",
"short circuit when possible",
"TODO revisit this branch",
"defensive check",
]
DOCSTRINGS = [
"Return a status for the given input.",
"Compute and return the aggregate value.",
"Find and return the matching element.",
"Validate the arguments and proceed.",
"Process the collection and report back.",
"Helper used by the main pipeline.",
]
# --------------------------------------------------------------------------- #
# Language syntax fragments
# --------------------------------------------------------------------------- #
PY_NAME, JS_NAME, CPP_NAME, C_NAME = "python", "javascript", "cpp", "c"
# Abstract parameter/return kinds -> concrete C / C++ types.
_TYPES = {
CPP_NAME: {"int": "int", "num": "int", "bound": "int", "bool": "bool",
"str": "std::string", "str_ref": "const std::string&",
"coll": "std::vector<int>", "coll_ref": "const std::vector<int>&",
"void": "void"},
C_NAME: {"int": "int", "num": "int", "bound": "int", "bool": "int",
"str": "const char*", "str_ref": "const char*",
"coll": "int*", "coll_ref": "int*", "void": "void"},
}
class Lang:
def __init__(self, name: str):
self.name = name
self.py = name == PY_NAME
self.braces = name in (JS_NAME, CPP_NAME, C_NAME)
self.semi = ";" if self.braces else ""
self.indent_unit = " " if self.py else " "
self.comment_prefix = "# " if self.py else "// "
def builder(self) -> CodeBuilder:
return CodeBuilder(self.indent_unit, self.comment_prefix)
# types & signatures ----------------------------------------------------- #
def _type(self, kind: str, by_ref: bool = False) -> str:
if by_ref and kind in ("str", "coll"):
kind = kind + "_ref"
return _TYPES[self.name][kind]
def sig(self, params) -> str:
"""params: list of name (=> int) or (kind, name). C collections gain a
companion length parameter."""
norm = [(p if isinstance(p, tuple) else ("int", p)) for p in params]
if self.name in (PY_NAME, JS_NAME):
return ", ".join(n for _, n in norm)
out = []
for kind, name in norm:
out.append(f"{self._type(kind, by_ref=True)} {name}")
if self.name == C_NAME and kind == "coll":
out.append(f"int {name}_len")
return ", ".join(out)
# headers ---------------------------------------------------------------- #
def def_header(self, fn: str, params, ret: str = "int") -> str:
s = self.sig(params)
if self.py:
return f"def {fn}({s}):"
if self.name == JS_NAME:
return f"function {fn}({s}) {{"
return f"{self._type(ret)} {fn}({s}) {{" # cpp / c
def if_header(self, cond: str) -> str:
return f"if {cond}:" if self.py else f"if ({cond}) {{"
def elif_header(self, cond: str) -> str:
return f"elif {cond}:" if self.py else f"}} else if ({cond}) {{"
def else_header(self) -> str:
return "else:" if self.py else "} else {"
def while_header(self, cond: str) -> str:
return f"while {cond}:" if self.py else f"while ({cond}) {{"
def forrange(self, cb: CodeBuilder, indent: int, ivar: str, n) -> int:
if self.py:
return cb.add(f"for {ivar} in range({n}):", indent)
decl = "let" if self.name == JS_NAME else "int"
return cb.add(f"for ({decl} {ivar} = 0; {ivar} < {n}; {ivar}++) {{", indent)
def foreach(self, cb: CodeBuilder, indent: int, item: str, coll: str, ivar: str = "i"):
"""Emit a for-each loop; return (line_no, element_expression)."""
if self.py:
return cb.add(f"for {item} in {coll}:", indent), item
if self.name == JS_NAME:
return cb.add(f"for (const {item} of {coll}) {{", indent), item
if self.name == CPP_NAME:
return cb.add(f"for (int {item} : {coll}) {{", indent), item
ln = cb.add(f"for (int {ivar} = 0; {ivar} < {coll}_len; {ivar}++) {{", indent)
return ln, f"{coll}[{ivar}]"
# length & lang-specific conditions ------------------------------------- #
def length(self, c: str) -> str:
return {PY_NAME: f"len({c})", JS_NAME: f"{c}.length",
CPP_NAME: f"{c}.size()", C_NAME: f"{c}_len"}[self.name]
def cond_empty(self, c: str) -> str:
return {PY_NAME: f"len({c}) == 0", JS_NAME: f"{c}.length === 0",
CPP_NAME: f"{c}.empty()", C_NAME: f"{c}_len == 0"}[self.name]
def cond_nonempty(self, c: str) -> str:
return {PY_NAME: f"len({c}) > 0", JS_NAME: f"{c}.length > 0",
CPP_NAME: f"!{c}.empty()", C_NAME: f"{c}_len > 0"}[self.name]
def cond_null(self, v: str) -> str:
return {PY_NAME: f"{v} is None", JS_NAME: f"{v} == null",
CPP_NAME: f"{v} == nullptr", C_NAME: f"{v} == NULL"}[self.name]
def cond_notnull(self, v: str) -> str:
return {PY_NAME: f"{v} is not None", JS_NAME: f"{v} != null",
CPP_NAME: f"{v} != nullptr", C_NAME: f"{v} != NULL"}[self.name]
def cond_flag(self, f: str) -> str:
return f
def cond_notflag(self, f: str) -> str:
return f"not {f}" if self.py else f"!{f}"
# literals --------------------------------------------------------------- #
def true(self) -> str:
return "True" if self.py else ("1" if self.name == C_NAME else "true")
def false(self) -> str:
return "False" if self.py else ("0" if self.name == C_NAME else "false")
def null(self) -> str:
return {PY_NAME: "None", JS_NAME: "null",
CPP_NAME: "nullptr", C_NAME: "NULL"}[self.name]
def and_op(self) -> str:
return "and" if self.py else "&&"
def eq(self) -> str:
return "===" if self.name == JS_NAME else "=="
# statements ------------------------------------------------------------- #
def declare(self, name: str, value: str, kind: str = "int") -> str:
if self.py:
return f"{name} = {value}"
if self.name == JS_NAME:
return f"let {name} = {value};"
return f"{self._type(kind)} {name} = {value};" # cpp / c
def reassign(self, name: str, value: str) -> str:
return f"{name} = {value}{self.semi}"
def aug(self, a: str, op: str, b: str) -> str:
return f"{a} {op}= {b}{self.semi}"
def stmt(self, expr: str) -> str:
return f"{expr}{self.semi}"
def ret(self, expr: str) -> str:
return f"return {expr}{self.semi}"
def break_(self) -> str:
return f"break{self.semi}"
def continue_(self) -> str:
return f"continue{self.semi}"
# block close (python uses indentation, no brace) ----------------------- #
def close(self, cb: CodeBuilder, indent: int) -> None:
if self.braces:
cb.add("}", indent)