Vadzim Kashko commited on
Commit
a356589
1 Parent(s): ea77cfd

feat: script

Browse files
Files changed (1) hide show
  1. speech-emotion-recognition-dataset.py +78 -111
speech-emotion-recognition-dataset.py CHANGED
@@ -1,37 +1,35 @@
 
 
1
  import datasets
 
 
2
  import PIL.Image
3
  import PIL.ImageOps
4
- import numpy as np
5
 
6
  _CITATION = """\
7
  @InProceedings{huggingface:dataset,
8
- title = {generated-usa-passeports-dataset},
9
  author = {TrainingDataPro},
10
  year = {2023}
11
  }
12
  """
13
 
14
  _DESCRIPTION = """\
15
- Data generation in machine learning involves creating or manipulating data
16
- to train and evaluate machine learning models. The purpose of data generation
17
- is to provide diverse and representative examples that cover a wide range of
18
- scenarios, ensuring the model's robustness and generalization.
19
- Data augmentation techniques involve applying various transformations to
20
- existing data samples to create new ones. These transformations include:
21
- random rotations, translations, scaling, flips, and more. Augmentation helps
22
- in increasing the dataset size, introducing natural variations, and improving
23
- model performance by making it more invariant to specific transformations.
24
- The dataset contains **GENERATED** USA passports, which are replicas of
25
- official passports but with randomly generated details, such as name, date of
26
- birth etc. The primary intention of generating these fake passports is to
27
- demonstrate the structure and content of a typical passport document and to
28
- train the neural network to identify this type of document.
29
- Generated passports can assist in conducting research without accessing or
30
- compromising real user data that is often sensitive and subject to privacy
31
- regulations. Synthetic data generation allows researchers to develop and
32
- refine models using simulated passport data without risking privacy leaks.
33
  """
34
- _NAME = 'generated-usa-passeports-dataset'
35
 
36
  _HOMEPAGE = f"https://huggingface.co/datasets/TrainingDataPro/{_NAME}"
37
 
@@ -40,108 +38,77 @@ _LICENSE = "cc-by-nc-nd-4.0"
40
  _DATA = f"https://huggingface.co/datasets/TrainingDataPro/{_NAME}/resolve/main/data/"
41
 
42
 
43
- def exif_transpose(img):
44
- if not img:
45
- return img
46
-
47
- exif_orientation_tag = 274
48
-
49
- # Check for EXIF data (only present on some files)
50
- if hasattr(img, "_getexif") and isinstance(
51
- img._getexif(), dict) and exif_orientation_tag in img._getexif():
52
- exif_data = img._getexif()
53
- orientation = exif_data[exif_orientation_tag]
54
-
55
- # Handle EXIF Orientation
56
- if orientation == 1:
57
- # Normal image - nothing to do!
58
- pass
59
- elif orientation == 2:
60
- # Mirrored left to right
61
- img = img.transpose(PIL.Image.FLIP_LEFT_RIGHT)
62
- elif orientation == 3:
63
- # Rotated 180 degrees
64
- img = img.rotate(180)
65
- elif orientation == 4:
66
- # Mirrored top to bottom
67
- img = img.rotate(180).transpose(PIL.Image.FLIP_LEFT_RIGHT)
68
- elif orientation == 5:
69
- # Mirrored along top-left diagonal
70
- img = img.rotate(-90,
71
- expand=True).transpose(PIL.Image.FLIP_LEFT_RIGHT)
72
- elif orientation == 6:
73
- # Rotated 90 degrees
74
- img = img.rotate(-90, expand=True)
75
- elif orientation == 7:
76
- # Mirrored along top-right diagonal
77
- img = img.rotate(90,
78
- expand=True).transpose(PIL.Image.FLIP_LEFT_RIGHT)
79
- elif orientation == 8:
80
- # Rotated 270 degrees
81
- img = img.rotate(90, expand=True)
82
-
83
- return img
84
-
85
-
86
- def load_image_file(file, mode='RGB'):
87
- # Load the image with PIL
88
- img = PIL.Image.open(file)
89
-
90
- if hasattr(PIL.ImageOps, 'exif_transpose'):
91
- # Very recent versions of PIL can do exit transpose internally
92
- img = PIL.ImageOps.exif_transpose(img)
93
- else:
94
- # Otherwise, do the exif transpose ourselves
95
- img = exif_transpose(img)
96
-
97
- img = img.convert(mode)
98
-
99
- return np.array(img)
100
-
101
-
102
- class GeneratedUsaPasseportsDataset(datasets.GeneratorBasedBuilder):
103
 
104
  def _info(self):
105
- return datasets.DatasetInfo(
106
- description=_DESCRIPTION,
107
- features=datasets.Features({
108
- 'original': datasets.Image(),
109
- 'us_pass_augmentated_1': datasets.Image(),
110
- 'us_pass_augmentated_2': datasets.Image(),
111
- 'us_pass_augmentated_3': datasets.Image()
112
- }),
113
- supervised_keys=None,
114
- homepage=_HOMEPAGE,
115
- citation=_CITATION,
116
- license=_LICENSE)
 
 
 
 
117
 
118
  def _split_generators(self, dl_manager):
119
- original = dl_manager.download_and_extract(f"{_DATA}original.zip")
120
- augmentation = dl_manager.download_and_extract(
121
- f"{_DATA}augmentation.zip")
122
  annotations = dl_manager.download(f"{_DATA}{_NAME}.csv")
123
- original = dl_manager.iter_files(original)
124
- augmentation = dl_manager.iter_files(augmentation)
125
  return [
126
  datasets.SplitGenerator(name=datasets.Split.TRAIN,
127
  gen_kwargs={
128
- "original": original,
129
- 'augmentation': augmentation,
130
  'annotations': annotations
131
  }),
132
  ]
133
 
134
- def _generate_examples(self, original, augmentation, annotations):
135
- original = list(original)
136
- augmentation = list(augmentation)
137
- augmentation = [
138
- augmentation[i:i + 3] for i in range(0, len(augmentation), 3)
139
- ]
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- for idx, (org, aug) in enumerate(zip(original, augmentation)):
142
  yield idx, {
143
- 'original': load_image_file(org),
144
- 'us_pass_augmentated_1': load_image_file(aug[0]),
145
- 'us_pass_augmentated_2': load_image_file(aug[1]),
146
- 'us_pass_augmentated_3': load_image_file(aug[2])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  }
 
1
+ from pathlib import Path
2
+
3
  import datasets
4
+ import numpy as np
5
+ import pandas as pd
6
  import PIL.Image
7
  import PIL.ImageOps
 
8
 
9
  _CITATION = """\
10
  @InProceedings{huggingface:dataset,
11
+ title = {speech-emotion-recognition-dataset},
12
  author = {TrainingDataPro},
13
  year = {2023}
14
  }
15
  """
16
 
17
  _DESCRIPTION = """\
18
+ The audio dataset consists of a collection of texts spoken with four distinct
19
+ emotions. These texts are spoken in English and represent four different
20
+ emotional states: **euphoria, joy, sadness and surprise**.
21
+ Each audio clip captures the tone, intonation, and nuances of speech as
22
+ individuals convey their emotions through their voice.
23
+ The dataset includes a diverse range of speakers, ensuring variability in age,
24
+ gender, and cultural backgrounds*, allowing for a more comprehensive
25
+ representation of the emotional spectrum.
26
+ The dataset is labeled and organized based on the emotion expressed in each
27
+ audio sample, making it a valuable resource for emotion recognition and
28
+ analysis. Researchers and developers can utilize this dataset to train and
29
+ evaluate machine learning models and algorithms, aiming to accurately
30
+ recognize and classify emotions in speech.
 
 
 
 
 
31
  """
32
+ _NAME = 'speech-emotion-recognition-dataset'
33
 
34
  _HOMEPAGE = f"https://huggingface.co/datasets/TrainingDataPro/{_NAME}"
35
 
 
38
  _DATA = f"https://huggingface.co/datasets/TrainingDataPro/{_NAME}/resolve/main/data/"
39
 
40
 
41
+ class SpeechEmotionRecognitionDataset(datasets.GeneratorBasedBuilder):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  def _info(self):
44
+ return datasets.DatasetInfo(description=_DESCRIPTION,
45
+ features=datasets.Features({
46
+ 'set_id': datasets.Value('string'),
47
+ 'euphoric': datasets.Audio(),
48
+ 'joyfully': datasets.Audio(),
49
+ 'sad': datasets.Audio(),
50
+ 'surprised': datasets.Audio(),
51
+ 'text': datasets.Value('string'),
52
+ 'gender': datasets.Value('string'),
53
+ 'age': datasets.Value('int8'),
54
+ 'country': datasets.Value('string')
55
+ }),
56
+ supervised_keys=None,
57
+ homepage=_HOMEPAGE,
58
+ citation=_CITATION,
59
+ license=_LICENSE)
60
 
61
  def _split_generators(self, dl_manager):
62
+ audio = dl_manager.download_and_extract(f"{_DATA}audio.zip")
 
 
63
  annotations = dl_manager.download(f"{_DATA}{_NAME}.csv")
64
+ # audio = dl_manager.iter_files(audio)
 
65
  return [
66
  datasets.SplitGenerator(name=datasets.Split.TRAIN,
67
  gen_kwargs={
68
+ "audio": audio,
 
69
  'annotations': annotations
70
  }),
71
  ]
72
 
73
+ def _generate_examples(self, audio, annotations):
74
+ annotations_df = pd.read_csv(annotations, sep=';')
75
+ audio = list(audio)
76
+
77
+ for idx, sub_dir in enumerate(audio):
78
+ sub_dir = Path(sub_dir)
79
+ set_id = sub_dir.name
80
+
81
+ for audio_file in sub_dir.iterdir():
82
+ if audio_file.name.startswith('euphoric'):
83
+ euphoric = audio_file
84
+ elif audio_file.name.startswith('joyfully'):
85
+ joyfully = audio_file
86
+ elif audio_file.name.startswith('sad'):
87
+ sad = audio_file
88
+ elif audio_file.name.startswith('surprised'):
89
+ surprised = audio_file
90
 
 
91
  yield idx, {
92
+ 'set_id':
93
+ set_id,
94
+ 'euphoric':
95
+ euphoric,
96
+ 'joyfully':
97
+ joyfully,
98
+ 'sad':
99
+ sad,
100
+ 'surprised':
101
+ surprised,
102
+ 'text':
103
+ annotations_df.loc[annotations_df['set_id'] == set_id]
104
+ ['text'].values[0],
105
+ 'gender':
106
+ annotations_df.loc[annotations_df['set_id'] == set_id]
107
+ ['gender'].values[0],
108
+ 'age':
109
+ annotations_df.loc[annotations_df['set_id'] == set_id]
110
+ ['age'].values[0],
111
+ 'country':
112
+ annotations_df.loc[annotations_df['set_id'] == set_id]
113
+ ['country'].values[0]
114
  }