Spaces:
Sleeping
Sleeping
Add comprehensive logging for debugging deployment issues
Browse filesFiles changed (2)
- app.py+36-12
- student_interface.py+42
8 unmodified lines910111213141516171819202122232 unmodified lines262728293031323334353637383940414243444546474849505152538 unmodified lines"""import osfrom dotenv import load_dotenv# Load .env if it exists (for local development)load_dotenv()# Apply proxy settings from .env if definedif 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")2 unmodified linesimport student_interface# Create demo at module level for Hugging Face Spacesprint("π Initializing Legacy Code Challenge...")has_key = bool(os.getenv("OPENAI_API_KEY"))if has_key:print("β API key detected in environment β skipping login page")else:print("π No API key found β login page will be shown")demo = student_interface.create_full_interface()print("β Interface created successfully!")# For local/Render deploymentif __name__ == "__main__":port = int(os.getenv("PORT", "7860"))print(f"π Server will listen on 0.0.0.0:{port}")print(f"π Launching Gradio on 0.0.0.0:{port}...")demo.launch(server_name="0.0.0.0",server_port=port,share=False,inbrowser=False,show_error=True,)8 unmodified lines910111213141516171819202122232425262728293031323334353637382 unmodified lines414243444546474849505152535455565758596061626364656667686970717273747576778 unmodified lines"""import osimport sysimport loggingfrom dotenv import load_dotenv# Configure logging BEFORE everything elselogging.basicConfig(level=logging.INFO,format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',handlers=[logging.FileHandler('app.log', encoding='utf-8'),logging.StreamHandler(sys.stdout)])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")2 unmodified linesimport 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,)except Exception as e:logger.error(f"β Launch failed: {e}", exc_info=True)raiseshow_error=True,)
13 unmodified lines14151617181920212223242523 unmodified lines49505152535455565758596061626364656667686970711295 unmodified lines1367136813691370137113721 unmodified line137413751376137713781379138013813 unmodified lines1385138613871388138913901391139213931394139513968 unmodified lines140514061407140814091410114 unmodified lines1525152615271528152915307 unmodified lines1538153915401541154215434 unmodified lines154815491550155115521553155413 unmodified linesimport osimport sysimport threadingfrom io import StringIOfrom datetime import datetimefrom pathlib import Pathimport gradio as grfrom orchestrator.scoring import evaluate_submissionfrom orchestrator.hint_graph import get_hint23 unmodified linesdef validate_openai_key(api_key: str) -> tuple[bool, str]:"""Validate OpenAI API key by making a test call."""if not api_key or not api_key.startswith("sk-"):return False, "β Invalid API key format. Must start with 'sk-'"try:os.environ["OPENAI_API_KEY"] = api_keyfrom langchain_openai import ChatOpenAIllm = ChatOpenAI(model="gpt-4o", temperature=0, request_timeout=5, max_tokens=5)llm.invoke("test")return True, "β API key validated!"except Exception as e:error = str(e)if "401" in error or "Incorrect API key" in error:return False, "β Invalid API key"elif "quota" in error.lower():return False, "β οΈ API key valid but no quota remaining"elif "timeout" in error.lower():return True, "β Key accepted (validation timed out - will verify during use)"return True, "β Key accepted (couldn't fully verify)"1295 unmodified lines# ββ Setup callback βββββββββββββββββββββββββββββββββββββββββββββββββdef on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins, user_name_from_login, user_api_key):nesting = int(nesting_lvl)# Use login name if available, otherwise name from setup form1 unmodified line# Ensure API key is set in environment (critical for pipeline)if user_api_key:os.environ["OPENAI_API_KEY"] = user_api_keyyield (gr.update(visible=True,value="β³ Cloning repository and generating challengeβ¦"3 unmodified lines)try:workspace_path = _run_pipeline(url.strip(), nesting, int(num_bugs), refactoring, debug)cs = ChallengeState(workspace_path)py_files = cs.list_py_files()default = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else "")suffix = f" | {name_str}" if name_str else ""yield (gr.update(visible=False),gr.update(interactive=True),8 unmodified lines)except Exception as exc:error_msg = str(exc)# Provide user-friendly error messages114 unmodified linesreturn cs.sabotaged_code, gr.update(selected=1)def on_submit(hints_used, submit_count, workspace_path, hint_log, user_name):# ULTRA-SIMPLE TEST: Just show SOMETHING immediatelytest_msg = f"""<div style='padding:20px;background:#1e1e1e;color:#fff;border-radius:8px;'>7 unmodified lines"""try:# First yield IMMEDIATELY: Show loading state (before any logic that might fail)_loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">β³ Running testsβ¦</p>'yield (4 unmodified lines"", # debug console"β³ Starting submission evaluation...", # live debug)except Exception as init_exc:# If even the first yield fails, show errorerr = f"<p style='color:#ef4444;'>β Initialization error: {init_exc}</p>"yield (gr.update(), gr.update(), err, "", "", "", submit_count, str(init_exc), str(init_exc))13 unmodified lines14151617181920212223242526272829303132333435363723 unmodified lines616263646566676869707172737475767778798081828384858687888990911295 unmodified lines138713881389139013911392139313941395139613971 unmodified line1399140014011402140314041405140614071408140914103 unmodified lines141414151416141714181419142014211422142314241425142614271428142914308 unmodified lines1439144014411442144314441445114 unmodified lines15601561156215631564156515661567156815697 unmodified lines15771578157915801581158215834 unmodified lines15881589159015911592159315941595159613 unmodified linesimport osimport sysimport threadingimport loggingfrom io import StringIOfrom datetime import datetimefrom pathlib import Pathimport gradio as gr# Configure detailed logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',handlers=[logging.FileHandler('app.log', encoding='utf-8'),logging.StreamHandler(sys.stdout)])logger = logging.getLogger(__name__)from orchestrator.scoring import evaluate_submissionfrom orchestrator.hint_graph import get_hint23 unmodified linesdef validate_openai_key(api_key: str) -> tuple[bool, str]:"""Validate OpenAI API key by making a test call."""logger.info("Validating OpenAI API key...")if not api_key or not api_key.startswith("sk-"):logger.warning("Invalid API key format")return False, "β Invalid API key format. Must start with 'sk-'"try:os.environ["OPENAI_API_KEY"] = api_keyfrom langchain_openai import ChatOpenAIlogger.info("Making test call to OpenAI...")llm = ChatOpenAI(model="gpt-4o", temperature=0, request_timeout=5, max_tokens=5)llm.invoke("test")logger.info("β API key validated successfully")return True, "β API key validated!"except Exception as e:error = str(e)logger.warning(f"API key validation failed: {error}")if "401" in error or "Incorrect API key" in error:return False, "β Invalid API key"elif "quota" in error.lower():return False, "β οΈ API key valid but no quota remaining"elif "timeout" in error.lower():logger.info("Validation timed out but accepting key")return True, "β Key accepted (validation timed out - will verify during use)"logger.info("Couldn't fully verify but accepting key")return True, "β Key accepted (couldn't fully verify)"1295 unmodified lines# ββ Setup callback βββββββββββββββββββββββββββββββββββββββββββββββββdef on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins, user_name_from_login, user_api_key):logger.info(f"=== START CHALLENGE ===")logger.info(f"User: {user_name_from_login or name}")logger.info(f"URL: {url}")logger.info(f"Nesting: {nesting_lvl}, Bugs: {num_bugs}, Refactoring: {refactoring}, Debug: {debug}")nesting = int(nesting_lvl)# Use login name if available, otherwise name from setup form1 unmodified line# Ensure API key is set in environment (critical for pipeline)if user_api_key:logger.info("Setting OPENAI_API_KEY from user login")os.environ["OPENAI_API_KEY"] = user_api_keyelse:logger.warning("No user_api_key provided!")logger.info("Yielding loading message...")yield (gr.update(visible=True,value="β³ Cloning repository and generating challengeβ¦"3 unmodified lines)try:logger.info(f"Starting pipeline for {url.strip()}")workspace_path = _run_pipeline(url.strip(), nesting, int(num_bugs), refactoring, debug)logger.info(f"Pipeline completed. Workspace: {workspace_path}")cs = ChallengeState(workspace_path)py_files = cs.list_py_files()default = cs.target_file if cs.target_file in py_files else (py_files[0] if py_files else "")suffix = f" | {name_str}" if name_str else ""logger.info(f"Challenge ready! Target file: {cs.target_file}, {len(py_files)} Python files")yield (gr.update(visible=False),gr.update(interactive=True),8 unmodified lines)except Exception as exc:logger.error(f"Pipeline failed: {exc}", exc_info=True)error_msg = str(exc)# Provide user-friendly error messages114 unmodified linesreturn cs.sabotaged_code, gr.update(selected=1)def on_submit(hints_used, submit_count, workspace_path, hint_log, user_name):logger.info(f"=== SUBMIT CHALLENGE ===")logger.info(f"User: {user_name}, Hints: {hints_used}, Submit#: {submit_count}")logger.info(f"Workspace: {workspace_path}")# ULTRA-SIMPLE TEST: Just show SOMETHING immediatelytest_msg = f"""<div style='padding:20px;background:#1e1e1e;color:#fff;border-radius:8px;'>7 unmodified lines"""try:logger.info("Yielding initial loading state...")# First yield IMMEDIATELY: Show loading state (before any logic that might fail)_loading = '<p style="text-align:center;padding:40px;color:#888;font-size:1.2em;">β³ Running testsβ¦</p>'yield (4 unmodified lines"", # debug console"β³ Starting submission evaluation...", # live debug)logger.info("Initial yield complete")except Exception as init_exc:logger.error(f"Initial yield failed: {init_exc}", exc_info=True)# If even the first yield fails, show errorerr = f"<p style='color:#ef4444;'>β Initialization error: {init_exc}</p>"yield (gr.update(), gr.update(), err, "", "", "", submit_count, str(init_exc), str(init_exc))
app.py+36-12
student_interface.py+42