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'' f'{rank}' ) inner_width = CHART_WIDTH - CHART_LEFT - CHART_RIGHT x_step = inner_width / max(len(page_dates) - 1, 1) date_labels = [] for index, page_date in enumerate(page_dates): x_value = CHART_LEFT + (index * x_step) date_labels.append(f'') date_labels.append(f'{html.escape(page_date)}') paths = [] for index, series in enumerate(series_list): values = series_values(series, page_dates) final_x = CHART_LEFT + ((len(page_dates) - 1) * x_step if page_dates else 0) final_y = rank_to_y(values[-1]) if values else rank_to_y(NOT_ON_LIST_RANK) color = LINE_COLORS[index % len(LINE_COLORS)] paths.append( f'' f'' ) return f''' {SVG_STYLE_BLOCK} {''.join(grid_lines)} {''.join(date_labels)} Position on NYT list Not on list {''.join(paths)} ''' def render_series_table(series_list: Sequence[NytSeries], show_amazon_column: bool) -> str: header_cells = ["Book", "NYT list", "Observed weeks", "Best rank"] if show_amazon_column: header_cells.extend(["Matched Amazon title", "Match score"]) rows = [] for series in series_list: cells = [ html.escape(series.title), html.escape(series.list_title), str(series.observed_weeks), str(series.best_rank), ] if show_amazon_column: cells.extend([ html.escape(series.amazon_title or "Not observed"), f"{series.amazon_match_score:.2f}" if series.amazon_match_score else "", ]) rows.append("" + "".join(f"{cell}" for cell in cells) + "") return ( "" + "".join(f"" for cell in header_cells) + "" + "".join(rows) + "
{html.escape(cell)}
" ) def render_section(title: str, description: str, series_list: Sequence[NytSeries], page_dates: Sequence[str], show_amazon_column: bool) -> str: if not series_list: return f"

{html.escape(title)}

{html.escape(description)}

No series available with the current inputs.

" return f'''

{html.escape(title)}

{html.escape(description)}

{len(series_list)} charted titles
{build_chart_svg(series_list, page_dates)} {render_series_table(series_list, show_amazon_column=show_amazon_column)}
''' def render_book_card(series: NytSeries, page_dates: Sequence[str], card_title: str, include_amazon_note: bool) -> str: values = series_values(series, page_dates) visible_dates = [page_date for page_date in page_dates if page_date in series.ranks_by_date] summary_bits = [ f"Observed weeks: {series.observed_weeks}", f"Best NYT rank: {series.best_rank}", f"List: {series.list_title}", ] if include_amazon_note and series.amazon_title: summary_bits.append(f"Amazon match: {series.amazon_title}") return f'''

{html.escape(card_title)}

{html.escape(' | '.join(summary_bits))}

{build_chart_svg([series], page_dates)}

Observed NYT page dates: {html.escape(', '.join(visible_dates) if visible_dates else 'None')}

{''.join(f'{html.escape(page_date)}: {value if value < NOT_ON_LIST_RANK else "not on list"}' for page_date, value in zip(page_dates, values))}
''' def render_book_card_section(title: str, description: str, series_list: Sequence[NytSeries], page_dates: Sequence[str], include_amazon_note: bool) -> str: if not series_list: return "" cards = [] for series in series_list: cards.append( render_book_card( series, page_dates, card_title=f"How {series.title} ranked over time", include_amazon_note=include_amazon_note, ) ) return f'''

{html.escape(title)}

{html.escape(description)}

{''.join(cards)}
''' def build_html( matched: Sequence[NytSeries], unmatched: Sequence[NytSeries], page_dates: Sequence[str], top_matched: int, top_unmatched: int, include_matched: bool = True, include_unmatched: bool = True, include_book_cards: bool = True, page_title: str = "NYT vs Amazon Comparison Charts", lead_text: str = "", ) -> str: matched_series = list(matched)[:top_matched] if include_matched else [] unmatched_series = list(unmatched)[:top_unmatched] if include_unmatched else [] lead = lead_text or ( "These comparison charts use the NYT public archive and weekly snapshots you already collected, then split the trajectories into two groups: books also observed in the tracked Amazon bestseller categories and books not observed there. A missing NYT week is shown in the gray band at the bottom as ‘Not on list,’ matching the visual logic of the reference chart." ) return f''' {html.escape(page_title)}

{html.escape(page_title)}

{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 ''}
''' def sibling_output_path(output_path: Path, suffix: str) -> Path: return output_path.with_name(f"{output_path.stem}_{suffix}{output_path.suffix}") def sibling_output_dir(output_path: Path, suffix: str) -> Path: return output_path.with_name(f"{output_path.stem}_{suffix}") def write_html(path: Path, content: str) -> Path: ensure_directory(path.parent) path.write_text(content, encoding="utf-8") return path def write_text(path: Path, content: str) -> Path: ensure_directory(path.parent) path.write_text(content, encoding="utf-8") return path def slugify(value: str) -> str: slug = normalize_text(value).replace(" ", "_") return slug[:80] or "untitled" def choose_paper_series(series_list: Sequence[NytSeries], explicit_titles: Sequence[str], count: int) -> List[NytSeries]: if explicit_titles: desired = {normalize_text(title) for title in explicit_titles} selected = [series for series in series_list if normalize_text(series.title) in desired] return selected[:count] if count > 0 else selected return list(series_list)[:count] def export_svg_figures( figure_dir: Path, matched_series: Sequence[NytSeries], unmatched_series: Sequence[NytSeries], page_dates: Sequence[str], ) -> List[Path]: svg_paths: List[Path] = [] panels_dir = figure_dir / "panels" matched_books_dir = figure_dir / "matched_books" unmatched_books_dir = figure_dir / "unmatched_books" panel_specs = [ (panels_dir / "matched_panel.svg", matched_series), (panels_dir / "unmatched_panel.svg", unmatched_series), ] for path, series_list in panel_specs: if not series_list: continue svg_paths.append(write_text(path, build_chart_svg(series_list, page_dates))) for index, series in enumerate(matched_series, start=1): path = matched_books_dir / f"{index:02d}_{slugify(series.title)}.svg" svg_paths.append(write_text(path, build_chart_svg([series], page_dates))) for index, series in enumerate(unmatched_series, start=1): path = unmatched_books_dir / f"{index:02d}_{slugify(series.title)}.svg" svg_paths.append(write_text(path, build_chart_svg([series], page_dates))) return svg_paths def export_paper_ready_figures( figure_dir: Path, paper_series: Sequence[NytSeries], page_dates: Sequence[str], ) -> List[Path]: svg_paths: List[Path] = [] panels_dir = figure_dir / "panels" matched_books_dir = figure_dir / "matched_books" if paper_series: svg_paths.append(write_text(panels_dir / "paper_matched_panel.svg", build_chart_svg(paper_series, page_dates))) for index, series in enumerate(paper_series, start=1): path = matched_books_dir / f"{index:02d}_{slugify(series.title)}.svg" svg_paths.append(write_text(path, build_chart_svg([series], page_dates))) return svg_paths def export_png_figures(svg_paths: Sequence[Path]) -> List[Path]: from playwright.sync_api import sync_playwright png_paths: List[Path] = [] with sync_playwright() as playwright: browser = playwright.chromium.launch() page = browser.new_page(viewport={"width": CHART_WIDTH + 32, "height": CHART_HEIGHT + 32}, device_scale_factor=2) for svg_path in svg_paths: page.goto(svg_path.resolve().as_uri()) page.locator("svg").first.screenshot(path=str(svg_path.with_suffix(".png"))) png_paths.append(svg_path.with_suffix(".png")) browser.close() return png_paths def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Render NYT-style comparison charts for NYT titles with and without Amazon-category overlap.") parser.add_argument( "--nyt-inputs", nargs="+", default=[ "validation_data/nyt_public_hardcover_nonfiction_archive_2026Q2.csv", "validation_data/nyt_public_weekly_history.csv", ], help="NYT public history CSV inputs.", ) parser.add_argument("--amazon-input", default="validation_data/amazon_public_history.csv", help="Amazon public history CSV input.") parser.add_argument("--output", default="validation_results/nyt_amazon_comparison_charts.html", help="Output HTML path.") parser.add_argument("--matched-output", default="", help="Optional matched-only HTML path. Defaults beside --output.") parser.add_argument("--unmatched-output", default="", help="Optional unmatched-only HTML path. Defaults beside --output.") parser.add_argument("--figures-dir", default="", help="Optional directory for standalone SVG and PNG chart exports. Defaults beside --output.") parser.add_argument("--paper-html-output", default="", help="Optional paper-ready matched-subset HTML path. Defaults beside --output.") parser.add_argument("--paper-figures-dir", default="", help="Optional paper-ready SVG and PNG figure directory. Defaults beside --output.") parser.add_argument("--paper-top-matched", type=int, default=6, help="Number of matched titles to include in the paper-ready subset export.") parser.add_argument("--paper-titles", nargs="*", default=[], help="Optional explicit matched NYT titles to use for the paper-ready subset export.") parser.add_argument("--top-matched", type=int, default=12, help="Number of matched NYT series to include.") parser.add_argument("--top-unmatched", type=int, default=12, help="Number of unmatched NYT series to include.") return parser.parse_args() def main() -> int: args = parse_args() nyt_series, page_dates = load_nyt_series(args.nyt_inputs) amazon_candidates = load_amazon_candidates(args.amazon_input) matched, unmatched = classify_series(nyt_series, amazon_candidates) output_path = Path(args.output) matched_output_path = Path(args.matched_output) if args.matched_output else sibling_output_path(output_path, "matched_only") unmatched_output_path = Path(args.unmatched_output) if args.unmatched_output else sibling_output_path(output_path, "unmatched_only") figures_dir = Path(args.figures_dir) if args.figures_dir else sibling_output_dir(output_path, "figures") paper_html_output_path = Path(args.paper_html_output) if args.paper_html_output else sibling_output_path(output_path, "paper_ready") paper_figures_dir = Path(args.paper_figures_dir) if args.paper_figures_dir else sibling_output_dir(output_path, "paper_ready_figures") matched_series = list(matched)[: args.top_matched] unmatched_series = list(unmatched)[: args.top_unmatched] paper_series = choose_paper_series(matched_series, args.paper_titles, args.paper_top_matched) content = build_html( matched_series, unmatched_series, page_dates, top_matched=args.top_matched, top_unmatched=args.top_unmatched, page_title="NYT Trajectories vs Amazon Presence", ) matched_content = build_html( matched_series, unmatched_series, page_dates, top_matched=args.top_matched, top_unmatched=args.top_unmatched, include_unmatched=False, page_title="NYT Titles Also Observed In Tracked Amazon Categories", lead_text="This page isolates the NYT titles that also appear in the tracked Amazon bestseller categories, shown first as a multi-line comparison and then as standalone per-book charts.", ) unmatched_content = build_html( matched_series, unmatched_series, page_dates, top_matched=args.top_matched, top_unmatched=args.top_unmatched, include_matched=False, page_title="NYT Titles Not Observed In Tracked Amazon Categories", lead_text="This page isolates NYT titles that were not observed in the currently tracked Amazon bestseller categories, shown as a multi-line comparison and standalone per-book charts.", ) paper_content = build_html( paper_series, [], page_dates, top_matched=len(paper_series), top_unmatched=0, include_unmatched=False, page_title="Paper-Ready Matched NYT Trajectories", lead_text="This page narrows the export to a smaller matched subset intended for paper figures and faster review.", ) write_html(output_path, content) write_html(matched_output_path, matched_content) write_html(unmatched_output_path, unmatched_content) write_html(paper_html_output_path, paper_content) svg_paths = export_svg_figures(figures_dir, matched_series, unmatched_series, page_dates) png_paths = export_png_figures(svg_paths) paper_svg_paths = export_paper_ready_figures(paper_figures_dir, paper_series, page_dates) paper_png_paths = export_png_figures(paper_svg_paths) print( f"Wrote NYT/Amazon comparison charts to {output_path}, {matched_output_path}, and {unmatched_output_path} " f"plus paper-ready HTML {paper_html_output_path}, {len(svg_paths)} SVG files and {len(png_paths)} PNG files in {figures_dir}, " f"and {len(paper_svg_paths)} paper-ready SVG files and {len(paper_png_paths)} paper-ready PNG files in {paper_figures_dir} " f"({len(matched)} matched series, {len(unmatched)} unmatched series, {len(page_dates)} page dates)" ) return 0 if __name__ == "__main__": raise SystemExit(main())