| from pathlib import Path | |
| import pandas as pd | |
| from datasets import Dataset, DatasetDict, Image | |
| DATA_ROOT = Path("FBHM") | |
| def create_split(split_name): | |
| csv_path = DATA_ROOT / f"{split_name}.csv" | |
| print(f"Loading: {csv_path}") | |
| df = pd.read_csv(csv_path) | |
| # Current value: | |
| # F1/memes/0151.jpg | |
| # | |
| # Convert it to: | |
| # /full/local/path/.../FBHM/F1/memes/0151.jpg | |
| df["img"] = df["img"].apply( | |
| lambda x: str((DATA_ROOT / x).resolve()) | |
| ) | |
| # Check whether images actually exist | |
| missing = [ | |
| p for p in df["img"] | |
| if not Path(p).exists() | |
| ] | |
| if missing: | |
| print(f"Missing images in {split_name}: {len(missing)}") | |
| print(missing[:10]) | |
| raise FileNotFoundError("Some images could not be found.") | |
| dataset = Dataset.from_pandas( | |
| df, | |
| preserve_index=False | |
| ) | |
| # VERY IMPORTANT | |
| dataset = dataset.cast_column( | |
| "img", | |
| Image() | |
| ) | |
| return dataset | |
| train_dataset = create_split("train") | |
| test_dataset = create_split("test") | |
| dataset = DatasetDict({ | |
| "train": train_dataset, | |
| "test": test_dataset, | |
| }) | |
| print(dataset) | |
| print("\nFeatures:") | |
| print(dataset["train"].features) | |
| print("\nTesting first image:") | |
| print(dataset["train"][0]["img"]) | |
| dataset.push_to_hub( | |
| "nrizwan/FBHM", | |
| max_shard_size="300MB" | |
| ) |