File size: 6,639 Bytes
cad72b6
 
 
 
d63ef26
 
 
cad72b6
82fe230
 
 
 
 
 
 
1ade13a
 
765dfc7
 
629bccb
 
4feec95
29c497f
1ade13a
82fe230
d63ef26
cad72b6
 
 
 
d63ef26
 
cad72b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63ef26
1ade13a
d63ef26
cad72b6
 
 
 
 
 
 
 
1ade13a
cad72b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4feec95
 
 
 
 
cad72b6
 
 
 
 
 
 
 
 
1ade13a
5d22746
1ade13a
cad72b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8f845
cad72b6
 
 
 
 
 
 
 
 
 
 
1ade13a
1d8f845
 
 
 
cea21bc
9ab5cc7
 
fc3a95c
9ab5cc7
86145ca
190a1e4
1ade13a
 
cad72b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8f845
cad72b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d63ef26
cad72b6
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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()