File size: 14,333 Bytes
67d6834 |
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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
import os
import json
import re
from collections import Counter
def target_speaker(segments):
speakers = [seg.get("speaker", "UNKNOWN") for seg in segments]
most_common = Counter(speakers).most_common(1)
return most_common[0][0] if most_common else "UNKNOWN"
def pause_feature(session_id, base_dir="session_data"):
json_file = os.path.join(base_dir, session_id, f"{session_id}_transcriptionCW.json")
feature_file = os.path.join(base_dir, session_id, f"{session_id}_feature.json")
if not os.path.exists(json_file):
print(f"[Error] transcriptionCW file not found: {json_file}")
return
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)
segments = data.get("segments", [])
tgt_speaker = target_speaker(segments)
tgt_segments = [seg for seg in segments if seg.get("speaker") == tgt_speaker]
total_words = 0
total_duration = 0.0
all_pauses = []
for seg in tgt_segments:
words = seg.get("words", [])
total_words += len(words)
duration = seg.get("end", 0) - seg.get("start", 0)
total_duration += duration
pauses = seg.get("pauses", [])
all_pauses.extend(pauses)
total_pauses = len(all_pauses)
pause_durations = [p["duration"] for p in all_pauses]
pause_total_duration = sum(pause_durations)
avg_pause_duration = sum(pause_durations) / total_pauses if total_pauses > 0 else 0
longest_pause = max(pause_durations) if pause_durations else 0
pause_density_1 = (total_pauses / total_words * 100) if total_words > 0 else 0
pause_density_2 = (total_pauses / total_duration * 60) if total_duration > 0 else 0
pause_proportion = (pause_total_duration / total_duration) * 100 if total_duration > 0 else 0
pause_feat = {
"Pause Density I": round(pause_density_1, 3),
"Pause Density II": round(pause_density_2, 3),
"Pause Proportion": round(pause_proportion, 3),
"Average Pause Duration": round(avg_pause_duration, 3),
"Longest Pause Duration": round(longest_pause, 3)
}
if os.path.exists(feature_file):
with open(feature_file, "r", encoding="utf-8") as f:
feature_data = json.load(f)
else:
feature_data = {}
feature_data.setdefault("pause", []).append(pause_feat)
with open(feature_file, "w", encoding="utf-8") as f:
json.dump(feature_data, f, indent=4, ensure_ascii=False)
print(f"[Done] Pause features written to {feature_file}")
def get_syllable_weight(cv_pattern):
weight1_patterns = {'CV', 'CVC', 'VC', 'V'}
weight2_patterns = {'VCC', 'CVCC', 'CCV', 'CCVC'}
if cv_pattern in weight1_patterns:
return 1
elif cv_pattern in weight2_patterns:
return 10
else:
return 100
def syllable_feature(session_id, base_dir="session_data"):
json_file = os.path.join(base_dir, session_id, f"{session_id}_transcriptionCW.json")
feature_file = os.path.join(base_dir, session_id, f"{session_id}_feature.json")
if not os.path.exists(json_file):
print(f"[Error] transcriptionCW file not found: {json_file}")
return
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)
segments = data.get("segments", [])
tgt_speaker = target_speaker(segments)
tgt_segments = [seg for seg in segments if seg.get("speaker") == tgt_speaker]
total_duration = sum(seg["end"] - seg["start"] for seg in tgt_segments)
syllable_types = set()
total_syllables = 0
total_weight = 0
max_syllable_len = 0
word_syllable_count = {}
word_counter = 0
for seg in tgt_segments:
syllables = seg.get("syllables", [])
for syl in syllables:
cv = syl.get("CV_pattern", "")
phonemes = syl.get("phonemes", [])
syllable_types.add(cv)
total_syllables += 1
total_weight += get_syllable_weight(cv)
max_syllable_len = max(max_syllable_len, len(phonemes))
local_idx = syl.get("word_index")
global_idx = word_counter + local_idx
word_syllable_count[global_idx] = word_syllable_count.get(global_idx, 0) + 1
word_counter += len(seg.get("words", []))
all_words = []
for seg in tgt_segments:
all_words.extend(seg.get("words", []))
total_words = len(all_words)
multi_syll_2 = sum(1 for c in word_syllable_count.values() if c >= 2)
multi_syll_3 = sum(1 for c in word_syllable_count.values() if c >= 3)
feat = {
"Number of Syllable Types": len(syllable_types),
"Syllable Complexity Index": round(total_weight / total_syllables, 3) if total_syllables > 0 else 0,
"Average Syllable Rate": round(total_syllables / total_duration, 3) if total_duration > 0 else 0,
"Longest Syllable Length": max_syllable_len,
"Proportion of Multisyllabic Words I": round((multi_syll_2 / total_words) * 100, 3) if total_words > 0 else 0,
"Proportion of Multisyllabic Words II": round((multi_syll_3 / total_words) * 100, 3) if total_words > 0 else 0
}
if os.path.exists(feature_file):
with open(feature_file, "r", encoding="utf-8") as f:
feature_data = json.load(f)
else:
feature_data = {}
feature_data.setdefault("syllable", []).append(feat)
with open(feature_file, "w", encoding="utf-8") as f:
json.dump(feature_data, f, indent=4, ensure_ascii=False)
print(f"[Done] Syllable features written to {feature_file}")
def get_rep_weight(length):
if length == 1:
return 1
elif length == 2:
return 5
elif length == 3:
return 10
elif length == 4:
return 20
else:
return 40
def repetition_feature(session_id, base_dir="session_data"):
json_file = os.path.join(base_dir, session_id, f"{session_id}_transcriptionCW.json")
feature_file = os.path.join(base_dir, session_id, f"{session_id}_feature.json")
if not os.path.exists(json_file):
print(f"[Error] transcriptionCW file not found: {json_file}")
return
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)
segments = data.get("segments", [])
tgt_speaker = target_speaker(segments)
tgt_segments = [seg for seg in segments if seg.get("speaker") == tgt_speaker]
total_duration = sum(seg["end"] - seg["start"] for seg in tgt_segments)
total_words = sum(len(seg.get("words", [])) for seg in tgt_segments)
rep_count = 0
rep_weights = 0
rep_lengths = []
rep_durations = []
for seg in tgt_segments:
words = seg.get("words", [])
repetitions = seg.get("repetitions", [])
for rep in repetitions:
indices = rep.get("words", [])
if not indices:
continue
length = len(indices)
rep_lengths.append(length)
rep_weights += get_rep_weight(length)
rep_count += 1
# compute duration based on word timestamps
start_idx = indices[0]
end_idx = indices[-1]
if 0 <= start_idx < len(words) and 0 <= end_idx < len(words):
start_time = words[start_idx]["start"]
end_time = words[end_idx]["end"]
rep_durations.append(end_time - start_time)
total_rep_time = sum(rep_durations)
longest_rep = max(rep_lengths) if rep_lengths else 0
avg_rep_len = sum(rep_lengths) / len(rep_lengths) if rep_lengths else 0
rep_feat = {
"Word Repetition Index": round(rep_weights / rep_count, 3) if rep_count > 0 else 0,
"Repetition Density I": round(rep_count / total_words * 100, 3) if total_words > 0 else 0,
"Repetition Density II": round(rep_count / total_duration * 60, 3) if total_duration > 0 else 0,
"Repetition Proportion": round((total_rep_time / total_duration) * 100, 3) if total_duration > 0 else 0,
"Longest Repetition Length": longest_rep,
"Average Repetition Length": round(avg_rep_len, 3)
}
if os.path.exists(feature_file):
with open(feature_file, "r", encoding="utf-8") as f:
feature_data = json.load(f)
else:
feature_data = {}
feature_data.setdefault("repetition", []).append(rep_feat)
with open(feature_file, "w", encoding="utf-8") as f:
json.dump(feature_data, f, indent=4, ensure_ascii=False)
print(f"[Done] Repetition features written to {feature_file}")
def fillerword_feature(session_id, base_dir="session_data"):
json_file = os.path.join(base_dir, session_id, f"{session_id}_transcriptionCW.json")
feature_file = os.path.join(base_dir, session_id, f"{session_id}_feature.json")
if not os.path.exists(json_file):
print(f"[Error] transcriptionCW file not found: {json_file}")
return
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)
segments = data.get("segments", [])
tgt_speaker = target_speaker(segments)
tgt_segments = [seg for seg in segments if seg.get("speaker") == tgt_speaker]
total_duration = sum(seg["end"] - seg["start"] for seg in tgt_segments)
total_words = sum(len(seg.get("words", [])) for seg in tgt_segments)
filler_total = 0
filler_durations = []
filler_intervals = []
for seg in tgt_segments:
fillers = seg.get("fillerwords", [])
words = seg.get("words", [])
filler_total += len(fillers)
filler_durations += [fw["duration"] for fw in fillers]
if len(fillers) >= 2:
indices = []
for fw in fillers:
for i, w in enumerate(words):
if abs(w.get("start", 0) - fw["start"]) < 0.01:
indices.append(i)
break
indices.sort()
intervals = [indices[i+1] - indices[i] - 1 for i in range(len(indices)-1)]
if intervals:
filler_intervals.append(sum(intervals) / len(intervals))
avg_duration = sum(filler_durations) / len(filler_durations) if filler_durations else 0
longest_duration = max(filler_durations) if filler_durations else 0
avg_interval = sum(filler_intervals) / len(filler_intervals) if filler_intervals else 0
feat = {
"Filler Word Density I": round(filler_total / total_words * 100, 3) if total_words > 0 else 0,
"Filler Word Density II": round(filler_total / total_duration * 60, 3) if total_duration > 0 else 0,
"Filler Word Proportion": round((sum(filler_durations) / total_duration) * 100, 3) if total_duration > 0 else 0,
"Average Filler Word Duration": round(avg_duration, 3),
"Longest Filler Word Duration": round(longest_duration, 3),
"Average Filler Word Interval": round(avg_interval, 3)
}
if os.path.exists(feature_file):
with open(feature_file, "r", encoding="utf-8") as f:
feature_data = json.load(f)
else:
feature_data = {}
feature_data.setdefault("fillerword", []).append(feat)
with open(feature_file, "w", encoding="utf-8") as f:
json.dump(feature_data, f, indent=4, ensure_ascii=False)
print(f"[Done] Filler word features written to {feature_file}")
def plm_feature(session_id, base_dir="session_data"):
json_file = os.path.join(base_dir, session_id, f"{session_id}_transcriptionCW.json")
feature_file = os.path.join(base_dir, session_id, f"{session_id}_feature.json")
if not os.path.exists(json_file):
print(f"[Error] transcriptionCW file not found: {json_file}")
return
with open(json_file, "r", encoding="utf-8") as f:
data = json.load(f)
segments = data.get("segments", [])
tgt_speaker = target_speaker(segments)
tgt_segments = [seg for seg in segments if seg.get("speaker") == tgt_speaker]
sequence = ''.join(seg.get("mispronunciation", "") for seg in tgt_segments)
sequence = re.sub(r"[^CE]", "", sequence.upper())
n = len(sequence)
if n == 0:
feat = {
"Mispronunciation Density": 0,
"Normalized Transition Count": 0,
"Average Common Correct": 0,
"Average Common Error": 0,
"Longest Common Correct": 0,
"Longest Common Error": 0
}
else:
transitions = sum(1 for i in range(1, n) if sequence[i] != sequence[i - 1])
MPD = sum(1 for ch in sequence if ch == 'E') / n
NTC = transitions / n
def run_lengths(s, ch):
return [len(g) for g in re.findall(f"{ch}+", s)]
c_runs = run_lengths(sequence, 'C')
e_runs = run_lengths(sequence, 'E')
ACC = sum(c_runs) / len(c_runs) if c_runs else 0
ACE = sum(e_runs) / len(e_runs) if e_runs else 0
LCC = max(c_runs) if c_runs else 0
LCE = max(e_runs) if e_runs else 0
feat = {
"Mispronunciation Density": round(MPD, 3),
"Normalized Transition Count": round(NTC, 3),
"Average Common Correct": round(ACC, 3),
"Average Common Error": round(ACE, 3),
"Longest Common Correct": LCC,
"Longest Common Error": LCE
}
if os.path.exists(feature_file):
with open(feature_file, "r", encoding="utf-8") as f:
feature_data = json.load(f)
else:
feature_data = {}
feature_data.setdefault("plm", []).append(feat)
with open(feature_file, "w", encoding="utf-8") as f:
json.dump(feature_data, f, indent=4, ensure_ascii=False)
print(f"[Done] PLM features written to {feature_file}")
def feature_extraction(session_id, base_dir="session_data"):
feature_file = os.path.join(base_dir, session_id, f"{session_id}_feature.json")
if not os.path.exists(feature_file):
with open(feature_file, "w", encoding="utf-8") as f:
json.dump({}, f, indent=4)
pause_feature(session_id, base_dir=base_dir)
syllable_feature(session_id, base_dir=base_dir)
repetition_feature(session_id, base_dir=base_dir)
fillerword_feature(session_id, base_dir=base_dir)
plm_feature(session_id, base_dir=base_dir)
print(f"[All Analysis Done] Feature extraction complete for session {session_id}")
if __name__ == "__main__":
feature_extraction("000030")
|