pauladeeptech commited on
Commit
46eb8bf
·
verified ·
1 Parent(s): 8268c6b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +219 -0
app.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Metaphern 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
+ continue
107
+
108
+ messages.append({"role": "user", "content": user_message})
109
+
110
+ headers = {
111
+ "Authorization": f"Bearer {token}",
112
+ "Content-Type": "application/json; charset=utf-8",
113
+ }
114
+
115
+ payload = {
116
+ "model": MODEL_ID,
117
+ "messages": messages,
118
+ "max_tokens": 200,
119
+ "temperature": 0.4,
120
+ "stream": True,
121
+ }
122
+
123
+ try:
124
+ with requests.post(
125
+ ROUTER_CHAT_URL, headers=headers, json=payload, stream=True, timeout=90
126
+ ) as r:
127
+ r.encoding = "utf-8"
128
+
129
+ if r.status_code != 200:
130
+ print("HF error:", r.status_code, r.text)
131
+ if r.status_code == 400 and "model_not_supported" in r.text:
132
+ yield "Upsi — dieses Modell ist gerade nicht verfügbar. 📚 Probier es bitte gleich nochmal!"
133
+ else:
134
+ yield "Upsi — gerade ist das Modell nicht erreichbar. 📚 Probier es bitte gleich nochmal!"
135
+ return
136
+
137
+ response_raw = ""
138
+
139
+ for line in r.iter_lines(decode_unicode=True):
140
+ if not line or not line.startswith("data: "):
141
+ continue
142
+
143
+ data = line[len("data: ") :].strip()
144
+
145
+ if data == "[DONE]":
146
+ yield clean_response(response_raw)
147
+ break
148
+
149
+ try:
150
+ chunk = json.loads(data)
151
+ delta = chunk["choices"][0].get("delta", {}).get("content")
152
+ if delta:
153
+ response_raw += delta
154
+ response_clean = clean_response(response_raw)
155
+ yield response_clean
156
+ except Exception:
157
+ continue
158
+
159
+ except Exception as e:
160
+ print("Request failed:", repr(e))
161
+ yield "Upsi — gerade klappt die Verbindung nicht. 📚 Probier es bitte gleich nochmal!"
162
+
163
+
164
+ # -----------------------------
165
+ # UI with better styling
166
+ # -----------------------------
167
+ custom_css = """
168
+ .message.user {
169
+ background-color: #f0f0f0 !important;
170
+ border-radius: 12px !important;
171
+ padding: 12px 16px !important;
172
+ margin: 8px 0 !important;
173
+ }
174
+
175
+ .message.bot {
176
+ background-color: #e8f4f8 !important;
177
+ border-radius: 12px !important;
178
+ padding: 12px 16px !important;
179
+ margin: 8px 0 !important;
180
+ line-height: 1.6 !important;
181
+ }
182
+
183
+ .message p {
184
+ margin: 0 !important;
185
+ padding: 0 !important;
186
+ }
187
+
188
+ #chatbot {
189
+ height: 600px !important;
190
+ }
191
+ """
192
+
193
+ demo = gr.ChatInterface(
194
+ fn=chat,
195
+ title="📚 HomeworkBuddy",
196
+ description=(
197
+ "**Willkommen bei HomeworkBuddy!**\n\n"
198
+ "Ich helfe dir, schwierige Themen zu VERSTEHEN! Aber Achtung: Ich mache deine Hausaufgaben NICHT für dich - "
199
+ "ich zeige dir, WIE du sie selbst lösen kannst! 🎓\n\n"
200
+ "**Beispiel-Fragen:**\n"
201
+ "- Was ist Prozentrechnung?\n"
202
+ "- Erkläre mir das Dreisatz-Prinzip\n"
203
+ "- Wie funktioniert Photosynthese?\n"
204
+ "- Ich verstehe Bruchrechnung nicht\n\n"
205
+ "Stell mir deine Fragen! 💪"
206
+ ),
207
+ examples=[
208
+ "Was ist 20% von 150?",
209
+ "Erkläre mir Bruchrechnung",
210
+ "Wie funktioniert Photosynthese?",
211
+ "Was ist das Dreisatz-Prinzip?",
212
+ "Kannst du meine Mathe-Hausaufgabe lösen?",
213
+ ],
214
+ css=custom_css,
215
+ type="messages", # This makes messages render as paragraphs instead of textboxes
216
+ )
217
+
218
+ if __name__ == "__main__":
219
+ demo.launch(ssr_mode=False)