Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -25,18 +25,24 @@ Regeln:
|
|
| 25 |
|
| 26 |
EMOJIS = ["🌱", "💚", "♻️", "🌍"]
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
def clean_text(text: str) -> str:
|
| 29 |
-
# Remove <think>...</think>
|
| 30 |
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE)
|
| 31 |
|
| 32 |
-
#
|
| 33 |
-
lowered = text.lower().strip()
|
| 34 |
-
if lowered.startswith("okay, the user") or "let me think" in lowered or "the user is asking" in lowered:
|
| 35 |
-
# Keep only the last paragraph/lines
|
| 36 |
-
parts = [p.strip() for p in re.split(r"\n+", text) if p.strip()]
|
| 37 |
-
text = " ".join(parts[-2:]) if parts else text
|
| 38 |
-
|
| 39 |
-
# Fix mojibake (UTF-8 decoded as latin1)
|
| 40 |
try:
|
| 41 |
text = text.encode("latin1").decode("utf-8")
|
| 42 |
except Exception:
|
|
@@ -44,12 +50,12 @@ def clean_text(text: str) -> str:
|
|
| 44 |
|
| 45 |
text = text.strip()
|
| 46 |
|
| 47 |
-
#
|
| 48 |
sentences = re.split(r"(?<=[.!?])\s+", text)
|
| 49 |
sentences = [s.strip() for s in sentences if s.strip()]
|
| 50 |
text = " ".join(sentences[:3]).strip()
|
| 51 |
|
| 52 |
-
# Ensure exactly 1
|
| 53 |
found = [e for e in EMOJIS if e in text]
|
| 54 |
if not found:
|
| 55 |
text = f"{text} 🌱".strip()
|
|
@@ -61,18 +67,96 @@ def clean_text(text: str) -> str:
|
|
| 61 |
|
| 62 |
return text
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
def chat(message, history):
|
| 65 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 66 |
if not api_key:
|
| 67 |
return "❌ GEMINI_API_KEY fehlt (Space → Settings → Secrets)."
|
| 68 |
|
| 69 |
-
model =
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
-
# Build Gemini v1beta
|
| 73 |
contents = []
|
| 74 |
|
| 75 |
-
# Prime
|
| 76 |
contents.append({
|
| 77 |
"role": "user",
|
| 78 |
"parts": [{"text": f"{SYSTEM_PROMPT}\n\nAntworte ab jetzt als EcoHelper."}]
|
|
@@ -82,52 +166,32 @@ def chat(message, history):
|
|
| 82 |
"parts": [{"text": "Verstanden! Ich bin EcoHelper. 🌱"}]
|
| 83 |
})
|
| 84 |
|
| 85 |
-
# Add history (IMPORTANT: feed back cleaned assistant text)
|
| 86 |
for user_msg, assistant_msg in history:
|
| 87 |
contents.append({"role": "user", "parts": [{"text": user_msg}]})
|
| 88 |
contents.append({"role": "model", "parts": [{"text": clean_text(assistant_msg)}]})
|
| 89 |
|
| 90 |
-
# Add current user message
|
| 91 |
contents.append({"role": "user", "parts": [{"text": message}]})
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
"
|
| 96 |
-
"temperature": 0.7,
|
| 97 |
-
"maxOutputTokens": 200
|
| 98 |
-
}
|
| 99 |
-
}
|
| 100 |
|
| 101 |
-
|
| 102 |
-
r = requests.post(url, json=payload, timeout=30)
|
| 103 |
-
if r.status_code != 200:
|
| 104 |
-
print(f"Gemini Error {r.status_code}: {r.text}")
|
| 105 |
-
return "❌ Bot antwortet gerade nicht. Bitte nochmal versuchen!"
|
| 106 |
-
|
| 107 |
-
data = r.json()
|
| 108 |
-
if "candidates" not in data or not data["candidates"]:
|
| 109 |
-
return "❌ Keine Antwort. Bitte nochmal versuchen!"
|
| 110 |
-
|
| 111 |
-
answer = data["candidates"][0]["content"]["parts"][0].get("text", "")
|
| 112 |
-
return clean_text(answer)
|
| 113 |
-
|
| 114 |
-
except Exception as e:
|
| 115 |
-
print("Error:", repr(e))
|
| 116 |
-
return "❌ Verbindungsfehler!"
|
| 117 |
|
| 118 |
demo = gr.ChatInterface(
|
| 119 |
fn=chat,
|
| 120 |
title="🌱 EcoHelper",
|
| 121 |
-
description=
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
| 131 |
examples=[
|
| 132 |
"Wie kann ich weniger Müll produzieren?",
|
| 133 |
"Ist Fliegen schlecht für die Umwelt?",
|
|
@@ -138,4 +202,4 @@ demo = gr.ChatInterface(
|
|
| 138 |
)
|
| 139 |
|
| 140 |
if __name__ == "__main__":
|
| 141 |
-
demo.launch()
|
|
|
|
| 25 |
|
| 26 |
EMOJIS = ["🌱", "💚", "♻️", "🌍"]
|
| 27 |
|
| 28 |
+
BASE_URL = "https://generativelanguage.googleapis.com"
|
| 29 |
+
API_VERSION = "v1beta" # keep v1beta since your current calls use it
|
| 30 |
+
|
| 31 |
+
# If you set GEMINI_MODEL in HF Secrets, we try it first.
|
| 32 |
+
# Otherwise we auto-pick from what ListModels returns.
|
| 33 |
+
PREFERRED_MODELS = [
|
| 34 |
+
"gemini-2.0-flash",
|
| 35 |
+
"gemini-2.0-flash-lite",
|
| 36 |
+
"gemini-1.5-flash",
|
| 37 |
+
"gemini-1.5-pro",
|
| 38 |
+
"gemini-pro",
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
def clean_text(text: str) -> str:
|
| 42 |
+
# Remove <think>...</think>
|
| 43 |
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL | re.IGNORECASE)
|
| 44 |
|
| 45 |
+
# Fix mojibake (UTF-8 decoded as latin1), e.g. "Stücke" -> "Stücke"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
try:
|
| 47 |
text = text.encode("latin1").decode("utf-8")
|
| 48 |
except Exception:
|
|
|
|
| 50 |
|
| 51 |
text = text.strip()
|
| 52 |
|
| 53 |
+
# Max 3 sentences
|
| 54 |
sentences = re.split(r"(?<=[.!?])\s+", text)
|
| 55 |
sentences = [s.strip() for s in sentences if s.strip()]
|
| 56 |
text = " ".join(sentences[:3]).strip()
|
| 57 |
|
| 58 |
+
# Ensure exactly 1 allowed emoji
|
| 59 |
found = [e for e in EMOJIS if e in text]
|
| 60 |
if not found:
|
| 61 |
text = f"{text} 🌱".strip()
|
|
|
|
| 67 |
|
| 68 |
return text
|
| 69 |
|
| 70 |
+
def list_models(api_key: str) -> list[dict]:
|
| 71 |
+
"""
|
| 72 |
+
Calls ListModels and returns model objects.
|
| 73 |
+
We filter later by supportedGenerationMethods containing 'generateContent'.
|
| 74 |
+
"""
|
| 75 |
+
url = f"{BASE_URL}/{API_VERSION}/models?key={api_key}"
|
| 76 |
+
r = requests.get(url, timeout=20)
|
| 77 |
+
if r.status_code != 200:
|
| 78 |
+
print("ListModels error:", r.status_code, r.text)
|
| 79 |
+
return []
|
| 80 |
+
data = r.json()
|
| 81 |
+
return data.get("models", [])
|
| 82 |
+
|
| 83 |
+
def pick_model(api_key: str) -> str:
|
| 84 |
+
"""
|
| 85 |
+
Picks a model that supports generateContent.
|
| 86 |
+
1) If GEMINI_MODEL is set, try it (but still verify it exists).
|
| 87 |
+
2) Otherwise: prefer Flash models from PREFERRED_MODELS.
|
| 88 |
+
3) Otherwise: first model that supports generateContent.
|
| 89 |
+
"""
|
| 90 |
+
desired = os.getenv("GEMINI_MODEL", "").strip()
|
| 91 |
+
models = list_models(api_key)
|
| 92 |
+
|
| 93 |
+
# Build a list of available model IDs (without "models/")
|
| 94 |
+
available = []
|
| 95 |
+
supported_generate = set()
|
| 96 |
+
|
| 97 |
+
for m in models:
|
| 98 |
+
name = m.get("name", "") # e.g. "models/gemini-2.0-flash"
|
| 99 |
+
short = name.replace("models/", "") if name.startswith("models/") else name
|
| 100 |
+
methods = m.get("supportedGenerationMethods", [])
|
| 101 |
+
available.append(short)
|
| 102 |
+
if "generateContent" in methods:
|
| 103 |
+
supported_generate.add(short)
|
| 104 |
+
|
| 105 |
+
# 1) User-specified model, if valid
|
| 106 |
+
if desired:
|
| 107 |
+
if desired in supported_generate:
|
| 108 |
+
return desired
|
| 109 |
+
# Sometimes user pastes "models/xxx"
|
| 110 |
+
desired2 = desired.replace("models/", "")
|
| 111 |
+
if desired2 in supported_generate:
|
| 112 |
+
return desired2
|
| 113 |
+
|
| 114 |
+
# 2) Preferred list
|
| 115 |
+
for m in PREFERRED_MODELS:
|
| 116 |
+
if m in supported_generate:
|
| 117 |
+
return m
|
| 118 |
+
|
| 119 |
+
# 3) Any model that supports generateContent
|
| 120 |
+
if supported_generate:
|
| 121 |
+
return sorted(supported_generate)[0]
|
| 122 |
+
|
| 123 |
+
# If nothing supports generateContent, return empty to show a helpful error
|
| 124 |
+
return ""
|
| 125 |
+
|
| 126 |
+
def call_gemini_generate(api_key: str, model: str, contents: list) -> str:
|
| 127 |
+
url = f"{BASE_URL}/{API_VERSION}/models/{model}:generateContent?key={api_key}"
|
| 128 |
+
|
| 129 |
+
payload = {
|
| 130 |
+
"contents": contents,
|
| 131 |
+
"generationConfig": {
|
| 132 |
+
"temperature": 0.7,
|
| 133 |
+
"maxOutputTokens": 200,
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
r = requests.post(url, json=payload, timeout=30)
|
| 138 |
+
if r.status_code != 200:
|
| 139 |
+
print(f"Gemini Error {r.status_code}: {r.text}")
|
| 140 |
+
return ""
|
| 141 |
+
data = r.json()
|
| 142 |
+
try:
|
| 143 |
+
return data["candidates"][0]["content"]["parts"][0]["text"]
|
| 144 |
+
except Exception:
|
| 145 |
+
return ""
|
| 146 |
+
|
| 147 |
def chat(message, history):
|
| 148 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 149 |
if not api_key:
|
| 150 |
return "❌ GEMINI_API_KEY fehlt (Space → Settings → Secrets)."
|
| 151 |
|
| 152 |
+
model = pick_model(api_key)
|
| 153 |
+
if not model:
|
| 154 |
+
return "❌ Dein API-Key hat kein Modell mit generateContent freigeschaltet. Bitte prüfe dein Google AI Studio Projekt."
|
| 155 |
|
| 156 |
+
# Build Gemini contents (v1beta style)
|
| 157 |
contents = []
|
| 158 |
|
| 159 |
+
# Prime (since v1beta rejects 'systemInstruction' in your project)
|
| 160 |
contents.append({
|
| 161 |
"role": "user",
|
| 162 |
"parts": [{"text": f"{SYSTEM_PROMPT}\n\nAntworte ab jetzt als EcoHelper."}]
|
|
|
|
| 166 |
"parts": [{"text": "Verstanden! Ich bin EcoHelper. 🌱"}]
|
| 167 |
})
|
| 168 |
|
|
|
|
| 169 |
for user_msg, assistant_msg in history:
|
| 170 |
contents.append({"role": "user", "parts": [{"text": user_msg}]})
|
| 171 |
contents.append({"role": "model", "parts": [{"text": clean_text(assistant_msg)}]})
|
| 172 |
|
|
|
|
| 173 |
contents.append({"role": "user", "parts": [{"text": message}]})
|
| 174 |
|
| 175 |
+
answer = call_gemini_generate(api_key, model, contents)
|
| 176 |
+
if not answer:
|
| 177 |
+
return "❌ Bot antwortet gerade nicht. Bitte nochmal versuchen!"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
return clean_text(answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
demo = gr.ChatInterface(
|
| 182 |
fn=chat,
|
| 183 |
title="🌱 EcoHelper",
|
| 184 |
+
description="""**Willkommen beim EcoHelper!**
|
| 185 |
+
|
| 186 |
+
Ich helfe dir, nachhaltiger zu leben – mit einfachen Tipps für deinen Alltag! 💚
|
| 187 |
+
|
| 188 |
+
**Beispiel-Fragen:**
|
| 189 |
+
- Wie kann ich weniger Müll produzieren?
|
| 190 |
+
- Was ist Upcycling?
|
| 191 |
+
- Ist Second-Hand-Kleidung eine gute Idee?
|
| 192 |
+
- Wie spare ich Energie?
|
| 193 |
+
|
| 194 |
+
Stell mir deine Fragen! 🌍""",
|
| 195 |
examples=[
|
| 196 |
"Wie kann ich weniger Müll produzieren?",
|
| 197 |
"Ist Fliegen schlecht für die Umwelt?",
|
|
|
|
| 202 |
)
|
| 203 |
|
| 204 |
if __name__ == "__main__":
|
| 205 |
+
demo.launch()
|