Spaces:
Sleeping
Sleeping
Switch to Tabs navigation - works on production!
Browse filesFiles changed (2)
- app.py+16-42
- minimal_test.py+135-222
12345678910111 unmodified line131415161718194 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""app.py β Simplified entry point for hosting platforms (Render, Hugging Face, etc.)This file launches the full interface with login page support.No API key required β users provide their own via the login page.For Hugging Face Spaces: demo object is created at module levelFor Render/local: can run with python app.py"""import os1 unmodified lineimport loggingfrom dotenv import load_dotenv# Configure logging BEFORE everything elselogging.basicConfig(level=logging.INFO,format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',4 unmodified lines)logger = logging.getLogger(__name__)# Load .env if it exists (for local development)load_dotenv()# Apply proxy settings from .env if definedif os.getenv("http_proxy"):logger.info(f"Setting http_proxy: {os.getenv('http_proxy')}")os.environ["http_proxy"] = os.getenv("http_proxy")if os.getenv("https_proxy"):logger.info(f"Setting https_proxy: {os.getenv('https_proxy')}")os.environ["https_proxy"] = os.getenv("https_proxy")if os.getenv("no_proxy"):os.environ["no_proxy"] = os.getenv("no_proxy")import gradio as grimport student_interface# Create demo at module level for Hugging Face Spaceslogger.info("π Initializing Legacy Code Challenge...")has_key = bool(os.getenv("OPENAI_API_KEY"))if has_key:logger.info("β API key detected in environment β skipping login page")else:logger.info("π No API key found β login page will be shown")try:demo = student_interface.create_full_interface()logger.info("β Interface created successfully!")except Exception as e:logger.error(f"β Failed to create interface: {e}", exc_info=True)raise# For local/Render deploymentif __name__ == "__main__":port = int(os.getenv("PORT", "7860"))logger.info(f"π Server will listen on 0.0.0.0:{port}")logger.info(f"π Launching Gradio on 0.0.0.0:{port}...")try:demo.launch(server_name="0.0.0.0",server_port=port,share=False,inbrowser=False,show_error=True,)logger.info("β Gradio server started successfully!")except Exception as e:logger.error(f"β Launch failed: {e}", exc_info=True)raise12345671 unmodified line91011121314154 unmodified lines2021222324252627282930313233343536373839404142434445464748495051"""app.py β Entry point using minimal_test.py (Tabs-based navigation)This version uses Tabs instead of Columns for better production compatibility."""import os1 unmodified lineimport loggingfrom dotenv import load_dotenv# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',4 unmodified lines)logger = logging.getLogger(__name__)# Load .env if it existsload_dotenv()# Apply proxy settingsif os.getenv("http_proxy"):os.environ["http_proxy"] = os.getenv("http_proxy")if os.getenv("https_proxy"):os.environ["https_proxy"] = os.getenv("https_proxy")if os.getenv("no_proxy"):os.environ["no_proxy"] = os.getenv("no_proxy")logger.info("π Launching Legacy Code Challenge (Tabs version)...")from minimal_test import demologger.info("β Demo imported successfully!")if __name__ == "__main__":port = int(os.getenv("PORT", "7860"))logger.info(f"π Launching on 0.0.0.0:{port}...")demo.launch(server_name="0.0.0.0",server_port=port,share=False,inbrowser=False,show_error=True,)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""Real Legacy Code Challenge - Working version with Columns"""import gradio as grimport osimport loggingimport jsonfrom pathlib import Path# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# ββ ChallengeState (copied from student_interface.py) ββββββββββββββββββββββββclass ChallengeState:"""Loads and exposes data from challenge_state.json."""def __init__(self, workspace_path: str) -> None:self.workspace = Path(workspace_path)state_file = self.workspace / "challenge_state.json"if not state_file.exists():raise FileNotFoundError(f"challenge_state.json not found in {workspace_path}")with open(state_file, encoding="utf-8") as f:data = json.load(f)self.github_url = data.get("github_url", "")raw_target = data.get("target_file", "")try:self.target_file = Path(raw_target).resolve().relative_to(self.workspace.resolve()).as_posix()except (ValueError, OSError):self.target_file = Path(raw_target).as_posix()self.original_code = data.get("original_code", "")self.sabotaged_code = data.get("sabotaged_code", "")self.function_name = data.get("function_name", "")self.bug_func_name = data.get("bug_func_name", "")# sabotaged_filessnapshot_dir = self.workspace / ".metadata"snap_files = {}if snapshot_dir.exists():target_rel_from_json = data.get("target_file", "")if target_rel_from_json:try:target_abs = Path(target_rel_from_json).resolve()target_rel = target_abs.relative_to(self.workspace.resolve()).as_posix()except (ValueError, OSError):target_rel = Path(target_rel_from_json).as_posix()expected_snapshot_name = target_rel.replace("/", "__")snapshot_path = snapshot_dir / expected_snapshot_nameif snapshot_path.exists():try:snap_files[target_rel] = snapshot_path.read_text(encoding="utf-8")except Exception:passif snap_files:self.sabotaged_files = snap_fileselse:stored = data.get("sabotaged_files", {})if not stored and self.sabotaged_code:try:rel = Path(self.target_file).resolve().relative_to(self.workspace.resolve()).as_posix()except ValueError:rel = Path(self.target_file).namestored = {rel: self.sabotaged_code}self.sabotaged_files = stored@propertydef target_path(self) -> Path:return self.workspace / self.target_filedef read_target(self) -> str:if self.target_path.exists():return self.target_path.read_text(encoding="utf-8")return self.sabotaged_codedef write_target(self, code: str) -> None:self.target_path.write_text(code, encoding="utf-8")def list_py_files(self) -> list[str]:files = sorted(self.workspace.rglob("*.py"))return [f.relative_to(self.workspace).as_posix() for f in filesif ".metadata" not in f.parts]def readme(self) -> str:readme_path = self.workspace / "STUDENT_README.md"if readme_path.exists():return readme_path.read_text(encoding="utf-8")return "# Challenge\n\nREADME not found."# ββ Pipeline function (copied from student_interface.py) βββββββββββββββββββββdef _run_pipeline(github_url: str, nesting_level: int, num_bugs: int,refactoring_enabled: bool = False, debug_mode: bool = False) -> str:"""Invoke the architect pipeline and return the workspace path."""from architect.graph import build_graphgraph = build_graph()result = graph.invoke({"github_url": github_url,"nesting_level": nesting_level,"refactoring_enabled": refactoring_enabled,"debug_mode": debug_mode,"num_bugs": num_bugs,"clone_path": "","target_file": "","original_code": "","sabotaged_code": "","function_name": "","test_args": "","expected_output": "","actual_output": "","bug_description": "","detailed_explanation": "","challenge_summary": "","test_cases": [],"public_tests": [],"secret_tests": [],"candidate_files": [],"bug_func_name": "","bug_func_source": "","call_chain": {},})workspace_path = result["clone_path"]target_file_rel = result.get("target_file", "")actual_sabotaged_code = result.get("sabotaged_code", "")workspace_path_obj = Path(workspace_path).resolve()if target_file_rel:target_path = Path(workspace_path) / target_file_relif target_path.exists():actual_sabotaged_code = target_path.read_text(encoding="utf-8")sabotaged_files: dict[str, str] = {}if target_file_rel and actual_sabotaged_code:try:rel_posix = Path(target_file_rel).resolve().relative_to(workspace_path_obj).as_posix()except (ValueError, OSError):rel_posix = Path(target_file_rel).as_posix()sabotaged_files[rel_posix] = actual_sabotaged_code# Persist challenge_state.jsonchallenge_state = {"github_url": github_url,"workspace_path": workspace_path,"target_file": target_file_rel,"original_code": result.get("original_code", ""),"sabotaged_code": actual_sabotaged_code,"sabotaged_files": sabotaged_files,"function_name": result.get("function_name", ""),"bug_func_name": result.get("bug_func_name", ""),"test_cases": result.get("test_cases", []),"public_tests": result.get("public_tests", []),"secret_tests": result.get("secret_tests", []),"nesting_level": nesting_level,"refactoring_enabled": refactoring_enabled,"debug_mode": debug_mode,"bug_description": result.get("bug_description", ""),}state_path = Path(workspace_path) / "challenge_state.json"with open(state_path, "w", encoding="utf-8") as f:json.dump(challenge_state, f, indent=2, ensure_ascii=False)return workspace_pathwith gr.Blocks(title="Legacy Code Challenge", theme=gr.themes.Soft()) as demo:# Page 1: Loginwith gr.Column(visible=True) as login_page:gr.Markdown("# π ΧΧ ΧΧ‘Χ ΧΧΧ’Χ¨ΧΧͺ")gr.Markdown("ΧΧΧ ΧΧͺ ΧΧ€Χ¨ΧΧΧ Χ©ΧΧ ΧΧΧ ΧΧΧͺΧΧΧ")name_input = gr.Textbox(label="Χ©Χ ΧΧΧ", placeholder="ΧΧΧ ΧΧͺ Χ©ΧΧ...", rtl=True)api_input = gr.Textbox(label="OpenAI API Key", placeholder="sk-proj-...", type="password")login_btn = gr.Button("ΧΧͺΧΧΧ¨ β‘οΈ", variant="primary", size="lg")# Page 2: Setupwith gr.Column(visible=False) as setup_page:gr.Markdown("# βοΈ ΧΧΧΧ¨Χͺ ΧΧͺΧΧ¨")gr.Markdown("ΧΧΧ¨ repository ΧΧ€οΏ½οΏ½ΧΧΧ¨ΧΧ")url_input = gr.Textbox(label="GitHub Repository URL",value="https://github.com/mahmoud/boltons")num_bugs = gr.Slider(1, 5, value=3, step=1, label="ΧΧ‘Χ€Χ¨ ΧΧΧΧΧ")num_tests = gr.Slider(5, 30, value=15, step=5, label="ΧΧ‘Χ€Χ¨ ΧΧ‘ΧΧΧ")start_btn = gr.Button("ΧΧͺΧΧ ΧΧͺΧΧ¨ β‘οΈ", variant="primary", size="lg")status_box = gr.Textbox(label="Χ‘ΧΧΧΧ‘", interactive=False, lines=3)# Page 3: Challengewith gr.Column(visible=False) as challenge_page:gr.Markdown("# π» ΧͺΧ§Χ ΧΧͺ ΧΧ§ΧΧ")gr.Markdown("ΧΧ§ΧΧ ΧΧΧΧ ΧΧΧΧ ΧΧΧΧΧ. ΧͺΧ§Χ ΧΧΧͺΧ ΧΧΧΧ₯ Χ’Χ 'Χ©ΧΧ'")code_display = gr.Textbox(label="Χ§ΧΧ Χ’Χ ΧΧΧΧΧ",lines=20,value="# ΧΧ§ΧΧ ΧΧΧ¦Χ ΧΧΧ ΧΧΧΧ¨ ΧΧ¦ΧΧ¨Χͺ ΧΧΧͺΧΧ¨\ndef hello():\n print('Hello World')\n\nhello()",max_lines=30)submit_btn = gr.Button("Χ©ΧΧ Χ€ΧͺΧ¨ΧΧ β‘οΈ", variant="primary", size="lg")# Page 4: Resultswith gr.Column(visible=False) as results_page:gr.Markdown("# π― ΧͺΧΧ¦ΧΧΧͺ ΧΧ’Χ¨ΧΧ")score_html = gr.HTML("<h2>ΧΧ¦ΧΧΧ Χ©ΧΧ ΧΧΧ€ΧΧ’ ΧΧΧ</h2>")diff_html = gr.HTML("<h3>Χ©ΧΧ ΧΧΧΧ</h3>")tests_html = gr.HTML("<h3>ΧΧ‘ΧΧΧ</h3>")hints_html = gr.HTML("<h3>Χ¨ΧΧΧΧ</h3>")# Event handlersdef on_login(name, api_key):if not name or not api_key:return gr.update(visible=True), gr.update(visible=False)# Save API key to environmentos.environ["OPENAI_API_KEY"] = api_keylogger.info(f"User logged in: {name}")return gr.update(visible=False), gr.update(visible=True)def on_start(url, bugs, tests):logger.info(f"Starting challenge: {url}, bugs={bugs}, tests={tests}")# Show loadingyield ("β³ Cloning repository and generating challenge... this may take 1-2 minutes.",gr.update(visible=True),gr.update(visible=False),gr.update() # code_display - no change)try:# Run the REAL pipeline!workspace_path = _run_pipeline(url.strip(),nesting_level=2, # defaultnum_bugs=int(bugs),refactoring_level=0, # defaultdebug_mode=False)logger.info(f"Pipeline complete! Workspace: {workspace_path}")# Load challenge statecs = ChallengeState(workspace_path)code = cs.read_target()# Move to challenge pageyield (f"β Challenge ready! File: {cs.target_file}",gr.update(visible=False),gr.update(visible=True),code # Update code_display)except Exception as exc:logger.error(f"Pipeline failed: {exc}", exc_info=True)yield (f"β Error: {exc}",gr.update(visible=True),gr.update(visible=False),"")def on_submit():# Immediate response - no processingyield (gr.update(visible=False), # challenge_pagegr.update(visible=True), # results_page"<div style='padding:20px;background:#e8f5e9;border-radius:10px;'><h2 style='color:green;'>β Χ¦ΧΧΧ: 85/100</h2></div>","<p>Diff ΧΧΧ€ΧΧ’ ΧΧΧ...</p>","<p>Tests ΧΧΧ€ΧΧ’Χ ΧΧΧ...</p>","<p>Hints ΧΧΧ€ΧΧ’Χ ΧΧΧ...</p>")# Wire eventslogin_btn.click(fn=on_login,inputs=[name_input, api_input],outputs=[login_page, setup_page])start_btn.click(fn=on_start,inputs=[url_input, num_bugs, num_tests],outputs=[status_box, setup_page, challenge_page, code_display])submit_btn.click(fn=on_submit,inputs=[],outputs=[challenge_page, results_page, score_html, diff_html, tests_html, hints_html])demo.queue()if __name__ == "__main__":demo.launch(share=False, inbrowser=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218"""Legacy Code Challenge - Tabs version (production-ready)"""import gradio as grimport osimport loggingimport jsonfrom pathlib import Pathfrom io import StringIOimport sysfrom datetime import datetime# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Import required modules from student_interfacefrom orchestrator.scoring import evaluate_submission# ββ ChallengeState ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass ChallengeState:"""Loads challenge data from challenge_state.json."""def __init__(self, workspace_path: str):self.workspace = Path(workspace_path)state_file = self.workspace / "challenge_state.json"if not state_file.exists():raise FileNotFoundError(f"challenge_state.json not found in {workspace_path}")with open(state_file, encoding="utf-8") as f:data = json.load(f)self.github_url = data.get("github_url", "")self.target_file = data.get("target_file", "")self.original_code = data.get("original_code", "")self.sabotaged_code = data.get("sabotaged_code", "")self.bug_func_name = data.get("bug_func_name", "")self.bug_func_names = data.get("bug_func_names", [])@propertydef target_path(self) -> Path:return self.workspace / self.target_filedef read_target(self) -> str:if self.target_path.exists():return self.target_path.read_text(encoding="utf-8")return self.sabotaged_codedef readme(self) -> str:readme_path = self.workspace / "STUDENT_README.md"if readme_path.exists():return readme_path.read_text(encoding="utf-8")return "# Challenge\n\nREADME not found."# ββ Pipeline function βββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _run_pipeline(github_url: str, nesting_level: int, num_bugs: int,refactoring_enabled: bool = False, debug_mode: bool = False) -> str:"""Invoke the architect pipeline and return workspace path."""from architect.graph import build_graphgraph = build_graph()result = graph.invoke({"github_url": github_url,"nesting_level": nesting_level,"refactoring_enabled": refactoring_enabled,"debug_mode": debug_mode,"num_bugs": num_bugs,"clone_path": "","target_file": "","original_code": "","sabotaged_code": "","function_name": "","test_cases": [],"public_tests": [],"secret_tests": [],"candidate_files": [],"bug_func_name": "","call_chain": {},})workspace_path = result["clone_path"]target_file_rel = result.get("target_file", "")actual_sabotaged_code = result.get("sabotaged_code", "")# Persist challenge_state.jsonchallenge_state = {"github_url": github_url,"workspace_path": workspace_path,"target_file": target_file_rel,"original_code": result.get("original_code", ""),"sabotaged_code": actual_sabotaged_code,"function_name": result.get("function_name", ""),"bug_func_name": result.get("bug_func_name", ""),"bug_func_names": result.get("bug_func_names", []),"test_cases": result.get("test_cases", []),"public_tests": result.get("public_tests", []),"secret_tests": result.get("secret_tests", []),"nesting_level": nesting_level,"refactoring_enabled": refactoring_enabled,"debug_mode": debug_mode,}state_path = Path(workspace_path) / "challenge_state.json"with open(state_path, "w", encoding="utf-8") as f:json.dump(challenge_state, f, indent=2, ensure_ascii=False)return workspace_path# ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(title="Legacy Code Challenge", theme=gr.themes.Soft()) as demo:# Hidden stateworkspace_state = gr.State("")with gr.Tabs() as tabs:# Tab 0: Loginwith gr.Tab("π Login", id=0):gr.Markdown("# π Welcome to Legacy Code Challenge")name_input = gr.Textbox(label="Your Name", placeholder="e.g. Alice")api_input = gr.Textbox(label="OpenAI API Key", placeholder="sk-proj-...", type="password")login_btn = gr.Button("Continue β‘οΈ", variant="primary", size="lg")# Tab 1: Setupwith gr.Tab("βοΈ Setup", id=1):gr.Markdown("# βοΈ Setup Challenge")url_input = gr.Textbox(label="GitHub URL", value="https://github.com/mahmoud/boltons")num_bugs = gr.Slider(1, 5, value=3, step=1, label="Number of Bugs")start_btn = gr.Button("Start Challenge β‘οΈ", variant="primary", size="lg")status_md = gr.Markdown("")# Tab 2: Challengewith gr.Tab("π» Challenge", id=2):gr.Markdown("# π» Fix the Code")code_box = gr.Textbox(label="Code", lines=20, interactive=True)submit_btn = gr.Button("Submit β‘οΈ", variant="primary", size="lg")# Tab 3: Resultswith gr.Tab("π― Results", id=3):gr.Markdown("# π― Evaluation Results")score_html = gr.HTML("")tests_html = gr.HTML("")# Event handlersdef on_login(name, api_key):if not name or not api_key:return gr.Tabs(selected=0)os.environ["OPENAI_API_KEY"] = api_keylogger.info(f"User logged in: {name}")return gr.Tabs(selected=1)def on_start(url, bugs):logger.info(f"Starting: {url}, bugs={bugs}")yield gr.Tabs(selected=1), "β³ Creating challenge...", ""try:workspace = _run_pipeline(url.strip(), nesting_level=2, num_bugs=int(bugs))cs = ChallengeState(workspace)code = cs.read_target()yield gr.Tabs(selected=2), f"β Ready! File: {cs.target_file}", code, workspaceexcept Exception as exc:logger.error(f"Pipeline failed: {exc}", exc_info=True)yield gr.Tabs(selected=1), f"β Error: {exc}", "", ""def on_submit(workspace):logger.info(f"Submit: workspace={workspace}")# Move to results tab immediatelyyield gr.Tabs(selected=3), "<p style='text-align:center;padding:40px;'>β³ Running tests...</p>", ""try:if not workspace:yield gr.Tabs(selected=3), "β No challenge loaded", ""returncs = ChallengeState(workspace)submitted_code = cs.read_target()result = evaluate_submission(workspace_path=workspace,student_code=submitted_code,original_code=cs.original_code,bug_func_name=cs.bug_func_name,hints_used=0,sabotaged_code=cs.sabotaged_code,target_file=str(cs.target_path),bug_func_names=cs.bug_func_names,)score = result.get("total_score", 0)passed = result.get("passed", 0)total = result.get("total_tests", 0)score_html_content = f"""<div style='padding:30px;background:#e8f5e9;border-radius:10px;text-align:center;'><h1 style='color:green;margin:0;'>Score: {score}/100</h1><p style='font-size:1.2em;margin-top:10px;'>β {passed}/{total} tests passed</p></div>"""tests_output = result.get("test_output", "No test output")tests_html_content = f"<pre style='background:#f5f5f5;padding:20px;border-radius:5px;'>{tests_output}</pre>"yield gr.Tabs(selected=3), score_html_content, tests_html_contentexcept Exception as exc:logger.error(f"Submission failed: {exc}", exc_info=True)yield gr.Tabs(selected=3), f"β Error: {exc}", ""# Wire eventslogin_btn.click(on_login, inputs=[name_input, api_input], outputs=[tabs])start_btn.click(on_start, inputs=[url_input, num_bugs], outputs=[tabs, status_md, code_box, workspace_state])submit_btn.click(on_submit, inputs=[workspace_state], outputs=[tabs, score_html, tests_html])demo.queue()if __name__ == "__main__":demo.launch()
app.py+16-42
minimal_test.py+135-222