File size: 9,627 Bytes
b3137bb
06850e7
b3137bb
 
 
06850e7
 
b3137bb
 
 
 
 
06850e7
 
 
 
b3137bb
 
 
06850e7
 
b3137bb
06850e7
 
 
 
 
b3137bb
06850e7
 
b3137bb
60e311c
b3137bb
 
 
 
 
60e311c
 
b3137bb
06850e7
b3137bb
 
 
06850e7
b3137bb
 
 
06850e7
 
 
b3137bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06850e7
 
b3137bb
06850e7
 
b3137bb
 
 
 
06850e7
b3137bb
 
06850e7
b3137bb
 
 
 
 
 
 
 
 
 
 
 
06850e7
b3137bb
 
 
 
 
06850e7
 
 
b3137bb
06850e7
 
b3137bb
 
 
 
06850e7
b3137bb
 
 
 
 
 
 
 
 
 
 
 
06850e7
b3137bb
 
 
 
 
06850e7
 
 
 
 
 
b3137bb
06850e7
 
 
 
 
 
b3137bb
 
e754f80
b3137bb
 
 
 
 
 
 
 
 
 
 
 
 
06850e7
 
b3137bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06850e7
e754f80
b3137bb
 
 
 
e754f80
b3137bb
 
 
 
 
06850e7
b3137bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3e0cd7
 
b3137bb
f3e0cd7
b3137bb
 
 
 
06850e7
b3137bb
 
 
 
 
2b361de
b3137bb
 
 
 
 
 
 
 
06850e7
4ba6af4
 
b3137bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import urllib.parse

import datasets
import pandas as pd
import requests

_CITATION = """\
@inproceedings{Wu2020not,
    title={Not only Look, but also Listen: Learning Multimodal Violence Detection under Weak Supervision},
    author={Wu, Peng and Liu, jing and Shi, Yujia and Sun, Yujia and Shao, Fangtao and Wu, Zhaoyang and Yang, Zhiwei},
    booktitle={European Conference on Computer Vision (ECCV)},
    year={2020}
}
"""

_DESCRIPTION = """\
Dataset for the paper "Not only Look, but also Listen: Learning Multimodal Violence Detection under Weak Supervision". \
The dataset is downloaded from the authors' website (https://roc-ng.github.io/XD-Violence/). Hosting this dataset on HuggingFace \
is just to make it easier for my own project to use this dataset. Please cite the original paper if you use this dataset.
"""

_NAME = "xd-violence"

_HOMEPAGE = f"https://huggingface.co/datasets/jherng/{_NAME}"

_LICENSE = "MIT"

_URL = f"https://huggingface.co/datasets/jherng/{_NAME}/resolve/main/data/"


class XDViolenceConfig(datasets.BuilderConfig):
    def __init__(self, **kwargs):
        """BuilderConfig for XD-Violence.
        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super(XDViolenceConfig, self).__init__(**kwargs)


class XDViolence(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        XDViolenceConfig(
            name="video",
            description="Video dataset",
        ),
        XDViolenceConfig(
            name="rgb",
            description="RGB visual features of the video dataset",
        ),
    ]

    DEFAULT_CONFIG_NAME = "video"
    BUILDER_CONFIG_CLASS = XDViolenceConfig

    CODE2LABEL = {
        "A": "Normal",
        "B1": "Fighting",
        "B2": "Shooting",
        "B4": "Riot",
        "B5": "Abuse",
        "B6": "Car accident",
        "G": "Explosion",
    }

    LABEL2IDX = {
        "Normal": 0,
        "Fighting": 1,
        "Shooting": 2,
        "Riot": 3,
        "Abuse": 4,
        "Car accident": 5,
        "Explosion": 6,
    }

    def _info(self):
        if self.config.name == "rgb":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "rgb_feats": datasets.Array3D(
                        shape=(None, 5, 2048),
                        dtype="float32",  # (num_frames, num_crops, feature_dim) use 5 crops by default as of now
                    ),
                    "binary_target": datasets.ClassLabel(
                        names=["Non-violence", "Violence"]
                    ),
                    "multilabel_target": datasets.Sequence(
                        datasets.ClassLabel(
                            names=[
                                "Normal",
                                "Fighting",
                                "Shooting",
                                "Riot",
                                "Abuse",
                                "Car accident",
                                "Explosion",
                            ]
                        )
                    ),
                    "frame_annotations": datasets.Sequence(
                        {
                            "start": datasets.Value("int32"),
                            "end": datasets.Value("int32"),
                        }
                    ),
                }
            )
        else:  # default = "video"
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "path": datasets.Value("string"),
                    "binary_target": datasets.ClassLabel(
                        names=["Non-violence", "Violence"]
                    ),
                    "multilabel_target": datasets.Sequence(
                        datasets.ClassLabel(
                            names=[
                                "Normal",
                                "Fighting",
                                "Shooting",
                                "Riot",
                                "Abuse",
                                "Car accident",
                                "Explosion",
                            ]
                        )
                    ),
                    "frame_annotations": datasets.Sequence(
                        {
                            "start": datasets.Value("int32"),
                            "end": datasets.Value("int32"),
                        }
                    ),
                }
            )

        return datasets.DatasetInfo(
            features=features,
            description=_DESCRIPTION,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        if self.config.name == "rgb":
            raise NotImplementedError("rgb not implemented yet")
        else:
            # Download train and test list files
            list_paths = {
                "train": dl_manager.download_and_extract(
                    urllib.parse.urljoin(_URL, "train_list.txt")
                ),
                "test": dl_manager.download_and_extract(
                    urllib.parse.urljoin(_URL, "test_list.txt")
                ),
            }

            # Download test annotation file
            annotation_path = dl_manager.download_and_extract(
                urllib.parse.urljoin(_URL, "test_annotations.txt")
            )

            # Download videos
            video_urls = {
                "train": pd.read_csv(
                    list_paths["train"],
                    header=None,
                    sep=" ",
                    usecols=[0],
                    names=["id"],
                )["id"]
                .apply(
                    lambda x: urllib.parse.quote(
                        urllib.parse.urljoin(_URL, f"video/{x.split('.mp4')[0]}.mp4"),
                        safe=":/",
                    )
                )
                .to_list(),
                "test": pd.read_csv(
                    list_paths["test"],
                    header=None,
                    sep=" ",
                    usecols=[0],
                    names=["id"],
                )["id"]
                .apply(
                    lambda x: urllib.parse.quote(
                        urllib.parse.urljoin(_URL, f"video/{x.split('.mp4')[0]}.mp4"),
                        safe=":/",
                    )
                )
                .to_list(),
            }

            video_paths = {
                "train": dl_manager.download(video_urls["train"]),
                "test": dl_manager.download(video_urls["test"]),
            }

            # Function to read annotations
            annotation_readers = {
                "train": self._read_list,
                "test": self._read_test_annotations,
            }

            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "list_path": list_paths["train"],
                        "frame_annotation_path": None,
                        "video_paths": video_paths["train"],
                        "annotation_reader": annotation_readers["train"],
                    },
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    gen_kwargs={
                        "list_path": list_paths["test"],
                        "frame_annotation_path": annotation_path,
                        "video_paths": video_paths["test"],
                        "annotation_reader": annotation_readers["test"],
                    },
                ),
            ]

    def _generate_examples(
        self, list_path, frame_annotation_path, video_paths, annotation_reader
    ):
        if self.config.name == "rgb":
            raise NotImplementedError("rgb not implemented yet")
        else:
            ann_data = annotation_reader(list_path, frame_annotation_path)

            for key, (path, annotation) in enumerate(zip(video_paths, ann_data)):
                id = annotation["id"]
                binary = annotation["binary_target"]
                multilabel = annotation["multilabel_target"]
                frame_annotations = annotation.get("frame_annotations", [])

                yield (
                    key,
                    {
                        "id": id,
                        "path": path,
                        "binary_target": binary,
                        "multilabel_target": multilabel,
                        "frame_annotations": frame_annotations,
                    },
                )

    @staticmethod
    def _read_list(list_path, frame_annotation_path):
        file_list = pd.read_csv(
            list_path, header=None, sep=" ", usecols=[0], names=["id"]
        )
        file_list["id"] = file_list["id"].apply(
            lambda x: x.split("/")[1].split(".mp4")[0]
        )
        file_list["binary_target"], file_list["multilabel_target"] = zip(
            *file_list["id"].apply(XDViolence._extract_labels)
        )

        return file_list.to_dict("records")

    @classmethod
    def _extract_labels(cls, video_id):
        """Extracts labels from the video id."""
        codes = video_id.split("_")[-1].split(".mp4")[0].split("-")

        binary = 1 if len(codes) > 1 else 0
        multilabel = [
            cls.LABEL2IDX[cls.CODE2LABEL[code]] for code in codes if code != "0"
        ]

        return binary, multilabel