ROCO-radiology / add_rows.py
eltorio's picture
Create add_rows.py
735bdd6 verified
!pip install datasets
from datasets import load_dataset, Dataset, Image as HFImage, concatenate_datasets
import datasets
from PIL import Image
import pandas as pd
import io
def add_rows_to_dataset(dataset, new_rows):
"""
Adds new rows to a Hugging Face dataset.
Args:
dataset: The Hugging Face dataset to add rows to.
new_rows: A list of dictionaries, where each dictionary represents a new row
and has the keys 'image', 'image_id', and 'caption'.
Returns:
The updated dataset.
"""
# Convert PIL.Image.Image objects to bytes and then back to PNG
# This will allow them to be stored within the Huggingface dataset
# and ensures the type is PIL.PngImagePlugin.PngImageFile.
for row in new_rows:
# Store the image as bytes in a buffer
image_bytes = io.BytesIO()
row['image'].save(image_bytes, format='PNG') # Save as PNG
# Replace PIL image with a new PNG image created from the bytes
row['image'] = image_bytes.getvalue()
new_dataset = Dataset.from_pandas(pd.DataFrame(new_rows)).cast_column("image", HFImage())
new_dataset.info.dataset_name = dataset.info.dataset_name
new_dataset.info.description = dataset.info.description
return concatenate_datasets([dataset,new_dataset])
# Load the dataset (replace with the correct dataset name if needed)
dataset = load_dataset("mdwiratathya/ROCO-radiology", split="train")
new_rows = [
{
"image": Image.open("radio/lux2.jpeg"),
"image_id": "RONA_00001",
"caption": "Right shoulder of a 50-year-old patient showing an anterior dislocated shoulder."
},
{
"image": Image.open("radio/lux1.jpeg"),
"image_id": "RONA_00002",
"caption": " Right shoulder of a 50-year-old patient showing an anterior dislocated shoulder"
},
{
"image": Image.open("radio/lux3.jpeg"),
"image_id": "RONA_00003",
"caption": "Right shoulder of a 50-year-old patient following a dislocated shoulder reduction"
},
{
"image": Image.open("radio/lux4.jpeg"),
"image_id": "RONA_00004",
"caption": "Right shoulder of a 50-year-old patient following a dislocated shoulder reduction"
},
]
new_dataset = add_rows_to_dataset(dataset, new_rows)
# print(f"Number of rows in the updated dataset: {len(new_dataset)}")
# print(f"Dataset information: {new_dataset.info}")
# Print some info about the updated dataset
new_dataset.push_to_hub("eltorio/ROCO-radiology")