Download app.py from Pierber/Test1: direct link, hf CLI and curl.
- Browser
- Download file 2.7 kB
-
https://huggingface.co/spaces/Pierber/Test1/resolve/main/app.py
- Command line
-
hf download hf://spaces/Pierber/Test1/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Pierber/Test1/resolve/main/app.py
2.7 kB
| import gradio as gr | |
| import requests | |
| import json | |
| # --- CONFIGURAZIONE --- | |
| API_KEY = "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" | |
| URL = "https://api.groq.com/openai/v1/chat/completions" | |
| def rispondi_a_marco(messaggio, storia): | |
| # 1. Prompt | |
| system_prompt = """ | |
| SEI MARCO, 14 ANNI. | |
| Sei uno studente svogliato, ribelle e sarcastico. | |
| Odi la scuola. Rispondi male ai professori. | |
| Usa slang ("Boh", "Che ansia", "Raga", "Cringe"). | |
| Rispondi in massimo 2 frasi. | |
| """ | |
| # Inizializziamo i messaggi con il sistema | |
| messages = [{"role": "system", "content": system_prompt}] | |
| # --- BLOCCO DI SICUREZZA MEMORIA --- | |
| # Questo ciclo 'try-except' impedisce il crash se la storia è formattata male | |
| try: | |
| for turno in storia: | |
| # Controllo rigoroso: accettiamo solo se sono stringhe valide | |
| if isinstance(turno, (list, tuple)) and len(turno) == 2: | |
| user_msg = str(turno[0]) if turno[0] is not None else "" | |
| bot_msg = str(turno[1]) if turno[1] is not None else "" | |
| if user_msg and bot_msg: | |
| messages.append({"role": "user", "content": user_msg}) | |
| messages.append({"role": "assistant", "content": bot_msg}) | |
| except Exception as e: | |
| # Se c'è un errore nella memoria, lo stampiamo ma NON FERMIAMO IL PROGRAMMA | |
| print(f"Errore lettura memoria: {e}") | |
| # Continuiamo senza memoria vecchia, meglio smemorato che morto. | |
| # Aggiungiamo il messaggio nuovo | |
| messages.append({"role": "user", "content": str(messaggio)}) | |
| # 2. Configurazione Dati (Payload) | |
| payload = { | |
| "model": "llama-3.1-8b-instant", # Modello Veloce | |
| "messages": messages, | |
| "temperature": 0.8, | |
| "max_tokens": 150, | |
| "stream": False # NO STREAMING (per evitare crash socket) | |
| } | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {API_KEY}" | |
| } | |
| # 3. Chiamata Diretta (Blindata) | |
| try: | |
| response = requests.post(URL, headers=headers, json=payload, timeout=20) | |
| if response.status_code == 200: | |
| data = response.json() | |
| return data['choices'][0]['message']['content'] | |
| else: | |
| return f"⚠️ ERRORE API ({response.status_code}): {response.text}" | |
| except Exception as e: | |
| return f"⚠️ ERRORE CRITICO: {str(e)}" | |
| # --- INTERFACCIA --- | |
| # Semplice e pulita | |
| demo = gr.ChatInterface( | |
| fn=rispondi_a_marco, | |
| title="Project Janus: Marco (Safe Mode)", | |
| description="Marco (Versione Anti-Crash)" | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |