MTA / plot_figures_from_metadata.py
Holomorphica's picture
Upload folder using huggingface_hub
97472de verified
Raw History Blame Contribute Delete
23.4 kB
"""
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()