forked from kahst/BirdNET-Analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
1994 lines (1666 loc) · 72.2 KB
/
gui.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
from contextlib import suppress
import concurrent.futures
import os
import sys
from pathlib import Path
from functools import partial
import config as cfg
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
# divert stdout & stderr to logs.txt file since we have no console when deployed
userdir = Path.home()
if sys.platform == "win32":
userdir /= "AppData/Roaming"
elif sys.platform == "linux":
userdir /= ".local/share"
elif sys.platform == "darwin":
userdir /= "Library/Application Support"
appdir = userdir / "BirdNET-Analyzer-GUI"
appdir.mkdir(parents=True, exist_ok=True)
sys.stderr = sys.stdout = open(str(appdir / "logs.txt"), "w")
cfg.ERROR_LOG_FILE = str(appdir / cfg.ERROR_LOG_FILE)
FROZEN = True
else:
FROZEN = False
import multiprocessing
import gradio as gr
import librosa
import webview
import analyze
import segments
import species
import utils
from train import trainModel
import localization as loc
loc.load_localization()
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
_WINDOW: webview.Window
OUTPUT_TYPE_MAP = {
"Raven selection table": "table",
"Audacity": "audacity",
"R": "r",
"CSV": "csv",
"Kaleidoscope": "kaleidoscope",
}
ORIGINAL_LABELS_FILE = cfg.LABELS_FILE
ORIGINAL_TRANSLATED_LABELS_PATH = cfg.TRANSLATED_LABELS_PATH
POSITIVE_LABEL_DIR = "Positive"
NEGATIVE_LABEL_DIR = "Negative"
def analyzeFile_wrapper(entry):
return (entry[0], analyze.analyzeFile(entry))
def extractSegments_wrapper(entry):
return (entry[0][0], segments.extractSegments(entry))
def validate(value, msg):
"""Checks if the value ist not falsy.
If the value is falsy, an error will be raised.
Args:
value: Value to be tested.
msg: Message in case of an error.
"""
if not value:
raise gr.Error(msg)
def run_species_list(out_path, filename, lat, lon, week, use_yearlong, sf_thresh, sortby):
validate(out_path, loc.localize("validation-no-directory-selected"))
species.run(
os.path.join(out_path, filename if filename else "species_list.txt"),
lat,
lon,
-1 if use_yearlong else week,
sf_thresh,
sortby,
)
gr.Info(f"{loc.localize('species-tab-finish-info')} {cfg.OUTPUT_PATH}")
def runSingleFileAnalysis(
input_path,
confidence,
sensitivity,
overlap,
fmin,
fmax,
species_list_choice,
species_list_file,
lat,
lon,
week,
use_yearlong,
sf_thresh,
custom_classifier_file,
locale,
):
validate(input_path, loc.localize("validation-no-file-selected"))
return runAnalysis(
input_path,
None,
confidence,
sensitivity,
overlap,
fmin,
fmax,
species_list_choice,
species_list_file,
lat,
lon,
week,
use_yearlong,
sf_thresh,
custom_classifier_file,
"csv",
None,
"en" if not locale else locale,
1,
4,
None,
skip_existing=False,
progress=None,
)
def runBatchAnalysis(
output_path,
confidence,
sensitivity,
overlap,
fmin,
fmax,
species_list_choice,
species_list_file,
lat,
lon,
week,
use_yearlong,
sf_thresh,
custom_classifier_file,
output_type,
combine_tables,
locale,
batch_size,
threads,
input_dir,
skip_existing,
progress=gr.Progress(),
):
validate(input_dir, loc.localize("validation-no-directory-selected"))
batch_size = int(batch_size)
threads = int(threads)
if species_list_choice == _CUSTOM_SPECIES:
validate(species_list_file, loc.localize("validation-no-species-list-selected"))
return runAnalysis(
None,
output_path,
confidence,
sensitivity,
overlap,
fmin,
fmax,
species_list_choice,
species_list_file,
lat,
lon,
week,
use_yearlong,
sf_thresh,
custom_classifier_file,
output_type,
combine_tables,
"en" if not locale else locale,
batch_size if batch_size and batch_size > 0 else 1,
threads if threads and threads > 0 else 4,
input_dir,
skip_existing,
progress,
)
def runAnalysis(
input_path: str,
output_path: str,
confidence: float,
sensitivity: float,
overlap: float,
fmin: int,
fmax: int,
species_list_choice: str,
species_list_file,
lat: float,
lon: float,
week: int,
use_yearlong: bool,
sf_thresh: float,
custom_classifier_file,
output_types: str,
combine_tables: bool,
locale: str,
batch_size: int,
threads: int,
input_dir: str,
skip_existing: bool,
progress: gr.Progress,
):
"""Starts the analysis.
Args:
input_path: Either a file or directory.
output_path: The output path for the result, if None the input_path is used
confidence: The selected minimum confidence.
sensitivity: The selected sensitivity.
overlap: The selected segment overlap.
fmin: The selected minimum bandpass frequency.
fmax: The selected maximum bandpass frequency.
species_list_choice: The choice for the species list.
species_list_file: The selected custom species list file.
lat: The selected latitude.
lon: The selected longitude.
week: The selected week of the year.
use_yearlong: Use yearlong instead of week.
sf_thresh: The threshold for the predicted species list.
custom_classifier_file: Custom classifier to be used.
output_type: The type of result to be generated.
output_filename: The filename for the combined output.
locale: The translation to be used.
batch_size: The number of samples in a batch.
threads: The number of threads to be used.
input_dir: The input directory.
progress: The gradio progress bar.
"""
if progress is not None:
progress(0, desc=f"{loc.localize('progress-preparing')} ...")
locale = locale.lower()
# Load eBird codes, labels
cfg.CODES = analyze.loadCodes()
cfg.LABELS = utils.readLines(os.path.join(SCRIPT_DIR, ORIGINAL_LABELS_FILE))
cfg.LATITUDE, cfg.LONGITUDE, cfg.WEEK = lat, lon, -1 if use_yearlong else week
cfg.LOCATION_FILTER_THRESHOLD = sf_thresh
cfg.SKIP_EXISTING_RESULTS = skip_existing
if species_list_choice == _CUSTOM_SPECIES:
if not species_list_file or not species_list_file.name:
cfg.SPECIES_LIST_FILE = None
else:
cfg.SPECIES_LIST_FILE = species_list_file.name
if os.path.isdir(cfg.SPECIES_LIST_FILE):
cfg.SPECIES_LIST_FILE = os.path.join(cfg.SPECIES_LIST_FILE, "species_list.txt")
cfg.SPECIES_LIST = utils.readLines(cfg.SPECIES_LIST_FILE)
cfg.CUSTOM_CLASSIFIER = None
elif species_list_choice == _PREDICT_SPECIES:
cfg.SPECIES_LIST_FILE = None
cfg.CUSTOM_CLASSIFIER = None
cfg.SPECIES_LIST = species.getSpeciesList(cfg.LATITUDE, cfg.LONGITUDE, cfg.WEEK, cfg.LOCATION_FILTER_THRESHOLD)
elif species_list_choice == _CUSTOM_CLASSIFIER:
if custom_classifier_file is None:
raise gr.Error(loc.localize("validation-no-custom-classifier-selected"))
# Set custom classifier?
cfg.CUSTOM_CLASSIFIER = (
custom_classifier_file # we treat this as absolute path, so no need to join with dirname
)
cfg.LABELS_FILE = custom_classifier_file.replace(".tflite", "_Labels.txt") # same for labels file
cfg.LABELS = utils.readLines(cfg.LABELS_FILE)
cfg.LATITUDE = -1
cfg.LONGITUDE = -1
cfg.SPECIES_LIST_FILE = None
cfg.SPECIES_LIST = []
locale = "en"
else:
cfg.SPECIES_LIST_FILE = None
cfg.SPECIES_LIST = []
cfg.CUSTOM_CLASSIFIER = None
# Load translated labels
lfile = os.path.join(
SCRIPT_DIR, cfg.TRANSLATED_LABELS_PATH, os.path.basename(cfg.LABELS_FILE).replace(".txt", f"_{locale}.txt")
)
if not locale in ["en"] and os.path.isfile(lfile):
cfg.TRANSLATED_LABELS = utils.readLines(lfile)
else:
cfg.TRANSLATED_LABELS = cfg.LABELS
if len(cfg.SPECIES_LIST) == 0:
print(f"Species list contains {len(cfg.LABELS)} species")
else:
print(f"Species list contains {len(cfg.SPECIES_LIST)} species")
# Set input and output path
cfg.INPUT_PATH = input_path
if input_dir:
cfg.OUTPUT_PATH = output_path if output_path else input_dir
else:
cfg.OUTPUT_PATH = output_path if output_path else os.path.dirname(input_path)
# Parse input files
if input_dir:
cfg.FILE_LIST = utils.collect_audio_files(input_dir)
cfg.INPUT_PATH = input_dir
elif os.path.isdir(cfg.INPUT_PATH):
cfg.FILE_LIST = utils.collect_audio_files(cfg.INPUT_PATH)
else:
cfg.FILE_LIST = [cfg.INPUT_PATH]
validate(cfg.FILE_LIST, loc.localize("validation-no-audio-files-found"))
# Set confidence threshold
cfg.MIN_CONFIDENCE = confidence
# Set sensitivity
cfg.SIGMOID_SENSITIVITY = max(0.5, min(1.0 - (float(sensitivity) - 1.0), 1.5))
# Set overlap
cfg.SIG_OVERLAP = max(0.0, min(2.9, float(overlap)))
# Set frequency range
cfg.BANDPASS_FMIN = max(0, min(cfg.SIG_FMAX, int(fmin)))
cfg.BANDPASS_FMAX = max(cfg.SIG_FMIN, min(cfg.SIG_FMAX, int(fmax)))
# Set result type
cfg.RESULT_TYPES = output_types
cfg.COMBINE_RESULTS = combine_tables
# Set number of threads
if input_dir:
cfg.CPU_THREADS = max(1, int(threads))
cfg.TFLITE_THREADS = 1
else:
cfg.CPU_THREADS = 1
cfg.TFLITE_THREADS = max(1, int(threads))
# Set batch size
cfg.BATCH_SIZE = max(1, int(batch_size))
flist = []
for f in cfg.FILE_LIST:
flist.append((f, cfg.getConfig()))
result_list = []
if progress is not None:
progress(0, desc=f"{loc.localize('progress-starting')} ...")
# Analyze files
if cfg.CPU_THREADS < 2:
for entry in flist:
result_list.append(analyzeFile_wrapper(entry))
else:
with concurrent.futures.ProcessPoolExecutor(max_workers=cfg.CPU_THREADS) as executor:
futures = (executor.submit(analyzeFile_wrapper, arg) for arg in flist)
for i, f in enumerate(concurrent.futures.as_completed(futures), start=1):
if progress is not None:
progress((i, len(flist)), total=len(flist), unit="files")
result = f.result()
result_list.append(result)
# Combine results?
if cfg.COMBINE_RESULTS:
print(f"Combining results, writing to {cfg.OUTPUT_PATH}...", end="", flush=True)
analyze.combineResults([i[1] for i in result_list])
print("done!", flush=True)
return [[os.path.relpath(r[0], input_dir), bool(r[1])] for r in result_list] if input_dir else result_list[0][1]["csv"]
_CUSTOM_SPECIES = loc.localize("species-list-radio-option-custom-list")
_PREDICT_SPECIES = loc.localize("species-list-radio-option-predict-list")
_CUSTOM_CLASSIFIER = loc.localize("species-list-radio-option-custom-classifier")
_ALL_SPECIES = loc.localize("species-list-radio-option-all")
def show_species_choice(choice: str):
"""Sets the visibility of the species list choices.
Args:
choice: The label of the currently active choice.
Returns:
A list of [
Row update,
File update,
Column update,
Column update,
]
"""
if choice == _CUSTOM_SPECIES:
return [
gr.Row(visible=False),
gr.File(visible=True),
gr.Column(visible=False),
gr.Column(visible=False),
]
elif choice == _PREDICT_SPECIES:
return [
gr.Row(visible=True),
gr.File(visible=False),
gr.Column(visible=False),
gr.Column(visible=False),
]
elif choice == _CUSTOM_CLASSIFIER:
return [
gr.Row(visible=False),
gr.File(visible=False),
gr.Column(visible=True),
gr.Column(visible=False),
]
return [
gr.Row(visible=False),
gr.File(visible=False),
gr.Column(visible=False),
gr.Column(visible=True),
]
def select_subdirectories():
"""Creates a directory selection dialog.
Returns:
A tuples of (directory, list of subdirectories) or (None, None) if the dialog was canceled.
"""
dir_name = _WINDOW.create_file_dialog(webview.FOLDER_DIALOG)
if dir_name:
subdirs = utils.list_subdirectories(dir_name[0])
labels = []
for folder in subdirs:
labels_in_folder = folder.split(",")
for label in labels_in_folder:
if not label in labels:
labels.append(label)
return dir_name[0], [[label] for label in sorted(labels)]
return None, None
def select_file(filetypes=()):
"""Creates a file selection dialog.
Args:
filetypes: List of filetypes to be filtered in the dialog.
Returns:
The selected file or None of the dialog was canceled.
"""
files = _WINDOW.create_file_dialog(webview.OPEN_DIALOG, file_types=filetypes)
return files[0] if files else None
def format_seconds(secs: float):
"""Formats a number of seconds into a string.
Formats the seconds into the format "h:mm:ss.ms"
Args:
secs: Number of seconds.
Returns:
A string with the formatted seconds.
"""
hours, secs = divmod(secs, 3600)
minutes, secs = divmod(secs, 60)
return f"{hours:2.0f}:{minutes:02.0f}:{secs:06.3f}"
def select_directory(collect_files=True, max_files=None):
"""Shows a directory selection system dialog.
Uses the pywebview to create a system dialog.
Args:
collect_files: If True, also lists a files inside the directory.
Returns:
If collect_files==True, returns (directory path, list of (relative file path, audio length))
else just the directory path.
All values will be None of the dialog is cancelled.
"""
dir_name = _WINDOW.create_file_dialog(webview.FOLDER_DIALOG)
if collect_files:
if not dir_name:
return None, None
files = utils.collect_audio_files(dir_name[0], max_files=max_files)
return dir_name[0], [
[os.path.relpath(file, dir_name[0]), format_seconds(librosa.get_duration(filename=file))] for file in files
]
return dir_name[0] if dir_name else None
def start_training(
data_dir,
crop_mode,
crop_overlap,
fmin,
fmax,
output_dir,
classifier_name,
model_save_mode,
cache_mode,
cache_file,
cache_file_name,
autotune,
autotune_trials,
autotune_executions_per_trials,
epochs,
batch_size,
learning_rate,
hidden_units,
use_mixup,
upsampling_ratio,
upsampling_mode,
model_format,
progress=gr.Progress(),
):
"""Starts the training of a custom classifier.
Args:
data_dir: Directory containing the training data.
output_dir: Directory for the new classifier.
classifier_name: File name of the classifier.
epochs: Number of epochs to train for.
batch_size: Number of samples in one batch.
learning_rate: Learning rate for training.
hidden_units: If > 0 the classifier contains a further hidden layer.
progress: The gradio progress bar.
Returns:
Returns a matplotlib.pyplot figure.
"""
validate(data_dir, loc.localize("validation-no-training-data-selected"))
validate(output_dir, loc.localize("validation-no-directory-for-classifier-selected"))
validate(classifier_name, loc.localize("validation-no-valid-classifier-name"))
if not epochs or epochs < 0:
raise gr.Error(loc.localize("validation-no-valid-epoch-number"))
if not batch_size or batch_size < 0:
raise gr.Error(loc.localize("validation-no-valid-batch-size"))
if not learning_rate or learning_rate < 0:
raise gr.Error(loc.localize("validation-no-valid-learning-rate"))
if fmin < cfg.SIG_FMIN or fmax > cfg.SIG_FMAX or fmin > fmax:
raise gr.Error(f"{loc.localize('validation-no-valid-frequency')} [{cfg.SIG_FMIN}, {cfg.SIG_FMAX}]")
if not hidden_units or hidden_units < 0:
hidden_units = 0
if progress is not None:
progress((0, epochs), desc=loc.localize("progress-build-classifier"), unit="epochs")
cfg.TRAIN_DATA_PATH = data_dir
cfg.SAMPLE_CROP_MODE = crop_mode
cfg.SIG_OVERLAP = max(0.0, min(2.9, float(crop_overlap)))
cfg.CUSTOM_CLASSIFIER = str(Path(output_dir) / classifier_name)
cfg.TRAIN_EPOCHS = int(epochs)
cfg.TRAIN_BATCH_SIZE = int(batch_size)
cfg.TRAIN_LEARNING_RATE = learning_rate
cfg.TRAIN_HIDDEN_UNITS = int(hidden_units)
cfg.TRAIN_WITH_MIXUP = use_mixup
cfg.UPSAMPLING_RATIO = min(max(0, upsampling_ratio), 1)
cfg.UPSAMPLING_MODE = upsampling_mode
cfg.TRAINED_MODEL_OUTPUT_FORMAT = model_format
cfg.BANDPASS_FMIN = max(0, min(cfg.SIG_FMAX, int(fmin)))
cfg.BANDPASS_FMAX = max(cfg.SIG_FMIN, min(cfg.SIG_FMAX, int(fmax)))
cfg.TRAINED_MODEL_SAVE_MODE = model_save_mode
cfg.TRAIN_CACHE_MODE = cache_mode
cfg.TRAIN_CACHE_FILE = os.path.join(cache_file, cache_file_name) if cache_mode == "save" else cache_file
cfg.TFLITE_THREADS = 1
cfg.CPU_THREADS = max(1, multiprocessing.cpu_count() - 1) # let's use everything we have (well, almost)
cfg.AUTOTUNE = autotune
cfg.AUTOTUNE_TRIALS = autotune_trials
cfg.AUTOTUNE_EXECUTIONS_PER_TRIAL = int(autotune_executions_per_trials)
def dataLoadProgression(num_files, num_total_files, label):
if progress is not None:
progress(
(num_files, num_total_files),
total=num_total_files,
unit="files",
desc=f"{loc.localize('progress-loading-data')} '{label}'",
)
def epochProgression(epoch, logs=None):
if progress is not None:
if epoch + 1 == epochs:
progress(
(epoch + 1, epochs),
total=epochs,
unit="epochs",
desc=f"{loc.localize('progress-saving')} {cfg.CUSTOM_CLASSIFIER}",
)
else:
progress((epoch + 1, epochs), total=epochs, unit="epochs", desc=loc.localize("progress-training"))
def trialProgression(trial):
if progress is not None:
progress(
(trial, autotune_trials), total=autotune_trials, unit="trials", desc=loc.localize("progress-autotune")
)
try:
history = trainModel(
on_epoch_end=epochProgression,
on_trial_result=trialProgression,
on_data_load_end=dataLoadProgression,
autotune_directory=appdir if FROZEN else "autotune",
)
except Exception as e:
if e.args and len(e.args) > 1:
raise gr.Error(loc.localize(e.args[1]))
else:
raise gr.Error(f"{e}")
if len(history.epoch) < epochs:
gr.Info(loc.localize("training-tab-early-stoppage-msg"))
auprc = history.history["val_AUPRC"]
auroc = history.history["val_AUROC"]
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(auprc, label="AUPRC")
plt.plot(auroc, label="AUROC")
plt.legend()
plt.xlabel("Epoch")
return fig
def extract_segments(audio_dir, result_dir, output_dir, min_conf, num_seq, seq_length, threads, progress=gr.Progress()):
validate(audio_dir, loc.localize("validation-no-audio-directory-selected"))
if not result_dir:
result_dir = audio_dir
if not output_dir:
output_dir = audio_dir
if progress is not None:
progress(0, desc=f"{loc.localize('progress-search')} ...")
# Parse audio and result folders
cfg.FILE_LIST = segments.parseFolders(audio_dir, result_dir)
# Set output folder
cfg.OUTPUT_PATH = output_dir
# Set number of threads
cfg.CPU_THREADS = int(threads)
# Set confidence threshold
cfg.MIN_CONFIDENCE = max(0.01, min(0.99, min_conf))
# Parse file list and make list of segments
cfg.FILE_LIST = segments.parseFiles(cfg.FILE_LIST, max(1, int(num_seq)))
# Add config items to each file list entry.
# We have to do this for Windows which does not
# support fork() and thus each process has to
# have its own config. USE LINUX!
flist = [(entry, max(cfg.SIG_LENGTH, float(seq_length)), cfg.getConfig()) for entry in cfg.FILE_LIST]
result_list = []
# Extract segments
if cfg.CPU_THREADS < 2:
for i, entry in enumerate(flist):
result = extractSegments_wrapper(entry)
result_list.append(result)
if progress is not None:
progress((i, len(flist)), total=len(flist), unit="files")
else:
with concurrent.futures.ProcessPoolExecutor(max_workers=cfg.CPU_THREADS) as executor:
futures = (executor.submit(extractSegments_wrapper, arg) for arg in flist)
for i, f in enumerate(concurrent.futures.as_completed(futures), start=1):
if progress is not None:
progress((i, len(flist)), total=len(flist), unit="files")
result = f.result()
result_list.append(result)
return [[os.path.relpath(r[0], audio_dir), r[1]] for r in result_list]
def sample_sliders(opened=True):
"""Creates the gradio accordion for the inference settings.
Args:
opened: If True the accordion is open on init.
Returns:
A tuple with the created elements:
(Slider (min confidence), Slider (sensitivity), Slider (overlap))
"""
with gr.Accordion(loc.localize("inference-settings-accordion-label"), open=opened):
with gr.Row():
confidence_slider = gr.Slider(
minimum=0,
maximum=1,
value=0.5,
step=0.01,
label=loc.localize("inference-settings-confidence-slider-label"),
info=loc.localize("inference-settings-confidence-slider-info"),
)
sensitivity_slider = gr.Slider(
minimum=0.5,
maximum=1.5,
value=1,
step=0.01,
label=loc.localize("inference-settings-sensitivity-slider-label"),
info=loc.localize("inference-settings-sensitivity-slider-info"),
)
overlap_slider = gr.Slider(
minimum=0,
maximum=2.99,
value=0,
step=0.01,
label=loc.localize("inference-settings-overlap-slider-label"),
info=loc.localize("inference-settings-overlap-slider-info"),
)
with gr.Row():
fmin_number = gr.Number(
cfg.SIG_FMIN,
minimum=0,
label=loc.localize("inference-settings-fmin-number-label"),
info=loc.localize("inference-settings-fmin-number-info"),
)
fmax_number = gr.Number(
cfg.SIG_FMAX,
minimum=0,
label=loc.localize("inference-settings-fmax-number-label"),
info=loc.localize("inference-settings-fmax-number-info"),
)
return confidence_slider, sensitivity_slider, overlap_slider, fmin_number, fmax_number
def locale():
"""Creates the gradio elements for locale selection
Reads the translated labels inside the checkpoints directory.
Returns:
The dropdown element.
"""
label_files = os.listdir(os.path.join(SCRIPT_DIR, ORIGINAL_TRANSLATED_LABELS_PATH))
options = ["EN"] + [label_file.rsplit("_", 1)[-1].split(".")[0].upper() for label_file in label_files]
return gr.Dropdown(
options,
value="EN",
label=loc.localize("analyze-locale-dropdown-label"),
info=loc.localize("analyze-locale-dropdown-info"),
)
def species_list_coordinates():
lat_number = gr.Slider(
minimum=-90,
maximum=90,
value=0,
step=1,
label=loc.localize("species-list-coordinates-lat-number-label"),
info=loc.localize("species-list-coordinates-lat-number-info"),
)
lon_number = gr.Slider(
minimum=-180,
maximum=180,
value=0,
step=1,
label=loc.localize("species-list-coordinates-lon-number-label"),
info=loc.localize("species-list-coordinates-lon-number-info"),
)
with gr.Row():
yearlong_checkbox = gr.Checkbox(True, label=loc.localize("species-list-coordinates-yearlong-checkbox-label"))
week_number = gr.Slider(
minimum=1,
maximum=48,
value=1,
step=1,
interactive=False,
label=loc.localize("species-list-coordinates-week-slider-label"),
info=loc.localize("species-list-coordinates-week-slider-info"),
)
def onChange(use_yearlong):
return gr.Slider(interactive=(not use_yearlong))
yearlong_checkbox.change(onChange, inputs=yearlong_checkbox, outputs=week_number, show_progress=False)
sf_thresh_number = gr.Slider(
minimum=0.01,
maximum=0.99,
value=0.03,
step=0.01,
label=loc.localize("species-list-coordinates-threshold-slider-label"),
info=loc.localize("species-list-coordinates-threshold-slider-info"),
)
return lat_number, lon_number, week_number, sf_thresh_number, yearlong_checkbox
def species_lists(opened=True):
"""Creates the gradio accordion for species selection.
Args:
opened: If True the accordion is open on init.
Returns:
A tuple with the created elements:
(Radio (choice), File (custom species list), Slider (lat), Slider (lon), Slider (week), Slider (threshold), Checkbox (yearlong?), State (custom classifier))
"""
with gr.Accordion(loc.localize("species-list-accordion-label"), open=opened):
with gr.Row():
species_list_radio = gr.Radio(
[_CUSTOM_SPECIES, _PREDICT_SPECIES, _CUSTOM_CLASSIFIER, _ALL_SPECIES],
value=_ALL_SPECIES,
label=loc.localize("species-list-radio-label"),
info=loc.localize("species-list-radio-info"),
elem_classes="d-block",
)
with gr.Column(visible=False) as position_row:
lat_number, lon_number, week_number, sf_thresh_number, yearlong_checkbox = species_list_coordinates()
species_file_input = gr.File(
file_types=[".txt"], visible=False, label=loc.localize("species-list-custom-list-file-label")
)
empty_col = gr.Column()
with gr.Column(visible=False) as custom_classifier_selector:
classifier_selection_button = gr.Button(
loc.localize("species-list-custom-classifier-selection-button-label")
)
classifier_file_input = gr.Files(file_types=[".tflite"], visible=False, interactive=False)
selected_classifier_state = gr.State()
def on_custom_classifier_selection_click():
file = select_file(("TFLite classifier (*.tflite)",))
if file:
labels = os.path.splitext(file)[0] + "_Labels.txt"
return file, gr.File(value=[file, labels], visible=True)
return None
classifier_selection_button.click(
on_custom_classifier_selection_click,
outputs=[selected_classifier_state, classifier_file_input],
show_progress=False,
)
species_list_radio.change(
show_species_choice,
inputs=[species_list_radio],
outputs=[position_row, species_file_input, custom_classifier_selector, empty_col],
show_progress=False,
)
return (
species_list_radio,
species_file_input,
lat_number,
lon_number,
week_number,
sf_thresh_number,
yearlong_checkbox,
selected_classifier_state,
)
if __name__ == "__main__":
multiprocessing.freeze_support()
def build_header():
# Custom HTML header with gr.Markdown
# There has to be another way, but this works for now; paths are weird in gradio
with gr.Row():
gr.Markdown(
f"""
<div style='display: flex; align-items: center;'>
<img src='data:image/png;base64,{utils.img2base64(os.path.join(SCRIPT_DIR, "gui/img/birdnet_logo.png"))}' style='width: 50px; height: 50px; margin-right: 10px;'>
<h2>BirdNET Analyzer</h2>
</div>
"""
)
def build_footer():
with gr.Row():
gr.Markdown(
f"""
<div style='display: flex; justify-content: space-around; align-items: center; padding: 10px; text-align: center'>
<div>
<div style="display: flex;flex-direction: row;">GUI version: <span id="current-version">{os.environ['GUI_VERSION'] if FROZEN else 'main'}</span><span style="display: none" id="update-available"><a>+</a></span></div>
<div>Model version: {cfg.MODEL_VERSION}</div>
</div>
<div>K. Lisa Yang Center for Conservation Bioacoustics<br>Chemnitz University of Technology</div>
<div>{loc.localize('footer-help')}:<br><a href='https://birdnet.cornell.edu/analyzer' target='_blank'>birdnet.cornell.edu/analyzer</a></div>
</div>
"""
)
def build_single_analysis_tab():
with gr.Tab(loc.localize("single-tab-title")):
audio_input = gr.Audio(type="filepath", label=loc.localize("single-audio-label"), sources=["upload"])
audio_path_state = gr.State()
confidence_slider, sensitivity_slider, overlap_slider, fmin_number, fmax_number = sample_sliders(False)
(
species_list_radio,
species_file_input,
lat_number,
lon_number,
week_number,
sf_thresh_number,
yearlong_checkbox,
selected_classifier_state,
) = species_lists(False)
locale_radio = locale()
def get_audio_path(i):
if i:
return i["path"], gr.Audio(i["path"], type="filepath", label=os.path.basename(i["path"]))
else:
return None, None
audio_input.change(
get_audio_path, inputs=audio_input, outputs=[audio_path_state, audio_input], preprocess=False
)
inputs = [
audio_path_state,
confidence_slider,
sensitivity_slider,
overlap_slider,
fmin_number,
fmax_number,
species_list_radio,
species_file_input,
lat_number,
lon_number,
week_number,
yearlong_checkbox,
sf_thresh_number,
selected_classifier_state,
locale_radio,
]
output_dataframe = gr.Dataframe(
type="pandas",
headers=[
loc.localize("single-tab-output-header-start"),
loc.localize("single-tab-output-header-end"),