File size: 6,906 Bytes
e48cc21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import datasets
from huggingface_hub import HfApi
from datasets import DownloadManager, DatasetInfo
from datasets.data_files import DataFilesDict
import os
import json


# ここに設定を記入
_NAME = "mickylan2367/LoadingScriptPractice"
_EXTENSION = [".png"]
_REVISION = "main"

# _HOMEPAGE = "https://github.com/fastai/imagenette"
# プログラムを置く場所が決まったら、ここにホームページURLつける
_HOMEPAGE = "https://huggingface.co/datasets/mickylan2367/spectrogram_musicCaps"

_DESCRIPTION = f"""\
{_NAME} Datasets including spectrogram.png file from Google MusicCaps Datasets!
Using for Project Learning...
"""

# URLを取得

# class LoadingScriptPracticeConfig(datasets.BuilderConfig):
#     """BuilderConfig for Imagette."""

#     def __init__(self, data_url, metadata_urls, **kwargs):
#         """BuilderConfig for Imagette.
#         Args:
#           data_url: `string`, url to download the zip file from.
#           matadata_urls: dictionary with keys 'train' and 'validation' containing the archive metadata URLs
#           **kwargs: keyword arguments forwarded to super.
#         """
#         super(LoadingScriptPracticeConfig, self).__init__(version=datasets.Version("1.0.0"), **kwargs)
#         self.data_url = data_url
#         self.metadata_urls = metadata_urls



class LoadingScriptPractice(datasets.GeneratorBasedBuilder):

    # データのサブセットはここで用意
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="train",
            description="this Datasets is personal practice for using loadingScript. Data is from Google/MusicCaps",
            # data_url = train_data_url["train"][0],
            # metadata_urls = {
            #     "train" : train_metadata_paths["train"][0]
            # }
        ),

        # splits (dict, optional) — The mapping between split name and metadata.
        datasets.BuilderConfig(
            name="test",
            description="this Datasets is personal practice for using loadingScript. Data is from Google/MusicCaps",
            # data_url = test_data_url["test"][0],
            # metadata_urls={
            #     "test" : test_metadata_paths["test"][0]
            # }
        )
    ]

    def _info(self) -> DatasetInfo:
      return datasets.DatasetInfo(
          description = self.config.description,
          features=datasets.Features(
              {
                  "image": datasets.Image(),
                  "caption": datasets.Value("string"),
                  "data_idx": datasets.Value("int32"),
                  "number" : datasets.Value("int32"),
                  "label" : datasets.ClassLabel(
                        names=[
                            "blues",
                            "classical",
                            "country",
                            "disco",
                            "hiphop",
                            "metal",
                            "pop",
                            "reggae",
                            "rock",
                            "jazz"
                        ]
                  )
              }
          ),
          supervised_keys=("image", "caption"),
          homepage=_HOMEPAGE,
          citation= "",
          # license=_LICENSE,
          # task_templates=[ImageClassification(image_column="image", label_column="label")],
      )

    def _split_generators(self, dl_manager: DownloadManager):
        # huggingfaceのディレクトリからデータを取ってくる
        hfh_dataset_info = HfApi().dataset_info(_NAME, revision=_REVISION, timeout=100.0)

        train_metadata_paths = DataFilesDict.from_hf_repo(
            {datasets.Split.TRAIN: ["**"]},
            dataset_info=hfh_dataset_info,
            allowed_extensions=["jsonl", ".jsonl"],
        )

        test_metadata_paths = DataFilesDict.from_hf_repo(
            {datasets.Split.TEST: ["**"]},
            dataset_info=hfh_dataset_info,
            allowed_extensions=["jsonl", ".jsonl"],
        )

        # **.zipのURLをDict型として取得?
        train_data_url = DataFilesDict.from_hf_repo(
            {datasets.Split.TRAIN: ["**"]},
            dataset_info=hfh_dataset_info,
            allowed_extensions=["zip", ".zip"],
        )

        test_data_url = DataFilesDict.from_hf_repo(
            {datasets.Split.test: ["**"]},
            dataset_info=hfh_dataset_info,
            allowed_extensions=["zip", ".zip"],
        )

        # 扱いやすいように再構成
        data_path = {
            "train" : train_data_url["train"][0],
            "test" : test_data_url["test"][0]
        }

        split_metadata_paths= {
            "train" : train_metadata_paths["train"][0],
            "test" : test_metadata_paths["test"][0]
        }
        
        gs = []
        for split, files in data_path.items():
            '''
            split : "train" or "test" or "val"
            files : zip files
            '''
            # リポジトリからダウンロードしてとりあえずキャッシュしたURLリストを取得
            split_metadata_path = dl_manager.download_and_extract(split_metadata_paths[split])
            downloaded_files_path = dl_manager.download(files) 
            
            # 元のコードではzipファイルの中身を"filepath"としてそのまま_generate_exampleに引き渡している?
            gs.append(
               datasets.SplitGenerator(
                  name = split, 
                  gen_kwargs={
                     "images" : dl_manager.iter_archive(downloaded_files_path), 
                     "metadata_path": split_metadata_path
                     }
                  )
            )
        return gs

    def _generate_examples(self, images, metadata_path):
        """Generate images and captions for splits."""
        # with open(metadata_path, encoding="utf-8") as f:
        #     files_to_keep = set(f.read().split("\n"))
        file_list = list()
        caption_list = list()
        dataIDX_list = list()
        num_list = list()
        label_list = list()

        with open(metadata_path) as fin:
            for line in fin:
                data =  json.loads(line)
                file_list.append(data["file_name"])
                caption_list.append(data["caption"])
                dataIDX_list.append(data["data_idx"])
                num_list.append(data["number"])
                label_list.append(data["label"])

        for idx, (file_path, file_obj) in enumerate(images):
            yield file_path, {
                "image": {
                    "path": file_path, 
                    "bytes": file_obj.read()
                },
                "caption" : caption_list[idx],
                "data_idx" : dataIDX_list[idx],
                "number" : num_list[idx],
                "label": label_list[idx]
            }