Datasets:
File size: 13,603 Bytes
917565f | 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 | #!/usr/bin/env python3
"""Build the standalone SmoothStyle Hugging Face dataset without mutating its source."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import tempfile
from collections import defaultdict
from pathlib import Path
from typing import Any
FILE_RE = re.compile(
r"^(?P<content>\d{4})_(?P<style>\d{4})_(?P<strength>0|[1-9]|10|11)\.jpg$"
)
EXPECTED_STRENGTHS = set(range(12))
def parse_args() -> argparse.Namespace:
repo_root = Path(__file__).resolve().parents[1]
default_source = repo_root.parent / "dataset"
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", type=Path, default=default_source)
parser.add_argument("--output", type=Path, default=repo_root)
return parser.parse_args()
def load_split_manifest(source: Path, split: str) -> dict[str, dict[str, str]]:
manifest_path = source / f"{split}_files.json"
with manifest_path.open("r", encoding="utf-8") as handle:
names = json.load(handle)
if not isinstance(names, list) or not all(isinstance(name, str) for name in names):
raise ValueError(f"{manifest_path} must contain a JSON list of filenames")
if len(names) != len(set(names)):
raise ValueError(f"{manifest_path} contains duplicate filenames")
grouped: dict[str, set[int]] = defaultdict(set)
pair_ids: dict[str, dict[str, str]] = {}
for name in names:
match = FILE_RE.fullmatch(name)
if match is None:
raise ValueError(f"Invalid result filename in {manifest_path}: {name}")
content_id = match.group("content")
style_id = match.group("style")
strength_id = int(match.group("strength"))
pair_id = f"{content_id}_{style_id}"
grouped[pair_id].add(strength_id)
pair_ids[pair_id] = {"content_id": content_id, "style_id": style_id}
incomplete = {
pair_id: sorted(EXPECTED_STRENGTHS - strengths)
for pair_id, strengths in grouped.items()
if strengths != EXPECTED_STRENGTHS
}
if incomplete:
first_items = list(incomplete.items())[:10]
raise ValueError(f"Incomplete groups in {manifest_path}: {first_items}")
return dict(sorted(pair_ids.items()))
def require_file(path: Path) -> Path:
if not path.is_file():
raise FileNotFoundError(path)
return path
def copy_file(source: Path, destination: Path) -> None:
require_file(source)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
def write_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
json.dump(value, handle, indent=2, ensure_ascii=False, sort_keys=True)
handle.write("\n")
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True))
handle.write("\n")
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for block in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def provenance_for_style(style_id: str, asset_path: str) -> dict[str, Any]:
if style_id.startswith("0"):
return {
"asset_id": asset_path,
"asset_type": "style",
"local_id": style_id,
"source_dataset": "Style30K",
"source_url": "https://github.com/alipay/style-tokenizer",
"source_via": "unknown-per-image",
"dataset_metadata_license": "CC-BY-4.0",
"image_license": "original-source-license-or-unknown",
"redistribution_status": "pending-rights-review",
}
if style_id.startswith("1"):
return {
"asset_id": asset_path,
"asset_type": "style",
"local_id": style_id,
"source_dataset": "SmoothStyle",
"source_via": "project-generated",
"generation_model": None,
"generation_model_license": None,
"reference_image": None,
"image_license": "project-license-pending-generation-audit",
"redistribution_status": "pending-generation-record",
}
raise ValueError(f"Unsupported style ID prefix: {style_id}")
def provenance_for_content(content_id: str, asset_path: str) -> dict[str, Any]:
return {
"asset_id": asset_path,
"asset_type": "content",
"local_id": content_id,
"source_dataset": "OmniStyle-150K",
"source_url": "https://huggingface.co/datasets/StyleXX/OmniStyle-150k",
"source_via": "randomly-selected-content-subset",
"source_original_filename": None,
"image_license": "Apache-2.0",
"license_basis": "upstream-dataset-card",
"generation_method_upstream": "FLUX",
"redistribution_status": "upstream-license-declared",
}
def build_split(
source: Path,
staging_root: Path,
split: str,
pairs: dict[str, dict[str, str]],
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
split_root = staging_root / "data" / split
rows: list[dict[str, Any]] = []
provenance: list[dict[str, Any]] = []
content_ids = sorted({pair["content_id"] for pair in pairs.values()})
style_ids = sorted({pair["style_id"] for pair in pairs.values()})
for content_id in content_ids:
relative = Path("data") / split / "content" / f"{content_id}.jpg"
copy_file(source / "content" / f"{content_id}.jpg", staging_root / relative)
provenance.append(
provenance_for_content(content_id, relative.as_posix())
)
for style_id in style_ids:
relative = Path("data") / split / "style" / f"{style_id}.jpg"
copy_file(source / "style" / f"{style_id}.jpg", staging_root / relative)
provenance.append(provenance_for_style(style_id, relative.as_posix()))
for pair_id, pair in pairs.items():
content_id = pair["content_id"]
style_id = pair["style_id"]
style_source = "Style30K" if style_id.startswith("0") else "project-generated"
for strength_id in range(1, 11):
filename = f"{pair_id}_{strength_id}.jpg"
relative_target = (
Path("data") / split / "target" / f"s{strength_id:02d}" / filename
)
copy_file(source / "result" / filename, staging_root / relative_target)
row = {
"id": f"{pair_id}_{strength_id:02d}",
"pair_id": pair_id,
"content_id": content_id,
"style_id": style_id,
"strength_id": strength_id,
"strength": strength_id / 10.0,
"content_file_name": f"content/{content_id}.jpg",
"style_file_name": f"style/{style_id}.jpg",
"target_file_name": f"target/s{strength_id:02d}/{filename}",
"style_source": style_source,
"generator": "STROTSS",
}
rows.append(row)
provenance.append(
{
"asset_id": relative_target.as_posix(),
"asset_type": "target",
"local_id": f"{pair_id}_{strength_id:02d}",
"content_id": content_id,
"style_id": style_id,
"strength_id": strength_id,
"generator": "STROTSS",
"generator_reference": "https://arxiv.org/abs/1904.12785",
"image_license": "inherits-source-rights-project-license-pending",
"redistribution_status": "pending-input-rights-review",
}
)
rows.sort(key=lambda row: (row["pair_id"], row["strength_id"]))
write_jsonl(split_root / "metadata.jsonl", rows)
stats = {
"pairs": len(pairs),
"examples": len(rows),
"content_images": len(content_ids),
"style_images": len(style_ids),
"style30k_images": sum(style_id.startswith("0") for style_id in style_ids),
"project_generated_style_images": sum(
style_id.startswith("1") for style_id in style_ids
),
"target_images": len(rows),
}
return stats, provenance
def write_checksums(staging_root: Path) -> None:
checksum_path = staging_root / "metadata" / "checksums.sha256"
files = sorted(
path
for path in staging_root.rglob("*")
if path.is_file() and path != checksum_path
)
with checksum_path.open("w", encoding="utf-8") as handle:
for path in files:
relative = path.relative_to(staging_root).as_posix()
handle.write(f"{sha256(path)} {relative}\n")
def main() -> None:
args = parse_args()
source = args.source.resolve()
output = args.output.resolve()
if source == output or source in output.parents:
raise ValueError("Output must not be inside the source dataset directory")
for required in (
source / "content",
source / "style",
source / "result",
source / "train_files.json",
source / "test_files.json",
):
if not required.exists():
raise FileNotFoundError(required)
generated_targets = [output / "data", output / "metadata"]
existing = [path for path in generated_targets if path.exists()]
if existing:
raise FileExistsError(f"Refusing to overwrite generated paths: {existing}")
train_pairs = load_split_manifest(source, "train")
test_pairs = load_split_manifest(source, "test")
overlap = set(train_pairs) & set(test_pairs)
if overlap:
raise ValueError(f"Train/test pair overlap: {sorted(overlap)[:10]}")
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".smoothstyle-build-", dir=output) as temp_dir:
staging_root = Path(temp_dir)
train_stats, train_provenance = build_split(
source, staging_root, "train", train_pairs
)
test_stats, test_provenance = build_split(
source, staging_root, "test", test_pairs
)
train_styles = {pair["style_id"] for pair in train_pairs.values()}
test_styles = {pair["style_id"] for pair in test_pairs.values()}
train_contents = {pair["content_id"] for pair in train_pairs.values()}
test_contents = {pair["content_id"] for pair in test_pairs.values()}
stats = {
"dataset": "SmoothStyle",
"schema_version": "1.0",
"splits": {"train": train_stats, "test": test_stats},
"totals": {
"pairs": len(train_pairs) + len(test_pairs),
"examples": train_stats["examples"] + test_stats["examples"],
"physical_images": (
train_stats["content_images"]
+ train_stats["style_images"]
+ train_stats["target_images"]
+ test_stats["content_images"]
+ test_stats["style_images"]
+ test_stats["target_images"]
),
"unique_style_ids": len(train_styles | test_styles),
"style_ids_shared_between_splits": len(train_styles & test_styles),
"content_ids_shared_between_splits": len(train_contents & test_contents),
},
"source_scope": {
"included": [
"dataset/content",
"dataset/style",
"dataset/result strengths 1-10",
"dataset/train_files.json",
"dataset/test_files.json",
],
"explicitly_ignored": ["dataset/src"],
"redundant_sources_not_copied": [
"dataset/train images",
"dataset/test images",
"dataset/result strengths 0 and 11",
],
"content_provenance": {
"source_dataset": "OmniStyle-150K",
"source_url": "https://huggingface.co/datasets/StyleXX/OmniStyle-150k",
"selection": "random subset of content images",
"declared_upstream_license": "Apache-2.0",
"generation_method_upstream": "FLUX",
},
},
}
write_json(staging_root / "metadata" / "dataset_stats.json", stats)
write_json(
staging_root / "metadata" / "split_manifest.json",
{
"seed": 42,
"strategy": "80/20 split over complete content-style pairs",
"train_pair_ids": sorted(train_pairs),
"test_pair_ids": sorted(test_pairs),
"style_ids_shared_between_splits": sorted(train_styles & test_styles),
},
)
provenance = sorted(
train_provenance + test_provenance, key=lambda row: row["asset_id"]
)
write_jsonl(staging_root / "metadata" / "sources.jsonl", provenance)
write_checksums(staging_root)
os.replace(staging_root / "data", output / "data")
os.replace(staging_root / "metadata", output / "metadata")
print(json.dumps(stats, indent=2, ensure_ascii=False, sort_keys=True))
if __name__ == "__main__":
main()
|