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