File size: 6,500 Bytes
46eb8bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
646fe2f
46eb8bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18a3dcc
46eb8bf
18a3dcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46eb8bf
 
18a3dcc
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
# -*- coding: utf-8 -*-
import os
import re
import json
import requests
import gradio as gr

# -----------------------------
# 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, maximal 4 Sätze
- Erkläre Schritt-für-Schritt mit klarer Struktur (z.B. "Schritt 1:", "Schritt 2:")
- 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:
Schreibe deine Antwort immer so:
Antwort: <deine Antwort>

Beispiel:
Frage: "Was ist Prozentrechnung?"
Antwort: Prozent bedeutet 'von Hundert'. Wenn du 20% von 50€ berechnen willst: Schritt 1: Teile 50 durch 100 (=0,5). Schritt 2: Multipliziere mit 20 (=10€). Stell dir vor: 100% ist der ganze Kuchen, 20% ist ein Fünftel!
"""

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 _extract_answer(text: str) -> str:
    text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE)
    if "Antwort:" in text:
        text = text.split("Antwort:")[-1]
    text = re.sub(
        r"^\s*(okay|alright|so|hmm|let me|i should|the user is asking).*?$",
        "",
        text.strip(),
        flags=re.IGNORECASE | re.DOTALL,
    )
    text = _maybe_fix_mojibake(text)
    return text.strip()


def _enforce_style(text: str) -> str:
    text = text.strip()
    text = re.sub(r"\s+", " ", text).strip()
    
    # Keep max 4 sentences
    parts = re.split(r"(?<=[.!?])\s+", text)
    parts = [p for p in parts if p]
    text = " ".join(parts[:4]).strip()
    
    return text


def clean_response(text: str) -> str:
    text = _extract_answer(text)
    return _enforce_style(text)


# -----------------------------
# Chat function (streaming)
# -----------------------------
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}]

    for item in history:
        if isinstance(item, dict):
            messages.append(item)
        elif isinstance(item, (list, tuple)) and len(item) == 2:
            u, a = item
            messages.append({"role": "user", "content": u})
            messages.append({"role": "assistant", "content": clean_response(a)})
        else:
            continue

    messages.append({"role": "user", "content": user_message})

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json; charset=utf-8",
    }

    payload = {
        "model": MODEL_ID,
        "messages": messages,
        "max_tokens": 200,
        "temperature": 0.4,
        "stream": True,
    }

    try:
        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("HF error:", r.status_code, r.text)
                if r.status_code == 400 and "model_not_supported" in r.text:
                    yield "Upsi — dieses Modell ist gerade nicht verfügbar. 📚 Probier es bitte gleich nochmal!"
                else:
                    yield "Upsi — gerade ist das Modell nicht erreichbar. 📚 Probier es bitte gleich nochmal!"
                return

            response_raw = ""

            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]":
                    yield clean_response(response_raw)
                    break

                try:
                    chunk = json.loads(data)
                    delta = chunk["choices"][0].get("delta", {}).get("content")
                    if delta:
                        response_raw += delta
                        response_clean = clean_response(response_raw)
                        yield response_clean
                except Exception:
                    continue

    except Exception as e:
        print("Request failed:", repr(e))
        yield "Upsi — gerade klappt die Verbindung nicht. 📚 Probier es bitte gleich nochmal!"


# -----------------------------
# UI - Simple version
# -----------------------------
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?",
    ],
)

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