Spaces:
Sleeping
Sleeping
Improve challenge generation and sheet sync
Browse filesFiles changed (4)
200 unmodified lines20120220320420520614 unmodified lines22122222322422522622722817 unmodified lines246247248249250251252200 unmodified linesdef map_files(state: ArchitectState) -> ArchitectState:clone_path = state["clone_path"]target_nesting = state["nesting_level"]suitable_files: list[tuple[int, int, str]] = [] # (func_count, line_count, path)for root, dirs, files in os.walk(clone_path):14 unmodified linesand not n.name.startswith("_") and not n.name.startswith("test"))line_count = len(content.splitlines())# Only keep files with enough functions (at least 5 for multi-bug support)if func_count >= 5:suitable_files.append((func_count, line_count, full))except:continue # Skip files that can't be parsed17 unmodified linesdebug_mode = state.get("debug_mode", False)if debug_mode:print(f"[mapper] Found {len(suitable_files)} suitable files (5+ functions each)")print(f"[mapper] WEIGHTED selection (longer files preferred): {chosen_path}")print(f"[mapper] Selected file: {chosen_func_count} functions, {chosen_line_count} lines")print(f"[mapper] {len(candidate_files)} total candidates available as fallback")200 unmodified lines20120220320420520620720814 unmodified lines22322422522622722822923017 unmodified lines248249250251252253254200 unmodified linesdef map_files(state: ArchitectState) -> ArchitectState:clone_path = state["clone_path"]target_nesting = state["nesting_level"]requested_bugs = max(1, state.get("num_bugs") or 1)min_functions = max(2, min(5, requested_bugs + 1))suitable_files: list[tuple[int, int, str]] = [] # (func_count, line_count, path)for root, dirs, files in os.walk(clone_path):14 unmodified linesand not n.name.startswith("_") and not n.name.startswith("test"))line_count = len(content.splitlines())# Keep smaller files in the fallback pool as long as they can plausibly host bug targets.if func_count >= min_functions:suitable_files.append((func_count, line_count, full))except:continue # Skip files that can't be parsed17 unmodified linesdebug_mode = state.get("debug_mode", False)if debug_mode:print(f"[mapper] Found {len(suitable_files)} suitable files ({min_functions}+ functions each)")print(f"[mapper] WEIGHTED selection (longer files preferred): {chosen_path}")print(f"[mapper] Selected file: {chosen_func_count} functions, {chosen_line_count} lines")print(f"[mapper] {len(candidate_files)} total candidates available as fallback")
832 unmodified lines83383483583683783883984084184284384416 unmodified lines86186286386486586648 unmodified lines9159169179189199209219229239249251079 unmodified lines200520062007200820092010201120122013201420154 unmodified lines202020212022202320242025202610 unmodified lines20372038203920402041204220438 unmodified lines20522053205420552056205720582059206034 unmodified lines20952096209720982099210021012102210346 unmodified lines2150215121522153215421552156832 unmodified linesif value == "":return "str:empty"if len(value) == 1:return "str:char"if len(value) <= 5:return "str:short"if len(value) <= 20:return "str:medium"return "str:long"if isinstance(value, list):elem_types = sorted({type(item).__name__ for item in value})size = "empty" if not value else "one" if len(value) == 1 else "short" if len(value) <= 4 else "long"16 unmodified linesreturn f"raw:{_normalize_test_args(args_text)}"def _generate_tests_for_function(func_source: str,func_name: str,48 unmodified linesfor test in test_casesif test.get("args", "") or test.get("test_args", "")}if (len(test_cases) >= 20and len(unique_args) >= max(18, int(len(test_cases) * 0.8))and len(diversity_signatures) >= min(8, len(unique_args))):if debug_mode:print(1079 unmodified linesfunc_code = "\n".join(source_lines[node.lineno-1:node.end_lineno])candidates.append((node.name, func_code))if len(candidates) < n_funcs:return [] # Not enough functions# Step 2: Use GPT to select best functions for bug injectionprint(f"[picker] Found {len(candidates)} candidate functions, asking GPT to select best {n_funcs}...")try:# Build prompt with function previews4 unmodified linesprompt = f"""You are an expert code analyst selecting functions for bug injection in a coding challenge.TASK: Select the {n_funcs} BEST functions from the candidates below for injecting subtle logical bugs.SELECTION CRITERIA (in priority order):1. TESTABILITY: Functions with clear inputs/outputs and deterministic behavior10 unmodified lines"selected_functions": ["function_name_1", "function_name_2", ...]}}Return EXACTLY {n_funcs} function names. Choose functions that would make good challenge candidates."""response = llm.invoke([HumanMessage(content=prompt)])response_text = response.content8 unmodified linesvalid_names = {name for name, _ in candidates}selected = [name for name in selected if name in valid_names]if len(selected) >= n_funcs:print(f"[picker] GPT selected: {selected[:n_funcs]}")return selected[:n_funcs]else:print(f"[picker] GPT returned only {len(selected)} valid functions, falling back to AST scoring...")34 unmodified lines# Sort by score and take top candidatesscored.sort(key=lambda x: x[0], reverse=True)top_candidates = scored[:min(n_funcs * 3, len(scored))]random.shuffle(top_candidates)return [name for _, name in top_candidates[:n_funcs]]def saboteur_init(state: ArchitectState) -> ArchitectState:46 unmodified linesremaining_bugs = n_bugs - len(all_bugs_data)# Pick candidate functions (we may not succeed with all)candidate_funcs = _pick_simple_functions(source, remaining_bugs * 3, llm)if not candidate_funcs:if debug_mode:832 unmodified lines83383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387416 unmodified lines89189289389489589689789889990090190290390490590690790890991091191291391491591648 unmodified lines9659669679689699709719729739749759769779781079 unmodified lines20582059206020612062206320642065206620672068206920704 unmodified lines207520762077207820792080208110 unmodified lines20922093209420952096209720988 unmodified lines21072108210921102111211221132114211534 unmodified lines21502151215221532154215521562157215846 unmodified lines22052206220722082209221022112212832 unmodified linesif value == "":return "str:empty"if len(value) == 1:length_bucket = "char"elif len(value) <= 5:length_bucket = "short"elif len(value) <= 20:length_bucket = "medium"else:length_bucket = "long"if value.islower():case_bucket = "lower"elif value.isupper():case_bucket = "upper"elif value[:1].isupper() and any(ch.islower() for ch in value[1:]):case_bucket = "title"elif any(ch.isupper() for ch in value) and any(ch.islower() for ch in value):case_bucket = "mixed"else:case_bucket = "other"separator_flags = []if "_" in value:separator_flags.append("underscore")if "-" in value:separator_flags.append("hyphen")if " " in value:separator_flags.append("space")if any(ch.isdigit() for ch in value):separator_flags.append("digit")if value[:1] == "_":separator_flags.append("leading_us")if value[-1:] == "_":separator_flags.append("trailing_us")if not separator_flags:separator_flags.append("plain")return f"str:{length_bucket}:{case_bucket}:{','.join(separator_flags)}"if isinstance(value, list):elem_types = sorted({type(item).__name__ for item in value})size = "empty" if not value else "one" if len(value) == 1 else "short" if len(value) <= 4 else "long"16 unmodified linesreturn f"raw:{_normalize_test_args(args_text)}"def _single_string_argument_cases(test_cases: list[dict]) -> bool:parsed_cases = 0for test in test_cases:args_text = test.get("args", "") or test.get("test_args", "")if not args_text:continuetry:value = ast.literal_eval(args_text)if not isinstance(value, tuple):value = (value,)except Exception:return Falseparsed_cases += 1if len(value) != 1 or not isinstance(value[0], str):return Falsereturn parsed_cases > 0def _generate_tests_for_function(func_source: str,func_name: str,48 unmodified linesfor test in test_casesif test.get("args", "") or test.get("test_args", "")}required_patterns = min(8, len(unique_args))if _single_string_argument_cases(test_cases):required_patterns = min(4, len(unique_args))if (len(test_cases) >= 20and len(unique_args) >= max(18, int(len(test_cases) * 0.8))and len(diversity_signatures) >= required_patterns):if debug_mode:print(1079 unmodified linesfunc_code = "\n".join(source_lines[node.lineno-1:node.end_lineno])candidates.append((node.name, func_code))if not candidates:return []requested_funcs = min(n_funcs, len(candidates))# Step 2: Use GPT to select best functions for bug injectionprint(f"[picker] Found {len(candidates)} candidate functions, asking GPT to select best {requested_funcs}...")try:# Build prompt with function previews4 unmodified linesprompt = f"""You are an expert code analyst selecting functions for bug injection in a coding challenge.TASK: Select the {requested_funcs} BEST functions from the candidates below for injecting subtle logical bugs.SELECTION CRITERIA (in priority order):1. TESTABILITY: Functions with clear inputs/outputs and deterministic behavior10 unmodified lines"selected_functions": ["function_name_1", "function_name_2", ...]}}Return EXACTLY {requested_funcs} function names if possible. If fewer candidates are truly suitable, return as many suitable names as you can. Choose functions that would make good challenge candidates."""response = llm.invoke([HumanMessage(content=prompt)])response_text = response.content8 unmodified linesvalid_names = {name for name, _ in candidates}selected = [name for name in selected if name in valid_names]if selected:print(f"[picker] GPT selected: {selected[:requested_funcs]}")return selected[:requested_funcs]else:print(f"[picker] GPT returned only {len(selected)} valid functions, falling back to AST scoring...")34 unmodified lines# Sort by score and take top candidatesscored.sort(key=lambda x: x[0], reverse=True)top_candidates = scored[:min(max(requested_funcs * 3, 8), len(scored))]random.shuffle(top_candidates)return [name for _, name in top_candidates[:requested_funcs]]def saboteur_init(state: ArchitectState) -> ArchitectState:46 unmodified linesremaining_bugs = n_bugs - len(all_bugs_data)# Pick candidate functions (we may not succeed with all)target_candidates = max(remaining_bugs * 6, 8)candidate_funcs = _pick_simple_functions(source, target_candidates, llm)if not candidate_funcs:if debug_mode:
8 unmodified lines910111213144 unmodified lines1920212223249 unmodified lines34353637383940414243444546474849505152535455565758596061626364656667686970717273748 unmodified lines83848586878889909192939495969740 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681698 unmodified linesfrom datetime import datetimefrom typing import Optionaldef log_to_google_sheets(student_name: str,4 unmodified linespassed_tests: int,all_passed: bool,chat_history: list,) -> bool:"""Log submission to Google Sheets.9 unmodified linestry:import gspreadfrom google.oauth2.service_account import Credentials# Check if service account file existsservice_account_file = "google-service-account.json"if not os.path.exists(service_account_file):print("⚠️ Google Sheets: service account file not found")return False# Authenticatescopes = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)client = gspread.authorize(creds)# Open the sheetsheet = client.open_by_key(sheet_id).sheet1# Initialize headers if this is the first timetry:if not sheet.row_values(1): # Empty sheetheaders = ["תאריך ושעה","שם סטודנט","GitHub Repository","ציון","הינטים","טסטים שעברו","הצליח?","התכתבות עם הצ'אט",]sheet.append_row(headers)# Make headers boldsheet.format('A1:H1', {'textFormat': {'bold': True}})except Exception as e:print(f"⚠️ Could not set headers: {e}")8 unmodified lines])else:chat_text = "לא השתמש בהינטים"row = [timestamp,student_name or "Anonymous",repo_url,score,hints_used,f"{passed_tests}/{total_tests}","✅ הצליח" if all_passed else "❌ לא הצליח",chat_text,]40 unmodified linessheet = client.open_by_key(sheet_id).sheet1# Check if already has headersif sheet.row_count > 0 and sheet.row_values(1):print("✅ Sheet already has headers")return True# Add headersheaders = ["Timestamp","Student Name","Repository","Score","Hints Used","Tests Passed","All Passed?","Code Preview","Chat Summary"]sheet.append_row(headers)# Format headers (bold)sheet.format("A1:I1", {"textFormat": {"bold": True},"backgroundColor": {"red": 0.9, "green": 0.9, "blue": 0.9}})print("✅ Headers initialized!")return True8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484 unmodified lines535455565758599 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081098 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914014140 unmodified lines1821831841851861871888 unmodified linesfrom datetime import datetimefrom typing import Optionalfrom dotenv import load_dotenvload_dotenv()SUMMARY_HEADERS = ["תאריך ושעה","שם סטודנט","אתגר","GitHub Repository","קובץ יעד","ציון","הינטים","טסטים שעברו","הצליח?","סוג תוצאה","נגעה בפונקציית באג?","תיאור הבאג","התכתבות עם הצ'אט",]def _ensure_sheet_headers(sheet) -> None:current_headers = sheet.row_values(1)if current_headers[:len(SUMMARY_HEADERS)] == SUMMARY_HEADERS:returnsheet.update(range_name="A1:M1", values=[SUMMARY_HEADERS])sheet.format("A1:M1", {"textFormat": {"bold": True},"backgroundColor": {"red": 0.9, "green": 0.9, "blue": 0.9},})def log_to_google_sheets(student_name: str,4 unmodified linespassed_tests: int,all_passed: bool,chat_history: list,submission_record: Optional[dict] = None,) -> bool:"""Log submission to Google Sheets.9 unmodified linestry:import gspreadimport jsonfrom google.oauth2.service_account import Credentials# Try to get service account from environment variable first (for cloud deployment)service_account_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON")if service_account_json:# Parse JSON from environment variableservice_account_info = json.loads(service_account_json)scopes = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']creds = Credentials.from_service_account_info(service_account_info, scopes=scopes)else:# Fall back to file (for local development)service_account_file = "google-service-account.json"if not os.path.exists(service_account_file):print("⚠️ Google Sheets: service account not configured (neither env var nor file)")return Falsescopes = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']creds = Credentials.from_service_account_file(service_account_file, scopes=scopes)client = gspread.authorize(creds)# Open the sheetsheet = client.open_by_key(sheet_id).sheet1# Initialize or migrate headers to the current schema.try:_ensure_sheet_headers(sheet)except Exception as e:print(f"⚠️ Could not set headers: {e}")8 unmodified lines])else:chat_text = "לא השתמש בהינטים"challenge = submission_record.get("challenge", {}) if submission_record else {}scoring = submission_record.get("scoring", {}) if submission_record else {}submission = submission_record.get("submission", {}) if submission_record else {}row = [timestamp,student_name or "Anonymous",challenge.get("challenge_id", ""),repo_url,challenge.get("target_file", ""),score,hints_used,f"{passed_tests}/{total_tests}","✅ הצליח" if all_passed else "❌ לא הצליח",scoring.get("submission_outcome", ""),"כן" if submission.get("touched_bug_function") else "לא",challenge.get("bug_description", ""),chat_text,]40 unmodified linessheet = client.open_by_key(sheet_id).sheet1_ensure_sheet_headers(sheet)print("✅ Headers initialized!")return True
13 unmodified lines1415161718192021292 unmodified lines31431531631731831932013 unmodified linesfrom typing import TypedDictfrom langgraph.graph import StateGraph, ENDfrom langchain_openai import ChatOpenAIfrom langchain_core.messages import HumanMessage, SystemMessage, AIMessage# Cumulative penalty table — index = number of hints used (mirrors scoring.py)_HINT_PENALTY = [0, 2, 6, 12, 20, 30]292 unmodified linesHINT_SUMMARY: <one short sentence (max 120 chars) summarising what aspect of the bug you hinted at>Do NOT write HINT_SUMMARY if GAVE_HINT:NO.{_confirmed_hint_instruction}"""llm = ChatOpenAI(model="gpt-4o", temperature=0.7, request_timeout=60)# Reconstruct the conversation for the LLMlc_messages: list = [SystemMessage(content=system_prompt)]13 unmodified lines1415161718192021292 unmodified lines31431531631731831932013 unmodified linesfrom typing import TypedDictfrom langgraph.graph import StateGraph, ENDfrom langchain_core.messages import HumanMessage, SystemMessage, AIMessagefrom llm_config import get_llm# Cumulative penalty table — index = number of hints used (mirrors scoring.py)_HINT_PENALTY = [0, 2, 6, 12, 20, 30]292 unmodified linesHINT_SUMMARY: <one short sentence (max 120 chars) summarising what aspect of the bug you hinted at>Do NOT write HINT_SUMMARY if GAVE_HINT:NO.{_confirmed_hint_instruction}"""llm = get_llm(temperature=0.7, request_timeout=60)# Reconstruct the conversation for the LLMlc_messages: list = [SystemMessage(content=system_prompt)]
architect/file_mapper.py+5-3
architect/saboteur.py+74-18
google_sheets_logger.py+71-52
orchestrator/hint_graph.py+2-2