-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib_final.py
1426 lines (1279 loc) · 51.7 KB
/
lib_final.py
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""cv-tbox Dataset Compiler - Final Compilation Phase - Processes"""
###########################################################################
# lib_final.py
#
# Used by final_compile.py
#
# This script is part of Common Voice ToolBox Package
#
# github: https://github.com/HarikalarKutusu/cv-tbox-dataset-compiler
# Copyright: (c) Bülent Özden, License: AGPL v3.0
###########################################################################
# Standard Lib
from collections import Counter
from typing import Optional
from ast import literal_eval
import os
import sys
import gc
# External dependencies
import numpy as np
import pandas as pd
import cvutils as cvu # type: ignore
# Module
import const as c
import conf
from typedef import (
MultiProcessingParams,
AudioAnalysisStatsRec,
TextCorpusStatsRec,
ReportedStatsRec,
SplitStatsRec,
CharSpeedRec,
dtype_pa_str,
dtype_pa_uint32,
)
from lib import (
df_read,
df_read_safe_reported,
df_write,
gender_backmapping,
dec3,
calc_dataset_prefix,
arr2str,
list2str,
)
HERE: str = os.path.dirname(os.path.realpath(__file__))
if not HERE in sys.path:
sys.path.append(HERE)
cv: cvu.CV = cvu.CV()
VALIDATORS: list[str] = cv.validators()
PHONEMISERS: list[str] = cv.phonemisers()
# ALPHABETS: list[str] = [str(p).split(os.sep)[-2] for p in cv.alphabets()]
# SEGMENTERS: list[str] = [str(p).split(os.sep)[-2] for p in cv.segmenters()]
DF_VARIANTS: pd.DataFrame = pd.DataFrame()
DF_ACCENTS: pd.DataFrame = pd.DataFrame()
########################################################
# Text-Corpus Stats (Multi Processing Handler)
########################################################
def handle_text_corpus(ver_lc: str) -> list[TextCorpusStatsRec]:
"""Multi-Process text-corpus for a single locale"""
def handle_df(
df: pd.DataFrame, algo: str = "", sp: str = ""
) -> TextCorpusStatsRec | None:
"""Calculate stats given a dataframe containing only sentences"""
if df.shape[0] == 0:
if conf.VERBOSE:
print(
f"WARN: Skipping empty data for: Ver: {ver} - LC: {lc} - Algo: {algo} - Split: {sp}"
)
return None
# prep result record with default
res: TextCorpusStatsRec = TextCorpusStatsRec(
ver=ver,
lc=lc,
algo=algo,
sp=sp,
has_val=has_validator,
has_phon=has_phonemiser,
)
# init counters
token_counter: Counter = Counter()
grapheme_counter: Counter = Counter()
phoneme_counter: Counter = Counter()
# decide on saving
do_save: bool = False
if conf.SAVE_LEVEL == c.SAVE_LEVEL_DETAILED:
do_save = True
elif conf.SAVE_LEVEL == c.SAVE_LEVEL_DEFAULT and algo == "" and sp == "":
do_save = True
elif (
conf.SAVE_LEVEL == c.SAVE_LEVEL_DEFAULT
and algo == "s1"
and sp in ["validated", "train", "dev", "test"]
):
do_save = True
# see: https://github.com/pylint-dev/pylint/issues/3956
_ser: pd.Series[int] = pd.Series() # pylint: disable=unsubscriptable-object
_df2: pd.DataFrame = pd.DataFrame()
_arr: np.ndarray
fn: str
# validator dependent
if has_validator:
token_counter.update(
w
for ww in df["tokens"].dropna().apply(literal_eval).to_list()
for w in ww
)
# word_cnt stats
_ser = df["word_cnt"].dropna()
if _ser.shape[0] > 0:
res.w_sum = _ser.sum()
res.w_avg = dec3(_ser.mean())
res.w_med = _ser.median()
res.w_std = dec3(_ser.std(ddof=0))
# Calc word count distribution
_arr = np.fromiter(
_ser.apply(int).reset_index(drop=True).to_list(), int
)
_hist = np.histogram(_arr, bins=c.BINS_WORDS)
res.w_freq = _hist[0].tolist()[1:] # type: ignore
# token_cnt stats
_df2 = pd.DataFrame(token_counter.most_common(), columns=c.FIELDS_TOKENS)
# "token", "count"
res.t_sum = _df2.shape[0]
_ser = _df2["count"].dropna()
if _ser.shape[0] > 0:
res.t_avg = dec3(_ser.mean())
res.t_med = _ser.median()
res.t_std = dec3(_ser.std(ddof=0))
# Token/word repeat distribution
_arr = np.fromiter(
_df2["count"].dropna().apply(int).reset_index(drop=True).to_list(),
int,
)
_hist = np.histogram(_arr, bins=c.BINS_TOKENS)
res.t_freq = _hist[0].tolist()[1:] # type: ignore
if do_save:
fn = os.path.join(
tc_anal_dir,
f"{c.TOKENS_FN}_{algo}_{sp}.tsv".replace("__", "_").replace(
"_.", "."
),
)
df_write(_df2, fn)
# phonemiser dependent
if has_phonemiser:
_ = [phoneme_counter.update(p) for p in df["phonemised"].dropna().tolist()]
# PHONEMES
_df2 = pd.DataFrame(
phoneme_counter.most_common(), columns=c.FIELDS_PHONEMES
)
_values = _df2.values.tolist()
res.p_cnt = len(_values)
_values = _values[:100]
res.p_items = list2str([x[0] for x in _values])
res.p_freq = [x[1] for x in _values] # type: ignore
if do_save:
fn = os.path.join(
tc_anal_dir,
f"{c.PHONEMES_FN}_{algo}_{sp}.tsv".replace("__", "_").replace(
"_.", "."
),
)
df_write(_df2, fn)
# simpler values which are independent
res.s_cnt = df.shape[0]
res.val = df["valid"].dropna().astype(int).sum()
res.uq_s = df["sentence"].dropna().unique().shape[0]
res.uq_n = df["normalized"].dropna().unique().shape[0]
# char_cnt stats
_ser = df["char_cnt"].dropna()
if _ser.shape[0] > 0:
res.c_sum = _ser.sum()
res.c_avg = dec3(_ser.mean())
res.c_med = _ser.median()
res.c_std = dec3(_ser.std(ddof=0))
# Calc character length distribution
_arr = np.fromiter(_ser.apply(int).reset_index(drop=True).to_list(), int)
_sl_bins: list[int] = (
c.BINS_CHARS_SHORT
if res.c_avg < c.CHARS_BIN_THRESHOLD
else c.BINS_CHARS_LONG
)
_hist = np.histogram(_arr, bins=_sl_bins)
res.c_freq = _hist[0].tolist() # type: ignore
# GRAPHEMES
_ = [grapheme_counter.update(s) for s in df["sentence"].dropna().tolist()]
_df2 = pd.DataFrame(grapheme_counter.most_common(), columns=c.FIELDS_GRAPHEMES)
_values = _df2.values.tolist()
res.g_cnt = len(_values)
_values = _values[:100]
res.g_items = list2str([x[0] for x in _values])
res.g_freq = [x[1] for x in _values] # type: ignore
if do_save:
fn = os.path.join(
tc_anal_dir,
f"{c.GRAPHEMES_FN}_{algo}_{sp}.tsv".replace("__", "_").replace(
"_.", "."
),
)
df_write(_df2, fn)
# SENTENCE DOMAINS
# for < CV v17.0, they will be "nodata", after that new items are added
# for CV v17.0, there will be single instance (or empty)
# [TODO] for CV >= v18.0, it can be comma delimited list of max 3 domains
_df2 = (
df["sentence_domain"]
.astype(dtype_pa_str)
# .fillna(c.NODATA)
.dropna()
.value_counts()
.to_frame()
.reset_index()
.reindex(columns=c.FIELDS_SENTENCE_DOMAINS)
# .sort_values("count", ascending=False)
).astype(c.FIELDS_SENTENCE_DOMAINS)
# prep counters & loop for comma delimited multi-domains
counters: dict[str, int] = {}
# domain_list: list[str] = c.CV_DOMAINS_V17 if ver == "17.0" else c.CV_DOMAINS
domain_list: list[str] = c.CV_DOMAINS
for dom in domain_list:
counters[dom] = 0
for _, row in _df2.iterrows():
domains: list[str] = row.iloc[0].split(",")
for dom in domains:
counters[c.CV_DOMAIN_MAPPER[dom]] += row.iloc[1]
res.dom_cnt = len([tup[0] for tup in counters.items() if tup[1] > 0])
res.dom_items = [tup[0] for tup in counters.items() if tup[1] > 0]
res.dom_freq = [tup[1] for tup in counters.items() if tup[1] > 0]
if do_save:
fn = os.path.join(
tc_anal_dir,
f"{c.DOMAINS_FN}_{algo}_{sp}.tsv".replace("__", "_").replace("_.", "."),
)
df_write(_df2, fn)
# return result
return res
def handle_tc_global(df_base_ver_tc: pd.DataFrame) -> None:
"""Calculate stats using the whole text corpus from server/data"""
# res: TextCorpusStatsRec | None = handle_df(
# df_read(base_tc_file).reset_index(drop=True)[["sentence"]]
# )
_res: TextCorpusStatsRec | None = handle_df(df_base_ver_tc)
if _res is not None:
results.append(_res)
def handle_tc_split(df_base_ver_tc: pd.DataFrame, sp: str, algo: str = "") -> None:
"""Calculate stats using sentence data in a algo - bucket/split"""
_fn: str = os.path.join(conf.SRC_BASE_DIR, algo, ver_dir, lc, f"{sp}.tsv")
if not os.path.isfile(_fn):
if conf.VERBOSE:
print(f"WARN: No such split file for: {ver} - {lc} - {algo} - {sp}")
return
_res: TextCorpusStatsRec | None = None
df: pd.DataFrame
if float(ver) >= 17.0:
# For newer versions, just use the sentence_id
sentence_id_list: list[str] = (
df_read(_fn)
.reset_index(drop=True)["sentence_id"]
.dropna()
.drop_duplicates()
.to_list()
)
df = df_base_ver_tc[df_base_ver_tc["sentence_id"].isin(sentence_id_list)]
_res = handle_df(df, algo=algo, sp=sp)
else:
# For older versions, use the sentence
sentence_list: list[str] = (
df_read(_fn)
.reset_index(drop=True)["sentence"]
.dropna()
.drop_duplicates()
.to_list()
)
df = df_base_ver_tc[df_base_ver_tc["sentence"].isin(sentence_list)]
_res = handle_df(df, algo=algo, sp=sp)
if _res is not None:
results.append(_res)
#
# handle_df main
#
ver: str = ver_lc.split("|")[0]
lc: str = ver_lc.split("|")[1]
ver_dir: str = calc_dataset_prefix(ver)
results: list[TextCorpusStatsRec] = []
base_tc_file: str = os.path.join(
conf.DATA_BASE_DIR, c.TC_DIRNAME, lc, f"{c.TEXT_CORPUS_FN}.tsv"
)
ver_tc_inx_file: str = os.path.join(
conf.DATA_BASE_DIR, c.TC_DIRNAME, lc, f"{c.TEXT_CORPUS_FN}_{ver}.tsv"
)
if not os.path.isfile(base_tc_file):
if conf.VERBOSE:
print(f"WARN: No text-corpus file for: {lc}")
return results
if not os.path.isfile(ver_tc_inx_file):
if conf.VERBOSE:
print(f"WARN: No text-corpus index file for: {ver} - {lc}")
return results
tc_anal_dir: str = os.path.join(
conf.DATA_BASE_DIR, c.TC_ANALYSIS_DIRNAME, ver_dir, lc
)
os.makedirs(tc_anal_dir, exist_ok=True)
# cvu - do we have them?
has_validator: bool = lc in VALIDATORS
has_phonemiser: bool = lc in PHONEMISERS
# tokeniser: cvu.Tokeniser = cvu.Tokeniser(lc)
# get and filter text_corpus data
df_base_ver_tc: pd.DataFrame = df_read(base_tc_file)
# we only should use allowed ones
df_base_ver_tc = df_base_ver_tc[df_base_ver_tc["is_used"] == 1]
df_ver_inx: pd.DataFrame = df_read(ver_tc_inx_file)
sentence_id_list: list[str] = df_ver_inx["sentence_id"].to_list()
df_base_ver_tc = df_base_ver_tc[
df_base_ver_tc["sentence_id"].isin(sentence_id_list)
]
del df_ver_inx
df_ver_inx = pd.DataFrame()
handle_tc_global(df_base_ver_tc)
for sp in ["validated", "invalidated", "other"]:
handle_tc_split(df_base_ver_tc, sp, c.ALGORITHMS[0])
# handle_tc_split(df_base_ver_tc, sp, "")
for algo in c.ALGORITHMS:
for sp in ["train", "dev", "test"]:
handle_tc_split(df_base_ver_tc, sp, algo)
# done
return results
# END handle_text_corpus
# END - Text-Corpus Stats (Multi Processing Handler)
########################################################
# Reported Stats
########################################################
def handle_reported(ver_lc: str) -> ReportedStatsRec:
"""Process text-corpus for a single locale"""
ver: str = ver_lc.split("|")[0]
lc: str = ver_lc.split("|")[1]
ver_dir: str = calc_dataset_prefix(ver)
# Calc reported file
rep_file: str = os.path.join(
conf.DATA_BASE_DIR, c.VC_DIRNAME, ver_dir, lc, "reported.tsv"
)
# skip process if no such file or there can be empty files :/
if not os.path.isfile(rep_file) or os.path.getsize(rep_file) == 0:
return ReportedStatsRec(ver=ver, lc=lc)
# read file in - Columns: sentence sentence_id locale reason
# df: pd.DataFrame = df_read(rep_file)
problem_list: list[str] = []
fields: dict[str, pd.ArrowDtype] = (
c.FIELDS_REPORTED if float(ver) >= 17.0 else c.FIELDS_REPORTED_OLD
)
df: pd.DataFrame = pd.DataFrame(columns=fields).astype(fields)
df, problem_list = df_read_safe_reported(rep_file)
# debug
if conf.CREATE_REPORTED_PROBLEMS:
# if ver == "17.0" and lc == "en":
if ver == "17.0":
df_write(
df,
os.path.join(conf.DATA_BASE_DIR, ".debug", f"{lc}_{ver}_reported.tsv"),
)
if len(problem_list) > 0:
with open(
os.path.join(
conf.DATA_BASE_DIR, ".debug", f"{lc}_{ver}_problems.txt"
),
mode="w",
encoding="utf8",
) as fd:
fd.write("\n".join(problem_list))
if df.shape[0] == 0: # skip those without records
return ReportedStatsRec(ver=ver, lc=lc)
# Now we have a file with some records in it...
df = df.drop(["sentence", "locale"], axis=1).reset_index(drop=True)
reported_total: int = df.shape[0]
reported_sentences: int = len(df["sentence_id"].unique().tolist())
# get a distribution of reasons/sentence & stats
rep_counts: pd.DataFrame = (
df["sentence_id"].value_counts().dropna().to_frame().reset_index()
)
# make others 'other'
df.loc[~df["reason"].isin(c.REPORTING_BASE)] = "other"
# Get statistics
ser: pd.Series = rep_counts["count"]
# sys.exit(0)
rep_mean: float = ser.mean()
rep_median: float = ser.median()
rep_std: float = ser.std(ddof=0)
# Calc report-per-sentence distribution
arr: np.ndarray = np.fromiter(
rep_counts["count"].dropna().apply(int).reset_index(drop=True).to_list(),
int,
)
hist = np.histogram(arr, bins=c.BINS_REPORTED)
rep_freq = hist[0].tolist()[1:] # type: ignore
# Get reason counts
reason_counts: pd.DataFrame = (
df["reason"].value_counts().dropna().to_frame().reset_index()
)
reason_counts.set_index(keys="reason", inplace=True)
reason_counts = reason_counts.reindex(index=c.REPORTING_ALL, fill_value=0)
reason_freq = reason_counts["count"].to_numpy(int).tolist()
res: ReportedStatsRec = ReportedStatsRec(
ver=ver,
lc=lc,
rep_sum=reported_total,
rep_sen=reported_sentences,
rep_avg=dec3(rep_mean),
rep_med=dec3(rep_median),
rep_std=dec3(rep_std),
rep_freq=rep_freq, # type: ignore
rea_freq=reason_freq, # type: ignore
)
return res
# END - Reported Stats
########################################################
# Dataset Split Stats (inc. Audio Specs Stats) (MP Handler)
########################################################
def handle_dataset_splits(
params: MultiProcessingParams,
) -> int:
"""Handle a single dataset (ver/lc)"""
# Handle one split, this is where calculations happen
# The default column structure of CV dataset splits is as follows [FIXME] variants?
# client_id, path, sentence, up_votes, down_votes, age, gender, accents, locale, segment
# we have as input:
# 'version', 'locale', 'algo', 'split'
path_list: list[str] = []
def handle_split_audio_stats(
ver: str,
lc: str,
algo: str,
split: str,
df_aspecs_sub: pd.DataFrame,
) -> AudioAnalysisStatsRec:
"""Processes a single split's audio specs statistics and return calculated values"""
# columns:
# clip_id
# orig_path, orig_encoding, orig_sample_rate, orig_num_frames, orig_num_channels, orig_bitrate_kbps, orig_bits_per_sample
# tc_path, tc_encoding, tc_sample_rate, tc_num_frames, tc_num_channels, tc_bitrate_kbps, tc_bits_per_sample
# duration, speech_duration, speech_power, silence_power, est_snr
# ver, ds, lc
nonlocal path_list
res: AudioAnalysisStatsRec = AudioAnalysisStatsRec(
ver=ver, lc=lc, alg=algo, sp=split
)
if df_aspecs_sub is None or df_aspecs_sub.shape[0] == 0:
# if no data, return an empty placeholder
return res
# Now get some statistics
_ser: pd.Series[float] # pylint: disable=unsubscriptable-object
_df2: pd.DataFrame
_df3: pd.DataFrame
_df4: pd.DataFrame
# Start with errors
_df2 = df_clip_errors[df_clip_errors["path"].isin(path_list)]
res.errors = _df2.shape[0]
# [TODO] Detailed error stats - type vs count
if _df2.shape[0] > 0:
_df2 = (
_df2["source"]
.value_counts()
.to_frame()
.reset_index(drop=False)
.astype({"source": dtype_pa_str, "count": dtype_pa_uint32})
.sort_values(["source"])
)
res.err_r = list2str(_df2["source"].to_list())
res.err_freq = list2str(_df2["count"].to_list())
# Add aa field for VAD %
df_aspecs_sub = df_aspecs_sub.assign(
vad_percentage=lambda row: 100 * row.speech_duration / row.duration
)
# general
res.clips = df_aspecs_sub.shape[0]
res.dur = round(df_aspecs_sub["duration"].dropna().sum() / 1000) # seconds
# vad stats (convert to secs)
_ser = df_aspecs_sub["speech_duration"].dropna().apply(lambda x: x / 1000)
if _ser.shape[0] > 0:
res.vad_sum = int(_ser.sum())
res.vad_avg = dec3(_ser.mean())
res.vad_med = dec3(_ser.median())
res.vad_std = dec3(_ser.std(ddof=0))
# Calc distribution
_arr = np.fromiter(_ser.apply(int).reset_index(drop=True).to_list(), int)
_hist = np.histogram(_arr, bins=c.BINS_DURATION)
res.vad_freq = _hist[0].tolist() # type: ignore
# vad percentage stats (data already betweek 0-100)
_ser = df_aspecs_sub["vad_percentage"].dropna()
if _ser.shape[0] > 0:
res.vadp_avg = dec3(_ser.mean())
res.vadp_med = dec3(_ser.median())
res.vadp_std = dec3(_ser.std(ddof=0))
# Calc distribution
_arr = np.fromiter(_ser.apply(int).reset_index(drop=True).to_list(), int)
_hist = np.histogram(_arr, bins=c.BINS_PERCENT)
res.vadp_freq = _hist[0].tolist() # type: ignore
# speech power stats (10^-6) we scale it
_ser = df_aspecs_sub["speech_power"].dropna().apply(lambda x: x * 1_000_000)
if _ser.shape[0] > 0:
res.sp_pwr_avg = dec3(_ser.mean())
res.sp_pwr_med = dec3(_ser.median())
res.sp_pwr_std = dec3(_ser.std(ddof=0))
# Calc distribution
_arr = np.fromiter(_ser.apply(int).reset_index(drop=True).to_list(), int)
_hist = np.histogram(_arr, bins=c.BINS_POWER)
res.sp_pwr_freq = _hist[0].tolist() # type: ignore
# silence power stats (10^-9) we scale it
_ser = (
df_aspecs_sub["silence_power"].dropna().apply(lambda x: x * 1_000_000_000)
)
if _ser.shape[0] > 0:
res.sil_pwr_avg = dec3(_ser.mean())
res.sil_pwr_med = dec3(_ser.median())
res.sil_pwr_std = dec3(_ser.std(ddof=0))
# Calc distribution
_arr = np.fromiter(_ser.apply(int).reset_index(drop=True).to_list(), int)
_hist = np.histogram(_arr, bins=c.BINS_POWER)
res.sil_pwr_freq = _hist[0].tolist() # type: ignore
# snr stats
# no speech
_df2 = df_aspecs_sub[df_aspecs_sub["est_snr"].isna()]
res.no_vad = _df2.shape[0]
# low snr
_df3 = df_aspecs_sub[df_aspecs_sub["est_snr"] < conf.LOW_SNR_THRESHOLD]
res.low_snr = _df3.shape[0]
# low power
_df4 = df_aspecs_sub[df_aspecs_sub["speech_power"] < conf.LOW_POWER_THRESHOLD]
res.low_power = _df4.shape[0]
# combine and save for main buckets
if algo == "" and split in c.MAIN_BUCKETS:
_df2 = pd.concat([_df2, _df3, _df4]).drop_duplicates()
if _df2.shape[0] > 0:
df_write(
df=_df3, fpath=os.path.join(ds_meta_dir, f"audio_bad_{split}.tsv")
)
# valid snr (where we detected speech)
_ser = df_aspecs_sub[~df_aspecs_sub["est_snr"].isna()]["est_snr"]
if _ser.shape[0] > 0:
res.snr_avg = dec3(_ser.mean())
res.snr_med = dec3(_ser.median())
res.snr_std = dec3(_ser.std(ddof=0))
# Calc word count distribution
_arr = np.fromiter(_ser.apply(int).reset_index(drop=True).to_list(), int)
_hist = np.histogram(_arr, bins=c.BINS_SNR)
res.snr_freq = _hist[0].tolist()[1:] # type: ignore # drop lower than -100 SNR
# direct distributions (value counts)
# encoding
_df2 = (
df_aspecs_sub["orig_encoding"]
.astype(dtype_pa_str)
.dropna()
.value_counts()
.to_frame()
.reset_index(drop=False)
.astype({"orig_encoding": dtype_pa_str, "count": dtype_pa_uint32})
.sort_values(["orig_encoding"])
)
res.enc_r = list2str(_df2["orig_encoding"].to_list())
res.enc_freq = list2str(_df2["count"].to_list())
# channels
_df2 = (
df_aspecs_sub["orig_num_channels"]
.astype(dtype_pa_str)
.dropna()
.value_counts()
.to_frame()
.reset_index(drop=False)
.astype({"orig_num_channels": dtype_pa_str, "count": dtype_pa_uint32})
.sort_values(["orig_num_channels"])
)
res.chan_r = list2str(_df2["orig_num_channels"].to_list())
res.chan_freq = list2str(_df2["count"].to_list())
# sample rate
_df2 = (
df_aspecs_sub["orig_sample_rate"]
.astype(dtype_pa_str)
.dropna()
.value_counts()
.to_frame()
.reset_index(drop=False)
.astype({"orig_sample_rate": dtype_pa_str, "count": dtype_pa_uint32})
.sort_values(["orig_sample_rate"])
)
res.srate_r = list2str(_df2["orig_sample_rate"].to_list())
res.srate_freq = list2str(_df2["count"].to_list())
# bit rate
_df2 = (
df_aspecs_sub["orig_bitrate_kbps"]
.astype(dtype_pa_str)
.dropna()
.value_counts()
.to_frame()
.reset_index(drop=False)
.astype({"orig_bitrate_kbps": dtype_pa_str, "count": dtype_pa_uint32})
.sort_values(["orig_bitrate_kbps"])
)
res.brate_r = list2str(_df2["orig_bitrate_kbps"].to_list())
res.brate_freq = list2str(_df2["count"].to_list())
return res
# now, do calculate some statistics...
def handle_split(
ver: str, lc: str, algo: str, split: str, src_ds_dir: str
) -> tuple[SplitStatsRec, CharSpeedRec, AudioAnalysisStatsRec]:
"""Processes a single split and return calculated values"""
nonlocal path_list
# find_fixes
# def find_fixes(df_split: pd.DataFrame) -> list[list[int]]:
# """Finds fixable demographic info from the split and returns a string"""
# # df is local dataframe which will keep records
# # only necessary columns with some additional columns
# df: pd.DataFrame = df_split.copy().reset_index(drop=True)
# df["v_enum"], _ = pd.factorize(
# df["client_id"]
# ) # add an enumaration column for client_id's, more memory efficient
# df["p_enum"], _ = pd.factorize(
# df["path"]
# ) # add an enumaration column for recordings, more memory efficient
# df = (
# df[["v_enum", "age", "gender", "p_enum"]]
# .fillna(c.NODATA)
# .reset_index(drop=True)
# )
# # prepare empty results
# fixes: pd.DataFrame = pd.DataFrame(columns=df.columns).reset_index(
# drop=True
# )
# dem_fixes_recs: list[int] = []
# dem_fixes_voices: list[int] = []
# # get unique voices with multiple demographic values
# df_counts: pd.DataFrame = (
# df[["v_enum", "age", "gender"]]
# .drop_duplicates()
# .copy()
# .groupby("v_enum")
# .agg({"age": "count", "gender": "count"})
# )
# df_counts.reset_index(inplace=True)
# df_counts = df_counts[
# (df_counts["age"].astype(int) == 2)
# | (df_counts["gender"].astype(int) == 2)
# ] # reduce that to only processible ones
# v_processable: list[int] = df_counts["v_enum"].unique().tolist()
# # now, work only on problem voices & records.
# # For each voice, get related records and decide
# for v in v_processable:
# recs: pd.DataFrame = df[df["v_enum"] == v].copy()
# recs_blanks: pd.DataFrame = recs[
# (recs["gender"] == c.NODATA) | (recs["age"] == c.NODATA)
# ].copy() # get full blanks
# # gender
# recs_w_gender: pd.DataFrame = recs[~(recs["gender"] == c.NODATA)].copy()
# if recs_w_gender.shape[0] > 0:
# val: str = recs_w_gender["gender"].tolist()[0]
# recs_blanks.loc[:, "gender"] = val
# # age
# recs_w_age: pd.DataFrame = recs[~(recs["age"] == c.NODATA)].copy()
# if recs_w_age.shape[0] > 0:
# val: str = recs_w_age["age"].tolist()[0]
# recs_blanks.loc[:, "age"] = val
# # now we can add them to the result fixed list
# fixes = pd.concat([fixes.loc[:], recs_blanks]).reset_index(drop=True)
# # Here, we have a df maybe with records of possible changes
# if fixes.shape[0] > 0:
# # records
# pt: pd.DataFrame = pd.pivot_table(
# fixes,
# values="p_enum",
# index=["age"],
# columns=["gender"],
# aggfunc="count",
# fill_value=0,
# dropna=False,
# margins=False,
# )
# # get only value parts : nodata is just negative sum of these, and TOTAL will be 0,
# # so we drop them for file size and leave computation to the client
# pt = (
# pt.reindex(c.CV_AGES, axis=0)
# .reindex(c.CV_GENDERS, axis=1)
# .fillna(value=0)
# .astype(int)
# .drop(c.NODATA, axis=0)
# .drop(c.NODATA, axis=1)
# )
# dem_fixes_recs = pt.to_numpy(int).tolist()
# # voices
# fixes = fixes.drop("p_enum", axis=1).drop_duplicates()
# pt: pd.DataFrame = pd.pivot_table(
# fixes,
# values="v_enum",
# index=["age"],
# columns=["gender"],
# aggfunc="count",
# fill_value=0,
# dropna=False,
# margins=False,
# )
# # get only value parts : nodata is just -sum of these, sum will be 0
# pt = (
# pt.reindex(c.CV_AGES, axis=0)
# .reindex(c.CV_GENDERS, axis=1)
# .fillna(value=0)
# .astype(int)
# .drop(c.NODATA, axis=0)
# .drop(c.NODATA, axis=1)
# )
# dem_fixes_voices = pt.to_numpy(int).tolist()
# return [dem_fixes_recs, dem_fixes_voices]
# END - find_fixes
#
# === START ===
#
# Read in DataFrames
sp_fpath: str
df_orig: pd.DataFrame = pd.DataFrame()
if split == "clips": # build "clips" from val+inval+other
sp_fpath = os.path.join(src_ds_dir, "validated.tsv")
df_orig = df_read(sp_fpath)
# add invalidated
_df: pd.DataFrame = df_read(sp_fpath.replace("validated", "invalidated"))
if _df.shape[0] > 0:
df_orig = pd.concat([df_orig, _df]) if df_orig.shape[0] > 0 else _df
# add other
_df = df_read(sp_fpath.replace("validated", "other"))
if _df.shape[0] > 0:
df_orig = pd.concat([df_orig, _df]) if df_orig.shape[0] > 0 else _df
else:
sp_fpath = os.path.join(src_ds_dir, f"{split}.tsv")
if os.path.isfile(sp_fpath):
df_orig = df_read(sp_fpath)
# Do nothing, if there is no data or no such split
if df_orig.shape[0] == 0:
return (
SplitStatsRec(ver=ver, lc=lc, alg=algo, sp=split),
CharSpeedRec(ver=ver, lc=lc, alg=algo, sp=split),
AudioAnalysisStatsRec(ver=ver, lc=lc, alg=algo, sp=split),
)
# [TODO] Move these to split_compile: Make all confirm to current style?
# Normalize data to the latest version's columns with typing
# Replace NA with NODATA with some typing and conditionals
# df: pd.DataFrame = df_orig.fillna(value=c.NODATA)
df: pd.DataFrame = pd.DataFrame(
columns=list(c.FIELDS_BUCKETS_SPLITS.keys())
).astype(c.FIELDS_BUCKETS_SPLITS)
# these should exist
df["client_id"] = df_orig["client_id"]
df["path"] = df_orig["path"]
df["sentence"] = df_orig["sentence"]
df["up_votes"] = df_orig["up_votes"]
df["down_votes"] = df_orig["down_votes"]
# these exist, but can be NaN
df["age"] = df_orig["age"].astype(dtype_pa_str).fillna(c.NODATA)
df["gender"] = df_orig["gender"].astype(dtype_pa_str).fillna(c.NODATA)
# These might not exist in older versions, so we fill them
df["locale"] = (
df_orig["locale"].astype(dtype_pa_str)
if "locale" in df_orig.columns
else lc
)
df["variant"] = (
df_orig["variant"].astype(dtype_pa_str).fillna(c.NODATA)
if "variant" in df_orig.columns
else c.NODATA
)
df["segment"] = (
df_orig["segment"].astype(dtype_pa_str).fillna(c.NODATA)
if "segment" in df_orig.columns
else c.NODATA
)
df["sentence_domain"] = (
df_orig["sentence_domain"].astype(dtype_pa_str).fillna(c.NODATA)
if "sentence_domain" in df_orig.columns
else c.NODATA
)
# The "accent" column renamed to "accents" along the way
if "accent" in df_orig.columns:
df["accents"] = df_orig["accent"].astype(dtype_pa_str).fillna(c.NODATA)
if "accents" in df_orig.columns:
df["accents"] = df_orig["accents"].astype(dtype_pa_str).fillna(c.NODATA)
# [TODO] this needs special consideration (back-lookup) but has quirks for now
df["sentence_id"] = (
df_orig["sentence_id"].astype(dtype_pa_str).fillna(c.NODATA)
if "sentence_id" in df_orig.columns
else c.NODATA
)
# backmap genders
df = gender_backmapping(df)
# add lowercase sentence column
df["sentence_lower"] = df["sentence"].str.lower()
# === DURATIONS: Calc duration agregate values
# there must be records + v1 cannot be mapped
ser: pd.Series
arr: np.ndarray
duration_freq: list[int] = []
# Assume no Duration data, set illegal defaults
duration_total: float = -1
duration_mean: float = -1
duration_median: float = -1
duration_std: float = -1
if df_clip_durations.shape[0] > 0 and ver != "1":
# Connect with duration table and convert to seconds
df["duration"] = df["path"].map(
df_clip_durations["duration[ms]"] / 1000, na_action="ignore"
)
ser = df["duration"].dropna()
duration_total = ser.sum()
duration_mean = ser.mean()
duration_median = ser.median()
duration_std = ser.std(ddof=0)
# Calc duration distribution
arr = np.fromiter(
df["duration"].dropna().apply(int).reset_index(drop=True).to_list(), int
)
hist = np.histogram(arr, bins=c.BINS_DURATION)
duration_freq = hist[0].tolist() # type: ignore
# === VOICES (how many recordings per voice)
voice_counts: pd.DataFrame = (
df["client_id"].value_counts().dropna().to_frame().reset_index()
)
ser = voice_counts["count"]
voice_mean: float = ser.mean()
voice_median: float = ser.median()
voice_std: float = ser.std(ddof=0)
# Calc speaker recording distribution
arr = np.fromiter(
voice_counts["count"].dropna().apply(int).reset_index(drop=True).to_list(),
int,
)
hist = np.histogram(arr, bins=c.BINS_VOICES)
voice_freq = hist[0].tolist()[1:] # type: ignore
# === SENTENCES (how many recordings per sentence)
sentence_counts: pd.DataFrame = (
df["sentence"].value_counts().dropna().to_frame().reset_index()
)
ser = sentence_counts["count"]
sentence_mean: float = ser.mean()
sentence_median: float = ser.median()
sentence_std: float = ser.std(ddof=0)
# Calc sentence recording distribution
arr = np.fromiter(
sentence_counts["count"]
.dropna()
.apply(int)
.reset_index(drop=True)
.to_list(),
int,
)
hist = np.histogram(arr, bins=c.BINS_SENTENCES)
sentence_freq = hist[0].tolist()[1:] # type: ignore
# === VOTES
bins: list[int] = c.BINS_VOTES_UP
up_votes_sum: int = df["up_votes"].sum()
vote_counts_df: pd.DataFrame = (
df["up_votes"].value_counts().dropna().to_frame().astype(int).reset_index()
)
vote_counts_df.rename(columns={"up_votes": "votes"}, inplace=True)
ser = vote_counts_df["count"]
up_votes_mean: float = ser.mean()
up_votes_median: float = ser.median()
up_votes_std: float = ser.std(ddof=0)
bin_val: int
bin_next: int
up_votes_freq: list[int] = []
for i in range(0, len(bins) - 1):
bin_val = bins[i]
bin_next = bins[i + 1]
up_votes_freq.append(
int(
vote_counts_df.loc[
(vote_counts_df["votes"] >= bin_val)
& (vote_counts_df["votes"] < bin_next)
]["count"].sum()
)
)
bins = c.BINS_VOTES_DOWN
down_votes_sum: int = df["down_votes"].sum()
vote_counts_df = (
df["down_votes"]
.value_counts()
.dropna()
.to_frame()
.astype(int)
.reset_index()
)
vote_counts_df.rename(columns={"down_votes": "votes"}, inplace=True)
ser = vote_counts_df["count"]
down_votes_mean: float = ser.mean()
down_votes_median: float = ser.median()
down_votes_std: float = ser.std(ddof=0)
down_votes_freq: list[int] = []
for i in range(0, len(bins) - 1):
bin_val = bins[i]
bin_next = bins[i + 1]
down_votes_freq.append(
int(