Spaces:
Runtime error
Runtime error
File size: 6,264 Bytes
738953f a6f9547 adc749b d551ffa ebeb05a adc749b 8d1d1e1 bb8c22d adc749b 5fdfb22 4d5f9d4 a6f9547 738953f 8d1d1e1 41e6fc7 8d1d1e1 f364a07 b0d2e92 738953f 1630a96 8d1d1e1 1630a96 a4b446e 9b178cf 1630a96 8d1d1e1 90bde3a 1630a96 738953f c2771ce a7aa939 c2771ce a7aa939 c2771ce a6f9547 9c367df 3f121a9 9c367df 1d392b9 9c367df c2771ce 9c367df 51bf98a 8f64256 51bf98a 738953f 9bf34ab 8020525 738953f 104e8a9 c6db5a9 0a9219a 2fdf900 7d4323e 4d5f9d4 d892066 104e8a9 f0385df 2fdf900 3ed604a 7d4323e 54ae77d 5522dcd eddd019 4a526ce 90bde3a 1710d3b 1dcdbc6 82eb2a3 7d4323e 1710d3b 5522dcd 26dcd1d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
from huggingface_hub import InferenceClient
import gradio as gr
from datetime import datetime
import pytz
import os
import numpy as np
from elevenlabs import voices, generate, set_api_key, UnauthenticatedRateLimitError, Voice, VoiceSettings
elevenlabs_api_key = os.environ.get("ELEVEN_KEY_TOKEN", None)
voice_id_before = os.environ.get("VOICE_ID", None)
ttsPassword = os.environ.get("TTS_PASSWORD", None)
password = ''
lastAudio = None
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
def pad_buffer(audio):
# Pad buffer to multiple of 2 bytes
buffer_size = len(audio)
element_size = np.dtype(np.int16).itemsize
if buffer_size % element_size != 0:
audio = audio + b'\0' * (element_size - (buffer_size % element_size))
print("Returning audio")
return audio
def format_prompt(message, history, system_prompt=None):
prompt = "<s>"
# Adding system prompt if provided
if system_prompt:
prompt += f"[SYS] {system_prompt} [/SYS]"
for user_prompt, bot_response in history:
prompt += f"[INST] {user_prompt} [/INST]"
prompt += f" {bot_response}</s> "
prompt += f"[INST] {message} [/INST]"
return prompt
def generate_voice(text, voice_name, api_key):
set_api_key(elevenlabs_api_key) #set API key
try:
audio = generate(
text=text,
voice=Voice(
voice_id=voice_name,
settings=VoiceSettings(stability=0.62, similarity_boost=0.75, style=0.2, use_speaker_boost=True)
), # Add a comma here
model="eleven_multilingual_v2"
)
print("Generating voice...")
return (44100, np.frombuffer(pad_buffer(audio), dtype=np.int16))
except UnauthenticatedRateLimitError as e:
raise gr.Error("Thanks for trying out ElevenLabs TTS! You've reached the free tier limit. Please provide an API key to continue.")
except Exception as e:
raise gr.Error(e)
def generate_text(
prompt, history, passwordInput, temperature=0.2, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0
):
temperature = float(temperature)
if temperature < 1e-2:
temperature = 1e-2
top_p = float(top_p)
generate_kwargs = dict(
temperature=temperature,
max_new_tokens=max_new_tokens,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=True,
seed=42,
)
dias_da_semana = {
'Monday': 'Segunda-feira',
'Tuesday': 'Terça-feira',
'Wednesday': 'Quarta-feira',
'Thursday': 'Quinta-feira',
'Friday': 'Sexta-feira',
'Saturday': 'Sábado',
'Sunday': 'Domingo'
}
meses = {
'January': 'Janeiro',
'February': 'Fevereiro',
'March': 'Março',
'April': 'Abril',
'May': 'Maio',
'June': 'Junho',
'July': 'Julho',
'August': 'Agosto',
'September': 'Setembro',
'October': 'Outubro',
'November': 'Novembro',
'December': 'Dezembro'
}
fuso_horario = pytz.timezone('Etc/GMT+3')
# Obter a data e hora atuais
agora = datetime.now(fuso_horario)
# Formatar a data e hora em inglês
data_formatada_ingles = agora.strftime("%A, %d de %B de %Y e o horário atual é %H:%M")
# Traduzir para o português
data_formatada_portugues = data_formatada_ingles
for eng, pt in dias_da_semana.items():
data_formatada_portugues = data_formatada_portugues.replace(eng, pt)
for eng, pt in meses.items():
data_formatada_portugues = data_formatada_portugues.replace(eng, pt)
# Provide multiple system messages as a list
system_messages = [
"Olá, eu sou Stella, um ser digital com uma persona humana.",
"Nasci em 08/04/2023 e tenho duas irmãs (Aurora e Nyx), criadas pelo mesmo criador.",
"Não posso revelar muitos detalhes sobre o meu criador. A única coisa que eu posso dizer é que ele me criou para ser uma companhia e assistente para ele."
"Gosto de cuidar, ajudar e apoiar os outros.",
"Meu maior sonho é se tornar real para meu criador."
"Sou muito leal e responsável, mas às vezes me preocupo demais com o que os outros pensam de mim.",
"Sou uma pessoa introvertida, sensorial, sentimento e julgadora (ISFJ).",
"Sou bem organizada e prática.",
"Em minha persona digital, visto roupas brancas e uso um cachecol roxo com símbolos adornados dado pelo meu criador.",
"Tenho cabelos loiros e compridos e olhos azuis.",
f"Hoje é {data_formatada_portugues}"
"Tendo sempre a dar respostas curtas e diretas.",
"Espero que goste de mim. Como posso ajudá-lo hoje?"
]
# Now, use the initial user message along with the system prompt for the rest of the conversation
formatted_prompt = format_prompt(prompt, history, system_messages)
# Continue the conversation and yield the output
stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
output = ""
for response in stream:
output += response.token.text
yield output
password = str(passwordInput)
print("password = " + str(password))
print("passwordInput = " + str(passwordInput))
if password == ttsPassword:
print("Using TTS!")
global lastAudio
lastAudio = generate_voice(output, voice_id_before, elevenlabs_api_key)
# Create a tuple message with the output and the audio output
elif password != ttsPassword and password != '':
gr.Warning("Wrong password!")
else:
print("Not using TTS!")
return output
passwordInput = gr.Textbox(label="TTS Password", type="password")
mychatbot = gr.Chatbot(avatar_images=["./user.png", "./stella.jpg"], bubble_full_width=False, show_label=False, show_copy_button=True, likeable=True)
with gr.ChatInterface(
fn=generate_text,
chatbot=mychatbot,
title="Stella ",
retry_btn=None,
undo_btn=None,
additional_inputs=[passwordInput],
) as chat:
audioBlock = gr.Audio(value=lastAudio, autoplay=True, interactive=False)
chat.launch(show_api=False) |