pauladeeptech commited on
Commit
67b3315
·
verified ·
1 Parent(s): baa001c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -50
app.py CHANGED
@@ -40,7 +40,7 @@ FORMAT DEINER ANTWORT (sehr wichtig — antworte NUR mit diesem JSON, keine Back
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 × 20 = 10€"}],"tip":"Merke: % bedeutet immer ÷ 100. Danach einfach mal den Prozentwert!"}
44
  """
45
 
46
  MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
@@ -59,8 +59,7 @@ def _maybe_fix_mojibake(text: str) -> str:
59
  return text
60
 
61
 
62
- def _parse_json(raw: str) -> dict | None:
63
- """Strip think-tags and extract JSON from the model output."""
64
  raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL | re.IGNORECASE)
65
  raw = raw.replace("```json", "").replace("```", "").strip()
66
  raw = _maybe_fix_mojibake(raw)
@@ -74,7 +73,6 @@ def _parse_json(raw: str) -> dict | None:
74
 
75
 
76
  def render_html(data: dict) -> str:
77
- """Turn the structured JSON into a styled HTML card."""
78
  emoji = data.get("emoji", "📚")
79
  intro = data.get("intro", "")
80
  steps = data.get("steps", [])
@@ -82,49 +80,51 @@ def render_html(data: dict) -> str:
82
 
83
  steps_html = ""
84
  for i, s in enumerate(steps):
85
- steps_html += f"""
86
- <div style="display:flex;gap:12px;align-items:flex-start;background:white;
87
- border-radius:12px;padding:10px 14px;border:1px solid #ece8ff;margin-bottom:8px;">
88
- <div style="min-width:28px;height:28px;border-radius:50%;
89
- background:linear-gradient(135deg,#6C63FF,#9b8fff);color:white;
90
- font-weight:700;font-size:12px;display:flex;align-items:center;
91
- justify-content:center;flex-shrink:0;">{i+1}</div>
92
- <div>
93
- <div style="font-weight:700;color:#6C63FF;font-size:11px;
94
- text-transform:uppercase;letter-spacing:0.5px;">{s.get('label','')}</div>
95
- <div style="margin-top:2px;color:#3a3360;font-size:14px;line-height:1.6;">{s.get('text','')}</div>
96
- </div>
97
- </div>"""
98
 
99
  tip_html = ""
100
  if tip:
101
- tip_html = f"""
102
- <div style="display:flex;gap:8px;align-items:flex-start;background:#fffbf0;
103
- border:1px dashed #f5c842;border-radius:10px;padding:8px 12px;margin-top:10px;">
104
- <span style="font-size:16px;flex-shrink:0;">💡</span>
105
- <span style="color:#7a6010;font-size:13px;line-height:1.5;">{tip}</span>
106
- </div>"""
107
-
108
- return f"""
109
- <div style="font-family:'Nunito',sans-serif;padding:4px 0;">
110
- <div style="display:flex;gap:10px;align-items:flex-start;margin-bottom:{'14px' if steps_html else '6px'};">
111
- <span style="font-size:26px;line-height:1.2;flex-shrink:0;">{emoji}</span>
112
- <p style="margin:0;color:#3a3360;line-height:1.6;font-size:15px;">{intro}</p>
113
- </div>
114
- {steps_html}
115
- {tip_html}
116
- </div>"""
 
 
 
117
 
118
 
119
  def fallback_html(text: str) -> str:
120
- """Plain text fallback if JSON parsing fails."""
121
  clean = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
122
  clean = _maybe_fix_mojibake(clean)
123
- return f'<div style="font-family:Nunito,sans-serif;color:#3a3360;line-height:1.6;font-size:15px;">📚 {clean}</div>'
124
 
125
 
126
  # -----------------------------
127
- # Chat function (streaming)
128
  # -----------------------------
129
  def chat(user_message, history):
130
  token = os.getenv("HF_TOKEN")
@@ -138,15 +138,12 @@ def chat(user_message, history):
138
  if isinstance(item, dict):
139
  role = item.get("role", "")
140
  content = item.get("content", "")
141
- # Strip HTML tags so model gets clean text as history
142
- clean = re.sub(r"<[^>]+>", " ", content).strip()
143
  messages.append({"role": role, "content": clean})
144
  elif isinstance(item, (list, tuple)) and len(item) == 2:
145
  u, a = item
146
  messages.append({"role": "user", "content": u})
147
  messages.append({"role": "assistant", "content": re.sub(r"<[^>]+>", " ", str(a)).strip()})
148
- else:
149
- continue
150
 
151
  messages.append({"role": "user", "content": user_message})
152
 
@@ -157,7 +154,7 @@ def chat(user_message, history):
157
  payload = {
158
  "model": MODEL_ID,
159
  "messages": messages,
160
- "max_tokens": 400, # increased from 200 to fit JSON
161
  "temperature": 0.4,
162
  "stream": True,
163
  }
@@ -177,16 +174,12 @@ def chat(user_message, history):
177
  return
178
 
179
  response_raw = ""
180
-
181
  for line in r.iter_lines(decode_unicode=True):
182
  if not line or not line.startswith("data: "):
183
  continue
184
-
185
  data = line[len("data: "):].strip()
186
-
187
  if data == "[DONE]":
188
  break
189
-
190
  try:
191
  chunk = json.loads(data)
192
  delta = chunk["choices"][0].get("delta", {}).get("content")
@@ -195,7 +188,6 @@ def chat(user_message, history):
195
  except Exception:
196
  continue
197
 
198
- # Render final formatted response
199
  parsed = _parse_json(response_raw)
200
  if parsed:
201
  yield render_html(parsed)
@@ -208,7 +200,7 @@ def chat(user_message, history):
208
 
209
 
210
  # -----------------------------
211
- # UI - same as before, one small addition: custom Chatbot with sanitize_html=False
212
  # -----------------------------
213
  demo = gr.ChatInterface(
214
  fn=chat,
@@ -232,13 +224,12 @@ demo = gr.ChatInterface(
232
  "Kannst du meine Mathe-Hausaufgabe lösen?",
233
  ],
234
  chatbot=gr.Chatbot(
235
- render_markdown=False,
236
- sanitize_html=False, # ← only new line vs. your original UI
237
  height=480,
238
- bubble_full_width=False,
239
  ),
240
  )
241
 
242
  if __name__ == "__main__":
243
  demo.launch(ssr_mode=False)
 
244
 
 
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"
 
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()
65
  raw = _maybe_fix_mojibake(raw)
 
73
 
74
 
75
  def render_html(data: dict) -> str:
 
76
  emoji = data.get("emoji", "📚")
77
  intro = data.get("intro", "")
78
  steps = data.get("steps", [])
 
80
 
81
  steps_html = ""
82
  for i, s in enumerate(steps):
83
+ steps_html += (
84
+ '<div style="display:flex;gap:12px;align-items:flex-start;background:white;'
85
+ 'border-radius:12px;padding:10px 14px;border:1px solid #ece8ff;margin-bottom:8px;">'
86
+ '<div style="min-width:28px;height:28px;border-radius:50%;'
87
+ 'background:linear-gradient(135deg,#6C63FF,#9b8fff);color:white;'
88
+ 'font-weight:700;font-size:12px;display:flex;align-items:center;'
89
+ f'justify-content:center;flex-shrink:0;">{i+1}</div>'
90
+ '<div>'
91
+ f'<div style="font-weight:700;color:#6C63FF;font-size:11px;'
92
+ f'text-transform:uppercase;letter-spacing:0.5px;">{s.get("label","")}</div>'
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 = (
100
+ '<div style="display:flex;gap:8px;align-items:flex-start;background:#fffbf0;'
101
+ 'border:1px dashed #f5c842;border-radius:10px;padding:8px 12px;margin-top:10px;">'
102
+ '<span style="font-size:16px;flex-shrink:0;">💡</span>'
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;">'
110
+ f'<div style="display:flex;gap:10px;align-items:flex-start;margin-bottom:{mb};">'
111
+ f'<span style="font-size:26px;line-height:1.2;flex-shrink:0;">{emoji}</span>'
112
+ f'<p style="margin:0;color:#3a3360;line-height:1.6;font-size:15px;">{intro}</p>'
113
+ '</div>'
114
+ f'{steps_html}'
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
  # -----------------------------
129
  def chat(user_message, history):
130
  token = os.getenv("HF_TOKEN")
 
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
 
 
154
  payload = {
155
  "model": MODEL_ID,
156
  "messages": messages,
157
+ "max_tokens": 400,
158
  "temperature": 0.4,
159
  "stream": True,
160
  }
 
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")
 
188
  except Exception:
189
  continue
190
 
 
191
  parsed = _parse_json(response_raw)
192
  if parsed:
193
  yield render_html(parsed)
 
200
 
201
 
202
  # -----------------------------
203
+ # UI
204
  # -----------------------------
205
  demo = gr.ChatInterface(
206
  fn=chat,
 
224
  "Kannst du meine Mathe-Hausaufgabe lösen?",
225
  ],
226
  chatbot=gr.Chatbot(
 
 
227
  height=480,
228
+ sanitize_html=False,
229
  ),
230
  )
231
 
232
  if __name__ == "__main__":
233
  demo.launch(ssr_mode=False)
234
+
235