Spaces:
Sleeping
Sleeping
File size: 4,800 Bytes
532e19f | 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 | """
Patch to add login page to student_interface.py
This adds user registration with API key input before the main interface.
"""
# Add this function at the top of student_interface.py, before create_full_interface():
def validate_openai_key(api_key: str) -> tuple[bool, str]:
"""Validate that an OpenAI API key is properly formatted and works."""
import os
if not api_key or not api_key.startswith("sk-"):
return False, "Invalid API key format. Must start with 'sk-'"
# Try a simple API call to validate
try:
os.environ["OPENAI_API_KEY"] = api_key
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o", temperature=0, request_timeout=5, max_tokens=5)
llm.invoke("test")
return True, "β
API key validated successfully!"
except Exception as e:
error_msg = str(e)
if "401" in error_msg or "Incorrect API key" in error_msg:
return False, "β Invalid API key. Please check your key."
elif "quota" in error_msg.lower():
return False, "β οΈ API key valid but no quota remaining."
else:
# Key is probably valid, just another error
return True, f"β οΈ API key accepted (error: {error_msg[:50]})"
# Then modify create_full_interface() to add login page:
# Add after line "with gr.Blocks..." and before "# Shared state":
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 0 β Login/Registration
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
user_api_key_state = gr.State("")
user_name_state = gr.State("")
with gr.Column(visible=True, elem_classes=["setup-card"]) as login_page:
gr.Markdown(
"# π Welcome to Legacy Code Challenge\n"
"### Please enter your details to continue"
)
login_name = gr.Textbox(
label="Your Name",
placeholder="e.g. Alice Smith",
info="This will appear in your challenge session",
)
login_api_key = gr.Textbox(
label="OpenAI API Key",
placeholder="sk-proj-...",
type="password",
info="Your API key will be used only for this session",
)
gr.Markdown(
"π‘ **Don't have an API key?** Get one at [platform.openai.com/api-keys](https://platform.openai.com/api-keys)\n\n"
"β οΈ **Note:** Running challenges will consume API credits from your OpenAI account"
)
login_btn = gr.Button("π Continue to Challenge Setup", variant="primary", size="lg")
login_status = gr.Markdown("")
# Add this callback at the bottom, before "return demo":
def on_login(name, api_key):
if not name.strip():
return (
gr.update(visible=True),
gr.update(visible=False),
"β Please enter your name",
"", ""
)
valid, msg = validate_openai_key(api_key)
if not valid:
return (
gr.update(visible=True),
gr.update(visible=False),
msg,
"", ""
)
# Success - hide login, show setup
import os
os.environ["OPENAI_API_KEY"] = api_key
return (
gr.update(visible=False), # hide login
gr.update(visible=True), # show setup
msg,
api_key, # save to state
name.strip() # save name to state
)
login_btn.click(
on_login,
inputs=[login_name, login_api_key],
outputs=[login_page, setup_page, login_status, user_api_key_state, user_name_state],
)
# Modify on_start() to use user_name_state instead of name_box:
# Change the first line from:
# def on_start(name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins):
# To:
# def on_start(saved_name, url, nesting_lvl, num_bugs, refactoring, debug, timer_mins):
# And use saved_name instead of name throughout
# Update start_btn.click():
# Change inputs from:
# inputs=[name_box, url_box, ...]
# To:
# inputs=[user_name_state, url_box, ...]
|