forked from ChelseaKR/queer-the-stacks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathview.py
More file actions
371 lines (338 loc) · 13.9 KB
/
Copy pathview.py
File metadata and controls
371 lines (338 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
"""Assemble the dashboard view from ingest → stats → Wrapped → recommender.
One place builds the whole picture so the FastAPI server, the static a11y build,
and the CLI all render identical content. The pure :func:`build_view` takes
already-ingested data; :func:`demo_view` walks the full offline demo pipeline.
"""
from __future__ import annotations
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from ingest.models import Book, DailyActivity, ReadingState, Recommendation
from ingest.store import CatalogPoolStatus
from ingest.unify import currently_reading, finished
from recommender.eval import PopCandidate
from recommender.explain import NearMiss, near_misses
from recommender.hybrid import recommend_hybrid
from recommender.lists import CuratedList
from recommender.model import build_taste_profile
from app.diversity import DEFAULT_DIMENSIONS, DiversityReport, compute_diversity, load_lens_config
from app.forecast import Forecast, forecast_book
from app.goals import Goal, compute_goals
from app.shelf import SeriesNext, series_continuations, to_read
from app.stats import ReadingStats, compute_stats
from app.wrapped import Wrapped, compute_wrapped
# How old the persisted refresh stamp can get before the dashboard calls it
# stale. A module constant (not a magic number inline) so tests can exercise
# the boundary without patching.
STALE_AFTER_SECONDS = 7 * 24 * 60 * 60 # 7 days
@dataclass(frozen=True)
class BookForecast:
"""A currently-reading book paired with its time-to-finish forecast."""
title: str
authors: tuple[str, ...]
forecast: Forecast
@dataclass(frozen=True)
class DashboardView:
"""Everything the dashboard renders, assembled once."""
currently_reading: tuple[ReadingState, ...]
finished: tuple[ReadingState, ...]
stats: ReadingStats
wrapped: Wrapped
recommendations: tuple[Recommendation, ...]
near_misses: tuple[NearMiss, ...] = ()
forecasts: tuple[BookForecast, ...] = ()
series_next: tuple[SeriesNext, ...] = ()
to_read: tuple[ReadingState, ...] = ()
library: tuple[ReadingState, ...] = ()
goals: tuple[Goal, ...] = ()
diversity: Optional[DiversityReport] = None
authored_lists: tuple[CuratedList, ...] = ()
user: str = "demo"
refreshed_at: Optional[int] = None
stale: bool = False
catalog_status: CatalogPoolStatus = CatalogPoolStatus()
#: The library/stats/Wrapped below came from the built-in demo world, not
#: the reader's libraries. Carried so every surface can say so: a fixture
#: shelf rendered without this flag is indistinguishable from a real one.
fixture_states: bool = False
#: The recommendations and near-misses came from demo candidates. Tracked
#: separately from :attr:`fixture_states` because the two mix: demo mode
#: reads the real store for states while still substituting fixture
#: candidates, so a page can be honest about one and lying about the other.
fixture_candidates: bool = False
#: :func:`app.shelf.to_read` actually had a taste signal to rank by. The
#: shelf is documented as "best taste-fit first"; with an empty taste profile
#: every book scores 0 and the result collapses to ``sorted(unread, key=title)``.
#: Surfaces describe the order they got, not the one the function is named for.
to_read_taste_ranked: bool = False
browse_query: str = ""
browse_theme: str = ""
browse_author: str = ""
browse_series: str = ""
browse_status: str = ""
def _infer_today_and_year(
states: list[ReadingState], daily_activity: list[DailyActivity]
) -> tuple[int, Optional[int]]:
"""Derive a deterministic 'today' + Wrapped year from the data itself.
The year is ``None`` when there is no activity to infer one from. It used to
be 1970 — the epoch leaking out of an ordinal arithmetic fallback — which
reached five rendered places on a Calibre-only library: "Reading Wrapped
1970", "0.0 hours read in 1970", "Standout reads of 1970", "Books in 1970:
0 / 52 — 0%", and a ``/share`` card composing "My 1970 in books" for public
posting. None of those are readings; they are one missing source, formatted.
"""
import datetime
today_ordinal = max((d.day_ordinal for d in daily_activity), default=0)
if not today_ordinal:
return 0, None
epoch = datetime.date(1970, 1, 1).toordinal()
return today_ordinal, datetime.date.fromordinal(epoch + today_ordinal).year
def _remaining_pages(state: ReadingState) -> int:
"""Pages left in a book from its reading stat; 0 when it can't be known.
``forecast_book`` treats a non-positive remaining count as unestimable, so a
book with no page stat honestly reports "not enough recent reading to
estimate" rather than a guessed range.
"""
stat = state.stat
if stat is None or stat.total_pages <= 0:
return 0
return max(0, stat.total_pages - stat.pages_read)
def build_view(
states: list[ReadingState],
daily_activity: list[DailyActivity],
candidates: tuple[object, ...],
*,
lists: tuple[CuratedList, ...] = (),
authored_lists: tuple[CuratedList, ...] = (),
user: str = "demo",
aperture_strength: float = 0.0,
use_embeddings: bool = False,
dnf_signals: bool = False,
goal_books: int = 0,
goal_pages: int = 0,
goal_hours: int = 0,
goal_streak_days: int = 0,
lens_dimensions: tuple[tuple[str, frozenset[str]], ...] = DEFAULT_DIMENSIONS,
lens_source: str = "built-in defaults",
lens_warning: Optional[str] = None,
lens_sensitive_names: Optional[frozenset[str]] = None,
hide_sensitive_descriptors: bool = False,
refreshed_at: Optional[int] = None,
now: Optional[int] = None,
catalog_status: Optional[CatalogPoolStatus] = None,
fixture_states: bool = False,
fixture_candidates: bool = False,
) -> DashboardView:
"""Build the dashboard view from unified state + candidates (pure).
``refreshed_at`` is the persisted store stamp (epoch seconds), if any;
``now`` defaults to the wall clock but is overridable so staleness is
testable without patching time. Staleness is silent (``False``) when
there is no stamp at all — "never refreshed" is its own, distinct state,
rendered as text rather than the staleness banner.
"""
today_ordinal, year = _infer_today_and_year(states, daily_activity)
stats = compute_stats(states, daily_activity, today_ordinal)
wrapped = compute_wrapped(states, daily_activity, year)
goals = compute_goals(
stats,
wrapped,
books_target=goal_books,
pages_target=goal_pages,
hours_target=goal_hours,
streak_target=goal_streak_days,
)
diversity = compute_diversity(
states,
lens_dimensions,
lens_source=lens_source,
lens_warning=lens_warning,
hide_sensitive=hide_sensitive_descriptors,
sensitive_lens_names=lens_sensitive_names,
)
candidate_books = tuple(
candidate if isinstance(candidate, Book) else candidate.book # type: ignore[attr-defined]
for candidate in candidates
)
recs = recommend_hybrid(
states,
candidate_books,
lists=lists,
k=10,
aperture_strength=aperture_strength,
use_embeddings=use_embeddings,
dnf_signals=dnf_signals,
)
misses = near_misses(
states,
candidate_books,
lists,
frozenset(r.book.book_id for r in recs),
)
# Built once and passed in, so the shelf's ranking and the claim the page
# makes about that ranking are derived from the same profile.
taste = build_taste_profile(states, dnf_signals=dnf_signals)
library = sorted(states, key=lambda s: (s.title.lower(), s.authors))
reading_now = tuple(currently_reading(states))
forecasts = tuple(
BookForecast(
title=s.title,
authors=s.authors,
forecast=forecast_book(_remaining_pages(s), daily_activity),
)
for s in reading_now
)
stale = False
if refreshed_at is not None:
current = int(time.time()) if now is None else now
stale = (current - refreshed_at) > STALE_AFTER_SECONDS
return DashboardView(
currently_reading=reading_now,
finished=tuple(finished(states)),
stats=stats,
wrapped=wrapped,
recommendations=tuple(recs),
near_misses=tuple(misses),
forecasts=forecasts,
series_next=tuple(series_continuations(states)),
to_read=tuple(to_read(states, taste)),
to_read_taste_ranked=bool(taste.theme_weights),
library=tuple(library),
goals=goals,
diversity=diversity,
authored_lists=authored_lists,
user=user,
refreshed_at=refreshed_at,
stale=stale,
catalog_status=catalog_status or CatalogPoolStatus(),
fixture_states=fixture_states,
fixture_candidates=fixture_candidates,
)
def render_view(view: DashboardView) -> str:
"""Render a :class:`DashboardView` to HTML (one place, used everywhere)."""
from app.render import render_dashboard
return render_dashboard(
view.currently_reading,
view.finished,
view.stats,
view.wrapped,
view.recommendations,
near_misses=view.near_misses,
forecasts=view.forecasts,
series_next=view.series_next,
to_read=view.to_read,
library=view.library,
goals=view.goals,
diversity=view.diversity,
authored_lists=view.authored_lists,
user=view.user,
refreshed_at=view.refreshed_at,
stale=view.stale,
catalog_status=view.catalog_status,
fixture_states=view.fixture_states,
fixture_candidates=view.fixture_candidates,
to_read_taste_ranked=view.to_read_taste_ranked,
browse_query=view.browse_query,
browse_theme=view.browse_theme,
browse_author=view.browse_author,
browse_series=view.browse_series,
browse_status=view.browse_status,
)
def view_from_store(
store: object,
*,
user: str = "you",
aperture_strength: float = 0.0,
use_embeddings: bool = False,
dnf_signals: bool = False,
goal_books: int = 0,
goal_pages: int = 0,
goal_hours: int = 0,
goal_streak_days: int = 0,
lens_config: Optional[Path] = None,
hide_sensitive_descriptors: bool = False,
authored_lists: tuple[CuratedList, ...] = (),
demo_mode: bool = False,
) -> DashboardView:
"""Build the dashboard view from persisted derived state in the store.
Recommendations draw on the last successfully persisted public catalog pool.
Demo candidates are used only for an explicitly requested demo-mode fallback
(primarily backward compatibility with stores created before pool persistence).
``lens_config``, if given, points at a validated ``[[lenses]]`` TOML file
(see :func:`app.diversity.load_lens_config`) that overrides the built-in
diversity-lens grouping; any read/parse/validation failure degrades to the
built-in defaults with a visible warning surfaced in the diversity section,
never a blank one.
"""
from ingest.demo import demo_candidates
from ingest.store import ORIGIN_DEMO
from recommender.lists import DEMO_LISTS
states = store.load_states() # type: ignore[attr-defined]
activity = store.load_daily_activity() # type: ignore[attr-defined]
candidates = store.load_catalog_candidates() # type: ignore[attr-defined]
fixture_candidates = False
if not candidates and demo_mode:
candidates = tuple(candidate.book for candidate in demo_candidates())
fixture_candidates = True
lists = DEMO_LISTS if demo_mode else ()
# Demo mode does not swap out the store: `make dev` sets STACKS_DEMO=1
# without redirecting STACKS_DATA_DIR, so the states here are frequently a
# real ingest while the candidates above are fixtures. Ask the store what
# wrote it rather than inferring the answer from the mode flag.
fixture_states = store.state_origin() == ORIGIN_DEMO # type: ignore[attr-defined]
lenses = load_lens_config(lens_config)
refreshed_at = store.refreshed_at() # type: ignore[attr-defined]
return build_view(
states,
activity,
candidates,
lists=lists,
authored_lists=authored_lists,
user=user,
aperture_strength=aperture_strength,
use_embeddings=use_embeddings,
dnf_signals=dnf_signals,
goal_books=goal_books,
goal_pages=goal_pages,
goal_hours=goal_hours,
goal_streak_days=goal_streak_days,
lens_dimensions=lenses.dimensions,
lens_source=lenses.source,
lens_warning=lenses.warning,
lens_sensitive_names=lenses.sensitive_lens_names,
hide_sensitive_descriptors=hide_sensitive_descriptors,
refreshed_at=refreshed_at,
catalog_status=store.catalog_pool_status(), # type: ignore[attr-defined]
fixture_states=fixture_states,
fixture_candidates=fixture_candidates,
)
def demo_view(workdir: Path) -> DashboardView:
"""Walk the full offline demo pipeline and return a ready-to-render view."""
from ingest.calibre import load_library
from ingest.demo import (
DEMO_RETRIEVED_AT,
DEMO_USER,
build_demo_dbs,
demo_candidates,
demo_kosync,
)
from ingest.koreader import load_daily_activity, load_stats
from ingest.unify import unify
from recommender.lists import DEMO_LISTS
workdir = Path(workdir)
metadata_db, statistics_db = build_demo_dbs(workdir)
snap = workdir / "snapshots"
books = load_library(metadata_db, snap, retrieved_at=DEMO_RETRIEVED_AT)
stats = load_stats(statistics_db, snap)
activity = load_daily_activity(statistics_db, snap)
states = unify(books, stats, demo_kosync())
candidates: tuple[PopCandidate, ...] = demo_candidates()
return build_view(
states,
activity,
candidates,
lists=DEMO_LISTS,
user=DEMO_USER,
fixture_states=True,
fixture_candidates=True,
)