Admin: KI-Anfragen nach Quelle aufschlüsseln (cloud/local/luna)

- ki_daily_calls: PK auf (user_id, date, source) erweitert + Index; Migration
  baut Tabelle mit neuer Struktur neu auf, behält Altdaten als 'cloud'
- ki.py: return_source=True-Parameter gibt (text, 'cloud'|'local') zurück
- training.py: ki_source aus ki.complete() auslesen, in DB speichern
- social.py: _ki_complete_tracked() zählt Luna-Anfragen mit source='luna';
  alle Content-Endpoints (generate, evaluate, training-tip, breed-of-day,
  pflege-tipp) nutzen tracking-Variante
- admin.py: Stats aufgeteilt in ki_cloud/ki_local/ki_luna je heute+Monat
- admin.js: KI-Karte zeigt 9 Zeilen mit ☁️ Claude / 🖥️ LM Studio / 🌙 Luna
- SW by-v359, APP_VER 344
This commit is contained in:
rene 2026-04-25 08:20:29 +02:00
parent 74b6c03bb3
commit 8d5c7a19b1
6 changed files with 136 additions and 33 deletions

View file

@ -160,8 +160,30 @@ async def stats(user=Depends(require_mod)):
ki_users_today = conn.execute(
"SELECT COUNT(DISTINCT user_id) FROM ki_daily_calls WHERE date=DATE('now')"
).fetchone()[0]
# Aufschlüsselung nach Quelle (heute)
_src_today = {
r[0]: r[1] for r in conn.execute(
"SELECT source, COALESCE(SUM(count),0) FROM ki_daily_calls "
"WHERE date=DATE('now') GROUP BY source"
).fetchall()
}
ki_cloud_today = _src_today.get("cloud", 0)
ki_local_today = _src_today.get("local", 0)
ki_luna_today = _src_today.get("luna", 0)
# Aufschlüsselung nach Quelle (Monat)
_src_month = {
r[0]: r[1] for r in conn.execute(
"SELECT source, COALESCE(SUM(count),0) FROM ki_daily_calls "
"WHERE date>=DATE('now','start of month') GROUP BY source"
).fetchall()
}
ki_cloud_month = _src_month.get("cloud", 0)
ki_local_month = _src_month.get("local", 0)
ki_luna_month = _src_month.get("luna", 0)
except Exception:
ki_today = ki_month = ki_users_today = 0
ki_cloud_today = ki_local_today = ki_luna_today = 0
ki_cloud_month = ki_local_month = ki_luna_month = 0
# Social Media Tracking
try:
@ -217,6 +239,12 @@ async def stats(user=Depends(require_mod)):
"ki_today": ki_today,
"ki_month": ki_month,
"ki_users_today": ki_users_today,
"ki_cloud_today": ki_cloud_today,
"ki_local_today": ki_local_today,
"ki_luna_today": ki_luna_today,
"ki_cloud_month": ki_cloud_month,
"ki_local_month": ki_local_month,
"ki_luna_month": ki_luna_month,
"social_total": social_total,
"social_published": social_published,
"social_scheduled": social_scheduled,

View file

@ -466,9 +466,19 @@ _PFLEGE_TIPPS = [
"fell_typ":"lang","saison":None,"tipp":"Von Beinen und Schwanz beginnen — dort filzt es zuerst."},
{"id":"fell_buersten_lockig","titel":"Pflege bei Lockenfell (Pudel, Labradoodle)","kat":"Fell",
"beschreibung":"Lockiges Fell verliert kaum Haare, verfilzt aber stark — spezielle Technik nötig.",
"schritte":["Täglich durchkämmen mit Metallkamm","Verfilzungen mit Finger lösen, dann Kamm","Alle 68 Wochen Schertermin","Zwischen Augen und Pfoten regelmäßig trimmen"],
"schritte":["Täglich durchkämmen mit Metallkamm","Verfilzungen mit Finger lösen, dann Kamm","Alle 68 Wochen Schertermin","Zwischen Augen und Pfoten regelmäßig kürzen"],
"materialien":"Metallkamm, Pin-Bürste, Schere","haeufigkeit":"Täglich + 68 Wochen Schertermin",
"fell_typ":"lockig","saison":None,"tipp":"Lockiges Fell = hypoallergen, aber Pflegeaufwand unterschätzt!"},
"fell_typ":"lockig","saison":None,"fell_pflege_art":"schneiden","tipp":"Lockiges Fell = hypoallergen, aber Pflegeaufwand unterschätzt!"},
{"id":"fell_scheren_technik","titel":"Fell schneiden: Technik & Scheren-Tipps","kat":"Fell",
"beschreibung":"Für Rassen mit kontinuierlichem Fellwuchs (Pudel, Bichon, Spoodle) — Scheren statt Trimmen!",
"schritte":["Fell nach dem Bad komplett trocknen und bürsten","Schere oder Clipper parallel zur Haarwuchsrichtung führen","Empfindliche Stellen (Gesicht, Pfoten) mit Effilierschere","Alle 68 Wochen zum Groomer oder selbst lernen","Nach dem Scheren: Fell bürsten und kontrollieren"],
"materialien":"Effilierschere, Clipper, Metallkamm","haeufigkeit":"Alle 68 Wochen",
"fell_typ":"lockig","saison":None,"fell_pflege_art":"schneiden","tipp":"Nie nasses Fell scheren — immer erst trocknen, sonst ungleichmäßiges Ergebnis."},
{"id":"fell_trimmen_technik","titel":"Fell trimmen: Stripping beim Rauhaar-Terrier","kat":"Fell",
"beschreibung":"Rauhaardrahtiges Fell (Westie, Schnauzer, Jack Russell) hat natürliche Wachstumsbegrenzung — Trimmen statt Scheren!",
"schritte":["Daumen und Zeigefinger: abgestorbene Haare zupfen (Stripping)","Immer in Haarwuchsrichtung arbeiten","Unterwolle mit feinem Rake ausbürsten","Niemals scheren — zerstört Textur dauerhaft","Alle 34 Monate professionelles Hand-Stripping"],
"materialien":"Stripper-Messer (Trimmmesser), Rake, Kreide für Grip","haeufigkeit":"Alle 34 Monate",
"fell_typ":"alle","saison":None,"fell_pflege_art":"trimmen","tipp":"Geschorenes Drahthaarfell verliert seine typische Textur dauerhaft — immer trimmen!"},
{"id":"fell_unterwolle", "titel":"Unterwolle ausbürsten (Fellwechsel)","kat":"Fell",
"beschreibung":"Zweimal jährlich toter Unterwolle-Berg — richtig ausgebürstet statt überall verteilt.",
"schritte":["Undercoat-Rake gegen Haarwuchsrichtung","Abschnittweise: Rücken, Flanken, Bauch","Furminator maximal 2x/Woche","Nach dem Bürsten: Hund ausschütteln lassen"],
@ -949,6 +959,28 @@ async def _ki_complete(prompt: str) -> str:
)
async def _ki_complete_tracked(prompt: str, user_id: int) -> str:
"""Wie _ki_complete, zählt die Anfrage in ki_daily_calls (source='luna')."""
import datetime as _dt
import ki as ki_module
text = await ki_module.complete(
prompt,
system=_SYSTEM,
max_tokens=1200,
requires_premium=False,
)
today = str(_dt.date.today())
try:
with db() as conn:
conn.execute("""
INSERT INTO ki_daily_calls (user_id, date, count, source) VALUES (?, ?, 1, 'luna')
ON CONFLICT(user_id, date, source) DO UPDATE SET count = count + 1
""", (user_id, today))
except Exception:
pass
return text
def _parse_json(raw: str) -> dict:
import re
try:
@ -1064,7 +1096,7 @@ async def generate_content(req: GenerateRequest, user=Depends(require_social_med
)
try:
raw = await _ki_complete(prompt)
raw = await _ki_complete_tracked(prompt, user["id"])
data = _parse_json(raw)
except Exception as e:
logger.error("Social-Media-Generierung fehlgeschlagen: %s", e)
@ -1113,7 +1145,7 @@ async def evaluate_content(req: EvaluateRequest, user=Depends(require_social_med
)
try:
raw = await _ki_complete(prompt)
raw = await _ki_complete_tracked(prompt, user["id"])
data = _parse_json(raw)
except Exception as e:
raise HTTPException(500, f"KI-Fehler: {e}")
@ -1197,13 +1229,21 @@ def _seed_pflege():
conn.execute(
"""INSERT OR IGNORE INTO pflege_tipps
(tipp_id, titel, kategorie, beschreibung, schritte,
materialien, haeufigkeit, fell_typ, saison, rassengruppe, tipp)
VALUES (?,?,?,?,?,?,?,?,?,?,?)""",
materialien, haeufigkeit, fell_typ, saison, rassengruppe, tipp,
fell_pflege_art)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",
(p["id"], p["titel"], p["kat"],
p.get("beschreibung"), json.dumps(p.get("schritte", []), ensure_ascii=False),
p.get("materialien"), p.get("haeufigkeit"),
p.get("fell_typ"), p.get("saison"), p.get("rassengruppe"), p.get("tipp")),
p.get("fell_typ"), p.get("saison"), p.get("rassengruppe"), p.get("tipp"),
p.get("fell_pflege_art")),
)
# UPDATE für bereits bestehende Tipps (idempotent)
if p.get("fell_pflege_art"):
conn.execute(
"UPDATE pflege_tipps SET fell_pflege_art=? WHERE tipp_id=? AND (fell_pflege_art IS NULL OR fell_pflege_art != ?)",
(p["fell_pflege_art"], p["id"], p["fell_pflege_art"]),
)
try:
_seed_exercises()
@ -1251,7 +1291,7 @@ async def training_tip(user=Depends(require_social_media)):
)
try:
raw = await _ki_complete(prompt)
raw = await _ki_complete_tracked(prompt, user["id"])
data = _parse_json(raw)
except Exception as e:
raise HTTPException(500, f"KI-Fehler: {e}")
@ -1407,7 +1447,7 @@ async def breed_of_day(user=Depends(require_social_media)):
)
try:
raw = await _ki_complete(prompt)
raw = await _ki_complete_tracked(prompt, user["id"])
data = _parse_json(raw)
except Exception as e:
raise HTTPException(500, f"KI-Fehler: {e}")
@ -1546,7 +1586,7 @@ async def pflege_tipp(breed_id: Optional[int] = None, user=Depends(require_socia
)
try:
raw = await _ki_complete(prompt)
raw = await _ki_complete_tracked(prompt, user["id"])
data = _parse_json(raw)
except Exception as e:
raise HTTPException(500, f"KI-Fehler: {e}")

View file

@ -777,11 +777,10 @@ async def ki_feedback(body: KiFeedbackRequest, user=Depends(get_current_user)):
).fetchone()[0]
if age_hours < 6 and new_since == 0:
daily_used = conn.execute(
"SELECT COALESCE(count,0) FROM ki_daily_calls WHERE user_id=? AND date=?",
used = conn.execute(
"SELECT COALESCE(SUM(count),0) FROM ki_daily_calls WHERE user_id=? AND date=?",
(uid, today)
).fetchone()
used = daily_used[0] if daily_used else 0
).fetchone()[0]
return {"feedback": cache_row["feedback"], "cached": True,
"daily_used": used, "daily_limit": KI_DAILY_LIMIT}
@ -791,14 +790,14 @@ async def ki_feedback(body: KiFeedbackRequest, user=Depends(get_current_user)):
user_id INTEGER NOT NULL,
date TEXT NOT NULL,
count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, date)
source TEXT NOT NULL DEFAULT 'cloud',
PRIMARY KEY (user_id, date, source)
)
""")
row = conn.execute(
"SELECT count FROM ki_daily_calls WHERE user_id=? AND date=?",
daily_used = conn.execute(
"SELECT COALESCE(SUM(count),0) FROM ki_daily_calls WHERE user_id=? AND date=?",
(uid, today)
).fetchone()
daily_used = row[0] if row else 0
).fetchone()[0]
if daily_used >= KI_DAILY_LIMIT:
raise HTTPException(429, f"Tages-Limit erreicht ({KI_DAILY_LIMIT} Anfragen/Tag). Morgen wieder verfügbar.")
@ -867,12 +866,13 @@ async def ki_feedback(body: KiFeedbackRequest, user=Depends(get_current_user)):
)
try:
feedback_text = await ki.complete(
feedback_text, ki_source = await ki.complete(
prompt,
system=system,
max_tokens=400,
requires_premium=False,
user_is_premium=user.get("is_premium", False),
return_source=True,
)
except (ki.KIUnavailableError, ki.KIPremiumRequired) as e:
raise HTTPException(503, str(e))
@ -889,11 +889,11 @@ async def ki_feedback(body: KiFeedbackRequest, user=Depends(get_current_user)):
(body.dog_id, feedback_text)
)
conn.execute("""
INSERT INTO ki_daily_calls (user_id, date, count) VALUES (?, ?, 1)
ON CONFLICT(user_id, date) DO UPDATE SET count = count + 1
""", (uid, today))
INSERT INTO ki_daily_calls (user_id, date, count, source) VALUES (?, ?, 1, ?)
ON CONFLICT(user_id, date, source) DO UPDATE SET count = count + 1
""", (uid, today, ki_source))
new_count = conn.execute(
"SELECT count FROM ki_daily_calls WHERE user_id=? AND date=?",
"SELECT COALESCE(SUM(count),0) FROM ki_daily_calls WHERE user_id=? AND date=?",
(uid, today)
).fetchone()[0]