classroom / app.py
NathVinter's picture
Add classroom app
42202c9
Raw History Blame Contribute Delete
7.64 kB
"""Classroom Space: students prompt an OpenAI model, the teacher watches prompts and
token usage, and everyone can follow the teacher's own prompts live."""
import os
import tempfile
import threading
from dataclasses import asdict, dataclass
from datetime import datetime
import gradio as gr
import pandas as pd
from openai import OpenAI, OpenAIError
def require_env(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"Missing Space secret: {name}")
return value
CLASS_CODE = require_env("CLASS_CODE")
TEACHER_CODE = require_env("TEACHER_CODE")
MODEL = os.environ.get("OPENAI_MODEL", "gpt-4o-mini")
TOKEN_LIMIT = int(os.environ.get("TOKEN_LIMIT_PER_STUDENT", "0")) # 0 = unlimited
TEACHER = "Teacher"
REFRESH_SECONDS = 3
client = OpenAI(api_key=require_env("OPENAI_API_KEY"))
# --- In-memory class log (resets when the Space restarts) -------------------
@dataclass
class Entry:
time: str
user: str
prompt: str
answer: str
input_tokens: int
output_tokens: int
entries: list[Entry] = []
lock = threading.Lock()
def entries_for(user: str) -> list[Entry]:
with lock:
return [e for e in entries if e.user == user]
def history_for(user: str) -> list[dict]:
"""A user's conversation, in the chat-message format both OpenAI and Gradio use."""
history = []
for e in entries_for(user):
history.append({"role": "user", "content": e.prompt})
history.append({"role": "assistant", "content": e.answer})
return history
def tokens_used(user: str) -> int:
return sum(e.input_tokens + e.output_tokens for e in entries_for(user))
def ask(user: str, prompt: str) -> None:
"""Send the prompt with the user's earlier conversation, and log the result."""
if TOKEN_LIMIT and user != TEACHER and tokens_used(user) >= TOKEN_LIMIT:
raise gr.Error(f"You've used your token allowance ({TOKEN_LIMIT}).")
messages = history_for(user) + [{"role": "user", "content": prompt}]
try:
response = client.chat.completions.create(model=MODEL, messages=messages)
except OpenAIError as err:
raise gr.Error(f"The model request failed: {err}")
entry = Entry(
time=datetime.now().strftime("%H:%M:%S"),
user=user,
prompt=prompt,
answer=response.choices[0].message.content or "",
input_tokens=response.usage.prompt_tokens,
output_tokens=response.usage.completion_tokens,
)
with lock:
entries.append(entry)
def usage_text(user: str) -> str:
limit = f" / {TOKEN_LIMIT}" if TOKEN_LIMIT and user != TEACHER else ""
return f"Tokens used: **{tokens_used(user)}{limit}**"
# --- Student tab ------------------------------------------------------------
def join(name: str, code: str):
name = name.strip()
if not name:
raise gr.Error("Please enter your name.")
if name.lower() == TEACHER.lower():
raise gr.Error(f'"{TEACHER}" is reserved. Please choose another name.')
if code.strip() != CLASS_CODE:
raise gr.Error("Wrong class code.")
return name, gr.update(visible=False), gr.update(visible=True), history_for(name), usage_text(name)
def student_send(user: str, prompt: str):
if not prompt.strip():
return gr.skip(), gr.skip(), gr.skip()
ask(user, prompt.strip())
return "", history_for(user), usage_text(user)
# --- Teacher tab ------------------------------------------------------------
def unlock(code: str):
if code.strip() != TEACHER_CODE:
raise gr.Error("Wrong teacher code.")
return gr.update(visible=False), gr.update(visible=True), gr.Timer(active=True)
def teacher_send(prompt: str):
if not prompt.strip():
return gr.skip(), gr.skip()
ask(TEACHER, prompt.strip())
return "", history_for(TEACHER)
def prompts_table() -> pd.DataFrame:
with lock:
rows = [asdict(e) for e in reversed(entries)]
return pd.DataFrame(rows, columns=list(Entry.__dataclass_fields__))
def usage_table() -> pd.DataFrame:
df = prompts_table()
if df.empty:
return pd.DataFrame(columns=["user", "prompts", "input_tokens", "output_tokens", "total_tokens"])
summary = df.groupby("user").agg(
prompts=("prompt", "count"),
input_tokens=("input_tokens", "sum"),
output_tokens=("output_tokens", "sum"),
)
summary["total_tokens"] = summary.input_tokens + summary.output_tokens
return summary.sort_values("total_tokens", ascending=False).reset_index()
def export_csv() -> str:
path = os.path.join(tempfile.gettempdir(), f"classroom_{datetime.now():%Y%m%d_%H%M%S}.csv")
prompts_table().to_csv(path, index=False)
return path
# --- UI ---------------------------------------------------------------------
with gr.Blocks(title="Classroom") as demo:
gr.Markdown(f"# Classroom\nModel: `{MODEL}`")
with gr.Tab("Student"):
student = gr.State("")
with gr.Column() as join_panel:
name_box = gr.Textbox(label="Your name")
code_box = gr.Textbox(label="Class code", type="password")
join_btn = gr.Button("Join", variant="primary")
with gr.Column(visible=False) as chat_panel:
student_chat = gr.Chatbot(type="messages", height=450)
student_prompt = gr.Textbox(label="Your prompt", lines=3)
student_btn = gr.Button("Send", variant="primary")
student_usage = gr.Markdown()
join_btn.click(
join,
[name_box, code_box],
[student, join_panel, chat_panel, student_chat, student_usage],
)
for trigger in (student_btn.click, student_prompt.submit):
trigger(student_send, [student, student_prompt], [student_prompt, student_chat, student_usage])
with gr.Tab("Follow the teacher"):
gr.Markdown(f"The teacher's prompts and answers. Updates every {REFRESH_SECONDS} seconds.")
feed = gr.Chatbot(type="messages", height=550)
gr.Timer(REFRESH_SECONDS).tick(lambda: history_for(TEACHER), outputs=feed)
with gr.Tab("Teacher"):
with gr.Column() as lock_panel:
teacher_code = gr.Textbox(label="Teacher code", type="password")
unlock_btn = gr.Button("Unlock", variant="primary")
with gr.Column(visible=False) as teacher_panel:
with gr.Row():
with gr.Column():
gr.Markdown("### Your prompts (shown live to students)")
teacher_chat = gr.Chatbot(type="messages", height=400)
teacher_prompt = gr.Textbox(label="Prompt", lines=3)
teacher_btn = gr.Button("Send", variant="primary")
with gr.Column():
gr.Markdown("### Token usage per person")
usage_df = gr.Dataframe(interactive=False)
export_btn = gr.Button("Export all prompts to CSV")
export_file = gr.File(label="CSV")
gr.Markdown("### All prompts (newest first)")
prompts_df = gr.Dataframe(interactive=False, wrap=True)
dashboard_timer = gr.Timer(REFRESH_SECONDS, active=False)
dashboard_timer.tick(lambda: (usage_table(), prompts_table()), outputs=[usage_df, prompts_df])
unlock_btn.click(unlock, teacher_code, [lock_panel, teacher_panel, dashboard_timer])
for trigger in (teacher_btn.click, teacher_prompt.submit):
trigger(teacher_send, teacher_prompt, [teacher_prompt, teacher_chat])
export_btn.click(export_csv, outputs=export_file)
if __name__ == "__main__":
demo.launch()