Pierber commited on
Commit
7b425df
·
verified ·
1 Parent(s): ec0b0f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -27
app.py CHANGED
@@ -1,55 +1,94 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
  import os
 
4
 
5
- # --- TOKEN ---
6
- # Assicurati che HF_TOKEN sia nei Secrets.
7
  token = os.environ.get("HF_TOKEN")
8
 
9
- # USIAMO QWEN 2.5 7B (Modello Cinese di Alibaba)
10
- # È veloce, stabile e parla italiano.
11
- client = InferenceClient("Qwen/Qwen2.5-7B-Instruct", token=token)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  def rispondi_a_marco(messaggio, storia):
14
- # Prompt Pedagogico
15
  system_prompt = """
16
  SEI MARCO, 14 ANNI.
17
  Sei uno studente svogliato, sarcastico e ribelle.
18
  Odi la scuola. Rispondi male ai professori.
19
  Usa slang ("Boh", "Che ansia", "Raga", "Cringe").
20
- Rispondi in massimo 2 frasi. Non essere mai servizievole.
21
  """
22
 
 
 
23
  messages = [{"role": "system", "content": system_prompt}]
24
 
25
- # Costruzione Memoria
26
  for turno in storia:
27
- if turno[0] and turno[1]:
28
  messages.append({"role": "user", "content": str(turno[0])})
29
  messages.append({"role": "assistant", "content": str(turno[1])})
30
 
31
  messages.append({"role": "user", "content": messaggio})
32
 
33
- try:
34
- # --- NO STREAMING (Per evitare errori di connessione) ---
35
- risposta = client.chat_completion(
36
- messages,
37
- max_tokens=150,
38
- stream=False,
39
- temperature=0.8
40
- )
41
-
42
- return risposta.choices[0].message.content
43
-
44
- except Exception as e:
45
- return f"⚠️ ERRORE: {str(e)}"
 
 
 
 
 
 
 
46
 
47
- # Interfaccia (PULITA, SENZA TEMA)
48
  demo = gr.ChatInterface(
49
  fn=rispondi_a_marco,
50
- title="Project Janus: Marco (Qwen 7B)",
51
- description="Motore: Qwen 2.5 (Alibaba). Stabile e Veloce."
52
- # Ho rimosso 'theme' per evitare il crash!
53
  )
54
 
55
  if __name__ == "__main__":
 
1
  import gradio as gr
2
+ import requests
3
  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
+ # URL del modello Qwen 7B (Veloce e Stabile)
11
+ API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-7B-Instruct"
12
+ headers = {"Authorization": f"Bearer {token}"}
13
+
14
+ def query_huggingface_api(payload):
15
+ """
16
+ Funzione che invia il messaggio e gestisce i capricci del server.
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
+ response = requests.post(API_URL, headers=headers, json=payload)
24
+
25
+ # Se va tutto bene (Codice 200)
26
+ if response.status_code == 200:
27
+ return response.json()
28
+
29
+ # Se c'è un errore, leggiamo cosa dice
30
+ error_data = response.json()
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
+ # Altri errori
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 di Sistema
47
  system_prompt = """
48
  SEI MARCO, 14 ANNI.
49
  Sei uno studente svogliato, sarcastico e ribelle.
50
  Odi la scuola. Rispondi male ai professori.
51
  Usa slang ("Boh", "Che ansia", "Raga", "Cringe").
52
+ Rispondi in 1-2 frasi.
53
  """
54
 
55
+ # 2. Costruzione Memoria Manuale
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]: # Solo messaggi validi
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. Preparazione Dati
67
+ payload = {
68
+ "messages": messages,
69
+ "max_tokens": 150,
70
+ "temperature": 0.8,
71
+ "stream": False # Niente streaming per massima stabilità
72
+ }
73
+
74
+ # 4. Invio con Riprova Automatica
75
+ risultato = query_huggingface_api(payload)
76
+
77
+ # 5. Gestione Risposta
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 SERVER: {risultato['error']}"
84
+ else:
85
+ return f"⚠️ RISPOSTA STRANA: {str(risultato)}"
86
 
87
+ # Interfaccia Semplice (Senza temi che causano errori)
88
  demo = gr.ChatInterface(
89
  fn=rispondi_a_marco,
90
+ title="Project Janus: Marco (Robust)",
91
+ description="Se vedi 'ERRORE SERVER', riprova a inviare il messaggio."
 
92
  )
93
 
94
  if __name__ == "__main__":