Update app.py
Browse files
app.py
CHANGED
|
@@ -4,46 +4,53 @@ import os
|
|
| 4 |
import time
|
| 5 |
|
| 6 |
# --- RECUPERO TOKEN ---
|
| 7 |
-
# Assicurati di avere HF_TOKEN nei Secrets!
|
| 8 |
token = os.environ.get("HF_TOKEN")
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
|
|
|
|
|
|
| 12 |
headers = {"Authorization": f"Bearer {token}"}
|
| 13 |
|
| 14 |
def query_huggingface_api(payload):
|
| 15 |
"""
|
| 16 |
-
|
| 17 |
-
Se il modello si sta caricando, aspetta e riprova.
|
| 18 |
"""
|
| 19 |
retry_count = 0
|
| 20 |
max_retries = 5
|
| 21 |
|
| 22 |
while retry_count < max_retries:
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
# CASO: IL MODELLO SI STA CARICANDO (Tipico alla seconda interazione)
|
| 33 |
-
if "error" in error_data and "loading" in error_data["error"]:
|
| 34 |
-
wait_time = error_data.get("estimated_time", 5)
|
| 35 |
-
print(f"Modello in caricamento... attendo {wait_time} secondi.")
|
| 36 |
-
time.sleep(wait_time)
|
| 37 |
retry_count += 1
|
| 38 |
-
continue # Riprova il ciclo
|
| 39 |
|
| 40 |
-
|
| 41 |
-
return error_data
|
| 42 |
-
|
| 43 |
-
return {"error": "Timeout: Il server non ha risposto dopo vari tentativi."}
|
| 44 |
|
| 45 |
def rispondi_a_marco(messaggio, storia):
|
| 46 |
-
# 1. Prompt
|
| 47 |
system_prompt = """
|
| 48 |
SEI MARCO, 14 ANNI.
|
| 49 |
Sei uno studente svogliato, sarcastico e ribelle.
|
|
@@ -52,43 +59,42 @@ def rispondi_a_marco(messaggio, storia):
|
|
| 52 |
Rispondi in 1-2 frasi.
|
| 53 |
"""
|
| 54 |
|
| 55 |
-
# 2. Costruzione
|
| 56 |
-
# Creiamo la lista messaggi pulita per evitare errori di formato
|
| 57 |
messages = [{"role": "system", "content": system_prompt}]
|
| 58 |
|
| 59 |
for turno in storia:
|
| 60 |
-
if turno[0] and turno[1]:
|
| 61 |
messages.append({"role": "user", "content": str(turno[0])})
|
| 62 |
messages.append({"role": "assistant", "content": str(turno[1])})
|
| 63 |
|
| 64 |
messages.append({"role": "user", "content": messaggio})
|
| 65 |
|
| 66 |
-
# 3.
|
| 67 |
payload = {
|
| 68 |
"messages": messages,
|
| 69 |
"max_tokens": 150,
|
| 70 |
"temperature": 0.8,
|
| 71 |
-
"stream": False
|
| 72 |
}
|
| 73 |
|
| 74 |
-
# 4. Invio
|
| 75 |
risultato = query_huggingface_api(payload)
|
| 76 |
|
| 77 |
-
# 5.
|
| 78 |
-
if isinstance(risultato, list) and 'generated_text' in risultato[0]:
|
| 79 |
return risultato[0]['generated_text']
|
| 80 |
-
elif 'choices' in risultato:
|
| 81 |
return risultato['choices'][0]['message']['content']
|
| 82 |
-
elif 'error' in risultato:
|
| 83 |
-
return f"⚠️ ERRORE
|
| 84 |
else:
|
| 85 |
-
return f"⚠️ RISPOSTA
|
| 86 |
|
| 87 |
-
# Interfaccia
|
| 88 |
demo = gr.ChatInterface(
|
| 89 |
fn=rispondi_a_marco,
|
| 90 |
-
title="Project Janus: Marco (
|
| 91 |
-
description="
|
| 92 |
)
|
| 93 |
|
| 94 |
if __name__ == "__main__":
|
|
|
|
| 4 |
import time
|
| 5 |
|
| 6 |
# --- RECUPERO TOKEN ---
|
|
|
|
| 7 |
token = os.environ.get("HF_TOKEN")
|
| 8 |
|
| 9 |
+
# --- NUOVO INDIRIZZO (CORRETTO) ---
|
| 10 |
+
# Il server ci ha chiesto di usare "router.huggingface.co". Eccolo:
|
| 11 |
+
API_URL = "https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-7B-Instruct"
|
| 12 |
+
|
| 13 |
headers = {"Authorization": f"Bearer {token}"}
|
| 14 |
|
| 15 |
def query_huggingface_api(payload):
|
| 16 |
"""
|
| 17 |
+
Invia il messaggio. Se il server sta caricando (errore 503), aspetta e riprova.
|
|
|
|
| 18 |
"""
|
| 19 |
retry_count = 0
|
| 20 |
max_retries = 5
|
| 21 |
|
| 22 |
while retry_count < max_retries:
|
| 23 |
+
try:
|
| 24 |
+
response = requests.post(API_URL, headers=headers, json=payload, timeout=10)
|
| 25 |
+
|
| 26 |
+
# Se va tutto bene (200)
|
| 27 |
+
if response.status_code == 200:
|
| 28 |
+
return response.json()
|
| 29 |
+
|
| 30 |
+
# Gestione Errori
|
| 31 |
+
error_data = response.json()
|
| 32 |
+
|
| 33 |
+
# CASO SPECIALE: "Model is loading"
|
| 34 |
+
# Questo succede spesso alla seconda interazione sui server free.
|
| 35 |
+
# Noi aspettiamo invece di dare errore.
|
| 36 |
+
if "error" in error_data and "loading" in error_data["error"]:
|
| 37 |
+
wait_time = error_data.get("estimated_time", 5)
|
| 38 |
+
print(f"Modello in caricamento... attendo {wait_time}s")
|
| 39 |
+
time.sleep(wait_time)
|
| 40 |
+
retry_count += 1
|
| 41 |
+
continue
|
| 42 |
+
|
| 43 |
+
return error_data
|
| 44 |
|
| 45 |
+
except Exception as e:
|
| 46 |
+
# Se la connessione cade, riproviamo
|
| 47 |
+
time.sleep(2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
retry_count += 1
|
|
|
|
| 49 |
|
| 50 |
+
return {"error": "Timeout: Il server non risponde dopo vari tentativi."}
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
def rispondi_a_marco(messaggio, storia):
|
| 53 |
+
# 1. Prompt
|
| 54 |
system_prompt = """
|
| 55 |
SEI MARCO, 14 ANNI.
|
| 56 |
Sei uno studente svogliato, sarcastico e ribelle.
|
|
|
|
| 59 |
Rispondi in 1-2 frasi.
|
| 60 |
"""
|
| 61 |
|
| 62 |
+
# 2. Costruzione Messaggi
|
|
|
|
| 63 |
messages = [{"role": "system", "content": system_prompt}]
|
| 64 |
|
| 65 |
for turno in storia:
|
| 66 |
+
if turno[0] and turno[1]:
|
| 67 |
messages.append({"role": "user", "content": str(turno[0])})
|
| 68 |
messages.append({"role": "assistant", "content": str(turno[1])})
|
| 69 |
|
| 70 |
messages.append({"role": "user", "content": messaggio})
|
| 71 |
|
| 72 |
+
# 3. Payload
|
| 73 |
payload = {
|
| 74 |
"messages": messages,
|
| 75 |
"max_tokens": 150,
|
| 76 |
"temperature": 0.8,
|
| 77 |
+
"stream": False
|
| 78 |
}
|
| 79 |
|
| 80 |
+
# 4. Invio
|
| 81 |
risultato = query_huggingface_api(payload)
|
| 82 |
|
| 83 |
+
# 5. Estrazione Risposta
|
| 84 |
+
if isinstance(risultato, list) and len(risultato) > 0 and 'generated_text' in risultato[0]:
|
| 85 |
return risultato[0]['generated_text']
|
| 86 |
+
elif isinstance(risultato, dict) and 'choices' in risultato:
|
| 87 |
return risultato['choices'][0]['message']['content']
|
| 88 |
+
elif isinstance(risultato, dict) and 'error' in risultato:
|
| 89 |
+
return f"⚠️ ERRORE: {risultato['error']}"
|
| 90 |
else:
|
| 91 |
+
return f"⚠️ RISPOSTA IMPREVISTA: {str(risultato)}"
|
| 92 |
|
| 93 |
+
# Interfaccia
|
| 94 |
demo = gr.ChatInterface(
|
| 95 |
fn=rispondi_a_marco,
|
| 96 |
+
title="Project Janus: Marco (Qwen Router)",
|
| 97 |
+
description="Marco è pronto. Se ritarda, sta caricando la risposta."
|
| 98 |
)
|
| 99 |
|
| 100 |
if __name__ == "__main__":
|