I hate this fucking language.
This commit is contained in:
+85
-19
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -12,6 +13,19 @@ from server.messages import pick
|
||||
from server.settings import settings
|
||||
from server.stats import compute_stats
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MOTIVATION_SYSTEM = (
|
||||
"Du schreibst Tages-Motivationssprüche für 'ADHD live, laugh, toaster bath motivational'. "
|
||||
"Stil: dark humor, Sarkasmus, passiv-aggressiv, kreativ-motivierend — nie gemein, nie medizinisch. "
|
||||
"Genau ein Satz auf Deutsch, max 25 Wörter. Keine Anführungszeichen um den Spruch."
|
||||
)
|
||||
|
||||
ORACLE_SYSTEM = (
|
||||
"Du bist das wöchentliche KI-Orakel einer ADHS-Medikamenten-App. "
|
||||
"Passiv-aggressiv, trocken, max 4 Sätze auf Deutsch. Keine medizinischen Ratschläge."
|
||||
)
|
||||
|
||||
|
||||
async def _get_cache(db: aiosqlite.Connection, key: str) -> str | None:
|
||||
cur = await db.execute("SELECT content FROM ai_cache WHERE key = ?", (key,))
|
||||
@@ -28,7 +42,7 @@ async def _set_cache(db: aiosqlite.Connection, key: str, content: str) -> None:
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def _call_openrouter(prompt: str) -> str | None:
|
||||
async def _call_openrouter(prompt: str, *, system: str) -> str | None:
|
||||
if not settings.openrouter_api_key:
|
||||
return None
|
||||
try:
|
||||
@@ -43,10 +57,7 @@ async def _call_openrouter(prompt: str) -> str | None:
|
||||
json={
|
||||
"model": settings.openrouter_model,
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": "Du bist ein sarkastischer, dark-humor Medikamenten-Coach für jemanden mit ADHS. Kurz (max 2 Sätze), deutsch, witzig aber nicht gemein. Keine medizinischen Ratschläge.",
|
||||
},
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": prompt},
|
||||
],
|
||||
"max_tokens": 120,
|
||||
@@ -56,29 +67,62 @@ async def _call_openrouter(prompt: str) -> str | None:
|
||||
data = resp.json()
|
||||
return data["choices"][0]["message"]["content"].strip()
|
||||
except Exception:
|
||||
logger.exception("OpenRouter request failed")
|
||||
return None
|
||||
|
||||
|
||||
async def get_roast_of_the_day(db: aiosqlite.Connection, tz: ZoneInfo) -> dict[str, Any]:
|
||||
day = datetime.now(tz).strftime("%Y-%m-%d")
|
||||
key = f"roast:{day}"
|
||||
cached = await _get_cache(db, key)
|
||||
def _motivation_key(day: str) -> str:
|
||||
return f"motivation:{day}"
|
||||
|
||||
|
||||
async def _cached_motivation(db: aiosqlite.Connection, day: str) -> str | None:
|
||||
cached = await _get_cache(db, _motivation_key(day))
|
||||
if cached:
|
||||
return cached
|
||||
return await _get_cache(db, f"roast:{day}")
|
||||
|
||||
|
||||
async def generate_daily_motivation(
|
||||
db: aiosqlite.Connection,
|
||||
tz: ZoneInfo,
|
||||
day: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
day = day or datetime.now(tz).strftime("%Y-%m-%d")
|
||||
key = _motivation_key(day)
|
||||
cached = await _cached_motivation(db, day)
|
||||
if cached:
|
||||
return {"text": cached, "source": "cache", "day": day}
|
||||
|
||||
stats = await compute_stats(db)
|
||||
prompt = f"Roast-of-the-Day für jemanden mit ADHS. Streak: {stats['streak']} Tage, Compliance 90d: {stats['compliance_percent']}%. Ein sarkastischer Spruch."
|
||||
text = await _call_openrouter(prompt)
|
||||
prompt = (
|
||||
"Schreibe den Motivationsspruch für heute. "
|
||||
f"Streak: {stats['streak']} Tage. "
|
||||
f"Compliance über {stats['compliance_window_days']} aktive Tage: {stats['compliance_percent']}%. "
|
||||
"Beispiel-Stil: Dein Gehirn ist nicht kaputt. Es läuft nur auf einem anderen Betriebssystem — ohne Support."
|
||||
)
|
||||
text = await _call_openrouter(prompt, system=MOTIVATION_SYSTEM)
|
||||
if not text:
|
||||
text = pick("roast_fallback")
|
||||
text = pick("motivation_fallback")
|
||||
source = "fallback"
|
||||
else:
|
||||
source = "ai"
|
||||
await _set_cache(db, key, text)
|
||||
|
||||
logger.info("Generated daily motivation for %s (%s)", day, source)
|
||||
return {"text": text, "source": source, "day": day}
|
||||
|
||||
|
||||
async def get_daily_motivation(db: aiosqlite.Connection, tz: ZoneInfo) -> dict[str, Any]:
|
||||
day = datetime.now(tz).strftime("%Y-%m-%d")
|
||||
cached = await _cached_motivation(db, day)
|
||||
if cached:
|
||||
return {"text": cached, "source": "cache", "day": day}
|
||||
return {"text": pick("motivation_fallback"), "source": "fallback", "day": day}
|
||||
|
||||
|
||||
async def get_roast_of_the_day(db: aiosqlite.Connection, tz: ZoneInfo) -> dict[str, Any]:
|
||||
return await get_daily_motivation(db, tz)
|
||||
|
||||
|
||||
async def get_oracle(db: aiosqlite.Connection, tz: ZoneInfo) -> dict[str, Any]:
|
||||
week = datetime.now(tz).strftime("%Y-W%W")
|
||||
key = f"oracle:{week}"
|
||||
@@ -87,14 +131,36 @@ async def get_oracle(db: aiosqlite.Connection, tz: ZoneInfo) -> dict[str, Any]:
|
||||
return {"text": cached, "source": "cache", "week": week}
|
||||
|
||||
stats = await compute_stats(db)
|
||||
prompt = (
|
||||
f"Wöchentlicher KI-Orakel-Report (passiv-aggressiv, max 4 Sätze). "
|
||||
f"Streak: {stats['streak']}, Compliance 90d: {stats['compliance_percent']}%, "
|
||||
f"genommen gesamt: {stats['total_taken']}."
|
||||
days_active = stats["days_active"]
|
||||
window = stats["compliance_window_days"]
|
||||
young_app = days_active < 90
|
||||
context = (
|
||||
f"App aktiv seit {days_active} Tag(en), erste Einnahme am {stats['first_day']}. "
|
||||
if young_app
|
||||
else ""
|
||||
)
|
||||
text = await _call_openrouter(prompt)
|
||||
caveat = (
|
||||
"Die App ist noch jung — lange Streaks oder 90-Tage-Compliance sind noch nicht realistisch erreichbar. "
|
||||
"Bewerte nur die verfügbaren Daten, sei fair aber sarkastisch. "
|
||||
if young_app
|
||||
else ""
|
||||
)
|
||||
prompt = (
|
||||
f"Wöchentlicher Orakel-Report. {context}{caveat}"
|
||||
f"Streak: {stats['streak']} Tage. "
|
||||
f"Compliance über {window} Tag(e): {stats['compliance_percent']}%. "
|
||||
f"Genommen gesamt: {stats['total_taken']}."
|
||||
)
|
||||
text = await _call_openrouter(prompt, system=ORACLE_SYSTEM)
|
||||
if not text:
|
||||
text = pick("streak", streak=stats["streak"]) + f" Compliance: {stats['compliance_percent']}%."
|
||||
if young_app:
|
||||
text = (
|
||||
f"Tag {days_active} deiner Medis-Karriere. "
|
||||
f"Streak: {stats['streak']}. Compliance ({window} Tage): {stats['compliance_percent']}%. "
|
||||
"Das Orakel ist beeindruckt — oder gelangweilt. Grenzwertig."
|
||||
)
|
||||
else:
|
||||
text = pick("streak", streak=stats["streak"]) + f" Compliance: {stats['compliance_percent']}%."
|
||||
source = "fallback"
|
||||
else:
|
||||
source = "ai"
|
||||
|
||||
+16
-1
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import pathlib
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
@@ -9,7 +11,7 @@ from fastapi import Depends, FastAPI, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from server.ai import get_oracle, get_roast_of_the_day
|
||||
from server.ai import generate_daily_motivation, get_oracle, get_roast_of_the_day
|
||||
from server.auth import create_token, require_auth, verify_pin
|
||||
from server.config_loader import load_meds_config, slot_to_dict, today_str
|
||||
from server.db import ensure_schema, get_db, new_id, utc_now_iso
|
||||
@@ -21,6 +23,18 @@ from server.slots import build_today
|
||||
from server.stats import build_history, check_milestones, compute_stats, MILESTONE_DEFS
|
||||
|
||||
NO_STORE = {"Cache-Control": "no-store"}
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def _ensure_today_motivation() -> None:
|
||||
config = load_meds_config()
|
||||
db = await get_db()
|
||||
try:
|
||||
await generate_daily_motivation(db, config.timezone)
|
||||
except Exception:
|
||||
logger.exception("Startup motivation generation failed")
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -29,6 +43,7 @@ async def lifespan(app: FastAPI):
|
||||
await ensure_schema(db)
|
||||
await db.close()
|
||||
start_scheduler()
|
||||
asyncio.create_task(_ensure_today_motivation())
|
||||
yield
|
||||
|
||||
|
||||
|
||||
+8
-1
@@ -21,6 +21,13 @@ DEFAULT_MESSAGES: dict[str, list[str]] = {
|
||||
"Dein Gehirn hat heute schon aufgegeben, bevor du die PIN eingegeben hast.",
|
||||
"Elvanse wartet. Du offenbar auch, aber im falschen Sinne.",
|
||||
],
|
||||
"motivation_fallback": [
|
||||
"Dein Gehirn ist nicht kaputt. Es läuft nur auf einem anderen Betriebssystem — ohne Support.",
|
||||
"Du bist nicht faul. Dein Dopamin ist nur gerade in einem Meeting ohne Agenda.",
|
||||
"Heute ist ein guter Tag — oder zumindest einer, an dem Medis existieren.",
|
||||
"ADHS: where focus goes to die. Medis: der Respawn-Button.",
|
||||
"Du schaffst das. Nicht alles, aber Medis. Das zählt.",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +46,7 @@ def load_messages(path: str | None = None) -> dict[str, list[str]]:
|
||||
|
||||
def pick(category: str, **fmt: Any) -> str:
|
||||
pool = load_messages()
|
||||
choices = pool.get(category) or pool.get("reminder", ["Medis."])
|
||||
choices = pool.get(category) or pool.get("motivation_fallback") or pool.get("reminder", ["Medis."])
|
||||
text = random.choice(choices)
|
||||
if fmt:
|
||||
try:
|
||||
|
||||
@@ -8,6 +8,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from apscheduler.triggers.date import DateTrigger
|
||||
|
||||
from server.ai import generate_daily_motivation
|
||||
from server.config_loader import load_meds_config, slot_to_dict, today_str
|
||||
from server.db import get_db, utc_now_iso
|
||||
from server.messages import pick
|
||||
@@ -37,6 +38,17 @@ async def _remind_slot(slot_id: str) -> None:
|
||||
await db.close()
|
||||
|
||||
|
||||
async def _generate_daily_motivation() -> None:
|
||||
config = load_meds_config()
|
||||
db = await get_db()
|
||||
try:
|
||||
await generate_daily_motivation(db, config.timezone)
|
||||
except Exception:
|
||||
logger.exception("Daily motivation generation failed")
|
||||
finally:
|
||||
await db.close()
|
||||
|
||||
|
||||
async def _evening_check() -> None:
|
||||
db = await get_db()
|
||||
try:
|
||||
@@ -100,6 +112,13 @@ def start_scheduler() -> None:
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
scheduler.add_job(
|
||||
_generate_daily_motivation,
|
||||
trigger=CronTrigger(hour=3, minute=0, timezone=tz),
|
||||
id="daily-motivation",
|
||||
replace_existing=True,
|
||||
)
|
||||
|
||||
if not scheduler.running:
|
||||
scheduler.start()
|
||||
logger.info("Scheduler started for timezone %s", tz)
|
||||
|
||||
+22
-4
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
@@ -9,6 +9,15 @@ import aiosqlite
|
||||
from server.config_loader import load_meds_config, today_str
|
||||
from server.db import new_id, utc_now_iso
|
||||
|
||||
|
||||
async def get_first_intake_day(db: aiosqlite.Connection, tz: ZoneInfo) -> str:
|
||||
cur = await db.execute("SELECT MIN(day) FROM intake_log WHERE status = 'taken'")
|
||||
row = await cur.fetchone()
|
||||
await cur.close()
|
||||
if row and row[0]:
|
||||
return str(row[0])
|
||||
return today_str(tz)
|
||||
|
||||
MILESTONE_DEFS: dict[str, str] = {
|
||||
"log_50": "Pharma-Intern: 50 Logs. Dein Arzt wäre stolz. Vielleicht.",
|
||||
"log_100": "Century Club: 100 Logs. Du bist offiziell zuverlässiger als dein WLAN.",
|
||||
@@ -100,12 +109,18 @@ async def compute_stats(db: aiosqlite.Connection) -> dict[str, Any]:
|
||||
slot_ids = [s.id for s in config.slots]
|
||||
streak = await compute_streak(db, tz)
|
||||
|
||||
days = 90
|
||||
first_day = await get_first_intake_day(db, tz)
|
||||
first_date = date.fromisoformat(first_day)
|
||||
today = datetime.now(tz).date()
|
||||
days_active = max(1, (today - first_date).days + 1)
|
||||
compliance_window_days = min(90, days_active)
|
||||
|
||||
taken = 0
|
||||
total = 0
|
||||
today = datetime.now(tz).date()
|
||||
for i in range(days):
|
||||
for i in range(compliance_window_days):
|
||||
d = (today - timedelta(days=i)).isoformat()
|
||||
if d < first_day:
|
||||
break
|
||||
for sid in slot_ids:
|
||||
total += 1
|
||||
cur = await db.execute(
|
||||
@@ -122,6 +137,9 @@ async def compute_stats(db: aiosqlite.Connection) -> dict[str, Any]:
|
||||
return {
|
||||
"streak": streak,
|
||||
"compliance_percent": compliance,
|
||||
"compliance_window_days": compliance_window_days,
|
||||
"days_active": days_active,
|
||||
"first_day": first_day,
|
||||
"total_taken": await count_logs(db),
|
||||
"milestones": milestones,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user