nrizwan commited on
Commit
19cf4fa
·
verified ·
1 Parent(s): 4227d09

Upload convert_dataset.py

Browse files
Files changed (1) hide show
  1. convert_dataset.py +73 -0
convert_dataset.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import pandas as pd
4
+ from datasets import Dataset, DatasetDict, Image
5
+
6
+
7
+ DATA_ROOT = Path("FBHM")
8
+
9
+
10
+ def create_split(split_name):
11
+ csv_path = DATA_ROOT / f"{split_name}.csv"
12
+
13
+ print(f"Loading: {csv_path}")
14
+
15
+ df = pd.read_csv(csv_path)
16
+
17
+ # Current value:
18
+ # F1/memes/0151.jpg
19
+ #
20
+ # Convert it to:
21
+ # /full/local/path/.../FBHM/F1/memes/0151.jpg
22
+ df["img"] = df["img"].apply(
23
+ lambda x: str((DATA_ROOT / x).resolve())
24
+ )
25
+
26
+ # Check whether images actually exist
27
+ missing = [
28
+ p for p in df["img"]
29
+ if not Path(p).exists()
30
+ ]
31
+
32
+ if missing:
33
+ print(f"Missing images in {split_name}: {len(missing)}")
34
+ print(missing[:10])
35
+ raise FileNotFoundError("Some images could not be found.")
36
+
37
+ dataset = Dataset.from_pandas(
38
+ df,
39
+ preserve_index=False
40
+ )
41
+
42
+ # VERY IMPORTANT
43
+ dataset = dataset.cast_column(
44
+ "img",
45
+ Image()
46
+ )
47
+
48
+ return dataset
49
+
50
+
51
+ train_dataset = create_split("train")
52
+ test_dataset = create_split("test")
53
+
54
+
55
+ dataset = DatasetDict({
56
+ "train": train_dataset,
57
+ "test": test_dataset,
58
+ })
59
+
60
+
61
+ print(dataset)
62
+
63
+ print("\nFeatures:")
64
+ print(dataset["train"].features)
65
+
66
+ print("\nTesting first image:")
67
+ print(dataset["train"][0]["img"])
68
+
69
+
70
+ dataset.push_to_hub(
71
+ "nrizwan/FBHM",
72
+ max_shard_size="300MB"
73
+ )