Spaces:
Paused
Paused
Download app.py from Davideconsole/ScoutPro: direct link, hf CLI and curl.
- Browser
- Download file 21.4 kB
-
https://huggingface.co/spaces/Davideconsole/ScoutPro/resolve/main/app.py
- Command line
-
hf download hf://spaces/Davideconsole/ScoutPro/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Davideconsole/ScoutPro/resolve/main/app.py
21.4 kB
| # -*- coding: utf-8 -*- | |
| """Untitled2.ipynb | |
| Automatically generated by Colab. | |
| Original file is located at | |
| https://colab.research.google.com/drive/1byXUq4f1TylXBhMW0Ai-WhXuSFEPzBMP | |
| """ | |
| !pip install -q google-genai gradio | |
| !pip install supabase | |
| !pip install --upgrade gradio | |
| !pip install -q google-genai gradio | |
| import os | |
| import uuid | |
| import mimetypes | |
| import html | |
| import gradio as gr | |
| from google import genai | |
| from google.genai import types | |
| from supabase import create_client | |
| # --------------------------------------------------------- | |
| # CONFIGURAZIONE (Variabili d'ambiente) | |
| # --------------------------------------------------------- | |
| GEMINI_API_KEY = "AQ.Ab8RN6IwLT--FS3cKjxy-NFdA03tSil4gtcaHnLx4Mg8SxUxAQ" | |
| SUPABASE_URL = "https://qhwbrrjxetxohnodywun.supabase.co" | |
| SUPABASE_SERVICE_KEY = "sb_secret__-yUO5uakdEmW1Jln-uaKQ_dhDrNy6i" | |
| MODELLO = "gemini-3.8-flash" | |
| BUCKET = "allegati" | |
| MAX_ALLEGATI = 5 | |
| MAX_MB = 10 | |
| client = genai.Client(api_key=GEMINI_API_KEY) | |
| supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY) if SUPABASE_URL and SUPABASE_SERVICE_KEY else None | |
| SYSTEM_PROMPT_CHAT = ( | |
| "Sei l'assistente virtuale ufficiale di un portale dedicato alle Case Scout, agli Oratori " | |
| "e alle Attività Giovanili in Italia. " | |
| "Il tuo compito è aiutare capi scout, educatori e ragazzi a trovare le attività, i luoghi " | |
| "(basi scout, oratori) o le idee di route/campi più adatte alle loro richieste. " | |
| "Rispondi in modo caloroso e chiaro, con risposte ben strutturate (elenchi brevi, grassetto per i nomi)." | |
| ) | |
| # --------------------------------------------------------- | |
| # CHAT OTTIMIZZATA PER LA VELOCITÀ | |
| # --------------------------------------------------------- | |
| def chat_consigli_scout(messaggio, cronologia): | |
| contenuti = [] | |
| ultimi_turni = cronologia[-4:] if len(cronologia) > 4 else cronologia | |
| for turno in ultimi_turni: | |
| ruolo = "user" if turno["role"] == "user" else "model" | |
| contenuti.append( | |
| types.Content(role=ruolo, parts=[types.Part.from_text(text=turno["content"])]) | |
| ) | |
| contenuti.append(types.Content(role="user", parts=[types.Part.from_text(text=messaggio)])) | |
| try: | |
| risposta = "" | |
| stream = client.models.generate_content_stream( | |
| model=MODELLO, | |
| contents=contenuti, | |
| config=types.GenerateContentConfig( | |
| system_instruction=SYSTEM_PROMPT_CHAT, | |
| temperature=0.25, | |
| max_output_tokens=650 | |
| ), | |
| ) | |
| for chunk in stream: | |
| if chunk.text: | |
| risposta += chunk.text | |
| yield risposta | |
| except Exception: | |
| yield "⚠️ Il servizio è momentaneamente sovraccarico. Riprova tra qualche secondo." | |
| # --------------------------------------------------------- | |
| # DATABASE E FILE (Supabase) | |
| # --------------------------------------------------------- | |
| def esito_html(tipo, titolo, testo): | |
| icone = {"ok": "✅", "warn": "⚠️"} | |
| return ( | |
| f'<div class="esito {tipo}"><div class="esito-icon">{icone[tipo]}</div>' | |
| f"<div><strong>{html.escape(titolo)}</strong><p>{html.escape(testo)}</p></div></div>" | |
| ) | |
| def carica_allegati(file_objs, cartella): | |
| if not file_objs: | |
| return [] | |
| if not isinstance(file_objs, list): | |
| file_objs = [file_objs] | |
| if len(file_objs) > MAX_ALLEGATI: | |
| raise ValueError(f"Puoi allegare al massimo {MAX_ALLEGATI} file.") | |
| urls = [] | |
| for f in file_objs: | |
| percorso = f if isinstance(f, str) else f.name | |
| if os.path.getsize(percorso) > MAX_MB * 1024 * 1024: | |
| raise ValueError(f"Un file supera i {MAX_MB} MB.") | |
| estensione = os.path.splitext(percorso)[1].lower() | |
| nome_remoto = f"{cartella}/{uuid.uuid4().hex}{estensione}" | |
| mime = mimetypes.guess_type(percorso)[0] or "application/octet-stream" | |
| with open(percorso, "rb") as fh: | |
| supabase.storage.from_(BUCKET).upload( | |
| path=nome_remoto, file=fh.read(), file_options={"content-type": mime} | |
| ) | |
| urls.append(supabase.storage.from_(BUCKET).get_public_url(nome_remoto)) | |
| return urls | |
| def salva(tabella, dati, file_objs, progress): | |
| if supabase is None: | |
| return esito_html( | |
| "warn", "Database non collegato", | |
| "Mancano SUPABASE_URL e SUPABASE_SERVICE_KEY tra le variabili d'ambiente.", | |
| ) | |
| try: | |
| progress(0.3, desc="Caricamento allegati in corso…") | |
| dati["allegati"] = carica_allegati(file_objs, tabella) | |
| progress(0.8, desc="Salvataggio record…") | |
| supabase.table(tabella).insert(dati).execute() | |
| n = len(dati["allegati"]) | |
| extra = f" con {n} allegat{'o' if n == 1 else 'i'}" if n else "" | |
| return esito_html("ok", "Proposta inviata con successo", f"Grazie! L'abbiamo salvata{extra} e ora è consultabile nell'archivio.") | |
| except ValueError as e: | |
| return esito_html("warn", "Controlla gli allegati", str(e)) | |
| except Exception as e: | |
| return esito_html("warn", "Errore di salvataggio", str(e)[:250]) | |
| def proponi_attivita(gruppo, branca, tipo, durata, partecipanti, descrizione, materiali, file_objs, progress=gr.Progress()): | |
| if not gruppo or not descrizione: | |
| return esito_html("warn", "Mancano dei dati", "Inserisci almeno il nome del gruppo e la descrizione dell'attività.") | |
| dati = { | |
| "gruppo": gruppo, "branca": branca, "tipo": tipo, "durata": durata, | |
| "partecipanti": int(partecipanti), "descrizione": descrizione, "materiali": materiali or None, | |
| } | |
| return salva("attivita", dati, file_objs, progress) | |
| def proponi_luogo(nome, tipo, localita, capienza, servizi, periodo, contatto, descrizione, file_objs, progress=gr.Progress()): | |
| if not nome or not localita or not descrizione: | |
| return esito_html("warn", "Mancano dei dati", "Inserisci almeno nome, località e descrizione del posto.") | |
| dati = { | |
| "nome": nome, "tipo": tipo, "localita": localita, "capienza": int(capienza), | |
| "servizi": servizi or [], "periodo": periodo, "contatto": contatto or None, "descrizione": descrizione, | |
| } | |
| return salva("luoghi", dati, file_objs, progress) | |
| # --------------------------------------------------------- | |
| # TEMA E STILE UI/UX | |
| # --------------------------------------------------------- | |
| tema = gr.themes.Soft( | |
| primary_hue=gr.themes.Color( | |
| c50="#eef5f0", c100="#d9e9de", c200="#b5d3bf", c300="#88b99a", c400="#5a9a74", | |
| c500="#2f7a52", c600="#1f6340", c700="#1a5035", c800="#153f2a", c900="#0f2e1e", c950="#0a2015", | |
| ), | |
| secondary_hue="amber", | |
| neutral_hue="stone", | |
| radius_size=gr.themes.sizes.radius_lg, | |
| font=[gr.themes.GoogleFont("Nunito Sans"), "system-ui", "sans-serif"], | |
| font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "monospace"], | |
| ).set( | |
| body_background_fill="#f4f7f4", | |
| block_background_fill="white", | |
| block_border_width="0px", | |
| block_shadow="none", | |
| button_primary_background_fill="#1f6340", | |
| button_primary_background_fill_hover="#153f2a", | |
| button_primary_text_color="white", | |
| input_background_fill="#f9fbf9", | |
| input_border_color="#d4e2d8", | |
| ) | |
| CSS = """ | |
| @import url('https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,500;12..96,700;12..96,800&display=swap'); | |
| .gradio-container { max-width: 1040px !important; margin: 0 auto !important; padding: 20px 12px !important; } | |
| footer { display: none !important; } | |
| #hero { | |
| position: relative; overflow: hidden; text-align: center; color: #fff; | |
| border-radius: 28px; padding: 44px 24px 110px; margin-bottom: 16px; | |
| background: | |
| radial-gradient(circle at 50% 0%, rgba(242,193,78,.3), transparent 60%), | |
| linear-gradient(175deg, #0f2e1e 0%, #1a5035 55%, #2f7a52 100%); | |
| box-shadow: 0 20px 40px -15px rgba(15,46,30,.4); | |
| } | |
| #hero .badge { | |
| width: 76px; height: 76px; margin: 0 auto 16px; border-radius: 50%; | |
| display: flex; align-items: center; justify-content: center; font-size: 2.1rem; | |
| background: #f2c14e; color: #123a29; | |
| box-shadow: 0 0 0 10px rgba(242,193,78,.2), 0 0 0 22px rgba(242,193,78,.08); | |
| } | |
| #hero h1 { | |
| font-family: 'Bricolage Grotesque', sans-serif; font-weight: 800; color: #fff; | |
| font-size: clamp(2.2rem, 5vw, 3.4rem); line-height: 1.1; letter-spacing: -0.02em; | |
| margin: 0 0 12px; text-align: center; | |
| } | |
| #hero p { max-width: 580px; margin: 0 auto; font-size: 1.1rem; line-height: 1.6; color: #d6e8dc; text-align: center; } | |
| #hero svg { position: absolute; left: 0; right: 0; bottom: -1px; width: 100%; height: 100px; } | |
| .tab-wrapper, .tab-container, div[role="tablist"] { justify-content: center !important; } | |
| .tab-container { gap: 8px; border-bottom: none !important; margin-bottom: 12px; } | |
| .tab-container button, button[role="tab"] { | |
| font-family: 'Bricolage Grotesque', sans-serif !important; | |
| font-weight: 700 !important; font-size: 1.05rem !important; | |
| padding: 10px 22px !important; border-radius: 999px !important; border: none !important; | |
| color: #3d5446 !important; background: #e6efe8 !important; transition: all 0.2s ease; | |
| } | |
| .tab-container button.selected, button[role="tab"][aria-selected="true"] { | |
| background: #1f6340 !important; color: #fff !important; | |
| box-shadow: 0 4px 12px rgba(31,99,64,0.25); | |
| } | |
| .tab-container::after, .tab-container button::after { display: none !important; } | |
| .card { | |
| background: #fff !important; border-radius: 28px !important; padding: 32px !important; | |
| box-shadow: 0 4px 20px -4px rgba(15,46,30,.08), 0 12px 32px -16px rgba(15,46,30,.15) !important; | |
| } | |
| .sezione-titolo { text-align: center; margin: 0 0 24px; } | |
| .sezione-titolo h2 { | |
| font-family: 'Bricolage Grotesque', sans-serif; font-weight: 800; font-size: 1.8rem; | |
| color: #123a29; margin: 0 0 6px; text-align: center; | |
| } | |
| .sezione-titolo p { color: #55655a; margin: 0 auto; max-width: 580px; line-height: 1.5; text-align: center; } | |
| #chat-box { border-radius: 20px; border: 1px solid #e1ebe3; background: #fff; } | |
| #chat-box .message { font-size: 1.02rem; line-height: 1.6; border-radius: 14px; padding: 12px 16px; } | |
| #chat-box .bot { background: #eef5f0 !important; border: 1px solid #d9e9de !important; color: #0f2e1e !important; } | |
| #chat-box .user { background: #1f6340 !important; color: #fff !important; } | |
| #chat-box .user * { color: #fff !important; } | |
| .card label > span, .card .block > label > span { font-weight: 700; color: #1f3a2b; font-size: 0.95rem; } | |
| .pannello-esito { | |
| background: linear-gradient(180deg, #f4f8f5, #ecf4ee) !important; border-radius: 20px !important; | |
| padding: 22px !important; display: flex; flex-direction: column; justify-content: center; | |
| } | |
| .hint { color: #4b5a50; text-align: center; padding: 30px 12px; line-height: 1.6; } | |
| .hint .big { font-size: 2.5rem; display: block; margin-bottom: 8px; } | |
| .hint strong { font-family: 'Bricolage Grotesque', sans-serif; font-size: 1.2rem; color: #123a29; } | |
| .esito { display: flex; gap: 14px; align-items: flex-start; border-radius: 16px; padding: 18px; border-left: 6px solid; box-shadow: 0 2px 8px rgba(0,0,0,0.03); } | |
| .esito-icon { font-size: 1.6rem; line-height: 1; } | |
| .esito strong { font-family: 'Bricolage Grotesque', sans-serif; font-size: 1.15rem; display: block; margin-bottom: 4px; } | |
| .esito p { margin: 0; line-height: 1.5; font-size: 0.96rem; } | |
| .esito.ok { background: #e6f4ea; border-color: #2f7a52; color: #123a29; } | |
| .esito.warn { background: #fff8e6; border-color: #f2c14e; color: #5a4300; } | |
| #foot { text-align: center; color: #6b7a70; font-size: .9rem; padding: 28px 12px 12px; } | |
| """ | |
| HERO = """ | |
| <div id="hero"> | |
| <div class="badge" aria-hidden="true">⚜️</div> | |
| <h1>Assistente virtuale<br>per scout e oratori</h1> | |
| <p>Trova basi, route e idee per la tua prossima uscita, oppure condividi con la community un'attività o un posto che hai scoperto.</p> | |
| <svg viewBox="0 0 1200 100" preserveAspectRatio="none" aria-hidden="true"> | |
| <path d="M0,100 L0,60 L130,25 L250,70 L380,15 L520,75 L650,35 L780,80 L920,20 L1050,65 L1150,40 L1200,65 L1200,100 Z" fill="#f4f7f4" opacity=".5"/> | |
| <path d="M0,100 L0,80 L90,50 L210,85 L340,45 L480,90 L620,55 L760,92 L900,50 L1040,88 L1140,65 L1200,85 L1200,100 Z" fill="#f4f7f4"/> | |
| </svg> | |
| </div> | |
| """ | |
| FOOTER = ( | |
| '<div id="foot">Realizzato con cura per capi, educatori e ragazzi. Le risposte dell\'assistente sono generate da un\'AI: ' | |
| "verifica sempre date, contatti e disponibilità prima di organizzare.</div>" | |
| ) | |
| PLACEHOLDER_CHAT = ( | |
| "<div style='text-align:center;padding:40px 16px;color:#55655a'>" | |
| "<div style='font-size:2.5rem;margin-bottom:8px'>⚜️</div>" | |
| "<h3 style='font-family:Bricolage Grotesque,sans-serif;font-size:1.3rem;color:#123a29;margin:0 0 6px'>Da dove partiamo?</h3>" | |
| "<p style='max-width:380px;margin:0 auto;line-height:1.5'>Chiedimi una base scout, un oratorio o un'idea di route.<br>" | |
| "Fornisci dettagli come regione o numero di partecipanti per risposte mirate!</p></div>" | |
| ) | |
| TIPI_FILE = [".pdf", ".png", ".jpg", ".jpeg", ".webp"] | |
| def titolo_sezione(titolo, sottotitolo): | |
| return f'<div class="sezione-titolo"><h2>{titolo}</h2><p>{sottotitolo}</p></div>' | |
| def box_attesa(titolo, testo, icona): | |
| return f'<div class="hint"><span class="big">{icona}</span><strong>{titolo}</strong><br>{testo}</div>' | |
| # --------------------------------------------------------- | |
| # COSTRUZIONE INTERFACCIA GRADIO | |
| # --------------------------------------------------------- | |
| with gr.Blocks(title="Assistente virtuale per scout e oratori") as demo: | |
| gr.HTML(HERO) | |
| with gr.Tabs(): | |
| # ---------- 1. ASSISTENTE ---------- | |
| with gr.Tab("💬 Assistente virtuale"): | |
| with gr.Column(elem_classes="card"): | |
| with gr.Row(elem_id="chat-top-bar"): | |
| gr.HTML(titolo_sezione( | |
| "Chiedi all'assistente", | |
| "Descrivi cosa cerchi: una base, un'attività, un'idea per un hike o per un campo.", | |
| )) | |
| with gr.Row(): | |
| btn_pulisci = gr.Button("🔄 Nuova Conversazione", scale=0, min_width=170, variant="secondary", size="sm") | |
| chat_interface = gr.ChatInterface( | |
| fn=chat_consigli_scout, | |
| chatbot=gr.Chatbot( | |
| height=500, | |
| elem_id="chat-box", | |
| show_label=False, | |
| placeholder=PLACEHOLDER_CHAT, | |
| avatar_images=(None, "https://em-content.zobj.net/source/apple/391/fleur-de-lis_269c-fe0f.png"), | |
| ), | |
| textbox=gr.Textbox( | |
| placeholder="Es. Una base scout in Lombardia per un campo estivo di reparto con 30 persone…", | |
| container=False, | |
| scale=7, | |
| ), | |
| examples=[ | |
| "Mi consigli una base scout adatta per un'uscita di branco?", | |
| "Che attività possiamo fare in oratorio per ragazzi di 14 anni?", | |
| "Cerco idee per un hike di squadriglia in montagna", | |
| ], | |
| ) | |
| btn_pulisci.click(fn=lambda: None, outputs=chat_interface.chatbot_state, queue=False).then( | |
| fn=lambda: [], outputs=chat_interface.chatbot, queue=False | |
| ) | |
| # ---------- 2. PROPONI ATTIVITÀ ---------- | |
| with gr.Tab("🎲 Proponi un'attività"): | |
| with gr.Column(elem_classes="card"): | |
| gr.HTML(titolo_sezione( | |
| "Proponi un'attività", | |
| "Un gioco, un hike, una veglia, un laboratorio: raccontaci cosa ha funzionato con il tuo gruppo.", | |
| )) | |
| with gr.Row(equal_height=False): | |
| with gr.Column(scale=3, min_width=300): | |
| a_gruppo = gr.Textbox(label="Gruppo, reparto o oratorio", placeholder="Es. Milano 12 – Reparto Orsa") | |
| with gr.Row(): | |
| a_branca = gr.Dropdown( | |
| choices=["Lupetti / Coccinelle", "Esploratori / Guide", "Rover / Scolte", | |
| "Oratorio / Giovanissimi", "Altro"], | |
| label="Per chi è", value="Esploratori / Guide", | |
| ) | |
| a_tipo = gr.Dropdown( | |
| choices=["Gioco", "Hike / Route", "Veglia / Spiritualità", "Laboratorio / Espressione", | |
| "Servizio", "Cerimonia / Tradizione", "Altro"], | |
| label="Tipo di attività", value="Gioco", | |
| ) | |
| with gr.Row(): | |
| a_durata = gr.Dropdown( | |
| choices=["Meno di 1 ora", "1–2 ore", "Mezza giornata", "Giornata intera", "Più giorni"], | |
| label="Durata", value="1–2 ore", | |
| ) | |
| a_part = gr.Slider(minimum=2, maximum=100, value=20, step=1, label="Partecipanti") | |
| a_desc = gr.Textbox(label="Come si svolge", lines=4, placeholder="Obiettivo, regole, svolgimento…") | |
| a_mat = gr.Textbox(label="Materiali necessari (facoltativo)", placeholder="Es. corde, bende, cartoncini…") | |
| a_file = gr.File(label=f"Allegati (fino a {MAX_ALLEGATI}, max {MAX_MB} MB l'uno)", | |
| file_count="multiple", file_types=TIPI_FILE) | |
| a_btn = gr.Button("Invia proposta", variant="primary", size="lg") | |
| with gr.Column(scale=2, min_width=260, elem_classes="pannello-esito"): | |
| a_out = gr.HTML(box_attesa( | |
| "Qui vedrai l'esito", | |
| "Compila il modulo e premi «Invia proposta».", | |
| "🎲", | |
| )) | |
| a_btn.click( | |
| fn=proponi_attivita, | |
| inputs=[a_gruppo, a_branca, a_tipo, a_durata, a_part, a_desc, a_mat, a_file], | |
| outputs=a_out, | |
| ) | |
| # ---------- 3. PROPONI LUOGO ---------- | |
| with gr.Tab("🏕️ Proponi una base o un luogo"): | |
| with gr.Column(elem_classes="card"): | |
| gr.HTML(titolo_sezione( | |
| "Proponi una base o un luogo", | |
| "Basi scout, oratori, case per ferie, prati per campi e posti per le uscite: aiuta gli altri a trovarli.", | |
| )) | |
| with gr.Row(equal_height=False): | |
| with gr.Column(scale=3, min_width=300): | |
| l_nome = gr.Textbox(label="Nome del posto", placeholder="Es. Base scout Il Rovere") | |
| with gr.Row(): | |
| l_tipo = gr.Dropdown( | |
| choices=["Base scout", "Oratorio", "Casa per ferie / Ostello", "Campo / Prato", | |
| "Rifugio / Baita", "Sede per uscite", "Altro"], | |
| label="Tipo di luogo", value="Base scout", | |
| ) | |
| l_cap = gr.Slider(minimum=5, maximum=300, value=40, step=5, label="Capienza (persone)") | |
| l_loc = gr.Textbox(label="Località", placeholder="Es. Clusone (BG), Lombardia") | |
| l_serv = gr.CheckboxGroup( | |
| choices=["Cucina", "Bagni", "Docce", "Acqua potabile", "Spazio esterno", "Riscaldamento", | |
| "Accessibile (disabilità)", "Parcheggio"], | |
| label="Servizi disponibili", | |
| ) | |
| l_per = gr.Dropdown( | |
| choices=["Tutto l'anno", "Solo estate", "Primavera / Autunno", "Solo inverno"], | |
| label="Periodo di utilizzo", value="Tutto l'anno", | |
| ) | |
| l_cont = gr.Textbox(label="Contatto per prenotare (facoltativo)", placeholder="Sito, email o telefono") | |
| l_desc = gr.Textbox(label="Descrivi il posto", lines=4, | |
| placeholder="Com'è fatto, come si arriva, cosa lo rende speciale…") | |
| l_file = gr.File(label=f"Foto o documenti (fino a {MAX_ALLEGATI}, max {MAX_MB} MB l'uno)", | |
| file_count="multiple", file_types=TIPI_FILE) | |
| l_btn = gr.Button("Invia proposta", variant="primary", size="lg") | |
| with gr.Column(scale=2, min_width=260, elem_classes="pannello-esito"): | |
| l_out = gr.HTML(box_attesa( | |
| "Qui vedrai l'esito", | |
| "Compila il modulo e premi «Invia proposta».", | |
| "🏕️", | |
| )) | |
| l_btn.click( | |
| fn=proponi_luogo, | |
| inputs=[l_nome, l_tipo, l_loc, l_cap, l_serv, l_per, l_cont, l_desc, l_file], | |
| outputs=l_out, | |
| ) | |
| gr.HTML(FOOTER) | |
| if __name__ == "__main__": | |
| import os | |
| port = int(os.environ.get("PORT", 7860)) | |
| demo.queue().launch(server_name="0.0.0.0", server_port=port, theme=tema, css=CSS) |