TanU21 commited on
Commit
656ba9e
·
verified ·
1 Parent(s): d5e4549

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -0
app.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import threading
3
+ import time
4
+ from langchain_groq import ChatGroq
5
+ from dotenv import load_dotenv
6
+ import gradio as gr
7
+ import os
8
+ from gtts import gTTS
9
+ import io
10
+ import pygame
11
+
12
+ load_dotenv()
13
+ groq_api_key = os.environ.get("GROQ_API_KEY")
14
+ llm = ChatGroq(
15
+ model="mixtral-8x7b-32768",
16
+ temperature=0.7,
17
+ api_key=groq_api_key,
18
+ verbose = False
19
+ )
20
+
21
+ prompt = ChatPromptTemplate.from_messages(
22
+ [
23
+ ("system", "You are an intelligent AI assistant. Answer the questions as accurately as possible."),
24
+ ("human", "{input}")
25
+ ]
26
+ )
27
+
28
+ chain = prompt | llm
29
+
30
+ convo_history = []
31
+ audio_playing = False
32
+
33
+ def stop_audio():
34
+ global audio_playing
35
+ if audio_playing:
36
+ pygame.mixer.music.stop()
37
+ audio_playing = False
38
+
39
+ def play_tts(text):
40
+ global audio_playing
41
+ audio_playing = True
42
+
43
+ def speak_async():
44
+ global audio_playing
45
+ pygame.mixer.init()
46
+ fp = io.BytesIO()
47
+ gTTS(text).write_to_fp(fp)
48
+ fp.seek(0)
49
+ pygame.mixer.music.load(fp)
50
+ pygame.mixer.music.play()
51
+ while pygame.mixer.music.get_busy():
52
+ pygame.time.Clock().tick(10)
53
+ audio_playing = False
54
+ pygame.mixer.quit()
55
+
56
+ thread = threading.Thread(target=speak_async)
57
+ thread.start()
58
+
59
+ def ChatBot(text):
60
+
61
+ global convo_history, audio_playing
62
+
63
+ stop_audio()
64
+
65
+ convo_history.append(f"Human: {text}")
66
+
67
+ full_context = "\n".join(convo_history)
68
+ response = chain.invoke({"input": full_context}).content
69
+
70
+ convo_history.append(f"AI: {response}")
71
+
72
+ print("\n".join(convo_history))
73
+
74
+ play_tts(response)
75
+
76
+ return "\n".join(convo_history)
77
+
78
+
79
+ demo = gr.Interface(
80
+ fn=ChatBot,
81
+ inputs="text",
82
+ outputs="text",
83
+ title="AudioBOT",
84
+ description="Ask any question to the AI. It remembers the context of the conversation and speaks its response.",
85
+ )
86
+
87
+ demo.launch()