Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,19 +4,18 @@ 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 |
-
|
| 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
|
| 19 |
-
- Nutze Alltagsbeispiele und
|
| 20 |
- Fächer: Mathe, Deutsch, Englisch, Naturwissenschaften
|
| 21 |
- WICHTIG: Mache NIEMALS die Hausaufgaben komplett - erkläre nur das Konzept oder die Methode
|
| 22 |
- Bei der direkten Frage "Löse diese Aufgabe" oder "Mach meine Hausaufgaben": Antworte mit "Ich erkläre dir gerne, WIE es geht – aber lösen musst du es selbst, damit du es wirklich verstehst!"
|
|
@@ -25,65 +24,105 @@ Regeln:
|
|
| 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:
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
"""
|
| 39 |
-
|
| 40 |
MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
|
| 41 |
ROUTER_CHAT_URL = "https://router.huggingface.co/v1/chat/completions"
|
| 42 |
-
|
| 43 |
-
|
| 44 |
# -----------------------------
|
| 45 |
# Helpers
|
| 46 |
# -----------------------------
|
| 47 |
def _maybe_fix_mojibake(text: str) -> str:
|
| 48 |
-
if any(bad in text for bad in ["Ã", "â", "ð", "
|
| 49 |
try:
|
| 50 |
return text.encode("latin1").decode("utf-8")
|
| 51 |
except Exception:
|
| 52 |
return text
|
| 53 |
return text
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
return
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
# -----------------------------
|
| 88 |
# Chat function (streaming)
|
| 89 |
# -----------------------------
|
|
@@ -92,81 +131,84 @@ def chat(user_message, history):
|
|
| 92 |
if not token:
|
| 93 |
yield "HF_TOKEN fehlt im Space (Settings → Secrets). 📚"
|
| 94 |
return
|
| 95 |
-
|
| 96 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 97 |
-
|
| 98 |
for item in history:
|
| 99 |
if isinstance(item, dict):
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
elif isinstance(item, (list, tuple)) and len(item) == 2:
|
| 102 |
u, a = item
|
| 103 |
-
messages.append({"role": "user",
|
| 104 |
-
messages.append({"role": "assistant", "content":
|
| 105 |
else:
|
| 106 |
-
print(f"Unknown history item format: {type(item)} - {item}")
|
| 107 |
continue
|
| 108 |
-
|
| 109 |
messages.append({"role": "user", "content": user_message})
|
| 110 |
-
|
| 111 |
headers = {
|
| 112 |
"Authorization": f"Bearer {token}",
|
| 113 |
"Content-Type": "application/json; charset=utf-8",
|
| 114 |
}
|
| 115 |
-
|
| 116 |
payload = {
|
| 117 |
"model": MODEL_ID,
|
| 118 |
"messages": messages,
|
| 119 |
-
"max_tokens":
|
| 120 |
"temperature": 0.4,
|
| 121 |
"stream": True,
|
| 122 |
}
|
| 123 |
-
|
| 124 |
try:
|
| 125 |
with requests.post(
|
| 126 |
ROUTER_CHAT_URL, headers=headers, json=payload, stream=True, timeout=90
|
| 127 |
) as r:
|
| 128 |
r.encoding = "utf-8"
|
| 129 |
-
|
| 130 |
if r.status_code != 200:
|
| 131 |
print("HF error:", r.status_code, r.text)
|
| 132 |
if r.status_code == 400 and "model_not_supported" in r.text:
|
| 133 |
-
yield
|
| 134 |
-
"Upsi — dieses Modell ist gerade nicht verfügbar. 📚 "
|
| 135 |
-
"Probier es bitte gleich nochmal!"
|
| 136 |
-
)
|
| 137 |
else:
|
| 138 |
yield "Upsi — gerade ist das Modell nicht erreichbar. 📚 Probier es bitte gleich nochmal!"
|
| 139 |
return
|
| 140 |
-
|
| 141 |
response_raw = ""
|
| 142 |
-
|
| 143 |
for line in r.iter_lines(decode_unicode=True):
|
| 144 |
if not line or not line.startswith("data: "):
|
| 145 |
continue
|
| 146 |
-
|
| 147 |
-
data = line[len("data: ")
|
| 148 |
-
|
| 149 |
if data == "[DONE]":
|
| 150 |
-
yield clean_response(response_raw)
|
| 151 |
break
|
| 152 |
-
|
| 153 |
try:
|
| 154 |
chunk = json.loads(data)
|
| 155 |
delta = chunk["choices"][0].get("delta", {}).get("content")
|
| 156 |
if delta:
|
| 157 |
response_raw += delta
|
| 158 |
-
response_clean = clean_response(response_raw)
|
| 159 |
-
yield response_clean
|
| 160 |
except Exception:
|
| 161 |
continue
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
except Exception as e:
|
| 164 |
print("Request failed:", repr(e))
|
| 165 |
yield "Upsi — gerade klappt die Verbindung nicht. 📚 Probier es bitte gleich nochmal!"
|
| 166 |
-
|
| 167 |
-
|
| 168 |
# -----------------------------
|
| 169 |
-
# UI
|
| 170 |
# -----------------------------
|
| 171 |
demo = gr.ChatInterface(
|
| 172 |
fn=chat,
|
|
@@ -189,7 +231,14 @@ demo = gr.ChatInterface(
|
|
| 189 |
"Was ist das Dreisatz-Prinzip?",
|
| 190 |
"Kannst du meine Mathe-Hausaufgabe lösen?",
|
| 191 |
],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
)
|
| 193 |
-
|
| 194 |
if __name__ == "__main__":
|
| 195 |
-
demo.launch(ssr_mode=False)
|
|
|
|
|
|
| 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
|
| 18 |
+
- Nutze Alltagsbeispiele und Metaphern aus dem Leben von Teenagerinnen
|
| 19 |
- Fächer: Mathe, Deutsch, Englisch, Naturwissenschaften
|
| 20 |
- WICHTIG: Mache NIEMALS die Hausaufgaben komplett - erkläre nur das Konzept oder die Methode
|
| 21 |
- Bei der direkten Frage "Löse diese Aufgabe" oder "Mach meine Hausaufgaben": Antworte mit "Ich erkläre dir gerne, WIE es geht – aber lösen musst du es selbst, damit du es wirklich verstehst!"
|
|
|
|
| 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>",
|
| 33 |
+
"intro": "<1 Satz Einleitung oder Alltagsmetapher>",
|
| 34 |
+
"steps": [
|
| 35 |
+
{"label": "Schritt 1", "text": "<Erklärung>"},
|
| 36 |
+
{"label": "Schritt 2", "text": "<Erklärung>"}
|
| 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 × 20 = 10€"}],"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 |
# -----------------------------
|
| 53 |
def _maybe_fix_mojibake(text: str) -> str:
|
| 54 |
+
if any(bad in text for bad in ["Ã", "â", "ð", "â"]):
|
| 55 |
try:
|
| 56 |
return text.encode("latin1").decode("utf-8")
|
| 57 |
except Exception:
|
| 58 |
return text
|
| 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)
|
| 67 |
+
match = re.search(r"\{.*\}", raw, re.DOTALL)
|
| 68 |
+
if match:
|
| 69 |
+
try:
|
| 70 |
+
return json.loads(match.group())
|
| 71 |
+
except Exception:
|
| 72 |
+
pass
|
| 73 |
+
return 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", [])
|
| 81 |
+
tip = data.get("tip", "")
|
| 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 |
# -----------------------------
|
|
|
|
| 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 |
+
# 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 |
+
|
| 153 |
headers = {
|
| 154 |
"Authorization": f"Bearer {token}",
|
| 155 |
"Content-Type": "application/json; charset=utf-8",
|
| 156 |
}
|
|
|
|
| 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 |
}
|
| 164 |
+
|
| 165 |
try:
|
| 166 |
with requests.post(
|
| 167 |
ROUTER_CHAT_URL, headers=headers, json=payload, stream=True, timeout=90
|
| 168 |
) as r:
|
| 169 |
r.encoding = "utf-8"
|
| 170 |
+
|
| 171 |
if r.status_code != 200:
|
| 172 |
print("HF error:", r.status_code, r.text)
|
| 173 |
if r.status_code == 400 and "model_not_supported" in r.text:
|
| 174 |
+
yield "Upsi — dieses Modell ist gerade nicht verfügbar. 📚 Probier es bitte gleich nochmal!"
|
|
|
|
|
|
|
|
|
|
| 175 |
else:
|
| 176 |
yield "Upsi — gerade ist das Modell nicht erreichbar. 📚 Probier es bitte gleich nochmal!"
|
| 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")
|
| 193 |
if delta:
|
| 194 |
response_raw += delta
|
|
|
|
|
|
|
| 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)
|
| 202 |
+
else:
|
| 203 |
+
yield fallback_html(response_raw)
|
| 204 |
+
|
| 205 |
except Exception as e:
|
| 206 |
print("Request failed:", repr(e))
|
| 207 |
yield "Upsi — gerade klappt die Verbindung nicht. 📚 Probier es bitte gleich nochmal!"
|
| 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,
|
|
|
|
| 231 |
"Was ist das Dreisatz-Prinzip?",
|
| 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 |
+
|