1aurent commited on
Commit
d6a496d
1 Parent(s): e28f9b1

Create script-generation.py

Browse files
Files changed (1) hide show
  1. script-generation.py +304 -0
script-generation.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ import datasets
4
+ import pandas as pd
5
+
6
+ _VERSION = "1.2.1"
7
+
8
+ _CITATION = f"""
9
+ @dataset{{unsplash-lite-dataset,
10
+ title = {{Unsplash Lite Dataset {_VERSION}}},
11
+ url = {{\\url{{https://github.com/unsplash/datasets}}}},
12
+ author = {{Unsplash}},
13
+ year = {{2023}},
14
+ month = {{May}},
15
+ day = {{02}},
16
+ }}
17
+ """
18
+
19
+ _DESCRIPTION = """
20
+ This dataset, available for commercial and noncommercial usage,
21
+ contains 25k nature-themed Unsplash photos, 25k keywords, and 1M searches.
22
+ """
23
+
24
+ _HOMEPAGE = f"https://github.com/unsplash/datasets/tree/{_VERSION}"
25
+
26
+ _URL = f"https://unsplash.com/data/lite/{_VERSION}"
27
+
28
+ _LICENSE = "Unsplash Dataset License"
29
+
30
+ _TSV = (
31
+ "collections",
32
+ "colors",
33
+ "conversions",
34
+ "keywords",
35
+ "photos",
36
+ )
37
+
38
+ _FEATURES = datasets.Features(
39
+ {
40
+ "photo": {
41
+ "id": datasets.Value("string"),
42
+ "url": datasets.Value("string"),
43
+ "image_url": datasets.Value("string"),
44
+ "submitted_at": datasets.Value("string"),
45
+ "featured": datasets.Value("bool"),
46
+ "width": datasets.Value("uint16"),
47
+ "height": datasets.Value("uint16"),
48
+ "aspect_ratio": datasets.Value("float32"),
49
+ "description": datasets.Value("string"),
50
+ "blur_hash": datasets.Value("string"),
51
+ },
52
+ "photographer": {
53
+ "username": datasets.Value("string"),
54
+ "first_name": datasets.Value("string"),
55
+ "last_name": datasets.Value("string"),
56
+ },
57
+ "exif": {
58
+ "camera_make": datasets.Value("string"),
59
+ "camera_model": datasets.Value("string"),
60
+ "iso": datasets.Value("string"),
61
+ "aperture_value": datasets.Value("string"),
62
+ "focal_length": datasets.Value("string"),
63
+ "exposure_time": datasets.Value("string"),
64
+ },
65
+ "location": {
66
+ "name": datasets.Value("string"),
67
+ "latitude": datasets.Value("float32"),
68
+ "longitude": datasets.Value("float32"),
69
+ "country": datasets.Value("string"),
70
+ "city": datasets.Value("string"),
71
+ },
72
+ "stats": {
73
+ "views": datasets.Value("uint32"),
74
+ "downloads": datasets.Value("uint32"),
75
+ },
76
+ "ai": {
77
+ "description": datasets.Value("string"),
78
+ "primary_landmark_name": datasets.Value("string"),
79
+ "primary_landmark_latitude": datasets.Value("string"),
80
+ "primary_landmark_longitude": datasets.Value("string"),
81
+ "primary_landmark_confidence": datasets.Value("string"),
82
+ },
83
+ "keywords": [
84
+ {
85
+ "keyword": datasets.Value("string"),
86
+ "ai_service_1_confidence": datasets.Value("string"),
87
+ "ai_service_2_confidence": datasets.Value("string"),
88
+ "suggested_by_user": datasets.Value("bool"),
89
+ },
90
+ ],
91
+ "collections": [
92
+ {
93
+ "collection_id": datasets.Value("string"),
94
+ "collection_title": datasets.Value("string"),
95
+ "photo_collected_at": datasets.Value("string"),
96
+ },
97
+ ],
98
+ "conversions": [
99
+ {
100
+ "converted_at": datasets.Value("string"),
101
+ "conversion_type": datasets.Value("string"),
102
+ "keyword": datasets.Value("string"),
103
+ "anonymous_user_id": datasets.Value("string"),
104
+ "conversion_country": datasets.Value("string"),
105
+ },
106
+ ],
107
+ "colors": [
108
+ {
109
+ "hex": datasets.Value("string"),
110
+ "red": datasets.Value("uint8"),
111
+ "green": datasets.Value("uint8"),
112
+ "blue": datasets.Value("uint8"),
113
+ "keyword": datasets.Value("string"),
114
+ "ai_coverage": datasets.Value("float32"),
115
+ "ai_score": datasets.Value("float32"),
116
+ },
117
+ ],
118
+ },
119
+ )
120
+
121
+ def df_withprefix(df, prefix, exclude=None):
122
+ columns = [col for col in df.columns if col.startswith(prefix)]
123
+ if exclude is not None:
124
+ columns = [col for col in columns if exclude not in col]
125
+ if "photo_id" not in columns:
126
+ columns.append("photo_id")
127
+
128
+ return df[columns].rename(columns=lambda col: col.removeprefix(prefix))
129
+
130
+ class Unsplash(datasets.GeneratorBasedBuilder):
131
+ """The Unsplash Lite dataset."""
132
+
133
+ DEFAULT_WRITER_BATCH_SIZE = 100
134
+
135
+ def _info(self):
136
+ return datasets.DatasetInfo(
137
+ features=_FEATURES,
138
+ supervised_keys=None,
139
+ description=_DESCRIPTION,
140
+ homepage=_HOMEPAGE,
141
+ license=_LICENSE,
142
+ version=_VERSION,
143
+ citation=_CITATION,
144
+ )
145
+
146
+ def _split_generators(self, dl_manager):
147
+ # raise NotImplementedError()
148
+
149
+ archive_path = Path(dl_manager.download_and_extract(_URL))
150
+
151
+ # read all tsv files
152
+ dataframes = {}
153
+ for doc in _TSV:
154
+ # read all tsv files for this document type
155
+ frames = []
156
+ for filename in archive_path.glob(f"{doc}.tsv*"):
157
+ frame = pd.read_csv(filename, sep="\t", header=0)
158
+ frames.append(frame)
159
+
160
+ # concatenate all subframes into one
161
+ concat_frames = pd.concat(frames, axis=0, ignore_index=True)
162
+
163
+ if doc != "photos":
164
+ dataframes[doc] = concat_frames
165
+ else:
166
+ # split "photos" into "photo", "photographer", "exif", "location", "stats", "ai"
167
+ dataframes["photo"] = df_withprefix(concat_frames, "photo_", "location")
168
+ dataframes["photo"]["blur_hash"] = concat_frames["blur_hash"]
169
+ dataframes["photographer"] = df_withprefix(concat_frames, "photographer_")
170
+ dataframes["exif"] = df_withprefix(concat_frames, "exif_")
171
+ dataframes["location"] = df_withprefix(concat_frames, "photo_location_")
172
+ dataframes["stats"] = df_withprefix(concat_frames, "stats_")
173
+ dataframes["ai"] = df_withprefix(concat_frames, "ai_")
174
+
175
+ # preprocess some columns
176
+ dataframes["photo"]["featured"] = dataframes["photo"]["featured"].map({"t": True, "f": False})
177
+ dataframes["keywords"]["suggested_by_user"] = dataframes["keywords"]["suggested_by_user"].map({"t": True, "f": False})
178
+
179
+ # cast columns to appropriate dtypes
180
+ for doc in dataframes.keys():
181
+ if doc in _TSV:
182
+ features = _FEATURES[doc][0]
183
+ else:
184
+ features = _FEATURES[doc]
185
+
186
+ dataframes[doc].astype({
187
+ key: features[key].dtype
188
+ for key in features.keys()
189
+ })
190
+
191
+ # groupby "photo_id" if not "photo" dataframe
192
+ for key in _TSV[:-1]:
193
+ dataframes[key] = dataframes[key].groupby("photo_id")
194
+
195
+ return [
196
+ datasets.SplitGenerator(
197
+ name=datasets.Split.TRAIN,
198
+ gen_kwargs={"dataframes": dataframes},
199
+ ),
200
+ ]
201
+
202
+ def _generate_examples(self, dataframes):
203
+ # iterate over rows of "photos" dataframe
204
+ photo_id_frames = {}
205
+ for index, row in dataframes["photo"].iterrows():
206
+ photo_id = row["id"]
207
+ photographer = dataframes["photographer"].iloc[index]
208
+ exif = dataframes["exif"].iloc[index]
209
+ location = dataframes["location"].iloc[index]
210
+ stats = dataframes["stats"].iloc[index]
211
+ ai = dataframes["ai"].iloc[index]
212
+
213
+ for key in _TSV[:-1]:
214
+ try:
215
+ photo_id_frames[key] = dataframes[key].get_group(photo_id)
216
+ except:
217
+ photo_id_frames[key] = pd.DataFrame()
218
+
219
+ data = {
220
+ "photo": {
221
+ "id": photo_id,
222
+ "url": row["url"],
223
+ "image_url": row["image_url"],
224
+ "submitted_at": row["submitted_at"],
225
+ "featured": row["featured"],
226
+ "width": row["width"],
227
+ "height": row["height"],
228
+ "aspect_ratio": row["aspect_ratio"],
229
+ "description": row["description"],
230
+ "blur_hash": row["blur_hash"],
231
+ },
232
+ "photographer": {
233
+ "username": photographer["username"],
234
+ "first_name": photographer["first_name"],
235
+ "last_name": photographer["last_name"],
236
+ },
237
+ "exif": {
238
+ "camera_make": exif["camera_make"],
239
+ "camera_model": exif["camera_model"],
240
+ "iso": exif["iso"],
241
+ "aperture_value": exif["aperture_value"],
242
+ "focal_length": exif["focal_length"],
243
+ "exposure_time": exif["exposure_time"],
244
+ },
245
+ "location": {
246
+ "name": location["name"],
247
+ "latitude": location["latitude"],
248
+ "longitude": location["longitude"],
249
+ "country": location["country"],
250
+ "city": location["city"],
251
+ },
252
+ "stats": {
253
+ "views": stats["views"],
254
+ "downloads": stats["downloads"],
255
+ },
256
+ "ai": {
257
+ "description": ai["description"],
258
+ "primary_landmark_name": ai["primary_landmark_name"],
259
+ "primary_landmark_latitude": ai["primary_landmark_latitude"],
260
+ "primary_landmark_longitude": ai["primary_landmark_longitude"],
261
+ "primary_landmark_confidence": ai["primary_landmark_confidence"],
262
+ },
263
+ "keywords": [
264
+ {
265
+ "keyword": keyword["keyword"],
266
+ "ai_service_1_confidence": keyword["ai_service_1_confidence"],
267
+ "ai_service_2_confidence": keyword["ai_service_2_confidence"],
268
+ "suggested_by_user": keyword["suggested_by_user"],
269
+ }
270
+ for _, keyword in photo_id_frames["keywords"].iterrows()
271
+ ],
272
+ "collections": [
273
+ {
274
+ "collection_id": collection["collection_id"],
275
+ "collection_title": str(collection["collection_title"]),
276
+ "photo_collected_at": collection["photo_collected_at"],
277
+ }
278
+ for _, collection in photo_id_frames["collections"].iterrows()
279
+ ],
280
+ "conversions": [
281
+ {
282
+ "converted_at": conversion["converted_at"],
283
+ "conversion_type": conversion["conversion_type"],
284
+ "keyword": conversion["keyword"],
285
+ "anonymous_user_id": conversion["anonymous_user_id"],
286
+ "conversion_country": str(conversion["conversion_country"]),
287
+ }
288
+ for _, conversion in photo_id_frames["conversions"].iterrows()
289
+ ],
290
+ "colors": [
291
+ {
292
+ "hex": color["hex"],
293
+ "red": color["red"],
294
+ "green": color["green"],
295
+ "blue": color["blue"],
296
+ "keyword": color["keyword"],
297
+ "ai_coverage": color["ai_coverage"],
298
+ "ai_score": color["ai_score"],
299
+ }
300
+ for _, color in photo_id_frames["colors"].iterrows()
301
+ ],
302
+ }
303
+
304
+ yield index, data