#!/usr/bin/env python3 """ prep_dataset.py — Problem-setter script for CLIP Pelatnas P2 2026 Generates the full competition dataset from: - STL-10 (torchvision) - Flickr8k (HuggingFace: jxie/flickr8k) - ScienceQA (HuggingFace: derek-thomas/ScienceQA) Run once locally. Outputs: ./output/clip-pelatnas-p2/ ← upload to Kaggle ./output/solution.csv ← keep private, use for Kaggle evaluator """ import os import re import random from collections import defaultdict from pathlib import Path import numpy as np import pandas as pd from PIL import Image from tqdm import tqdm SEED = 42 random.seed(SEED) np.random.seed(SEED) OUTPUT_DIR = Path('./output/clip-pelatnas-p2') SOLUTION_FILE = Path('./output/solution.csv') STOP_WORDS = { 'a', 'an', 'the', 'is', 'in', 'on', 'at', 'of', 'and', 'with', 'to', 'it', 'its', 'this', 'that', 'are', 'was', 'be', 'by', 'he', 'she', 'they', 'we', 'you', 'or', 'but', 'from', 'as', 'into', 'over', 'under', 'then', 'when', 'where', 'all', 'each', 'some', 'no', 'not', 'up', 'out', 'man', 'men', 'woman', 'women', 'person', 'people', 'one', 'two', 'three', 'his', 'her', 'their', 'while', 'after', 'before', 'near', 'next', 'has', 'have', 'had', 'been', 'who', 'what', 'which', 'so', 'just', 'than', 'too', } LETTER_MAP = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'} # ───────────────────────────────────────────────────────────────────────────── # Section 1: STL-10 # ───────────────────────────────────────────────────────────────────────────── def prepare_stl10(): print("\n" + "=" * 60) print("SECTION 1: STL-10") print("=" * 60) import torchvision.datasets as tv_datasets lp_train_img_dir = OUTPUT_DIR / 'train/linear_probing/images' zs_test_img_dir = OUTPUT_DIR / 'test/zero_shot/images' lp_test_img_dir = OUTPUT_DIR / 'test/linear_probing/images' for d in [lp_train_img_dir, zs_test_img_dir, lp_test_img_dir]: d.mkdir(parents=True, exist_ok=True) print("Downloading STL-10 (train + test)...") stl10_train = tv_datasets.STL10(root='./raw_data', split='train', download=True) stl10_test = tv_datasets.STL10(root='./raw_data', split='test', download=True) # Use the dataset's own class list so label indices are correct STL10_CLASSES = stl10_train.classes print(f"STL-10 classes: {STL10_CLASSES}") # ── Linear probing train: first 100 per class from train split ──────────── lp_train_records = [] class_count = defaultdict(int) print("Building linear probing train set (100/class = 1000 images)...") for idx in tqdm(range(len(stl10_train))): img, label = stl10_train[idx] if class_count[label] < 100: n = class_count[label] cls = STL10_CLASSES[label] fname = f'{cls}_{n:03d}.png' img.save(lp_train_img_dir / fname) lp_train_records.append({ 'id': f'lp_train_{len(lp_train_records)+1:04d}', 'image_path': fname, 'label': cls, }) class_count[label] += 1 if sum(class_count.values()) == 1000: break pd.DataFrame(lp_train_records).to_csv( OUTPUT_DIR / 'train/linear_probing/labels.csv', index=False ) print(f" → {len(lp_train_records)} images saved") # ── Test splits: 20/class zs_test, next 20/class lp_test ───────────────── zs_count = defaultdict(int) lp_count = defaultdict(int) zs_records = [] lp_records = [] print("Building zero-shot + linear probing test sets (20/class each)...") for idx in tqdm(range(len(stl10_test))): img, label = stl10_test[idx] cls = STL10_CLASSES[label] if zs_count[label] < 20: n = len(zs_records) + 1 fname = f'zs_{n:04d}.png' img.save(zs_test_img_dir / fname) zs_records.append({'id': f'zs_{n:04d}', 'image_path': fname, 'label': cls}) zs_count[label] += 1 elif lp_count[label] < 20: n = len(lp_records) + 1 fname = f'lp_{n:04d}.png' img.save(lp_test_img_dir / fname) lp_records.append({'id': f'lp_{n:04d}', 'image_path': fname, 'label': cls}) lp_count[label] += 1 if sum(zs_count.values()) == 200 and sum(lp_count.values()) == 200: break print(f" → ZS test: {len(zs_records)} images, LP test: {len(lp_records)} images") # class_names.txt with open(OUTPUT_DIR / 'class_names.txt', 'w') as f: for cls in STL10_CLASSES: f.write(cls + '\n') return STL10_CLASSES, zs_records, lp_records # ───────────────────────────────────────────────────────────────────────────── # Section 2: Flickr8k # ───────────────────────────────────────────────────────────────────────────── def _content_words(caption: str) -> set: words = re.findall(r'\b[a-z]{4,}\b', caption.lower()) return {w for w in words if w not in STOP_WORDS} def prepare_flickr8k(): print("\n" + "=" * 60) print("SECTION 2: Flickr8k") print("=" * 60) from datasets import load_dataset ret_train_img_dir = OUTPUT_DIR / 'train/retrieval/images' ret_test_query_dir = OUTPUT_DIR / 'test/retrieval/queries' for d in [ret_train_img_dir, ret_test_query_dir]: d.mkdir(parents=True, exist_ok=True) print("Loading jxie/flickr8k from HuggingFace...") flickr = load_dataset('jxie/flickr8k') # ── Train split: save all 6000 images ──────────────────────────────────── print("Processing retrieval train (6000 image-caption pairs)...") train_records = [] for i, item in enumerate(tqdm(flickr['train'])): fname = f'ret_train_{i+1:04d}.jpg' item['image'].save(ret_train_img_dir / fname, format='JPEG', quality=95) train_records.append({ 'id': f'ret_train_{i+1:04d}', 'image_path': fname, 'caption': item['caption_0'], }) pd.DataFrame(train_records).to_csv( OUTPUT_DIR / 'train/retrieval/captions.csv', index=False ) print(f" → {len(train_records)} train pairs saved") # ── Test split: sample 200 queries from 1000 test images ───────────────── print("Processing retrieval test (200 queries + distractors)...") test_split = flickr['test'] N_test = len(test_split) # 1000 rng = random.Random(SEED) query_indices = sorted(rng.sample(range(N_test), 200)) query_set = set(query_indices) # All test captions indexed by position all_captions = [test_split[i]['caption_0'] for i in range(N_test)] # Build inverted index over NON-query items for distractors word_to_idx = defaultdict(set) for i in range(N_test): if i in query_set: continue for w in _content_words(all_captions[i]): word_to_idx[w].add(i) non_query_pool = [i for i in range(N_test) if i not in query_set] candidate_records = [] for q_rank, q_idx in enumerate(tqdm(query_indices)): item = test_split[q_idx] correct_cap = item['caption_0'] # Save query image fname = f'ret_{q_rank+1:04d}.jpg' item['image'].save(ret_test_query_dir / fname, format='JPEG', quality=95) # Find distractors sharing ≥1 content word with correct caption cw = _content_words(correct_cap) candidate_pool = set() for w in cw: candidate_pool |= word_to_idx[w] candidate_pool = list(candidate_pool) if len(candidate_pool) >= 3: distractor_indices = rng.sample(candidate_pool, 3) else: distractor_indices = rng.sample(non_query_pool, 3) distractor_caps = [all_captions[i] for i in distractor_indices] # Shuffle position of correct caption options = distractor_caps + [correct_cap] rng.shuffle(options) correct_idx = options.index(correct_cap) candidate_records.append({ 'id': f'ret_{q_rank+1:04d}', 'image_path': fname, 'caption_0': options[0], 'caption_1': options[1], 'caption_2': options[2], 'caption_3': options[3], 'correct_idx': correct_idx, }) pd.DataFrame(candidate_records).to_csv( OUTPUT_DIR / 'test/retrieval/candidates.csv', index=False ) print(f" → {len(candidate_records)} retrieval queries saved") ret_records = [{'id': r['id'], 'label': r['correct_idx']} for r in candidate_records] return ret_records # ───────────────────────────────────────────────────────────────────────────── # Section 3: ScienceQA # ───────────────────────────────────────────────────────────────────────────── def _sciqa_rows(items, n, img_dir, id_prefix, rng, include_answer=True): """Stratified sample n items by subject, save images, return list of row dicts.""" items_with_img = [x for x in items if x.get('image') is not None] # Stratified sample by subject by_subject = defaultdict(list) for x in items_with_img: by_subject[x['subject']].append(x) subjects = sorted(by_subject.keys()) per_subj = n // len(subjects) remainder = n % len(subjects) sampled = [] for i, subj in enumerate(subjects): quota = per_subj + (1 if i < remainder else 0) pool = by_subject[subj] sampled.extend(rng.sample(pool, min(quota, len(pool)))) # Top-up if any subject was too small if len(sampled) < n: seen = set(id(x) for x in sampled) rest = [x for x in items_with_img if id(x) not in seen] sampled.extend(rng.sample(rest, n - len(sampled))) rng.shuffle(sampled) sampled = sampled[:n] rows = [] for i, item in enumerate(tqdm(sampled)): item_id = f'{id_prefix}_{i+1:04d}' fname = f'{item_id}.png' img = item['image'] if not isinstance(img, Image.Image): img = Image.fromarray(img) img.save(img_dir / fname) choices = item['choices'] n_choices = len(choices) row = { 'id': item_id, 'image_path': fname, 'question': item['question'], 'num_choices': n_choices, 'subject': item['subject'], 'grade': item['grade'], } for j in range(5): row[f'choice_{LETTER_MAP[j]}'] = choices[j] if j < n_choices else '' if include_answer: row['answer'] = LETTER_MAP[int(item['answer'])] rows.append(row) return rows def prepare_scienceqa(): print("\n" + "=" * 60) print("SECTION 3: ScienceQA") print("=" * 60) from datasets import load_dataset mcqa_train_img_dir = OUTPUT_DIR / 'train/mcqa/images' mcqa_test_img_dir = OUTPUT_DIR / 'test/mcqa/images' for d in [mcqa_train_img_dir, mcqa_test_img_dir]: d.mkdir(parents=True, exist_ok=True) print("Loading derek-thomas/ScienceQA from HuggingFace...") sciqa = load_dataset('derek-thomas/ScienceQA') rng = random.Random(SEED) train_cols_public = [ 'id', 'image_path', 'question', 'choice_A', 'choice_B', 'choice_C', 'choice_D', 'choice_E', 'num_choices', 'answer', 'subject', 'grade', ] test_cols_public = [ 'id', 'image_path', 'question', 'choice_A', 'choice_B', 'choice_C', 'choice_D', 'choice_E', 'num_choices', 'subject', 'grade', ] print("Processing MCQA train (2000 questions)...") train_rows = _sciqa_rows( list(sciqa['train']), 2000, mcqa_train_img_dir, 'mcqa_train', rng, include_answer=True ) pd.DataFrame(train_rows)[train_cols_public].to_csv( OUTPUT_DIR / 'train/mcqa/train.csv', index=False ) print("Processing MCQA test (200 questions)...") test_rows = _sciqa_rows( list(sciqa['test']), 200, mcqa_test_img_dir, 'mcqa', rng, include_answer=True ) # Public test CSV: no answer column pd.DataFrame(test_rows)[test_cols_public].to_csv( OUTPUT_DIR / 'test/mcqa/test.csv', index=False ) print(f" → MCQA train: {len(train_rows)}, test: {len(test_rows)}") return [{'id': r['id'], 'label': r['answer']} for r in test_rows] # ───────────────────────────────────────────────────────────────────────────── # Section 4: sample_submission.csv + solution.csv # ───────────────────────────────────────────────────────────────────────────── def generate_submission_files(zs_records, lp_records, ret_records, mcqa_records): print("\n" + "=" * 60) print("SECTION 4: Submission files") print("=" * 60) SOLUTION_FILE.parent.mkdir(parents=True, exist_ok=True) # Placeholder prediction per task prefix def placeholder(id_str): if id_str.startswith('zs') or id_str.startswith('lp'): return 'airplane' if id_str.startswith('ret'): return '0' return 'A' all_groups = [zs_records, lp_records, ret_records, mcqa_records] all_ids = [r['id'] for group in all_groups for r in group] sample_sub = pd.DataFrame({ 'id': all_ids, 'prediction': [placeholder(i) for i in all_ids], }) sample_sub.to_csv(OUTPUT_DIR / 'sample_submission.csv', index=False) print(f" sample_submission.csv: {len(sample_sub)} rows") # solution.csv with Public/Private split rng = random.Random(SEED) solution_rows = [] for group in all_groups: shuffled = list(group) rng.shuffle(shuffled) for i, r in enumerate(shuffled): solution_rows.append({ 'Id': r['id'], 'prediction': str(r['label']), 'Usage': 'Public' if i < 100 else 'Private', }) sol_df = pd.DataFrame(solution_rows) sol_df.to_csv(SOLUTION_FILE, index=False) pub = (sol_df['Usage'] == 'Public').sum() priv = (sol_df['Usage'] == 'Private').sum() print(f" solution.csv: {len(sol_df)} rows ({pub} Public, {priv} Private)") print(f" Saved to: {SOLUTION_FILE.absolute()}") print(" ⚠️ DO NOT upload solution.csv to Kaggle public dataset!") # ───────────────────────────────────────────────────────────────────────────── # Main # ───────────────────────────────────────────────────────────────────────────── if __name__ == '__main__': print("CLIP Pelatnas P2 2026 — Dataset Preparation") print(f"Output: {OUTPUT_DIR.absolute()}") OUTPUT_DIR.mkdir(parents=True, exist_ok=True) stl10_classes, zs_records, lp_records = prepare_stl10() ret_records = prepare_flickr8k() mcqa_records = prepare_scienceqa() generate_submission_files(zs_records, lp_records, ret_records, mcqa_records) print("\n" + "=" * 60) print("DONE!") print(f" Dataset : {OUTPUT_DIR.absolute()}") print(f" Solution: {SOLUTION_FILE.absolute()}") print("=" * 60)