Shanulhaq commited on
Commit
c81d3c9
β€’
1 Parent(s): 1433f35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -40
app.py CHANGED
@@ -1,43 +1,41 @@
1
  import streamlit as st
2
  import google.generativeai as genai
3
- import os
4
- from groq import Groq, GroqError
5
  import whisper
6
  from gtts import gTTS
7
  import tempfile
 
8
  import logging
9
  import numpy as np
10
  from pydub import AudioSegment
 
 
11
 
12
- # Set up logging
13
- logging.basicConfig(level=logging.INFO)
14
- logger = logging.getLogger(__name__)
15
-
16
- # Securely configure Google API Key for generative AI (set this in the deployment environment)
17
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
18
  genai.configure(api_key=GOOGLE_API_KEY)
19
 
20
- # Set up Groq API key for audio processing
21
- groq_api_key = os.getenv('groq_api_key')
22
-
23
- if not groq_api_key:
24
  raise ValueError("GROQ_API_KEY is not set.")
25
  try:
26
- groq_client = Groq(api_key=groq_api_key)
27
- logger.info("Groq API key is set and client is initialized.")
28
  except GroqError as e:
29
- logger.error(f"Failed to initialize Groq client: {e}")
30
- raise
 
 
 
31
 
 
32
  try:
33
- # Load Whisper model for audio transcription
34
  whisper_model = whisper.load_model("base")
35
  logger.info("Whisper model loaded successfully.")
36
  except Exception as e:
37
  logger.error(f"Failed to load Whisper model: {e}")
38
  raise
39
 
40
- # Initialize the Generative Model for heart health chatbot
41
  model = genai.GenerativeModel(
42
  'gemini-1.5-flash',
43
  system_instruction=(
@@ -48,12 +46,7 @@ model = genai.GenerativeModel(
48
  )
49
  )
50
 
51
- # Function to get response from the Generative AI chatbot
52
- def get_chatbot_response(user_input):
53
- response = model.generate_content(user_input)
54
- return response.text.strip()
55
-
56
- # Function to process audio using Whisper, Groq, and gTTS
57
  def process_audio(audio_file):
58
  try:
59
  # Transcribe audio using Whisper
@@ -92,7 +85,7 @@ def process_audio(audio_file):
92
 
93
  # Streamlit page configuration
94
  st.set_page_config(
95
- page_title="Heart Health & Audio Chatbot",
96
  page_icon="πŸ‘¨β€βš•οΈ",
97
  layout="centered",
98
  initial_sidebar_state="collapsed",
@@ -130,12 +123,12 @@ st.markdown("""
130
  </style>
131
  """, unsafe_allow_html=True)
132
 
133
- # Custom header
134
  def load_header():
135
  st.markdown("""
136
  <div style="padding:10px;text-align:center;color:white;">
137
- <h1>Heart Health & Audio Chatbot πŸ«€</h1>
138
- <p>Ask me anything about heart diseases or process audio queries!</p>
139
  </div>
140
  """, unsafe_allow_html=True)
141
 
@@ -143,9 +136,8 @@ def load_header():
143
  if "history" not in st.session_state:
144
  st.session_state.history = []
145
 
146
- # Avatar URLs
147
- user_avatar_url = "https://img.freepik.com/free-photo/sad-cartoon-anatomical-heart_23-2149767987.jpg"
148
- bot_avatar_url = "https://img.freepik.com/premium-photo/3d-render-man-doctor-avatar-round-sticker-with-cartoon-character-face-user-id-thumbnail-modern-69_1181551-3160.jpg"
149
 
150
  # Function to display chat history
151
  def display_chat_history():
@@ -172,11 +164,12 @@ def display_chat_history():
172
  # Main application layout
173
  def main():
174
  load_header()
 
175
 
176
  with st.container():
177
  display_chat_history()
178
 
179
- # User input for text-based chat
180
  with st.form(key="user_input_form", clear_on_submit=True):
181
  user_input = st.text_input(
182
  label="Type your message...",
@@ -188,23 +181,25 @@ def main():
188
  if submit_button and user_input.strip():
189
  with st.spinner("Thinking..."):
190
  bot_response = get_chatbot_response(user_input)
191
-
192
  # Update chat history
193
  st.session_state.history.append({"role": "user", "content": user_input})
194
  st.session_state.history.append({"role": "bot", "content": bot_response})
195
-
196
  # Refresh chat display
197
  display_chat_history()
198
 
199
- # File uploader for audio processing
200
- st.subheader("Upload audio for processing")
201
- audio_file = st.file_uploader("Choose an audio file", type=["mp3", "wav"])
202
 
203
- if audio_file is not None:
 
204
  with st.spinner("Processing audio..."):
205
- response_text, audio_response = process_audio(audio_file)
206
- st.text(f"Response: {response_text}")
207
- st.audio(audio_response)
 
208
 
209
  # Run the app
210
  if __name__ == "__main__":
 
1
  import streamlit as st
2
  import google.generativeai as genai
 
 
3
  import whisper
4
  from gtts import gTTS
5
  import tempfile
6
+ import os
7
  import logging
8
  import numpy as np
9
  from pydub import AudioSegment
10
+ from groq import Groq, GroqError
11
+ import gradio as gr
12
 
13
+ # Securely configure API Key (set this in the deployment environment)
 
 
 
 
14
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
15
  genai.configure(api_key=GOOGLE_API_KEY)
16
 
17
+ # Set up Groq API key
18
+ GROQ_API_KEY = os.getenv('GROQ_API_KEY')
19
+ if not GROQ_API_KEY:
 
20
  raise ValueError("GROQ_API_KEY is not set.")
21
  try:
22
+ groq_client = Groq(api_key=GROQ_API_KEY)
 
23
  except GroqError as e:
24
+ raise ValueError(f"Failed to initialize Groq client: {e}")
25
+
26
+ # Set up logging
27
+ logging.basicConfig(level=logging.INFO)
28
+ logger = logging.getLogger(__name__)
29
 
30
+ # Initialize Whisper Model
31
  try:
 
32
  whisper_model = whisper.load_model("base")
33
  logger.info("Whisper model loaded successfully.")
34
  except Exception as e:
35
  logger.error(f"Failed to load Whisper model: {e}")
36
  raise
37
 
38
+ # Initialize the Generative Model
39
  model = genai.GenerativeModel(
40
  'gemini-1.5-flash',
41
  system_instruction=(
 
46
  )
47
  )
48
 
49
+ # Function to process audio
 
 
 
 
 
50
  def process_audio(audio_file):
51
  try:
52
  # Transcribe audio using Whisper
 
85
 
86
  # Streamlit page configuration
87
  st.set_page_config(
88
+ page_title="Heart Health Chatbot",
89
  page_icon="πŸ‘¨β€βš•οΈ",
90
  layout="centered",
91
  initial_sidebar_state="collapsed",
 
123
  </style>
124
  """, unsafe_allow_html=True)
125
 
126
+ # Load and display a custom header
127
  def load_header():
128
  st.markdown("""
129
  <div style="padding:10px;text-align:center;color:white;">
130
+ <h1>Heart Health Chatbot πŸ«€</h1>
131
+ <p>Ask me anything about heart diseases!</p>
132
  </div>
133
  """, unsafe_allow_html=True)
134
 
 
136
  if "history" not in st.session_state:
137
  st.session_state.history = []
138
 
139
+ user_avatar_url = "https://img.freepik.com/free-photo/sad-cartoon-anatomical-heart_23-2149767987.jpg?t=st=1725263300~exp=1725266900~hmac=3763e175a896a554720d54c6d774dc645dd73078c952913accec719977d50b48&w=740"
140
+ bot_avatar_url = "https://img.freepik.com/premium-photo/3d-render-man-doctor-avatar-round-sticker-with-cartoon-character-face-user-id-thumbnail-modern-69_1181551-3160.jpg?w=740"
 
141
 
142
  # Function to display chat history
143
  def display_chat_history():
 
164
  # Main application layout
165
  def main():
166
  load_header()
167
+ st.write("") # Add spacing
168
 
169
  with st.container():
170
  display_chat_history()
171
 
172
+ # User input area for text
173
  with st.form(key="user_input_form", clear_on_submit=True):
174
  user_input = st.text_input(
175
  label="Type your message...",
 
181
  if submit_button and user_input.strip():
182
  with st.spinner("Thinking..."):
183
  bot_response = get_chatbot_response(user_input)
184
+
185
  # Update chat history
186
  st.session_state.history.append({"role": "user", "content": user_input})
187
  st.session_state.history.append({"role": "bot", "content": bot_response})
188
+
189
  # Refresh chat display
190
  display_chat_history()
191
 
192
+ # Audio upload section
193
+ st.markdown("### Upload your audio for consultation")
194
+ uploaded_audio = st.file_uploader("Upload an audio file", type=["mp3", "wav", "ogg"])
195
 
196
+ if uploaded_audio:
197
+ st.audio(uploaded_audio)
198
  with st.spinner("Processing audio..."):
199
+ response_text, response_audio = process_audio(uploaded_audio)
200
+ if response_text:
201
+ st.markdown(f"**Response Text:** {response_text}")
202
+ st.audio(response_audio)
203
 
204
  # Run the app
205
  if __name__ == "__main__":