script.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. from pathlib import Path
  2. import gradio as gr
  3. from elevenlabslib import ElevenLabsUser
  4. from elevenlabslib.helpers import save_bytes_to_path
  5. import re
  6. import modules.shared as shared
  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. # regexp is way faster than repeated string concatenation!
  45. # this expression matches to 'as few symbols as possible (0 upwards) between any asterisks' OR
  46. # 'as few symbols as possible (0 upwards) between an asterisk and the end of the string'
  47. return re.sub('\*[^\*]*?(\*|$)','',string)
  48. def input_modifier(string):
  49. """
  50. This function is applied to your text inputs before
  51. they are fed into the model.
  52. """
  53. return string
  54. def output_modifier(string):
  55. """
  56. This function is applied to the model outputs.
  57. """
  58. global params, wav_idx, user, user_info
  59. if params['activate'] == False:
  60. return string
  61. elif user_info == None:
  62. return string
  63. string = remove_surrounded_chars(string)
  64. string = string.replace('"', '')
  65. string = string.replace('“', '')
  66. string = string.replace('\n', ' ')
  67. string = string.strip()
  68. if string == '':
  69. string = 'empty reply, try regenerating'
  70. output_file = Path(f'extensions/elevenlabs_tts/outputs/{wav_idx:06d}.wav'.format(wav_idx))
  71. voice = user.get_voices_by_name(params['selected_voice'])[0]
  72. audio_data = voice.generate_audio_bytes(string)
  73. save_bytes_to_path(Path(f'extensions/elevenlabs_tts/outputs/{wav_idx:06d}.wav'), audio_data)
  74. string = f'<audio src="file/{output_file.as_posix()}" controls></audio>'
  75. wav_idx += 1
  76. return string
  77. def ui():
  78. # Gradio elements
  79. with gr.Row():
  80. activate = gr.Checkbox(value=params['activate'], label='Activate TTS')
  81. connection_status = gr.Textbox(value='Disconnected', label='Connection Status')
  82. voice = gr.Dropdown(value=params['selected_voice'], choices=initial_voice, label='TTS Voice')
  83. with gr.Row():
  84. api_key = gr.Textbox(placeholder="Enter your API key.", label='API Key')
  85. connect = gr.Button(value='Connect')
  86. # Event functions to update the parameters in the backend
  87. activate.change(lambda x: params.update({'activate': x}), activate, None)
  88. voice.change(lambda x: params.update({'selected_voice': x}), voice, None)
  89. api_key.change(lambda x: params.update({'api_key': x}), api_key, None)
  90. connect.click(check_valid_api, [], connection_status)
  91. connect.click(refresh_voices, [], voice)