File size: 2,506 Bytes
31d2139 |
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 |
"""One-off script to convert labels from .csv to json format for easier access."""
import csv
import json
from tqdm import tqdm
from pathlib import Path
def csv_to_padded_json(
csv_path: Path,
json_path: Path,
key_field: str = "image_number",
pad_width: int = 5,
dtype_map: dict[str, callable] = None
):
"""
Reads a CSV and writes a JSON dict of dicts, keyed by zero-padded key_field.
Args:
csv_path: Path to input CSV.
json_path: Path to output JSON.
key_field: Column name to use as the top‐level key (will be zero‐padded).
pad_width: Number of digits to pad key_field to.
dtype_map: Mapping column_name → type constructor (e.g. int, float, str, custom_fn).
"""
dtype_map = dtype_map or {}
result: dict[str, dict] = {}
with open(csv_path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in tqdm(reader):
raw_key = row[key_field]
padded_key = raw_key.zfill(pad_width)
entry: dict[str, object] = {}
for col, val in row.items():
if col == key_field:
continue
# If user provided a constructor for this column, use it
if col in dtype_map:
try:
entry[col] = dtype_map[col](val)
except Exception as e:
raise ValueError(f"Error converting column '{col}' value '{val}': {e}")
else:
raise Exception(f"Column {col} not specified in datatype mapping!")
# fallback: keep as string
# entry[col] = val
result[padded_key] = entry
# Write JSON
with open(json_path, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
if __name__ == "__main__":
dtype_map = {
"image_number": str,
"age_group": str,
"age_group_confidence": float,
"gender": str,
"gender_confidence": float,
"head_pitch": float,
"head_roll": float,
"head_yaw": float,
"left_eye_occluded": float,
"right_eye_occluded": float,
"glasses": str,
}
csv_to_padded_json(
csv_path=Path("labels/ffhq_aging_labels.csv"),
json_path=Path("labels/ffhq_aging_labels.json"),
key_field="image_number",
pad_width=5,
dtype_map=dtype_map,
)
print("DONE.")
|