{html.escape(card_title)}
{html.escape(' | '.join(summary_bits))}
Observed NYT page dates: {html.escape(', '.join(visible_dates) if visible_dates else 'None')}
from __future__ import annotations
import argparse
import csv
import html
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Set, Tuple
from capt_validation_schema import ensure_directory
NOT_ON_LIST_RANK = 16
CHART_WIDTH = 1120
CHART_HEIGHT = 420
CHART_LEFT = 68
CHART_TOP = 28
CHART_RIGHT = 24
CHART_BOTTOM = 68
RANK_MAX = 15
LINE_COLORS = [
"#163a5f",
"#9d2c00",
"#46734b",
"#6b4f9f",
"#b26a00",
"#3d6f8e",
"#8d3d57",
"#557a95",
"#6a7f3a",
"#9a5d56",
]
SVG_STYLE_BLOCK = """
"""
@dataclass
class AmazonCandidate:
title: str
author: str
@dataclass
class NytSeries:
title: str
author: str
list_slug: str
list_title: str
ranks_by_date: Dict[str, int]
page_dates: Set[str]
best_rank: int
amazon_title: str = ""
amazon_match_score: float = 0.0
@property
def observed_weeks(self) -> int:
return len(self.page_dates)
@property
def label(self) -> str:
return f"{self.title} ({self.list_title})"
def read_rows(path: str | Path) -> List[Dict[str, str]]:
with Path(path).open("r", newline="", encoding="utf-8") as handle:
return list(csv.DictReader(handle))
def parse_int(value: str) -> Optional[int]:
text = str(value).strip().replace(",", "")
if not text:
return None
try:
return int(float(text))
except ValueError:
return None
def normalize_text(value: str) -> str:
text = str(value or "").lower().replace("&", " and ")
text = re.sub(r"\bby\b", " ", text)
text = re.sub(r"[^a-z0-9]+", " ", text)
return " ".join(text.split())
def title_variants(title: str) -> Set[str]:
normalized = normalize_text(title)
variants = {normalized}
for separator in (":", "(", "["):
head = title.split(separator, 1)[0]
normalized_head = normalize_text(head)
if len(normalized_head.split()) >= 2:
variants.add(normalized_head)
return {variant for variant in variants if variant}
def author_tokens(author: str) -> Set[str]:
normalized = normalize_text(author)
return {token for token in normalized.split() if len(token) >= 3 and token not in {"with", "and", "the"}}
def overlap_ratio(left: Set[str], right: Set[str]) -> float:
if not left or not right:
return 0.0
return len(left & right) / min(len(left), len(right))
def match_score(nyt_title: str, nyt_author: str, amazon_title: str, amazon_author: str) -> float:
nyt_variants = title_variants(nyt_title)
amazon_variants = title_variants(amazon_title)
if nyt_variants & amazon_variants:
return 1.0
nyt_full = max(nyt_variants, key=len, default="")
amazon_full = max(amazon_variants, key=len, default="")
if not nyt_full or not amazon_full:
return 0.0
sequence_ratio = similarity_ratio(nyt_full, amazon_full)
nyt_tokens = set(nyt_full.split())
amazon_tokens = set(amazon_full.split())
token_ratio = overlap_ratio(nyt_tokens, amazon_tokens)
author_overlap = bool(author_tokens(nyt_author) & author_tokens(amazon_author))
if nyt_full in amazon_full and len(nyt_tokens) >= 2:
return 0.94
if amazon_full in nyt_full and len(amazon_tokens) >= 2:
return 0.94
if token_ratio == 1.0 and sequence_ratio >= 0.7:
return 0.9
if author_overlap and sequence_ratio >= 0.72 and token_ratio >= 0.5:
return 0.84
if sequence_ratio >= 0.86 and token_ratio >= 0.6:
return 0.8
return 0.0
def similarity_ratio(left: str, right: str) -> float:
if not left or not right:
return 0.0
if left == right:
return 1.0
left_bigrams = {left[index:index + 2] for index in range(max(len(left) - 1, 1))}
right_bigrams = {right[index:index + 2] for index in range(max(len(right) - 1, 1))}
if not left_bigrams or not right_bigrams:
return 0.0
return (2 * len(left_bigrams & right_bigrams)) / (len(left_bigrams) + len(right_bigrams))
def load_nyt_series(paths: Sequence[str | Path]) -> Tuple[List[NytSeries], List[str]]:
dedupe_keys: Set[Tuple[str, str, str, str, str]] = set()
by_series: Dict[Tuple[str, str], NytSeries] = {}
all_dates: Set[str] = set()
for path in paths:
for row in read_rows(path):
page_date = str(row.get("page_date", "")).strip()
title = str(row.get("title", "")).strip()
list_slug = str(row.get("list_slug", "")).strip()
rank = parse_int(row.get("rank", ""))
if not page_date or not title or not list_slug or rank is None:
continue
dedupe_key = (
page_date,
list_slug,
str(row.get("isbn13", "")).strip(),
title,
str(rank),
)
if dedupe_key in dedupe_keys:
continue
dedupe_keys.add(dedupe_key)
all_dates.add(page_date)
series_key = (title, list_slug)
if series_key not in by_series:
by_series[series_key] = NytSeries(
title=title,
author=str(row.get("author", "")).strip(),
list_slug=list_slug,
list_title=str(row.get("list_title", list_slug)).strip() or list_slug,
ranks_by_date={},
page_dates=set(),
best_rank=rank,
)
series = by_series[series_key]
existing_rank = series.ranks_by_date.get(page_date)
if existing_rank is None or rank < existing_rank:
series.ranks_by_date[page_date] = rank
series.page_dates.add(page_date)
series.best_rank = min(series.best_rank, rank)
sorted_dates = sorted(all_dates)
sorted_series = sorted(by_series.values(), key=lambda item: (-item.observed_weeks, item.best_rank, item.title, item.list_slug))
return sorted_series, sorted_dates
def load_amazon_candidates(path: str | Path) -> List[AmazonCandidate]:
deduped: Dict[Tuple[str, str], AmazonCandidate] = {}
for row in read_rows(path):
title = str(row.get("title", "")).strip()
author = str(row.get("author", "")).strip()
if not title:
continue
key = (normalize_text(title), normalize_text(author))
deduped[key] = AmazonCandidate(title=title, author=author)
return list(deduped.values())
def classify_series(series_list: Sequence[NytSeries], amazon_candidates: Sequence[AmazonCandidate]) -> Tuple[List[NytSeries], List[NytSeries]]:
matched: List[NytSeries] = []
unmatched: List[NytSeries] = []
for series in series_list:
best_score = 0.0
best_candidate: Optional[AmazonCandidate] = None
for candidate in amazon_candidates:
score = match_score(series.title, series.author, candidate.title, candidate.author)
if score > best_score:
best_score = score
best_candidate = candidate
if best_candidate and best_score >= 0.8:
series.amazon_title = best_candidate.title
series.amazon_match_score = best_score
matched.append(series)
else:
unmatched.append(series)
return matched, unmatched
def series_values(series: NytSeries, page_dates: Sequence[str]) -> List[int]:
return [series.ranks_by_date.get(page_date, NOT_ON_LIST_RANK) for page_date in page_dates]
def rank_to_y(rank_value: int) -> float:
inner_height = CHART_HEIGHT - CHART_TOP - CHART_BOTTOM
y_min = CHART_TOP
y_max = CHART_HEIGHT - CHART_BOTTOM
return y_min + ((rank_value - 1) / (NOT_ON_LIST_RANK - 1)) * inner_height
def step_path(values: Sequence[int]) -> str:
if not values:
return ""
inner_width = CHART_WIDTH - CHART_LEFT - CHART_RIGHT
x_step = inner_width / max(len(values) - 1, 1)
commands: List[str] = []
last_x = CHART_LEFT
last_y = rank_to_y(values[0])
commands.append(f"M {last_x:.1f} {last_y:.1f}")
for index, value in enumerate(values[1:], start=1):
x_value = CHART_LEFT + (index * x_step)
current_y = rank_to_y(value)
commands.append(f"L {x_value:.1f} {last_y:.1f}")
commands.append(f"L {x_value:.1f} {current_y:.1f}")
last_x = x_value
last_y = current_y
return " ".join(commands)
def build_chart_svg(series_list: Sequence[NytSeries], page_dates: Sequence[str]) -> str:
chart_bottom_y = CHART_HEIGHT - CHART_BOTTOM
band_top = rank_to_y(RANK_MAX + 0.2)
grid_lines = []
for rank in range(1, RANK_MAX + 1):
y_value = rank_to_y(rank)
grid_lines.append(
f'
| {html.escape(cell)} | " for cell in header_cells) + "
|---|
{html.escape(description)}
No series available with the current inputs.
{html.escape(description)}
{html.escape(' | '.join(summary_bits))}
Observed NYT page dates: {html.escape(', '.join(visible_dates) if visible_dates else 'None')}
{html.escape(description)}
{html.escape(lead)}
{render_section( title="NYT books also observed in tracked Amazon categories", description="Matched conservatively by normalized title, subtitle trimming, and author-aware fuzzy checks. These are the clearest cross-surface overlaps in the current tracked categories.", series_list=matched_series, page_dates=page_dates, show_amazon_column=True, ) if include_matched else ''} {render_section( title="NYT books not observed in tracked Amazon categories", description="These books appeared in the NYT inputs but were not found in the Amazon public history you are currently tracking. This is category-limited absence, not global Amazon absence.", series_list=unmatched_series, page_dates=page_dates, show_amazon_column=False, ) if include_unmatched else ''} {render_book_card_section( title="Standalone per-book charts for NYT books also observed on Amazon", description="Each card isolates one title so you can inspect the exact weekly NYT trajectory without line overlap.", series_list=matched_series, page_dates=page_dates, include_amazon_note=True, ) if include_book_cards and include_matched else ''} {render_book_card_section( title="Standalone per-book charts for NYT books not observed in tracked Amazon categories", description="These cards show the same NYT trajectories for the unmatched group, one book at a time.", series_list=unmatched_series, page_dates=page_dates, include_amazon_note=False, ) if include_book_cards and include_unmatched else ''}