File size: 2,099 Bytes
c738c50
 
 
6252e34
c738c50
f74aef8
 
 
 
c738c50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f74aef8
c738c50
 
 
 
6252e34
 
 
 
c738c50
f74aef8
4464901
6252e34
 
 
 
 
c738c50
6252e34
c738c50
 
211a7b2
6252e34
 
 
 
211a7b2
6252e34
 
211a7b2
 
 
 
6252e34
 
 
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
import streamlit as st
from huggingface_hub import InferenceClient
from gtts import gTTS
import base64
import os
from langdetect import detect, DetectorFactory

# To ensure consistent results from langdetect
DetectorFactory.seed = 0

client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")

def generate_response(message, system_message, max_tokens, temperature, top_p):
    messages = [{"role": "system", "content": system_message}]
    messages.append({"role": "user", "content": message})

    response = ""
    for message in client.chat_completion(
        messages,
        max_tokens=max_tokens,
        stream=True,
        temperature=temperature,
        top_p=top_p,
    ):
        token = message.choices[0].delta.content
        response += token

    # Generate speech from the response text using gTTS
    tts = gTTS(text=response, lang='en' if detect(message) == 'en' else 'ar')
    audio_file = "response.mp3"
    tts.save(audio_file)
    return response, audio_file

def get_base64_audio(audio_file):
    with open(audio_file, "rb") as f:
        audio_data = f.read()
    return base64.b64encode(audio_data).decode()

st.title("A Chatbot with Voice Response")

message = st.text_input("Enter your message:")
system_message = st.text_input("System message:", value="You are a friendly Chatbot.")
max_tokens = st.slider("Max new tokens", 1, 2048, 512)
temperature = st.slider("Temperature", 0.1, 4.0, 0.7, step=0.1)
top_p = st.slider("Top-p (nucleus sampling)", 0.1, 1.0, 0.95, step=0.05)

if st.button("Generate Response"):
    response, audio_file = generate_response(message, system_message, max_tokens, temperature, top_p)
    st.write(response)

    # Get base64 encoded audio data
    audio_base64 = get_base64_audio(audio_file)
    
    # HTML to autoplay the audio
    audio_html = f"""
    <audio controls autoplay>
    <source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
    Your browser does not support the audio element.
    </audio>
    """
    st.markdown(audio_html, unsafe_allow_html=True)

    # Clean up the audio file
    os.remove(audio_file)