Spaces:
Running
Running
File size: 10,210 Bytes
59a8d26 4f6bb9e 8800c81 59a8d26 8800c81 59a8d26 8800c81 59a8d26 8800c81 59a8d26 a42236e 59a8d26 8800c81 59a8d26 8800c81 a42236e 59a8d26 8800c81 59a8d26 8800c81 59a8d26 8800c81 59a8d26 a42236e 59a8d26 8800c81 4f6bb9e 8800c81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | import ast
import json
import re
import ai_cache
import db
def extract_starter_code(reference_code: str) -> str:
"""
Extracts a clean, spoiler-free starter code skeleton from reference_code.
Preserves all class definitions, helper type definition comments (e.g. ListNode/TreeNode),
and all function/method signatures with empty 'pass' bodies.
Never returns implementation logic or dumps the reference solution.
"""
if not reference_code or not reference_code.strip():
return ""
# 1. Collect any leading definition comments (e.g. # Definition for singly-linked list.)
leading_comments = []
lines = reference_code.splitlines()
in_def_comment = False
for line in lines:
stripped = line.strip()
if stripped.startswith("# Definition for"):
in_def_comment = True
leading_comments.append(line)
elif in_def_comment:
if stripped.startswith("#"):
leading_comments.append(line)
else:
break
elif (
stripped.startswith("class ")
or stripped.startswith("def ")
or stripped.startswith("type ")
):
break
try:
tree = ast.parse(reference_code)
# Keep ClassDef, FunctionDef, AsyncFunctionDef, and modern TypeAlias (PEP 695)
allowed_types = [ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef]
if hasattr(ast, "TypeAlias"):
allowed_types.append(ast.TypeAlias)
defs = [n for n in tree.body if isinstance(n, tuple(allowed_types))]
if not defs:
return "def solve():\n pass\n"
tree.body = defs
class BodyStripper(ast.NodeTransformer):
def visit_FunctionDef(self, node):
node.body = [ast.Pass()]
return node
def visit_AsyncFunctionDef(self, node):
node.body = [ast.Pass()]
return node
new_tree = BodyStripper().visit(tree)
unparsed = ast.unparse(new_tree)
if leading_comments:
return "\n".join(leading_comments) + "\n" + unparsed
return unparsed
except Exception:
# Fallback to line scanning without leaking function bodies
starter_lines = []
for line in lines:
stripped = line.strip()
if stripped.startswith("class ") or stripped.startswith("type "):
starter_lines.append(line)
elif stripped.startswith("def "):
starter_lines.append(line)
indent = len(line) - len(line.lstrip())
starter_lines.append(" " * (indent + 4) + "pass")
if starter_lines:
return "\n".join(starter_lines)
return "def solve():\n pass\n"
def parse_examples_and_constraints_from_text(text: str):
"""
If a problem's description contains embedded 'Example 1:', 'Constraints:', etc.,
splits it into clean description, structured examples list, and constraints list.
"""
if not text:
return "", [], []
clean_desc = text
examples = []
constraints = []
ex_match = re.search(r"\bExample\s*\d*:", text, re.IGNORECASE)
co_match = re.search(r"\bConstraints\s*:", text, re.IGNORECASE)
first_split = None
if ex_match and co_match:
first_split = min(ex_match.start(), co_match.start())
elif ex_match:
first_split = ex_match.start()
elif co_match:
first_split = co_match.start()
if first_split is not None:
clean_desc = text[:first_split].strip()
body_rest = text[first_split:]
if co_match:
c_in_rest = re.search(r"\bConstraints\s*:", body_rest, re.IGNORECASE)
if c_in_rest:
ex_part = body_rest[: c_in_rest.start()].strip()
co_part = body_rest[c_in_rest.end() :].strip()
else:
ex_part = body_rest.strip()
co_part = ""
else:
ex_part = body_rest.strip()
co_part = ""
if ex_part:
ex_blocks = list(re.finditer(r"\bExample\s*(\d*)\s*:", ex_part, re.IGNORECASE))
for i, blk in enumerate(ex_blocks):
blk_start = blk.end()
blk_end = ex_blocks[i + 1].start() if i + 1 < len(ex_blocks) else len(ex_part)
blk_text = ex_part[blk_start:blk_end].strip()
inp_match = re.search(
r"Input:\s*(.+?)(?=(?:Output:|Explanation:|\Z))",
blk_text,
re.IGNORECASE | re.DOTALL,
)
out_match = re.search(
r"Output:\s*(.+?)(?=(?:Explanation:|\Z))", blk_text, re.IGNORECASE | re.DOTALL
)
exp_match = re.search(r"Explanation:\s*(.+)", blk_text, re.IGNORECASE | re.DOTALL)
inp = inp_match.group(1).strip() if inp_match else ""
out = out_match.group(1).strip() if out_match else ""
exp = exp_match.group(1).strip() if exp_match else ""
if inp or out:
examples.append({"input": inp, "output": out, "explanation": exp})
elif blk_text:
examples.append({"input": blk_text, "output": "", "explanation": ""})
if co_part:
for line in co_part.split("\n"):
line = line.strip()
line = re.sub(r"^[•\-\*]\s*", "", line).strip()
if line:
constraints.append(line)
return clean_desc, examples, constraints
def enrich_problem_examples_and_constraints(
prob: dict, client=None, check_remote_cache: bool = True
) -> dict:
"""Ensures problem has structured examples, constraints, and clean description."""
if not prob:
return prob
# Parse JSON strings for examples and constraints if stored as JSON (e.g. from SQLite)
raw_examples = prob.get("examples")
if isinstance(raw_examples, str) and raw_examples.strip():
try:
parsed_ex = json.loads(raw_examples)
if isinstance(parsed_ex, list):
prob["examples"] = parsed_ex
except Exception:
pass
raw_constraints = prob.get("constraints")
if isinstance(raw_constraints, str) and raw_constraints.strip():
try:
parsed_co = json.loads(raw_constraints)
if isinstance(parsed_co, list):
prob["constraints"] = parsed_co
except Exception:
pass
if client and hasattr(db, "is_sandbox_or_mock") and db.is_sandbox_or_mock(client):
check_remote_cache = False
has_examples = bool(
prob.get("examples") and isinstance(prob["examples"], list) and len(prob["examples"]) > 0
)
has_constraints = bool(
prob.get("constraints")
and (
(isinstance(prob["constraints"], list) and len(prob["constraints"]) > 0)
or (isinstance(prob["constraints"], str) and prob["constraints"].strip())
)
)
# 1. Try parsing from description if missing
if (not has_examples or not has_constraints) and prob.get("description"):
clean_desc, parsed_ex, parsed_co = parse_examples_and_constraints_from_text(
prob["description"]
)
updated = False
if not has_examples and parsed_ex:
prob["examples"] = parsed_ex
has_examples = True
updated = True
if not has_constraints and parsed_co:
prob["constraints"] = parsed_co
has_constraints = True
updated = True
if clean_desc and clean_desc != prob["description"]:
prob["description"] = clean_desc
updated = True
if updated and prob.get("id"):
try:
db.update_problem(
prob["id"],
{
"examples": prob.get("examples", []),
"constraints": prob.get("constraints", []),
"description": prob.get("description", ""),
},
client,
)
except Exception as e:
db.log_trace(f"Error persisting parsed examples/constraints: {e}")
# 2. Check ai_cache if still missing and remote check allowed
if check_remote_cache and (not has_examples or not has_constraints) and prob.get("name"):
raw_name = prob["name"]
clean_title = re.sub(r"\s*-\s*Method.*$", "", raw_name).strip()
cached = ai_cache.get_leetcode_problem(clean_title)
if not cached and prob.get("problem_number"):
cached = ai_cache.get_leetcode_problem(f"{prob['problem_number']}. {clean_title}")
if cached and isinstance(cached, dict):
updated = False
if not has_examples and cached.get("examples"):
prob["examples"] = cached["examples"]
has_examples = True
updated = True
if not has_constraints and cached.get("constraints"):
prob["constraints"] = cached["constraints"]
has_constraints = True
updated = True
if not prob.get("description") and cached.get("description"):
prob["description"] = cached["description"]
updated = True
if updated and prob.get("id"):
try:
db.update_problem(
prob["id"],
{
"examples": prob.get("examples", []),
"constraints": prob.get("constraints", []),
"description": prob.get("description", ""),
},
client,
)
except Exception as e:
db.log_trace(f"Error persisting cached examples/constraints: {e}")
# Normalize constraints to list if string
if isinstance(prob.get("constraints"), str):
prob["constraints"] = [c.strip() for c in prob["constraints"].split("\n") if c.strip()]
return prob
|