pauladeeptech commited on
Commit
dc05af5
·
verified ·
1 Parent(s): 100899c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -0
app.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ 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, maximal 4 Sätze
18
+ - Erkläre Schritt-für-Schritt mit klarer Struktur (z.B. "Schritt 1:", "Schritt 2:")
19
+ - Nutze Alltagsbeispiele und Metaphoren aus dem Leben von Teenagerinnen
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!"
23
+ - Sei nie ungeduldig oder herablassend
24
+ - Bei zu komplexen Fragen für das Alter: "Das ist schon sehr fortgeschritten! Frag am besten deine Lehrerin."
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
+ Schreibe deine Antwort immer so:
33
+ Antwort: <deine Antwort>
34
+
35
+ Beispiel:
36
+ Frage: "Was ist Prozentrechnung?"
37
+ 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!
38
+ """
39
+
40
+ MODEL_ID = "HuggingFaceTB/SmolLM3-3B"
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 _extract_answer(text: str) -> str:
57
+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE)
58
+ if "Antwort:" in text:
59
+ text = text.split("Antwort:")[-1]
60
+ text = re.sub(
61
+ r"^\s*(okay|alright|so|hmm|let me|i should|the user is asking).*?$",
62
+ "",
63
+ text.strip(),
64
+ flags=re.IGNORECASE | re.DOTALL,
65
+ )
66
+ text = _maybe_fix_mojibake(text)
67
+ return text.strip()
68
+
69
+
70
+ def _enforce_style(text: str) -> str:
71
+ text = text.strip()
72
+ text = re.sub(r"\s+", " ", text).strip()
73
+
74
+ # Keep max 4 sentences
75
+ parts = re.split(r"(?<=[.!?])\s+", text)
76
+ parts = [p for p in parts if p]
77
+ text = " ".join(parts[:4]).strip()
78
+
79
+ return text
80
+
81
+
82
+ def clean_response(text: str) -> str:
83
+ text = _extract_answer(text)
84
+ return _enforce_style(text)
85
+
86
+
87
+ # -----------------------------
88
+ # Chat function (streaming)
89
+ # -----------------------------
90
+ def chat(user_message, history):
91
+ token = os.getenv("HF_TOKEN")
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
+ messages.append(item)
101
+ elif isinstance(item, (list, tuple)) and len(item) == 2:
102
+ u, a = item
103
+ messages.append({"role": "user", "content": u})
104
+ messages.append({"role": "assistant", "content": clean_response(a)})
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": 200,
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: ") :].strip()
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,
173
+ title="📚 HomeworkBuddy",
174
+ description=(
175
+ "**Willkommen bei HomeworkBuddy!**\n\n"
176
+ "Ich helfe dir, schwierige Themen zu VERSTEHEN! Aber Achtung: Ich mache deine Hausaufgaben NICHT für dich - "
177
+ "ich zeige dir, WIE du sie selbst lösen kannst! 🎓\n\n"
178
+ "**Beispiel-Fragen:**\n"
179
+ "- Was ist Prozentrechnung?\n"
180
+ "- Erkläre mir das Dreisatz-Prinzip\n"
181
+ "- Wie funktioniert Photosynthese?\n"
182
+ "- Ich verstehe Bruchrechnung nicht\n\n"
183
+ "Stell mir deine Fragen! 💪"
184
+ ),
185
+ examples=[
186
+ "Was ist 20% von 150?",
187
+ "Erkläre mir Bruchrechnung",
188
+ "Wie funktioniert Photosynthese?",
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)