From d2bec3d26dd6b0de89192c6f62a45c4b404a4afe Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Tue, 22 Sep 2026 18:44:09 +0900 Subject: [PATCH 1/9] feat(csv-import): show success message under uploader after import Previously the success st.success() was shown right before st.rerun(), so the message was cleared before the user could ever see it. The imported count is now stashed in session_state and rendered under the file uploader on the next render, right below the "Upload" control. Co-Authored-By: Claude Sonnet 5 --- app/pages/csv_import.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/pages/csv_import.py b/app/pages/csv_import.py index 6986ea6..d8b40fd 100644 --- a/app/pages/csv_import.py +++ b/app/pages/csv_import.py @@ -107,6 +107,13 @@ def _render_import_tab( uploaded = st.file_uploader( t("CSVファイルを選択"), type="csv", key=f"{key_prefix}_uploader_{uploader_version}" ) + + # インポート直後はst.rerun()で画面が作り直されるため、成功メッセージは + # session_stateへ預けておき、再描画後にアップローダの直下で表示する。 + imported_count = st.session_state.pop(f"{key_prefix}_imported_count", None) + if imported_count is not None: + st.success(t("{count}件のログをインポートしました。", count=imported_count)) + if uploaded is None: return @@ -159,7 +166,7 @@ def _render_import_tab( for log in result.logs: record_fn(log) st.session_state[uploader_version_key] = uploader_version + 1 - st.success(t("{count}件のログをインポートしました。", count=len(result.logs))) + st.session_state[f"{key_prefix}_imported_count"] = len(result.logs) st.rerun() From 94c73e87e9d8d681c076f444f94008a5aefaf452 Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Tue, 22 Sep 2026 18:44:21 +0900 Subject: [PATCH 2/9] feat(dashboard): add period selector, fix N+1 queries, tune chart axes - Add a 7/30/90-day period selector so historical CSV-imported logs (older than 7 days) are actually visible on the dashboard instead of being silently dropped by the previously hardcoded 7-day window. - Compute the reference date from JST instead of UTC, matching the rest of the app's date-boundary convention (avoids a 1-day window shift during 00:00-08:59 JST). - Fix an N+1 query pattern: the study/work-time and household-expense sections looped list_task_logs/get_journal once per displayed day (up to ~180 DB round trips at the 90-day setting). Added list_by_date_range to DailyTaskLogRepository/DailyJournalRepository (protocol + SQLAlchemy + fake test impls) and corresponding DailyJournalService methods to fetch each range in a single query. - Fix chart readability: integer-only y-axis ticks for session count and condition score, angled date labels for longer periods, and fixed y-axis ranges tuned to this user's typical values (calories 0-3500, PFC 0-500g, weight 60-75kg, study/work time 0-600min, workout sessions 0-10, cardio time 0-360min). Co-Authored-By: Claude Sonnet 5 --- app/i18n.py | 4 +- app/pages/dashboard.py | 116 ++++++++++++++---- .../repositories/protocols.py | 20 +++ .../sqlalchemy/daily_journal_repository.py | 9 ++ .../sqlalchemy/daily_task_log_repository.py | 9 ++ .../services/daily_journal_service.py | 22 ++++ tests/conftest.py | 18 +++ tests/unit/test_daily_journal_service.py | 46 +++++++ 8 files changed, 222 insertions(+), 22 deletions(-) diff --git a/app/i18n.py b/app/i18n.py index ab4ed17..e7d86dc 100644 --- a/app/i18n.py +++ b/app/i18n.py @@ -73,6 +73,8 @@ def t(text: str, **kwargs: object) -> str: # --- pages/login.py --- "このアプリは招待制です。": "This app is invite-only.", # --- pages/dashboard.py --- + "表示期間": "Period", + "直近{days}日間": "Last {days} days", "指標": "Metric", "睡眠・体調": "Sleep & Condition", "睡眠時間(h)": "Sleep duration (h)", @@ -85,7 +87,7 @@ def t(text: str, **kwargs: object) -> str: "ストレス": "Stress", "スコア": "Score", "体重(kg)": "Weight (kg)", - "直近7日間の体重記録がありません。": "No weight records in the past 7 days.", + "直近{days}日間の体重記録がありません。": "No weight records in the past {days} days.", "食事": "Meals", "カロリー(kcal)": "Calories (kcal)", "PFC(g)": "PFC (g)", diff --git a/app/pages/dashboard.py b/app/pages/dashboard.py index 6bf2c46..81d1f8e 100644 --- a/app/pages/dashboard.py +++ b/app/pages/dashboard.py @@ -1,13 +1,15 @@ """ダッシュボードページ。 -過去7日間の睡眠・体調/食事/学習/PF開発・仕事/運動/家計を、 -できるだけグラフのみで一覧できるようにする。 +睡眠・体調/食事/学習/PF開発・仕事/運動/家計を、できるだけグラフのみで +一覧できるようにする。表示期間は7日/30日/90日から選べる(デフォルトは +日々の状態把握という元来の用途に合わせ7日間。CSVインポート等でまとめて +投入した過去のログを見たい場合は30日/90日に切り替える)。 """ from __future__ import annotations import sys -from datetime import UTC, datetime +from datetime import UTC, date, datetime from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) @@ -40,23 +42,60 @@ LearningCategory, TaskLogType, ) +from health_intelligence.domain.models import DailyTaskLog # noqa: E402 auth_state = require_login() user_id = auth_state.require_user_id() st.title(":material/dashboard: " + t("ダッシュボード")) -_DAYS = last_n_days(datetime.now(UTC).date(), 7) -_DATE_LABELS = [d.strftime("%m/%d") for d in _DAYS] - +# 表示期間の切り替え。CSVインポート等でまとめて投入した過去のログは +# 「直近7日間」の外に出てしまうことがあるため、7日/30日/90日から選べる +# ようにする(デフォルトは日々の状態把握という元来の用途に合わせ7日間)。 +_PERIOD_OPTIONS = [7, 30, 90] +selected_period = st.radio( + t("表示期間"), + options=_PERIOD_OPTIONS, + format_func=lambda n: t("直近{days}日間", days=n), + horizontal=True, + key="dashboard_period_days", +) -def _bar_chart(values: list[float], *, y_title: str, key: str, caption: str) -> None: +# 日付の区切りはJST基準(今日の手入力・CSVインポートと同じ規則)。 +# datetime.now(UTC).date()をそのまま使うとJST 0:00〜8:59の間だけ +# 「今日」が1日ズレるため、jst_date_ofで変換してから使う。 +_DAYS = last_n_days(jst_date_of(datetime.now(UTC)), selected_period) +_DATE_LABELS = [d.strftime("%m/%d") for d in _DAYS] +# 表示日数が多いほど日付ラベルが重なるため、その場合は斜めにする。 +_LABEL_ANGLE = 0 if selected_period <= 7 else -45 + + +def _bar_chart( + values: list[float], + *, + y_title: str, + key: str, + caption: str, + integer_y: bool = False, + y_domain: tuple[float, float] | None = None, +) -> None: + """`integer_y=True`で、y軸の目盛りを整数のみにする(セッション数等、 + 小数を取り得ない値用。指定しない場合、Altairが値の範囲に応じて + 0.5刻み等の目盛りを自動生成し、整数しかないデータでも小数表示に + 見えてしまうことがあるため)。`y_domain`でy軸の表示範囲を固定する + (カロリー等、目安値に合わせた見やすさのため)。 + """ date_col = t("日付") df = pd.DataFrame({date_col: _DATE_LABELS, y_title: values}) + y_axis = alt.Axis(tickMinStep=1, format="d") if integer_y else alt.Axis() + y_scale = alt.Scale(domain=list(y_domain)) if y_domain is not None else alt.Undefined chart = ( alt.Chart(df) .mark_bar(cornerRadiusTopLeft=2, cornerRadiusTopRight=2) - .encode(x=alt.X(f"{date_col}:N", sort=None, title=None), y=alt.Y(f"{y_title}:Q")) + .encode( + x=alt.X(f"{date_col}:N", sort=None, title=None, axis=alt.Axis(labelAngle=_LABEL_ANGLE)), + y=alt.Y(f"{y_title}:Q", axis=y_axis, scale=y_scale), + ) ) with st.container(border=True, key=f"dashboard-chart-{key}"): st.caption(caption) @@ -64,8 +103,18 @@ def _bar_chart(values: list[float], *, y_title: str, key: str, caption: str) -> def _line_chart( - series: dict[str, list[float | None]], *, y_title: str, key: str, caption: str + series: dict[str, list[float | None]], + *, + y_title: str, + key: str, + caption: str, + integer_y: bool = False, ) -> None: + """`integer_y=True`で、y軸の目盛りを整数のみにする(体調スコア等、 + 値自体は1〜5の整数だが、1日に複数回記録した日はその日の平均を + プロットするため点の位置は小数になり得る値用。目盛りだけを整数に + 揃え、点・線の位置(実際の平均値)自体は変えない)。 + """ date_col = t("日付") indicator_col = t("指標") frames = [ @@ -73,9 +122,10 @@ def _line_chart( for name, values in series.items() ] df = pd.concat(frames, ignore_index=True) + y_axis = alt.Axis(tickMinStep=1, format="d") if integer_y else alt.Axis() encode_kwargs: dict[str, object] = { - "x": alt.X(f"{date_col}:N", sort=None, title=None), - "y": alt.Y(f"{y_title}:Q"), + "x": alt.X(f"{date_col}:N", sort=None, title=None, axis=alt.Axis(labelAngle=_LABEL_ANGLE)), + "y": alt.Y(f"{y_title}:Q", axis=y_axis), } if len(series) > 1: encode_kwargs["color"] = alt.Color( @@ -142,6 +192,7 @@ def _line_chart( y_title=t("スコア"), key="condition", caption=t("体調スコア(1〜5)"), + integer_y=True, ) weight_logs = get_weight_service().list_weight_logs(user_id) @@ -154,19 +205,21 @@ def _line_chart( with st.container(border=True, key="dashboard-chart-weight"): st.caption(_weight_col) if weight_df.empty: - st.caption(t("直近7日間の体重記録がありません。")) + st.caption(t("直近{days}日間の体重記録がありません。", days=selected_period)) else: - # y軸は50〜75kgを5kg刻みで固定表示する(体重の目標レンジに合わせた見やすさのため)。 + # y軸は60〜75kgを5kg刻みで固定表示する(体重の目標レンジに合わせた見やすさのため)。 weight_chart = ( alt.Chart(weight_df) .mark_line(point=True) .encode( - x=alt.X(f"{_date_col}:N", sort=None, title=None), + x=alt.X( + f"{_date_col}:N", sort=None, title=None, axis=alt.Axis(labelAngle=_LABEL_ANGLE) + ), y=alt.Y( f"{_weight_col}:Q", title=_weight_col, - scale=alt.Scale(domain=[50, 75]), - axis=alt.Axis(values=list(range(50, 76, 5))), + scale=alt.Scale(domain=[60, 75]), + axis=alt.Axis(values=list(range(60, 76, 5))), ), ) ) @@ -189,6 +242,7 @@ def _line_chart( y_title=t("カロリー(kcal)"), key="calories", caption=t("カロリー(kcal)"), + y_domain=(0, 3500), ) with pfc_col: date_col = t("日付") @@ -206,8 +260,8 @@ def _line_chart( alt.Chart(pfc_df) .mark_bar() .encode( - x=alt.X(f"{date_col}:N", sort=None, title=None), - y=alt.Y("g:Q", stack="zero"), + x=alt.X(f"{date_col}:N", sort=None, title=None, axis=alt.Axis(labelAngle=_LABEL_ANGLE)), + y=alt.Y("g:Q", stack="zero", scale=alt.Scale(domain=[0, 500])), color=alt.Color( f"{nutrient_col}:N", title=nutrient_col, @@ -225,7 +279,15 @@ def _line_chart( # 学習 / PF開発・仕事 # ============================================================ learning_logs = get_learning_service().list_learning_logs(user_id) -task_logs_by_day = {d: get_daily_journal_service().list_task_logs(user_id, d) for d in _DAYS} +# _DAYS分ループしてlist_task_logsを日毎に呼ぶとDBラウンドトリップが表示日数分 +# 発生する(N+1)ため、range一括取得してからPython側で日付ごとに振り分ける。 +task_logs_in_range = get_daily_journal_service().list_task_logs_in_range( + user_id, _DAYS[0], _DAYS[-1] +) +task_logs_by_day: dict[date, list[DailyTaskLog]] = {d: [] for d in _DAYS} +for log in task_logs_in_range: + if log.journal_date in task_logs_by_day: + task_logs_by_day[log.journal_date].append(log) all_tasks = get_task_service().list_tasks(user_id) task_by_id = {t.task_id: t for t in all_tasks} @@ -264,6 +326,7 @@ def _task_minutes_by_category(categories: set[GoalCategory]) -> list[float]: y_title=t("学習時間(分)"), key="study", caption=t("学習時間(分) — 学習ログ + タスク実績"), + y_domain=(0, 600), ) with pfdev_col: @@ -286,6 +349,7 @@ def _task_minutes_by_category(categories: set[GoalCategory]) -> list[float]: y_title=t("作業時間(分)"), key="pfdev", caption=t("作業時間(分) — 学習ログ + タスク実績"), + y_domain=(0, 600), ) st.divider() @@ -303,6 +367,8 @@ def _task_minutes_by_category(categories: set[GoalCategory]) -> list[float]: y_title=t("セッション数"), key="workout-sessions", caption=t("運動セッション数"), + integer_y=True, + y_domain=(0, 10), ) with cardio_col: cardio_pairs = [ @@ -316,6 +382,7 @@ def _task_minutes_by_category(categories: set[GoalCategory]) -> list[float]: y_title=t("有酸素運動時間(分)"), key="cardio", caption=t("有酸素運動時間(分)"), + y_domain=(0, 360), ) st.divider() @@ -326,8 +393,15 @@ def _task_minutes_by_category(categories: set[GoalCategory]) -> list[float]: st.subheader(t("家計")) daily_journal_service = get_daily_journal_service() -journals = [daily_journal_service.get_journal(user_id, d) for d in _DAYS] -expense_values = [j.food_expense_yen or 0 if j is not None else 0 for j in journals] +# get_journalを_DAYS分ループするとDBラウンドトリップが日数分発生する(N+1) +# ため、range一括取得してからPython側で日付ごとの食費に振り分ける。 +journals_by_day = { + j.journal_date: j + for j in daily_journal_service.list_journals_in_range(user_id, _DAYS[0], _DAYS[-1]) +} +expense_values = [ + journals_by_day[d].food_expense_yen or 0 if d in journals_by_day else 0 for d in _DAYS +] _bar_chart( expense_values, y_title=t("食費合計(円)"), diff --git a/src/health_intelligence/repositories/protocols.py b/src/health_intelligence/repositories/protocols.py index f4165f3..7f93bc0 100644 --- a/src/health_intelligence/repositories/protocols.py +++ b/src/health_intelligence/repositories/protocols.py @@ -230,6 +230,16 @@ def get_by_task_and_date( def list_by_date(self, user_id: UUID, journal_date: date) -> list[DailyTaskLog]: ... + def list_by_date_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyTaskLog]: + """ダッシュボードの期間集計用、[start_date, end_date]の全日分を1回で返す。 + + `list_by_date`を表示日数分ループ呼び出しするとDBラウンドトリップが + 日数分発生してしまう(N+1)ため、範囲一括取得用に用意する。 + """ + ... + def list_by_task(self, user_id: UUID, task_id: UUID) -> list[DailyTaskLog]: """Goalの進捗集計(累計問題数・累計時間等)のため、同一Taskの全日分を返す。""" ... @@ -246,6 +256,16 @@ class DailyJournalRepository(Protocol): def get_by_date(self, user_id: UUID, journal_date: date) -> DailyJournal | None: ... + def list_by_date_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyJournal]: + """ダッシュボードの期間集計用、[start_date, end_date]の全日分を1回で返す。 + + `get_by_date`を表示日数分ループ呼び出しするとDBラウンドトリップが + 日数分発生してしまう(N+1)ため、範囲一括取得用に用意する。 + """ + ... + def add(self, daily_journal: DailyJournal) -> None: ... def update(self, daily_journal: DailyJournal) -> None: ... diff --git a/src/health_intelligence/repositories/sqlalchemy/daily_journal_repository.py b/src/health_intelligence/repositories/sqlalchemy/daily_journal_repository.py index 84ce11f..4961716 100644 --- a/src/health_intelligence/repositories/sqlalchemy/daily_journal_repository.py +++ b/src/health_intelligence/repositories/sqlalchemy/daily_journal_repository.py @@ -60,6 +60,15 @@ def get_by_date(self, user_id: UUID, journal_date: date) -> DailyJournal | None: orm = self._session.scalars(stmt).first() return _to_domain(orm) if orm is not None else None + def list_by_date_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyJournal]: + stmt = select(DailyJournalORM).where( + DailyJournalORM.user_id == user_id, + DailyJournalORM.journal_date.between(start_date, end_date), + ) + return [_to_domain(orm) for orm in self._session.scalars(stmt)] + def add(self, daily_journal: DailyJournal) -> None: self._session.add(_to_orm(daily_journal)) diff --git a/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py b/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py index 869fb82..48d9c7c 100644 --- a/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py +++ b/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py @@ -60,6 +60,15 @@ def list_by_date(self, user_id: UUID, journal_date: date) -> list[DailyTaskLog]: ) return [_to_domain(orm) for orm in self._session.scalars(stmt)] + def list_by_date_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyTaskLog]: + stmt = select(DailyTaskLogORM).where( + DailyTaskLogORM.user_id == user_id, + DailyTaskLogORM.journal_date.between(start_date, end_date), + ) + return [_to_domain(orm) for orm in self._session.scalars(stmt)] + def list_by_task(self, user_id: UUID, task_id: UUID) -> list[DailyTaskLog]: stmt = select(DailyTaskLogORM).where( DailyTaskLogORM.user_id == user_id, DailyTaskLogORM.task_id == task_id diff --git a/src/health_intelligence/services/daily_journal_service.py b/src/health_intelligence/services/daily_journal_service.py index 3060822..bfdf5ee 100644 --- a/src/health_intelligence/services/daily_journal_service.py +++ b/src/health_intelligence/services/daily_journal_service.py @@ -27,6 +27,17 @@ def get_journal(self, user_id: UUID, journal_date: date) -> DailyJournal | None: with self._uow_factory() as uow: return uow.daily_journals.get_by_date(user_id, journal_date) + def list_journals_in_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyJournal]: + """[start_date, end_date]のDailyJournalを1回のDBアクセスでまとめて返す。 + + ダッシュボードの期間集計用。日ごとに`get_journal`をループ呼び出しする + とDBラウンドトリップが日数分発生してしまう(N+1)ため、こちらを使う。 + """ + with self._uow_factory() as uow: + return uow.daily_journals.list_by_date_range(user_id, start_date, end_date) + def get_or_create_draft(self, user_id: UUID, journal_date: date) -> DailyJournal: """指定日のDailyJournalが無ければ、未保存のドラフトを返す。 @@ -69,6 +80,17 @@ def list_task_logs(self, user_id: UUID, journal_date: date) -> list[DailyTaskLog with self._uow_factory() as uow: return uow.daily_task_logs.list_by_date(user_id, journal_date) + def list_task_logs_in_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyTaskLog]: + """[start_date, end_date]のDailyTaskLogを1回のDBアクセスでまとめて返す。 + + ダッシュボードの期間集計用。日ごとに`list_task_logs`をループ呼び出し + するとDBラウンドトリップが日数分発生してしまう(N+1)ため、こちらを使う。 + """ + with self._uow_factory() as uow: + return uow.daily_task_logs.list_by_date_range(user_id, start_date, end_date) + def save_task_log(self, daily_task_log: DailyTaskLog) -> None: """指定日・指定Taskの実績をupsertする。""" with self._uow_factory() as uow: diff --git a/tests/conftest.py b/tests/conftest.py index 886ceea..023aaac 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -177,6 +177,15 @@ def list_by_date(self, user_id: UUID, journal_date: date) -> list[DailyTaskLog]: if log.user_id == user_id and log.journal_date == journal_date ] + def list_by_date_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyTaskLog]: + return [ + log + for log in self._logs.values() + if log.user_id == user_id and start_date <= log.journal_date <= end_date + ] + def list_by_task(self, user_id: UUID, task_id: UUID) -> list[DailyTaskLog]: return [ log for log in self._logs.values() if log.user_id == user_id and log.task_id == task_id @@ -204,6 +213,15 @@ def get_by_date(self, user_id: UUID, journal_date: date) -> DailyJournal | None: return journal return None + def list_by_date_range( + self, user_id: UUID, start_date: date, end_date: date + ) -> list[DailyJournal]: + return [ + journal + for journal in self._journals.values() + if journal.user_id == user_id and start_date <= journal.journal_date <= end_date + ] + def add(self, daily_journal: DailyJournal) -> None: self._journals[daily_journal.daily_journal_id] = daily_journal diff --git a/tests/unit/test_daily_journal_service.py b/tests/unit/test_daily_journal_service.py index be617a9..2121939 100644 --- a/tests/unit/test_daily_journal_service.py +++ b/tests/unit/test_daily_journal_service.py @@ -146,6 +146,52 @@ def test_save_task_log_inserts_when_absent( assert logs[0].quantity == 10 +def test_list_task_logs_in_range_returns_only_logs_within_range( + make_fake_uow_factory, + fake_daily_journal_repo, + fake_daily_task_log_repo, + fake_daily_plan_item_repo, +) -> None: + user_id = uuid4() + task_id = uuid4() + service = _make_service( + make_fake_uow_factory, + fake_daily_journal_repo=fake_daily_journal_repo, + fake_daily_task_log_repo=fake_daily_task_log_repo, + fake_daily_plan_item_repo=fake_daily_plan_item_repo, + ) + for d in (date(2026, 8, 28), date(2026, 8, 30), date(2026, 9, 2)): + service.save_task_log( + DailyTaskLog( + daily_task_log_id=uuid4(), + user_id=user_id, + journal_date=d, + task_id=task_id, + quantity=1, + ) + ) + + logs = service.list_task_logs_in_range(user_id, date(2026, 8, 29), date(2026, 9, 1)) + + assert [log.journal_date for log in logs] == [date(2026, 8, 30)] + + +def test_list_journals_in_range_returns_only_journals_within_range( + make_fake_uow_factory, fake_daily_journal_repo +) -> None: + user_id = uuid4() + for d in (date(2026, 8, 28), date(2026, 8, 30), date(2026, 9, 2)): + fake_daily_journal_repo.add( + DailyJournal(daily_journal_id=uuid4(), user_id=user_id, journal_date=d) + ) + uow_factory = make_fake_uow_factory(daily_journals=fake_daily_journal_repo) + service = DailyJournalService(uow_factory) + + journals = service.list_journals_in_range(user_id, date(2026, 8, 29), date(2026, 9, 1)) + + assert [j.journal_date for j in journals] == [date(2026, 8, 30)] + + def test_save_task_log_updates_existing_entry_for_same_task_and_date( make_fake_uow_factory, fake_daily_journal_repo, From e0fab6fc34d595a8b84bcf803c38e1a514adc27b Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Thu, 24 Sep 2026 05:15:44 +0900 Subject: [PATCH 3/9] docs: sync README/architecture/requirements with recent changes - Dashboard period selector (7/30/90 days, JST day boundaries) - CI now runs migrations and integration tests against a Postgres service - Weight ML pipeline real-data readiness check and weekly workflow - Browser-based initial locale for new users; login screen fixed to English - Recipe history accordions with delete Co-Authored-By: Claude Opus 5.5 --- README.ja.md | 17 ++++++++++++----- README.md | 15 ++++++++++----- docs/architecture.md | 10 ++++++++-- docs/requirements.md | 12 +++++++++--- 4 files changed, 39 insertions(+), 15 deletions(-) diff --git a/README.ja.md b/README.ja.md index 5a7bd63..be53ff1 100644 --- a/README.ja.md +++ b/README.ja.md @@ -14,11 +14,11 @@ - 「今日」ページ: 1日分の記録をP(計画)→D(実績)→C(振り返り)→A(改善)のPDCA形式で1画面完結。睡眠・体調(5軸)・食事・運動(セッション/種目/セット構造)・学習/PF開発/仕事・家計(買い物メモ/食費)をここで記録する - 長期目標(Goal)・タスク(Task)管理: 長期目標ごとにタスクを紐づけ、「今日」ページのPで日々選択、進捗を集計。学習/PF開発/仕事は数量・時間・メモを記録し、食事方針/運動目標/睡眠目標は選ぶだけで実績は既存ドメイン(MealLog/WorkoutLog/SleepLog)に記録される - 学習ログ(試験勉強・PF開発・調べ物・キャリア/プロダクト戦略設計、カテゴリごとに入力項目が切り替わる)。「今日」ページのD(実績)タブで記録 -- Dashboardページで過去7日間の睡眠・体調・食事・学習/作業時間・運動・食費をグラフ表示 -- Gemini APIによるAIレシピ生成(食材入力 → レシピ提案、生成結果はキャッシュ)。生成したレシピの材料は「今日」ページの買い物メモへワンタップで追記可能 +- Dashboardページで睡眠・体調・食事・学習/作業時間・運動・食費をグラフ表示(表示期間は直近7日/30日/90日から選択。既定は7日) +- Gemini APIによるAIレシピ生成(食材入力 → レシピ提案、生成結果はキャッシュ)。生成したレシピの材料は「今日」ページの買い物メモへワンタップで追記可能。レシピ履歴は開閉式のアコーディオンで一覧し、削除も可能 - 食べたものの自由記述からAIがカロリー・PFCを推定(食事記録の入力補助) - 「前回と同じ内容」「よく使うテンプレート/キーワード」によるクイック入力、CSVファイルからのログ一括インポート -- 日本語/英語の表示切り替え(i18n、ユーザーごとにDB永続化) +- 日本語/英語の表示切り替え(i18n、ユーザーごとにDB永続化)。新規ユーザーの初期表示言語はブラウザの`Accept-Language`から判定する(ログイン画面自体は常に英語表示) - Google OAuth(OIDC、`st.login()`)によるマルチユーザーWebアプリ(ユーザーごとにデータを分離) - Health Score(独自指標、医療診断目的ではない)とRule-basedによる改善提案(Recommendation Engine)をバックエンドに実装済み(現在のUIには非表示。[既知の制限事項](#既知の制限事項)参照) - LightGBMによる体重変化予測のML Pipeline(Rule-based Baseline比較、採用基準を満たした場合のみ有効化。未達時はRule-basedにFallback) @@ -135,7 +135,7 @@ uv run mypy src uv run pytest ``` -CI(GitHub Actions)はPushごとに上記一式を実行する。ただしCIでは`DATABASE_URL`を設定していないため、Migration Test・Integration Testは自動的にskipされ、外部サービス不要なUnit Testのみが実行される([.github/workflows/ci.yml](.github/workflows/ci.yml))。 +CI(GitHub Actions)はPush・Pull Requestごとに上記一式を実行する。CIでは使い捨てのPostgreSQL 16サービスコンテナを起動して`DATABASE_URL`をそこへ向け、`pytest`の前に`alembic upgrade head`を実行するため、Migration Test・Integration Testも含めて実行される([.github/workflows/ci.yml](.github/workflows/ci.yml))。 ## ML Pipeline @@ -145,7 +145,14 @@ CI(GitHub Actions)はPushごとに上記一式を実行する。ただしCIで uv run python -m health_intelligence.ml.run_weight_pipeline ``` -評価結果は`mlruns/`(MLflow)に記録され、採用判断は`ml_artifacts/weight_model_decision.json`に保存される。アプリ本体(`RecommendationService`)はこの判断を読み取り、採用基準(Baseline比で改善率10%以上、過学習チェック20%以内、最低60日分のデータ)を満たしていればAI予測を表示し、満たしていなければRule-basedの提案のみを表示する。判断基準の詳細は[docs/requirements.md](docs/requirements.md)の9.3.1を参照。 +スクリプトはまずDBに蓄積された実データの状況(Weight領域: 60日分以上・欠損率30%未満)を確認する。 + +- **基準を満たす場合**: 実データでPipelineを評価し、結果を`mlruns/`(MLflow)に記録、採用判断を`ml_artifacts/weight_model_decision.json`に保存する +- **基準を満たさない場合**: 60日到達の見込み日を表示し、ダミーデータでPipelineの配線確認のみを行う。ダミーデータの評価結果はMLflowには記録する(run名`weight_change_model_dummy_wiring_check`)が、採用判断としては**保存しない** + +このスクリプトは定期ワークフロー([.github/workflows/ml-weight-readiness.yml](.github/workflows/ml-weight-readiness.yml))により毎週月曜06:00 JSTに(手動実行も可)、リポジトリSecretの`DATABASE_URL`に対して実行され、出力はJob Summaryに書き出される。 + +`RecommendationService`はこの判断を読み取り、採用基準(Baseline比で改善率10%以上、過学習チェック20%以内、最低60日分のデータ)を満たしていればAI予測を表示し、満たしていなければRule-basedの提案のみを表示する。判断基準の詳細は[docs/requirements.md](docs/requirements.md)の9.3.1を参照。 ## デプロイ(Streamlit Community Cloud + Neon を想定) diff --git a/README.md b/README.md index a9dc57b..29d510b 100644 --- a/README.md +++ b/README.md @@ -14,11 +14,11 @@ See below for the detailed design (documents are in Japanese). - **"Today" page**: Complete one day's record in a single screen, in PDCA order — Plan → Do → Check → Act. Sleep, condition (5 axes), meals, workouts (session/exercise/set structure), study/PF-dev/work, and household (shopping memo/food expense) are all recorded here. - **Goal & Task management**: Attach tasks to long-term goals, select them daily in the "Today" page's Plan step, and track progress. Study/PF-dev/work tasks record quantity/duration/memo; diet-policy/exercise-goal/sleep-goal tasks are just selected, with the actual record still living in the existing domains (MealLog/WorkoutLog/SleepLog). - **Learning log** (exam study, portfolio development, research, career/product strategy — the input fields change per category). Recorded in the "Today" page's Do tab. -- **Dashboard** showing the past 7 days of sleep/condition, meals, study/work time, workouts, and food expense as charts. -- **AI recipe generation** via the Gemini API (enter ingredients → get a recipe suggestion, results are cached). Ingredients from a generated recipe can be appended to the "Today" page's shopping memo with one tap. +- **Dashboard** showing sleep/condition, meals, study/work time, workouts, and food expense as charts, with a selectable period (last 7 / 30 / 90 days; defaults to 7). +- **AI recipe generation** via the Gemini API (enter ingredients → get a recipe suggestion, results are cached). Past recipes are listed as collapsible accordions and can be deleted. Ingredients from a generated recipe can be appended to the "Today" page's shopping memo with one tap. - AI estimates calories/PFC from a free-text description of what you ate (assists meal logging). - Quick entry via "same as last time" / frequently-used templates & keywords, plus bulk log import from CSV files. -- **i18n**: switch the UI between Japanese and English (persisted per user in the DB). +- **i18n**: switch the UI between Japanese and English (persisted per user in the DB). A new user's initial language is detected from the browser's `Accept-Language`; the login screen itself is always shown in English. - Multi-user web app with Google OAuth (OIDC, via `st.login()`) login (data isolated per user). - **Health Score** (a proprietary metric, not intended for medical diagnosis) and rule-based improvement suggestions (Recommendation Engine) are implemented on the backend (currently hidden from the UI — see [Known limitations](#known-limitations)). - ML pipeline for weight-change prediction using LightGBM (compared against a rule-based baseline; only enabled once it meets the adoption criteria, otherwise falls back to rule-based). @@ -137,7 +137,7 @@ uv run mypy src uv run pytest ``` -CI (GitHub Actions) runs the full suite above on every push. However, CI does not set `DATABASE_URL`, so migration tests and integration tests are automatically skipped there — only the unit tests (which require no external services) actually run ([.github/workflows/ci.yml](.github/workflows/ci.yml)). +CI (GitHub Actions) runs the full suite above on every push and pull request. CI starts a disposable PostgreSQL 16 service container, points `DATABASE_URL` at it, and runs `alembic upgrade head` before `pytest`, so migration tests and integration tests run there too ([.github/workflows/ci.yml](.github/workflows/ci.yml)). ## ML pipeline @@ -147,7 +147,12 @@ Evaluate and train the weight-change prediction model with: uv run python -m health_intelligence.ml.run_weight_pipeline ``` -Evaluation results are logged to `mlruns/` (MLflow), and the adoption decision is saved to `ml_artifacts/weight_model_decision.json`. The app (`RecommendationService`) reads this decision: if the adoption criteria are met (≥10% relative improvement over baseline, overfitting check within 20%, at least 60 days of data), it shows the AI prediction; otherwise it shows only rule-based suggestions. See section 9.3.1 of [docs/requirements.md](docs/requirements.md) for the full adoption criteria. +The script first checks how much real data has accumulated in the database (Weight domain: at least 60 days with under 30% missing-value rate). + +- **Criteria met**: the pipeline is evaluated on real data; the result is logged to `mlruns/` (MLflow) and the adoption decision is saved to `ml_artifacts/weight_model_decision.json`. +- **Criteria not met**: it prints the estimated date on which 60 days will be reached, then runs the pipeline on dummy data only as a wiring check. The dummy-data result is logged to MLflow (run name `weight_change_model_dummy_wiring_check`) but is **not** saved as an adoption decision. + +A scheduled workflow ([.github/workflows/ml-weight-readiness.yml](.github/workflows/ml-weight-readiness.yml)) runs this script every Monday at 06:00 JST (also runnable manually) against the `DATABASE_URL` repository secret and writes the output to the job summary. `RecommendationService` reads this decision: if the adoption criteria are met (≥10% relative improvement over baseline, overfitting check within 20%, at least 60 days of data), it shows the AI prediction; otherwise it shows only rule-based suggestions. See section 9.3.1 of [docs/requirements.md](docs/requirements.md) for the full adoption criteria. ## Deployment (assumes Streamlit Community Cloud + Neon) diff --git a/docs/architecture.md b/docs/architecture.md index d94687a..b8be80e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -243,8 +243,11 @@ Repositoryはビジネスルールを持たない。「条件付きでMealLogを 翻訳キーには日本語原文をそのまま使う(意味付きキーは導入しない)。`t(text, **kwargs)`が現在の表示言語に応じて`TRANSLATIONS`辞書を引き、無ければ原文をそのままフォールバック返却する。表示言語(`Locale`)は`User.locale`にDB永続化し、ログイン時にSession State(`AuthSessionState`)へコピーする。切り替えUIは`app/auth_guard.py`のサイドバーに置く。 +新規User作成時の初期表示言語は、ブラウザの`Accept-Language`(`st.context.locale`)から`detect_browser_locale()`で判定し、`UserService.get_or_create_user(default_locale=...)`へ渡す。既存Userの場合はDBに保存済みの本人の選択が常に優先される。ログイン画面には言語切り替えを置かない(`st.login()`はOAuthプロバイダ経由のリダイレクトを伴い、戻った時点でSession Stateがリセットされるため、ログイン前の選択をログイン後へ引き継げない)。そのためログイン画面の文言は常に英語固定とする。 + ```mermaid flowchart LR + Browser[Accept-Language] -. 新規User作成時のみ .-> DB DB[(User.locale)] --> Login[Login] Login --> Session[AuthSessionState.locale] Session --> T["t(text)"] @@ -439,6 +442,8 @@ flowchart LR 対象領域はPhase 8開始時点で、データ量・欠損率・Featureの品質・目的変数の定義可能性・予測可能性・Rule-based Baselineの性能・ML導入によるメリットを評価して決定する。 +現状の対象はWeight領域(`ml/run_weight_pipeline.py`)。実行時にまず`ml/real_data.py`でDBの実データから`DailyFeatures`を組み立て、データ量・欠損率の基準(11.5.1)を確認する。基準を満たせば実データで評価して採用判断を`ml_artifacts/`へ保存し、満たさなければ60日到達の見込み日を表示した上で、ダミーデータによる配線確認のみを行う(ダミーデータの評価結果はMLflowへ記録するが、採用判断としては保存しない)。この判定はGitHub Actionsの定期ワークフロー(`ml-weight-readiness.yml`、毎週月曜06:00 JST)で継続的に実行する。 + ### 11.4 MLflow Parameters / Metrics / Model / Experiment / Evaluation Resultsを記録し、実験の再現性・モデル比較・Baseline比較・採用判断に利用する。 @@ -525,7 +530,7 @@ flowchart LR RR --> DB[(PostgreSQL)] ``` -生成済みRecipeはCacheを利用し、不要なAI API呼び出しを抑制する。Recipe作成時など複数Repositoryにまたがる更新では、Unit of Workによって1つのトランザクションとして扱う。 +生成済みRecipeはCacheを利用し、不要なAI API呼び出しを抑制する。レシピ履歴はUI上で開閉式のアコーディオンとして一覧し、個別に削除できる(`RecipeService.delete_recipe`。紐づくRecipeIngredientはORMのcascadeで合わせて削除される)。Recipe作成時など複数Repositoryにまたがる更新では、Unit of Workによって1つのトランザクションとして扱う。 --- @@ -620,7 +625,8 @@ Application全体で適切なLoggingおよびException Handlingを実装する Python-Smart-Health-Intelligence-Platform/ ├── .github/ │ └── workflows/ -│ └── ci.yml +│ ├── ci.yml # Lint/型チェック/テスト(Postgresサービスコンテナ付き) +│ └── ml-weight-readiness.yml # Weight ML実データ蓄積状況の週次チェック │ ├── src/ │ └── health_intelligence/ diff --git a/docs/requirements.md b/docs/requirements.md index 008d934..880e7a1 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -278,7 +278,7 @@ P画面を開いた際の挙動: ## 4.6 多言語対応(i18n) -UI表示言語として日本語(既定)と英語を切り替えられること。表示言語はユーザーごとにDBへ永続化し、ログイン時にSession Stateへ復元する。未翻訳の文言があってもアプリの動作を妨げないこと(該当文言は日本語のままフォールバック表示する)。 +UI表示言語として日本語(既定)と英語を切り替えられること。表示言語はユーザーごとにDBへ永続化し、ログイン時にSession Stateへ復元する。新規ユーザーの初期表示言語はブラウザの言語設定(`Accept-Language`)から判定する。ログイン画面は言語切り替えを持たず、常に英語で表示する。未翻訳の文言があってもアプリの動作を妨げないこと(該当文言は日本語のままフォールバック表示する)。 --- @@ -611,7 +611,7 @@ Recipe 履歴 ``` -生成されたRecipeはユーザーごとに管理する。 +生成されたRecipeはユーザーごとに管理する。レシピ履歴は開閉式のアコーディオンで一覧し、不要になったRecipeは削除できる(削除ボタンは誤操作防止のため2回クリックで確定)。 Recipe Cacheを導入し、不要なAI API呼び出しを抑制する。 @@ -1020,9 +1020,15 @@ Ruff Format Check ↓ mypy ↓ +Alembic Migration(upgrade head) + ↓ pytest ``` +CIではPostgreSQLのサービスコンテナを起動して`DATABASE_URL`をそこへ向けるため、Migration Test・Integration Testも含めて実行する。 + +また、Weight領域の実データ蓄積状況(9.3.1の最低データ量)を確認し、基準を満たしていればML採用判断を実行する定期ワークフローを週1回(月曜06:00 JST)実行する。 + ## 17.4 セキュリティ * API Keyをソースコードへ直接記述しない @@ -1057,7 +1063,7 @@ pytest サイドバーから表示言語(日本語/英語)を切り替えられる(4.6節)。 -Dashboardでは過去7日間について以下をグラフで表示する。 +Dashboardでは、選択した表示期間(直近7日/30日/90日。既定は7日)について以下をグラフで表示する。日付の区切りはJST基準とする。 * 睡眠時間・体調スコア(総合/朝/夜/メンタル/疲労/ストレス) * カロリー・PFC From 49e05e3e2f3dacadedae15fb8008c77c4a2d8cc0 Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Thu, 24 Sep 2026 07:15:27 +0900 Subject: [PATCH 4/9] perf: speed up CSV import and page loads against remote DB - CSV import: add record_*_logs bulk methods and save all rows in a single transaction instead of one commit per row (~50s -> <1s for 140 rows) - app/services.py: cache read-only service calls (list_/get_/compute_), invalidating the written service and its dependents on every write - prefetch(): run independent page-load reads in parallel on dashboard/today/goals/recipe - Remove N+1 queries in recipe ingredient names and goal task progress Co-Authored-By: Claude Opus 5.5 --- app/pages/csv_import.py | 15 +- app/pages/dashboard.py | 12 ++ app/pages/goals.py | 10 +- app/pages/recipe.py | 13 +- app/pages/today.py | 20 +- app/services.py | 177 ++++++++++++++++-- .../repositories/protocols.py | 6 + .../sqlalchemy/daily_task_log_repository.py | 8 + .../sqlalchemy/ingredient_repository.py | 7 + .../services/goal_service.py | 7 +- .../services/health_service.py | 11 ++ .../services/learning_service.py | 11 ++ .../services/meal_service.py | 11 ++ .../services/recipe_service.py | 8 +- .../services/sleep_service.py | 11 ++ .../services/weight_service.py | 11 ++ .../services/workout_service.py | 11 ++ tests/conftest.py | 5 + 18 files changed, 323 insertions(+), 31 deletions(-) diff --git a/app/pages/csv_import.py b/app/pages/csv_import.py index d8b40fd..bca3445 100644 --- a/app/pages/csv_import.py +++ b/app/pages/csv_import.py @@ -163,8 +163,7 @@ def _render_import_tab( key=f"{key_prefix}_import_button", type="primary", ): - for log in result.logs: - record_fn(log) + record_fn(result.logs) st.session_state[uploader_version_key] = uploader_version + 1 st.session_state[f"{key_prefix}_imported_count"] = len(result.logs) st.rerun() @@ -209,7 +208,7 @@ def _render_import_tab( "AIによる推定は行わず、CSVの数値をそのまま取り込みます。" ), parse_fn=parse_meal_rows, - record_fn=lambda log: get_meal_service().record_meal_log(log), + record_fn=lambda logs: get_meal_service().record_meal_logs(logs), preview_columns={ t("日時"): lambda m: format_datetime_jst(m.consumed_at), t("区分"): lambda m: m.meal_type.value, @@ -238,7 +237,7 @@ def _render_import_tab( "複数セットとして取り込まれます。" ), parse_fn=parse_workout_rows, - record_fn=lambda log: get_workout_service().record_workout_log(log), + record_fn=lambda logs: get_workout_service().record_workout_logs(logs), preview_columns={ t("日時"): lambda w: format_datetime_jst(w.performed_at), t("種目数"): lambda w: len(w.exercises), @@ -254,7 +253,7 @@ def _render_import_tab( example_row=["2026-06-01", "23:30", "2026-06-02", "07:00", "good"], caption=t("qualityは任意。poor / fair / good / excellent のいずれか。"), parse_fn=parse_sleep_rows, - record_fn=lambda log: get_sleep_service().record_sleep_log(log), + record_fn=lambda logs: get_sleep_service().record_sleep_logs(logs), preview_columns={ t("就寝"): lambda s: format_datetime_jst(s.bedtime), t("起床"): lambda s: format_datetime_jst(s.wake_time), @@ -270,7 +269,7 @@ def _render_import_tab( example_row=["2026-06-01", "07:00", "65.5"], caption=t("timeは任意(省略時は00:00として記録されます)。"), parse_fn=parse_weight_rows, - record_fn=lambda log: get_weight_service().record_weight_log(log), + record_fn=lambda logs: get_weight_service().record_weight_logs(logs), preview_columns={ t("日時"): lambda w: format_datetime_jst(w.recorded_at), t("体重(kg)"): lambda w: w.weight_kg, @@ -288,7 +287,7 @@ def _render_import_tab( "複数ある場合はセミコロン(;)区切りで記入してください。" ), parse_fn=parse_health_rows, - record_fn=lambda log: get_health_service().record_health_log(log), + record_fn=lambda logs: get_health_service().record_health_logs(logs), preview_columns={ t("日時"): lambda h: format_datetime_jst(h.recorded_at), t("スコア"): lambda h: h.condition_score, @@ -330,7 +329,7 @@ def _render_import_tab( "セミコロン(;)区切りで記入してください。" ), parse_fn=parse_learning_rows, - record_fn=lambda log: get_learning_service().record_learning_log(log), + record_fn=lambda logs: get_learning_service().record_learning_logs(logs), preview_columns={ t("日時"): lambda learning: format_datetime_jst(learning.started_at), t("カテゴリ"): lambda learning: learning.category.value, diff --git a/app/pages/dashboard.py b/app/pages/dashboard.py index 81d1f8e..63f181a 100644 --- a/app/pages/dashboard.py +++ b/app/pages/dashboard.py @@ -34,6 +34,7 @@ get_task_service, get_weight_service, get_workout_service, + prefetch, ) from health_intelligence.domain.enums import ( # noqa: E402 @@ -65,6 +66,17 @@ # datetime.now(UTC).date()をそのまま使うとJST 0:00〜8:59の間だけ # 「今日」が1日ズレるため、jst_date_ofで変換してから使う。 _DAYS = last_n_days(jst_date_of(datetime.now(UTC)), selected_period) + +prefetch( + lambda: get_sleep_service().list_sleep_logs(user_id), + lambda: get_health_service().list_health_logs(user_id), + lambda: get_weight_service().list_weight_logs(user_id), + lambda: get_meal_service().list_meal_logs(user_id), + lambda: get_learning_service().list_learning_logs(user_id), + lambda: get_daily_journal_service().list_task_logs_in_range(user_id, _DAYS[0], _DAYS[-1]), + lambda: get_task_service().list_tasks(user_id), + lambda: get_workout_service().list_workout_logs(user_id), +) _DATE_LABELS = [d.strftime("%m/%d") for d in _DAYS] # 表示日数が多いほど日付ラベルが重なるため、その場合は斜めにする。 _LABEL_ANGLE = 0 if selected_period <= 7 else -45 diff --git a/app/pages/goals.py b/app/pages/goals.py index ea710ed..5618826 100644 --- a/app/pages/goals.py +++ b/app/pages/goals.py @@ -25,7 +25,7 @@ task_log_type_labels, ) from i18n import t # noqa: E402 -from services import get_goal_service, get_task_service # noqa: E402 +from services import get_goal_service, get_task_service, prefetch # noqa: E402 from health_intelligence.domain.enums import GoalCategory, GoalStatus, TaskLogType # noqa: E402 from health_intelligence.domain.models import Goal, Task # noqa: E402 @@ -234,6 +234,10 @@ def _render_task_row(task: Task, *, goal: Goal | None) -> None: _task_edit_dialog(task, goals_all) +prefetch( + lambda: task_service.list_tasks(user_id), + lambda: goal_service.list_goals(user_id), +) all_tasks = task_service.list_tasks(user_id) goals_all = sorted( goal_service.list_goals(user_id), @@ -244,6 +248,10 @@ def _render_task_row(task: Task, *, goal: Goal | None) -> None: ), ) +prefetch( + *(lambda g=goal: goal_service.compute_task_progress(user_id, g.goal_id) for goal in goals_all) +) + if st.button(t("+ 新しい長期目標を追加"), type="primary"): _goal_create_dialog() diff --git a/app/pages/recipe.py b/app/pages/recipe.py index e0ffd12..127c406 100644 --- a/app/pages/recipe.py +++ b/app/pages/recipe.py @@ -15,7 +15,7 @@ from auth_guard import require_login # noqa: E402 from components.recipe_card import render_recipe_card # noqa: E402 from i18n import t # noqa: E402 -from services import get_recipe_service # noqa: E402 +from services import get_recipe_service, prefetch # noqa: E402 from health_intelligence.ai.errors import AIProviderError # noqa: E402 @@ -59,6 +59,17 @@ st.subheader(t("レシピ履歴")) history = recipe_service.list_recipe_history(user_id) +# 履歴1件ごとに材料・材料名を直列に取得するとDB往復が件数×2回積み上がるため、 +# 先に並列で取得してキャッシュに載せておく(材料名は材料一覧に依存するため2段階)。 +prefetch(*(lambda r=r: recipe_service.get_recipe_ingredients(r.recipe_id) for r in history)) +prefetch( + *( + lambda r=r: recipe_service.get_ingredient_names( + recipe_service.get_recipe_ingredients(r.recipe_id) + ) + for r in history + ) +) if not history: st.info(t("まだ生成されたレシピがありません。")) else: diff --git a/app/pages/today.py b/app/pages/today.py index c0a86c9..3cbaec7 100644 --- a/app/pages/today.py +++ b/app/pages/today.py @@ -78,6 +78,7 @@ get_task_service, get_weight_service, get_workout_service, + prefetch, ) from health_intelligence.ai.errors import AIProviderError # noqa: E402 @@ -918,6 +919,24 @@ def _render_learning_new_record_section( st.session_state["today_journal_date"] += timedelta(days=1) st.rerun() date_suffix = journal_date.isoformat() +yesterday = journal_date - timedelta(days=1) + +prefetch( + lambda: daily_journal_service.list_plan(user_id, journal_date), + lambda: daily_journal_service.list_task_logs(user_id, journal_date), + lambda: daily_journal_service.get_journal(user_id, journal_date), + lambda: daily_journal_service.get_journal(user_id, yesterday), + lambda: daily_journal_service.list_plan(user_id, yesterday), + lambda: daily_journal_service.get_or_create_draft(user_id, journal_date), + lambda: task_service.list_tasks(user_id, include_archived=False), + lambda: meal_service.list_meal_logs(user_id), + lambda: workout_service.list_workout_logs(user_id), + lambda: sleep_service.list_sleep_logs(user_id), + lambda: weight_service.list_weight_logs(user_id), + lambda: health_service.list_health_logs(user_id), + lambda: learning_service.list_learning_logs(user_id), + lambda: recipe_service.list_recipe_history(user_id), +) plan_items = daily_journal_service.list_plan(user_id, journal_date) task_logs_today = daily_journal_service.list_task_logs(user_id, journal_date) @@ -957,7 +976,6 @@ def _render_learning_new_record_section( ) st.caption(f"P:{pdca_status.plan} D:{pdca_status.do} C:{pdca_status.check} A:{pdca_status.act}") -yesterday = journal_date - timedelta(days=1) yesterday_journal = daily_journal_service.get_journal(user_id, yesterday) if yesterday_journal is not None and yesterday_journal.improvement_point: st.info(t("前日の改善点(A): {point}", point=yesterday_journal.improvement_point)) diff --git a/app/services.py b/app/services.py index 4ab3fa2..3272282 100644 --- a/app/services.py +++ b/app/services.py @@ -3,10 +3,26 @@ `st.cache_resource`により、DB接続やAI Providerなど状態を持つ オブジェクトをStreamlitの再実行(rerun)間で使い回す (毎回の再実行でSQLAlchemy Engineを作り直さないようにするため)。 + +加えて、各Serviceを`_CachedService`で包み、読み取り系メソッド +(list_/get_/compute_)の結果をキャッシュする。DBはリモート(Neon)で +1回のService呼び出しに数百msかかる一方、Streamlitはウィジェット操作の +たびにページ全体を再実行するため、キャッシュ無しでは操作のたびに +全ログを取得し直して画面が重くなる。書き込み系メソッドが呼ばれたら +そのServiceと、同じテーブルを読む関連Service(`_DEPENDENTS`)の +キャッシュを破棄するので、このアプリ経由の更新は即座に反映される +(アプリ外からのDB直接変更はTTL経過後に反映される)。 """ from __future__ import annotations +import copy +import threading +import time +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from typing import Any, cast + import streamlit as st from health_intelligence.config import get_ai_provider @@ -26,6 +42,143 @@ WorkoutService, ) +_CACHE_TTL_SECONDS = 600.0 +_READ_PREFIXES = ("list_", "get_", "compute_") +_WRITE_METHODS = {"get_or_create_user"} +"""名前はget_で始まるが、Userを新規作成しうるため書き込みとして扱う。""" +_PASSTHROUGH_METHODS = {"estimate_nutrition"} +"""DBを読み書きしない(AI推定のみ)ため、キャッシュも破棄もしない。""" +_DEPENDENTS: dict[str, set[str]] = { + "MealService": {"RecommendationService"}, + "SleepService": {"RecommendationService"}, + "WeightService": {"RecommendationService"}, + "WorkoutService": {"RecommendationService"}, + "GoalService": {"TaskService", "DailyJournalService"}, + "TaskService": {"GoalService", "DailyJournalService"}, + "DailyJournalService": {"GoalService", "TaskService"}, +} +"""書き込んだServiceのキャッシュに加えて破棄すべき、他Serviceの名前。 +あるServiceのテーブル(例: TaskのDailyTaskLog)を別Service(例: +GoalServiceの進捗計算)も読んでいる組み合わせを列挙する +(src/health_intelligence/services/ の各uow.参照から導出)。 +Goal/Task/DailyJournalは相互に参照し合うため1グループとして扱う。""" + + +def _freeze(value: Any) -> Any: + """キャッシュキーにするため、list/dictを再帰的にhash可能な形へ変換する。""" + if isinstance(value, list | tuple): + return tuple(_freeze(v) for v in value) + if isinstance(value, dict): + return tuple(sorted((k, _freeze(v)) for k, v in value.items())) + return value + + +class _ReadCache: + """全Service共通の読み取り結果キャッシュ(スレッドセーフ)。 + + エントリはService名(namespace)ごとに分けて保持し、書き込み時は + namespace単位で破棄する。 + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self._entries: dict[str, dict[Any, tuple[float, Any]]] = {} + self._generations: dict[str, int] = {} + + def get_or_load(self, namespace: str, key: Any, loader: Callable[[], Any]) -> Any: + now = time.monotonic() + with self._lock: + entry = self._entries.get(namespace, {}).get(key) + if entry is not None and entry[0] > now: + return entry[1] + generation = self._generations.get(namespace, 0) + value = loader() + with self._lock: + # 読み込み中に別セッションが書き込んだ場合、古い値を保存しない。 + if generation == self._generations.get(namespace, 0): + self._entries.setdefault(namespace, {})[key] = ( + now + _CACHE_TTL_SECONDS, + value, + ) + return value + + def invalidate(self, namespaces: set[str]) -> None: + with self._lock: + for namespace in namespaces: + self._entries.pop(namespace, None) + self._generations[namespace] = self._generations.get(namespace, 0) + 1 + + +class _CachedService: + """Serviceへの呼び出しを中継し、読み取り結果をキャッシュするProxy。""" + + def __init__(self, service: object, cache: _ReadCache) -> None: + self._service = service + self._cache = cache + self._namespace = type(service).__name__ + + def __getattr__(self, name: str) -> Any: + attr = getattr(self._service, name) + if name.startswith("_") or not callable(attr) or name in _PASSTHROUGH_METHODS: + return attr + + if name.startswith(_READ_PREFIXES) and name not in _WRITE_METHODS: + + def cached_read(*args: Any, **kwargs: Any) -> Any: + key = (name, _freeze(args), _freeze(kwargs)) + try: + hash(key) + except TypeError: + return attr(*args, **kwargs) + value = self._cache.get_or_load(self._namespace, key, lambda: attr(*args, **kwargs)) + # 呼び出し側でlist/dictを破壊的に変更されてもキャッシュが + # 汚れないよう、コンテナはコピーして返す(要素のDomain Modelは + # frozen dataclassのため共有してよい)。 + return copy.copy(value) if isinstance(value, list | dict) else value + + return cached_read + + def write(*args: Any, **kwargs: Any) -> Any: + try: + return attr(*args, **kwargs) + finally: + self._cache.invalidate({self._namespace, *_DEPENDENTS.get(self._namespace, set())}) + + return write + + +@st.cache_resource +def _read_cache() -> _ReadCache: + return _ReadCache() + + +def _cached[T](service: T) -> T: + return cast(T, _CachedService(service, _read_cache())) + + +def prefetch(*loaders: Callable[[], object]) -> None: + """互いに独立した読み取り系Service呼び出しを並列実行し、キャッシュを温める。 + + キャッシュが空の初回表示や書き込み直後は、ページ冒頭の読み取りが + DB往復分ずつ直列に積み上がって遅くなるため、先にまとめて並列に + 実行しておく。直後のページ本体からの同じ呼び出しはキャッシュから + 即座に返る(引数が完全に一致する呼び出しのみヒットする点に注意)。 + 例外はここでは握りつぶし、ページ本体の同じ呼び出しで改めて + 発生させる(通常の実行経路でエラー表示させるため)。 + """ + + if not loaders: + return + + def run(loader: Callable[[], object]) -> None: + try: + loader() + except Exception: # noqa: BLE001 + pass + + with ThreadPoolExecutor(max_workers=min(len(loaders), 8)) as executor: + list(executor.map(run, loaders)) + @st.cache_resource def _uow_factory(): @@ -34,37 +187,37 @@ def _uow_factory(): @st.cache_resource def get_user_service() -> UserService: - return UserService(_uow_factory()) + return _cached(UserService(_uow_factory())) @st.cache_resource def get_health_service() -> HealthService: - return HealthService(_uow_factory()) + return _cached(HealthService(_uow_factory())) @st.cache_resource def get_learning_service() -> LearningService: - return LearningService(_uow_factory()) + return _cached(LearningService(_uow_factory())) @st.cache_resource def get_meal_service() -> MealService: - return MealService(_uow_factory(), get_ai_provider()) + return _cached(MealService(_uow_factory(), get_ai_provider())) @st.cache_resource def get_workout_service() -> WorkoutService: - return WorkoutService(_uow_factory()) + return _cached(WorkoutService(_uow_factory())) @st.cache_resource def get_sleep_service() -> SleepService: - return SleepService(_uow_factory()) + return _cached(SleepService(_uow_factory())) @st.cache_resource def get_weight_service() -> WeightService: - return WeightService(_uow_factory()) + return _cached(WeightService(_uow_factory())) @st.cache_resource @@ -74,24 +227,24 @@ def get_recommendation_service() -> RecommendationService: 評価が完了し、学習済みモデルのロード方法が整備され次第、 model_predict_fnを差し込む(architecture.md Section 11.6)。 """ - return RecommendationService(_uow_factory()) + return _cached(RecommendationService(_uow_factory())) @st.cache_resource def get_recipe_service() -> RecipeService: - return RecipeService(_uow_factory(), get_ai_provider()) + return _cached(RecipeService(_uow_factory(), get_ai_provider())) @st.cache_resource def get_goal_service() -> GoalService: - return GoalService(_uow_factory()) + return _cached(GoalService(_uow_factory())) @st.cache_resource def get_task_service() -> TaskService: - return TaskService(_uow_factory()) + return _cached(TaskService(_uow_factory())) @st.cache_resource def get_daily_journal_service() -> DailyJournalService: - return DailyJournalService(_uow_factory()) + return _cached(DailyJournalService(_uow_factory())) diff --git a/src/health_intelligence/repositories/protocols.py b/src/health_intelligence/repositories/protocols.py index 7f93bc0..508e8c3 100644 --- a/src/health_intelligence/repositories/protocols.py +++ b/src/health_intelligence/repositories/protocols.py @@ -147,6 +147,8 @@ class IngredientRepository(Protocol): def get_by_id(self, ingredient_id: UUID) -> Ingredient | None: ... + def list_by_ids(self, ingredient_ids: list[UUID]) -> list[Ingredient]: ... + def get_by_name(self, name: str) -> Ingredient | None: ... def list_all(self) -> list[Ingredient]: ... @@ -244,6 +246,10 @@ def list_by_task(self, user_id: UUID, task_id: UUID) -> list[DailyTaskLog]: """Goalの進捗集計(累計問題数・累計時間等)のため、同一Taskの全日分を返す。""" ... + def list_by_tasks(self, user_id: UUID, task_ids: list[UUID]) -> list[DailyTaskLog]: + """複数Task分の全日分を1回で返す(`list_by_task`のTask数分ループ=N+1を避ける)。""" + ... + def add(self, daily_task_log: DailyTaskLog) -> None: ... def update(self, daily_task_log: DailyTaskLog) -> None: ... diff --git a/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py b/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py index 48d9c7c..294f67c 100644 --- a/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py +++ b/src/health_intelligence/repositories/sqlalchemy/daily_task_log_repository.py @@ -75,6 +75,14 @@ def list_by_task(self, user_id: UUID, task_id: UUID) -> list[DailyTaskLog]: ) return [_to_domain(orm) for orm in self._session.scalars(stmt)] + def list_by_tasks(self, user_id: UUID, task_ids: list[UUID]) -> list[DailyTaskLog]: + if not task_ids: + return [] + stmt = select(DailyTaskLogORM).where( + DailyTaskLogORM.user_id == user_id, DailyTaskLogORM.task_id.in_(task_ids) + ) + return [_to_domain(orm) for orm in self._session.scalars(stmt)] + def add(self, daily_task_log: DailyTaskLog) -> None: self._session.add(_to_orm(daily_task_log)) diff --git a/src/health_intelligence/repositories/sqlalchemy/ingredient_repository.py b/src/health_intelligence/repositories/sqlalchemy/ingredient_repository.py index ba2b8d7..1bc5717 100644 --- a/src/health_intelligence/repositories/sqlalchemy/ingredient_repository.py +++ b/src/health_intelligence/repositories/sqlalchemy/ingredient_repository.py @@ -46,6 +46,13 @@ def get_by_id(self, ingredient_id: UUID) -> Ingredient | None: orm = self._session.get(IngredientORM, ingredient_id) return _to_domain(orm) if orm is not None else None + def list_by_ids(self, ingredient_ids: list[UUID]) -> list[Ingredient]: + """複数IDをIN句の1クエリでまとめて取得する(1件ずつのN+1クエリを避ける)。""" + if not ingredient_ids: + return [] + stmt = select(IngredientORM).where(IngredientORM.id.in_(ingredient_ids)) + return [_to_domain(orm) for orm in self._session.scalars(stmt)] + def get_by_name(self, name: str) -> Ingredient | None: """大文字小文字を区別せず名前で検索する(get or create用)。""" stmt = select(IngredientORM).where(func.lower(IngredientORM.name) == name.lower()) diff --git a/src/health_intelligence/services/goal_service.py b/src/health_intelligence/services/goal_service.py index b575d39..9f0d536 100644 --- a/src/health_intelligence/services/goal_service.py +++ b/src/health_intelligence/services/goal_service.py @@ -7,7 +7,7 @@ from uuid import UUID from health_intelligence.domain.enums import GoalStatus, TaskLogType -from health_intelligence.domain.models import Goal, Task +from health_intelligence.domain.models import DailyTaskLog, Goal, Task from health_intelligence.repositories.unit_of_work import UnitOfWork @@ -75,9 +75,12 @@ def compute_task_progress(self, user_id: UUID, goal_id: UUID) -> list[TaskProgre for task in uow.tasks.list_by_user(user_id, goal_id=goal_id) if task.log_type == TaskLogType.COUNT_AND_DURATION ] + logs_by_task: dict[UUID, list[DailyTaskLog]] = {task.task_id: [] for task in tasks} + for log in uow.daily_task_logs.list_by_tasks(user_id, list(logs_by_task)): + logs_by_task[log.task_id].append(log) progresses = [] for task in tasks: - logs = uow.daily_task_logs.list_by_task(user_id, task.task_id) + logs = logs_by_task[task.task_id] progresses.append( TaskProgress( task=task, diff --git a/src/health_intelligence/services/health_service.py b/src/health_intelligence/services/health_service.py index 6c1f474..64bdec1 100644 --- a/src/health_intelligence/services/health_service.py +++ b/src/health_intelligence/services/health_service.py @@ -20,6 +20,17 @@ def record_health_log(self, health_log: HealthLog) -> None: uow.health_logs.add(health_log) uow.commit() + def record_health_logs(self, health_logs: list[HealthLog]) -> None: + """複数件を1トランザクションでまとめて記録する(CSV一括インポート用)。 + + 1件ずつ`record_health_log`を呼ぶと件数分のDB往復・commitが発生し、 + リモートDBでは件数に比例して著しく遅くなるため。 + """ + with self._uow_factory() as uow: + for health_log in health_logs: + uow.health_logs.add(health_log) + uow.commit() + def list_health_logs(self, user_id: UUID) -> list[HealthLog]: with self._uow_factory() as uow: return uow.health_logs.list_by_user(user_id) diff --git a/src/health_intelligence/services/learning_service.py b/src/health_intelligence/services/learning_service.py index f9b8b12..bd6a5f4 100644 --- a/src/health_intelligence/services/learning_service.py +++ b/src/health_intelligence/services/learning_service.py @@ -20,6 +20,17 @@ def record_learning_log(self, learning_log: LearningLog) -> None: uow.learning_logs.add(learning_log) uow.commit() + def record_learning_logs(self, learning_logs: list[LearningLog]) -> None: + """複数件を1トランザクションでまとめて記録する(CSV一括インポート用)。 + + 1件ずつ`record_learning_log`を呼ぶと件数分のDB往復・commitが発生し、 + リモートDBでは件数に比例して著しく遅くなるため。 + """ + with self._uow_factory() as uow: + for learning_log in learning_logs: + uow.learning_logs.add(learning_log) + uow.commit() + def list_learning_logs(self, user_id: UUID) -> list[LearningLog]: with self._uow_factory() as uow: return uow.learning_logs.list_by_user(user_id) diff --git a/src/health_intelligence/services/meal_service.py b/src/health_intelligence/services/meal_service.py index 4f8087c..d4d963c 100644 --- a/src/health_intelligence/services/meal_service.py +++ b/src/health_intelligence/services/meal_service.py @@ -48,6 +48,17 @@ def record_meal_log(self, meal_log: MealLog) -> None: uow.meal_logs.add(meal_log) uow.commit() + def record_meal_logs(self, meal_logs: list[MealLog]) -> None: + """複数件を1トランザクションでまとめて記録する(CSV一括インポート用)。 + + 1件ずつ`record_meal_log`を呼ぶと件数分のDB往復・commitが発生し、 + リモートDBでは件数に比例して著しく遅くなるため。 + """ + with self._uow_factory() as uow: + for meal_log in meal_logs: + uow.meal_logs.add(meal_log) + uow.commit() + def list_meal_logs(self, user_id: UUID) -> list[MealLog]: with self._uow_factory() as uow: return uow.meal_logs.list_by_user(user_id) diff --git a/src/health_intelligence/services/recipe_service.py b/src/health_intelligence/services/recipe_service.py index a953435..715dec2 100644 --- a/src/health_intelligence/services/recipe_service.py +++ b/src/health_intelligence/services/recipe_service.py @@ -73,13 +73,9 @@ def get_ingredient_names(self, recipe_ingredients: list[RecipeIngredient]) -> di Presentation Layer(app/)がIngredientRepositoryへ直接 アクセスしないよう、Service経由でまとめて解決する。 """ + ingredient_ids = list({ri.ingredient_id for ri in recipe_ingredients}) with self._uow_factory() as uow: - names: dict[UUID, str] = {} - for recipe_ingredient in recipe_ingredients: - ingredient = uow.ingredients.get_by_id(recipe_ingredient.ingredient_id) - if ingredient is not None: - names[recipe_ingredient.ingredient_id] = ingredient.name - return names + return {i.ingredient_id: i.name for i in uow.ingredients.list_by_ids(ingredient_ids)} def generate_recipe(self, user_id: UUID, ingredient_names: list[str]) -> Recipe: """食材リストからAIによってレシピを生成し、保存する。 diff --git a/src/health_intelligence/services/sleep_service.py b/src/health_intelligence/services/sleep_service.py index a41e812..ecf88b6 100644 --- a/src/health_intelligence/services/sleep_service.py +++ b/src/health_intelligence/services/sleep_service.py @@ -20,6 +20,17 @@ def record_sleep_log(self, sleep_log: SleepLog) -> None: uow.sleep_logs.add(sleep_log) uow.commit() + def record_sleep_logs(self, sleep_logs: list[SleepLog]) -> None: + """複数件を1トランザクションでまとめて記録する(CSV一括インポート用)。 + + 1件ずつ`record_sleep_log`を呼ぶと件数分のDB往復・commitが発生し、 + リモートDBでは件数に比例して著しく遅くなるため。 + """ + with self._uow_factory() as uow: + for sleep_log in sleep_logs: + uow.sleep_logs.add(sleep_log) + uow.commit() + def list_sleep_logs(self, user_id: UUID) -> list[SleepLog]: with self._uow_factory() as uow: return uow.sleep_logs.list_by_user(user_id) diff --git a/src/health_intelligence/services/weight_service.py b/src/health_intelligence/services/weight_service.py index b421381..34d222b 100644 --- a/src/health_intelligence/services/weight_service.py +++ b/src/health_intelligence/services/weight_service.py @@ -20,6 +20,17 @@ def record_weight_log(self, weight_log: WeightLog) -> None: uow.weight_logs.add(weight_log) uow.commit() + def record_weight_logs(self, weight_logs: list[WeightLog]) -> None: + """複数件を1トランザクションでまとめて記録する(CSV一括インポート用)。 + + 1件ずつ`record_weight_log`を呼ぶと件数分のDB往復・commitが発生し、 + リモートDBでは件数に比例して著しく遅くなるため。 + """ + with self._uow_factory() as uow: + for weight_log in weight_logs: + uow.weight_logs.add(weight_log) + uow.commit() + def list_weight_logs(self, user_id: UUID) -> list[WeightLog]: with self._uow_factory() as uow: return uow.weight_logs.list_by_user(user_id) diff --git a/src/health_intelligence/services/workout_service.py b/src/health_intelligence/services/workout_service.py index 5ab3c1a..be38026 100644 --- a/src/health_intelligence/services/workout_service.py +++ b/src/health_intelligence/services/workout_service.py @@ -20,6 +20,17 @@ def record_workout_log(self, workout_log: WorkoutLog) -> None: uow.workout_logs.add(workout_log) uow.commit() + def record_workout_logs(self, workout_logs: list[WorkoutLog]) -> None: + """複数件を1トランザクションでまとめて記録する(CSV一括インポート用)。 + + 1件ずつ`record_workout_log`を呼ぶと件数分のDB往復・commitが発生し、 + リモートDBでは件数に比例して著しく遅くなるため。 + """ + with self._uow_factory() as uow: + for workout_log in workout_logs: + uow.workout_logs.add(workout_log) + uow.commit() + def list_workout_logs(self, user_id: UUID) -> list[WorkoutLog]: with self._uow_factory() as uow: return uow.workout_logs.list_by_user(user_id) diff --git a/tests/conftest.py b/tests/conftest.py index 023aaac..aac5db0 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -191,6 +191,11 @@ def list_by_task(self, user_id: UUID, task_id: UUID) -> list[DailyTaskLog]: log for log in self._logs.values() if log.user_id == user_id and log.task_id == task_id ] + def list_by_tasks(self, user_id: UUID, task_ids: list[UUID]) -> list[DailyTaskLog]: + return [ + log for log in self._logs.values() if log.user_id == user_id and log.task_id in task_ids + ] + def add(self, daily_task_log: DailyTaskLog) -> None: self._logs[daily_task_log.daily_task_log_id] = daily_task_log From d46b6938fd42018d300e9d0324dd43e345af753c Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Thu, 24 Sep 2026 07:28:13 +0900 Subject: [PATCH 5/9] fix: prevent duplicate CSV imports and keep dashboard charts visible - CSV import: skip rows whose content matches an existing log (split_new_logs), so importing the same file twice no longer multiplies dashboard totals - Dashboard: expand the fixed y-axis max (calories/PFC etc.) when a day exceeds it instead of drawing bars outside the plot - prefetch(): propagate ScriptRunContext to worker threads to silence "missing ScriptRunContext" warnings - Dashboard line charts: build long-form DataFrame directly to avoid pandas FutureWarning on all-NA series Co-Authored-By: Claude Opus 5.5 --- app/components/csv_import.py | 37 ++++++++++++++++++++++- app/i18n.py | 3 ++ app/pages/csv_import.py | 31 ++++++++++++++++---- app/pages/dashboard.py | 28 +++++++++++++----- app/services.py | 13 +++++++-- tests/unit/test_csv_import.py | 55 +++++++++++++++++++++++++++++++++++ 6 files changed, 150 insertions(+), 17 deletions(-) diff --git a/app/components/csv_import.py b/app/components/csv_import.py index 15f8ed7..7533d51 100644 --- a/app/components/csv_import.py +++ b/app/components/csv_import.py @@ -17,9 +17,11 @@ from __future__ import annotations -from dataclasses import dataclass +from collections.abc import Iterable +from dataclasses import asdict, dataclass from datetime import date as date_type from datetime import time as time_type +from typing import Any from uuid import UUID, uuid4 from components.formatting import combine_jst_to_utc @@ -441,3 +443,36 @@ def parse_learning_rows(rows: list[dict[str, str]], *, user_id: UUID) -> ImportR ) return ImportResult(logs=logs, errors=errors) + + +def _hashable(value: Any) -> Any: + if isinstance(value, list | tuple): + return tuple(_hashable(v) for v in value) + if isinstance(value, dict): + return tuple(sorted((k, _hashable(v)) for k, v in value.items())) + return value + + +def _content_key(log: Any) -> Any: + """IDフィールド(`*_log_id`)を除いた全フィールドの値を、比較用のキーにする。 + + CSVインポートではIDを毎回`uuid4()`で採番するため、同じ行を取り込み直すと + IDだけが異なる重複レコードになる。内容が完全に一致するかで判定する。 + """ + return _hashable({k: v for k, v in asdict(log).items() if not k.endswith("_log_id")}) + + +def split_new_logs[T](logs: list[T], existing: Iterable[T]) -> tuple[list[T], list[T]]: + """`logs`を、登録済みの`existing`と内容が一致しない新規分と、一致する重複分に分ける。 + + 同じCSVを誤って複数回インポートすると、ダッシュボードの合計値が + インポート回数倍に膨らんでしまうため、登録済みと同じ内容の行は + 取り込まない。CSVファイル内で同じ内容の行が複数ある場合は、 + それぞれ別の記録(例: 同じ時刻の間食2回)とみなして両方取り込む。 + """ + existing_keys = {_content_key(log) for log in existing} + new: list[T] = [] + duplicates: list[T] = [] + for log in logs: + (duplicates if _content_key(log) in existing_keys else new).append(log) + return new, duplicates diff --git a/app/i18n.py b/app/i18n.py index e7d86dc..b139997 100644 --- a/app/i18n.py +++ b/app/i18n.py @@ -210,6 +210,9 @@ def t(text: str, **kwargs: object) -> str: "行番号": "Row", "エラー内容": "Error", "有効な{count}件をインポートする": "Import {count} valid row(s)", + "登録済みのログと同じ内容の{count}件は、重複を避けるため取り込みません。": ( + "{count} rows match existing logs and will be skipped to avoid duplicates." + ), "{count}件のログをインポートしました。": "Imported {count} log(s).", "納豆ご飯": "Natto rice bowl", "日時": "Date/time", diff --git a/app/pages/csv_import.py b/app/pages/csv_import.py index bca3445..1b0561f 100644 --- a/app/pages/csv_import.py +++ b/app/pages/csv_import.py @@ -33,6 +33,7 @@ parse_sleep_rows, parse_weight_rows, parse_workout_rows, + split_new_logs, ) from components.formatting import format_datetime_jst # noqa: E402 from components.workout_form import format_exercise_line # noqa: E402 @@ -83,6 +84,7 @@ def _render_import_tab( example_row: list[str], caption: str, parse_fn, + existing_fn, record_fn, preview_columns: dict[str, object], ) -> None: @@ -91,6 +93,9 @@ def _render_import_tab( 5種類のログでUIの流れ(テンプレート→アップロード→プレビュー→ インポート)は共通なため、差分(列定義・パース関数・保存関数・ プレビュー列)だけをパラメータ化する。 + + `existing_fn`で取得した登録済みログと内容が完全に一致する行は、 + 同じCSVの二重インポートとみなして取り込まない(split_new_logs参照)。 """ st.caption(caption) st.download_button( @@ -128,14 +133,22 @@ def _render_import_tab( return result: ImportResult = parse_fn(rows, user_id=user_id) + new_logs, duplicate_logs = split_new_logs(result.logs, existing_fn()) st.write( t( "有効な行: {valid}件 / エラー: {error}件", - valid=len(result.logs), + valid=len(new_logs), error=len(result.errors), ) ) + if duplicate_logs: + st.info( + t( + "登録済みのログと同じ内容の{count}件は、重複を避けるため取り込みません。", + count=len(duplicate_logs), + ) + ) if result.errors: st.dataframe( @@ -149,23 +162,23 @@ def _render_import_tab( width="stretch", ) - if result.logs: + if new_logs: st.dataframe( pd.DataFrame( - {name: [fn(log) for log in result.logs] for name, fn in preview_columns.items()} + {name: [fn(log) for log in new_logs] for name, fn in preview_columns.items()} ), hide_index=True, width="stretch", ) if st.button( - t("有効な{count}件をインポートする", count=len(result.logs)), + t("有効な{count}件をインポートする", count=len(new_logs)), key=f"{key_prefix}_import_button", type="primary", ): - record_fn(result.logs) + record_fn(new_logs) st.session_state[uploader_version_key] = uploader_version + 1 - st.session_state[f"{key_prefix}_imported_count"] = len(result.logs) + st.session_state[f"{key_prefix}_imported_count"] = len(new_logs) st.rerun() @@ -208,6 +221,7 @@ def _render_import_tab( "AIによる推定は行わず、CSVの数値をそのまま取り込みます。" ), parse_fn=parse_meal_rows, + existing_fn=lambda: get_meal_service().list_meal_logs(user_id), record_fn=lambda logs: get_meal_service().record_meal_logs(logs), preview_columns={ t("日時"): lambda m: format_datetime_jst(m.consumed_at), @@ -237,6 +251,7 @@ def _render_import_tab( "複数セットとして取り込まれます。" ), parse_fn=parse_workout_rows, + existing_fn=lambda: get_workout_service().list_workout_logs(user_id), record_fn=lambda logs: get_workout_service().record_workout_logs(logs), preview_columns={ t("日時"): lambda w: format_datetime_jst(w.performed_at), @@ -253,6 +268,7 @@ def _render_import_tab( example_row=["2026-06-01", "23:30", "2026-06-02", "07:00", "good"], caption=t("qualityは任意。poor / fair / good / excellent のいずれか。"), parse_fn=parse_sleep_rows, + existing_fn=lambda: get_sleep_service().list_sleep_logs(user_id), record_fn=lambda logs: get_sleep_service().record_sleep_logs(logs), preview_columns={ t("就寝"): lambda s: format_datetime_jst(s.bedtime), @@ -269,6 +285,7 @@ def _render_import_tab( example_row=["2026-06-01", "07:00", "65.5"], caption=t("timeは任意(省略時は00:00として記録されます)。"), parse_fn=parse_weight_rows, + existing_fn=lambda: get_weight_service().list_weight_logs(user_id), record_fn=lambda logs: get_weight_service().record_weight_logs(logs), preview_columns={ t("日時"): lambda w: format_datetime_jst(w.recorded_at), @@ -287,6 +304,7 @@ def _render_import_tab( "複数ある場合はセミコロン(;)区切りで記入してください。" ), parse_fn=parse_health_rows, + existing_fn=lambda: get_health_service().list_health_logs(user_id), record_fn=lambda logs: get_health_service().record_health_logs(logs), preview_columns={ t("日時"): lambda h: format_datetime_jst(h.recorded_at), @@ -329,6 +347,7 @@ def _render_import_tab( "セミコロン(;)区切りで記入してください。" ), parse_fn=parse_learning_rows, + existing_fn=lambda: get_learning_service().list_learning_logs(user_id), record_fn=lambda logs: get_learning_service().record_learning_logs(logs), preview_columns={ t("日時"): lambda learning: format_datetime_jst(learning.started_at), diff --git a/app/pages/dashboard.py b/app/pages/dashboard.py index 63f181a..86bb75f 100644 --- a/app/pages/dashboard.py +++ b/app/pages/dashboard.py @@ -95,12 +95,18 @@ def _bar_chart( 小数を取り得ない値用。指定しない場合、Altairが値の範囲に応じて 0.5刻み等の目盛りを自動生成し、整数しかないデータでも小数表示に 見えてしまうことがあるため)。`y_domain`でy軸の表示範囲を固定する - (カロリー等、目安値に合わせた見やすさのため)。 + (カロリー等、目安値に合わせた見やすさのため)。上限を超える日がある + 場合は、棒が描画領域からはみ出して見えなくならないよう上限をその値まで + 広げる。 """ date_col = t("日付") df = pd.DataFrame({date_col: _DATE_LABELS, y_title: values}) y_axis = alt.Axis(tickMinStep=1, format="d") if integer_y else alt.Axis() - y_scale = alt.Scale(domain=list(y_domain)) if y_domain is not None else alt.Undefined + y_scale = ( + alt.Scale(domain=[y_domain[0], max(y_domain[1], *values)]) + if y_domain is not None + else alt.Undefined + ) chart = ( alt.Chart(df) .mark_bar(cornerRadiusTopLeft=2, cornerRadiusTopRight=2) @@ -129,11 +135,15 @@ def _line_chart( """ date_col = t("日付") indicator_col = t("指標") - frames = [ - pd.DataFrame({date_col: _DATE_LABELS, y_title: values, indicator_col: name}) - for name, values in series.items() - ] - df = pd.concat(frames, ignore_index=True) + # 系列ごとのDataFrameをpd.concatすると、値がすべてNone(記録なし)の系列が + # あるときpandasのFutureWarningが出るため、縦持ちの列を直接組み立てる。 + df = pd.DataFrame( + { + date_col: [label for _ in series for label in _DATE_LABELS], + y_title: pd.Series([v for values in series.values() for v in values], dtype="float64"), + indicator_col: [name for name, values in series.items() for _ in values], + } + ) y_axis = alt.Axis(tickMinStep=1, format="d") if integer_y else alt.Axis() encode_kwargs: dict[str, object] = { "x": alt.X(f"{date_col}:N", sort=None, title=None, axis=alt.Axis(labelAngle=_LABEL_ANGLE)), @@ -268,12 +278,14 @@ def _line_chart( values = group_sum_by_date(meal_logs, lambda m: jst_date_of(m.consumed_at), getter, _DAYS) pfc_frames.append(pd.DataFrame({date_col: _DATE_LABELS, "g": values, nutrient_col: label})) pfc_df = pd.concat(pfc_frames, ignore_index=True) + # カロリーと同様、積み上げ合計が固定上限(500g)を超える日は上限を広げる。 + pfc_max = max(500.0, *pfc_df.groupby(date_col)["g"].sum()) pfc_chart = ( alt.Chart(pfc_df) .mark_bar() .encode( x=alt.X(f"{date_col}:N", sort=None, title=None, axis=alt.Axis(labelAngle=_LABEL_ANGLE)), - y=alt.Y("g:Q", stack="zero", scale=alt.Scale(domain=[0, 500])), + y=alt.Y("g:Q", stack="zero", scale=alt.Scale(domain=[0, pfc_max])), color=alt.Color( f"{nutrient_col}:N", title=nutrient_col, diff --git a/app/services.py b/app/services.py index 3272282..98dd2c6 100644 --- a/app/services.py +++ b/app/services.py @@ -24,6 +24,7 @@ from typing import Any, cast import streamlit as st +from streamlit.runtime.scriptrunner import add_script_run_ctx, get_script_run_ctx from health_intelligence.config import get_ai_provider from health_intelligence.repositories.sqlalchemy import build_uow_factory @@ -165,18 +166,26 @@ def prefetch(*loaders: Callable[[], object]) -> None: 即座に返る(引数が完全に一致する呼び出しのみヒットする点に注意)。 例外はここでは握りつぶし、ページ本体の同じ呼び出しで改めて 発生させる(通常の実行経路でエラー表示させるため)。 - """ + ワーカースレッドには呼び出し元のScriptRunContextを引き継ぐ。loader内で + `get_*_service()`(`st.cache_resource`)を呼ぶため、引き継がないと + 「missing ScriptRunContext」警告がスレッド数分出力される。 + """ if not loaders: return + ctx = get_script_run_ctx() + def run(loader: Callable[[], object]) -> None: try: loader() except Exception: # noqa: BLE001 pass - with ThreadPoolExecutor(max_workers=min(len(loaders), 8)) as executor: + with ThreadPoolExecutor( + max_workers=min(len(loaders), 8), + initializer=lambda: add_script_run_ctx(threading.current_thread(), ctx), + ) as executor: list(executor.map(run, loaders)) diff --git a/tests/unit/test_csv_import.py b/tests/unit/test_csv_import.py index edb6d9a..6e44ded 100644 --- a/tests/unit/test_csv_import.py +++ b/tests/unit/test_csv_import.py @@ -20,6 +20,7 @@ parse_sleep_rows, parse_weight_rows, parse_workout_rows, + split_new_logs, ) @@ -298,3 +299,57 @@ def test_parse_learning_rows_rejects_invalid_category_and_location() -> None: assert result.logs == [] assert len(result.errors) == 2 + + +def test_split_new_logs_skips_rows_already_imported() -> None: + user_id = uuid4() + rows = [ + {"date": "2026-06-01", "time": "07:00", "weight_kg": "65.5"}, + {"date": "2026-06-02", "time": "07:00", "weight_kg": "65.2"}, + ] + existing = parse_weight_rows(rows[:1], user_id=user_id).logs + # 再パースすると別IDが採番されるが、内容が同じなら重複と判定する + logs = parse_weight_rows(rows, user_id=user_id).logs + + new, duplicates = split_new_logs(logs, existing) + + assert [log.weight_kg for log in new] == [65.2] + assert [log.weight_kg for log in duplicates] == [65.5] + + +def test_split_new_logs_compares_nested_workout_exercises() -> None: + user_id = uuid4() + row = { + "date": "2026-06-01", + "time": "19:00", + "exercise_name": "レッグプレス", + "category": "strength", + "reps": "10", + "weight_kg": "75", + } + existing = parse_workout_rows([row], user_id=user_id).logs + same = parse_workout_rows([row], user_id=user_id).logs + heavier = parse_workout_rows([{**row, "weight_kg": "80"}], user_id=user_id).logs + + assert split_new_logs(same, existing) == ([], same) + assert split_new_logs(heavier, existing) == (heavier, []) + + +def test_split_new_logs_keeps_identical_rows_within_same_file() -> None: + user_id = uuid4() + row = { + "date": "2026-06-01", + "time": "15:00", + "meal_type": "snack", + "calories": "100", + "protein_g": "1", + "fat_g": "1", + "carbohydrate_g": "20", + "memo": "", + } + logs = parse_meal_rows([row, row], user_id=user_id).logs + + new, duplicates = split_new_logs(logs, []) + + assert len(new) == 2 + assert duplicates == [] From acb42c7394867489fc19ea0488f767e8a5d9125b Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Thu, 24 Sep 2026 07:36:27 +0900 Subject: [PATCH 6/9] feat(dashboard): replace workout session chart with strength/cardio charts - Remove the "workout sessions" chart - Add max weight per exercise (top 5 by recorded days) line chart, connecting gaps between sparse training days - Add daily strength volume (weight x reps, bodyweight excluded) - Cardio time is now stacked by exercise, y-axis max 90 min (expands when exceeded) - Rename sidebar "Recipe" label to "AI Recipes" to match the page title Co-Authored-By: Claude Opus 5.5 --- app/components/dashboard_charts.py | 85 ++++++++++++++++++++++- app/i18n.py | 14 +++- app/pages/dashboard.py | 101 +++++++++++++++++++++------- app/streamlit_app.py | 2 +- docs/requirements.md | 2 +- tests/unit/test_dashboard_charts.py | 89 +++++++++++++++++++++++- 6 files changed, 262 insertions(+), 31 deletions(-) diff --git a/app/components/dashboard_charts.py b/app/components/dashboard_charts.py index cb13d83..03ed2e7 100644 --- a/app/components/dashboard_charts.py +++ b/app/components/dashboard_charts.py @@ -2,7 +2,8 @@ 各グラフは「過去7日間、日付ごとの合計/平均」という同じ形の集計を 繰り返し使うため、`group_sum_by_date`/`group_average_by_date`という -2つの汎用関数に集約する。 +2つの汎用関数に集約する。運動(WorkoutLog)は種目・セットの入れ子構造を +持つため、専用の集計関数を別に用意する。 """ from __future__ import annotations @@ -10,6 +11,9 @@ from collections.abc import Callable, Iterable from datetime import date, timedelta +from health_intelligence.domain.enums import ExerciseCategory +from health_intelligence.domain.models import WorkoutLog + def last_n_days(reference: date, n: int) -> list[date]: """`reference`を含む直近n日間を、古い→新しい順で返す。""" @@ -53,3 +57,82 @@ def group_average_by_date[T]( sums[d] += v counts[d] += 1 return [sums[d] / counts[d] if counts[d] else None for d in dates] + + +def strength_max_weight_by_exercise( + workout_logs: Iterable[WorkoutLog], + date_of: Callable[[WorkoutLog], date], + dates: list[date], + *, + top_n: int = 5, +) -> dict[str, list[float | None]]: + """筋トレ種目ごとの、日別の最大重量(kg)を`dates`の並び順で返す。 + + 表示期間内に記録した日数が多い上位`top_n`種目のみを返す(種目が多いと + 線が重なって読めなくなるため)。重量の無いセット(懸垂等の自重種目)は + 対象外で、その日に記録が無い場合はNoneを返す。 + """ + date_set = set(dates) + max_by_exercise: dict[str, dict[date, float]] = {} + for log in workout_logs: + d = date_of(log) + if d not in date_set: + continue + for exercise in log.exercises: + if exercise.category != ExerciseCategory.STRENGTH: + continue + weights = [s.weight_kg for s in exercise.sets if s.weight_kg is not None] + if not weights: + continue + by_date = max_by_exercise.setdefault(exercise.exercise_name, {}) + by_date[d] = max(by_date.get(d, 0.0), *weights) + + top = sorted(max_by_exercise, key=lambda name: (-len(max_by_exercise[name]), name))[:top_n] + return {name: [max_by_exercise[name].get(d) for d in dates] for name in top} + + +def strength_volume_by_date( + workout_logs: Iterable[WorkoutLog], + date_of: Callable[[WorkoutLog], date], + dates: list[date], +) -> list[float]: + """筋トレの総挙上量(重量×回数の全セット合計、kg)を日別に返す。 + + 重量の無いセット(自重種目)は重量を決められないため含めない。 + """ + totals = dict.fromkeys(dates, 0.0) + for log in workout_logs: + d = date_of(log) + if d not in totals: + continue + for exercise in log.exercises: + if exercise.category != ExerciseCategory.STRENGTH: + continue + totals[d] += sum(s.weight_kg * s.reps for s in exercise.sets if s.weight_kg is not None) + return [totals[d] for d in dates] + + +def cardio_minutes_by_exercise( + workout_logs: Iterable[WorkoutLog], + date_of: Callable[[WorkoutLog], date], + dates: list[date], +) -> dict[str, list[float]]: + """有酸素種目ごとの日別運動時間(分)を返す(種目別の積み上げ棒グラフ用)。 + + 表示期間内に一度も記録の無い種目は含めない。種目の並びは期間内の + 合計時間が長い順(積み上げの下側・凡例の上側に主要な種目が来るように)。 + """ + date_set = set(dates) + minutes: dict[str, dict[date, float]] = {} + for log in workout_logs: + d = date_of(log) + if d not in date_set: + continue + for exercise in log.exercises: + if exercise.category != ExerciseCategory.CARDIO: + continue + by_date = minutes.setdefault(exercise.exercise_name, {}) + by_date[d] = by_date.get(d, 0.0) + (exercise.duration_minutes or 0) + + order = sorted(minutes, key=lambda name: (-sum(minutes[name].values()), name)) + return {name: [minutes[name].get(d, 0.0) for d in dates] for name in order} diff --git a/app/i18n.py b/app/i18n.py index b139997..fe0d8ef 100644 --- a/app/i18n.py +++ b/app/i18n.py @@ -66,7 +66,6 @@ def t(text: str, **kwargs: object) -> str: "今日": "Today", "長期目標": "Goals", "CSVインポート": "CSV Import", - "レシピ": "Recipe", "言語": "Language", "ログアウト": "Log out", "ログインしてください。": "Please log in.", @@ -102,9 +101,18 @@ def t(text: str, **kwargs: object) -> str: "作業時間(分) — 学習ログ + タスク実績": "Work time (min) — learning log + task records", "作業時間(分)": "Work time (min)", "運動": "Exercise", - "運動セッション数": "Workout sessions", - "セッション数": "Sessions", "有酸素運動時間(分)": "Cardio time (min)", + "有酸素運動時間(分) — 種目別": "Cardio time (min) — by exercise", + "種目別の最大重量(kg) — 記録日数の多い上位5種目": ( + "Max weight per exercise (kg) — top 5 most frequent" + ), + "直近{days}日間の筋トレ(重量あり)の記録がありません。": ( + "No weighted strength training records in the past {days} days." + ), + "総挙上量(kg)": "Total volume (kg)", + "総挙上量(kg) — 重量×回数の合計、自重種目は除く": ( + "Total volume (kg) — weight × reps, excluding bodyweight exercises" + ), "家計": "Household", "食費合計(円)": "Total food expense (JPY)", # --- pages/recipe.py --- diff --git a/app/pages/dashboard.py b/app/pages/dashboard.py index 86bb75f..9ecbfc7 100644 --- a/app/pages/dashboard.py +++ b/app/pages/dashboard.py @@ -19,9 +19,12 @@ import streamlit as st # noqa: E402 from auth_guard import require_login # noqa: E402 from components.dashboard_charts import ( # noqa: E402 + cardio_minutes_by_exercise, group_average_by_date, group_sum_by_date, last_n_days, + strength_max_weight_by_exercise, + strength_volume_by_date, ) from components.formatting import jst_date_of # noqa: E402 from i18n import t # noqa: E402 @@ -38,12 +41,11 @@ ) from health_intelligence.domain.enums import ( # noqa: E402 - ExerciseCategory, GoalCategory, LearningCategory, TaskLogType, ) -from health_intelligence.domain.models import DailyTaskLog # noqa: E402 +from health_intelligence.domain.models import DailyTaskLog, WorkoutLog # noqa: E402 auth_state = require_login() user_id = auth_state.require_user_id() @@ -127,11 +129,17 @@ def _line_chart( key: str, caption: str, integer_y: bool = False, + connect_gaps: bool = False, ) -> None: """`integer_y=True`で、y軸の目盛りを整数のみにする(体調スコア等、 値自体は1〜5の整数だが、1日に複数回記録した日はその日の平均を プロットするため点の位置は小数になり得る値用。目盛りだけを整数に 揃え、点・線の位置(実際の平均値)自体は変えない)。 + + `connect_gaps=True`で、記録の無い日(None)を飛ばして前後の点を線で + 結ぶ(筋トレ種目の重量等、数日おきにしか記録しない値用。既定では + Noneの日で線が途切れ、点が孤立して推移が読み取れないため)。 + x軸には記録の無い日も含めて表示期間の全日付を並べる。 """ date_col = t("日付") indicator_col = t("指標") @@ -144,10 +152,18 @@ def _line_chart( indicator_col: [name for name, values in series.items() for _ in values], } ) + if connect_gaps: + df = df.dropna(subset=[y_title]) y_axis = alt.Axis(tickMinStep=1, format="d") if integer_y else alt.Axis() encode_kwargs: dict[str, object] = { - "x": alt.X(f"{date_col}:N", sort=None, title=None, axis=alt.Axis(labelAngle=_LABEL_ANGLE)), - "y": alt.Y(f"{y_title}:Q", axis=y_axis), + "x": alt.X( + f"{date_col}:N", + sort=None, + title=None, + axis=alt.Axis(labelAngle=_LABEL_ANGLE), + scale=alt.Scale(domain=_DATE_LABELS), + ), + "y": alt.Y(f"{y_title}:Q", axis=y_axis, scale=alt.Scale(zero=not connect_gaps)), } if len(series) > 1: encode_kwargs["color"] = alt.Color( @@ -384,30 +400,67 @@ def _task_minutes_by_category(categories: set[GoalCategory]) -> list[float]: st.subheader(t("運動")) workout_logs = get_workout_service().list_workout_logs(user_id) -session_col, cardio_col = st.columns(2) -with session_col: + + +def _workout_date(w: WorkoutLog) -> date: + return jst_date_of(w.performed_at) + + +max_weight_series = strength_max_weight_by_exercise(workout_logs, _workout_date, _DAYS) +if max_weight_series: + _line_chart( + max_weight_series, + y_title=t("重量(kg)"), + key="strength-max-weight", + caption=t("種目別の最大重量(kg) — 記録日数の多い上位5種目"), + connect_gaps=True, + ) +else: + with st.container(border=True, key="dashboard-chart-strength-max-weight"): + st.caption(t("種目別の最大重量(kg) — 記録日数の多い上位5種目")) + st.caption(t("直近{days}日間の筋トレ(重量あり)の記録がありません。", days=selected_period)) + +volume_col, cardio_col = st.columns(2) +with volume_col: _bar_chart( - group_sum_by_date(workout_logs, lambda w: jst_date_of(w.performed_at), lambda w: 1, _DAYS), - y_title=t("セッション数"), - key="workout-sessions", - caption=t("運動セッション数"), - integer_y=True, - y_domain=(0, 10), + strength_volume_by_date(workout_logs, _workout_date, _DAYS), + y_title=t("総挙上量(kg)"), + key="strength-volume", + caption=t("総挙上量(kg) — 重量×回数の合計、自重種目は除く"), ) with cardio_col: - cardio_pairs = [ - (jst_date_of(w.performed_at), exercise.duration_minutes or 0) - for w in workout_logs - for exercise in w.exercises - if exercise.category == ExerciseCategory.CARDIO - ] - _bar_chart( - group_sum_by_date(cardio_pairs, lambda p: p[0], lambda p: p[1], _DAYS), - y_title=t("有酸素運動時間(分)"), - key="cardio", - caption=t("有酸素運動時間(分)"), - y_domain=(0, 360), + exercise_col = t("種目") + minutes_col = t("時間(分)") + cardio_series = cardio_minutes_by_exercise(workout_logs, _workout_date, _DAYS) + cardio_df = pd.DataFrame( + { + _date_col: [label for _ in cardio_series for label in _DATE_LABELS], + minutes_col: pd.Series( + [v for values in cardio_series.values() for v in values], dtype="float64" + ), + exercise_col: [name for name, values in cardio_series.items() for _ in values], + } + ) + # カロリー等と同様、積み上げ合計が固定上限(90分)を超える日は上限を広げる。 + cardio_max = max([90.0, *(sum(day) for day in zip(*cardio_series.values(), strict=True))]) + cardio_chart = ( + alt.Chart(cardio_df) + .mark_bar() + .encode( + x=alt.X( + f"{_date_col}:N", + sort=None, + title=None, + axis=alt.Axis(labelAngle=_LABEL_ANGLE), + scale=alt.Scale(domain=_DATE_LABELS), + ), + y=alt.Y(f"{minutes_col}:Q", stack="zero", scale=alt.Scale(domain=[0, cardio_max])), + color=alt.Color(f"{exercise_col}:N", title=exercise_col, sort=list(cardio_series)), + ) ) + with st.container(border=True, key="dashboard-chart-cardio"): + st.caption(t("有酸素運動時間(分) — 種目別")) + st.altair_chart(cardio_chart, width="stretch") st.divider() diff --git a/app/streamlit_app.py b/app/streamlit_app.py index b416f7e..21d0fbe 100644 --- a/app/streamlit_app.py +++ b/app/streamlit_app.py @@ -190,7 +190,7 @@ csv_import_page = st.Page( "pages/csv_import.py", title=t("CSVインポート"), icon=":material/upload_file:" ) - recipe_page = st.Page("pages/recipe.py", title=t("レシピ"), icon=":material/restaurant_menu:") + recipe_page = st.Page("pages/recipe.py", title=t("AIレシピ"), icon=":material/restaurant_menu:") pg = st.navigation( [ dashboard_page, diff --git a/docs/requirements.md b/docs/requirements.md index 880e7a1..064e7b4 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -1068,7 +1068,7 @@ Dashboardでは、選択した表示期間(直近7日/30日/90日。既定は7 * 睡眠時間・体調スコア(総合/朝/夜/メンタル/疲労/ストレス) * カロリー・PFC * 学習時間・作業時間(学習ログ + Task実績) -* 運動セッション数・有酸素運動時間 +* 有酸素運動時間 * 食費合計 > Health ScoreおよびRule-based Recommendationは8章・9章の通りバックエンドでは実装済みだが、現在のUIでは表示していない(過去にダッシュボードへ表示していたが、週間グラフ中心の構成へ変更した際に外した)。再度UIへ統合する場合は別途設計する。 diff --git a/tests/unit/test_dashboard_charts.py b/tests/unit/test_dashboard_charts.py index 53da58d..071f696 100644 --- a/tests/unit/test_dashboard_charts.py +++ b/tests/unit/test_dashboard_charts.py @@ -4,15 +4,26 @@ import sys from dataclasses import dataclass -from datetime import date +from datetime import UTC, date, datetime from pathlib import Path +from uuid import uuid4 sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "app")) from components.dashboard_charts import ( # noqa: E402 + cardio_minutes_by_exercise, group_average_by_date, group_sum_by_date, last_n_days, + strength_max_weight_by_exercise, + strength_volume_by_date, +) + +from health_intelligence.domain.enums import ExerciseCategory # noqa: E402 +from health_intelligence.domain.models import ( # noqa: E402 + WorkoutExercise, + WorkoutLog, + WorkoutSet, ) @@ -69,3 +80,79 @@ def test_group_average_by_date_averages_and_skips_none_values() -> None: result = group_average_by_date(items, lambda i: i.day, lambda i: i.value, dates) assert result == [None, 3.0] + + +_D1, _D2, _D3 = date(2026, 6, 1), date(2026, 6, 2), date(2026, 6, 3) + + +def _strength(name: str, *sets: tuple[int, float | None]) -> WorkoutExercise: + return WorkoutExercise( + exercise_name=name, + category=ExerciseCategory.STRENGTH, + sets=[WorkoutSet(reps=reps, weight_kg=weight) for reps, weight in sets], + ) + + +def _cardio(name: str, minutes: int) -> WorkoutExercise: + return WorkoutExercise( + exercise_name=name, category=ExerciseCategory.CARDIO, duration_minutes=minutes + ) + + +def _workout(day: date, *exercises: WorkoutExercise) -> WorkoutLog: + return WorkoutLog( + workout_log_id=uuid4(), + user_id=uuid4(), + performed_at=datetime(day.year, day.month, day.day, tzinfo=UTC), + exercises=list(exercises), + ) + + +def _day_of(w: WorkoutLog) -> date: + return w.performed_at.date() + + +def test_strength_max_weight_takes_daily_max_and_skips_bodyweight_sets() -> None: + logs = [ + _workout(_D1, _strength("スクワット", (10, 60.0), (8, 70.0)), _strength("懸垂", (8, None))), + _workout(_D3, _strength("スクワット", (5, 80.0))), + _workout(_D3, _cardio("ランニング", 30)), + ] + + result = strength_max_weight_by_exercise(logs, _day_of, [_D1, _D2, _D3]) + + assert result == {"スクワット": [70.0, None, 80.0]} + + +def test_strength_max_weight_keeps_top_n_by_recorded_days() -> None: + logs = [ + _workout(_D1, _strength("A", (1, 10.0)), _strength("B", (1, 10.0))), + _workout(_D2, _strength("B", (1, 10.0)), _strength("C", (1, 10.0))), + _workout(_D3, _strength("B", (1, 10.0)), _strength("C", (1, 10.0))), + ] + + result = strength_max_weight_by_exercise(logs, _day_of, [_D1, _D2, _D3], top_n=2) + + assert list(result) == ["B", "C"] + + +def test_strength_volume_sums_weight_times_reps_per_day() -> None: + logs = [ + _workout(_D1, _strength("スクワット", (10, 60.0), (8, 70.0)), _strength("懸垂", (8, None))), + _workout(_D1, _strength("デッドリフト", (5, 100.0))), + _workout(_D2, _cardio("ランニング", 30)), + ] + + assert strength_volume_by_date(logs, _day_of, [_D1, _D2]) == [1660.0, 0.0] + + +def test_cardio_minutes_by_exercise_orders_by_total_minutes() -> None: + logs = [ + _workout(_D1, _cardio("散歩", 20), _cardio("ランニング", 30)), + _workout(_D2, _cardio("ランニング", 40), _strength("スクワット", (10, 60.0))), + _workout(date(2026, 5, 1), _cardio("サイクリング", 90)), + ] + + result = cardio_minutes_by_exercise(logs, _day_of, [_D1, _D2]) + + assert result == {"ランニング": [30.0, 40.0], "散歩": [20.0, 0.0]} From f7a999e3ee9dcf7a7b7dc424bf4f7bdf01a3f192 Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Thu, 24 Sep 2026 07:42:41 +0900 Subject: [PATCH 7/9] feat(dashboard): remove strength volume chart Workout section now shows max weight per exercise and cardio time by exercise, both full width. Co-Authored-By: Claude Opus 5.5 --- app/components/dashboard_charts.py | 21 --------- app/i18n.py | 4 -- app/pages/dashboard.py | 72 +++++++++++++---------------- tests/unit/test_dashboard_charts.py | 11 ----- 4 files changed, 31 insertions(+), 77 deletions(-) diff --git a/app/components/dashboard_charts.py b/app/components/dashboard_charts.py index 03ed2e7..fc76133 100644 --- a/app/components/dashboard_charts.py +++ b/app/components/dashboard_charts.py @@ -91,27 +91,6 @@ def strength_max_weight_by_exercise( return {name: [max_by_exercise[name].get(d) for d in dates] for name in top} -def strength_volume_by_date( - workout_logs: Iterable[WorkoutLog], - date_of: Callable[[WorkoutLog], date], - dates: list[date], -) -> list[float]: - """筋トレの総挙上量(重量×回数の全セット合計、kg)を日別に返す。 - - 重量の無いセット(自重種目)は重量を決められないため含めない。 - """ - totals = dict.fromkeys(dates, 0.0) - for log in workout_logs: - d = date_of(log) - if d not in totals: - continue - for exercise in log.exercises: - if exercise.category != ExerciseCategory.STRENGTH: - continue - totals[d] += sum(s.weight_kg * s.reps for s in exercise.sets if s.weight_kg is not None) - return [totals[d] for d in dates] - - def cardio_minutes_by_exercise( workout_logs: Iterable[WorkoutLog], date_of: Callable[[WorkoutLog], date], diff --git a/app/i18n.py b/app/i18n.py index fe0d8ef..176a455 100644 --- a/app/i18n.py +++ b/app/i18n.py @@ -109,10 +109,6 @@ def t(text: str, **kwargs: object) -> str: "直近{days}日間の筋トレ(重量あり)の記録がありません。": ( "No weighted strength training records in the past {days} days." ), - "総挙上量(kg)": "Total volume (kg)", - "総挙上量(kg) — 重量×回数の合計、自重種目は除く": ( - "Total volume (kg) — weight × reps, excluding bodyweight exercises" - ), "家計": "Household", "食費合計(円)": "Total food expense (JPY)", # --- pages/recipe.py --- diff --git a/app/pages/dashboard.py b/app/pages/dashboard.py index 9ecbfc7..0f492fe 100644 --- a/app/pages/dashboard.py +++ b/app/pages/dashboard.py @@ -24,7 +24,6 @@ group_sum_by_date, last_n_days, strength_max_weight_by_exercise, - strength_volume_by_date, ) from components.formatting import jst_date_of # noqa: E402 from i18n import t # noqa: E402 @@ -420,47 +419,38 @@ def _workout_date(w: WorkoutLog) -> date: st.caption(t("種目別の最大重量(kg) — 記録日数の多い上位5種目")) st.caption(t("直近{days}日間の筋トレ(重量あり)の記録がありません。", days=selected_period)) -volume_col, cardio_col = st.columns(2) -with volume_col: - _bar_chart( - strength_volume_by_date(workout_logs, _workout_date, _DAYS), - y_title=t("総挙上量(kg)"), - key="strength-volume", - caption=t("総挙上量(kg) — 重量×回数の合計、自重種目は除く"), - ) -with cardio_col: - exercise_col = t("種目") - minutes_col = t("時間(分)") - cardio_series = cardio_minutes_by_exercise(workout_logs, _workout_date, _DAYS) - cardio_df = pd.DataFrame( - { - _date_col: [label for _ in cardio_series for label in _DATE_LABELS], - minutes_col: pd.Series( - [v for values in cardio_series.values() for v in values], dtype="float64" - ), - exercise_col: [name for name, values in cardio_series.items() for _ in values], - } - ) - # カロリー等と同様、積み上げ合計が固定上限(90分)を超える日は上限を広げる。 - cardio_max = max([90.0, *(sum(day) for day in zip(*cardio_series.values(), strict=True))]) - cardio_chart = ( - alt.Chart(cardio_df) - .mark_bar() - .encode( - x=alt.X( - f"{_date_col}:N", - sort=None, - title=None, - axis=alt.Axis(labelAngle=_LABEL_ANGLE), - scale=alt.Scale(domain=_DATE_LABELS), - ), - y=alt.Y(f"{minutes_col}:Q", stack="zero", scale=alt.Scale(domain=[0, cardio_max])), - color=alt.Color(f"{exercise_col}:N", title=exercise_col, sort=list(cardio_series)), - ) +exercise_col = t("種目") +minutes_col = t("時間(分)") +cardio_series = cardio_minutes_by_exercise(workout_logs, _workout_date, _DAYS) +cardio_df = pd.DataFrame( + { + _date_col: [label for _ in cardio_series for label in _DATE_LABELS], + minutes_col: pd.Series( + [v for values in cardio_series.values() for v in values], dtype="float64" + ), + exercise_col: [name for name, values in cardio_series.items() for _ in values], + } +) +# カロリー等と同様、積み上げ合計が固定上限(90分)を超える日は上限を広げる。 +cardio_max = max([90.0, *(sum(day) for day in zip(*cardio_series.values(), strict=True))]) +cardio_chart = ( + alt.Chart(cardio_df) + .mark_bar() + .encode( + x=alt.X( + f"{_date_col}:N", + sort=None, + title=None, + axis=alt.Axis(labelAngle=_LABEL_ANGLE), + scale=alt.Scale(domain=_DATE_LABELS), + ), + y=alt.Y(f"{minutes_col}:Q", stack="zero", scale=alt.Scale(domain=[0, cardio_max])), + color=alt.Color(f"{exercise_col}:N", title=exercise_col, sort=list(cardio_series)), ) - with st.container(border=True, key="dashboard-chart-cardio"): - st.caption(t("有酸素運動時間(分) — 種目別")) - st.altair_chart(cardio_chart, width="stretch") +) +with st.container(border=True, key="dashboard-chart-cardio"): + st.caption(t("有酸素運動時間(分) — 種目別")) + st.altair_chart(cardio_chart, width="stretch") st.divider() diff --git a/tests/unit/test_dashboard_charts.py b/tests/unit/test_dashboard_charts.py index 071f696..3aeca7d 100644 --- a/tests/unit/test_dashboard_charts.py +++ b/tests/unit/test_dashboard_charts.py @@ -16,7 +16,6 @@ group_sum_by_date, last_n_days, strength_max_weight_by_exercise, - strength_volume_by_date, ) from health_intelligence.domain.enums import ExerciseCategory # noqa: E402 @@ -136,16 +135,6 @@ def test_strength_max_weight_keeps_top_n_by_recorded_days() -> None: assert list(result) == ["B", "C"] -def test_strength_volume_sums_weight_times_reps_per_day() -> None: - logs = [ - _workout(_D1, _strength("スクワット", (10, 60.0), (8, 70.0)), _strength("懸垂", (8, None))), - _workout(_D1, _strength("デッドリフト", (5, 100.0))), - _workout(_D2, _cardio("ランニング", 30)), - ] - - assert strength_volume_by_date(logs, _day_of, [_D1, _D2]) == [1660.0, 0.0] - - def test_cardio_minutes_by_exercise_orders_by_total_minutes() -> None: logs = [ _workout(_D1, _cardio("散歩", 20), _cardio("ランニング", 30)), From d7985642feb56fe94ed091641275ebdd2826bd2e Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Thu, 24 Sep 2026 07:42:41 +0900 Subject: [PATCH 8/9] chore(claude): add pytest DB guard hook and /check, /db-health skills - PreToolUse hook blocks pytest unless .env.test exists or DATABASE_URL is overridden to localhost (test_migrations.py wipes the configured DB) - /check: ruff, format, mypy, i18n duplicate keys, safe unit tests - /db-health: read-only production DB check (counts, content duplicates, latest record date, orphaned workout rows) - Expose csv_import.content_key for reuse by /db-health - Ignore .claude/settings.local.json Co-Authored-By: Claude Opus 5.5 --- .claude/hooks/guard_pytest_db.py | 57 ++++++++++++++ .claude/settings.json | 16 ++++ .claude/skills/check/SKILL.md | 26 +++++++ .claude/skills/check/check.sh | 45 +++++++++++ .claude/skills/db-health/SKILL.md | 28 +++++++ .claude/skills/db-health/db_health.py | 104 ++++++++++++++++++++++++++ .gitignore | 3 + app/components/csv_import.py | 6 +- 8 files changed, 282 insertions(+), 3 deletions(-) create mode 100644 .claude/hooks/guard_pytest_db.py create mode 100644 .claude/settings.json create mode 100644 .claude/skills/check/SKILL.md create mode 100755 .claude/skills/check/check.sh create mode 100644 .claude/skills/db-health/SKILL.md create mode 100644 .claude/skills/db-health/db_health.py diff --git a/.claude/hooks/guard_pytest_db.py b/.claude/hooks/guard_pytest_db.py new file mode 100644 index 0000000..7332884 --- /dev/null +++ b/.claude/hooks/guard_pytest_db.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""PreToolUse(Bash) hook: 本番DBを巻き込むpytest実行をブロックする。 + +tests/unit/test_migrations.py は全テーブルを drop/再作成し、 +tests/integration/ は実データを書き込む。`.env.test`(テスト専用DB)が +無い状態でpytestを走らせると、`.env`の日常用DB(Neon)がそのまま使われ、 +データが消える(過去に実際に起きかけた事故)。 + +次のいずれかを満たす場合のみpytestの実行を許可する: +- プロジェクト直下に `.env.test` がある(conftest.pyがテスト用DBへ上書きする) +- コマンド内で DATABASE_URL を localhost / 127.0.0.1 へ上書きしている + (/check スキルはこの形で実行する) +""" + +from __future__ import annotations + +import json +import os +import re +import sys +from pathlib import Path + +# pytestを「コマンドとして」起動している箇所だけを検出する +# (`grep pytest pyproject.toml` のような引数中の出現は対象外)。 +_PYTEST_INVOCATION = re.compile( + r"(?:^|[;&|(\n]|\bthen\b|\bdo\b)\s*" + r"(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*" + r"(?:env\s+(?:(?:-u|--unset)\s+\S+\s+|-\S+\s+)*(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*)?" + r"(?:(?:uv|poetry)\s+run\s+)?" + r"(?:\S*/)?(?:pytest|py\.test|python3?(?:\.\d+)?\s+-m\s+pytest)\b" +) +_SAFE_DB_OVERRIDE = re.compile(r"DATABASE_URL=\S*@(?:127\.0\.0\.1|localhost)[:/]") + + +def main() -> int: + payload = json.load(sys.stdin) + command = payload.get("tool_input", {}).get("command", "") + if not _PYTEST_INVOCATION.search(command): + return 0 + + project_dir = Path(os.environ.get("CLAUDE_PROJECT_DIR", Path(__file__).resolve().parents[2])) + if (project_dir / ".env.test").exists() or _SAFE_DB_OVERRIDE.search(command): + return 0 + + print( + "Blocked: .env.test が無い状態で pytest を実行すると、.env の本番DB(Neon)に対して" + " test_migrations.py が全テーブルを drop/再作成します。\n" + "代わりに /check スキル(.claude/skills/check/check.sh)を使うか、" + "DATABASE_URL=postgresql+psycopg://safe:safe@127.0.0.1:1/unreachable を" + "コマンドの先頭に付けて実行してください。", + file=sys.stderr, + ) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..751de2c --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard_pytest_db.py\"", + "timeout": 10 + } + ] + } + ] + } +} diff --git a/.claude/skills/check/SKILL.md b/.claude/skills/check/SKILL.md new file mode 100644 index 0000000..f418dd5 --- /dev/null +++ b/.claude/skills/check/SKILL.md @@ -0,0 +1,26 @@ +--- +name: check +description: Run this project's full quality gate (ruff lint, ruff format, mypy, i18n duplicate-key check, unit tests against a safe dummy DB). Use after code changes and before committing, instead of running pytest directly — plain pytest can wipe the production Neon DB. +--- + +# /check + +Run the bundled script from the repository root: + +```bash +.claude/skills/check/check.sh +``` + +It runs, in order, and reports every failure (it does not stop at the first): + +1. `ruff check app src tests` +2. `ruff format --check app src tests` +3. `mypy src` +4. Duplicate keys in `TRANSLATIONS` (`app/i18n.py`) +5. `pytest tests/unit` with `DATABASE_URL` pointed at an unreachable localhost and `tests/unit/test_migrations.py` excluded + +## Rules + +- Never run `pytest` directly against the default environment. Without `.env.test`, `tests/unit/test_migrations.py` drops and recreates every table in the `.env` production DB, and `tests/integration/` writes to it. A PreToolUse hook (`.claude/hooks/guard_pytest_db.py`) blocks such runs. +- If ruff format fails, fix with `.venv/bin/ruff format app src tests` and re-run. +- Report the final `ALL PASSED` / `FAILED: ...` line to the user; on failure include the failing step's output. diff --git a/.claude/skills/check/check.sh b/.claude/skills/check/check.sh new file mode 100755 index 0000000..b149e00 --- /dev/null +++ b/.claude/skills/check/check.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# lint / format / 型 / i18n / ユニットテストを一括で実行する。 +# テストは本番DB(.envのNeon)に触れないよう、DATABASE_URLを到達不能な +# localhostへ差し替え、DBを破壊するtest_migrations.pyを除外して実行する +# (.env.testがある場合はconftest.pyがそちらで上書きする)。 +set -uo pipefail +cd "$(git rev-parse --show-toplevel)" + +SAFE_DB_URL="postgresql+psycopg://safe:safe@127.0.0.1:1/unreachable" +failed=() + +step() { + local name="$1" + shift + echo "== ${name}" + if "$@"; then echo " OK"; else echo " FAILED"; failed+=("$name"); fi +} + +check_i18n() { + .venv/bin/python - <<'PY' +import collections +import re +import sys + +keys = re.findall(r'^ "(.+?)":', open("app/i18n.py", encoding="utf-8").read(), re.M) +dups = [k for k, n in collections.Counter(keys).items() if n > 1] +if dups: + print(" duplicate TRANSLATIONS keys:", dups) + sys.exit(1) +PY +} + +step "ruff check" .venv/bin/ruff check app src tests +step "ruff format" .venv/bin/ruff format --check app src tests +step "mypy" .venv/bin/mypy src +step "i18n duplicate keys" check_i18n +step "pytest (unit, safe DB)" env DATABASE_URL="$SAFE_DB_URL" \ + .venv/bin/pytest tests/unit --ignore=tests/unit/test_migrations.py -q -p no:cacheprovider + +echo +if ((${#failed[@]})); then + echo "FAILED: ${failed[*]}" + exit 1 +fi +echo "ALL PASSED" diff --git a/.claude/skills/db-health/SKILL.md b/.claude/skills/db-health/SKILL.md new file mode 100644 index 0000000..77cc0fa --- /dev/null +++ b/.claude/skills/db-health/SKILL.md @@ -0,0 +1,28 @@ +--- +name: db-health +description: Read-only health check of the production Neon DB — per-user log counts, content-duplicate records (e.g. double CSV imports), latest record date per log type, and orphaned workout exercises/sets. Use when dashboard charts look empty, inflated, or wrong, or after bulk CSV imports. +--- + +# /db-health + +Run from the repository root: + +```bash +.venv/bin/python .claude/skills/db-health/db_health.py +``` + +The script connects with `postgresql_readonly` (Postgres rejects any write with `ReadOnlySqlTransaction`), so it is safe to run against production. It takes a few seconds because the DB is remote. + +## Reading the output + +- **重複**: records whose content matches another record exactly (all fields except the ID). Same rule as the CSV import dedupe (`content_key` in `app/components/csv_import.py`). Non-zero usually means a CSV was imported more than once, which multiplies dashboard totals. +- **最終記録日**: if it is more than 7 days ago, the dashboard's default "last 7 days" view is empty for that log type. That is expected, not a bug. +- **Orphans**: workout exercises or sets with no parent row. + +## Fixing problems + +This skill only diagnoses. Deleting duplicates is destructive and irreversible, so: + +1. Show the user the counts and ask for explicit confirmation first. +2. Dry-run, then delete through the repositories (`uow..delete(user_id, id)`, keeping one record per `content_key`) in a single transaction, so workout exercises and sets cascade and a failure rolls everything back. +3. Re-run `/db-health` to confirm, and tell the user to restart Streamlit: the app caches reads for up to 10 minutes and does not see changes made outside the app. diff --git a/.claude/skills/db-health/db_health.py b/.claude/skills/db-health/db_health.py new file mode 100644 index 0000000..1b23edb --- /dev/null +++ b/.claude/skills/db-health/db_health.py @@ -0,0 +1,104 @@ +"""本番DB(.envのDATABASE_URL)の健全性を読み取り専用で点検する。 + +- ログ種別ごとの件数・重複件数(内容が完全一致するレコード。CSVインポートの + 二重取り込み判定 `content_key` と同じ基準)・最終記録日(JST) +- 運動ログの子テーブル(種目・セット)の孤児行 + +接続は `postgresql_readonly` を指定したトランザクションで行うため、 +このスクリプトからDBへ書き込むことはできない。 + +使い方(リポジトリ直下から): + .venv/bin/python .claude/skills/db-health/db_health.py +""" + +from __future__ import annotations + +import os +import sys +from collections import Counter +from datetime import UTC, datetime +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT / "app")) + +from components.csv_import import content_key # noqa: E402 +from components.formatting import jst_date_of # noqa: E402 +from sqlalchemy import create_engine, text # noqa: E402 +from sqlalchemy.orm import sessionmaker # noqa: E402 + +from health_intelligence.config import load_environment # noqa: E402 +from health_intelligence.repositories.sqlalchemy.unit_of_work import ( # noqa: E402 + SqlAlchemyUnitOfWork, +) + +# (UoWの属性名, 表示名, 記録日時の属性名) +_LOGS = [ + ("meal_logs", "食事", "consumed_at"), + ("workout_logs", "運動", "performed_at"), + ("sleep_logs", "睡眠", "bedtime"), + ("weight_logs", "体重", "recorded_at"), + ("health_logs", "体調", "recorded_at"), + ("learning_logs", "学習", "started_at"), +] +_STALE_DAYS = 7 +_ORPHAN_QUERIES = { + "workout_exercises(親の運動ログなし)": ( + "select count(*) from workout_exercises e" + " where not exists (select 1 from workout_logs w where w.id = e.workout_log_id)" + ), + "workout_sets(親の種目なし)": ( + "select count(*) from workout_sets s" + " where not exists (select 1 from workout_exercises e where e.id = s.workout_exercise_id)" + ), +} + + +def main() -> int: + load_environment() + engine = create_engine( + os.environ["DATABASE_URL"], + pool_pre_ping=True, + execution_options={"postgresql_readonly": True}, + ) + today = jst_date_of(datetime.now(UTC)) + problems: list[str] = [] + + with SqlAlchemyUnitOfWork(sessionmaker(bind=engine)) as uow: + session = uow._session + assert session is not None + users = session.execute(text("select id, email from users order by email")).all() + + for user_id, email in users: + print(f"# {email}") + print(f" {'種別':<4} {'件数':>6} {'重複':>6} {'最終記録日(JST)':>16}") + for attr, label, at_field in _LOGS: + logs = getattr(uow, attr).list_by_user(user_id) + counts = Counter(content_key(log) for log in logs) + duplicates = sum(n - 1 for n in counts.values()) + latest = max((jst_date_of(getattr(log, at_field)) for log in logs), default=None) + latest_text = latest.isoformat() if latest else "-" + print(f" {label:<4} {len(logs):>6} {duplicates:>6} {latest_text:>16}") + + if duplicates: + problems.append(f"{email} {label}: 内容が同一の重複 {duplicates}件") + if latest is not None and (today - latest).days > _STALE_DAYS: + problems.append( + f"{email} {label}: 最終記録が{(today - latest).days}日前" + f"({latest.isoformat()}) → ダッシュボードの直近{_STALE_DAYS}日間は空" + ) + print() + + for label, sql in _ORPHAN_QUERIES.items(): + orphans = session.execute(text(sql)).scalar_one() + if orphans: + problems.append(f"{label}: {orphans}行") + + print("## 検出事項") + for problem in problems or ["なし"]: + print(f"- {problem}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.gitignore b/.gitignore index 6da64ab..9a827c9 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,6 @@ Thumbs.db kiroku data + +# Claude Code personal settings +.claude/settings.local.json diff --git a/app/components/csv_import.py b/app/components/csv_import.py index 7533d51..7258579 100644 --- a/app/components/csv_import.py +++ b/app/components/csv_import.py @@ -453,7 +453,7 @@ def _hashable(value: Any) -> Any: return value -def _content_key(log: Any) -> Any: +def content_key(log: Any) -> Any: """IDフィールド(`*_log_id`)を除いた全フィールドの値を、比較用のキーにする。 CSVインポートではIDを毎回`uuid4()`で採番するため、同じ行を取り込み直すと @@ -470,9 +470,9 @@ def split_new_logs[T](logs: list[T], existing: Iterable[T]) -> tuple[list[T], li 取り込まない。CSVファイル内で同じ内容の行が複数ある場合は、 それぞれ別の記録(例: 同じ時刻の間食2回)とみなして両方取り込む。 """ - existing_keys = {_content_key(log) for log in existing} + existing_keys = {content_key(log) for log in existing} new: list[T] = [] duplicates: list[T] = [] for log in logs: - (duplicates if _content_key(log) in existing_keys else new).append(log) + (duplicates if content_key(log) in existing_keys else new).append(log) return new, duplicates From e0daf9fe8704eb88dc21214abca3b8bf95408c8f Mon Sep 17 00:00:00 2001 From: Shimpei Ohtani Date: Thu, 24 Sep 2026 07:45:54 +0900 Subject: [PATCH 9/9] docs: sync README/architecture/requirements with recent changes - README (en/ja): describe new dashboard workout charts and CSV duplicate-row skipping; fix the testing section (tests/unit includes the DB-destroying test_migrations.py) to use check.sh / /check, add /db-health usage, the pytest DB guard hook, the 10-minute read cache limitation, and .claude/ in the project structure - architecture.md: add 7.4 remote-DB performance design (read cache and invalidation, parallel prefetch, bulk CSV insert, N+1 avoidance), test DB protection layers in ch.18, and .claude/ in ch.20 - requirements.md: update dashboard chart list and y-axis auto-expand, CSV import dedupe/bulk save, "AI Recipes" page name, and add 17.6 performance requirements Co-Authored-By: Claude Opus 5.5 --- README.ja.md | 38 ++++++++++++++++++++++++++------------ README.md | 39 +++++++++++++++++++++++++++------------ docs/architecture.md | 24 +++++++++++++++++++++++- docs/requirements.md | 18 +++++++++++++++--- 4 files changed, 91 insertions(+), 28 deletions(-) diff --git a/README.ja.md b/README.ja.md index be53ff1..30b363d 100644 --- a/README.ja.md +++ b/README.ja.md @@ -14,10 +14,10 @@ - 「今日」ページ: 1日分の記録をP(計画)→D(実績)→C(振り返り)→A(改善)のPDCA形式で1画面完結。睡眠・体調(5軸)・食事・運動(セッション/種目/セット構造)・学習/PF開発/仕事・家計(買い物メモ/食費)をここで記録する - 長期目標(Goal)・タスク(Task)管理: 長期目標ごとにタスクを紐づけ、「今日」ページのPで日々選択、進捗を集計。学習/PF開発/仕事は数量・時間・メモを記録し、食事方針/運動目標/睡眠目標は選ぶだけで実績は既存ドメイン(MealLog/WorkoutLog/SleepLog)に記録される - 学習ログ(試験勉強・PF開発・調べ物・キャリア/プロダクト戦略設計、カテゴリごとに入力項目が切り替わる)。「今日」ページのD(実績)タブで記録 -- Dashboardページで睡眠・体調・食事・学習/作業時間・運動・食費をグラフ表示(表示期間は直近7日/30日/90日から選択。既定は7日) +- Dashboardページで睡眠・体調・食事・学習/作業時間・運動(筋トレ種目別の最大重量の推移、種目別の有酸素運動時間)・食費をグラフ表示(表示期間は直近7日/30日/90日から選択。既定は7日) - Gemini APIによるAIレシピ生成(食材入力 → レシピ提案、生成結果はキャッシュ)。生成したレシピの材料は「今日」ページの買い物メモへワンタップで追記可能。レシピ履歴は開閉式のアコーディオンで一覧し、削除も可能 - 食べたものの自由記述からAIがカロリー・PFCを推定(食事記録の入力補助) -- 「前回と同じ内容」「よく使うテンプレート/キーワード」によるクイック入力、CSVファイルからのログ一括インポート +- 「前回と同じ内容」「よく使うテンプレート/キーワード」によるクイック入力、CSVファイルからのログ一括インポート(登録済みと内容が同一の行は二重取り込み防止のため自動でスキップ) - 日本語/英語の表示切り替え(i18n、ユーザーごとにDB永続化)。新規ユーザーの初期表示言語はブラウザの`Accept-Language`から判定する(ログイン画面自体は常に英語表示) - Google OAuth(OIDC、`st.login()`)によるマルチユーザーWebアプリ(ユーザーごとにデータを分離) - Health Score(独自指標、医療診断目的ではない)とRule-basedによる改善提案(Recommendation Engine)をバックエンドに実装済み(現在のUIには非表示。[既知の制限事項](#既知の制限事項)参照) @@ -113,6 +113,11 @@ cp .env.test.example .env.test (`.env.test`が無ければ従来通り`.env`のDATABASE_URLがテストにも 使われる。CI等はこの既定動作を利用する)。 +Claude Codeで開発する場合は、`.claude/settings.json`のPreToolUse hook +([.claude/hooks/guard_pytest_db.py](.claude/hooks/guard_pytest_db.py))が、 +`.env.test`が無い状態でのpytest実行を(`DATABASE_URL`をlocalhostへ +上書きしている場合を除き)ブロックする。 + ### 4. アプリの起動 ```bash @@ -122,19 +127,26 @@ uv run streamlit run app/streamlit_app.py ## テスト ```bash -# Unit Test(外部サービス不要) -uv run pytest tests/unit - -# Integration Test(要DATABASE_URL。未設定の場合は自動的にスキップされる) -uv run pytest tests/integration +# Lint / Format / 型チェック / i18nの重複キー / Unit Testを一括実行 +# (DATABASE_URLを到達不能なlocalhostへ差し替え、DBを破壊する +# test_migrations.pyを除外して実行するため、.env.test無しでも安全) +.claude/skills/check/check.sh -# 全体(Lint / Format / 型チェック / テスト) -uv run ruff check . -uv run ruff format --check . -uv run mypy src +# Migration Test・Integration Testを含む全体(要.env.test。3.5節参照) uv run pytest ``` +`tests/unit/`にもDBを使う`test_migrations.py`が含まれるため、`.env.test`が +無い状態で`uv run pytest tests/unit`を実行すると`.env`のDBが初期化される。 +ローカルでは上の`check.sh`(Claude Codeでは`/check`スキル)を使う。 + +本番DBの状態(ログ件数・内容が同一の重複レコード・最終記録日など)は、 +読み取り専用で点検できる(Claude Codeでは`/db-health`スキル)。 + +```bash +uv run python .claude/skills/db-health/db_health.py +``` + CI(GitHub Actions)はPush・Pull Requestごとに上記一式を実行する。CIでは使い捨てのPostgreSQL 16サービスコンテナを起動して`DATABASE_URL`をそこへ向け、`pytest`の前に`alembic upgrade head`を実行するため、Migration Test・Integration Testも含めて実行される([.github/workflows/ci.yml](.github/workflows/ci.yml))。 ## ML Pipeline @@ -168,6 +180,7 @@ uv run python -m health_intelligence.ml.run_weight_pipeline - **Health Score / Recommendation Engine**: `RecommendationService`としてバックエンドには実装済みだが、Dashboardを週間グラフ中心の構成へ変更した際にUI表示を外しており、現在どのページからも呼び出されていない - **Recipe Cache**: プロセスメモリ上の実装。アプリ再起動やStreamlit Community Cloudのスリープ復帰で消える([ai/recipe_cache.py](src/health_intelligence/ai/recipe_cache.py)) +- **読み取りキャッシュ**: リモートDB(Neon)の往復待ちを減らすため、各Serviceの読み取り結果をプロセス内で最大10分キャッシュする([app/services.py](app/services.py))。アプリ経由の書き込みでは即座に破棄されるが、SQL等でDBを直接変更した場合は、アプリを再起動するまで(最長10分)画面に反映されない - **HealthLogのフィールド構成**: 汎用的な体調記録の受け皿として、総合スコア(`condition_score`)・体調5軸(朝/夜/メンタル/疲労/ストレス)・`symptoms`・`memo`を持つ。実運用しながら見直しを重ねてきた経緯があり、今後もフィールド構成が変わる前提 - **ML Pipeline**: 実データが60日分・欠損率30%未満に達するまでは、Rule-basedのみで動作する(意図した挙動)。対象領域は現状Weightのみ(Nutrition/Sleep/Workoutへの横展開は未着手) - **運動記録フォーム**: 同じ種目名・カテゴリの入力行をまとめて1種目・複数セットとして保存する設計のため、同じ種目を1日に複数回(例: 午前と夕方で2回)行った場合を区別できない @@ -188,8 +201,9 @@ uv run python -m health_intelligence.ml.run_weight_pipeline │ ├── ml/ ML Pipeline(Dataset/評価/LightGBM/MLflow) │ └── database/ SQLAlchemy ORM・Alembic Migration ├── tests/ -│ ├── unit/ 外部サービス不要のテスト +│ ├── unit/ Unit Test(test_migrations.pyのみ要DATABASE_URL) │ └── integration/ 要DATABASE_URL(CI/ローカルDBで実行) +├── .claude/ Claude Code用のhook(pytestのDB保護)・スキル(/check, /db-health) └── docs/ 要件定義・アーキテクチャ・DB設計 ``` diff --git a/README.md b/README.md index 29d510b..1977cd1 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,10 @@ See below for the detailed design (documents are in Japanese). - **"Today" page**: Complete one day's record in a single screen, in PDCA order — Plan → Do → Check → Act. Sleep, condition (5 axes), meals, workouts (session/exercise/set structure), study/PF-dev/work, and household (shopping memo/food expense) are all recorded here. - **Goal & Task management**: Attach tasks to long-term goals, select them daily in the "Today" page's Plan step, and track progress. Study/PF-dev/work tasks record quantity/duration/memo; diet-policy/exercise-goal/sleep-goal tasks are just selected, with the actual record still living in the existing domains (MealLog/WorkoutLog/SleepLog). - **Learning log** (exam study, portfolio development, research, career/product strategy — the input fields change per category). Recorded in the "Today" page's Do tab. -- **Dashboard** showing sleep/condition, meals, study/work time, workouts, and food expense as charts, with a selectable period (last 7 / 30 / 90 days; defaults to 7). +- **Dashboard** showing sleep/condition, meals, study/work time, workouts (max weight per strength exercise over time, cardio time by exercise), and food expense as charts, with a selectable period (last 7 / 30 / 90 days; defaults to 7). - **AI recipe generation** via the Gemini API (enter ingredients → get a recipe suggestion, results are cached). Past recipes are listed as collapsible accordions and can be deleted. Ingredients from a generated recipe can be appended to the "Today" page's shopping memo with one tap. - AI estimates calories/PFC from a free-text description of what you ate (assists meal logging). -- Quick entry via "same as last time" / frequently-used templates & keywords, plus bulk log import from CSV files. +- Quick entry via "same as last time" / frequently-used templates & keywords, plus bulk log import from CSV files (rows identical to an existing log are skipped automatically to prevent double imports). - **i18n**: switch the UI between Japanese and English (persisted per user in the DB). A new user's initial language is detected from the browser's `Accept-Language`; the login screen itself is always shown in English. - Multi-user web app with Google OAuth (OIDC, via `st.login()`) login (data isolated per user). - **Health Score** (a proprietary metric, not intended for medical diagnosis) and rule-based improvement suggestions (Recommendation Engine) are implemented on the backend (currently hidden from the UI — see [Known limitations](#known-limitations)). @@ -115,6 +115,11 @@ with it at startup, so `pytest` never touches your everyday database (if `.env.test` is absent, the `DATABASE_URL` from `.env` is used for tests as before — CI relies on this default behavior). +When developing with Claude Code, a PreToolUse hook in +`.claude/settings.json` ([.claude/hooks/guard_pytest_db.py](.claude/hooks/guard_pytest_db.py)) +blocks pytest runs while `.env.test` is absent, unless the command +overrides `DATABASE_URL` to localhost. + ### 4. Run the app ```bash @@ -124,19 +129,27 @@ uv run streamlit run app/streamlit_app.py ## Testing ```bash -# Unit tests (no external services required) -uv run pytest tests/unit - -# Integration tests (require DATABASE_URL; auto-skipped if unset) -uv run pytest tests/integration +# Lint / format / type check / i18n duplicate keys / unit tests in one go +# (points DATABASE_URL at an unreachable localhost and excludes the +# DB-destroying test_migrations.py, so it is safe without .env.test) +.claude/skills/check/check.sh -# Everything (lint / format / type check / tests) -uv run ruff check . -uv run ruff format --check . -uv run mypy src +# Everything, including migration and integration tests (requires .env.test; see 3.5) uv run pytest ``` +`tests/unit/` also contains `test_migrations.py`, which uses the database, +so running `uv run pytest tests/unit` without `.env.test` resets the DB in +`.env`. Locally, use `check.sh` above (the `/check` skill in Claude Code). + +The production database can be inspected read-only (log counts, +content-duplicate records, latest record date, etc.; the `/db-health` +skill in Claude Code): + +```bash +uv run python .claude/skills/db-health/db_health.py +``` + CI (GitHub Actions) runs the full suite above on every push and pull request. CI starts a disposable PostgreSQL 16 service container, points `DATABASE_URL` at it, and runs `alembic upgrade head` before `pytest`, so migration tests and integration tests run there too ([.github/workflows/ci.yml](.github/workflows/ci.yml)). ## ML pipeline @@ -168,6 +181,7 @@ Because development proceeded on a compressed schedule, the following are intent - **Health Score / Recommendation Engine**: implemented on the backend as `RecommendationService`, but its UI display was removed when the Dashboard was redesigned around weekly charts, and it is currently not called from any page. - **Recipe Cache**: an in-process-memory implementation. It is lost on app restart or when Streamlit Community Cloud wakes from sleep ([ai/recipe_cache.py](src/health_intelligence/ai/recipe_cache.py)). +- **Read cache**: to cut round trips to the remote DB (Neon), each service's read results are cached in-process for up to 10 minutes ([app/services.py](app/services.py)). Writes made through the app invalidate it immediately, but changes made directly in the DB (e.g. via SQL) do not show up until the app restarts (up to 10 minutes). - **HealthLog field set**: as a catch-all for general condition tracking, it holds an overall score (`condition_score`), the 5-axis condition (morning/evening/mental/fatigue/stress), `symptoms`, and `memo`. This field set has already been revised once based on real-world use, and is expected to keep evolving. - **ML pipeline**: runs rule-based only until real data reaches 60 days with under 30% missing-value rate (intended behavior). Currently scoped to Weight only (extending to Nutrition/Sleep/Workout has not started). - **Workout log form**: rows with the same exercise name/category are grouped and saved as one exercise with multiple sets, so performing the same exercise more than once in a day (e.g., morning and evening) cannot be distinguished. @@ -188,8 +202,9 @@ Because development proceeded on a compressed schedule, the following are intent │ ├── ml/ ML pipeline (dataset/evaluation/LightGBM/MLflow) │ └── database/ SQLAlchemy ORM & Alembic migrations ├── tests/ -│ ├── unit/ Tests requiring no external services +│ ├── unit/ Unit tests (only test_migrations.py needs DATABASE_URL) │ └── integration/ Requires DATABASE_URL (run in CI/local DB) +├── .claude/ Claude Code hook (pytest DB guard) & skills (/check, /db-health) └── docs/ Requirements, architecture, DB design ``` diff --git a/docs/architecture.md b/docs/architecture.md index b8be80e..9f2d16a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -281,6 +281,15 @@ Database接続情報は環境変数またはStreamlit Secretsから取得する( 秘密情報(`DATABASE_URL`、`GEMINI_API_KEY` 等)はGit Repositoryへコミットしない。 +### 7.4 リモートDB前提の性能設計 + +DBはリモート(Neon、アプリ実行環境からの往復は約110ms)のため、1回のService呼び出し(接続確認 + BEGIN + クエリ + ROLLBACK)に約360msかかる。一方Streamlitはウィジェット操作のたびにページ全体を再実行するため、DB往復の回数そのものを減らすことを性能設計の中心に置く。 + +* **読み取りキャッシュ**(`app/services.py`): 各Serviceを`_CachedService`で包み、読み取り系メソッド(`list_`/`get_`/`compute_`で始まるもの)の結果を引数ごとにプロセス内でキャッシュする(TTL 10分)。書き込み系メソッドが呼ばれたら、そのServiceと、同じテーブルを読む関連Service(`_DEPENDENTS`。例: 食事/睡眠/体重/運動 → `RecommendationService`、Goal/Task/DailyJournalは相互)のキャッシュを破棄する。読み込み中に書き込みがあった場合は古い値を保存しない(世代番号で判定)。アプリを経由しないDB変更はTTL経過まで反映されない。 +* **並列プリフェッチ**(`prefetch()`): ページ冒頭の互いに独立した読み取りをスレッドプールで並列実行し、キャッシュが空の初回表示・書き込み直後の再描画でDB往復が直列に積み上がるのを防ぐ。ワーカースレッドには呼び出し元の`ScriptRunContext`を引き継ぐ。 +* **一括書き込み**: CSVインポートは`record_*_logs(list)`で全件を1トランザクション・1回のcommitで保存する(1件ずつcommitすると件数×DB往復になる)。 +* **N+1の回避**: 一覧取得で関連データを1件ずつ引かない(運動ログの種目・セットは`selectinload`、ダッシュボードのTask実績は期間一括取得、レシピの材料名・Goal進捗のTask実績は`IN`句で一括取得)。 + --- ## 8. user_id Architecture @@ -609,6 +618,12 @@ Application → E2E Test 重要なテスト対象:user_id分離、Repository境界、Transaction境界、Unit of Work、Rollback、AI Retry/Timeout/Validation、ML / Rule-based切り替え、Fallback、Authentication、Session State。 +**テスト用DBの保護**: `tests/unit/test_migrations.py`は`DATABASE_URL`のDBに対して全テーブルのdrop/再作成を行い、`tests/integration/`も実データを書き込む。日常用DBを巻き込まないよう、以下の多層防御を置く。 + +* `.env.test`が存在すれば、`tests/conftest.py`が`DATABASE_URL`をテスト専用DBへ上書きする +* ローカルの品質チェックは`.claude/skills/check/check.sh`(Claude Codeの`/check`スキル)で行う。`DATABASE_URL`を到達不能なlocalhostへ差し替え、`test_migrations.py`を除外して実行する +* Claude CodeのPreToolUse hook(`.claude/hooks/guard_pytest_db.py`)が、`.env.test`が無い状態でのpytest実行を(`DATABASE_URL`をlocalhostへ上書きしている場合を除き)ブロックする + --- ## 19. Configuration & Logging @@ -704,12 +719,19 @@ Python-Smart-Health-Intelligence-Platform/ │ ├── streamlit_app.py # st.navigation()によるルーター │ ├── auth_guard.py # 認証ガード・言語切り替えUI │ ├── i18n.py # 6.6節 -│ ├── services.py # DIコンテナ(Service/Repository/UoWの組み立て) +│ ├── services.py # DIコンテナ(Service/UoWの組み立て)・読み取りキャッシュ・prefetch(7.4節) │ ├── pages/ # login / dashboard / today / goals / csv_import / recipe │ └── components/ │ ├── tests/ ├── data/ +├── .claude/ +│ ├── settings.json # Claude Code設定(PreToolUse hookの登録) +│ ├── hooks/ +│ │ └── guard_pytest_db.py # .env.test無しのpytest実行をブロック(18章) +│ └── skills/ +│ ├── check/ # /check: lint・型・i18n・Unit Testの一括実行 +│ └── db-health/ # /db-health: 本番DBの読み取り専用点検 ├── docs/ │ ├── architecture.md │ └── requirements.md # ER図は14.1節に統合 diff --git a/docs/requirements.md b/docs/requirements.md index 064e7b4..488f408 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -1046,6 +1046,16 @@ CIではPostgreSQLのサービスコンテナを起動して`DATABASE_URL`をそ * AI障害時のFallbackを用意する * Loggingを実装する +## 17.6 性能 + +DBはリモート(Neon)であり、1回のDB往復に100ms前後かかる前提で設計する。 + +* Streamlitの再実行(ウィジェット操作)ごとに全データを取得し直さないよう、読み取り結果をキャッシュする。アプリ経由の書き込み後は、次の表示で必ず最新の内容を反映する +* 一覧表示で関連データを1件ずつ取得しない(N+1クエリを作らない) +* 複数件の一括登録(CSVインポート)は1トランザクションで行う + +詳細はarchitecture.md 7.4節を参照。 + --- # 18. Streamlit Dashboard @@ -1058,8 +1068,8 @@ CIではPostgreSQLのサービスコンテナを起動して`DATABASE_URL`をそ * Dashboard(ダッシュボード) * 今日(1日分のP/D/C/Aを1画面で完結させるカード型UI。睡眠・体調・食事・運動・学習/PF開発/仕事・家計の実績入力と、長期目標管理画面で登録したTaskの選択をここで行う。詳細は4.4節・4.5節参照) * 長期目標(Goal/Taskの一覧・追加・編集・ステータス変更・アーカイブ) -* CSVインポート(食事・運動・睡眠・体重・体調・学習ログの一括登録) -* AI Recipe Generator(レシピ) +* CSVインポート(食事・運動・睡眠・体重・体調・学習ログの一括登録。登録済みのログと内容が完全に一致する行は、同じCSVの二重取り込みとみなして取り込まない。有効な行は1トランザクションでまとめて保存する) +* AIレシピ(AI Recipe Generator) サイドバーから表示言語(日本語/英語)を切り替えられる(4.6節)。 @@ -1068,9 +1078,11 @@ Dashboardでは、選択した表示期間(直近7日/30日/90日。既定は7 * 睡眠時間・体調スコア(総合/朝/夜/メンタル/疲労/ストレス) * カロリー・PFC * 学習時間・作業時間(学習ログ + Task実績) -* 有酸素運動時間 +* 運動: 筋トレ種目別の最大重量の推移(表示期間内の記録日数が多い上位5種目。自重種目は除く)、有酸素運動時間(種目別の積み上げ) * 食費合計 +カロリー・PFC・有酸素運動時間などY軸の上限を目安値で固定しているグラフは、上限を超える日がある場合、その値まで上限を自動で広げる(棒が描画領域からはみ出して見えなくなるのを防ぐため)。 + > Health ScoreおよびRule-based Recommendationは8章・9章の通りバックエンドでは実装済みだが、現在のUIでは表示していない(過去にダッシュボードへ表示していたが、週間グラフ中心の構成へ変更した際に外した)。再度UIへ統合する場合は別途設計する。 ---