File size: 10,742 Bytes
4b86302
 
 
5fc19f9
edc5e1c
4b86302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a3e21f
4b86302
 
 
 
 
6263356
4b86302
 
 
 
 
 
 
 
 
 
 
5fc19f9
4b86302
 
 
 
 
 
 
 
 
 
 
 
 
 
a8a6b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b86302
 
 
 
d8b66c6
4b86302
 
 
 
 
a8a6b5c
4b86302
 
 
 
a8a6b5c
4b86302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8b66c6
 
4b86302
a8a6b5c
4b86302
 
 
 
a8a6b5c
4b86302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
edc5e1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8b66c6
 
edc5e1c
 
7fd2e4c
edc5e1c
ab126ad
edc5e1c
 
 
 
 
 
d8b66c6
 
edc5e1c
 
7fd2e4c
edc5e1c
 
ab126ad
edc5e1c
 
 
 
 
 
 
 
 
a8a6b5c
 
edc5e1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f9cbea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8a6b5c
 
 
edc5e1c
 
d8b66c6
d541e32
 
 
a8a6b5c
 
 
 
edc5e1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d541e32
edc5e1c
 
 
 
 
 
 
 
 
 
 
 
 
d541e32
edc5e1c
 
 
 
 
 
 
 
a8a6b5c
 
 
 
4509a2f
a8a6b5c
 
 
 
 
 
 
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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, 10, 2048),
                        dtype="float32",  # (num_frames, num_crops, feature_dim) use 10 crops by default as of now
                    ),
                    "binary_target": datasets.ClassLabel(
                        names=["Non-violence", "Violence"]
                    ),
                    "multilabel_targets": 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_targets": 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 annotations file
            annotation_urls = {
                "train": urllib.parse.urljoin(_URL, "train_list.txt"),
                "test": urllib.parse.urljoin(_URL, "test_annotations.txt"),
            }
            annotation_paths = {
                "train": dl_manager.download_and_extract(annotation_urls["train"]),
                "test": dl_manager.download_and_extract(annotation_urls["test"]),
            }

            # Download videos
            video_urls = {
                "train": pd.read_csv(
                    annotation_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(
                    annotation_paths["test"],
                    header=None,
                    sep=" ",
                    usecols=[0],
                    names=["id"],
                )["id"]
                .apply(
                    lambda x: urllib.parse.quote(
                        urllib.parse.urljoin(_URL, f"video/test_videos/{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_train_list,
                "test": self._read_test_annotations,
            }

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

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

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

                binary, multilabel = self.extract_labels(id)

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

    @staticmethod
    def _read_train_list(path):
        """Reads the train_list.txt file and returns a list of video ids."""

        train_list = pd.read_csv(path, header=None, sep=" ", usecols=[0], names=["id"])
        train_list["id"] = train_list["id"].apply(
            lambda x: x.split("/")[1].split(".mp4")[0]
        )
        return train_list.to_dict("records")

    @staticmethod
    def _read_test_annotations(path):
        """Reads the test_annotations.txt file and returns a list of annotations."""
        url_components = urllib.parse.urlparse(path)
        is_url = url_components.scheme == "https" or url_components.scheme == "http"

        annotations = []

        if is_url:
            with requests.get(path, stream=True) as r:
                r.raise_for_status()

                for line in r.iter_lines():
                    parts = line.decode("utf-8").strip().split(" ")

                    annotations.append(
                        {
                            "id": parts[0].split(".mp4")[0],
                            "frame_annotations": [
                                {"start": parts[start_idx], "end": parts[start_idx + 1]}
                                for start_idx in range(1, len(parts), 2)
                            ],
                        }
                    )
        else:
            with open(path, "r") as f:
                for line in f:
                    parts = line.strip().split(" ")

                    annotations.append(
                        {
                            "id": parts[0].split(".mp4")[0],
                            "frame_annotations": [
                                {"start": parts[start_idx], "end": parts[start_idx + 1]}
                                for start_idx in range(1, len(parts), 2)
                            ],
                        }
                    )

        return annotations

    @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