Spaces:
Runtime error
Runtime error
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) |