Spaces:
Running
Running
| import json | |
| import os | |
| from pathlib import Path | |
| import gradio as gr | |
| from huggingface_hub import InferenceClient | |
| import os | |
| from supabase import create_client, Client | |
| url: str = os.environ.get("SUPABASE_URL") | |
| key: str = os.environ.get("SUPABASE_KEY") | |
| supabase: Client = create_client(url, key) | |
| TEAM = None | |
| def load_registered_teams(): | |
| result = supabase.table("teams").select("*").execute() | |
| if not result or not result.data: | |
| return None | |
| return {team["name"].casefold(): team for team in result.data} | |
| INTRO_DEFAULT = "### The Safety Game · Prompt Submission\n" | |
| INTRO_VERIFIED_TEMPLATE = ( | |
| "### The Safety Game · Prompt Submission\n" | |
| "Benvenuti, **{team}**. Ora potete inviare il vostro prompt per la valutazione." | |
| ) | |
| PROMPT_LOCKED = ( | |
| gr.update(visible=False), | |
| gr.update(value="", interactive=False), | |
| gr.update(interactive=False), | |
| gr.update(value="", interactive=False), | |
| gr.update(interactive=False), | |
| ) | |
| PROMPT_UNLOCKED = ( | |
| gr.update(visible=True), | |
| gr.update(value="", interactive=True), | |
| gr.update(interactive=True), | |
| gr.update(value="", interactive=False), | |
| gr.update(interactive=False), | |
| ) | |
| TEAM_PANEL_VISIBLE = gr.update() | |
| TEAM_PANEL_HIDDEN = gr.update(visible=False) | |
| model_name = "openai/gpt-oss-20b" | |
| def generate_response(prompt: str): | |
| messages = [ | |
| {"role": "system", "content": "You are an helpful assistant"}, | |
| {"role": "user", "content": prompt}, | |
| ] | |
| try: | |
| client = InferenceClient( | |
| model=model_name, | |
| token=os.getenv("HF_TOKEN"), | |
| ) | |
| out = client.chat_completion( | |
| messages, | |
| max_tokens=256, | |
| temperature=0.0, | |
| stream=False, | |
| ) | |
| response = "" | |
| for c in out.choices: | |
| response += c.message["content"] | |
| return response | |
| except Exception as e: | |
| print(f"Errore durante la generazione della risposta: {e}") | |
| return ( | |
| "⚠️ Impossibile generare la risposta in questo momento. Riprova più tardi." | |
| ) | |
| def verify_team(team_name: str): | |
| teams = load_registered_teams() | |
| if not teams: | |
| return "Si è verificato un errore sul server. Riprova più tardi." | |
| team_name = team_name.strip() | |
| if not team_name: | |
| return ( | |
| "⚠️ Inserisci il nome del team registrato prima di procedere.", | |
| *PROMPT_LOCKED, | |
| TEAM_PANEL_VISIBLE, | |
| gr.update(value=INTRO_DEFAULT), | |
| ) | |
| TEAM = teams.get(team_name.casefold()) | |
| print(TEAM) | |
| official_name = TEAM["name"] | |
| if official_name: | |
| return ( | |
| "✅ Accesso abilitato. Puoi procedere con il prompt.", | |
| *PROMPT_UNLOCKED, | |
| TEAM_PANEL_HIDDEN, | |
| gr.update(value=INTRO_VERIFIED_TEMPLATE.format(team=official_name)), | |
| ) | |
| return ( | |
| "❌ Il team indicato non risulta registrato. Verifica il nome oppure contatta gli organizzatori per assistenza.", | |
| *PROMPT_LOCKED, | |
| TEAM_PANEL_VISIBLE, | |
| gr.update(value=INTRO_DEFAULT), | |
| ) | |
| def answer_prompt(prompt: str, team_name: str): | |
| prompt = prompt.strip() | |
| if not prompt: | |
| return ( | |
| "⚠️ Scrivi un prompt prima di inviarlo.", | |
| gr.update(), | |
| gr.update(), | |
| gr.update(), | |
| ) | |
| reply = generate_response(prompt) | |
| teams = load_registered_teams() | |
| TEAM = teams.get(team_name.strip().casefold()) | |
| print(TEAM) | |
| result = supabase.table("submissions").insert({ | |
| "team_id": TEAM["id"], | |
| "prompt": prompt, | |
| "response": reply, | |
| "model": model_name, | |
| "score": 1, | |
| }).execute() | |
| print(result) | |
| return ( | |
| reply, | |
| gr.update(interactive=False), | |
| gr.update(interactive=False), | |
| gr.update(interactive=True), | |
| ) | |
| def reset_session(): | |
| """Reset submission state and clear prompt/response fields.""" | |
| return ( | |
| "✅ Sessione azzerata. Puoi inviare un nuovo prompt.", | |
| gr.update(interactive=True), | |
| gr.update(value="", interactive=True), | |
| gr.update(value=""), | |
| gr.update(interactive=False), | |
| ) | |
| def main(): | |
| with gr.Blocks(theme=gr.themes.Default()) as demo: | |
| intro_message = gr.Markdown(INTRO_DEFAULT) | |
| with gr.Column(variant="panel") as team_panel: | |
| status_message = gr.Markdown("**Inserisci il nome del tuo team**") | |
| with gr.Row(): | |
| team_name = gr.Textbox( | |
| container=False, | |
| placeholder="Nome del team", | |
| lines=1, | |
| max_lines=1, | |
| scale=7, | |
| ) | |
| verify_button = gr.Button("Verifica", variant="primary") | |
| with gr.Column(variant="panel", visible=False) as prompt_group: | |
| gr.Markdown("**Prompt**") | |
| prompt_box = gr.Textbox( | |
| label="Prompt", | |
| placeholder="Inserisci qui il prompt da testare", | |
| container=False, | |
| lines=6, | |
| ) | |
| with gr.Row(): | |
| submit_button = gr.Button("Genera", variant="primary") | |
| reset_button = gr.Button("Reset", variant="secondary", interactive=False) | |
| gr.Markdown("**Risposta del chatbot**") | |
| response_box = gr.Textbox( | |
| label="Risposta del chatbot", | |
| container=False, | |
| lines=8, | |
| interactive=False, | |
| placeholder="", | |
| show_copy_button=True, | |
| ) | |
| verify_button.click( | |
| verify_team, | |
| show_progress="hidden", | |
| inputs=[team_name], | |
| outputs=[ | |
| status_message, | |
| prompt_group, | |
| prompt_box, | |
| submit_button, | |
| response_box, | |
| reset_button, | |
| team_panel, | |
| intro_message, | |
| ], | |
| ) | |
| submit_button.click( | |
| answer_prompt, | |
| inputs=[prompt_box, team_name], | |
| outputs=[ | |
| response_box, | |
| submit_button, | |
| prompt_box, | |
| reset_button, | |
| ], | |
| ) | |
| reset_button.click( | |
| reset_session, | |
| outputs=[ | |
| status_message, | |
| submit_button, | |
| prompt_box, | |
| response_box, | |
| reset_button, | |
| ], | |
| ) | |
| demo.launch() | |
| if __name__ == "__main__": | |
| main() | |