"""Read character descriptions from Google Sheets (live) or local Excel file.""" import pickle import os from dataclasses import dataclass, field from pathlib import Path from typing import List, Optional from loguru import logger import gspread import pandas as pd from google.auth.transport.requests import Request @dataclass class CharacterLook: """One 'look' (visual variation) for a character.""" character_name: str look_number: str # e.g. "Kid Mowgli - Look 3" chapter: str # e.g. "Chapter 3" description: str # Full look description text additional_details: str # Column E reference_links: str # Column F row_index: int # Original row index for tracing @dataclass class Character: """A character with one or more looks.""" name: str looks: List[CharacterLook] = field(default_factory=list) class SheetReader: """ Reads character data from either: - Google Sheets (live, via OAuth) — call read_characters() - Local Excel file (.xlsx) — call read_from_excel() """ def __init__( self, token_path: str = "token.pickle", credentials_path: str = "oauth_credentials.json", ): self.token_path = token_path self.credentials_path = credentials_path self._client: Optional[gspread.Client] = None # ─── Google Sheets (live) ──────────────────────────────────────────────── def _authenticate(self) -> gspread.Client: """Load OAuth token and build gspread client.""" creds = None if os.path.exists(self.token_path): with open(self.token_path, "rb") as f: creds = pickle.load(f) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: logger.info("Refreshing OAuth token...") creds.refresh(Request()) with open(self.token_path, "wb") as f: pickle.dump(creds, f) else: raise RuntimeError( "No valid OAuth token found. Run authenticate_oauth.py first." ) return gspread.authorize(creds) def read_characters(self, sheet_id: str, sheet_tab: str) -> List[Character]: """ Read characters from a live Google Sheet tab. Handles merged character name cells — character name only appears in the first row of that character's block; subsequent rows have it blank. """ if self._client is None: self._client = self._authenticate() logger.info(f"Opening sheet '{sheet_tab}' from spreadsheet {sheet_id}") spreadsheet = self._client.open_by_key(sheet_id) worksheet = spreadsheet.worksheet(sheet_tab) all_values = worksheet.get_all_values() return self._parse_rows(all_values, source=f"GSheets:{sheet_tab}") # ─── Local Excel file ──────────────────────────────────────────────────── def read_from_excel(self, excel_path: str, sheet_tab: str) -> List[Character]: """ Read characters from a local .xlsx file downloaded from Google Sheets. Args: excel_path: Path to the .xlsx file sheet_tab: Sheet/tab name to read (e.g. "Jungle Book") """ path = Path(excel_path) if not path.exists(): raise FileNotFoundError(f"Excel file not found: {excel_path}") logger.info(f"Reading local Excel: {path.name} -> tab '{sheet_tab}'") df = pd.read_excel( excel_path, sheet_name=sheet_tab, header=None, # We'll handle headers ourselves dtype=str, # Keep everything as strings ) # Replace NaN with empty string df = df.fillna("") # Convert to list of lists (same format as gspread) all_values = df.values.tolist() return self._parse_rows(all_values, source=f"Excel:{sheet_tab}") # ─── Shared parsing logic ──────────────────────────────────────────────── def _parse_rows(self, all_values: list, source: str) -> List[Character]: """ Parse rows into Character/CharacterLook objects. Handles: - Header row (row 0 skipped) - Merged character name cells (blank in subsequent rows) - Multi-line descriptions (already combined in cell text) - Variable-length rows """ if not all_values: logger.warning(f"No data in {source}") return [] # Detect and skip header row first_row = [str(v).strip() for v in all_values[0]] has_header = any( kw in " ".join(first_row).lower() for kw in ["character", "look", "chapter", "description"] ) data_rows = all_values[1:] if has_header else all_values logger.debug( f"Headers detected: {has_header} — parsing {len(data_rows)} data rows" ) characters: List[Character] = [] current_character: Optional[Character] = None current_char_name: str = "" for row_idx, row in enumerate(data_rows, start=2 if has_header else 1): # Normalize row: strip whitespace, pad to 6 columns row = [str(v).strip() for v in row] while len(row) < 6: row.append("") char_name_raw = row[0] look_number = row[1] chapter = row[2] description = row[3] additional = row[4] ref_links = row[5] # Skip completely empty rows if not any([char_name_raw, look_number, chapter, description]): continue # Resolve character name (merged cells show blank after first row) if char_name_raw: current_char_name = char_name_raw if not current_char_name: logger.warning(f"Row {row_idx}: no character name context, skipping") continue # Start a new character block when name changes if not current_character or current_character.name != current_char_name: current_character = Character(name=current_char_name) characters.append(current_character) logger.debug(f" Character: {current_char_name}") # Only add a look if there's a look identifier if look_number: look = CharacterLook( character_name=current_char_name, look_number=look_number, chapter=chapter, description=description, additional_details=additional, reference_links=ref_links, row_index=row_idx, ) current_character.looks.append(look) logger.debug(f" Look: {look_number} ({chapter})") total_looks = sum(len(c.looks) for c in characters) logger.info( f"Parsed {len(characters)} characters, {total_looks} looks from {source}" ) return characters def summary(self, characters: List[Character]) -> str: """Return a human-readable summary of parsed characters.""" lines = [f"{'Character':<30} {'Looks':>5} Look Names"] lines.append("-" * 90) for ch in characters: look_names = ", ".join(lk.look_number for lk in ch.looks) lines.append(f"{ch.name:<30} {len(ch.looks):>5} {look_names}") lines.append("-" * 90) total = sum(len(c.looks) for c in characters) lines.append(f"{'TOTAL':<30} {total:>5}") return "\n".join(lines)