diff --git a/CLAUDE.md b/CLAUDE.md index 0ca9d2a..2074ade 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -7,14 +7,14 @@ > **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase, > kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002). > Verteilung über den Markt, Repo öffentlich (E-0005). -> **Status:** 26.11.23 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut: +> **Status:** 26.11.24 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut: > Anmeldung (Passkeys, Kinder mit Gerät + PIN), Gerichte (Link, Kochbuchfoto, AI über den > Olares Router), Wünschen, Plan, Einkaufsliste (Echtzeit, offline), Kochmodus mit > Bewertung, Web-App; Einzahl bei Stück-Mengen (26.11.15), Preise und Kosten mit Ampel > (V2a, 26.11.16), Olares Router als Standard (26.11.17), untere Leiste am iPhone (26.11.18), > Rolle „Jugendlich“ (26.11.19), Rezepte in einer Form (26.11.20), > Produkte je Gericht (26.11.21), Veto mit Gegenvorschlag (26.11.22), -> bis zu 5 Fotos je Gericht (26.11.23). Offen sind V2b (Kassenbons) +> bis zu 5 Fotos je Gericht (26.11.23), Gerichte einsprechen (26.11.24). Offen sind V2b (Kassenbons) > und der Magic Link. > **Letzte Aktualisierung:** 7. November 2026 @@ -363,6 +363,17 @@ Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt `setCover`; `removePhoto`: nächstes rückt nach). Hinzufügen: `WISHERS` (auch Kinder, über „Foto vom Essen“ in der Bewertungskarte); Vorschau und Entfernen: `PLANNERS`. +## Gerichte einsprechen (seit 26.11.24) + +- `/gerichte/sprechen`: Aufnahme (MediaRecorder) → `/api/dishes/voice` → `transcribe` + (`/audio/transcriptions`, Router `default-stt`, eigener Endpunkt: + `household_ai.speech_model`, Migration 0015) → Abschrift prüfen → `/api/dishes/text-import` + (`DICTATION_PROMPT`) → `draftFromRecipe` wie beim Link. Die Aufnahme wird nicht gespeichert. +- **Mengen und Zeiten nur, wenn gesagt** (`lib/spoken-numbers.ts`: Ziffern und Zahlwörter, + auch „zweihundertfünfzig“; `guardAmounts`, `guardSteps`). +- `Permissions-Policy` erlaubt das Mikrofon nur für die eigene Seite (`next.config.ts`). + Playwright nimmt mit künstlichem Mikrofon auf (`playwright.config.ts`, `launchOptions`). + ## Rollen - `admin`, `member`, `teen` (seit 26.11.19), `child`, `guest`. Wer was darf, steht nur diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index ab2a21c..b0a9083 100644 --- a/OlaresManifest.yaml +++ b/OlaresManifest.yaml @@ -21,7 +21,7 @@ metadata: title: What's cooking? description: The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.23 + version: 26.11.24 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.23' + versionName: '26.11.24' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/app/(app)/gerichte/hinzufuegen/page.tsx b/app/(app)/gerichte/hinzufuegen/page.tsx index 31188ec..42f7037 100644 --- a/app/(app)/gerichte/hinzufuegen/page.tsx +++ b/app/(app)/gerichte/hinzufuegen/page.tsx @@ -1,9 +1,9 @@ -import { Camera, ChevronRight, Link2, PenLine, Sparkles } from "lucide-react"; +import { Camera, ChevronRight, Link2, Mic, PenLine, Sparkles } from "lucide-react"; import Link from "next/link"; import { getTranslations } from "next-intl/server"; import { requireSession } from "@/lib/auth/session"; -// Wege in den Pool: Klassiker, Link, Kochbuchfoto, von Hand. +// Wege in den Pool: Klassiker, Link, Kochbuchfoto, einsprechen, von Hand. export default async function AddDishPage() { await requireSession(); const t = await getTranslations("dishes"); @@ -11,6 +11,7 @@ export default async function AddDishPage() { { href: "/gerichte/vorlagen", icon: Sparkles, title: t("addStarters"), text: t("addStartersText") }, { href: "/gerichte/link", icon: Link2, title: t("addLink"), text: t("addLinkText") }, { href: "/gerichte/foto", icon: Camera, title: t("addPhoto"), text: t("addPhotoText") }, + { href: "/gerichte/sprechen", icon: Mic, title: t("addVoice"), text: t("addVoiceText") }, { href: "/gerichte/neu", icon: PenLine, title: t("addManual"), text: t("addManualText") }, ]; return ( diff --git a/app/(app)/gerichte/sprechen/page.tsx b/app/(app)/gerichte/sprechen/page.tsx new file mode 100644 index 0000000..ae3c495 --- /dev/null +++ b/app/(app)/gerichte/sprechen/page.tsx @@ -0,0 +1,30 @@ +import { redirect } from "next/navigation"; +import { getTranslations } from "next-intl/server"; +import { VoiceImport } from "@/components/dishes/voice-import"; +import { aiFor } from "@/lib/ai-settings"; +import { requireSession } from "@/lib/auth/session"; + +export const dynamic = "force-dynamic"; + +export default async function SpeakDishPage() { + const session = await requireSession(); + if (session.role !== "admin" && session.role !== "member") redirect("/gerichte"); + const t = await getTranslations("dishes"); + const ai = await aiFor(session.householdId); + return ( +
+
+

{t("addEyebrow")}

+

{t("voice.title")}

+

{t("voice.intro")}

+
+ {ai?.textModel ? ( + + ) : ( +

+ {t("voice.noAi")} +

+ )} +
+ ); +} diff --git a/app/(app)/mehr/ki/page.tsx b/app/(app)/mehr/ki/page.tsx index b62fdd2..d9945ef 100644 --- a/app/(app)/mehr/ki/page.tsx +++ b/app/(app)/mehr/ki/page.tsx @@ -28,7 +28,11 @@ export default async function AiSettingsPage() { diff --git a/app/api/ai/settings/route.ts b/app/api/ai/settings/route.ts index 1c7b27d..dc34d8a 100644 --- a/app/api/ai/settings/route.ts +++ b/app/api/ai/settings/route.ts @@ -17,6 +17,7 @@ const input = z.object({ .refine((u) => /^https?:\/\//.test(u)), textModel: z.string().trim().max(200).nullable().optional(), visionModel: z.string().trim().max(200).nullable().optional(), + speechModel: z.string().trim().max(200).nullable().optional(), // undefined: Schlüssel bleibt; Text: neuer Schlüssel; null: Schlüssel entfernen apiKey: z.string().trim().max(500).nullable().optional(), }); @@ -26,15 +27,15 @@ export async function PUT(request: Request) { if (isResponse(session)) return session; const body = input.safeParse(await readJson(request)); if (!body.success) return fail("invalid", 400); - const { endpoint, textModel, visionModel, apiKey } = body.data; + const { endpoint, textModel, visionModel, speechModel, apiKey } = body.data; const sealed = apiKey ? await seal(apiKey) : null; await withHousehold(session.householdId, (c) => c.query( - `insert into household_ai (household_id, endpoint, text_model, vision_model, api_key_enc, updated_by) - values ($1, $2, $3, $4, $5, $6) - on conflict (household_id) do update set endpoint = $2, text_model = $3, vision_model = $4, + `insert into household_ai (household_id, endpoint, text_model, vision_model, speech_model, api_key_enc, updated_by) + values ($1, $2, $3, $4, $8, $5, $6) + on conflict (household_id) do update set endpoint = $2, text_model = $3, vision_model = $4, speech_model = $8, api_key_enc = case when $7 then $5 else household_ai.api_key_enc end, updated_by = $6, updated_at = now()`, - [session.householdId, endpoint, textModel || null, visionModel || null, sealed, session.memberId, apiKey !== undefined], + [session.householdId, endpoint, textModel || null, visionModel || null, sealed, session.memberId, apiKey !== undefined, speechModel || null], ), ); return json({ ok: true }); diff --git a/app/api/dishes/text-import/route.ts b/app/api/dishes/text-import/route.ts new file mode 100644 index 0000000..be43ec6 --- /dev/null +++ b/app/api/dishes/text-import/route.ts @@ -0,0 +1,32 @@ +import { getLocale } from "next-intl/server"; +import { z } from "zod"; +import { AiUnavailable, askJson, DICTATION_PROMPT, recipeFromReply } from "@/lib/ai"; +import { aiFor } from "@/lib/ai-settings"; +import { guardWrite, isResponse } from "@/lib/auth/guard"; +import { fail, json, readJson } from "@/lib/auth/http"; +import { draftFromRecipe } from "@/lib/recipe-draft"; +import { guardAmounts, guardSteps } from "@/lib/spoken-numbers"; + +export const dynamic = "force-dynamic"; + +// Gericht einsprechen, Schritt 2: Abschrift (oder diktierter Text) → Entwurf im +// Formular. Mengen nur, wenn sie gesagt wurden (lib/spoken-numbers.ts); danach +// derselbe Weg wie beim Link: Zutaten zuordnen, Hausform, Timer. Gespeichert wird nichts. +export async function POST(request: Request) { + const session = await guardWrite(request); + if (isResponse(session)) return session; + const body = z.object({ text: z.string().trim().min(20).max(20000) }).safeParse(await readJson(request)); + if (!body.success) return fail("short", 400); + const ai = await aiFor(session.householdId); + if (!ai?.textModel) return fail("noAi", 409); + let recipe; + try { + recipe = recipeFromReply(await askJson(ai, "text", DICTATION_PROMPT, body.data.text)); + } catch (error) { + if (error instanceof AiUnavailable) return fail("aiUnavailable", 503); + throw error; + } + if (!recipe) return fail("noRecipe", 422); + recipe = { ...recipe, ingredients: guardAmounts(recipe.ingredients, body.data.text), steps: guardSteps(recipe.steps, body.data.text) }; + return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai })), byAi: true }); +} diff --git a/app/api/dishes/voice/route.ts b/app/api/dishes/voice/route.ts new file mode 100644 index 0000000..8c78d45 --- /dev/null +++ b/app/api/dishes/voice/route.ts @@ -0,0 +1,30 @@ +import { getLocale } from "next-intl/server"; +import { AiNotConfigured, AiUnavailable, transcribe } from "@/lib/ai"; +import { aiFor } from "@/lib/ai-settings"; +import { guardWrite, isResponse } from "@/lib/auth/guard"; +import { fail, json } from "@/lib/auth/http"; + +export const dynamic = "force-dynamic"; + +const MAX_BYTES = 25 * 1024 * 1024; // rund zehn Minuten Sprache + +// Gericht einsprechen, Schritt 1: Aufnahme → Abschrift (Router „default-stt“ oder +// eigenes Sprachmodell). Die Aufnahme wird nicht gespeichert. +export async function POST(request: Request) { + const session = await guardWrite(request); + if (isResponse(session)) return session; + const form = await request.formData().catch(() => null); + const audio = form?.get("audio"); + if (!(audio instanceof File) || audio.size === 0 || audio.size > MAX_BYTES || !/^(audio|video)\//.test(audio.type)) return fail("audio", 400); + const ai = await aiFor(session.householdId); + if (!ai?.speechModel) return fail("noSpeech", 409); + try { + const ext = audio.type.includes("mp4") || audio.type.includes("m4a") ? "m4a" : audio.type.includes("ogg") ? "ogg" : audio.type.includes("wav") ? "wav" : "webm"; + const text = await transcribe(ai, audio, `aufnahme.${ext}`, await getLocale()); + if (!text) return fail("empty", 422); + return json({ text }); + } catch (error) { + if (error instanceof AiUnavailable || error instanceof AiNotConfigured) return fail("aiUnavailable", 503); + throw error; + } +} diff --git a/components/dishes/voice-import.tsx b/components/dishes/voice-import.tsx new file mode 100644 index 0000000..da4040b --- /dev/null +++ b/components/dishes/voice-import.tsx @@ -0,0 +1,136 @@ +"use client"; + +import { Mic, Square } from "lucide-react"; +import { useTranslations } from "next-intl"; +import { useEffect, useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Label } from "@/components/ui/label"; +import { ErrorNotice } from "@/components/ui/notice"; +import { DishForm, type DishFormValue } from "./dish-form"; + +const mmss = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; + +// Gericht einsprechen: aufnehmen (Router „default-stt“), Abschrift prüfen, daraus +// einen Entwurf machen lassen — oder gleich ins Textfeld diktieren/schreiben. +// Gespeichert wird erst im Formular, von einem Menschen. +export function VoiceImport({ canRecord }: { canRecord: boolean }) { + const t = useTranslations("dishes.voice"); + const [text, setText] = useState(""); + const [recording, setRecording] = useState(false); + const [seconds, setSeconds] = useState(0); + const [busy, setBusy] = useState<"transcribe" | "draft" | null>(null); + const [error, setError] = useState(null); + const [draft, setDraft] = useState(null); + const recorder = useRef(null); + const chunks = useRef([]); + + useEffect(() => { + if (!recording) return; + const tick = setInterval(() => setSeconds((s) => s + 1), 1000); + return () => clearInterval(tick); + }, [recording]); + + async function start() { + setError(null); + try { + const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); + const type = ["audio/mp4", "audio/webm;codecs=opus", "audio/webm"].find((x) => MediaRecorder.isTypeSupported?.(x)); + const rec = new MediaRecorder(stream, type ? { mimeType: type } : undefined); + chunks.current = []; + rec.ondataavailable = (e) => e.data.size && chunks.current.push(e.data); + rec.onstop = () => { + stream.getTracks().forEach((track) => track.stop()); + void upload(new Blob(chunks.current, { type: rec.mimeType || "audio/webm" })); + }; + rec.start(1000); + recorder.current = rec; + setSeconds(0); + setRecording(true); + } catch { + setError("mic"); + } + } + + function stop() { + setRecording(false); + recorder.current?.stop(); + } + + async function upload(audio: Blob) { + setBusy("transcribe"); + const form = new FormData(); + form.append("audio", new File([audio], "aufnahme", { type: audio.type })); + const res = await fetch("/api/dishes/voice", { method: "POST", body: form }).catch(() => null); + const data = await res?.json().catch(() => ({})); + setBusy(null); + if (!res?.ok) return setError(["noSpeech", "aiUnavailable", "empty", "audio"].includes(data?.error) ? data.error : "unknown"); + setText((old) => (old.trim() ? `${old.trim()}\n${data.text}` : data.text)); + } + + async function makeDraft() { + setBusy("draft"); + setError(null); + const res = await fetch("/api/dishes/text-import", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ text }), + }).catch(() => null); + const data = await res?.json().catch(() => ({})); + setBusy(null); + if (!res?.ok) return setError(["short", "noAi", "aiUnavailable", "noRecipe"].includes(data?.error) ? data.error : "unknown"); + setDraft({ ...data, base: null, tags: [], isTrial: false }); + } + + if (draft) { + return ( +
+

{t("check")}

+ +
+ ); + } + + return ( +
+ {canRecord ? ( +
+ +

+ {recording ? t("recording", { time: mmss(seconds) }) : busy === "transcribe" ? t("transcribing") : t("recordHint")} +

+
+ ) : ( +

+ {t("noSpeech")} +

+ )} +
+ +