Transformers
Daporte commited on
Commit
2cbf616
·
verified ·
1 Parent(s): fe1925b

Upload config

Browse files
Files changed (3) hide show
  1. README.md +199 -0
  2. config.json +14 -0
  3. prosody_preprocessor.py +201 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoConfig": "prosody_preprocessor.ProsodyConfig"
4
+ },
5
+ "f0_max": 500.0,
6
+ "f0_min": 65.0,
7
+ "frame_length": 20.0,
8
+ "frame_space": 5.0,
9
+ "intensity_max": 100.0,
10
+ "intensity_min": 0.0,
11
+ "model_type": "prosody_preprocessor",
12
+ "sampling_rate": 16000,
13
+ "transformers_version": "4.52.4"
14
+ }
prosody_preprocessor.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import amfm_decompy.basic_tools as basic
3
+ import amfm_decompy.pYAAPT as pYAAPT
4
+ from dataclasses import dataclass
5
+ from typing import Dict, List, Optional
6
+ import numpy as np
7
+ import torch
8
+ import dataclasses
9
+ import parselmouth
10
+ from transformers import PreTrainedModel,PretrainedConfig
11
+ from datasets import Dataset
12
+
13
+ @dataclass
14
+ class SpeakerStats:
15
+ f0_mean: float
16
+ f0_std: float
17
+ intensity_mean: float
18
+ intensity_std: float
19
+
20
+ @classmethod
21
+ def from_features(cls, f0_values: List[np.ndarray], intensity_values: List[np.ndarray]):
22
+ """Calculate stats from a list of features"""
23
+ # Convert lists to numpy arrays
24
+ f0_arrays = [np.array(f0) for f0 in f0_values]
25
+ intensity_arrays = [np.array(i) for i in intensity_values]
26
+
27
+ # Now we can use numpy operations
28
+ f0_concat = np.concatenate([f0[f0 != 0] for f0 in f0_arrays])
29
+ intensity_concat = np.concatenate(intensity_arrays)
30
+
31
+ print(f"F0 shape: {f0_concat.shape}")
32
+ print(f"Intensity shape: {intensity_concat.shape}")
33
+
34
+ return cls(
35
+ f0_mean=float(np.mean(f0_concat)),
36
+ f0_std=float(np.std(f0_concat)),
37
+ intensity_mean=float(np.mean(intensity_concat)),
38
+ intensity_std=float(np.std(intensity_concat))
39
+ )
40
+
41
+ class ProsodyConfig(PretrainedConfig):
42
+ """Configuration class for prosody preprocessing"""
43
+ model_type = "prosody_preprocessor"
44
+
45
+ def __init__(
46
+ self,
47
+ sampling_rate: int = 16000,
48
+ frame_length: float = 20.0, # in ms
49
+ frame_space: float = 5.0, # in ms
50
+ f0_min: float = 65.0,
51
+ f0_max: float = 500.0,
52
+ intensity_min: float = 0.0,
53
+ intensity_max: float = 100.0,
54
+ **kwargs
55
+ ):
56
+ super().__init__(**kwargs)
57
+ self.sampling_rate = sampling_rate
58
+ self.frame_length = frame_length
59
+ self.frame_space = frame_space
60
+ self.f0_min = f0_min
61
+ self.f0_max = f0_max
62
+ self.intensity_min = intensity_min
63
+ self.intensity_max = intensity_max
64
+
65
+ class ProsodyPreprocessor(PreTrainedModel):
66
+ config_class = ProsodyConfig
67
+
68
+ def __init__(self, config: Optional[ProsodyConfig] = None):
69
+ self.config = config or ProsodyConfig()
70
+ self.speaker_stats: Dict[str, SpeakerStats] = {}
71
+
72
+ def extract_features(self, audio):
73
+ """Extract F0 and intensity features"""
74
+ print(f"audio", audio)
75
+ audio = torch.Tensor(audio)
76
+
77
+ if audio.dim() == 1:
78
+ audio = audio.unsqueeze(0)
79
+ f0, f0_interp = self._get_f0(audio)
80
+ f0 = f0[0, 0, :]
81
+ f0_interpolated = f0_interp[0, 0, :]
82
+
83
+ # Remove first 5 frames as in original
84
+ f0 = f0[5:]
85
+ f0_interpolated = f0_interpolated[5:]
86
+
87
+ sound = parselmouth.Sound(audio.numpy(), sampling_frequency=self.config.sampling_rate, start_time=0)
88
+ print(f"Sound duration: {sound.duration} seconds")
89
+
90
+ # Extract intensity at 200Hz
91
+ intensity = sound.to_intensity(time_step=1/200.0)
92
+ print(f"Intensity duration: {intensity.duration} seconds")
93
+ intensity_values = intensity.values.T.flatten()
94
+
95
+
96
+ # Ensure same length
97
+ min_len = min(len(f0), len(intensity))
98
+ f0 = f0[:min_len]
99
+ intensity_values = intensity_values[:min_len]
100
+ # Your existing _get_f0 and intensity extraction code here
101
+ # Returns raw features
102
+ print(f"f0", f0)
103
+ return {
104
+ "f0": f0,
105
+ "f0_interp": f0_interpolated,
106
+ "intensity": intensity_values,
107
+ }
108
+
109
+ def collect_stats(self, dataset: Dataset, num_proc: int = 4, batch_size: int = 32) -> Dict[str, SpeakerStats]:
110
+ """First pass: collect speaker statistics using dataset.map"""
111
+
112
+ # Step 1: Extract features using map
113
+ def extract_features_batch(examples):
114
+ features_list = []
115
+ for audio in examples['audio']:
116
+ features = self.extract_features(audio)
117
+ features_list.append(features)
118
+
119
+ return {
120
+ 'f0': [f['f0'] for f in features_list],
121
+ 'intensity': [f['intensity'] for f in features_list],
122
+ 'speaker_id': examples['speaker_id']
123
+ }
124
+
125
+ # Extract features for all samples
126
+ features_dataset = dataset.map(
127
+ extract_features_batch,
128
+ batched=True,
129
+ batch_size=batch_size,
130
+ num_proc=num_proc,
131
+ # load_from_cache_file=False
132
+ remove_columns=dataset.column_names
133
+ )
134
+
135
+ print(f"features_dataset", features_dataset)
136
+ # Step 2: Group features by speaker
137
+ speaker_features = {}
138
+ for item in features_dataset:
139
+ print(f"item", item)
140
+ speaker_id = item['speaker_id']
141
+ if speaker_id not in speaker_features:
142
+ speaker_features[speaker_id] = {'f0': [], 'intensity': []}
143
+
144
+ speaker_features[speaker_id]['f0'].append(item['f0'])
145
+ speaker_features[speaker_id]['intensity'].append(item['intensity'])
146
+
147
+ # Step 3: Calculate stats per speaker
148
+ self.speaker_stats = {
149
+ spk: SpeakerStats.from_features(
150
+ feats['f0'],
151
+ feats['intensity']
152
+ )
153
+ for spk, feats in speaker_features.items()
154
+ }
155
+
156
+ return features_dataset, self.speaker_stats
157
+
158
+ def save_stats(self, path: str):
159
+ """Save speaker stats to file"""
160
+ stats_dict = {
161
+ spk: dataclasses.asdict(stats)
162
+ for spk, stats in self.speaker_stats.items()
163
+ }
164
+ torch.save(stats_dict, path)
165
+
166
+ @classmethod
167
+ def load_stats(cls, path: str) -> Dict[str, SpeakerStats]:
168
+ """Load speaker stats from file"""
169
+ stats_dict = torch.load(path)
170
+ return {
171
+ spk: SpeakerStats(**stats)
172
+ for spk, stats in stats_dict.items()
173
+ }
174
+ def _get_f0(self, audio: torch.Tensor):
175
+ """Extract F0 using YAAPT."""
176
+ to_pad = int(self.config.frame_length / 1000 * self.config.sampling_rate) // 2
177
+
178
+ f0s = []
179
+ f0s_interp = []
180
+
181
+ for y in audio.numpy().astype(np.float64):
182
+ y_pad = np.pad(y.squeeze(), (to_pad, to_pad), "constant", constant_values=0)
183
+ signal = basic.SignalObj(y_pad, self.config.sampling_rate)
184
+ pitch = pYAAPT.yaapt(
185
+ signal,
186
+ frame_length=self.config.frame_length,
187
+ frame_space=self.config.frame_space,
188
+ nccf_thresh1=0.25,
189
+ tda_frame_length=25.0
190
+ )
191
+ f0s_interp.append(pitch.samp_interp[None, None, :])
192
+ f0s.append(pitch.samp_values[None, None, :])
193
+
194
+ f0 = np.vstack(f0s)
195
+ f0_interp = np.vstack(f0s_interp)
196
+
197
+ # Apply frequency threshold
198
+ f0[f0 > 500] = 0
199
+ f0_interp[f0_interp > 500] = 0
200
+
201
+ return f0, f0_interp