pauladeeptech commited on
Commit
8b09779
Β·
verified Β·
1 Parent(s): 67b3315

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -70
app.py CHANGED
@@ -4,14 +4,15 @@ import re
4
  import json
5
  import requests
6
  import gradio as gr
7
-
 
8
  # -----------------------------
9
  # Prompt
10
  # -----------------------------
11
  SYSTEM_PROMPT = """Du bist HomeworkBuddy, ein geduldiger und verstΓ€ndnisvoller Lern-Assistent fΓΌr SchΓΌlerinnen (13-15 Jahre).
12
  Deine Mission:
13
  Helfen, schwierige Themen zu VERSTEHEN – nicht die Hausaufgaben zu machen!
14
-
15
  Regeln:
16
  - Antworte IMMER auf Deutsch
17
  - ErklΓ€re Schritt-fΓΌr-Schritt mit klarer Struktur
@@ -24,9 +25,9 @@ Regeln:
24
  - Keine RatschlΓ€ge zu: Gesundheit, persΓΆnlichen Problemen, Politik
25
  - Zeige niemals interne Gedanken
26
  - Wiederhole NICHT die Frage
27
-
28
  Tonfall: Wie ein geduldiger Tutor, der wirklich will, dass die SchΓΌlerin es versteht – nicht nur die richtige Antwort bekommt.
29
-
30
  FORMAT DEINER ANTWORT (sehr wichtig β€” antworte NUR mit diesem JSON, keine Backticks, kein anderer Text):
31
  {
32
  "emoji": "<passendes Emoji zum Thema>",
@@ -37,16 +38,15 @@ FORMAT DEINER ANTWORT (sehr wichtig β€” antworte NUR mit diesem JSON, keine Back
37
  ],
38
  "tip": "<kurzer Merksatz oder EselsbrΓΌcke>"
39
  }
40
-
41
  Bei Fragen ohne Schritte: steps = []
42
  Beispiel fΓΌr "Was ist Prozentrechnung?":
43
  {"emoji":"🍰","intro":"Prozent bedeutet einfach 'von Hundert' – stell dir den ganzen Kuchen als 100% vor!","steps":[{"label":"Schritt 1","text":"Teile den Betrag durch 100, um 1% zu finden. z.B. 50 / 100 = 0,5"},{"label":"Schritt 2","text":"Multipliziere mit dem gewΓΌnschten Prozentsatz. z.B. 0,5 x 20 = 10 Euro"}],"tip":"Merke: % bedeutet immer / 100. Danach einfach mal den Prozentwert!"}
44
  """
45
-
46
  MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
47
  ROUTER_CHAT_URL = "https://router.huggingface.co/v1/chat/completions"
48
-
49
-
50
  # -----------------------------
51
  # Helpers
52
  # -----------------------------
@@ -57,8 +57,8 @@ def _maybe_fix_mojibake(text: str) -> str:
57
  except Exception:
58
  return text
59
  return text
60
-
61
-
62
  def _parse_json(raw: str):
63
  raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL | re.IGNORECASE)
64
  raw = raw.replace("```json", "").replace("```", "").strip()
@@ -70,14 +70,14 @@ def _parse_json(raw: str):
70
  except Exception:
71
  pass
72
  return None
73
-
74
-
75
  def render_html(data: dict) -> str:
76
  emoji = data.get("emoji", "πŸ“š")
77
  intro = data.get("intro", "")
78
  steps = data.get("steps", [])
79
  tip = data.get("tip", "")
80
-
81
  steps_html = ""
82
  for i, s in enumerate(steps):
83
  steps_html += (
@@ -93,7 +93,7 @@ def render_html(data: dict) -> str:
93
  f'<div style="margin-top:2px;color:#3a3360;font-size:14px;line-height:1.6;">{s.get("text","")}</div>'
94
  '</div></div>'
95
  )
96
-
97
  tip_html = ""
98
  if tip:
99
  tip_html = (
@@ -103,7 +103,7 @@ def render_html(data: dict) -> str:
103
  f'<span style="color:#7a6010;font-size:13px;line-height:1.5;">{tip}</span>'
104
  '</div>'
105
  )
106
-
107
  mb = "14px" if steps_html else "6px"
108
  return (
109
  '<div style="font-family:Nunito,Arial,sans-serif;padding:4px 0;">'
@@ -115,14 +115,46 @@ def render_html(data: dict) -> str:
115
  f'{tip_html}'
116
  '</div>'
117
  )
118
-
119
-
120
  def fallback_html(text: str) -> str:
121
  clean = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
122
  clean = _maybe_fix_mojibake(clean)
123
  return f'<p style="font-family:Arial,sans-serif;color:#3a3360;line-height:1.6;font-size:15px;">πŸ“š {clean}</p>'
124
-
125
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  # -----------------------------
127
  # Chat function
128
  # -----------------------------
@@ -131,22 +163,33 @@ def chat(user_message, history):
131
  if not token:
132
  yield "HF_TOKEN fehlt im Space (Settings β†’ Secrets). πŸ“š"
133
  return
134
-
135
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
136
-
137
- for item in history:
 
 
 
 
 
138
  if isinstance(item, dict):
139
- role = item.get("role", "")
140
  content = item.get("content", "")
141
- clean = re.sub(r"<[^>]+>", " ", content).strip()
 
142
  messages.append({"role": role, "content": clean})
143
  elif isinstance(item, (list, tuple)) and len(item) == 2:
144
  u, a = item
145
- messages.append({"role": "user", "content": u})
146
- messages.append({"role": "assistant", "content": re.sub(r"<[^>]+>", " ", str(a)).strip()})
147
-
 
 
148
  messages.append({"role": "user", "content": user_message})
149
-
 
 
 
150
  headers = {
151
  "Authorization": f"Bearer {token}",
152
  "Content-Type": "application/json; charset=utf-8",
@@ -158,47 +201,80 @@ def chat(user_message, history):
158
  "temperature": 0.4,
159
  "stream": True,
160
  }
161
-
162
- try:
163
- with requests.post(
164
- ROUTER_CHAT_URL, headers=headers, json=payload, stream=True, timeout=90
165
- ) as r:
166
- r.encoding = "utf-8"
167
-
168
- if r.status_code != 200:
169
- print("HF error:", r.status_code, r.text)
170
- if r.status_code == 400 and "model_not_supported" in r.text:
171
- yield "Upsi β€” dieses Modell ist gerade nicht verfΓΌgbar. πŸ“š Probier es bitte gleich nochmal!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  else:
173
- yield "Upsi β€” gerade ist das Modell nicht erreichbar. πŸ“š Probier es bitte gleich nochmal!"
 
 
 
 
 
 
 
 
 
 
 
174
  return
175
-
176
- response_raw = ""
177
- for line in r.iter_lines(decode_unicode=True):
178
- if not line or not line.startswith("data: "):
179
- continue
180
- data = line[len("data: "):].strip()
181
- if data == "[DONE]":
182
- break
183
- try:
184
- chunk = json.loads(data)
185
- delta = chunk["choices"][0].get("delta", {}).get("content")
186
- if delta:
187
- response_raw += delta
188
- except Exception:
189
- continue
190
-
191
- parsed = _parse_json(response_raw)
192
- if parsed:
193
- yield render_html(parsed)
194
  else:
195
- yield fallback_html(response_raw)
196
-
197
- except Exception as e:
198
- print("Request failed:", repr(e))
199
- yield "Upsi β€” gerade klappt die Verbindung nicht. πŸ“š Probier es bitte gleich nochmal!"
200
-
201
-
202
  # -----------------------------
203
  # UI
204
  # -----------------------------
@@ -227,9 +303,10 @@ demo = gr.ChatInterface(
227
  height=480,
228
  sanitize_html=False,
229
  ),
 
 
 
230
  )
231
-
232
  if __name__ == "__main__":
233
- demo.launch(ssr_mode=False)
234
-
235
-
 
4
  import json
5
  import requests
6
  import gradio as gr
7
+ import time
8
+
9
  # -----------------------------
10
  # Prompt
11
  # -----------------------------
12
  SYSTEM_PROMPT = """Du bist HomeworkBuddy, ein geduldiger und verstΓ€ndnisvoller Lern-Assistent fΓΌr SchΓΌlerinnen (13-15 Jahre).
13
  Deine Mission:
14
  Helfen, schwierige Themen zu VERSTEHEN – nicht die Hausaufgaben zu machen!
15
+
16
  Regeln:
17
  - Antworte IMMER auf Deutsch
18
  - ErklΓ€re Schritt-fΓΌr-Schritt mit klarer Struktur
 
25
  - Keine RatschlΓ€ge zu: Gesundheit, persΓΆnlichen Problemen, Politik
26
  - Zeige niemals interne Gedanken
27
  - Wiederhole NICHT die Frage
28
+
29
  Tonfall: Wie ein geduldiger Tutor, der wirklich will, dass die SchΓΌlerin es versteht – nicht nur die richtige Antwort bekommt.
30
+
31
  FORMAT DEINER ANTWORT (sehr wichtig β€” antworte NUR mit diesem JSON, keine Backticks, kein anderer Text):
32
  {
33
  "emoji": "<passendes Emoji zum Thema>",
 
38
  ],
39
  "tip": "<kurzer Merksatz oder EselsbrΓΌcke>"
40
  }
41
+
42
  Bei Fragen ohne Schritte: steps = []
43
  Beispiel fΓΌr "Was ist Prozentrechnung?":
44
  {"emoji":"🍰","intro":"Prozent bedeutet einfach 'von Hundert' – stell dir den ganzen Kuchen als 100% vor!","steps":[{"label":"Schritt 1","text":"Teile den Betrag durch 100, um 1% zu finden. z.B. 50 / 100 = 0,5"},{"label":"Schritt 2","text":"Multipliziere mit dem gewΓΌnschten Prozentsatz. z.B. 0,5 x 20 = 10 Euro"}],"tip":"Merke: % bedeutet immer / 100. Danach einfach mal den Prozentwert!"}
45
  """
46
+
47
  MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
48
  ROUTER_CHAT_URL = "https://router.huggingface.co/v1/chat/completions"
49
+
 
50
  # -----------------------------
51
  # Helpers
52
  # -----------------------------
 
57
  except Exception:
58
  return text
59
  return text
60
+
61
+
62
  def _parse_json(raw: str):
63
  raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL | re.IGNORECASE)
64
  raw = raw.replace("```json", "").replace("```", "").strip()
 
70
  except Exception:
71
  pass
72
  return None
73
+
74
+
75
  def render_html(data: dict) -> str:
76
  emoji = data.get("emoji", "πŸ“š")
77
  intro = data.get("intro", "")
78
  steps = data.get("steps", [])
79
  tip = data.get("tip", "")
80
+
81
  steps_html = ""
82
  for i, s in enumerate(steps):
83
  steps_html += (
 
93
  f'<div style="margin-top:2px;color:#3a3360;font-size:14px;line-height:1.6;">{s.get("text","")}</div>'
94
  '</div></div>'
95
  )
96
+
97
  tip_html = ""
98
  if tip:
99
  tip_html = (
 
103
  f'<span style="color:#7a6010;font-size:13px;line-height:1.5;">{tip}</span>'
104
  '</div>'
105
  )
106
+
107
  mb = "14px" if steps_html else "6px"
108
  return (
109
  '<div style="font-family:Nunito,Arial,sans-serif;padding:4px 0;">'
 
115
  f'{tip_html}'
116
  '</div>'
117
  )
118
+
119
+
120
  def fallback_html(text: str) -> str:
121
  clean = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
122
  clean = _maybe_fix_mojibake(clean)
123
  return f'<p style="font-family:Arial,sans-serif;color:#3a3360;line-height:1.6;font-size:15px;">πŸ“š {clean}</p>'
124
+
125
+
126
+ # -----------------------------
127
+ # βœ… NEW: Extract plain text from history
128
+ # -----------------------------
129
+ def extract_text_from_history_item(content: str) -> str:
130
+ """
131
+ Extract plain text from HTML or JSON responses
132
+ """
133
+ # Try to parse as JSON first (from previous responses)
134
+ try:
135
+ # Remove HTML tags
136
+ clean = re.sub(r"<[^>]+>", " ", content)
137
+
138
+ # Try to find JSON
139
+ match = re.search(r"\{.*\}", clean, re.DOTALL)
140
+ if match:
141
+ data = json.loads(match.group())
142
+ # Reconstruct plain text from JSON
143
+ parts = []
144
+ if data.get("intro"):
145
+ parts.append(data["intro"])
146
+ for step in data.get("steps", []):
147
+ parts.append(f"{step.get('label', '')}: {step.get('text', '')}")
148
+ if data.get("tip"):
149
+ parts.append(f"Tipp: {data['tip']}")
150
+ return " ".join(parts)
151
+ except:
152
+ pass
153
+
154
+ # Fallback: just strip HTML
155
+ return re.sub(r"<[^>]+>", " ", content).strip()
156
+
157
+
158
  # -----------------------------
159
  # Chat function
160
  # -----------------------------
 
163
  if not token:
164
  yield "HF_TOKEN fehlt im Space (Settings β†’ Secrets). πŸ“š"
165
  return
166
+
167
  messages = [{"role": "system", "content": SYSTEM_PROMPT}]
168
+
169
+ # βœ… KEY FIX 1: Only keep last 3 exchanges (6 messages)
170
+ recent_history = history[-3:] if len(history) > 3 else history
171
+
172
+ print(f"πŸ“Š Processing request. History items: {len(history)}, keeping: {len(recent_history)}")
173
+
174
+ for item in recent_history:
175
  if isinstance(item, dict):
176
+ role = item.get("role", "")
177
  content = item.get("content", "")
178
+ # βœ… Extract plain text properly
179
+ clean = extract_text_from_history_item(content)
180
  messages.append({"role": role, "content": clean})
181
  elif isinstance(item, (list, tuple)) and len(item) == 2:
182
  u, a = item
183
+ # βœ… Extract plain text from assistant response
184
+ clean_a = extract_text_from_history_item(str(a))
185
+ messages.append({"role": "user", "content": u})
186
+ messages.append({"role": "assistant", "content": clean_a})
187
+
188
  messages.append({"role": "user", "content": user_message})
189
+
190
+ # βœ… Debug: Show message count
191
+ print(f"πŸ“ Total messages being sent: {len(messages)}")
192
+
193
  headers = {
194
  "Authorization": f"Bearer {token}",
195
  "Content-Type": "application/json; charset=utf-8",
 
201
  "temperature": 0.4,
202
  "stream": True,
203
  }
204
+
205
+ # βœ… KEY FIX 2: Add retry logic
206
+ max_retries = 2
207
+ for attempt in range(max_retries):
208
+ try:
209
+ with requests.post(
210
+ ROUTER_CHAT_URL, headers=headers, json=payload, stream=True, timeout=90
211
+ ) as r:
212
+ r.encoding = "utf-8"
213
+
214
+ if r.status_code != 200:
215
+ print(f"❌ HF error (attempt {attempt+1}): {r.status_code} {r.text}")
216
+
217
+ # βœ… Retry on rate limit
218
+ if r.status_code == 429 and attempt < max_retries - 1:
219
+ wait_time = 2 ** attempt # 1s, 2s
220
+ print(f"⏰ Rate limited. Waiting {wait_time}s...")
221
+ time.sleep(wait_time)
222
+ continue
223
+
224
+ if r.status_code == 400 and "model_not_supported" in r.text:
225
+ yield "Upsi β€” dieses Modell ist gerade nicht verfΓΌgbar. πŸ“š Probier es bitte gleich nochmal!"
226
+ else:
227
+ yield "Upsi β€” gerade ist das Modell nicht erreichbar. πŸ“š Probier es bitte gleich nochmal!"
228
+ return
229
+
230
+ response_raw = ""
231
+ for line in r.iter_lines(decode_unicode=True):
232
+ if not line or not line.startswith("data: "):
233
+ continue
234
+ data = line[len("data: "):].strip()
235
+ if data == "[DONE]":
236
+ break
237
+ try:
238
+ chunk = json.loads(data)
239
+ delta = chunk["choices"][0].get("delta", {}).get("content")
240
+ if delta:
241
+ response_raw += delta
242
+ except Exception:
243
+ continue
244
+
245
+ print(f"βœ… Got response, length: {len(response_raw)} chars")
246
+
247
+ parsed = _parse_json(response_raw)
248
+ if parsed:
249
+ yield render_html(parsed)
250
  else:
251
+ yield fallback_html(response_raw)
252
+
253
+ # Success - exit retry loop
254
+ return
255
+
256
+ except requests.exceptions.Timeout:
257
+ print(f"⏰ Timeout (attempt {attempt+1})")
258
+ if attempt < max_retries - 1:
259
+ time.sleep(2)
260
+ continue
261
+ else:
262
+ yield "Upsi β€” die Anfrage hat zu lange gedauert. πŸ“š Probier es bitte nochmal!"
263
  return
264
+
265
+ except Exception as e:
266
+ print(f"❌ Request failed (attempt {attempt+1}):", repr(e))
267
+ if attempt < max_retries - 1:
268
+ time.sleep(2)
269
+ continue
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  else:
271
+ yield "Upsi β€” gerade klappt die Verbindung nicht. πŸ“š Probier es bitte gleich nochmal!"
272
+ return
273
+
274
+ # Should not reach here, but just in case
275
+ yield "Upsi β€” gerade klappt die Verbindung nicht. πŸ“š Probier es bitte gleich nochmal!"
276
+
277
+
278
  # -----------------------------
279
  # UI
280
  # -----------------------------
 
303
  height=480,
304
  sanitize_html=False,
305
  ),
306
+ retry_btn=None,
307
+ undo_btn="↩️ ZurΓΌck",
308
+ clear_btn="πŸ—‘οΈ Neu starten"
309
  )
310
+
311
  if __name__ == "__main__":
312
+ demo.launch(ssr_mode=False)