Spaces:
Sleeping
Sleeping
Download app.py from pauladeeptech/HomeworkBuddy2: direct link, hf CLI and curl.
- Browser
- Download file 6.5 kB
-
https://huggingface.co/spaces/pauladeeptech/HomeworkBuddy2/resolve/main/app.py
- Command line
-
hf download hf://spaces/pauladeeptech/HomeworkBuddy2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/pauladeeptech/HomeworkBuddy2/resolve/main/app.py
6.5 kB
| # -*- 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) |