File size: 23,356 Bytes
97472de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
"""
Regenerate all paper figures from metadata parquet.

This script reads the metadata parquet file and recreates all figures.
You can modify the plotting code to customize the figures as needed.

Usage:
    python plot_figures_from_metadata.py --fig 1  # Generate figure 1 only
    python plot_figures_from_metadata.py --all    # Generate all figures
"""

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import json
import os
import argparse

# Output directory
OUTPUT_DIR = '/opt/tiger/DataWorks/paper_figures'
METADATA_PATH = '/opt/tiger/DataWorks/paper_figures/metadata.parquet'

# Set matplotlib style
plt.rcParams['font.family'] = 'DejaVu Sans'
plt.rcParams['font.size'] = 10
plt.rcParams['axes.titlesize'] = 12
plt.rcParams['axes.labelsize'] = 10
plt.rcParams['figure.dpi'] = 150


def load_metadata():
    """Load metadata from parquet file."""
    df = pd.read_parquet(METADATA_PATH)
    meta = df.iloc[0].to_dict()
    # Parse JSON fields
    for key in meta:
        if isinstance(meta[key], str) and (meta[key].startswith('{') or meta[key].startswith('[')):
            try:
                meta[key] = json.loads(meta[key])
            except:
                pass
    return meta


def fig1_keyword_category(meta):
    """Figure 1: Keyword Category Double-Layer Pie Chart (Aligned)."""
    print("Creating Figure 1: Keyword Category...")

    category_hierarchy = meta['category_hierarchy']
    parent_colors = meta['parent_colors']
    real_category_counts = meta['real_category_counts']
    data_category_counts = meta['data_category_counts']

    def get_parent_category(sub_category):
        for parent, children in category_hierarchy.items():
            if sub_category in children:
                return parent
        return None

    def make_aligned_double_pie(ax, sub_counts, title):
        valid_subs = {k: v for k, v in sub_counts.items() if get_parent_category(k) is not None}
        if not valid_subs:
            return

        all_data = []
        for parent in category_hierarchy.keys():
            for sub in category_hierarchy[parent]:
                if sub in valid_subs:
                    all_data.append((parent, sub, valid_subs[sub]))

        if not all_data:
            return

        parent_counts = {}
        for parent, sub, count in all_data:
            parent_counts[parent] = parent_counts.get(parent, 0) + count

        total = sum(parent_counts.values())
        start_angle = 90
        segments = []
        current_angle = start_angle

        for parent in category_hierarchy.keys():
            if parent not in parent_counts:
                continue
            parent_total = parent_counts[parent]
            subs_for_parent = [(sub, count) for p, sub, count in all_data if p == parent]
            sub_start = current_angle

            for sub, count in subs_for_parent:
                sub_angle = 360 * count / total
                sub_end = sub_start + sub_angle
                segments.append({
                    'parent': parent, 'sub': sub,
                    'start_angle': sub_start, 'end_angle': sub_end,
                    'count': count, 'parent_count': parent_total
                })
                sub_start = sub_end
            current_angle += 360 * parent_total / total

        # Outer pie (sub-categories)
        outer_colors = [parent_colors[seg['parent']] for seg in segments]
        outer_sizes = [seg['end_angle'] - seg['start_angle'] for seg in segments]
        outer_labels = [seg['sub'] for seg in segments]

        ax.pie(outer_sizes, labels=outer_labels, colors=outer_colors, radius=1.4,
               wedgeprops=dict(width=0.4, edgecolor='white'),
               textprops={'fontsize': 7}, labeldistance=1.15, startangle=start_angle)

        # Inner pie (parents)
        inner_colors = [parent_colors[p] for p in category_hierarchy.keys() if p in parent_counts]
        inner_sizes = [360 * parent_counts[p] / total for p in category_hierarchy.keys() if p in parent_counts]
        inner_labels = [p for p in category_hierarchy.keys() if p in parent_counts]

        ax.pie(inner_sizes, labels=inner_labels, autopct='%1.1f%%',
               colors=inner_colors, radius=1.0,
               wedgeprops=dict(width=0.4, edgecolor='white'),
               textprops={'fontsize': 9}, pctdistance=0.75, startangle=start_angle)

        ax.set_title(title, fontweight='bold', fontsize=12)

    fig, axes = plt.subplots(1, 2, figsize=(14, 7))
    real_total = sum(v for k, v in real_category_counts.items() if get_parent_category(k))
    data_total = sum(v for k, v in data_category_counts.items() if get_parent_category(k))

    make_aligned_double_pie(axes[0], real_category_counts, 'Real Data (n={:,})'.format(real_total))
    make_aligned_double_pie(axes[1], data_category_counts, 'Synthetic Data (n={:,})'.format(data_total))

    plt.suptitle('Keyword Category Distribution (Double-Layer Aligned)', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig1_keyword_category.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig1_keyword_category.pdf/png")


def fig2_duration(meta):
    """Figure 2: Duration Distribution Histograms."""
    print("Creating Figure 2: Duration Histograms...")

    duration_stats = meta['duration_stats']
    duration_buckets_real = meta['duration_buckets_real']
    duration_buckets_synthetic = meta['duration_buckets_synthetic']

    fig, axes = plt.subplots(1, 2, figsize=(14, 6))

    # Left: Bar chart by buckets
    labels = ['0-3s', '3-5s', '5-8s', '8-10s', '10-15s', '15-20s', '20-30s', '30-60s', '60-120s', '>120s']
    x = np.arange(len(labels))
    width = 0.35

    synth_stats = duration_stats['synthetic']
    real_stats = duration_stats['real']

    synthetic_vals = [duration_buckets_synthetic[l] for l in labels]
    real_vals = [duration_buckets_real[l] for l in labels]

    synthetic_pct = [v / synth_stats['count'] * 100 for v in synthetic_vals]
    real_pct = [v / real_stats['count'] * 100 for v in real_vals]

    axes[0].bar(x - width/2, synthetic_pct, width, label='Synthetic (n={:,})'.format(int(synth_stats['count'])),
                color='#e74c3c', alpha=0.8)
    axes[0].bar(x + width/2, real_pct, width, label='Real (n={:,})'.format(int(real_stats['count'])),
                color='#3498db', alpha=0.8)

    axes[0].set_xlabel('Duration Bucket')
    axes[0].set_ylabel('Percentage (%)')
    axes[0].set_title('Duration Distribution by Buckets', fontweight='bold')
    axes[0].set_xticks(x)
    axes[0].set_xticklabels(labels, rotation=45, ha='right')
    axes[0].legend()

    stats_text = (
        "Synthetic: Mean={:.2f}s, Median={:.2f}s\n"
        "Exceeding 8s: {:.1f}%, 15s: {:.1f}%\n\n"
        "Real: Mean={:.2f}s, Median={:.2f}s\n"
        "Exceeding 8s: {:.1f}%, 15s: {:.1f}%"
    ).format(
        synth_stats['mean'], synth_stats['median'],
        synth_stats['exceed_8s'], synth_stats['exceed_15s'],
        real_stats['mean'], real_stats['median'],
        real_stats['exceed_8s'], real_stats['exceed_15s']
    )
    axes[0].text(0.98, 0.98, stats_text, transform=axes[0].transAxes, fontsize=9,
                verticalalignment='top', horizontalalignment='right',
                bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))

    # Right: Density histogram
    max_dur = 60
    bin_width = 1.0
    x_bins = np.arange(0, max_dur + bin_width, bin_width)

    bucket_ranges = {
        '0-3s': (0, 3), '3-5s': (3, 5), '5-8s': (5, 8), '8-10s': (8, 10),
        '10-15s': (10, 15), '15-20s': (15, 20), '20-30s': (20, 30), '30-60s': (30, 60),
        '60-120s': (60, 120), '>120s': (120, 200)
    }

    synth_density = np.zeros(len(x_bins))
    real_density = np.zeros(len(x_bins))

    for label, count in duration_buckets_synthetic.items():
        start, end = bucket_ranges[label]
        if start < max_dur:
            density = count / synth_stats['count'] / (end - start)
            for i, t in enumerate(x_bins):
                if start <= t < min(end, max_dur):
                    synth_density[i] = density

    for label, count in duration_buckets_real.items():
        start, end = bucket_ranges[label]
        if start < max_dur:
            density = count / real_stats['count'] / (end - start)
            for i, t in enumerate(x_bins):
                if start <= t < min(end, max_dur):
                    real_density[i] = density

    axes[1].step(x_bins, synth_density, where='mid', label='Synthetic', color='#e74c3c', linewidth=2)
    axes[1].fill_between(x_bins, synth_density, step='mid', alpha=0.3, color='#e74c3c')
    axes[1].step(x_bins, real_density, where='mid', label='Real', color='#3498db', linewidth=2)
    axes[1].fill_between(x_bins, real_density, step='mid', alpha=0.3, color='#3498db')
    axes[1].axvline(x=8, color='green', linestyle='--', linewidth=1.5, label='8s threshold')
    axes[1].axvline(x=15, color='orange', linestyle='--', linewidth=1.5, label='15s threshold')

    axes[1].set_xlabel('Duration (seconds)')
    axes[1].set_ylabel('Density')
    axes[1].set_title('Duration Density Distribution (0-60s)', fontweight='bold')
    axes[1].legend()
    axes[1].set_xlim(0, 60)

    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig2_duration_histograms.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig2_duration_histograms.pdf/png")


def fig3_language(meta):
    """Figure 3: Language Distribution."""
    print("Creating Figure 3: Language Distribution...")

    real_lang = meta['real_lang_counts']
    data_lang = meta['data_lang_counts']

    # Top languages
    all_langs = set(real_lang.keys()) | set(data_lang.keys())
    top_langs = sorted(all_langs, key=lambda x: real_lang.get(x, 0) + data_lang.get(x, 0), reverse=True)[:6]

    fig, axes = plt.subplots(1, 2, figsize=(12, 6))

    colors = ['#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c']

    # Real data
    real_vals = [real_lang.get(l, 0) for l in top_langs]
    axes[0].pie(real_vals, labels=top_langs, autopct='%1.1f%%', colors=colors,
                startangle=90, explode=[0.02]*len(top_langs))
    axes[0].set_title('Real Data (n={:,})'.format(sum(real_lang.values())), fontweight='bold')

    # Synthetic data
    data_vals = [data_lang.get(l, 0) for l in top_langs]
    axes[1].pie(data_vals, labels=top_langs, autopct='%1.1f%%', colors=colors,
                startangle=90, explode=[0.02]*len(top_langs))
    axes[1].set_title('Synthetic Data (n={:,})'.format(sum(data_lang.values())), fontweight='bold')

    plt.suptitle('Language Distribution', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig3_language_distribution.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig3_language_distribution.pdf/png")


def fig4_query_length(meta):
    """Figure 4: Query Length Distribution (Normalized)."""
    print("Creating Figure 4: Query Length...")

    bins = meta['query_len_bins']
    real_hist = meta['real_query_hist']
    data_hist = meta['data_query_hist']

    fig, ax = plt.subplots(figsize=(10, 6))

    # Normalize
    real_total = sum(real_hist)
    data_total = sum(data_hist)
    bin_width = bins[1] - bins[0]

    real_density = [v / real_total / bin_width for v in real_hist]
    data_density = [v / data_total / bin_width for v in data_hist]

    bin_centers = [(bins[i] + bins[i+1]) / 2 for i in range(len(bins)-1)]

    ax.bar([b - 2.5 for b in bin_centers], real_density, width=4, alpha=0.6,
           label='Real (mean={:.1f})'.format(meta['real_query_len_mean']), color='#3498db')
    ax.bar([b + 2.5 for b in bin_centers], data_density, width=4, alpha=0.6,
           label='Synthetic (mean={:.1f})'.format(meta['data_query_len_mean']), color='#e74c3c')

    ax.set_xlabel('Query Length (characters)')
    ax.set_ylabel('Density')
    ax.set_title('Query Length Distribution (Normalized, cropped at 200)', fontweight='bold')
    ax.legend()
    ax.set_xlim(0, 200)

    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig4_query_length.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig4_query_length.pdf/png")


def fig5_keyword_category_simple(meta):
    """Figure 5: Keyword Category Distribution (Simple Pie)."""
    print("Creating Figure 5: Keyword Category Simple...")

    real_counts = meta['real_category_counts']
    data_counts = meta['data_category_counts']

    categories = list(real_counts.keys())
    colors = plt.cm.Set3(np.linspace(0, 1, len(categories)))

    fig, axes = plt.subplots(1, 2, figsize=(14, 6))

    real_vals = [real_counts[c] for c in categories]
    axes[0].pie(real_vals, labels=categories, autopct='%1.1f%%', colors=colors)
    axes[0].set_title('Real Data (n={:,})'.format(sum(real_vals)), fontweight='bold')

    data_vals = [data_counts.get(c, 0) for c in categories]
    axes[1].pie(data_vals, labels=categories, autopct='%1.1f%%', colors=colors)
    axes[1].set_title('Synthetic Data (n={:,})'.format(sum(data_vals)), fontweight='bold')

    plt.suptitle('Keyword Category Distribution', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig5_keyword_category_distribution.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig5_keyword_category_distribution.pdf/png")


def fig6_content_type(meta):
    """Figure 6: Content Type (Live vs VOD)."""
    print("Creating Figure 6: Content Type...")

    fig, axes = plt.subplots(1, 2, figsize=(10, 5))

    axes[0].pie([meta['real_live_count'], meta['real_vod_count']],
               labels=['Live', 'VOD'], autopct='%1.1f%%',
               colors=['#FF6B6B', '#4ECDC4'], explode=[0.02, 0.02])
    axes[0].set_title('Real Data (n={:,})'.format(meta['real_live_count'] + meta['real_vod_count']), fontweight='bold')

    axes[1].pie([meta['data_live_count'], meta['data_vod_count']],
               labels=['Live', 'VOD'], autopct='%1.1f%%',
               colors=['#FF6B6B', '#4ECDC4'], explode=[0.02, 0.02])
    axes[1].set_title('Synthetic Data (n={:,})'.format(meta['data_live_count'] + meta['data_vod_count']), fontweight='bold')

    plt.suptitle('Content Type Distribution (Live vs VOD)', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig6_content_type.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig6_content_type.pdf/png")


def fig7_human_count(meta):
    """Figure 7: Human Count Pie Charts."""
    print("Creating Figure 7: Human Count...")

    real_counts = meta['real_human_counts']
    data_counts = meta['data_human_counts']

    categories = ['NA', '0', '1', '2', '3+']
    colors = ['#95a5a6', '#e74c3c', '#3498db', '#2ecc71', '#9b59b6']

    fig, axes = plt.subplots(1, 2, figsize=(12, 6))

    real_vals = [real_counts[c] for c in categories]
    axes[0].pie(real_vals, labels=categories, autopct='%1.1f%%', colors=colors, explode=[0.02]*5)
    axes[0].set_title('Real Data', fontweight='bold')

    data_vals = [data_counts[c] for c in categories]
    axes[1].pie(data_vals, labels=categories, autopct='%1.1f%%', colors=colors, explode=[0.02]*5)
    axes[1].set_title('Synthetic Data', fontweight='bold')

    plt.suptitle('Human Count Distribution', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig7_human_count.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig7_human_count.pdf/png")


def fig8_scene_multiscreen(meta):
    """Figure 8: Scene Cut and Multiscreen."""
    print("Creating Figure 8: Scene Cut & Multiscreen...")

    fig, axes = plt.subplots(1, 2, figsize=(12, 5))

    x = np.arange(2)
    width = 0.35

    # Scene cut
    axes[0].bar(x - width/2, [meta['real_total'] - meta['real_scene_cut'], meta['real_scene_cut']],
               width, label='Real', color='#3498db')
    axes[0].bar(x + width/2, [meta['data_total'] - meta['data_scene_cut'], meta['data_scene_cut']],
               width, label='Synthetic', color='#e74c3c')
    axes[0].set_xticks(x)
    axes[0].set_xticklabels(['No Scene Cut', 'Scene Cut'])
    axes[0].set_ylabel('Number of Clips')
    axes[0].set_title('Scene Cut Distribution', fontweight='bold')
    axes[0].legend()

    # Multiscreen
    axes[1].bar(x - width/2, [meta['real_total'] - meta['real_multiscreen'], meta['real_multiscreen']],
               width, label='Real', color='#3498db')
    axes[1].bar(x + width/2, [meta['data_total'] - meta['data_multiscreen'], meta['data_multiscreen']],
               width, label='Synthetic', color='#e74c3c')
    axes[1].set_xticks(x)
    axes[1].set_xticklabels(['Single Screen', 'Multiscreen'])
    axes[1].set_ylabel('Number of Clips')
    axes[1].set_title('Multiscreen Distribution', fontweight='bold')
    axes[1].legend()

    plt.suptitle('Visual Features Distribution', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig8_scene_multiscreen.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig8_scene_multiscreen.pdf/png")


def fig9_relevance_by_category(meta):
    """Figure 9: Relevance by Category Heatmap."""
    print("Creating Figure 9: Relevance by Category...")

    import seaborn as sns

    real_rel = meta['real_relevance_by_cat']
    data_rel = meta['data_relevance_by_cat']

    categories = list(real_rel.keys())

    real_matrix = pd.DataFrame([real_rel[c] for c in categories],
                               index=categories, columns=['DIRECT', 'THEMATIC', 'UNRELATED'])
    data_matrix = pd.DataFrame([data_rel.get(c, {'DIRECT': 0, 'THEMATIC': 0, 'UNRELATED': 0}) for c in categories],
                               index=categories, columns=['DIRECT', 'THEMATIC', 'UNRELATED'])

    fig, axes = plt.subplots(1, 2, figsize=(14, 7))

    sns.heatmap(real_matrix * 100, annot=True, fmt='.1f', cmap='YlGnBu', ax=axes[0])
    axes[0].set_title('Real Data', fontweight='bold')
    axes[0].set_xlabel('Relevance Rating')
    axes[0].set_ylabel('Category')

    sns.heatmap(data_matrix * 100, annot=True, fmt='.1f', cmap='YlGnBu', ax=axes[1])
    axes[1].set_title('Synthetic Data', fontweight='bold')
    axes[1].set_xlabel('Relevance Rating')
    axes[1].set_ylabel('Category')

    plt.suptitle('Relevance Rating by Keyword Category (%)', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig9_relevance_by_category.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig9_relevance_by_category.pdf/png")


def fig10_caption_length(meta):
    """Figure 10: Caption Length Distribution."""
    print("Creating Figure 10: Caption Length...")

    bins = meta['caption_bins']
    real_simple = meta['real_caption_simple_hist']
    real_detailed = meta['real_caption_detailed_hist']
    data_simple = meta['data_caption_simple_hist']
    data_detailed = meta['data_caption_detailed_hist']

    fig, axes = plt.subplots(1, 2, figsize=(12, 5))

    bin_centers = [(bins[i] + bins[i+1]) / 2 for i in range(len(bins)-1)]

    # Normalize
    real_simple_norm = [v / sum(real_simple) for v in real_simple]
    data_simple_norm = [v / sum(data_simple) for v in data_simple]

    axes[0].bar(bin_centers, real_simple_norm, width=8, alpha=0.7, label='Real', color='#3498db')
    axes[0].bar(bin_centers, data_simple_norm, width=8, alpha=0.5, label='Synthetic', color='#e74c3c')
    axes[0].set_xlabel('Caption Length (chars)')
    axes[0].set_ylabel('Density')
    axes[0].set_title('Caption Simple', fontweight='bold')
    axes[0].legend()

    real_detailed_norm = [v / sum(real_detailed) for v in real_detailed]
    data_detailed_norm = [v / sum(data_detailed) for v in data_detailed]

    axes[1].bar(bin_centers, real_detailed_norm, width=8, alpha=0.7, label='Real', color='#3498db')
    axes[1].bar(bin_centers, data_detailed_norm, width=8, alpha=0.5, label='Synthetic', color='#e74c3c')
    axes[1].set_xlabel('Caption Length (chars)')
    axes[1].set_ylabel('Density')
    axes[1].set_title('Caption Detailed', fontweight='bold')
    axes[1].legend()

    plt.suptitle('Caption Length Distribution (Normalized)', fontsize=14, fontweight='bold')
    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig10_caption_length.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig10_caption_length.pdf/png")


def fig11_clips_per_video(meta):
    """Figure 11: Clips per Video Distribution."""
    print("Creating Figure 11: Clips per Video...")

    bins = meta['clips_bins']
    real_hist = meta['real_clips_hist']
    data_hist = meta['data_clips_hist']

    fig, ax = plt.subplots(figsize=(10, 6))

    bin_labels = ['{}-{}'.format(bins[i], bins[i+1]) for i in range(len(bins)-1)]
    x = np.arange(len(bin_labels))
    width = 0.35

    ax.bar(x - width/2, real_hist, width, label='Real (mean={:.1f})'.format(meta['real_clips_mean']),
          color='#3498db')
    ax.bar(x + width/2, data_hist, width, label='Synthetic (mean={:.1f})'.format(meta['data_clips_mean']),
          color='#e74c3c')

    ax.set_xlabel('Clips per Video')
    ax.set_ylabel('Number of Videos')
    ax.set_title('Clips per Video Distribution', fontweight='bold')
    ax.set_xticks(x)
    ax.set_xticklabels(bin_labels, rotation=45, ha='right')
    ax.legend()

    plt.tight_layout()

    for ext in ['pdf', 'png']:
        plt.savefig(os.path.join(OUTPUT_DIR, 'fig11_clips_per_video.{}'.format(ext)), dpi=300, bbox_inches='tight')
    plt.close()
    print("  Saved fig11_clips_per_video.pdf/png")


def main():
    parser = argparse.ArgumentParser(description='Regenerate figures from metadata parquet')
    parser.add_argument('--all', action='store_true', help='Generate all figures')
    parser.add_argument('--fig', type=int, help='Generate specific figure (1-11)')
    args = parser.parse_args()

    print("Loading metadata from parquet...")
    meta = load_metadata()
    print("Loaded {} metadata fields".format(len(meta)))

    figure_funcs = {
        1: fig1_keyword_category,
        2: fig2_duration,
        3: fig3_language,
        4: fig4_query_length,
        5: fig5_keyword_category_simple,
        6: fig6_content_type,
        7: fig7_human_count,
        8: fig8_scene_multiscreen,
        9: fig9_relevance_by_category,
        10: fig10_caption_length,
        11: fig11_clips_per_video,
    }

    if args.all:
        print("\n" + "="*60)
        print("Generating all figures...")
        print("="*60)
        for fig_num in sorted(figure_funcs.keys()):
            figure_funcs[fig_num](meta)
    elif args.fig:
        if args.fig in figure_funcs:
            figure_funcs[args.fig](meta)
        else:
            print("Invalid figure number. Must be 1-11.")
    else:
        parser.print_help()


if __name__ == "__main__":
    main()