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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
import json
|
17 |
+
from pathlib import Path
|
18 |
+
from typing import Dict, List, Tuple
|
19 |
+
|
20 |
+
import datasets
|
21 |
+
import gdown
|
22 |
+
|
23 |
+
from seacrowd.utils import schemas
|
24 |
+
from seacrowd.utils.configs import SEACrowdConfig
|
25 |
+
from seacrowd.utils.constants import TASK_TO_SCHEMA, Licenses, Tasks
|
26 |
+
|
27 |
+
_CITATION = """\
|
28 |
+
@inproceedings{10.1145/3587819.3592545,
|
29 |
+
author = {Prakash, Nirmalendu and Hee, Ming Shan and Lee, Roy Ka-Wei},
|
30 |
+
title = {TotalDefMeme: A Multi-Attribute Meme dataset on Total Defence in Singapore},
|
31 |
+
year = {2023},
|
32 |
+
isbn = {9798400701481},
|
33 |
+
publisher = {Association for Computing Machinery},
|
34 |
+
address = {New York, NY, USA},
|
35 |
+
url = {https://doi.org/10.1145/3587819.3592545},
|
36 |
+
doi = {10.1145/3587819.3592545},
|
37 |
+
booktitle = {Proceedings of the 14th Conference on ACM Multimedia Systems},
|
38 |
+
pages = {369–375},
|
39 |
+
numpages = {7},
|
40 |
+
keywords = {multimodal, meme, dataset, topic clustering, stance classification},
|
41 |
+
location = {Vancouver, BC, Canada},
|
42 |
+
series = {MMSys '23}
|
43 |
+
}
|
44 |
+
"""
|
45 |
+
|
46 |
+
_DATASETNAME = "total_defense_meme"
|
47 |
+
|
48 |
+
_DESCRIPTION = """\
|
49 |
+
This is a large-scale multimodal and multi-attribute dataset containing memes
|
50 |
+
about Singapore's Total Defence policy from different social media platforms.
|
51 |
+
The type (Singaporean or generic), pillars (military, civil, economic, social,
|
52 |
+
psychological, digital, others), topics and stances (against, neutral,
|
53 |
+
supportive) of each meme are manually identified by annotators.
|
54 |
+
"""
|
55 |
+
|
56 |
+
_HOMEPAGE = "https://gitlab.com/bottle_shop/meme/TotalDefMemes"
|
57 |
+
|
58 |
+
_LANGUAGES = ["eng"]
|
59 |
+
|
60 |
+
_LICENSE = Licenses.UNKNOWN.value
|
61 |
+
|
62 |
+
_LOCAL = False
|
63 |
+
|
64 |
+
_URLS = {
|
65 |
+
"image": "https://drive.google.com/file/d/1oJIh4QQS3Idff2g6bZORstS5uBROjUUz/view?usp=share_link",
|
66 |
+
"annotations": "https://gitlab.com/bottle_shop/meme/TotalDefMemes/-/raw/main/report/annotation.json?ref_type=heads",
|
67 |
+
}
|
68 |
+
|
69 |
+
_SUPPORTED_TASKS = [Tasks.OPTICAL_CHARACTER_RECOGNITION, Tasks.IMAGE_CLASSIFICATION_MULTILABEL]
|
70 |
+
_SEACROWD_SCHEMA = {
|
71 |
+
task.value: f"seacrowd_{TASK_TO_SCHEMA[task].lower()}" for task in _SUPPORTED_TASKS
|
72 |
+
} # ocr: imtext, imc_multi: image_multi
|
73 |
+
|
74 |
+
_SOURCE_VERSION = "1.0.0"
|
75 |
+
|
76 |
+
_SEACROWD_VERSION = "2024.06.20"
|
77 |
+
|
78 |
+
|
79 |
+
class TotalDefenseMemeDataset(datasets.GeneratorBasedBuilder):
|
80 |
+
"""Multimodal dataset containing memes about Singapore's Total Defence policy"""
|
81 |
+
|
82 |
+
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
|
83 |
+
SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)
|
84 |
+
|
85 |
+
BUILDER_CONFIGS = [
|
86 |
+
SEACrowdConfig(
|
87 |
+
name=f"{_DATASETNAME}_source",
|
88 |
+
version=SOURCE_VERSION,
|
89 |
+
description=f"{_DATASETNAME} source schema",
|
90 |
+
schema="source",
|
91 |
+
subset_id=_DATASETNAME,
|
92 |
+
),
|
93 |
+
SEACrowdConfig(
|
94 |
+
name=f"{_DATASETNAME}_{_SEACROWD_SCHEMA['OCR']}",
|
95 |
+
version=SEACROWD_VERSION,
|
96 |
+
description=f"{_DATASETNAME} SEACrowd schema",
|
97 |
+
schema=_SEACROWD_SCHEMA["OCR"],
|
98 |
+
subset_id=_DATASETNAME,
|
99 |
+
),
|
100 |
+
SEACrowdConfig(
|
101 |
+
name=f"{_DATASETNAME}_{_SEACROWD_SCHEMA['IMC_MULTI']}",
|
102 |
+
version=SEACROWD_VERSION,
|
103 |
+
description=f"{_DATASETNAME} SEACrowd schema",
|
104 |
+
schema=_SEACROWD_SCHEMA["IMC_MULTI"],
|
105 |
+
subset_id=_DATASETNAME,
|
106 |
+
),
|
107 |
+
]
|
108 |
+
|
109 |
+
DEFAULT_CONFIG_NAME = f"{_DATASETNAME}_source"
|
110 |
+
|
111 |
+
def _info(self) -> datasets.DatasetInfo:
|
112 |
+
# define labelling
|
113 |
+
meme_type = ["Non_Memes", "Non_SG_Memes", "SG_Memes"]
|
114 |
+
pillar_type = [
|
115 |
+
"Social",
|
116 |
+
"Economic",
|
117 |
+
"Psychological",
|
118 |
+
"Military",
|
119 |
+
"Civil",
|
120 |
+
"Digital",
|
121 |
+
"Others",
|
122 |
+
]
|
123 |
+
stance_type = ["Against", "Neutral", "Supportive"]
|
124 |
+
|
125 |
+
if self.config.schema == "source":
|
126 |
+
features = datasets.Features(
|
127 |
+
{
|
128 |
+
"image_path": datasets.Value("string"),
|
129 |
+
"meme_type": datasets.Sequence(datasets.ClassLabel(names=meme_type)),
|
130 |
+
"text": datasets.Value("string"),
|
131 |
+
"tags": datasets.Sequence(datasets.Value("string")),
|
132 |
+
"pillar_stances": datasets.Sequence(
|
133 |
+
{
|
134 |
+
"category": datasets.ClassLabel(names=pillar_type),
|
135 |
+
"stance": datasets.Sequence(datasets.ClassLabel(names=stance_type)),
|
136 |
+
}
|
137 |
+
),
|
138 |
+
}
|
139 |
+
)
|
140 |
+
|
141 |
+
elif self.config.schema == _SEACROWD_SCHEMA["OCR"]: # all images
|
142 |
+
features = schemas.image_text_features(label_names=meme_type)
|
143 |
+
features["metadata"] = {
|
144 |
+
"tags": datasets.Sequence(datasets.Value("string")),
|
145 |
+
"pillar_stances": datasets.Sequence(
|
146 |
+
{
|
147 |
+
"category": datasets.ClassLabel(names=pillar_type),
|
148 |
+
"stance": datasets.Sequence(datasets.ClassLabel(names=stance_type)),
|
149 |
+
}
|
150 |
+
),
|
151 |
+
}
|
152 |
+
elif self.config.schema == _SEACROWD_SCHEMA["IMC_MULTI"]: # sg meme images only
|
153 |
+
features = schemas.image_multi_features(label_names=pillar_type)
|
154 |
+
features["metadata"] = {
|
155 |
+
"tags": datasets.Sequence(datasets.Value("string")),
|
156 |
+
"stances": datasets.Sequence(datasets.Sequence(datasets.ClassLabel(names=stance_type))),
|
157 |
+
}
|
158 |
+
|
159 |
+
return datasets.DatasetInfo(
|
160 |
+
description=_DESCRIPTION,
|
161 |
+
features=features,
|
162 |
+
homepage=_HOMEPAGE,
|
163 |
+
license=_LICENSE,
|
164 |
+
citation=_CITATION,
|
165 |
+
)
|
166 |
+
|
167 |
+
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
|
168 |
+
"""Returns SplitGenerators."""
|
169 |
+
# download image from gdrive
|
170 |
+
output_dir = Path.cwd() / "data" / _DATASETNAME
|
171 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
172 |
+
output_file = output_dir / f"{_DATASETNAME}.zip"
|
173 |
+
if not output_file.exists():
|
174 |
+
gdown.download(_URLS["image"], str(output_file), fuzzy=True)
|
175 |
+
else:
|
176 |
+
print(f"File already downloaded: {str(output_file)}")
|
177 |
+
# extract image data
|
178 |
+
image_dir = Path(dl_manager.extract(output_file)) / "TD_Memes"
|
179 |
+
|
180 |
+
# download annotations
|
181 |
+
annotation_path = Path(dl_manager.download(_URLS["annotations"]))
|
182 |
+
return [
|
183 |
+
datasets.SplitGenerator(
|
184 |
+
name=datasets.Split.TRAIN,
|
185 |
+
gen_kwargs={
|
186 |
+
"image_dir": image_dir,
|
187 |
+
"annotation_file": annotation_path,
|
188 |
+
},
|
189 |
+
),
|
190 |
+
]
|
191 |
+
|
192 |
+
def _generate_examples(self, image_dir: Path, annotation_file: Path) -> Tuple[int, Dict]:
|
193 |
+
"""Yields examples as (key, example) tuples."""
|
194 |
+
# load annotation
|
195 |
+
with open(annotation_file, "r", encoding="utf-8") as file:
|
196 |
+
annotation = json.load(file)
|
197 |
+
|
198 |
+
# get unique image names
|
199 |
+
image_names = sorted(
|
200 |
+
list(
|
201 |
+
set(annotation["Non_Memes"])
|
202 |
+
| set(annotation["Non_SG_Memes"])
|
203 |
+
| set(annotation["SG_Memes"])
|
204 |
+
)
|
205 |
+
)
|
206 |
+
|
207 |
+
# annotation data is a list of dict, instead of dict of image names
|
208 |
+
def get_value(image_name, list_of_dicts):
|
209 |
+
for dictionary in list_of_dicts:
|
210 |
+
if image_name in dictionary:
|
211 |
+
return dictionary[image_name]
|
212 |
+
return None
|
213 |
+
|
214 |
+
key = 0
|
215 |
+
for image_name in image_names:
|
216 |
+
# assert image exist in directory
|
217 |
+
assert (image_dir / image_name).exists(), f"Image {image_name} not found"
|
218 |
+
image_path = str(image_dir / image_name)
|
219 |
+
|
220 |
+
# get categories, can be multiple
|
221 |
+
categories = []
|
222 |
+
if image_name in annotation["Non_Memes"]:
|
223 |
+
categories.append("Non_Memes")
|
224 |
+
if image_name in annotation["Non_SG_Memes"]:
|
225 |
+
categories.append("Non_SG_Memes")
|
226 |
+
if image_name in annotation["SG_Memes"]:
|
227 |
+
categories.append("SG_Memes")
|
228 |
+
|
229 |
+
# get attributes
|
230 |
+
text = get_value(image_name, annotation["Text"])
|
231 |
+
tags = get_value(image_name, annotation["Tags"])
|
232 |
+
raw_pillar_stances = get_value(image_name, annotation["Pillar_Stances"])
|
233 |
+
|
234 |
+
# process pillar stances
|
235 |
+
pillar_stances = []
|
236 |
+
if raw_pillar_stances:
|
237 |
+
for pillar, stances in raw_pillar_stances:
|
238 |
+
category = pillar.split(" ")[0]
|
239 |
+
pillar_stances.append({"category": category, "stance": stances})
|
240 |
+
|
241 |
+
# source schema
|
242 |
+
if self.config.schema == "source":
|
243 |
+
yield key, {
|
244 |
+
"image_path": image_path,
|
245 |
+
"meme_type": categories,
|
246 |
+
"text": text,
|
247 |
+
"tags": tags,
|
248 |
+
"pillar_stances": pillar_stances,
|
249 |
+
}
|
250 |
+
key += 1
|
251 |
+
|
252 |
+
# ocr seacrowd schema
|
253 |
+
elif self.config.schema == _SEACROWD_SCHEMA["OCR"]:
|
254 |
+
yield key, {
|
255 |
+
"id": str(key),
|
256 |
+
"image_paths": [image_path],
|
257 |
+
"texts": text,
|
258 |
+
"metadata": {
|
259 |
+
"tags": tags,
|
260 |
+
"pillar_stances": pillar_stances,
|
261 |
+
},
|
262 |
+
}
|
263 |
+
key += 1
|
264 |
+
|
265 |
+
# pillar/topic classification seacrowd schema
|
266 |
+
elif self.config.schema == _SEACROWD_SCHEMA["IMC_MULTI"]:
|
267 |
+
if pillar_stances: # only those with pillar stances
|
268 |
+
yield key, {
|
269 |
+
"id": str(key),
|
270 |
+
"labels": [pillar["category"] for pillar in pillar_stances],
|
271 |
+
"image_path": image_path,
|
272 |
+
"metadata": {
|
273 |
+
"tags": tags,
|
274 |
+
"stances": [pillar["stance"] for pillar in pillar_stances],
|
275 |
+
},
|
276 |
+
}
|
277 |
+
key += 1
|