Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e8f703db1 |
+6
-23
@@ -5,13 +5,11 @@ activity rows — no own table, no migration (ADR-003), and changing the rules r
|
|||||||
|
|
||||||
«Without pressure»: points only add up (a skipped day takes nothing away), growth counts the fact of an activity
|
«Without pressure»: points only add up (a skipped day takes nothing away), growth counts the fact of an activity
|
||||||
and never its content (scale scores, mood), and there is no comparison between patients. Only the patient sees it.
|
and never its content (scale scores, mood), and there is no comparison between patients. Only the patient sees it.
|
||||||
An honest «Пропущу» on a dose grows the garden like «Принял(а)», so the garden never rewards a false «taken» (#120).
|
|
||||||
After a recent acute/high alert the garden is `quiet`: growth stays, celebration does not.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from collections.abc import Iterable
|
from collections.abc import Iterable
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Literal
|
from typing import Literal
|
||||||
@@ -23,7 +21,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.core import clock
|
from app.core import clock
|
||||||
from app.core.intake_questions import DIARY_KINDS
|
from app.core.intake_questions import DIARY_KINDS
|
||||||
from app.db.clinical import Alert, DailyCheckin, Dose, ScaleResult
|
from app.db.clinical import DailyCheckin, Dose, ScaleResult
|
||||||
from app.db.intake import QuestionnaireRecord
|
from app.db.intake import QuestionnaireRecord
|
||||||
|
|
||||||
Activity = Literal["meds", "diary", "questionnaire"]
|
Activity = Literal["meds", "diary", "questionnaire"]
|
||||||
@@ -39,15 +37,8 @@ class TitleRule(BaseModel):
|
|||||||
title: str
|
title: str
|
||||||
|
|
||||||
|
|
||||||
class QuietRule(BaseModel):
|
|
||||||
alert_levels: list[str]
|
|
||||||
hours: int
|
|
||||||
|
|
||||||
|
|
||||||
class GardenConfig(BaseModel):
|
class GardenConfig(BaseModel):
|
||||||
activities: dict[Activity, ActivityRule]
|
activities: dict[Activity, ActivityRule]
|
||||||
answered_dose_statuses: list[str]
|
|
||||||
quiet: QuietRule
|
|
||||||
step_points: int
|
step_points: int
|
||||||
stages_per_plant: int
|
stages_per_plant: int
|
||||||
max_plants: int
|
max_plants: int
|
||||||
@@ -82,7 +73,6 @@ class Garden(BaseModel):
|
|||||||
points_in_step: int # progress towards the next growth step: «8 из 10»
|
points_in_step: int # progress towards the next growth step: «8 из 10»
|
||||||
plants: list[Plant]
|
plants: list[Plant]
|
||||||
today: list[TodayItem]
|
today: list[TodayItem]
|
||||||
quiet: bool = False # recent acute/high alert: no «Сад подрос», no grow-in animation
|
|
||||||
|
|
||||||
|
|
||||||
def compute(events: Iterable[tuple[Activity, date]], today: date, cfg: GardenConfig | None = None) -> Garden:
|
def compute(events: Iterable[tuple[Activity, date]], today: date, cfg: GardenConfig | None = None) -> Garden:
|
||||||
@@ -123,7 +113,7 @@ async def garden_for(s: AsyncSession, token: str) -> Garden:
|
|||||||
|
|
||||||
doses = (await s.scalars(select(Dose).where(Dose.token == token))).all()
|
doses = (await s.scalars(select(Dose).where(Dose.token == token))).all()
|
||||||
for d in doses:
|
for d in doses:
|
||||||
if d.status in cfg.answered_dose_statuses:
|
if d.status == "taken":
|
||||||
events.append(("meds", _day(d.answered_at or d.planned_at, tz)))
|
events.append(("meds", _day(d.answered_at or d.planned_at, tz)))
|
||||||
checkins = (await s.scalars(select(DailyCheckin).where(DailyCheckin.token == token))).all()
|
checkins = (await s.scalars(select(DailyCheckin).where(DailyCheckin.token == token))).all()
|
||||||
for c in checkins:
|
for c in checkins:
|
||||||
@@ -143,26 +133,19 @@ async def garden_for(s: AsyncSession, token: str) -> Garden:
|
|||||||
events.append(("questionnaire", _day(sc.ts, tz)))
|
events.append(("questionnaire", _day(sc.ts, tz)))
|
||||||
|
|
||||||
garden = compute(events, today, cfg)
|
garden = compute(events, today, cfg)
|
||||||
since = now - timedelta(hours=cfg.quiet.hours)
|
|
||||||
recent_alert = await s.scalar(
|
|
||||||
select(Alert.id)
|
|
||||||
.where(Alert.token == token, Alert.level.in_(cfg.quiet.alert_levels), Alert.ts >= since, Alert.ts <= now)
|
|
||||||
.limit(1)
|
|
||||||
)
|
|
||||||
garden.quiet = recent_alert is not None
|
|
||||||
done_today = {kind for kind, day in events if day == today}
|
done_today = {kind for kind, day in events if day == today}
|
||||||
|
|
||||||
items: list[TodayItem] = []
|
items: list[TodayItem] = []
|
||||||
due = [d for d in doses if _day(d.planned_at, tz) == today]
|
due = [d for d in doses if _day(d.planned_at, tz) == today]
|
||||||
if due:
|
if due:
|
||||||
answered = sum(d.status in cfg.answered_dose_statuses for d in due)
|
taken = sum(d.status == "taken" for d in due)
|
||||||
due_now = sum(d.planned_at <= now for d in due)
|
due_now = sum(d.planned_at <= now for d in due)
|
||||||
items.append(
|
items.append(
|
||||||
TodayItem(
|
TodayItem(
|
||||||
activity="meds",
|
activity="meds",
|
||||||
title=cfg.today["meds"],
|
title=cfg.today["meds"],
|
||||||
done=answered > 0 and answered >= due_now,
|
done=taken > 0 and taken >= due_now,
|
||||||
detail=f"{answered} из {len(due)}",
|
detail=f"{taken} из {len(due)}",
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
items.append(TodayItem(activity="diary", title=cfg.today["diary"], done="diary" in done_today))
|
items.append(TodayItem(activity="diary", title=cfg.today["diary"], done="diary" in done_today))
|
||||||
|
|||||||
+2
-14
@@ -3,13 +3,10 @@
|
|||||||
# 1. Сад не вянет: очки только прибавляются, пропуск ничего не отнимает.
|
# 1. Сад не вянет: очки только прибавляются, пропуск ничего не отнимает.
|
||||||
# 2. Рост не зависит от ответов: считается факт активности, а не баллы шкал или настроение.
|
# 2. Рост не зависит от ответов: считается факт активности, а не баллы шкал или настроение.
|
||||||
# 3. Нет соревнования: только свой сад, никаких сравнений.
|
# 3. Нет соревнования: только свой сад, никаких сравнений.
|
||||||
# 4. Растит честная отметка, а не «правильный» ответ: «Пропущу» по дозе растит сад так же, как «Принял(а)»,
|
|
||||||
# иначе сад подталкивал бы отмечать приём, которого не было, и искажал бы данные о приёме для врача.
|
|
||||||
# 5. После кризиса — тишина: рост сохраняется, но без поздравлений и анимации.
|
|
||||||
|
|
||||||
# Очки за активность и дневной лимит по каждому типу (чтобы пять одинаковых действий подряд не давали пятикратный рост).
|
# Очки за активность и дневной лимит по каждому типу (чтобы пять одинаковых действий подряд не давали пятикратный рост).
|
||||||
activities:
|
activities:
|
||||||
meds: # ответ по назначенной дозе: «Принял(а)» или «Пропущу» (см. answered_dose_statuses)
|
meds: # отметка «Принял(а)» по назначенной дозе
|
||||||
points: 2
|
points: 2
|
||||||
daily_cap: 4
|
daily_cap: 4
|
||||||
diary: # ежедневный чек-ин или запись дневника
|
diary: # ежедневный чек-ин или запись дневника
|
||||||
@@ -19,15 +16,6 @@ activities:
|
|||||||
points: 4
|
points: 4
|
||||||
daily_cap: 1
|
daily_cap: 1
|
||||||
|
|
||||||
# Какие ответы по дозе растят сад. missed (доза осталась без ответа) не растит, но и ничего не отнимает.
|
|
||||||
answered_dose_statuses: [taken, skipped]
|
|
||||||
|
|
||||||
# Тишина после кризиса: если за последние hours часов был алерт одного из этих уровней (в т.ч. по шкале
|
|
||||||
# или опросу, не только в чате), сад не поздравляет и не анимирует рост.
|
|
||||||
quiet:
|
|
||||||
alert_levels: [acute, high]
|
|
||||||
hours: 72
|
|
||||||
|
|
||||||
# Каждые step_points очков — один шаг роста. Растения растут по очереди: у каждого stages_per_plant стадий
|
# Каждые step_points очков — один шаг роста. Растения растут по очереди: у каждого stages_per_plant стадий
|
||||||
# (росток → стебель → бутон → цветок); распустился один — проклёвывается следующий.
|
# (росток → стебель → бутон → цветок); распустился один — проклёвывается следующий.
|
||||||
step_points: 10
|
step_points: 10
|
||||||
@@ -45,6 +33,6 @@ titles:
|
|||||||
|
|
||||||
# Подписи пунктов «Сегодня».
|
# Подписи пунктов «Сегодня».
|
||||||
today:
|
today:
|
||||||
meds: "Отметка о лекарствах"
|
meds: "Приём лекарств"
|
||||||
diary: "Запись в дневнике"
|
diary: "Запись в дневнике"
|
||||||
questionnaire: "Назначенный опрос"
|
questionnaire: "Назначенный опрос"
|
||||||
|
|||||||
@@ -3,16 +3,6 @@
|
|||||||
> Живой журнал: **что** решили и **почему**. Новые записи — сверху. Одна запись = одно решение.
|
> Живой журнал: **что** решили и **почему**. Новые записи — сверху. Одна запись = одно решение.
|
||||||
> При конфликте с [`docs/info/SPEC.md`](info/SPEC.md) действует ADR.
|
> При конфликте с [`docs/info/SPEC.md`](info/SPEC.md) действует ADR.
|
||||||
|
|
||||||
## 2026-10-31 — ADR-015: Сад — растит честная отметка, после кризиса тишина, материалы не считаются
|
|
||||||
**Контекст:** геймификация при ПТСР и депрессии клинически чувствительна (#120). Сад (#118, #119) не должен давить, подменять клиническую динамику и искажать данные для врача. Решение принято командой и **ждёт вычитки психиатром** (отметка в #120).
|
|
||||||
**Решение:**
|
|
||||||
1. Растит **факт честного ответа**, а не «правильный» ответ: «Пропущу» по дозе растит сад так же, как «Принял(а)» (`answered_dose_statuses`). Иначе сад подталкивал бы отмечать приём, которого не было, и врач видел бы ложную приверженность. Доза без ответа (`missed`) не растит, но ничего и не отнимает.
|
|
||||||
2. Настроение и баллы шкал на рост не влияют. Очки только прибавляются, дневные лимиты есть по каждому типу активности. Сравнения с другими пациентами нет.
|
|
||||||
3. **Тишина после кризиса:** если за 72 ч был алерт уровня `acute`/`high` из любого источника (чат, шкала, опрос), сервер отдаёт `quiet` — рост сохраняется, но без «Сад подрос» и анимации.
|
|
||||||
4. Тексты не обещают улучшения: «Растёт от ваших отметок» вместо «Растёт вместе с вами»; о пропуске — «сад не вянет», без «не страшно».
|
|
||||||
5. **Материалы от врача не растят сад:** просмотр пассивен, награда за него поощряла бы пролистывание. Если такой раздел появится, его можно учесть только как отдельное решение после вычитки.
|
|
||||||
**Последствия:** правила и пороги — в `config/garden.yaml`, тексты — в `web/src/content/ru.ts`; менять их можно без кода по итогам вычитки.
|
|
||||||
|
|
||||||
## 2026-10-31 — ADR-014: Голосовой ввод — расшифровка отдельно от диалога; OpenRouter только на синтетике
|
## 2026-10-31 — ADR-014: Голосовой ввод — расшифровка отдельно от диалога; OpenRouter только на синтетике
|
||||||
**Контекст:** для гранта ВШЭ и пилота «Династия» нужен голосовой ввод (слайд 11: «Записать → Проверить → Сводка»). Голос — ПДн, а `scrub()` его не обезличивает. OpenRouter — зарубежный сервис (ADR-004, guardrail 9).
|
**Контекст:** для гранта ВШЭ и пилота «Династия» нужен голосовой ввод (слайд 11: «Записать → Проверить → Сводка»). Голос — ПДн, а `scrub()` его не обезличивает. OpenRouter — зарубежный сервис (ADR-004, guardrail 9).
|
||||||
**Решение:**
|
**Решение:**
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from sqlalchemy import select
|
|||||||
from app.config import Settings
|
from app.config import Settings
|
||||||
from app.core import clock
|
from app.core import clock
|
||||||
from app.db import session
|
from app.db import session
|
||||||
from app.db.clinical import Alert, DailyCheckin, Dose
|
from app.db.clinical import DailyCheckin, Dose
|
||||||
from app.main import app
|
from app.main import app
|
||||||
from app.services.garden import compute, load_config
|
from app.services.garden import compute, load_config
|
||||||
from scripts.seed_demo import seed
|
from scripts.seed_demo import seed
|
||||||
@@ -83,50 +83,6 @@ async def test_andrey_has_a_living_garden_that_grows_and_ignores_mood(client: As
|
|||||||
assert any(i["activity"] == "diary" for i in after["today"])
|
assert any(i["activity"] == "diary" for i in after["today"])
|
||||||
|
|
||||||
|
|
||||||
async def test_honest_skip_grows_like_taken_and_missed_does_not(client: AsyncClient) -> None:
|
|
||||||
"""#120: the garden rewards an honest answer, never a «taken» mark — otherwise it would push to false marks."""
|
|
||||||
token = (await seed(12)).andrey_token
|
|
||||||
url = f"/api/v1/me/{token}/garden"
|
|
||||||
base = (await client.get(url)).json()["points"]
|
|
||||||
async with session.get_clinical_session() as s:
|
|
||||||
for d in (await s.scalars(select(Dose).where(Dose.token == token))).all():
|
|
||||||
await s.delete(d)
|
|
||||||
none = (await client.get(url)).json()["points"]
|
|
||||||
|
|
||||||
async def with_dose(status: str) -> int:
|
|
||||||
async with session.get_clinical_session() as s:
|
|
||||||
for d in (await s.scalars(select(Dose).where(Dose.token == token))).all():
|
|
||||||
await s.delete(d)
|
|
||||||
s.add(Dose(token=token, prescription_id=1, planned_at=clock.now(), status=status, answered_at=clock.now()))
|
|
||||||
return (await client.get(url)).json()["points"]
|
|
||||||
|
|
||||||
assert await with_dose("taken") == await with_dose("skipped") > none
|
|
||||||
assert await with_dose("missed") == none
|
|
||||||
assert base >= none
|
|
||||||
|
|
||||||
|
|
||||||
async def test_quiet_after_recent_high_alert(client: AsyncClient) -> None:
|
|
||||||
"""#120: no celebration after a crisis signal from any source; an old or moderate alert does not silence it."""
|
|
||||||
token = (await seed(12)).andrey_token
|
|
||||||
url = f"/api/v1/me/{token}/garden"
|
|
||||||
async with session.get_clinical_session() as s:
|
|
||||||
for a in (await s.scalars(select(Alert).where(Alert.token == token))).all():
|
|
||||||
await s.delete(a)
|
|
||||||
assert (await client.get(url)).json()["quiet"] is False
|
|
||||||
|
|
||||||
def alert(level: str, hours_ago: int) -> Alert:
|
|
||||||
ts = clock.now() - timedelta(hours=hours_ago)
|
|
||||||
return Alert(token=token, ts=ts, level=level, code="test", reason="test", params={})
|
|
||||||
|
|
||||||
async with session.get_clinical_session() as s:
|
|
||||||
s.add_all([alert("moderate", 1), alert("acute", 24 * 10)])
|
|
||||||
assert (await client.get(url)).json()["quiet"] is False
|
|
||||||
async with session.get_clinical_session() as s:
|
|
||||||
s.add(alert("high", 2))
|
|
||||||
quiet = (await client.get(url)).json()
|
|
||||||
assert quiet["quiet"] is True and quiet["points"] > 0
|
|
||||||
|
|
||||||
|
|
||||||
async def test_unknown_patient_404(client: AsyncClient) -> None:
|
async def test_unknown_patient_404(client: AsyncClient) -> None:
|
||||||
await seed(0)
|
await seed(0)
|
||||||
assert (await client.get("/api/v1/me/nobody/garden")).status_code == 404
|
assert (await client.get("/api/v1/me/nobody/garden")).status_code == 404
|
||||||
|
|||||||
@@ -14,6 +14,5 @@ server {
|
|||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_buffering off;
|
proxy_buffering off;
|
||||||
proxy_read_timeout 120s;
|
proxy_read_timeout 120s;
|
||||||
client_max_body_size 4m; # voice input: up to 60 s of 16 kHz WAV (~1.9 MB)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-17
@@ -47,23 +47,7 @@ export const api = {
|
|||||||
signInAnonymous: (focus?: Focus) => post<AuthResult>("/auth/anonymous", { focus }),
|
signInAnonymous: (focus?: Focus) => post<AuthResult>("/auth/anonymous", { focus }),
|
||||||
// Presentation entry: a fresh private copy of the demo patient, straight to the chat.
|
// Presentation entry: a fresh private copy of the demo patient, straight to the chat.
|
||||||
signInDemoFresh: () => post<AuthResult>("/auth/demo/fresh", {}),
|
signInDemoFresh: () => post<AuthResult>("/auth/demo/fresh", {}),
|
||||||
patientCapabilities: () =>
|
patientCapabilities: () => request<{ primary_screening: boolean }>("/patient/capabilities"),
|
||||||
request<{ primary_screening: boolean; voice_input?: boolean }>("/patient/capabilities"),
|
|
||||||
// Voice → text for the patient to check (#117). Raw WAV body; the server only transcribes.
|
|
||||||
transcribe: async (token: string, wav: Blob): Promise<string> => {
|
|
||||||
let res: Response;
|
|
||||||
try {
|
|
||||||
res = await fetch(`${BASE}/me/${encodeURIComponent(token)}/stt`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "audio/wav" },
|
|
||||||
body: wav,
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
throw new ApiError(0, "network");
|
|
||||||
}
|
|
||||||
if (!res.ok) throw new ApiError(res.status, res.statusText);
|
|
||||||
return ((await res.json()) as { text: string }).text;
|
|
||||||
},
|
|
||||||
connectDoctor: (token: string) => post<{ has_doctor: boolean }>(`/me/${encodeURIComponent(token)}/doctor/connect`),
|
connectDoctor: (token: string) => post<{ has_doctor: boolean }>(`/me/${encodeURIComponent(token)}/doctor/connect`),
|
||||||
demoPersonas: () => request<DemoPersona[]>("/patient/demo-personas"),
|
demoPersonas: () => request<DemoPersona[]>("/patient/demo-personas"),
|
||||||
crisisResources: () => request<CrisisResource[]>("/crisis/resources"),
|
crisisResources: () => request<CrisisResource[]>("/crisis/resources"),
|
||||||
|
|||||||
@@ -192,6 +192,4 @@ export interface Garden {
|
|||||||
points_in_step: number;
|
points_in_step: number;
|
||||||
plants: { stage: number }[];
|
plants: { stage: number }[];
|
||||||
today: { activity: GardenActivity; title: string; done: boolean; detail: string | null }[];
|
today: { activity: GardenActivity; title: string; done: boolean; detail: string | null }[];
|
||||||
/** Recent acute/high alert (#120): growth stays, no toast or animation. */
|
|
||||||
quiet: boolean;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -70,10 +70,9 @@ export function Garden({ refreshKey }: { refreshKey?: unknown }) {
|
|||||||
setGarden(g);
|
setGarden(g);
|
||||||
const raw = window.localStorage.getItem(seenKey(session.token));
|
const raw = window.localStorage.getItem(seenKey(session.token));
|
||||||
const seen = raw === null ? null : Number(raw);
|
const seen = raw === null ? null : Number(raw);
|
||||||
// No celebration right after a crisis: growth stays, the toast and the animation do not. The server knows
|
// No celebration right after a crisis: growth stays, the toast and the animation do not.
|
||||||
// about alerts from scales and questionnaires too (`quiet`); the chat check covers a crisis reply just shown.
|
|
||||||
const recentCrisis = dialog.entries.slice(-12).some((e) => e.from === "assistant" && e.reply.kind === "crisis");
|
const recentCrisis = dialog.entries.slice(-12).some((e) => e.from === "assistant" && e.reply.kind === "crisis");
|
||||||
if (seen !== null && g.steps > seen && !g.quiet && !recentCrisis) {
|
if (seen !== null && g.steps > seen && !recentCrisis) {
|
||||||
setFreshFrom(seen);
|
setFreshFrom(seen);
|
||||||
if (!announced.current) toast(ru.garden.grew);
|
if (!announced.current) toast(ru.garden.grew);
|
||||||
announced.current = true;
|
announced.current = true;
|
||||||
|
|||||||
@@ -32,12 +32,6 @@ const paths = {
|
|||||||
arrowLeft: <path d="M19 12H5m6-6l-6 6 6 6" />,
|
arrowLeft: <path d="M19 12H5m6-6l-6 6 6 6" />,
|
||||||
close: <path d="M6 6l12 12M18 6L6 18" />,
|
close: <path d="M6 6l12 12M18 6L6 18" />,
|
||||||
check: <path d="M5 12.5l4.5 4.5L19 7.5" />,
|
check: <path d="M5 12.5l4.5 4.5L19 7.5" />,
|
||||||
mic: (
|
|
||||||
<>
|
|
||||||
<rect x="9" y="3" width="6" height="11" rx="3" />
|
|
||||||
<path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21" />
|
|
||||||
</>
|
|
||||||
),
|
|
||||||
x: <path d="M7 7l10 10M17 7L7 17" />,
|
x: <path d="M7 7l10 10M17 7L7 17" />,
|
||||||
info: (
|
info: (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -1,165 +0,0 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
|
||||||
|
|
||||||
import { ApiError, api } from "../api/client";
|
|
||||||
import { ru } from "../content/ru";
|
|
||||||
import { useSession } from "../session/SessionContext";
|
|
||||||
import { MAX_SECONDS, Recorder, voiceSupported } from "../voice/recorder";
|
|
||||||
import { Icon } from "./Icon";
|
|
||||||
import { useToast } from "./Toast";
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Voice input next to a free-text field (#117, slide 11: «Записать → Проверить»). The recognised text is put into
|
|
||||||
* the field for the patient to check and edit — never sent automatically: safety and scrub() run when they send it.
|
|
||||||
*/
|
|
||||||
|
|
||||||
let capability: Promise<boolean> | null = null;
|
|
||||||
function voiceEnabled(): Promise<boolean> {
|
|
||||||
capability ??= api
|
|
||||||
.patientCapabilities()
|
|
||||||
.then((c) => Boolean(c.voice_input) && voiceSupported())
|
|
||||||
.catch(() => false);
|
|
||||||
return capability;
|
|
||||||
}
|
|
||||||
|
|
||||||
const BARS = 14;
|
|
||||||
type State = "idle" | "recording" | "transcribing";
|
|
||||||
|
|
||||||
export function VoiceInput({
|
|
||||||
disabled,
|
|
||||||
onText,
|
|
||||||
compact,
|
|
||||||
}: {
|
|
||||||
disabled?: boolean;
|
|
||||||
onText: (text: string) => void;
|
|
||||||
/** Chat composer: a round icon button; the recording panel floats above the composer. */
|
|
||||||
compact?: boolean;
|
|
||||||
}) {
|
|
||||||
const { session } = useSession();
|
|
||||||
const toast = useToast();
|
|
||||||
const [enabled, setEnabled] = useState(false);
|
|
||||||
const [state, setState] = useState<State>("idle");
|
|
||||||
const [seconds, setSeconds] = useState(0);
|
|
||||||
const [levels, setLevels] = useState<number[]>(() => Array(BARS).fill(0));
|
|
||||||
const rec = useRef<Recorder | null>(null);
|
|
||||||
const timer = useRef<number>();
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let alive = true;
|
|
||||||
void voiceEnabled().then((on) => alive && setEnabled(on));
|
|
||||||
return () => {
|
|
||||||
alive = false;
|
|
||||||
window.clearInterval(timer.current);
|
|
||||||
rec.current?.cancel();
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
if (!enabled || !session) return null;
|
|
||||||
|
|
||||||
const start = async () => {
|
|
||||||
const r = new Recorder();
|
|
||||||
try {
|
|
||||||
await r.start((level) => setLevels((prev) => [...prev.slice(1), level]));
|
|
||||||
} catch {
|
|
||||||
r.cancel();
|
|
||||||
toast(ru.voice.noMic);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
rec.current = r;
|
|
||||||
setSeconds(0);
|
|
||||||
setState("recording");
|
|
||||||
const began = Date.now();
|
|
||||||
timer.current = window.setInterval(() => {
|
|
||||||
const s = Math.floor((Date.now() - began) / 1000);
|
|
||||||
setSeconds(s);
|
|
||||||
if (s >= MAX_SECONDS) void stop();
|
|
||||||
}, 250);
|
|
||||||
};
|
|
||||||
|
|
||||||
const reset = () => {
|
|
||||||
window.clearInterval(timer.current);
|
|
||||||
rec.current = null;
|
|
||||||
setLevels(Array(BARS).fill(0));
|
|
||||||
};
|
|
||||||
|
|
||||||
const stop = async () => {
|
|
||||||
const wav = rec.current?.stop() ?? null;
|
|
||||||
reset();
|
|
||||||
if (!wav) {
|
|
||||||
setState("idle");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setState("transcribing");
|
|
||||||
try {
|
|
||||||
const text = await api.transcribe(session.token, wav);
|
|
||||||
onText(text);
|
|
||||||
toast(ru.voice.check);
|
|
||||||
} catch (e) {
|
|
||||||
const status = e instanceof ApiError ? e.status : 0;
|
|
||||||
toast(status === 422 ? ru.voice.noSpeech : status === 413 ? ru.voice.tooLong : ru.voice.failed);
|
|
||||||
} finally {
|
|
||||||
setState("idle");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const cancel = () => {
|
|
||||||
rec.current?.cancel();
|
|
||||||
reset();
|
|
||||||
setState("idle");
|
|
||||||
};
|
|
||||||
|
|
||||||
if (state === "idle" && compact) {
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="mic"
|
|
||||||
disabled={disabled}
|
|
||||||
onClick={() => void start()}
|
|
||||||
aria-label={ru.voice.start}
|
|
||||||
title={ru.voice.start}
|
|
||||||
>
|
|
||||||
<Icon name="mic" size={20} />
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (state === "idle") {
|
|
||||||
return (
|
|
||||||
<button type="button" className="voice-btn" disabled={disabled} onClick={() => void start()}>
|
|
||||||
<Icon name="mic" size={20} />
|
|
||||||
{ru.voice.start}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const mm = String(Math.floor(seconds / 60)).padStart(2, "0");
|
|
||||||
const ss = String(seconds % 60).padStart(2, "0");
|
|
||||||
return (
|
|
||||||
<div className={compact ? "voice voice--float" : "voice"} role="group" aria-label={ru.voice.recording}>
|
|
||||||
{state === "recording" ? (
|
|
||||||
<>
|
|
||||||
<p className="voice__hint">{ru.voice.recording}</p>
|
|
||||||
<div className="voice__wave" aria-hidden="true">
|
|
||||||
{levels.map((l, i) => (
|
|
||||||
<span key={i} style={{ height: `${Math.max(12, Math.round(l * 100))}%` }} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
<div className="voice__row">
|
|
||||||
<span className="voice__time" aria-live="off">
|
|
||||||
{mm}:{ss}
|
|
||||||
</span>
|
|
||||||
<button type="button" className="btn btn--ghost voice__cancel" onClick={cancel}>
|
|
||||||
{ru.voice.cancel}
|
|
||||||
</button>
|
|
||||||
<button type="button" className="btn btn--primary voice__stop" onClick={() => void stop()}>
|
|
||||||
{ru.voice.stop}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<p className="voice__privacy">{ru.voice.privacy}</p>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<p className="voice__hint" aria-live="polite">
|
|
||||||
{ru.voice.transcribing}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+3
-16
@@ -88,12 +88,12 @@ export const ru = {
|
|||||||
},
|
},
|
||||||
garden: {
|
garden: {
|
||||||
eyebrow: "Ваш сад",
|
eyebrow: "Ваш сад",
|
||||||
lead: "Растёт от ваших отметок",
|
lead: "Растёт вместе с вами",
|
||||||
next: "Новый росток",
|
next: "Новый росток",
|
||||||
of: (a: number, b: number) => `${a} из ${b}`,
|
of: (a: number, b: number) => `${a} из ${b}`,
|
||||||
today: "Сегодня",
|
today: "Сегодня",
|
||||||
noPressure: "Сад не вянет от пропусков. Честное «Пропущу» по лекарству тоже растит сад",
|
noPressure: "Пропуск — не страшно, сад не вянет",
|
||||||
grew: "Сад подрос",
|
grew: "Сад подрос — появился новый росток",
|
||||||
label: (title: string, bloom: number, growing: number) =>
|
label: (title: string, bloom: number, growing: number) =>
|
||||||
`${title}. Цветов: ${bloom}, растёт: ${growing}.`,
|
`${title}. Цветов: ${bloom}, растёт: ${growing}.`,
|
||||||
},
|
},
|
||||||
@@ -262,19 +262,6 @@ export const ru = {
|
|||||||
drinksLead: "Посчитайте, сколько порций выходит в обычный день, когда вы выпиваете.",
|
drinksLead: "Посчитайте, сколько порций выходит в обычный день, когда вы выпиваете.",
|
||||||
noticeTitle: "Опрос приостановлен",
|
noticeTitle: "Опрос приостановлен",
|
||||||
},
|
},
|
||||||
voice: {
|
|
||||||
start: "Сказать голосом",
|
|
||||||
stop: "Остановить запись",
|
|
||||||
cancel: "Отменить",
|
|
||||||
recording: "Говорите — запись идёт",
|
|
||||||
transcribing: "Распознаём речь…",
|
|
||||||
check: "Проверьте распознанный текст — его можно исправить перед отправкой.",
|
|
||||||
privacy: "Запись не сохраняется: её видит только система распознавания, текст — специалисты вашей программы.",
|
|
||||||
noMic: "Нет доступа к микрофону. Разрешите его в настройках браузера или напишите текстом.",
|
|
||||||
noSpeech: "Не удалось разобрать речь. Попробуйте ещё раз или напишите текстом.",
|
|
||||||
failed: "Распознавание сейчас недоступно. Напишите, пожалуйста, текстом.",
|
|
||||||
tooLong: "Запись слишком длинная — до минуты за раз.",
|
|
||||||
},
|
|
||||||
messages: {
|
messages: {
|
||||||
typing: "Помощник печатает",
|
typing: "Помощник печатает",
|
||||||
title: "Сообщения",
|
title: "Сообщения",
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import type { Catalog, DialogButton } from "../api/types";
|
|||||||
import { AppShell, Notice, TopBar } from "../components/AppShell";
|
import { AppShell, Notice, TopBar } from "../components/AppShell";
|
||||||
import { HotlineCard, telHref, useHelp } from "../components/HelpSheet";
|
import { HotlineCard, telHref, useHelp } from "../components/HelpSheet";
|
||||||
import { useToast } from "../components/Toast";
|
import { useToast } from "../components/Toast";
|
||||||
import { VoiceInput } from "../components/VoiceInput";
|
|
||||||
import { Icon, type IconName } from "../components/Icon";
|
import { Icon, type IconName } from "../components/Icon";
|
||||||
import { useCatalog } from "../content/reference";
|
import { useCatalog } from "../content/reference";
|
||||||
import { ru } from "../content/ru";
|
import { ru } from "../content/ru";
|
||||||
@@ -260,7 +259,6 @@ function FreeText({
|
|||||||
/>
|
/>
|
||||||
<span className="textarea__count">{text.length}/500</span>
|
<span className="textarea__count">{text.length}/500</span>
|
||||||
</div>
|
</div>
|
||||||
<VoiceInput disabled={busy} onText={(t) => setText((prev) => (prev.trim() ? `${prev.trim()} ${t}` : t).slice(0, 500))} />
|
|
||||||
<div className="btn-row">
|
<div className="btn-row">
|
||||||
{skip ? (
|
{skip ? (
|
||||||
<button type="button" className="btn btn--ghost" disabled={busy} onClick={() => onSkip(skip)}>
|
<button type="button" className="btn btn--ghost" disabled={busy} onClick={() => onSkip(skip)}>
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { useNavigate } from "react-router-dom";
|
|||||||
|
|
||||||
import { AppShell, TopBar } from "../components/AppShell";
|
import { AppShell, TopBar } from "../components/AppShell";
|
||||||
import { Icon } from "../components/Icon";
|
import { Icon } from "../components/Icon";
|
||||||
import { VoiceInput } from "../components/VoiceInput";
|
|
||||||
import { ru } from "../content/ru";
|
import { ru } from "../content/ru";
|
||||||
import { useDialog } from "../dialog/DialogContext";
|
import { useDialog } from "../dialog/DialogContext";
|
||||||
|
|
||||||
@@ -113,11 +112,6 @@ export function Messages() {
|
|||||||
onKeyDown={onKeyDown}
|
onKeyDown={onKeyDown}
|
||||||
maxLength={2000}
|
maxLength={2000}
|
||||||
/>
|
/>
|
||||||
<VoiceInput
|
|
||||||
compact
|
|
||||||
disabled={dialog.busy}
|
|
||||||
onText={(text) => setDraft((prev) => (prev.trim() ? `${prev.trim()} ${text}` : text).slice(0, 2000))}
|
|
||||||
/>
|
|
||||||
<button type="submit" className="send" disabled={dialog.busy || !draft.trim()} aria-label={ru.common.send}>
|
<button type="submit" className="send" disabled={dialog.busy || !draft.trim()} aria-label={ru.common.send}>
|
||||||
<Icon name="send" size={20} />
|
<Icon name="send" size={20} />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1566,106 +1566,6 @@ button.row-card:hover:not(:disabled) {
|
|||||||
color: var(--c-text-3);
|
color: var(--c-text-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- voice input (#117, slide 11) */
|
|
||||||
|
|
||||||
.voice-btn {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--s-2);
|
|
||||||
justify-self: start;
|
|
||||||
min-height: 44px;
|
|
||||||
padding: 0 var(--s-4);
|
|
||||||
border: 1.5px solid var(--c-border-strong);
|
|
||||||
border-radius: 999px;
|
|
||||||
background: var(--c-surface);
|
|
||||||
color: var(--c-teal-strong);
|
|
||||||
font-weight: 600;
|
|
||||||
font-size: var(--fs-14);
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice-btn:hover:not(:disabled) {
|
|
||||||
background: var(--c-teal-soft);
|
|
||||||
}
|
|
||||||
|
|
||||||
.mic {
|
|
||||||
flex: none;
|
|
||||||
width: 44px;
|
|
||||||
height: 44px;
|
|
||||||
display: grid;
|
|
||||||
place-items: center;
|
|
||||||
border: 1.5px solid var(--c-border);
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--c-surface);
|
|
||||||
color: var(--c-teal-strong);
|
|
||||||
}
|
|
||||||
|
|
||||||
.mic:hover:not(:disabled) {
|
|
||||||
background: var(--c-teal-soft);
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice {
|
|
||||||
display: grid;
|
|
||||||
gap: var(--s-3);
|
|
||||||
padding: var(--s-4);
|
|
||||||
border: 1px solid var(--c-border);
|
|
||||||
border-radius: var(--r-tile);
|
|
||||||
background: #fbf6ee; /* warm, as on the slide */
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice--float {
|
|
||||||
position: absolute;
|
|
||||||
left: 0;
|
|
||||||
right: 0;
|
|
||||||
bottom: calc(100% + var(--s-2));
|
|
||||||
box-shadow: 0 8px 24px rgb(33 59 56 / 12%);
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice__hint {
|
|
||||||
margin: 0;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--c-text);
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice__wave {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 5px;
|
|
||||||
height: 44px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice__wave span {
|
|
||||||
flex: 1;
|
|
||||||
max-width: 6px;
|
|
||||||
border-radius: 3px;
|
|
||||||
background: #b5452f;
|
|
||||||
transition: height 90ms linear;
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice__row {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: auto 1fr 1.4fr;
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--s-2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice__time {
|
|
||||||
font-variant-numeric: tabular-nums;
|
|
||||||
font-weight: 600;
|
|
||||||
color: var(--c-text-2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice__row .btn {
|
|
||||||
min-height: 44px;
|
|
||||||
padding: 0 var(--s-3);
|
|
||||||
font-size: var(--fs-14);
|
|
||||||
}
|
|
||||||
|
|
||||||
.voice__privacy {
|
|
||||||
margin: 0;
|
|
||||||
font-size: var(--fs-12);
|
|
||||||
color: var(--c-text-3);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ---------------------------------------------------------------- garden (#119, slide 13) */
|
/* ---------------------------------------------------------------- garden (#119, slide 13) */
|
||||||
|
|
||||||
.garden {
|
.garden {
|
||||||
|
|||||||
@@ -1,121 +0,0 @@
|
|||||||
/*
|
|
||||||
* Voice recording for the patient's messages (#117, slide 11): microphone → 16 kHz mono 16-bit WAV in the browser,
|
|
||||||
* so the server needs no ffmpeg and Chrome, Android and iOS Safari produce the same format (ADR-014).
|
|
||||||
* The audio lives only in memory until it is sent for transcription; nothing is stored on the device.
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const TARGET_RATE = 16_000;
|
|
||||||
export const MAX_SECONDS = 60;
|
|
||||||
|
|
||||||
type WindowWithWebkit = Window & { webkitAudioContext?: typeof AudioContext };
|
|
||||||
|
|
||||||
export function voiceSupported(): boolean {
|
|
||||||
const w = window as WindowWithWebkit;
|
|
||||||
return (
|
|
||||||
typeof navigator.mediaDevices?.getUserMedia === "function" && Boolean(window.AudioContext || w.webkitAudioContext)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export class Recorder {
|
|
||||||
private ctx: AudioContext | null = null;
|
|
||||||
private stream: MediaStream | null = null;
|
|
||||||
private node: ScriptProcessorNode | null = null;
|
|
||||||
private chunks: Float32Array[] = [];
|
|
||||||
private rate = 48_000;
|
|
||||||
|
|
||||||
/** `onLevel` gets the loudness 0..1 of each audio block (for the waveform). */
|
|
||||||
async start(onLevel: (level: number) => void): Promise<void> {
|
|
||||||
this.stream = await navigator.mediaDevices.getUserMedia({
|
|
||||||
audio: { channelCount: 1, echoCancellation: true, noiseSuppression: true, autoGainControl: true },
|
|
||||||
});
|
|
||||||
const Ctx = window.AudioContext || (window as WindowWithWebkit).webkitAudioContext!;
|
|
||||||
this.ctx = new Ctx();
|
|
||||||
await this.ctx.resume();
|
|
||||||
this.rate = this.ctx.sampleRate;
|
|
||||||
const source = this.ctx.createMediaStreamSource(this.stream);
|
|
||||||
// ScriptProcessorNode is deprecated but works everywhere (incl. older iOS Safari) without a worklet file.
|
|
||||||
this.node = this.ctx.createScriptProcessor(4096, 1, 1);
|
|
||||||
this.node.onaudioprocess = (e) => {
|
|
||||||
const data = new Float32Array(e.inputBuffer.getChannelData(0));
|
|
||||||
this.chunks.push(data);
|
|
||||||
let sum = 0;
|
|
||||||
for (let i = 0; i < data.length; i++) sum += data[i] * data[i];
|
|
||||||
onLevel(Math.min(1, Math.sqrt(sum / data.length) * 4));
|
|
||||||
};
|
|
||||||
source.connect(this.node);
|
|
||||||
this.node.connect(this.ctx.destination);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stops the microphone and returns the WAV, or null if nothing was recorded. */
|
|
||||||
stop(): Blob | null {
|
|
||||||
const chunks = this.chunks;
|
|
||||||
const rate = this.rate;
|
|
||||||
this.release();
|
|
||||||
if (!chunks.length) return null;
|
|
||||||
return encodeWav(downsample(concat(chunks), rate, TARGET_RATE), TARGET_RATE);
|
|
||||||
}
|
|
||||||
|
|
||||||
cancel(): void {
|
|
||||||
this.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
private release(): void {
|
|
||||||
this.node?.disconnect();
|
|
||||||
if (this.node) this.node.onaudioprocess = null;
|
|
||||||
this.stream?.getTracks().forEach((t) => t.stop());
|
|
||||||
void this.ctx?.close();
|
|
||||||
this.node = null;
|
|
||||||
this.stream = null;
|
|
||||||
this.ctx = null;
|
|
||||||
this.chunks = [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function concat(chunks: Float32Array[]): Float32Array {
|
|
||||||
const out = new Float32Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
||||||
let pos = 0;
|
|
||||||
for (const c of chunks) {
|
|
||||||
out.set(c, pos);
|
|
||||||
pos += c.length;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Averaging downsampler: good enough for speech, avoids aliasing better than dropping samples. */
|
|
||||||
function downsample(input: Float32Array, from: number, to: number): Float32Array {
|
|
||||||
if (from === to) return input;
|
|
||||||
const ratio = from / to;
|
|
||||||
const out = new Float32Array(Math.floor(input.length / ratio));
|
|
||||||
for (let i = 0; i < out.length; i++) {
|
|
||||||
const start = Math.floor(i * ratio);
|
|
||||||
const end = Math.min(input.length, Math.floor((i + 1) * ratio));
|
|
||||||
let sum = 0;
|
|
||||||
for (let j = start; j < end; j++) sum += input[j];
|
|
||||||
out[i] = sum / Math.max(1, end - start);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function encodeWav(samples: Float32Array, rate: number): Blob {
|
|
||||||
const buf = new ArrayBuffer(44 + samples.length * 2);
|
|
||||||
const v = new DataView(buf);
|
|
||||||
const str = (o: number, s: string) => [...s].forEach((ch, i) => v.setUint8(o + i, ch.charCodeAt(0)));
|
|
||||||
str(0, "RIFF");
|
|
||||||
v.setUint32(4, 36 + samples.length * 2, true);
|
|
||||||
str(8, "WAVE");
|
|
||||||
str(12, "fmt ");
|
|
||||||
v.setUint32(16, 16, true);
|
|
||||||
v.setUint16(20, 1, true); // PCM
|
|
||||||
v.setUint16(22, 1, true); // mono
|
|
||||||
v.setUint32(24, rate, true);
|
|
||||||
v.setUint32(28, rate * 2, true); // byte rate
|
|
||||||
v.setUint16(32, 2, true); // block align
|
|
||||||
v.setUint16(34, 16, true);
|
|
||||||
str(36, "data");
|
|
||||||
v.setUint32(40, samples.length * 2, true);
|
|
||||||
for (let i = 0; i < samples.length; i++) {
|
|
||||||
const s = Math.max(-1, Math.min(1, samples[i]));
|
|
||||||
v.setInt16(44 + i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);
|
|
||||||
}
|
|
||||||
return new Blob([buf], { type: "audio/wav" });
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user