File size: 1,887 Bytes
ae5a762
 
 
e10682b
ae5a762
 
 
 
 
 
dcc024a
ae5a762
 
 
 
08dc7a1
ae5a762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656ba9e
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
import datetime
import threading
from langchain_core.prompts import ChatPromptTemplate
import time
from langchain_groq import ChatGroq
import gradio as gr
import os
from gtts import gTTS
import io
import pygame
groq_api_key = os.environ.get("GROQ_API_KEY")

llm = ChatGroq(
    model="mixtral-8x7b-32768",  
    temperature=0.7,
    api_key=groq_api_key,
    verbose = False
)

prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are an intelligent AI assistant. Answer the questions as accurately as possible."),
        ("human", "{input}")
    ]
)

chain = prompt | llm

convo_history = []
audio_playing = False

def stop_audio():
    global audio_playing
    if audio_playing:
        pygame.mixer.music.stop()
        audio_playing = False

def play_tts(text):
    global audio_playing
    audio_playing = True

    def speak_async():
        global audio_playing
        pygame.mixer.init()
        fp = io.BytesIO()
        gTTS(text).write_to_fp(fp)
        fp.seek(0)
        pygame.mixer.music.load(fp)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            pygame.time.Clock().tick(10)
        audio_playing = False
        pygame.mixer.quit()

    thread = threading.Thread(target=speak_async)
    thread.start()

def ChatBot(text):

    global convo_history, audio_playing

    stop_audio()

    convo_history.append(f"Human: {text}")

    full_context = "\n".join(convo_history)
    response = chain.invoke({"input": full_context}).content

    convo_history.append(f"AI: {response}")

    print("\n".join(convo_history))

    play_tts(response)

    return "\n".join(convo_history)


demo = gr.Interface(
    fn=ChatBot,
    inputs="text",
    outputs="text",
    title="AudioBOT",
    description="Ask any question to the AI. It remembers the context of the conversation and speaks its response.",
)

demo.launch()