#!/usr/bin/env python3 """Export current, unwrapped Code2Video task inputs; no media or API calls.""" from __future__ import annotations import argparse import ast import csv import hashlib import json import math import re import sys import zipfile from collections import Counter from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path TASKS = ('t2v', 'i2v', 'v2v') VERSION = '1.2' def dumps(value): return json.dumps(value, ensure_ascii=False, sort_keys=True) def read_json(path, required=False): if not path.is_file(): if required: raise FileNotFoundError(path) return {} return json.loads(path.read_text(encoding='utf-8')) def sha_text(value): return hashlib.sha256(value.encode('utf-8')).hexdigest() def number(value): if value in (None, '') or isinstance(value, bool): return None if isinstance(value, (int, float)): return float(value) if math.isfinite(value) else None text = re.sub(r'\s*(?:seconds?|secs?|s)\s*$', '', str(value).strip(), flags=re.I) if not re.fullmatch(r'-?\d+(?:\.\d+)?(?::\d+(?:\.\d+)?){0,2}', text): return None parts = text.split(':') result = 0.0 try: for part in parts: result = result * 60 + float(part) return result if math.isfinite(result) else None except ValueError: return None def urls(value): if isinstance(value, list): return list(dict.fromkeys(u for v in value for u in urls(v))) if not isinstance(value, str): return [] return list(dict.fromkeys(re.findall(r'https?://[^\s|<>"\[\]]+', value))) def read_csv(path): if not path.is_file(): return [] with path.open(encoding='utf-8-sig', newline='') as stream: return list(csv.DictReader(stream)) def write_json(path, value): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') def write_csv(path, rows): if not rows: path.write_text('', encoding='utf-8-sig') return fields = list(dict.fromkeys(k for row in rows for k in row)) with path.open('w', encoding='utf-8-sig', newline='') as stream: writer = csv.DictWriter(stream, fieldnames=fields) writer.writeheader() writer.writerows({k: dumps(v) if isinstance(v, (list, dict)) else v for k, v in row.items()} for row in rows) def taxonomy(project): """Read literal definitions, without importing or changing project modules.""" paths = [project / 'code_video_pilot/scripts/source_quality/video_taxonomy.py', project / 'code_video_pilot/scripts/video_prompt/taxonomy.py'] result = {} for path in paths: for node in ast.parse(path.read_text()).body: if isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict): for target in node.targets: if isinstance(target, ast.Name) and target.id in {'FAMILY_NAMES', 'SUBTYPE_NAMES', 'SUBTYPE_FOCUS'}: result[target.id] = ast.literal_eval(node.value) for field in ('FAMILY_NAMES', 'SUBTYPE_NAMES'): result[field] = {key: value.rsplit(' / ', 1)[-1] for key, value in result.get(field, {}).items()} return result def collect_sample(job): collection, folder, source_number = job meta = read_json(folder / 'metadata.json', required=True) annotation = read_json(folder / 'annotation.json') task = read_json(folder / 'task.json') if collection == 'generate' else {} seed = read_json(folder / 'seed.json') if collection == 'generate' else {} payloads = {setting: read_json(folder / f'{setting}.json') for setting in TASKS if (folder / f'{setting}.json').is_file()} return {'collection': collection, 'original_id': folder.name, 'source_number': source_number, 'folder': str(folder), 'metadata': meta, 'annotation': annotation, 'task': task, 'seed': seed, 'payloads': payloads} def list_samples(input_root): indexed = read_csv(input_root / 'index.csv') order = {(r['collection'], r['sample_id']): i for i, r in enumerate(indexed)} samples = [] for collection in ('reproduce', 'generate'): directory = input_root / f'code2video-{collection if collection == "reproduce" else "gen"}' folders = [p for p in directory.iterdir() if p.is_dir() and not p.name.startswith(('_', '.'))] folders.sort(key=lambda p: (order.get((collection, p.name), len(order)), p.name)) samples.extend((collection, p, 0) for p in folders) return [(collection, folder, i + 1) for i, (collection, folder, _) in enumerate(samples)] def source_manifest(project): path = project / 'code_video_pilot/data/quality/high_score_gallery_20261004/reviewed_final/prompt_input_manifest.csv' return {r['sample_id']: r for r in read_csv(path)} def first_nonempty(*values): return next((v for v in values if v not in (None, '', [], {})), None) def label_ids(meta, source): tax = meta.get('taxonomy') or {} candidates = first_nonempty(meta.get('final_category_ids'), meta.get('subtype_ids'), [tax['subtype_id']] if tax.get('subtype_id') else None, re.findall(r'\b\d+\.\d+\b', source.get('prompt_category_ids', ''))) or [] subtypes = list(dict.fromkeys(str(x) for x in candidates if '.' in str(x))) return list(dict.fromkeys(s.split('.')[0] for s in subtypes)), subtypes def as_strings(value): if value is None: return [] if not isinstance(value, list): value = [value] return [v if isinstance(v, str) else dumps(v) for v in value] def public_metadata(value): """Drop machine-local paths; originals remain in the private snapshot.""" if isinstance(value, dict): return {k: public_metadata(v) for k, v in value.items() if not k.endswith('_path') and k not in {'path', 'source_reference_path'}} if isinstance(value, list): return [public_metadata(v) for v in value] if isinstance(value, str) and value.startswith(('/mnt/', '/Users/', 'file://')): return None return value def make_records(sample, manifest, tax, reference_sources=None): meta = sample['metadata']; task = sample['task']; seed = sample['seed'] source = manifest.get(sample['original_id'], {}) if sample['collection'] == 'reproduce' else {} annotation = first_nonempty(sample['annotation'].get('source_annotation'), task.get('source_annotation'), meta.get('source_annotation'), {}) or {} fields = meta.get('fields') or {} summary = first_nonempty(annotation.get('summary'), fields.get('brief_summary')) categories, subtypes = label_ids(meta, source) difficulty = meta.get('difficulty') or {} C = first_nonempty(fields.get('construction_complexity'), difficulty.get('target_C')) D = first_nonempty(fields.get('dynamic_complexity'), difficulty.get('target_D')) S = first_nonempty(fields.get('dependency_span'), difficulty.get('target_S')) group_id = f'C2VC-{sample["source_number"]:04d}' subjects = annotation.get('primary_subject', []) events = annotation.get('events', []) motion = annotation.get('motion_types', []) subtitle = first_nonempty(sample['annotation'].get('subtitle_segments'), task.get('subtitle_segments'), []) or [] rm = meta.get('reference_media') or {} source_urls = urls(first_nonempty(source.get('source_urls'), rm.get('source_url'), seed.get('source_url'))) common = { 'sample_id': group_id, 'sequence_index': sample['source_number'], 'collection': sample['collection'], 'available_tasks': list(sample['payloads']), 'is_paired': len(sample['payloads']) > 1, 'summary': summary, 'video_category_ids': categories, 'video_categories': [tax['FAMILY_NAMES'].get(c, c) for c in categories], 'subtype_ids': subtypes, 'subtypes': [tax['SUBTYPE_NAMES'].get(s, s).rsplit(' / ', 1)[-1] for s in subtypes], 'subjects': as_strings(subjects), 'events': as_strings(events), 'motion_types': as_strings(motion), 'subject_label_count': len(subjects) if isinstance(subjects, list) else None, 'event_count': len(events) if isinstance(events, list) else None, 'construction_complexity': C, 'dynamic_complexity': D, 'dependency_span': S, 'source_urls': source_urls, 'source_platform': source.get('platform'), 'annotation_json': dumps(annotation), 'subtitle_segments_json': dumps(subtitle), 'difficulty_evidence_json': dumps({k: v for k, v in difficulty.items() if k.endswith('_evidence') or k in ('assessment_source', 'evidence_scope')}), } result = []; mapping = []; issues = [] for setting in TASKS: if setting not in sample['payloads']: continue payload = sample['payloads'][setting] prompt = payload.get('prompt') if not isinstance(prompt, str) or not prompt.strip(): raise ValueError(f'Missing final prompt: {sample["folder"]}/{setting}.json') row = dict(common, task_id=f'{group_id}-{setting}', task=setting, prompt=prompt, prompt_sha256=sha_text(prompt), reference_url=None, reference_description=None, keyframe_timestamp_s=None, keyclip_start_s=None, keyclip_end_s=None, review_reference_start_s=None, review_reference_end_s=None, reference_time_basis=None, reference_kind=None, reference_locator_status='not_applicable', reference_metadata_json=None, task_events_json=dumps(first_nonempty(payload.get('task_events'), task.get('task_events'), sample['annotation'].get('task_events'), events)), task_attributes_json=dumps({k: v for k, v in payload.items() if k != 'prompt'})) flags = [] if not summary: flags.append('missing_summary') if not categories or not subtypes: flags.append('missing_taxonomy') if not all((C, D, S)): flags.append('missing_difficulty') if not isinstance(events, list) or not events: flags.append('missing_event_annotation') if setting != 't2v': recovered = (reference_sources or {}).get(row['task_id'], {}) row['reference_url'] = recovered.get('reference_url') or (source_urls[0] if source_urls else None) row['reference_description'] = payload.get('reference_frame_summary' if setting == 'i2v' else 'reference_clip_summary') row['reference_kind'] = 'image' if setting == 'i2v' else 'video_clip' safe_rm = public_metadata(rm) row['reference_metadata_json'] = dumps(safe_rm) review_interval = rm.get('selected_interval_in_review_video_seconds') or {} if isinstance(review_interval, dict): row['review_reference_start_s'] = number(review_interval.get('start')) row['review_reference_end_s'] = number(review_interval.get('end')) if sample['collection'] == 'reproduce': row['reference_time_basis'] = 'local_source_video_seconds' if setting == 'i2v': row['keyframe_timestamp_s'] = number(first_nonempty(payload.get('timestamp'), (meta.get('generation') or {}).get('keyframe_timestamp'))) else: row['keyclip_start_s'] = number(first_nonempty(payload.get('start_timestamp'), (meta.get('generation') or {}).get('keyclip_start'))) row['keyclip_end_s'] = number(first_nonempty(payload.get('end_timestamp'), (meta.get('generation') or {}).get('keyclip_end'))) else: timestamps = first_nonempty(rm.get('source_timestamps_seconds'), seed.get('source_timestamp_seconds')) row['reference_time_basis'] = 'original_image' if setting == 'i2v' else 'source_video_seconds' if setting == 'i2v': row['keyframe_timestamp_s'] = number(timestamps) if not isinstance(timestamps, (list, dict)) else None else: if isinstance(timestamps, dict): row['keyclip_start_s'] = number(first_nonempty(timestamps.get('start'), timestamps.get('start_s'))) row['keyclip_end_s'] = number(first_nonempty(timestamps.get('end'), timestamps.get('end_s'))) elif isinstance(timestamps, list) and len(timestamps) == 2: row['keyclip_start_s'], row['keyclip_end_s'] = map(number, timestamps) # The local source used to construct the task is the original video. # Preserve the actual selected interval recorded for that source. if setting == 'v2v' and (row['keyclip_start_s'] is None or row['keyclip_end_s'] is None): start, end = row.get('review_reference_start_s'), row.get('review_reference_end_s') if start is not None and end is not None and 0 <= start < end: row['keyclip_start_s'], row['keyclip_end_s'] = start, end if setting == 'v2v' and recovered.get('keyclip_start_s') is not None and recovered.get('keyclip_end_s') is not None: row['keyclip_start_s'] = number(recovered['keyclip_start_s']) row['keyclip_end_s'] = number(recovered['keyclip_end_s']) if not row['reference_description']: flags.append('missing_reference_description') if not row['reference_url']: flags.append('missing_reference_url') if setting == 'i2v' and sample['collection'] == 'reproduce' and row['keyframe_timestamp_s'] is None: flags.append('missing_keyframe_timestamp') if setting == 'v2v' and (row['keyclip_start_s'] is None or row['keyclip_end_s'] is None): flags.append('missing_source_clip_timestamps') times = [row[k] for k in ('keyframe_timestamp_s', 'keyclip_start_s', 'keyclip_end_s') if row[k] is not None] if any(v < 0 for v in times): flags.append('negative_reference_time') if (row['keyclip_start_s'] is not None and row['keyclip_end_s'] is not None and row['keyclip_start_s'] >= row['keyclip_end_s']): flags.append('invalid_clip_interval') row['reference_locator_status'] = 'missing_information' if any( f in flags for f in ('missing_reference_url', 'missing_keyframe_timestamp', 'missing_source_clip_timestamps', 'negative_reference_time', 'invalid_clip_interval')) else 'recorded_not_url_verified' row['data_warnings'] = flags for flag in flags: issues.append({'task_id': row['task_id'], 'sample_id': group_id, 'task': setting, 'collection': sample['collection'], 'issue': flag}) mapping.append({'task_id': row['task_id'], 'sample_id': group_id, 'sequence_index': sample['source_number'], 'original_sample_id': sample['original_id'], 'collection': sample['collection'], 'task': setting, 'input_folder': sample['folder'], 'prompt_path': str(Path(sample['folder']) / f'{setting}.json'), 'prompt_field': 'prompt', 'prompt_sha256': row['prompt_sha256'], 'annotation_path': str(Path(sample['folder']) / ('annotation.json' if sample['collection'] == 'reproduce' else 'task.json')), 'metadata_path': str(Path(sample['folder']) / 'metadata.json'), 'original_source_locator': first_nonempty(source.get('source_urls'), rm.get('source_url'), seed.get('source_url')), 'reference_media_path': str(Path(sample['folder']) / ('keyframe.png' if setting == 'i2v' else 'keyclip.mp4')) if setting != 't2v' else None}) result.append(row) return result, mapping, issues PUBLIC_COMMON_FIELDS = ( 'sample_id', 'task_id', 'task', 'prompt', 'global_description', 'video_categories', 'subtypes', 'subjects', 'motion_types', 'events', 'construction_complexity', 'dynamic_complexity', 'dependency_span', ) PUBLIC_REFERENCE_FIELDS = { 't2v': (), 'i2v': ('reference_url', 'reference_frame_summary', 'keyframe_timestamp_s'), 'v2v': ('reference_url', 'reference_clip_summary', 'keyclip_start_s', 'keyclip_end_s'), } PUBLIC_LIST_FIELDS = ('video_categories', 'subtypes', 'subjects', 'motion_types', 'events') PUBLIC_OMITTED_FIELDS = frozenset({ 'prompt_sha256', 'source_platform', 'data_warnings', 'sequence_index', 'subject_label_count', 'event_count', 'available_tasks', 'subtype_ids', 'video_category_ids', 'reference_locator_status', 'reference_metadata_json', 'difficulty_evidence_json', 'annotation_json', 'subtitle_segments_json', 'task_events_json', 'task_attributes_json', 'source_urls', 'collection', 'is_paired', 'review_reference_start_s', 'review_reference_end_s', 'reference_time_basis', }) def public_record(row): """Export complete original annotation lists and task-specific reference information.""" result = dict(row) result['global_description'] = row['summary'] if row['task'] == 'i2v': result['reference_frame_summary'] = row.get('reference_description') elif row['task'] == 'v2v': result['reference_clip_summary'] = row.get('reference_description') if result.get('keyclip_start_s') is None or result.get('keyclip_end_s') is None: start, end = row.get('review_reference_start_s'), row.get('review_reference_end_s') if start is not None and end is not None and 0 <= start < end: result['keyclip_start_s'], result['keyclip_end_s'] = start, end for key in PUBLIC_LIST_FIELDS: value = result[key] if not isinstance(value, list) or not all(isinstance(v, str) for v in value): raise ValueError(f'{key} must be a list of original string annotations') result[key] = list(value) fields = PUBLIC_COMMON_FIELDS + PUBLIC_REFERENCE_FIELDS[row['task']] published = {key: result.get(key) for key in fields} published['qa'] = row['qa'] return published def schema(setting=None): import pyarrow as pa fields = list(PUBLIC_COMMON_FIELDS) for task in (TASKS if setting is None else (setting,)): fields.extend(k for k in PUBLIC_REFERENCE_FIELDS[task] if k not in fields) numeric = {'keyframe_timestamp_s', 'keyclip_start_s', 'keyclip_end_s'} qa_type = pa.list_(pa.struct([(key, pa.string()) for key in ('section', 'dimension', 'name', 'question', 'expected_answer')])) return pa.schema([(key, pa.list_(pa.string()) if key in PUBLIC_LIST_FIELDS else pa.float64() if key in numeric else pa.string()) for key in fields] + [('qa', qa_type)]) QA_SPECIFIC = {'t2v': 'FullVideoSpecific', 'i2v': 'KeyframeSpecific', 'v2v': 'ReferenceClipSpecific'} def flatten_task_qa(qa, setting): """Preserve saved QA order and exact text; select only this task's specific section.""" result = [] shared = qa.get('SharedChecklist') if not isinstance(shared, dict): raise ValueError('QA is missing SharedChecklist') for group, dimensions in shared.items(): if not isinstance(dimensions, dict): raise ValueError(f'Invalid QA group: {group}') for dimension, item in dimensions.items(): if item is None: continue if not isinstance(item, dict) or not isinstance(item.get('question'), str) or not item['question'].strip(): raise ValueError(f'Invalid shared QA item: {group}.{dimension}') if item.get('expected_answer') not in ('Yes', 'No'): raise ValueError(f'Invalid QA expected answer: {group}.{dimension}') result.append({'section': 'SharedChecklist', 'dimension': group + '.' + dimension, 'name': item.get('name'), 'question': item['question'], 'expected_answer': item['expected_answer']}) section = QA_SPECIFIC[setting] specific = qa.get(section) if not isinstance(specific, list) or not specific: raise ValueError(f'QA is missing {section}') for item in specific: if not isinstance(item, dict) or not isinstance(item.get('question'), str) or not item['question'].strip(): raise ValueError(f'Invalid specific QA item: {section}') if item.get('expected_answer') not in ('Yes', 'No'): raise ValueError(f'Invalid QA expected answer: {section}') result.append({'section': section, 'dimension': None, 'name': item.get('name'), 'question': item['question'], 'expected_answer': item['expected_answer']}) return result def attach_task_qa(rows, mappings, input_root): """Use the same authoritative QA roots as the 9029 review page; never generate QA.""" index = {mapping['task_id']: mapping for mapping in mappings} cache = {} audit = [] for row in rows: mapping = index[row['task_id']] qa_root = 'code2video-qa-reproduce' if mapping['collection'] == 'reproduce' else 'code2video-qa-gen' source = input_root / qa_root / mapping['original_sample_id'] / 'qa.json' if source not in cache: content = source.read_bytes() cache[source] = (json.loads(content), hashlib.sha256(content).hexdigest()) qa, source_hash = cache[source] row['qa'] = flatten_task_qa(qa, row['task']) audit.append({'task_id': row['task_id'], 'source_path': str(source), 'source_sha256': source_hash, 'questions': len(row['qa']), 'specific_section': QA_SPECIFIC[row['task']]}) return audit def validate_rows(rows): seen = set(); pairs = {} for row in rows: assert row['task_id'] not in seen, row['task_id'] seen.add(row['task_id']) assert sha_text(row['prompt']) == row['prompt_sha256'] assert '/mnt/disk/' not in dumps(row), row['task_id'] assert 'data:image/' not in dumps(row) and 'data:video/' not in dumps(row) assert row['task_id'] == f'{row["sample_id"]}-{row["task"]}' pairs.setdefault(row['sample_id'], []).append(row) for sample_id, group in pairs.items(): if group[0]['collection'] == 'reproduce': assert {r['task'] for r in group} == set(TASKS), sample_id for name in ('summary', 'subjects', 'events', 'subtype_ids', 'construction_complexity', 'dynamic_complexity', 'dependency_span', 'sequence_index'): assert len({dumps(r[name]) for r in group}) == 1, (sample_id, name) def write_tables(public, rows, split=None): import pyarrow as pa import pyarrow.parquet as pq files = [] for setting in TASKS: subset = [public_record(r) for r in rows if r['task'] == setting] folder = public / (split or 'all') / setting folder.mkdir(parents=True, exist_ok=True) parquet = folder / ('train-00000-of-00001.parquet' if split == 'train' else 'data-00000-of-00001.parquet') table = pa.Table.from_pylist(subset, schema=schema(setting)) temporary = parquet.with_suffix('.parquet.tmp') pq.write_table(table, temporary, compression='zstd') restored = pq.read_table(temporary).to_pylist() assert restored == table.to_pylist(), f'Parquet roundtrip mismatch: {parquet}' temporary.replace(parquet) jsonl = folder / 'records.jsonl' jsonl.write_text(''.join(dumps(r) + '\n' for r in subset), encoding='utf-8') write_csv(folder / 'records.csv', subset) files.extend([parquet, jsonl, folder / 'records.csv']) return files def select_training_rows(rows, mappings, selected): """Require every manifest entry to resolve, and keep real pairs together.""" index = {m['task_id']: m for m in mappings} criteria = {(r.get('collection') or None, r['sample_id'], r.get('task') or None) for r in selected} matched = set(); chosen = set() for row in rows: m = index[row['task_id']] for criterion in criteria: collection, sample_id, setting = criterion if (collection in (None, m['collection']) and sample_id == m['original_sample_id'] and setting in (None, m['task'])): matched.add(criterion); chosen.add(row['task_id']) if criteria - matched: raise ValueError(f'Unresolved train manifest entries: {sorted(criteria-matched, key=str)}') if not chosen: raise ValueError('Explicit train manifest selects no tasks') paired = {r['sample_id'] for r in rows if r['task_id'] in chosen and r['collection'] == 'reproduce'} return [r for r in rows if r['task_id'] in chosen or r['sample_id'] in paired] def public_readme(rows, train_mode): template = Path(__file__).resolve().parents[1] / 'docs/README.template.md' text = template.read_text(encoding='utf-8') counts = Counter((r['collection'], r['task']) for r in rows) by_task = Counter(r['task'] for r in rows) sample = next((r for r in rows if r['task'] == 't2v' and 'Lody' in r['summary']), next(r for r in rows if r['task'] == 't2v')) siblings = {r['task']: r for r in rows if r['sample_id'] == sample['sample_id']} example = {k: sample[k] for k in ('sample_id', 'summary', 'video_categories', 'subtypes', 'subjects', 'events', 'construction_complexity', 'dynamic_complexity', 'dependency_span')} example['global_description'] = example.pop('summary') count_rows = [] for collection, label in [('reproduce', 'Source-paired'), ('generate', 'Independent')]: values = [counts[collection, t] for t in TASKS] count_rows.append('| ' + label + ' | ' + ' | '.join(map(str, values)) + ' | ' + str(sum(values)) + ' |') count_rows.append('| **Total** | ' + ' | '.join('**' + str(by_task[t]) + '**' for t in TASKS) + ' | **' + format(len(rows), ',') + '** |') conditional = [r for r in rows if r['task'] != 't2v'] missing_urls = Counter((r['collection'], r['task']) for r in conditional if 'missing_reference_url' in r['data_warnings']) missing_times = sum('missing_source_clip_timestamps' in r['data_warnings'] for r in rows) notes = (f"All {len(rows):,} tasks have their existing summaries. " f"Reference descriptions are present for {sum(bool(r['reference_description']) for r in conditional):,} " f"of {len(conditional):,} conditional tasks. " f"{sum(missing_urls.values())} conditional tasks lack recorded public reference URLs: " f"{missing_urls['generate', 'i2v']} independent I2V, " f"{missing_urls['generate', 'v2v']} independent V2V, and " f"{missing_urls['reproduce', 'i2v'] + missing_urls['reproduce', 'v2v']} source-paired tasks. " f"{missing_times} V2V tasks lack recorded original-source clip timestamps.") def timestamp(setting, key): value = siblings.get(setting, {}).get(key) return f'{value:.3f}' if value is not None else 'not recorded' replacements = { 'TOTAL_TASKS': format(len(rows), ','), 'FAMILY_COUNT': str(len({c for r in rows for c in r['video_category_ids']})), 'SUBTYPE_COUNT': str(len({s for r in rows for s in r['subtype_ids']})), 'PAIRED_GROUPS': str(len({r['sample_id'] for r in rows if r['collection'] == 'reproduce'})), 'INDEPENDENT_TASKS': str(sum(r['collection'] == 'generate' for r in rows)), 'COUNT_ROWS': '\n'.join(count_rows), 'EXAMPLE_SAMPLE_ID': sample['sample_id'], 'EXAMPLE_METADATA': json.dumps(example, ensure_ascii=False, indent=2), 'EXAMPLE_PROMPT': sample['prompt'], 'EXAMPLE_FRAME_TIME': timestamp('i2v', 'keyframe_timestamp_s'), 'EXAMPLE_CLIP_START': timestamp('v2v', 'keyclip_start_s'), 'EXAMPLE_CLIP_END': timestamp('v2v', 'keyclip_end_s'), 'COMPLETENESS_NOTES': notes, **{t.upper() + '_COUNT': str(by_task[t]) for t in TASKS}, } for key, value in replacements.items(): text = text.replace('{{' + key + '}}', value) if re.search(r'\{\{[A-Z_]+\}\}', text): raise ValueError('Unfilled dataset-card marker') return text def write_project_readmes(out, rows, train_mode): public = out / 'huggingface' card = public_readme(rows, train_mode) (public / 'README.md').write_text(card, encoding='utf-8') homepage = card.split('\n---\n', 1)[1].lstrip() homepage = homepage.replace('src="assets/', 'src="huggingface/assets/') for name in ('taxonomy.json', 'pair_index.csv', 'data_issues.csv', 'manifest.json', 'schema.json'): homepage = homepage.replace('](' + name + ')', '](huggingface/' + name + ')') homepage += ('\n---\n\nLocal archive and source-index documentation: ' '[LOCAL_EXPORT_README.md](LOCAL_EXPORT_README.md)。' 'Publish the `huggingface/` directory; keep `private/` and the private index archive local.\n') (out / 'README.md').write_text(homepage, encoding='utf-8') docs = public / 'docs'; docs.mkdir(exist_ok=True) source = Path(__file__).resolve().parents[1] / 'docs/README.template.md' (docs / 'README.template.md').write_text(source.read_text(), encoding='utf-8') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--project-root', type=Path, required=True) parser.add_argument('--output-root', type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument('--workers', type=int, default=12) parser.add_argument('--reuse-snapshot', action='store_true', help='Re-export a previously saved private input snapshot') group = parser.add_mutually_exclusive_group() group.add_argument('--hf-train-full', action='store_true', help='Explicitly use all rows as the HF train loading entry') group.add_argument('--train-manifest', type=Path, help='Explicit training subset CSV: original sample_id, optional task and collection') args = parser.parse_args() project = args.project_root.resolve(); out = args.output_root.resolve() public = out / 'huggingface'; private = out / 'private' public.mkdir(parents=True, exist_ok=True); private.mkdir(parents=True, exist_ok=True) snapshot = private / 'input_snapshot.jsonl' if args.reuse_snapshot: with snapshot.open() as stream: samples = [json.loads(line) for line in stream] else: jobs = list_samples(project / 'code2video-input') samples = [] print(f'Reading {len(jobs)} sample groups; metadata/text only; no media/API calls', flush=True) with ThreadPoolExecutor(max_workers=args.workers) as pool: for i, sample in enumerate(pool.map(collect_sample, jobs), 1): samples.append(sample) if i % 50 == 0 or i == len(jobs): print(f'Inputs {i}/{len(jobs)}', flush=True) snapshot.write_text(''.join(dumps(s) + '\n' for s in samples), encoding='utf-8') tax = taxonomy(project); manifest = source_manifest(project) reference_sources = read_json(public / 'reference_sources.json') rows = []; mappings = []; issues = [] for sample in samples: r, m, flags = make_records(sample, manifest, tax, reference_sources) rows.extend(r); mappings.extend(m); issues.extend(flags) rows.sort(key=lambda r: (r['sequence_index'], TASKS.index(r['task']))) qa_audit = attach_task_qa(rows, mappings, project / 'code2video-input') write_json(private / 'qa_export_audit.json', qa_audit) validate_rows(rows) counts = Counter(r['task'] for r in rows) print(f'Validated {len(rows)} tasks: {dict(counts)}', flush=True) files = write_tables(public, rows) train_mode = 'not yet specified; no independent training subset inferred' if args.hf_train_full: files.extend(write_tables(public, rows, 'train')) train_mode = 'HF train contains the same complete records as all; not a held-out split' elif args.train_manifest: selected = read_csv(args.train_manifest) train_rows = select_training_rows(rows, mappings, selected) files.extend(write_tables(public, train_rows, 'train')) train_mode = f'explicit manifest; {len(train_rows)} rows; reproduction pairing kept together' write_csv(private / 'source_index.csv', mappings) (private / 'source_index.jsonl').write_text(''.join(dumps(m) + '\n' for m in mappings), encoding='utf-8') write_csv(public / 'data_issues.csv', issues) write_json(public / 'taxonomy.json', tax) write_json(public / 'schema.json', {task: {f.name: str(f.type) for f in schema(task)} for task in TASKS}) write_project_readmes(out, rows, train_mode) info = {'schema_version': VERSION, 'built_at': datetime.now(timezone.utc).isoformat(), 'sample_groups': len(samples), 'task_count': len(rows), 'by_task': dict(counts), 'by_collection_and_task': dict(Counter(r['collection'] + '/' + r['task'] for r in rows)), 'train_mode': train_mode, 'warnings': dict(Counter(i['issue'] for i in issues)), 'rows_with_warnings': sum(bool(r['data_warnings']) for r in rows), 'prompt_fields': ['t2v.json:prompt', 'i2v.json:prompt', 'v2v.json:prompt'], 'media_embedded': False, 'shuffled': False, 'api_calls': 0, 'source_input_index_sha256': hashlib.sha256((project/'code2video-input/index.csv').read_bytes()).hexdigest(), 'pyarrow_version': __import__('pyarrow').__version__, 'list_presentation': 'Native lists of complete original string entries; no count replacement', 'public_omitted_fields': sorted(PUBLIC_OMITTED_FIELDS), 'documentation_asset_source': 'code2video-compass-release.zip', 'documentation_files': {str(f.relative_to(public)): {'bytes': f.stat().st_size, 'sha256': hashlib.sha256(f.read_bytes()).hexdigest()} for f in [public/'README.md', public/'docs/README.template.md', *sorted((public/'assets').glob('*'))] if f.is_file()}, 'files': {str(f.relative_to(public)): {'bytes': f.stat().st_size, 'sha256': hashlib.sha256(f.read_bytes()).hexdigest()} for f in files}} write_json(public / 'manifest.json', info) paired = [] for s in samples: sample_id = f'C2VC-{s["source_number"]:04d}' paired.append({'sample_id': sample_id, 'collection': s['collection'], **{t: f'{sample_id}-{t}' if t in s['payloads'] else None for t in TASKS}}) write_csv(public / 'pair_index.csv', paired) (out / 'LOCAL_EXPORT_README.md').write_text(f'''# Code2Video-Compass local release bundle ## Contents - {len(samples)} source or independent task groups and {len(rows)} tasks: T2V {counts['t2v']}, I2V {counts['i2v']}, V2V {counts['v2v']}. - `huggingface/`: public files, with separate Parquet, JSONL, and CSV tables for each setting, descriptions, category labels, subject types, events, and C/D/S annotations. - `huggingface/pair_index.csv`: public IDs for corresponding source-paired tasks. The original order is preserved. Independent tasks do not receive invented counterparts. - `private/source_index.csv`: public ID to original sample ID, input folder, prompt field, and local reference path. Keep this file private. - `private/input_snapshot.jsonl`: a read-only snapshot of source instructions and metadata. Keep this file private. - T2V keeps its task prompt; I2V/V2V also contain reference URLs, recorded timestamps, and reference descriptions. - Source data is preserved. Media is not embedded or copied, models are not called, and nothing is uploaded by this builder. Each task includes its applicable QA; common code-generation templates are excluded. - Descriptions reuse existing annotations. Subjects keep the original `primary_subject` type labels rather than entity counts. - Missing information remains null. See `huggingface/data_issues.csv` and `huggingface/manifest.json`. ## Train and all {train_mode} The existing half-sample CSV files define evaluation scopes, not training sets. `all/` contains the complete tasks; `train` in the HF card is a loading split. Supply an explicit manifest for a separate training subset, keeping the three settings of each source-paired group together. ## Rebuild ```bash cd {out} python scripts/build_release.py \\ --project-root {project} --workers 12 --hf-train-full # For a separate training subset, replace --hf-train-full with --train-manifest /path/to/train.csv. # Add --reuse-snapshot to rebuild from the saved input snapshot. ``` The organization of HF configs, documentation, and field descriptions follows the supplied ChartAnno example archives. Project names, licenses, figures, citations, and data from those examples are not copied into this release. ''', encoding='utf-8') script_dest = public / 'scripts' script_dest.mkdir(exist_ok=True) (script_dest / 'build_release.py').write_text(Path(__file__).read_text(), encoding='utf-8') (public / 'requirements.txt').write_text(f'pyarrow=={__import__("pyarrow").__version__}\n', encoding='utf-8') archive = out / 'code2video_compass_hf.zip' temporary_archive = archive.with_suffix('.zip.tmp') with zipfile.ZipFile(temporary_archive, 'w', compression=zipfile.ZIP_DEFLATED) as zipped: for p in sorted(public.rglob('*')): if p.is_file() and not p.name.endswith('.tmp'): assert p.suffix not in ('.mp4', '.webm') assert p.suffix not in ('.png', '.jpg', '.svg') or p.relative_to(public).parts[0] == 'assets' zipped.write(p, 'code2video_compass/' + p.relative_to(public).as_posix()) temporary_archive.replace(archive) print(json.dumps({'release': str(public), 'archive': str(archive), **info}, ensure_ascii=False, indent=2), flush=True) if __name__ == '__main__': main()