script.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import re
  2. from pathlib import Path
  3. import gradio as gr
  4. import modules.shared as shared
  5. from elevenlabslib import ElevenLabsUser
  6. from elevenlabslib.helpers import save_bytes_to_path
  7. params = {
  8. 'activate': True,
  9. 'api_key': '12345',
  10. 'selected_voice': 'None',
  11. }
  12. initial_voice = ['None']
  13. wav_idx = 0
  14. user = ElevenLabsUser(params['api_key'])
  15. user_info = None
  16. if not shared.args.no_stream:
  17. print("Please add --no-stream. This extension is not meant to be used with streaming.")
  18. raise ValueError
  19. # Check if the API is valid and refresh the UI accordingly.
  20. def check_valid_api():
  21. global user, user_info, params
  22. user = ElevenLabsUser(params['api_key'])
  23. user_info = user._get_subscription_data()
  24. print('checking api')
  25. if params['activate'] == False:
  26. return gr.update(value='Disconnected')
  27. elif user_info is None:
  28. print('Incorrect API Key')
  29. return gr.update(value='Disconnected')
  30. else:
  31. print('Got an API Key!')
  32. return gr.update(value='Connected')
  33. # Once the API is verified, get the available voices and update the dropdown list
  34. def refresh_voices():
  35. global user, user_info
  36. your_voices = [None]
  37. if user_info is not None:
  38. for voice in user.get_available_voices():
  39. your_voices.append(voice.initialName)
  40. return gr.Dropdown.update(choices=your_voices)
  41. else:
  42. return
  43. def remove_surrounded_chars(string):
  44. # this expression matches to 'as few symbols as possible (0 upwards) between any asterisks' OR
  45. # 'as few symbols as possible (0 upwards) between an asterisk and the end of the string'
  46. return re.sub('\*[^\*]*?(\*|$)','',string)
  47. def input_modifier(string):
  48. """
  49. This function is applied to your text inputs before
  50. they are fed into the model.
  51. """
  52. return string
  53. def output_modifier(string):
  54. """
  55. This function is applied to the model outputs.
  56. """
  57. global params, wav_idx, user, user_info
  58. if params['activate'] == False:
  59. return string
  60. elif user_info == None:
  61. return string
  62. string = remove_surrounded_chars(string)
  63. string = string.replace('"', '')
  64. string = string.replace('“', '')
  65. string = string.replace('\n', ' ')
  66. string = string.strip()
  67. if string == '':
  68. string = 'empty reply, try regenerating'
  69. output_file = Path(f'extensions/elevenlabs_tts/outputs/{wav_idx:06d}.wav'.format(wav_idx))
  70. voice = user.get_voices_by_name(params['selected_voice'])[0]
  71. audio_data = voice.generate_audio_bytes(string)
  72. save_bytes_to_path(Path(f'extensions/elevenlabs_tts/outputs/{wav_idx:06d}.wav'), audio_data)
  73. string = f'<audio src="file/{output_file.as_posix()}" controls></audio>'
  74. wav_idx += 1
  75. return string
  76. def ui():
  77. # Gradio elements
  78. with gr.Row():
  79. activate = gr.Checkbox(value=params['activate'], label='Activate TTS')
  80. connection_status = gr.Textbox(value='Disconnected', label='Connection Status')
  81. voice = gr.Dropdown(value=params['selected_voice'], choices=initial_voice, label='TTS Voice')
  82. with gr.Row():
  83. api_key = gr.Textbox(placeholder="Enter your API key.", label='API Key')
  84. connect = gr.Button(value='Connect')
  85. # Event functions to update the parameters in the backend
  86. activate.change(lambda x: params.update({'activate': x}), activate, None)
  87. voice.change(lambda x: params.update({'selected_voice': x}), voice, None)
  88. api_key.change(lambda x: params.update({'api_key': x}), api_key, None)
  89. connect.click(check_valid_api, [], connection_status)
  90. connect.click(refresh_voices, [], voice)