renovation / renovation.py
rshrott's picture
Update renovation.py
2fea8b1
raw
history blame
3.16 kB
import csv
import random
import datasets
import requests
import os
from PIL import Image
from io import BytesIO
from datasets.tasks import ImageClassification
_HOMEPAGE = "https://huggingface.co/datasets/rshrott/renovation"
_CITATION = """\
@ONLINE {renovationquality,
author="Your Name",
title="Renovation Quality Dataset",
month="Your Month",
year="Your Year",
url="https://huggingface.co/datasets/rshrott/renovation"
}
"""
_DESCRIPTION = """\
This dataset contains images of various properties, along with labels indicating the quality of renovation - 'cheap', 'average', 'expensive'.
"""
_URL = "https://huggingface.co/datasets/rshrott/renovation/raw/main/labels.csv"
_NAMES = ["cheap", "average", "expensive"]
class RenovationQualityDataset(datasets.GeneratorBasedBuilder):
"""Renovation Quality Dataset."""
VERSION = datasets.Version("1.0.0")
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"image_file_path": datasets.Value("string"),
"image": datasets.Image(),
"labels": datasets.features.ClassLabel(names=_NAMES),
}
),
supervised_keys=("image", "labels"),
homepage=_HOMEPAGE,
citation=_CITATION,
task_templates=[ImageClassification(image_column="image", label_column="labels")],
)
def _split_generators(self, dl_manager):
csv_path = dl_manager.download(_URL)
with open(csv_path, "r") as f:
reader = csv.reader(f)
next(reader) # skip header
rows = list(reader)
# Shuffle rows
random.shuffle(rows)
# 80% for training, 10% for validation, 10% for testing
train_end = int(0.8 * len(rows))
val_end = int(0.9 * len(rows))
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"rows": rows[:train_end],
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"rows": rows[train_end:val_end],
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"rows": rows[val_end:],
},
),
]
def _generate_examples(self, rows):
def url_to_image(url):
response = requests.get(url)
img = Image.open(BytesIO(response.content))
return img
for id_, row in enumerate(rows):
if len(row) < 2:
print(f"Row with id {id_} has less than 2 elements: {row}")
else:
image_file_path = str(row[0])
image = url_to_image(image_file_path)
yield id_, {
'image_file_path': image_file_path,
'image': image,
'labels': row[1],
}