algospaced-dsa / core /problem_utils.py
iamfebin's picture
feat: offline review queue caching, connection fallback UI, and cache failure cooldowns
4f6bb9e
Raw History Blame Contribute Delete
10.2 kB
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