hotwords_callbacks.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from dash.dependencies import Input, Output, State, ALL
  2. from dash import html, callback_context
  3. from utils.file_utils import list_files_in_directory, save_file, delete_file, ensure_directory_exists
  4. from components.hotwords import generate_training_data_table, HotwordsLayout, ManageHotwordLayout
  5. import os
  6. import dash_bootstrap_components as dbc
  7. TRAINING_HOTWORD_DIR = './training/hotword/'
  8. def register_hotwords_callbacks(app):
  9. @app.callback(
  10. Output("new-hotword-input", "children"),
  11. Input("add-new-hotword", "n_clicks"),
  12. prevent_initial_call=True
  13. )
  14. def display_new_hotword_input(n_clicks):
  15. if n_clicks:
  16. return dbc.Input(id="new-hotword-name", placeholder="Enter new hotword name", type="text")
  17. @app.callback(
  18. Output("page-manage-content-nav", "children"),
  19. [
  20. Input("new-hotword-name", "n_submit"),
  21. Input({'type': 'delete-hotword', 'index': ALL}, 'n_clicks')
  22. ],
  23. [
  24. State("new-hotword-name", "value"),
  25. State({'type': 'delete-hotword', 'index': ALL}, 'id')
  26. ],
  27. prevent_initial_call=True
  28. )
  29. def manage_hotwords(n_submit, n_clicks_delete, hotword_name, delete_id):
  30. ctx = callback_context
  31. if not ctx.triggered:
  32. return html.Div()
  33. triggered_id = ctx.triggered[0]['prop_id'].split('.')[0]
  34. if 'new-hotword-name' in triggered_id and hotword_name:
  35. new_hotword_path = os.path.join(TRAINING_HOTWORD_DIR, hotword_name)
  36. ensure_directory_exists(new_hotword_path)
  37. return HotwordsLayout()
  38. if 'delete-hotword' in triggered_id:
  39. model_name = delete_id[0]['index']
  40. hotword_path = os.path.join(TRAINING_HOTWORD_DIR, model_name)
  41. if os.path.exists(hotword_path):
  42. os.rmdir(hotword_path)
  43. return HotwordsLayout()
  44. return html.Div()
  45. @app.callback(
  46. Output('data-table-body', 'children'),
  47. [Input('data-table-pagination', 'active_page')],
  48. [State('url', 'pathname')]
  49. )
  50. def update_table(page, pathname):
  51. model_name = pathname.split('/')[-1]
  52. filepath = f"{TRAINING_HOTWORD_DIR}/{model_name}/"
  53. training_data = list_files_in_directory(filepath, ".wav")
  54. rows = generate_training_data_table(model_name, training_data, page, page_size=10)
  55. return rows