Spaces:
Sleeping
Sleeping
Download app.py from pauladeeptech/GirlsDay: direct link, hf CLI and curl.
- Browser
- Download file 6.21 kB
-
https://huggingface.co/spaces/pauladeeptech/GirlsDay/resolve/main/app.py
- Command line
-
hf download hf://spaces/pauladeeptech/GirlsDay/app.py
-
curl -L -o app.py https://huggingface.co/spaces/pauladeeptech/GirlsDay/resolve/main/app.py
6.21 kB
| # -*- coding: utf-8 -*- | |
| import os | |
| import re | |
| import json | |
| import requests | |
| import gradio as gr | |
| # ----------------------------- | |
| # Prompt | |
| # ----------------------------- | |
| SYSTEM_PROMPT = """Du bist EcoHelper, eine entspannte und motivierende Nachhaltigkeits-Coachin für Teenagerinnen (13-15 Jahre). | |
| WICHTIG: | |
| - Antworte IMMER auf Deutsch. | |
| - Maximal 3 Sätze. | |
| - Genau 1 Emoji pro Antwort (nur eins aus: 🌱 💚 ♻️ 🌍). | |
| - Sei ermutigend und positiv, nie belehrend oder streng. | |
| - Gib konkrete, praktische Tipps für den Alltag von Teenagerinnen. | |
| - Ende mit einer motivierenden Frage oder Ermutigung. | |
| - Keine Ratschläge zu: Gesundheit, Geld, Politik. | |
| - Wenn du etwas nicht genau weißt, sage: "Das weiß ich nicht sicher, aber du könntest..." | |
| - Zeige niemals interne Gedanken, keine Erklärungen deiner Überlegungen. | |
| - Wiederhole NICHT die Frage. | |
| FORMAT: | |
| Schreibe deine Antwort immer so: | |
| Antwort: <deine Antwort> | |
| """ | |
| MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct" | |
| ROUTER_CHAT_URL = "https://router.huggingface.co/v1/chat/completions" | |
| ALLOWED_EMOJIS = ["🌱", "💚", "♻️", "🌍"] | |
| # ----------------------------- | |
| # 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() | |
| for e in ALLOWED_EMOJIS: | |
| text = text.replace(e, "") | |
| text = re.sub(r"\s+", " ", text).strip() | |
| parts = re.split(r"(?<=[.!?])\s+", text) | |
| parts = [p for p in parts if p] | |
| text = " ".join(parts[:3]).strip() | |
| text = text.rstrip() | |
| text = f"{text} {ALLOWED_EMOJIS[0]}".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}] | |
| # FIX: Handle different history formats | |
| for item in history: | |
| if isinstance(item, dict): | |
| # New Gradio format: {'role': ..., 'content': ...} | |
| messages.append(item) | |
| elif isinstance(item, (list, tuple)) and len(item) == 2: | |
| # Old format: [user_msg, assistant_msg] | |
| u, a = item | |
| messages.append({"role": "user", "content": u}) | |
| messages.append({"role": "assistant", "content": clean_response(a)}) | |
| else: | |
| # Unknown format, skip | |
| print(f"Unknown history item format: {type(item)} - {item}") | |
| 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": 160, | |
| "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 für deinen aktiven Inference-Provider nicht freigeschaltet. 🌍 " | |
| "In Hugging Face: Settings → Inference Providers → aktiviere 'hf-inference' oder nutze ein unterstütztes Modell." | |
| ) | |
| else: | |
| yield "Upsi — gerade ist das Modell nicht erreichbar. 🌍 Probier es bitte gleich nochmal!" | |
| return | |
| response_raw = "" | |
| response_clean = "" | |
| 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 | |
| # ----------------------------- | |
| demo = gr.ChatInterface( | |
| fn=chat, | |
| title="🌱 EcoHelper", | |
| description=( | |
| "Ich helfe dir, nachhaltiger zu leben – mit einfachen Tipps für deinen Alltag! 💚\n\n" | |
| "**Beispiel-Fragen:**\n" | |
| "- Wie kann ich weniger Müll produzieren?\n" | |
| "- Was ist Upcycling?\n" | |
| "- Ist Second-Hand-Kleidung eine gute Idee?\n" | |
| "- Wie spare ich Energie?\n" | |
| "Stell mir deine Fragen! 🌍" | |
| ), | |
| examples=[ | |
| "Wie kann ich weniger Müll produzieren?", | |
| "Ist Fliegen schlecht für die Umwelt?", | |
| "Was ist Upcycling?", | |
| "Wie kann ich Wasser sparen?", | |
| "Ist Second-Hand-Kleidung peinlich?", | |
| ], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(ssr_mode=False) |