Datasets:

Languages:
English
ArXiv:
License:
SynthCheX-75K / SynthCheX-75K.py
raman07's picture
CSV filename updated in the python script
e10c2cc
import datasets
import pandas as pd
import os
import ast
import zipfile # To handle the zip file
import numpy as np
# --- Dataset Metadata ---
_CITATION = """\
@article{yourarticle,
author = {Your Name / Ramanan},
title = {SynthCheX-230K: A Synthetically Generated Chest X-Ray Dataset},
journal = {Your Journal/Conference},
year = {2024},
}
"""
_DESCRIPTION = """\
SynthCheX-75K contains approximately 75,000 synthetically generated Chest X-Ray images.
The dataset is provided as a single zip file ('ALL_FILES.zip') containing all images and
a metadata CSV file ('metadata_with_generations_subset.csv').
This version provides a single 'train' split containing all images.
"""
_HOMEPAGE = "https://huggingface.co/datasets/raman07/SynthCheX-75K"
_LICENSE = "Specify your license (e.g., cc-by-nc-4.0, mit, etc.)"
# --- File Configuration ---
# Name of the zip file in your dataset repository
_ZIP_FILE_NAME = "ALL_FILES.zip"
# Path *INSIDE* the zip file to your metadata CSV
_METADATA_PATH_IN_ZIP = "ALL_FILES/metadata_with_generations_cleaned.csv"
# Path *INSIDE* the zip file to the folder containing the images
_IMAGE_FOLDER_PATH_IN_ZIP = "ALL_FILES/images/" # Must end with a slash if it's a folder prefix
# Column in your CSV that contains the image filenames (relative to _IMAGE_FOLDER_PATH_IN_ZIP)
_FILENAME_COLUMN_IN_CSV = "synthetic_filename"
_LABELS_COLUMN = "chexpert_labels"
_PROMPT_COLUMN = "annotated_prompt"
_PATHOLOGIES = ['Atelectasis', 'Cardiomegaly', 'Consolidation', 'Edema', 'Enlarged Cardiomediastinum',
'Fracture', 'Lung Lesion', 'Lung Opacity', 'No Finding', 'Pleural Effusion',
'Pleural Other', 'Pneumonia', 'Pneumothorax', 'Support Devices']
class SynthCheXDataset(datasets.GeneratorBasedBuilder):
"""SynthCheX-75K Dataset from ALL_FILES.zip (single train split)."""
VERSION = datasets.Version("1.0.0")
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"image": datasets.Image(),
"filename": datasets.Value("string"),
"prompt": datasets.Value("string"),
"labels_dict": {
"Atelectasis": datasets.Value("int32"),
"Cardiomegaly": datasets.Value("int32"),
"Consolidation": datasets.Value("int32"),
"Edema": datasets.Value("int32"),
"Enlarged Cardiomediastinum": datasets.Value("int32"),
"Fracture": datasets.Value("int32"),
"Lung Lesion": datasets.Value("int32"),
"Lung Opacity": datasets.Value("int32"),
"No Finding": datasets.Value("int32"),
"Pleural Effusion": datasets.Value("int32"),
"Pleural Other": datasets.Value("int32"),
"Pneumonia": datasets.Value("int32"),
"Pneumothorax": datasets.Value("int32"),
"Support Devices": datasets.Value("int32"),
}
}
),
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
)
def _split_generators(self, dl_manager: datasets.DownloadManager):
"""Downloads the zip file, extracts it, and defines a single train split."""
print(f"[SPLIT_GENERATORS] Attempting to download/resolve: {_ZIP_FILE_NAME}")
extracted_zip_path = dl_manager.download_and_extract(_ZIP_FILE_NAME)
print(f"[SPLIT_GENERATORS] Zip file extracted to: {extracted_zip_path}")
metadata_filepath_in_extracted = os.path.join(extracted_zip_path, _METADATA_PATH_IN_ZIP)
print(f"[SPLIT_GENERATORS] Expected metadata path in extracted: {metadata_filepath_in_extracted}")
if not os.path.exists(metadata_filepath_in_extracted):
raise FileNotFoundError(
f"Metadata file '{_METADATA_PATH_IN_ZIP}' not found inside the extracted zip at: "
f"{metadata_filepath_in_extracted}. Check _METADATA_PATH_IN_ZIP and zip contents."
)
image_dir_in_extracted = os.path.join(extracted_zip_path, _IMAGE_FOLDER_PATH_IN_ZIP)
print(f"[SPLIT_GENERATORS] Expected image folder path in extracted: {image_dir_in_extracted}")
if not os.path.isdir(image_dir_in_extracted):
raise FileNotFoundError(
f"Image folder '{_IMAGE_FOLDER_PATH_IN_ZIP}' not found or not a directory inside the extracted zip at: "
f"{image_dir_in_extracted}. Check _IMAGE_FOLDER_PATH_IN_ZIP and zip contents."
)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, # Single split named 'train'
gen_kwargs={
"metadata_filepath": metadata_filepath_in_extracted,
"image_dir": image_dir_in_extracted,
},
)
]
def _generate_examples(self, metadata_filepath, image_dir):
"""Yields all examples from the extracted data for the train split."""
print(f"[_GENERATE_EXAMPLES] Using metadata: {metadata_filepath}, image_dir: {image_dir}")
try:
df = pd.read_csv(metadata_filepath)
except Exception as e:
raise ValueError(f"Could not read metadata CSV at {metadata_filepath}: {e}")
if _FILENAME_COLUMN_IN_CSV not in df.columns:
raise ValueError(f"CSV must contain a '{_FILENAME_COLUMN_IN_CSV}' column.")
count = 0
for idx, row in df.iterrows():
image_filename = row[_FILENAME_COLUMN_IN_CSV]
image_path = os.path.join(image_dir, image_filename)
if not os.path.exists(image_path):
print(f"Warning: Image file {image_path} not found. CSV filename: {image_filename}, Base dir: {image_dir}")
continue
## Prompt
prompt = row.get(_PROMPT_COLUMN, "")
## Labels
label_vals_string = row.get(_LABELS_COLUMN, "{}")
labels_dict = ast.literal_eval(label_vals_string)
label_vals = list(labels_dict.values())
label_vals = np.array(label_vals)
label_vals = np.where(label_vals == None, 0, label_vals)
_labels_dict = dict(zip(_PATHOLOGIES, label_vals))
yield idx, {
"image": image_path,
"filename": image_filename,
"prompt": prompt,
"labels_dict": _labels_dict,
# Add other features from row if defined in _info()
}
count +=1
print(f"[_GENERATE_EXAMPLES] Yielded {count} examples for the train split.")