RichardScottOZ commited on
Commit
e0306f8
Β·
verified Β·
1 Parent(s): b342f45

Update README.md

Browse files

add readme basics

Files changed (1) hide show
  1. README.md +199 -0
README.md CHANGED
@@ -1,3 +1,202 @@
1
  ---
 
 
 
 
 
 
 
 
2
  license: mit
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language: en
3
+ tags:
4
+ - vision
5
+ - comics
6
+ - sequence-modeling
7
+ - transformer
8
+ - feature-extraction
9
+ - narrative-understanding
10
  license: mit
11
  ---
12
+
13
+ # Comic Strip Encoder v1 (Stage 4)
14
+
15
+ This model is a **Transformer sequence encoder** designed to generate narrative-aware, contextualized embeddings of comic book page strips. It serves as "Stage 4" of the [Comic Analysis Framework v2.0](https://github.com/RichardScottOZ/Comic-Analysis).
16
+
17
+ Where [comic-panel-vlm-v1 (Stage 3)](https://huggingface.co/RichardScottOZ/comic-panel-vlm-v1) generates a **512-dimensional embedding per panel in isolation**, this model takes a full page's worth of panel embeddings (a strip) and runs them through a Transformer encoder. Every output embedding is then **conditioned on the panels surrounding it** β€” the model has learned what a panel means *in the context of the story around it*. The outputs are:
18
+
19
+ - **`contextualized_panels`** `(N, 512)` β€” per-panel embeddings enriched with sequential narrative context
20
+ - **`strip_embeddings`** `(512,)` β€” a single vector summarising an entire page/strip
21
+
22
+ These are intended as the primary inputs for downstream retrieval, reranking, and narrative analysis tasks (Stage 5).
23
+
24
+ ## Model Architecture
25
+
26
+ The `comic-strip-encoder-v1` is a **BERT-style Transformer Encoder** (`Stage4SequenceModel`):
27
+
28
+ 1. **Input Projection**: Linear layer mapping 512-d panel embeddings into the model's d_model space.
29
+ 2. **Positional Encoding**: Learned positional encodings for panel sequence order.
30
+ 3. **Panel Sequence Transformer**:
31
+ - 6 Transformer encoder layers
32
+ - 8 attention heads
33
+ - Pre-norm (LayerNorm before attention) for training stability
34
+ - Attention masking for variable-length strips (max 16 panels)
35
+ 4. **Strip Aggregation**: A learned `[CLS]`-style query attends over all panel outputs to produce a single strip-level vector.
36
+ 5. **Task-Specific Heads** (7 total, used during training):
37
+
38
+ | Head | Task | Paper |
39
+ | :--- | :--- | :--- |
40
+ | `ReadingOrderHead` | Pairwise panel ordering (adjacency matrix) | ComicsPAP |
41
+ | `PanelPickingHead` | Select missing panel from candidates | ComicsPAP |
42
+ | `CharacterCoherenceHead` | Visual identity consistency across panels | ComicsPAP |
43
+ | `VisualClosureHead` | Action continuation plausibility | ComicsPAP |
44
+ | `TextClosureHead` | Dialogue continuation plausibility | ComicsPAP |
45
+ | `CaptionRelevanceHead` | Text-visual alignment scoring | ComicsPAP |
46
+ | `TextClozeHead` | Select correct dialogue given visual context | Text-Cloze |
47
+
48
+ At inference time only the Transformer backbone + strip aggregator are required for embedding generation. The task heads can be used directly for scoring tasks.
49
+
50
+ ## Training Data & Methodology
51
+
52
+ The model was trained on sequences of panel embeddings generated by [comic-panel-vlm-v1](https://huggingface.co/RichardScottOZ/comic-panel-vlm-v1) across approximately **1 million comic pages**, filtered for narrative/story content by Stage 2 (CoSMo PSS).
53
+
54
+ ### Research Foundation
55
+
56
+ - **ComicsPAP** ([arXiv:2503.08561](https://arxiv.org/abs/2503.08561)): Five discriminative tasks for sequential comic understanding. State-of-the-art LMMs perform near chance on these tasks; domain-trained sequence models are necessary.
57
+ - **Text-Cloze** ([arXiv:2403.03719](https://arxiv.org/abs/2403.03719)): Multimodal transformers outperform RNNs by ~10% on dialogue cloze tasks; domain-adapted encoders are critical.
58
+
59
+ ### Training Objectives
60
+
61
+ ```
62
+ L_total = Ξ£(weighted task losses) + 0.5 * L_contrastive + 0.3 * L_reading_order
63
+ ```
64
+
65
+ Task weights during multi-task training:
66
+
67
+ ```python
68
+ task_weights = {
69
+ 'panel_picking': 1.0, # Primary ComicsPAP task
70
+ 'text_cloze': 1.0, # Primary Text-Cloze task
71
+ 'reading_order': 0.7,
72
+ 'visual_closure': 0.8,
73
+ 'text_closure': 0.8,
74
+ 'character_coherence': 0.5,
75
+ 'caption_relevance': 0.5,
76
+ }
77
+ ```
78
+
79
+ **Key design choice β€” discriminative not generative**: candidates are selected from a pool rather than generated, following the ComicsPAP framework. This makes training tractable and evaluation unambiguous.
80
+
81
+ ## Usage
82
+
83
+ The codebase is available at the [Comic Analysis GitHub Repository](https://github.com/RichardScottOZ/Comic-Analysis) under `src/version2/stage4_sequence_modeling_framework.py`.
84
+
85
+ ### Example: Generating Strip & Panel Embeddings
86
+
87
+ ```python
88
+ import torch
89
+ from stage4_sequence_modeling_framework import Stage4SequenceModel
90
+
91
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
92
+
93
+ # 1. Initialize model
94
+ model = Stage4SequenceModel(d_model=512, num_layers=6, nhead=8).to(device)
95
+
96
+ # Load weights from Hugging Face
97
+ state_dict = torch.hub.load_state_dict_from_url(
98
+ "https://huggingface.co/RichardScottOZ/comic-strip-encoder-v1/resolve/main/best_model.pt",
99
+ map_location=device
100
+ )
101
+ model.load_state_dict(state_dict['model_state_dict'])
102
+ model.eval()
103
+
104
+ # 2. Inputs: panel embeddings from comic-panel-vlm-v1
105
+ # panel_embeddings: (B, N, 512) β€” N panels on one page, up to 16
106
+ # panel_mask: (B, N) β€” True where panel exists
107
+
108
+ panel_embeddings = torch.randn(1, 6, 512).to(device) # 1 page, 6 panels
109
+ panel_mask = torch.ones(1, 6, dtype=torch.bool).to(device)
110
+
111
+ # 3. Generate embeddings
112
+ with torch.no_grad():
113
+ outputs = model(panel_embeddings, panel_mask)
114
+
115
+ contextualized_panels = outputs['contextualized_panels'] # (1, 6, 512)
116
+ strip_embedding = outputs['strip_embedding'] # (1, 512)
117
+
118
+ print(f"Contextualized panels: {contextualized_panels.shape}")
119
+ print(f"Strip embedding: {strip_embedding.shape}")
120
+ ```
121
+
122
+ ### Example: Reading Order Scoring
123
+
124
+ ```python
125
+ with torch.no_grad():
126
+ # order_matrix[0, i, j] = score indicating if panel i comes before panel j
127
+ order_matrix = model.reading_order_head(panel_embeddings) # (1, N, N)
128
+
129
+ # Compute sorting order based on average row scores
130
+ predicted_order = order_matrix[0].sum(dim=1).argsort(descending=True)
131
+ print(f"Predicted reading order: {predicted_order.tolist()}")
132
+ ```
133
+
134
+ ### Example: Panel Picking (ComicsPAP-style)
135
+
136
+ ```python
137
+ # context: panels from the strip with one masked out
138
+ # candidates: 5 panel embeddings (1 correct, 4 distractors)
139
+ context_emb = contextualized_panels[:, :5, :] # (1, 5, 512)
140
+ candidate_embs = torch.randn(1, 5, 512).to(device) # (1, 5 candidates, 512)
141
+
142
+ with torch.no_grad():
143
+ scores = model.panel_picking_head(context_emb.mean(dim=1), candidate_embs)
144
+ predicted_idx = scores.argmax(dim=-1)
145
+ print(f"Predicted panel index: {predicted_idx.item()}")
146
+ ```
147
+
148
+ ## Pipeline Position
149
+
150
+ ```
151
+ Stage 1: Raw Comics β†’ Panel crops + OCR text
152
+ Stage 2: CoSMo (PSS) β†’ Narrative page classification
153
+ Stage 3: comic-panel-vlm-v1 β†’ Multimodal panel embeddings (V + T + Composition) β†’ (N, 512)
154
+ Stage 4: comic-strip-encoder-v1 β†’ Contextualized panel + strip embeddings ← THIS MODEL
155
+ Stage 5: Storage & Query β†’ Zarr store + semantic search
156
+ ```
157
+
158
+ ## Intended Use
159
+
160
+ - **Narrative reranking**: Stage 3 retrieves top-N candidates; Stage 4 strip embeddings rerank by sequence coherence.
161
+ - **Story-level similarity**: Encode a query as a single panel β†’ Stage 4 β†’ compare strip embeddings across a corpus (story-level search, not panel-level).
162
+ - **Reading order auditing**: Use the `ReadingOrderHead` pairwise matrix to verify or correct panel sequencing in digitised comics.
163
+ - **Narrative flow verification**: Score a proposed page sequence for coherence using the closure heads.
164
+ - **Localisation/dialogue drift auditing**: Use the `TextClozeHead` to flag pages where dialogue is likely misattributed or out of order.
165
+
166
+ ## Limitations
167
+
168
+ - **Fixed max sequence length**: 16 panels per page (memory constraint at training time).
169
+ - **Discriminative only**: Task heads require candidate sets; not a generative model.
170
+ - **Page-level only**: Does not model multi-page narrative arcs.
171
+ - **Upstream dependency**: Requires Stage 3 (`comic-panel-vlm-v1`) embeddings as input; raw images are not accepted directly.
172
+ - **No explicit character re-identification**: The `CharacterCoherenceHead` scores visual consistency but does not track named characters across pages.
173
+
174
+ ## Performance Expectations
175
+
176
+ | Task | Expected Accuracy | Random Baseline |
177
+ | :--- | :--- | :--- |
178
+ | Panel Picking | 60–70% | 20% |
179
+ | Visual Closure | 55–65% | 20% |
180
+ | Text Closure | 50–60% | 20% |
181
+ | Reading Order | 75–85% | 50% |
182
+ | Text-Cloze | 50–60% | 25% |
183
+
184
+ ## Citation
185
+
186
+ If you use this model or the associated framework, please link back to the [Comic Analysis GitHub Repository](https://github.com/RichardScottOZ/Comic-Analysis).
187
+
188
+ Related work this model is based on:
189
+
190
+ ```bibtex
191
+ @article{comicspap2025,
192
+ title={ComicsPAP: A Panel-Aware Pipeline for Comic Understanding},
193
+ year={2025},
194
+ url={https://arxiv.org/abs/2503.08561}
195
+ }
196
+
197
+ @article{textcloze2024,
198
+ title={Text-Cloze: Multimodal Dialogue Prediction in Comics},
199
+ year={2024},
200
+ url={https://arxiv.org/abs/2403.03719}
201
+ }
202
+ ```