birdnet-analyzer 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. birdnet_analyzer/__init__.py +8 -0
  2. birdnet_analyzer/analyze/__init__.py +5 -0
  3. birdnet_analyzer/analyze/__main__.py +4 -0
  4. birdnet_analyzer/analyze/cli.py +25 -0
  5. birdnet_analyzer/analyze/core.py +245 -0
  6. birdnet_analyzer/analyze/utils.py +701 -0
  7. birdnet_analyzer/audio.py +372 -0
  8. birdnet_analyzer/cli.py +707 -0
  9. birdnet_analyzer/config.py +242 -0
  10. birdnet_analyzer/eBird_taxonomy_codes_2021E.json +25280 -0
  11. birdnet_analyzer/embeddings/__init__.py +4 -0
  12. birdnet_analyzer/embeddings/__main__.py +3 -0
  13. birdnet_analyzer/embeddings/cli.py +13 -0
  14. birdnet_analyzer/embeddings/core.py +70 -0
  15. birdnet_analyzer/embeddings/utils.py +193 -0
  16. birdnet_analyzer/evaluation/__init__.py +195 -0
  17. birdnet_analyzer/evaluation/__main__.py +3 -0
  18. birdnet_analyzer/gui/__init__.py +23 -0
  19. birdnet_analyzer/gui/__main__.py +3 -0
  20. birdnet_analyzer/gui/analysis.py +174 -0
  21. birdnet_analyzer/gui/assets/arrow_down.svg +4 -0
  22. birdnet_analyzer/gui/assets/arrow_left.svg +4 -0
  23. birdnet_analyzer/gui/assets/arrow_right.svg +4 -0
  24. birdnet_analyzer/gui/assets/arrow_up.svg +4 -0
  25. birdnet_analyzer/gui/assets/gui.css +29 -0
  26. birdnet_analyzer/gui/assets/gui.js +94 -0
  27. birdnet_analyzer/gui/assets/img/birdnet-icon.ico +0 -0
  28. birdnet_analyzer/gui/assets/img/birdnet_logo.png +0 -0
  29. birdnet_analyzer/gui/assets/img/birdnet_logo_no_transparent.png +0 -0
  30. birdnet_analyzer/gui/assets/img/clo-logo-bird.svg +1 -0
  31. birdnet_analyzer/gui/embeddings.py +620 -0
  32. birdnet_analyzer/gui/evaluation.py +813 -0
  33. birdnet_analyzer/gui/localization.py +68 -0
  34. birdnet_analyzer/gui/multi_file.py +246 -0
  35. birdnet_analyzer/gui/review.py +527 -0
  36. birdnet_analyzer/gui/segments.py +191 -0
  37. birdnet_analyzer/gui/settings.py +129 -0
  38. birdnet_analyzer/gui/single_file.py +269 -0
  39. birdnet_analyzer/gui/species.py +95 -0
  40. birdnet_analyzer/gui/train.py +698 -0
  41. birdnet_analyzer/gui/utils.py +808 -0
  42. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_af.txt +6522 -0
  43. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_ar.txt +6522 -0
  44. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_bg.txt +6522 -0
  45. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_ca.txt +6522 -0
  46. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_cs.txt +6522 -0
  47. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_da.txt +6522 -0
  48. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_de.txt +6522 -0
  49. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_el.txt +6522 -0
  50. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_en_uk.txt +6522 -0
  51. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_es.txt +6522 -0
  52. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_fi.txt +6522 -0
  53. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_fr.txt +6522 -0
  54. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_he.txt +6522 -0
  55. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_hr.txt +6522 -0
  56. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_hu.txt +6522 -0
  57. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_in.txt +6522 -0
  58. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_is.txt +6522 -0
  59. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_it.txt +6522 -0
  60. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_ja.txt +6522 -0
  61. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_ko.txt +6522 -0
  62. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_lt.txt +6522 -0
  63. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_ml.txt +6522 -0
  64. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_nl.txt +6522 -0
  65. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_no.txt +6522 -0
  66. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_pl.txt +6522 -0
  67. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_pt_BR.txt +6522 -0
  68. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_pt_PT.txt +6522 -0
  69. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_ro.txt +6522 -0
  70. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_ru.txt +6522 -0
  71. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_sk.txt +6522 -0
  72. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_sl.txt +6522 -0
  73. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_sr.txt +6522 -0
  74. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_sv.txt +6522 -0
  75. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_th.txt +6522 -0
  76. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_tr.txt +6522 -0
  77. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_uk.txt +6522 -0
  78. birdnet_analyzer/labels/V2.4/BirdNET_GLOBAL_6K_V2.4_Labels_zh.txt +6522 -0
  79. birdnet_analyzer/lang/de.json +335 -0
  80. birdnet_analyzer/lang/en.json +335 -0
  81. birdnet_analyzer/lang/fi.json +335 -0
  82. birdnet_analyzer/lang/fr.json +335 -0
  83. birdnet_analyzer/lang/id.json +335 -0
  84. birdnet_analyzer/lang/pt-br.json +335 -0
  85. birdnet_analyzer/lang/ru.json +335 -0
  86. birdnet_analyzer/lang/se.json +335 -0
  87. birdnet_analyzer/lang/tlh.json +335 -0
  88. birdnet_analyzer/lang/zh_TW.json +335 -0
  89. birdnet_analyzer/model.py +1243 -0
  90. birdnet_analyzer/search/__init__.py +3 -0
  91. birdnet_analyzer/search/__main__.py +3 -0
  92. birdnet_analyzer/search/cli.py +12 -0
  93. birdnet_analyzer/search/core.py +78 -0
  94. birdnet_analyzer/search/utils.py +111 -0
  95. birdnet_analyzer/segments/__init__.py +3 -0
  96. birdnet_analyzer/segments/__main__.py +3 -0
  97. birdnet_analyzer/segments/cli.py +14 -0
  98. birdnet_analyzer/segments/core.py +78 -0
  99. birdnet_analyzer/segments/utils.py +394 -0
  100. birdnet_analyzer/species/__init__.py +3 -0
  101. birdnet_analyzer/species/__main__.py +3 -0
  102. birdnet_analyzer/species/cli.py +14 -0
  103. birdnet_analyzer/species/core.py +35 -0
  104. birdnet_analyzer/species/utils.py +75 -0
  105. birdnet_analyzer/train/__init__.py +3 -0
  106. birdnet_analyzer/train/__main__.py +3 -0
  107. birdnet_analyzer/train/cli.py +14 -0
  108. birdnet_analyzer/train/core.py +113 -0
  109. birdnet_analyzer/train/utils.py +847 -0
  110. birdnet_analyzer/translate.py +104 -0
  111. birdnet_analyzer/utils.py +419 -0
  112. birdnet_analyzer-2.0.0.dist-info/METADATA +129 -0
  113. birdnet_analyzer-2.0.0.dist-info/RECORD +117 -0
  114. birdnet_analyzer-2.0.0.dist-info/WHEEL +5 -0
  115. birdnet_analyzer-2.0.0.dist-info/entry_points.txt +11 -0
  116. birdnet_analyzer-2.0.0.dist-info/licenses/LICENSE +19 -0
  117. birdnet_analyzer-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,808 @@
1
+ import multiprocessing
2
+ import os
3
+ import sys
4
+ from collections.abc import Callable
5
+ from contextlib import suppress
6
+ from pathlib import Path
7
+
8
+ import gradio as gr
9
+ import webview
10
+
11
+ import birdnet_analyzer.config as cfg
12
+ import birdnet_analyzer.utils as utils
13
+
14
+
15
+ if utils.FROZEN:
16
+ # divert stdout & stderr to logs.txt file since we have no console when deployed
17
+ userdir = Path.home()
18
+
19
+ if sys.platform == "win32":
20
+ userdir /= "AppData/Roaming"
21
+ elif sys.platform == "linux":
22
+ userdir /= ".local/share"
23
+ elif sys.platform == "darwin":
24
+ userdir /= "Library/Application Support"
25
+
26
+ APPDIR = userdir / "BirdNET-Analyzer-GUI"
27
+
28
+ APPDIR.mkdir(parents=True, exist_ok=True)
29
+
30
+ sys.stderr = sys.stdout = open(str(APPDIR / "logs.txt"), "a")
31
+ cfg.ERROR_LOG_FILE = str(APPDIR / os.path.basename(cfg.ERROR_LOG_FILE))
32
+
33
+ import birdnet_analyzer.gui.settings as settings # noqa: E402
34
+ import birdnet_analyzer.gui.localization as loc # noqa: E402
35
+
36
+ loc.load_local_state()
37
+
38
+ SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
39
+ ORIGINAL_TRANSLATED_LABELS_PATH = str(Path(SCRIPT_DIR).parent / cfg.TRANSLATED_LABELS_PATH)
40
+ _CUSTOM_SPECIES = loc.localize("species-list-radio-option-custom-list")
41
+ _PREDICT_SPECIES = loc.localize("species-list-radio-option-predict-list")
42
+ _CUSTOM_CLASSIFIER = loc.localize("species-list-radio-option-custom-classifier")
43
+ _ALL_SPECIES = loc.localize("species-list-radio-option-all")
44
+ _WINDOW: webview.Window = None
45
+ _URL = ""
46
+
47
+
48
+ def gui_runtime_error_handler(f: callable):
49
+ """
50
+ A decorator function to handle errors during the execution of a callable.
51
+
52
+ This function attempts to execute the provided callable `f`. If an exception
53
+ occurs during execution, it logs the error using `utils.write_error_log` and
54
+ raises a `gr.Error` exception.
55
+
56
+ Args:
57
+ f (callable): The function or callable object to be executed.
58
+
59
+ Returns:
60
+ The result of the callable `f` if no exception occurs.
61
+
62
+ Raises:
63
+ gr.Error: If an exception is raised during the execution of `f`.
64
+ """
65
+
66
+ def wrapper(*args, **kwargs):
67
+ try:
68
+ return f(*args, **kwargs)
69
+ except Exception as e:
70
+ utils.write_error_log(e)
71
+ raise gr.Error(message=str(e), duration=None) from e
72
+
73
+ return wrapper
74
+
75
+
76
+ # Nishant - Following two functions (select_folder and get_files_and_durations) are written for Folder selection
77
+ def select_folder(state_key=None):
78
+ """
79
+ Opens a folder selection dialog and returns the selected folder path.
80
+ On Windows, it uses tkinter's filedialog to open the folder selection dialog.
81
+ On other platforms, it uses webview's FOLDER_DIALOG to open the folder selection dialog.
82
+ If a state_key is provided, the initial directory for the dialog is retrieved from the state.
83
+ If a folder is selected and a state_key is provided, the selected folder path is saved to the state.
84
+ Args:
85
+ state_key (str, optional): The key to retrieve and save the folder path in the state. Defaults to None.
86
+ Returns:
87
+ str: The path of the selected folder, or None if no folder was selected.
88
+ """
89
+ if sys.platform == "win32":
90
+ from tkinter import Tk, filedialog
91
+
92
+ tk = Tk()
93
+ tk.withdraw()
94
+
95
+ initial_dir = settings.get_state(state_key, None) if state_key else None
96
+ folder_selected = filedialog.askdirectory(initialdir=initial_dir)
97
+
98
+ tk.destroy()
99
+ else:
100
+ initial_dir = settings.get_state(state_key, "") if state_key else ""
101
+ dirname = _WINDOW.create_file_dialog(webview.FOLDER_DIALOG, directory=initial_dir)
102
+ folder_selected = dirname[0] if dirname else None
103
+
104
+ if folder_selected and state_key:
105
+ settings.set_state(state_key, folder_selected)
106
+
107
+ return folder_selected
108
+
109
+
110
+ def get_audio_files_and_durations(folder, max_files=None):
111
+ """
112
+ Collects audio files from a specified folder and retrieves their durations.
113
+ Args:
114
+ folder (str): The path to the folder containing audio files.
115
+ max_files (int, optional): The maximum number of files to collect. If None, all files are collected.
116
+ Returns:
117
+ list: A list of lists, where each inner list contains the relative file path and its duration as a string.
118
+ """
119
+ import librosa
120
+
121
+ files_and_durations = []
122
+ files = utils.collect_audio_files(folder, max_files=max_files) # Use the collect_audio_files function
123
+
124
+ for file_path in files:
125
+ try:
126
+ duration = format_seconds(librosa.get_duration(path=file_path))
127
+
128
+ except Exception as _:
129
+ duration = "0:00" # Default value in case of an error
130
+
131
+ files_and_durations.append([os.path.relpath(file_path, folder), duration])
132
+ return files_and_durations
133
+
134
+
135
+ def set_window(window):
136
+ """
137
+ Sets the global _WINDOW variable to the provided window object.
138
+
139
+ Args:
140
+ window: The window object to be set as the global _WINDOW.
141
+ """
142
+ global _WINDOW
143
+ _WINDOW = window
144
+
145
+
146
+ def validate(value, msg):
147
+ """Checks if the value ist not falsy.
148
+
149
+ If the value is falsy, an error will be raised.
150
+
151
+ Args:
152
+ value: Value to be tested.
153
+ msg: Message in case of an error.
154
+ """
155
+ if not value:
156
+ raise gr.Error(msg)
157
+
158
+
159
+ def format_seconds(secs: float):
160
+ """Formats a number of seconds into a string.
161
+
162
+ Formats the seconds into the format "h:mm:ss.ms"
163
+
164
+ Args:
165
+ secs: Number of seconds.
166
+
167
+ Returns:
168
+ A string with the formatted seconds.
169
+ """
170
+ hours, secs = divmod(secs, 3600)
171
+ minutes, secs = divmod(secs, 60)
172
+
173
+ return f"{hours:2.0f}:{minutes:02.0f}:{secs:06.3f}"
174
+
175
+
176
+ def select_directory(collect_files=True, max_files=None, state_key=None):
177
+ """Shows a directory selection system dialog.
178
+
179
+ Uses the pywebview to create a system dialog.
180
+
181
+ Args:
182
+ collect_files: If True, also lists a files inside the directory.
183
+
184
+ Returns:
185
+ If collect_files==True, returns (directory path, list of (relative file path, audio length))
186
+ else just the directory path.
187
+ All values will be None of the dialog is cancelled.
188
+ """
189
+ import librosa
190
+
191
+ dir_name = select_folder(state_key=state_key)
192
+
193
+ if collect_files:
194
+ if not dir_name:
195
+ return None, None
196
+
197
+ files = utils.collect_audio_files(dir_name, max_files=max_files)
198
+
199
+ return dir_name, [
200
+ [os.path.relpath(file, dir_name), format_seconds(librosa.get_duration(filename=file))] for file in files
201
+ ]
202
+
203
+ return dir_name if dir_name else None
204
+
205
+
206
+ def build_header():
207
+ with gr.Row():
208
+ gr.Markdown(
209
+ f"""
210
+ <div style='display: flex; align-items: center;'>
211
+ <img src='data:image/png;base64,{utils.img2base64(os.path.join(SCRIPT_DIR, "assets/img/birdnet_logo.png"))}' style='width: 50px; height: 50px; margin-right: 10px;'>
212
+ <h2>BirdNET Analyzer</h2>
213
+ </div>
214
+ """
215
+ )
216
+
217
+
218
+ def build_footer():
219
+ with gr.Row():
220
+ gr.Markdown(
221
+ f"""
222
+ <div style='display: flex; justify-content: space-around; align-items: center; padding: 10px; text-align: center'>
223
+ <div>
224
+ <div style="display: flex;flex-direction: row;">GUI version:&nbsp<span id="current-version">{os.environ["GUI_VERSION"] if utils.FROZEN else "main"}</span><span style="display: none" id="update-available"><a>+</a></span></div>
225
+ <div>Model version: {cfg.MODEL_VERSION}</div>
226
+ </div>
227
+ <div>K. Lisa Yang Center for Conservation Bioacoustics<br>Chemnitz University of Technology</div>
228
+ <div>{loc.localize("footer-help")}:<br><a href='https://birdnet.cornell.edu/analyzer' target='_blank'>birdnet.cornell.edu/analyzer</a></div>
229
+ </div>
230
+ """
231
+ )
232
+
233
+
234
+ def build_settings():
235
+ with gr.Tab(loc.localize("settings-tab-title")) as settings_tab:
236
+ with gr.Group():
237
+ with gr.Row():
238
+ options = [lang.rsplit(".", 1)[0] for lang in os.listdir(loc.LANGUAGE_DIR) if lang.endswith(".json")]
239
+ languages_dropdown = gr.Dropdown(
240
+ options,
241
+ value=loc.TARGET_LANGUAGE,
242
+ label=loc.localize("settings-tab-language-dropdown-label"),
243
+ info=loc.localize("settings-tab-language-dropdown-info"),
244
+ interactive=True,
245
+ )
246
+
247
+ with gr.Row():
248
+ theme_radio = gr.Radio(
249
+ [
250
+ (loc.localize("settings-tab-theme-dropdown-dark-option"), "dark"),
251
+ (loc.localize("settings-tab-theme-dropdown-light-option"), "light"),
252
+ ],
253
+ value=lambda: settings.theme(),
254
+ label=loc.localize("settings-tab-theme-dropdown-label"),
255
+ info="⚠️" + loc.localize("settings-tab-theme-dropdown-info"),
256
+ interactive=True,
257
+ scale=10,
258
+ )
259
+
260
+ gr.Markdown(
261
+ """
262
+ If you encounter a bug or error, please provide the error log.\n
263
+ You can submit an issue on our [GitHub](https://github.com/birdnet-team/BirdNET-Analyzer/issues).
264
+ """,
265
+ label=loc.localize("settings-tab-error-log-textbox-label"),
266
+ elem_classes="mh-200",
267
+ )
268
+
269
+ error_log_tb = gr.TextArea(
270
+ label=loc.localize("settings-tab-error-log-textbox-label"),
271
+ info=f"{loc.localize('settings-tab-error-log-textbox-info-path')}: {cfg.ERROR_LOG_FILE}",
272
+ interactive=False,
273
+ placeholder=loc.localize("settings-tab-error-log-textbox-placeholder"),
274
+ show_copy_button=True,
275
+ )
276
+
277
+ def on_language_change(value):
278
+ loc.set_language(value)
279
+ gr.Warning(loc.localize("settings-tab-language-dropdown-info"))
280
+
281
+ def on_theme_change(value):
282
+ prev_theme = settings.theme()
283
+ if prev_theme != value:
284
+ settings.set_setting("theme", value)
285
+ _WINDOW.load_url(_URL.rstrip("/") + f"?__theme={value}")
286
+
287
+ def on_tab_select(value: gr.SelectData):
288
+ if value.selected and os.path.exists(cfg.ERROR_LOG_FILE):
289
+ with open(cfg.ERROR_LOG_FILE, "r", encoding="utf-8") as f:
290
+ lines = f.readlines()
291
+ last_100_lines = lines[-100:]
292
+ return "".join(last_100_lines)
293
+
294
+ return ""
295
+
296
+ languages_dropdown.input(on_language_change, inputs=languages_dropdown, show_progress=False)
297
+ theme_radio.input(on_theme_change, inputs=theme_radio, show_progress=False)
298
+ settings_tab.select(on_tab_select, outputs=error_log_tb, show_progress=False)
299
+
300
+
301
+ def sample_sliders(opened=True):
302
+ """Creates the gradio accordion for the inference settings.
303
+
304
+ Args:
305
+ opened: If True the accordion is open on init.
306
+
307
+ Returns:
308
+ A tuple with the created elements:
309
+ (Slider (min confidence), Slider (sensitivity), Slider (overlap), Slider (audio speed), Number (fmin), Number (fmax))
310
+ """
311
+ with gr.Accordion(loc.localize("inference-settings-accordion-label"), open=opened):
312
+ with gr.Group():
313
+ with gr.Row():
314
+ use_top_n_checkbox = gr.Checkbox(
315
+ label=loc.localize("inference-settings-use-top-n-checkbox-label"),
316
+ value=False,
317
+ info=loc.localize("inference-settings-use-top-n-checkbox-info"),
318
+ )
319
+ top_n_input = gr.Number(
320
+ value=5,
321
+ minimum=1,
322
+ precision=1,
323
+ visible=False,
324
+ label=loc.localize("inference-settings-top-n-number-label"),
325
+ info=loc.localize("inference-settings-top-n-number-info"),
326
+ )
327
+ confidence_slider = gr.Slider(
328
+ minimum=0.05,
329
+ maximum=0.95,
330
+ value=cfg.MIN_CONFIDENCE,
331
+ step=0.05,
332
+ label=loc.localize("inference-settings-confidence-slider-label"),
333
+ info=loc.localize("inference-settings-confidence-slider-info"),
334
+ )
335
+
336
+ use_top_n_checkbox.change(
337
+ lambda use_top_n: (gr.Number(visible=use_top_n), gr.Slider(visible=not use_top_n)),
338
+ inputs=use_top_n_checkbox,
339
+ outputs=[top_n_input, confidence_slider],
340
+ show_progress=False,
341
+ )
342
+
343
+ with gr.Row():
344
+ sensitivity_slider = gr.Slider(
345
+ minimum=0.75,
346
+ maximum=1.25,
347
+ value=cfg.SIGMOID_SENSITIVITY,
348
+ step=0.01,
349
+ label=loc.localize("inference-settings-sensitivity-slider-label"),
350
+ info=loc.localize("inference-settings-sensitivity-slider-info"),
351
+ )
352
+ overlap_slider = gr.Slider(
353
+ minimum=0,
354
+ maximum=2.9,
355
+ value=cfg.SIG_OVERLAP,
356
+ step=0.1,
357
+ label=loc.localize("inference-settings-overlap-slider-label"),
358
+ info=loc.localize("inference-settings-overlap-slider-info"),
359
+ )
360
+
361
+ with gr.Row():
362
+ merge_consecutive_slider = gr.Slider(
363
+ minimum=1,
364
+ maximum=10,
365
+ value=cfg.MERGE_CONSECUTIVE,
366
+ step=1,
367
+ label=loc.localize("inference-settings-merge-consecutive-slider-label"),
368
+ info=loc.localize("inference-settings-merge-consecutive-slider-info"),
369
+ )
370
+ audio_speed_slider = gr.Slider(
371
+ minimum=-10,
372
+ maximum=10,
373
+ value=cfg.AUDIO_SPEED,
374
+ step=1,
375
+ label=loc.localize("inference-settings-audio-speed-slider-label"),
376
+ info=loc.localize("inference-settings-audio-speed-slider-info"),
377
+ )
378
+
379
+ with gr.Row():
380
+ fmin_number = gr.Number(
381
+ cfg.SIG_FMIN,
382
+ minimum=0,
383
+ label=loc.localize("inference-settings-fmin-number-label"),
384
+ info=loc.localize("inference-settings-fmin-number-info"),
385
+ )
386
+
387
+ fmax_number = gr.Number(
388
+ cfg.SIG_FMAX,
389
+ minimum=0,
390
+ label=loc.localize("inference-settings-fmax-number-label"),
391
+ info=loc.localize("inference-settings-fmax-number-info"),
392
+ )
393
+
394
+ return (
395
+ use_top_n_checkbox,
396
+ top_n_input,
397
+ confidence_slider,
398
+ sensitivity_slider,
399
+ overlap_slider,
400
+ merge_consecutive_slider,
401
+ audio_speed_slider,
402
+ fmin_number,
403
+ fmax_number,
404
+ )
405
+
406
+
407
+ def locale():
408
+ """Creates the gradio elements for locale selection
409
+
410
+ Reads the translated labels inside the checkpoints directory.
411
+
412
+ Returns:
413
+ The dropdown element.
414
+ """
415
+ label_files = os.listdir(ORIGINAL_TRANSLATED_LABELS_PATH)
416
+ options = ["EN"] + [
417
+ label_file.split("BirdNET_GLOBAL_6K_V2.4_Labels_", 1)[1].split(".txt")[0].upper() for label_file in label_files
418
+ ]
419
+
420
+ return gr.Dropdown(
421
+ options,
422
+ value="EN",
423
+ label=loc.localize("analyze-locale-dropdown-label"),
424
+ info=loc.localize("analyze-locale-dropdown-info"),
425
+ )
426
+
427
+
428
+ def plot_map_scatter_mapbox(lat, lon, zoom=4):
429
+ import plotly.express as px
430
+
431
+ fig = px.scatter_map(lat=[lat], lon=[lon], zoom=zoom, map_style="open-street-map", size=[10])
432
+ # fig.update_traces(marker=dict(size=10, color="red")) # Explicitly set color and size
433
+ fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
434
+ return fig
435
+
436
+
437
+ def species_list_coordinates(show_map=False):
438
+ with gr.Row(equal_height=True):
439
+ with gr.Column(scale=1):
440
+ with gr.Group():
441
+ lat_number = gr.Slider(
442
+ minimum=-90,
443
+ maximum=90,
444
+ value=0,
445
+ step=1,
446
+ label=loc.localize("species-list-coordinates-lat-number-label"),
447
+ info=loc.localize("species-list-coordinates-lat-number-info"),
448
+ )
449
+ lon_number = gr.Slider(
450
+ minimum=-180,
451
+ maximum=180,
452
+ value=0,
453
+ step=1,
454
+ label=loc.localize("species-list-coordinates-lon-number-label"),
455
+ info=loc.localize("species-list-coordinates-lon-number-info"),
456
+ )
457
+
458
+ map_plot = gr.Plot(plot_map_scatter_mapbox(0, 0), show_label=False, scale=2, visible=show_map)
459
+
460
+ lat_number.change(
461
+ plot_map_scatter_mapbox, inputs=[lat_number, lon_number], outputs=map_plot, show_progress=False
462
+ )
463
+ lon_number.change(
464
+ plot_map_scatter_mapbox, inputs=[lat_number, lon_number], outputs=map_plot, show_progress=False
465
+ )
466
+
467
+ with gr.Group():
468
+ with gr.Row():
469
+ yearlong_checkbox = gr.Checkbox(
470
+ True, label=loc.localize("species-list-coordinates-yearlong-checkbox-label")
471
+ )
472
+ week_number = gr.Slider(
473
+ minimum=1,
474
+ maximum=48,
475
+ value=1,
476
+ step=1,
477
+ interactive=False,
478
+ label=loc.localize("species-list-coordinates-week-slider-label"),
479
+ info=loc.localize("species-list-coordinates-week-slider-info"),
480
+ )
481
+
482
+ sf_thresh_number = gr.Slider(
483
+ minimum=0.01,
484
+ maximum=0.99,
485
+ value=cfg.LOCATION_FILTER_THRESHOLD,
486
+ step=0.01,
487
+ label=loc.localize("species-list-coordinates-threshold-slider-label"),
488
+ info=loc.localize("species-list-coordinates-threshold-slider-info"),
489
+ )
490
+
491
+ def on_change(use_yearlong):
492
+ return gr.Slider(interactive=(not use_yearlong))
493
+
494
+ yearlong_checkbox.change(on_change, inputs=yearlong_checkbox, outputs=week_number, show_progress=False)
495
+
496
+ return lat_number, lon_number, week_number, sf_thresh_number, yearlong_checkbox, map_plot
497
+
498
+
499
+ def save_file_dialog(filetypes=(), state_key=None, default_filename=""):
500
+ """Creates a file save dialog.
501
+
502
+ Args:
503
+ filetypes: List of filetypes to be filtered in the dialog.
504
+
505
+ Returns:
506
+ The selected file or None of the dialog was canceled.
507
+ """
508
+ initial_selection = settings.get_state(state_key, "") if state_key else ""
509
+ file = _WINDOW.create_file_dialog(
510
+ webview.SAVE_DIALOG, file_types=filetypes, directory=initial_selection, save_filename=default_filename
511
+ )
512
+
513
+ if file:
514
+ if state_key:
515
+ settings.set_state(state_key, os.path.dirname(file))
516
+
517
+ return file
518
+
519
+ return None
520
+
521
+
522
+ def select_file(filetypes=(), state_key=None):
523
+ """Creates a file selection dialog.
524
+
525
+ Args:
526
+ filetypes: List of filetypes to be filtered in the dialog.
527
+
528
+ Returns:
529
+ The selected file or None of the dialog was canceled.
530
+ """
531
+ initial_selection = settings.get_state(state_key, "") if state_key else ""
532
+ files = _WINDOW.create_file_dialog(webview.OPEN_DIALOG, file_types=filetypes, directory=initial_selection)
533
+
534
+ if files:
535
+ if state_key:
536
+ settings.set_state(state_key, os.path.dirname(files[0]))
537
+
538
+ return files[0]
539
+
540
+ return None
541
+
542
+
543
+ def show_species_choice(choice: str):
544
+ """Sets the visibility of the species list choices.
545
+
546
+ Args:
547
+ choice: The label of the currently active choice.
548
+
549
+ Returns:
550
+ A list of [
551
+ Row update,
552
+ File update,
553
+ Column update,
554
+ Column update,
555
+ ]
556
+ """
557
+ if choice == _CUSTOM_SPECIES:
558
+ return [
559
+ gr.Row(visible=False),
560
+ gr.File(visible=True),
561
+ gr.Column(visible=False),
562
+ gr.Column(visible=False),
563
+ ]
564
+ elif choice == _PREDICT_SPECIES:
565
+ return [
566
+ gr.Row(visible=True),
567
+ gr.File(visible=False),
568
+ gr.Column(visible=False),
569
+ gr.Column(visible=False),
570
+ ]
571
+ elif choice == _CUSTOM_CLASSIFIER:
572
+ return [
573
+ gr.Row(visible=False),
574
+ gr.File(visible=False),
575
+ gr.Column(visible=True),
576
+ gr.Column(visible=False),
577
+ ]
578
+
579
+ return [
580
+ gr.Row(visible=False),
581
+ gr.File(visible=False),
582
+ gr.Column(visible=False),
583
+ gr.Column(visible=True),
584
+ ]
585
+
586
+
587
+ def species_lists(opened=True):
588
+ """Creates the gradio accordion for species selection.
589
+
590
+ Args:
591
+ opened: If True the accordion is open on init.
592
+
593
+ Returns:
594
+ A tuple with the created elements:
595
+ (Radio (choice), File (custom species list), Slider (lat), Slider (lon), Slider (week), Slider (threshold), Checkbox (yearlong?), State (custom classifier))
596
+ """
597
+ with gr.Accordion(loc.localize("species-list-accordion-label"), open=opened):
598
+ with gr.Row():
599
+ species_list_radio = gr.Radio(
600
+ [_CUSTOM_SPECIES, _PREDICT_SPECIES, _CUSTOM_CLASSIFIER, _ALL_SPECIES],
601
+ value=_ALL_SPECIES,
602
+ label=loc.localize("species-list-radio-label"),
603
+ info=loc.localize("species-list-radio-info"),
604
+ elem_classes="d-block",
605
+ )
606
+
607
+ with gr.Column(visible=False) as position_row:
608
+ lat_number, lon_number, week_number, sf_thresh_number, yearlong_checkbox, map_plot = (
609
+ species_list_coordinates()
610
+ )
611
+
612
+ species_file_input = gr.File(
613
+ file_types=[".txt"], visible=False, label=loc.localize("species-list-custom-list-file-label")
614
+ )
615
+ empty_col = gr.Column()
616
+
617
+ with gr.Column(visible=False) as custom_classifier_selector:
618
+ classifier_selection_button = gr.Button(
619
+ loc.localize("species-list-custom-classifier-selection-button-label")
620
+ )
621
+ classifier_file_input = gr.Files(file_types=[".tflite"], visible=False, interactive=False)
622
+ selected_classifier_state = gr.State()
623
+
624
+ def on_custom_classifier_selection_click():
625
+ file = select_file(("TFLite classifier (*.tflite)",), state_key="custom_classifier_file")
626
+
627
+ if file:
628
+ labels = os.path.splitext(file)[0] + "_Labels.txt"
629
+
630
+ if not os.path.isfile(labels):
631
+ labels = file.replace("Model_FP32.tflite", "Labels.txt")
632
+
633
+ return file, gr.File(value=[file, labels], visible=True)
634
+
635
+ return None, None
636
+
637
+ classifier_selection_button.click(
638
+ on_custom_classifier_selection_click,
639
+ outputs=[selected_classifier_state, classifier_file_input],
640
+ show_progress=False,
641
+ )
642
+
643
+ species_list_radio.change(
644
+ show_species_choice,
645
+ inputs=[species_list_radio],
646
+ outputs=[position_row, species_file_input, custom_classifier_selector, empty_col],
647
+ show_progress=False,
648
+ )
649
+
650
+ return (
651
+ species_list_radio,
652
+ species_file_input,
653
+ lat_number,
654
+ lon_number,
655
+ week_number,
656
+ sf_thresh_number,
657
+ yearlong_checkbox,
658
+ selected_classifier_state,
659
+ map_plot,
660
+ )
661
+
662
+
663
+ def _get_network_shortcuts():
664
+ """
665
+ Retrieves a list of network shortcut paths from the user's Network Shortcuts folder.
666
+ This function accesses the Network Shortcuts folder (Nethood) on a Windows system,
667
+ iterates through its contents, and attempts to resolve `.lnk` files (shortcuts)
668
+ to their target paths. If successful, the resolved paths are added to the list of shortcuts.
669
+ Returns:
670
+ list: A list of resolved network shortcut paths.
671
+ Notes:
672
+ - This function uses the `pythoncom` and `win32com.shell` modules, which are part of the
673
+ `pywin32` package.
674
+ - Errors encountered while resolving shortcuts are printed to the console.
675
+ """
676
+ import pythoncom
677
+ from win32com.shell import shell, shellcon # type: ignore[import]
678
+
679
+ try:
680
+ # https://learn.microsoft.com/de-de/windows/win32/shell/csidl
681
+ # CSIDL_NETHOOD: Path to folder containing network shortcuts
682
+ network_shortcuts = shell.SHGetFolderPath(0, shellcon.CSIDL_NETHOOD, None, 0)
683
+ shortcuts = []
684
+
685
+ for item in os.listdir(network_shortcuts):
686
+ item_path = os.path.join(network_shortcuts, item)
687
+
688
+ if os.path.isdir(item_path):
689
+ # network shortcuts are folders containing a target.lnk file
690
+ target_lnk = os.path.join(item_path, "target.lnk")
691
+
692
+ if os.path.exists(target_lnk):
693
+ try:
694
+ # https://learn.microsoft.com/de-de/windows/win32/shell/links
695
+ # CLSID_ShellLink: Class ID for Shell Link object
696
+ shell_link = pythoncom.CoCreateInstance(
697
+ shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink
698
+ )
699
+
700
+ # https://learn.microsoft.com/de-de/windows/win32/api/objidl/nn-objidl-ipersistfile
701
+ # Query IPersistFile interface used to
702
+ persist_file = shell_link.QueryInterface(pythoncom.IID_IPersistFile)
703
+
704
+ # https://learn.microsoft.com/de-de/windows/win32/api/objidl/nf-objidl-ipersistfile-load
705
+ # Load shell link file
706
+ persist_file.Load(target_lnk)
707
+
708
+ # https://learn.microsoft.com/de-de/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinka-getpath
709
+ path_buffer, _ = shell_link.GetPath(shell.SLGP_RAWPATH)
710
+
711
+ shortcuts.append(path_buffer)
712
+ except Exception as e:
713
+ print(f"Error reading {target_lnk}: {e}")
714
+ raise e
715
+
716
+ return shortcuts
717
+ except Exception as e:
718
+ utils.write_error_log(e)
719
+ return []
720
+
721
+
722
+ def _get_win_drives():
723
+ from string import ascii_uppercase as UPPER_CASE
724
+
725
+ return [f"{drive}:\\" for drive in UPPER_CASE] + _get_network_shortcuts()
726
+
727
+
728
+ def open_window(builder: list[Callable] | Callable):
729
+ """
730
+ Opens a GUI window using the Gradio library and the webview module.
731
+ Args:
732
+ builder (list[Callable] | Callable): A callable or a list of callables that build the GUI components.
733
+ """
734
+ global _URL
735
+ multiprocessing.freeze_support()
736
+
737
+ utils.ensure_model_exists()
738
+
739
+ with gr.Blocks(
740
+ css=open(os.path.join(SCRIPT_DIR, "assets/gui.css")).read(),
741
+ js=open(os.path.join(SCRIPT_DIR, "assets/gui.js")).read(),
742
+ theme=gr.themes.Default(),
743
+ analytics_enabled=False,
744
+ ) as demo:
745
+ build_header()
746
+
747
+ map_plots = []
748
+
749
+ if callable(builder):
750
+ map_plots.append(builder())
751
+ elif isinstance(builder, (tuple, set, list)):
752
+ for build in builder:
753
+ map_plots.append(build())
754
+
755
+ build_settings()
756
+ build_footer()
757
+
758
+ map_plots = [plot for plot in map_plots if plot]
759
+
760
+ if map_plots:
761
+ inputs = []
762
+ outputs = []
763
+ for lat, lon, plot in map_plots:
764
+ inputs.extend([lat, lon])
765
+ outputs.append(plot)
766
+
767
+ def update_plots(*args):
768
+ return [plot_map_scatter_mapbox(lat, lon) for lat, lon in utils.batched(args, 2, strict=True)]
769
+
770
+ demo.load(update_plots, inputs=inputs, outputs=outputs)
771
+
772
+ _URL = demo.queue(api_open=False).launch(
773
+ prevent_thread_lock=True,
774
+ quiet=True,
775
+ show_api=False,
776
+ enable_monitoring=False,
777
+ allowed_paths=_get_win_drives() if sys.platform == "win32" else ["/"],
778
+ )[1]
779
+ webview.settings["ALLOW_DOWNLOADS"] = True
780
+ _WINDOW = webview.create_window(
781
+ "BirdNET-Analyzer",
782
+ _URL.rstrip("/") + f"?__theme={settings.theme()}",
783
+ width=1300,
784
+ height=900,
785
+ min_size=(1300, 900),
786
+ )
787
+ set_window(_WINDOW)
788
+
789
+ with suppress(ModuleNotFoundError):
790
+ import pyi_splash # type: ignore
791
+
792
+ pyi_splash.close()
793
+
794
+ if sys.platform == "win32":
795
+ import ctypes
796
+ from ctypes import wintypes
797
+
798
+ from webview.platforms.winforms import BrowserView
799
+
800
+ dwmapi = ctypes.windll.LoadLibrary("dwmapi")
801
+ _WINDOW.events.loaded += lambda: dwmapi.DwmSetWindowAttribute(
802
+ BrowserView.instances[_WINDOW.uid].Handle.ToInt32(),
803
+ 20, # DWMWA_USE_IMMERSIVE_DARK_MODE
804
+ ctypes.byref(ctypes.c_bool(settings.theme() == "dark")),
805
+ ctypes.sizeof(wintypes.BOOL),
806
+ )
807
+
808
+ webview.start(private_mode=False)