File size: 1,606 Bytes
0c97faa
db2ba20
2b1e81b
d2e67c6
 
 
 
0c97faa
 
 
 
ccadd27
db2ba20
d67a1b2
d2e67c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c97faa
 
 
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
import gradio as gr
from huggingface_hub import InferenceClient
from transformers import pipeline
from scipy.io.wavfile import write as write_wav

AUDIO_FILE_PATH = "bark_generation.wav"
synthesizer = pipeline("text-to-speech", "suno/bark-small")

"""
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
"""

client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")

with gr.Blocks() as demo:
    chatbot = gr.Chatbot(type="messages")
    audio_box = gr.Audio(autoplay=True)
    msg = gr.Textbox(submit_btn=True)
    clear = gr.Button("Clear")

    def synthesize_audio(text):
        speech = synthesizer(text, forward_params={"do_sample": True})
        write_wav(AUDIO_FILE_PATH, rate=speech["sampling_rate"], data=speech["audio"])

    def user(user_message, history: list):
        return "", history + [{"role": "user", "content": user_message}]

    def bot(history: list):
        history.append({"role": "assistant", "content": ""})
        for message in client.chat_completion(
            history,
            stream=True,
        ):
            token = message.choices[0].delta.content
            history[-1]["content"] += token
            yield history, None

        synthesize_audio(history[-1]["content"])
        return history, AUDIO_FILE_PATH

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, [chatbot, audio_box]
    )
    clear.click(lambda: None, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch()