File size: 7,979 Bytes
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
68697dc
74888a1
 
 
 
 
 
68697dc
 
 
 
 
74888a1
68697dc
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74888a1
 
 
68697dc
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)