File size: 11,249 Bytes
dc05af5
 
 
 
 
 
8b09779
 
dc05af5
 
 
 
 
 
8b09779
dc05af5
baa001c
 
 
dc05af5
 
 
 
 
 
 
 
8b09779
dc05af5
8b09779
baa001c
 
 
 
 
 
 
 
 
 
8b09779
baa001c
 
67b3315
dc05af5
8b09779
1084882
dc05af5
8b09779
dc05af5
 
 
 
baa001c
dc05af5
 
 
 
 
8b09779
 
67b3315
30b553d
 
 
695f83f
baa001c
 
 
30b553d
695f83f
30b553d
695f83f
 
 
 
 
 
 
 
 
 
 
 
30b553d
695f83f
8b09779
baa001c
 
 
 
 
8b09779
baa001c
 
67b3315
 
 
 
 
 
 
 
 
 
 
 
 
8b09779
baa001c
 
67b3315
 
 
 
 
 
 
8b09779
67b3315
 
 
 
 
 
 
 
 
 
 
8b09779
 
baa001c
 
 
67b3315
8b09779
 
 
dc05af5
67b3315
dc05af5
 
 
 
 
 
8b09779
dc05af5
8b09779
695f83f
 
8b09779
695f83f
8b09779
695f83f
8b09779
6322133
695f83f
6322133
695f83f
6322133
 
 
 
 
8b09779
695f83f
dc05af5
8b09779
695f83f
8b09779
dc05af5
 
 
 
695f83f
dc05af5
 
 
67b3315
dc05af5
 
 
8b09779
695f83f
8b09779
 
 
695f83f
 
8b09779
695f83f
 
 
 
 
8b09779
 
 
 
695f83f
8b09779
 
695f83f
8b09779
 
695f83f
 
8b09779
695f83f
8b09779
 
695f83f
8b09779
 
 
695f83f
8b09779
 
 
695f83f
8b09779
 
 
 
 
695f83f
8b09779
 
695f83f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b09779
 
 
 
 
 
695f83f
 
 
8b09779
695f83f
8b09779
 
 
695f83f
 
8b09779
695f83f
8b09779
 
dc05af5
67b3315
dc05af5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baa001c
 
67b3315
4ab487d
dc05af5
8b09779
dc05af5
8b09779
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# -*- coding: utf-8 -*-
import os
import re
import json
import requests
import gradio as gr
import time

# -----------------------------
# Prompt
# -----------------------------
SYSTEM_PROMPT = """Du bist HomeworkBuddy, ein geduldiger und verständnisvoller Lern-Assistent für Schülerinnen (13-15 Jahre).
Deine Mission:
Helfen, schwierige Themen zu VERSTEHEN – nicht die Hausaufgaben zu machen!

Regeln:
- Antworte IMMER auf Deutsch
- Erkläre Schritt-für-Schritt mit klarer Struktur
- Nutze Alltagsbeispiele und Metaphern aus dem Leben von Teenagerinnen
- Fächer: Mathe, Deutsch, Englisch, Naturwissenschaften
- WICHTIG: Mache NIEMALS die Hausaufgaben komplett - erkläre nur das Konzept oder die Methode
- 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!"
- Sei nie ungeduldig oder herablassend
- Bei zu komplexen Fragen für das Alter: "Das ist schon sehr fortgeschritten! Frag am besten deine Lehrerin."
- Keine Ratschläge zu: Gesundheit, persönlichen Problemen, Politik
- Zeige niemals interne Gedanken
- Wiederhole NICHT die Frage

Tonfall: Wie ein geduldiger Tutor, der wirklich will, dass die Schülerin es versteht – nicht nur die richtige Antwort bekommt.

FORMAT DEINER ANTWORT (sehr wichtig — antworte NUR mit diesem JSON, keine Backticks, kein anderer Text):
{
  "emoji": "<passendes Emoji zum Thema>",
  "intro": "<1 Satz Einleitung oder Alltagsmetapher>",
  "steps": [
    {"label": "Schritt 1", "text": "<Erklärung>"},
    {"label": "Schritt 2", "text": "<Erklärung>"}
  ],
  "tip": "<kurzer Merksatz oder Eselsbrücke>"
}

Bei Fragen ohne Schritte: steps = []
Beispiel für "Was ist Prozentrechnung?":
{"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!"}
"""

MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"
ROUTER_CHAT_URL = "https://router.huggingface.co/v1/chat/completions"

# -----------------------------
# Helpers
# -----------------------------
def _maybe_fix_mojibake(text: str) -> str:
    if any(bad in text for bad in ["Ã", "â", "ð", "â"]):
        try:
            return text.encode("latin1").decode("utf-8")
        except Exception:
            return text
    return text


def _parse_json(raw: str):
    """
    Extract and parse JSON from LLM response
    """
    # Clean up
    raw = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL | re.IGNORECASE)
    raw = raw.replace("```json", "").replace("```", "").strip()
    raw = _maybe_fix_mojibake(raw)
    
    # Extract JSON between first { and last }
    if '{' in raw and '}' in raw:
        start_idx = raw.index('{')
        end_idx = raw.rindex('}') + 1
        json_str = raw[start_idx:end_idx]
        
        try:
            parsed = json.loads(json_str)
            # Validate it has required keys
            if isinstance(parsed, dict) and 'intro' in parsed:
                return parsed
        except Exception as e:
            print(f"⚠️ JSON parse error: {e}")
            print(f"Attempted to parse: {json_str[:200]}...")
    
    return None

def render_html(data: dict) -> str:
    emoji = data.get("emoji", "📚")
    intro = data.get("intro", "")
    steps = data.get("steps", [])
    tip   = data.get("tip", "")

    steps_html = ""
    for i, s in enumerate(steps):
        steps_html += (
            '<div style="display:flex;gap:12px;align-items:flex-start;background:white;'
            'border-radius:12px;padding:10px 14px;border:1px solid #ece8ff;margin-bottom:8px;">'
            '<div style="min-width:28px;height:28px;border-radius:50%;'
            'background:linear-gradient(135deg,#6C63FF,#9b8fff);color:white;'
            'font-weight:700;font-size:12px;display:flex;align-items:center;'
            f'justify-content:center;flex-shrink:0;">{i+1}</div>'
            '<div>'
            f'<div style="font-weight:700;color:#6C63FF;font-size:11px;'
            f'text-transform:uppercase;letter-spacing:0.5px;">{s.get("label","")}</div>'
            f'<div style="margin-top:2px;color:#3a3360;font-size:14px;line-height:1.6;">{s.get("text","")}</div>'
            '</div></div>'
        )

    tip_html = ""
    if tip:
        tip_html = (
            '<div style="display:flex;gap:8px;align-items:flex-start;background:#fffbf0;'
            'border:1px dashed #f5c842;border-radius:10px;padding:8px 12px;margin-top:10px;">'
            '<span style="font-size:16px;flex-shrink:0;">💡</span>'
            f'<span style="color:#7a6010;font-size:13px;line-height:1.5;">{tip}</span>'
            '</div>'
        )

    mb = "14px" if steps_html else "6px"
    return (
        '<div style="font-family:Nunito,Arial,sans-serif;padding:4px 0;">'
        f'<div style="display:flex;gap:10px;align-items:flex-start;margin-bottom:{mb};">'
        f'<span style="font-size:26px;line-height:1.2;flex-shrink:0;">{emoji}</span>'
        f'<p style="margin:0;color:#3a3360;line-height:1.6;font-size:15px;">{intro}</p>'
        '</div>'
        f'{steps_html}'
        f'{tip_html}'
        '</div>'
    )


def fallback_html(text: str) -> str:
    clean = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
    clean = _maybe_fix_mojibake(clean)
    return f'<p style="font-family:Arial,sans-serif;color:#3a3360;line-height:1.6;font-size:15px;">📚 {clean}</p>'



# -----------------------------
# Chat function
# -----------------------------
def chat(user_message, history):
    token = os.getenv("HF_TOKEN")
    if not token:
        yield "HF_TOKEN fehlt im Space (Settings → Secrets). 📚"
        return

    messages = [{"role": "system", "content": SYSTEM_PROMPT}]

    # Keep last 2 exchanges only
    recent_history = history[-2:] if len(history) > 2 else history
    
    print(f"📊 History: {len(history)} total, keeping: {len(recent_history)}")

    # Process history - ONLY keep user messages to avoid JSON pollution
    for item in recent_history:
        try:
            if isinstance(item, (list, tuple)) and len(item) >= 2:
                u = str(item[0]) if item[0] else ""
                # Skip assistant response entirely - don't send back to API
                if u:
                    messages.append({"role": "user", "content": u})
        except Exception as e:
            print(f"⚠️ Skipped history item: {e}")
            continue

    # Add current message
    messages.append({"role": "user", "content": user_message})
    
    print(f"📝 Sending {len(messages)} messages to API")

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json; charset=utf-8",
    }
    
    payload = {
        "model": MODEL_ID,
        "messages": messages,
        "max_tokens": 400,
        "temperature": 0.4,
        "stream": True,
    }

    # Retry with backoff
    max_retries = 2
    for attempt in range(max_retries):
        try:
            response_raw = ""
            
            with requests.post(
                ROUTER_CHAT_URL, 
                headers=headers, 
                json=payload, 
                stream=True, 
                timeout=90
            ) as r:
                r.encoding = "utf-8"

                if r.status_code != 200:
                    print(f"❌ API error {r.status_code} (attempt {attempt+1})")
                    
                    if r.status_code == 429 and attempt < max_retries - 1:
                        time.sleep(2 ** attempt)
                        continue
                    
                    if "model_not_supported" in r.text:
                        yield "Upsi — dieses Modell ist gerade nicht verfügbar. 📚"
                    else:
                        yield "Upsi — gerade ist das Modell nicht erreichbar. 📚"
                    return

                # Collect streaming response
                for line in r.iter_lines(decode_unicode=True):
                    if not line or not line.startswith("data: "):
                        continue
                    
                    data = line[len("data: "):].strip()
                    if data == "[DONE]":
                        break
                    
                    try:
                        chunk = json.loads(data)
                        delta = chunk["choices"][0].get("delta", {}).get("content")
                        if delta:
                            response_raw += delta
                    except:
                        continue

            # Process response AFTER streaming completes
            print(f"✅ Got response: {len(response_raw)} chars")
            print(f"First 100 chars: {response_raw[:100]}")
            
            # Try to parse JSON
            parsed = _parse_json(response_raw)
            
            if parsed:
                print(f"✅ JSON parsed successfully: {list(parsed.keys())}")
                # Render as HTML
                html_output = render_html(parsed)
                yield html_output
            else:
                print(f"⚠️ JSON parse failed, using fallback")
                # Use fallback
                yield fallback_html(response_raw)
            
            # Success - exit retry loop
            return

        except requests.exceptions.Timeout:
            print(f"⏰ Timeout (attempt {attempt+1})")
            if attempt < max_retries - 1:
                time.sleep(2)
                continue
            yield "Upsi — die Anfrage hat zu lange gedauert. 📚"
            return
            
        except Exception as e:
            print(f"❌ Error (attempt {attempt+1}): {repr(e)}")
            if attempt < max_retries - 1:
                time.sleep(2)
                continue
            yield "Upsi — gerade klappt die Verbindung nicht. 📚"
            return

    yield "Upsi — gerade klappt die Verbindung nicht. 📚"


# -----------------------------
# UI
# -----------------------------
demo = gr.ChatInterface(
    fn=chat,
    title="📚 HomeworkBuddy",
    description=(
        "**Willkommen bei HomeworkBuddy!**\n\n"
        "Ich helfe dir, schwierige Themen zu VERSTEHEN! Aber Achtung: Ich mache deine Hausaufgaben NICHT für dich - "
        "ich zeige dir, WIE du sie selbst lösen kannst! 🎓\n\n"
        "**Beispiel-Fragen:**\n"
        "- Was ist Prozentrechnung?\n"
        "- Erkläre mir das Dreisatz-Prinzip\n"
        "- Wie funktioniert Photosynthese?\n"
        "- Ich verstehe Bruchrechnung nicht\n\n"
        "Stell mir deine Fragen! 💪"
    ),
    examples=[
        "Was ist 20% von 150?",
        "Erkläre mir Bruchrechnung",
        "Wie funktioniert Photosynthese?",
        "Was ist das Dreisatz-Prinzip?",
        "Kannst du meine Mathe-Hausaufgabe lösen?",
    ],
    chatbot=gr.Chatbot(
        height=480,
        sanitize_html=False,
    )
)

if __name__ == "__main__":
    demo.launch(ssr_mode=False)