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