Pijush2023 commited on
Commit
1616068
·
verified ·
1 Parent(s): 189b7c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +753 -69
app.py CHANGED
@@ -1,3 +1,731 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
@@ -63,11 +791,7 @@ def get_current_time_and_date():
63
 
64
  current_time_and_date = get_current_time_and_date()
65
 
66
-
67
-
68
  def fetch_local_events():
69
-
70
-
71
  api_key = os.environ['SERP_API']
72
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
73
  response = requests.get(url)
@@ -130,9 +854,6 @@ def fetch_local_events():
130
  else:
131
  return "<p>Failed to fetch local events</p>"
132
 
133
-
134
-
135
-
136
  def fetch_local_weather():
137
  try:
138
  api_key = os.environ['WEATHER_API']
@@ -226,14 +947,6 @@ event type and description.And also add this Birmingham,AL at the end of each ad
226
  Question: {question}
227
  Helpful Answer:"""
228
 
229
-
230
- # template2 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on today's weather being a sunny bright day and today's date is 1st july 2024, take the location or address but don't show the location or address on the output prompts. Use the following pieces of context,
231
- # memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
232
- # Keep the answer short and sweet and crisp. Always say "It was my pleasure!" at the end of the answer.
233
- # {context}
234
- # Question: {question}
235
- # Helpful Answer:"""
236
-
237
  template2 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on today's weather being a sunny bright day and today's date is 16th july 2024, take the location or address but don't show the location or address on the output prompts. Use the following pieces of context,
238
  memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
239
  Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
@@ -273,7 +986,6 @@ def initialize_agent_with_prompt(prompt_template):
273
  )
274
  return agent
275
 
276
-
277
  def generate_answer(message, choice):
278
  logging.debug(f"generate_answer called with prompt_choice: {choice}")
279
 
@@ -289,8 +1001,6 @@ def generate_answer(message, choice):
289
  addresses = extract_addresses(response['output'])
290
  return response['output'], addresses
291
 
292
-
293
-
294
  def bot(history, choice, tts_choice, state):
295
  if not history:
296
  return history
@@ -317,8 +1027,6 @@ def add_message(history, message):
317
  history.append((message, None))
318
  return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
319
 
320
-
321
-
322
  def print_like_dislike(x: gr.LikeData):
323
  print(x.index, x.value, x.liked)
324
 
@@ -344,8 +1052,6 @@ def extract_addresses(response):
344
 
345
  all_addresses = []
346
 
347
-
348
-
349
  def generate_map(location_names):
350
  global all_addresses
351
  all_addresses.extend(location_names)
@@ -367,7 +1073,6 @@ def generate_map(location_names):
367
  map_html = m._repr_html_()
368
  return map_html
369
 
370
-
371
  def fetch_local_news():
372
  api_key = os.environ['SERP_API']
373
  url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
@@ -452,41 +1157,36 @@ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
452
  model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
453
  processor = AutoProcessor.from_pretrained(model_id)
454
 
455
- pipe_asr = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor, max_new_tokens=128, chunk_length_s=15, batch_size=16, torch_dtype=torch_dtype, device=device, return_timestamps=True)
456
 
457
  base_audio_drive = "/data/audio"
458
 
459
- # def transcribe_function(stream, new_chunk):
460
- # try:
461
- # sr, y = new_chunk[0], new_chunk[1]
462
- # except TypeError:
463
- # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
464
- # return stream, "", None
465
-
466
- # y = y.astype(np.float32) / np.max(np.abs(y))
467
-
468
- # if stream is not None:
469
- # stream = np.concatenate([stream, y])
470
- # else:
471
- # stream = y
472
-
473
- # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
474
-
475
- # full_text = result.get("text","")
476
-
477
- # return stream, full_text, result
478
-
479
-
480
  def transcribe_function(stream, new_chunk):
481
- sr, y = new_chunk[0], new_chunk[1]
 
 
 
 
 
482
  y = y.astype(np.float32) / np.max(np.abs(y))
 
483
  if stream is not None:
484
  stream = np.concatenate([stream, y])
485
  else:
486
  stream = y
 
487
  result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
 
488
  full_text = result.get("text", "")
489
- return stream, full_text # Return the transcribed text
 
 
 
 
 
 
 
 
490
 
491
  def update_map_with_response(history):
492
  if not history:
@@ -498,7 +1198,7 @@ def update_map_with_response(history):
498
  def clear_textbox():
499
  return ""
500
 
501
- def show_map_if_details(history,choice):
502
  if choice in ["Details", "Conversational"]:
503
  return gr.update(visible=True), update_map_with_response(history)
504
  else:
@@ -631,7 +1331,6 @@ def generate_audio_mars5(text):
631
  cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
632
  ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
633
 
634
-
635
  temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
636
  torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
637
  audio_segments.append(AudioSegment.from_wav(temp_audio_path))
@@ -669,6 +1368,7 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
669
  with gr.Row():
670
  with gr.Column():
671
  state = gr.State()
 
672
 
673
  chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
674
  choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
@@ -692,21 +1392,12 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
692
  clear_button = gr.Button("Clear")
693
  clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
694
 
695
- audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy')
696
- audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
697
-
698
-
699
-
700
-
701
-
702
-
703
 
704
- # with gr.Column():
705
- # weather_output = gr.HTML(value=fetch_local_weather())
706
- # news_output = gr.HTML(value=fetch_local_news())
707
- # news_output = gr.HTML(value=fetch_local_events())
708
 
709
-
710
  with gr.Column():
711
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
712
  image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
@@ -716,8 +1407,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
716
  refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
717
  location_output = gr.HTML()
718
  bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output], api_name="map_finder")
719
-
720
-
721
 
722
  demo.queue()
723
  demo.launch(share=True)
@@ -725,8 +1414,3 @@ demo.launch(share=True)
725
 
726
 
727
 
728
-
729
-
730
-
731
-
732
-
 
1
+ # import gradio as gr
2
+ # import requests
3
+ # import os
4
+ # import time
5
+ # import re
6
+ # import logging
7
+ # import tempfile
8
+ # import folium
9
+ # import concurrent.futures
10
+ # import torch
11
+ # from PIL import Image
12
+ # from datetime import datetime
13
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
14
+ # from googlemaps import Client as GoogleMapsClient
15
+ # from gtts import gTTS
16
+ # from diffusers import StableDiffusionPipeline
17
+ # from langchain_openai import OpenAIEmbeddings, ChatOpenAI
18
+ # from langchain_pinecone import PineconeVectorStore
19
+ # from langchain.prompts import PromptTemplate
20
+ # from langchain.chains import RetrievalQA
21
+ # from langchain.chains.conversation.memory import ConversationBufferWindowMemory
22
+ # from langchain.agents import Tool, initialize_agent
23
+ # from huggingface_hub import login
24
+ # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
25
+ # from parler_tts import ParlerTTSForConditionalGeneration
26
+ # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
27
+ # from scipy.io.wavfile import write as write_wav
28
+ # from pydub import AudioSegment
29
+ # from string import punctuation
30
+ # import librosa
31
+ # from pathlib import Path
32
+ # import torchaudio
33
+
34
+ # # Check if the token is already set in the environment variables
35
+ # hf_token = os.getenv("HF_TOKEN")
36
+ # if hf_token is None:
37
+ # print("Please set your Hugging Face token in the environment variables.")
38
+ # else:
39
+ # login(token=hf_token)
40
+
41
+ # logging.basicConfig(level=logging.DEBUG)
42
+
43
+ # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
44
+
45
+ # from pinecone import Pinecone
46
+ # pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
47
+
48
+ # index_name = "birminghumsummary1"
49
+ # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
50
+ # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
51
+
52
+ # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
53
+
54
+ # conversational_memory = ConversationBufferWindowMemory(
55
+ # memory_key='chat_history',
56
+ # k=10,
57
+ # return_messages=True
58
+ # )
59
+
60
+ # def get_current_time_and_date():
61
+ # now = datetime.now()
62
+ # return now.strftime("%Y-%m-%d %H:%M:%S")
63
+
64
+ # current_time_and_date = get_current_time_and_date()
65
+
66
+
67
+
68
+ # def fetch_local_events():
69
+
70
+
71
+ # api_key = os.environ['SERP_API']
72
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
73
+ # response = requests.get(url)
74
+ # if response.status_code == 200:
75
+ # events_results = response.json().get("events_results", [])
76
+ # events_html = """
77
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
78
+ # <style>
79
+ # table {
80
+ # font-family: 'Verdana', sans-serif;
81
+ # color: #333;
82
+ # border-collapse: collapse;
83
+ # width: 100%;
84
+ # }
85
+ # th, td {
86
+ # border: 1px solid #fff !important;
87
+ # padding: 8px;
88
+ # }
89
+ # th {
90
+ # background-color: #f2f2f2;
91
+ # color: #333;
92
+ # text-align: left;
93
+ # }
94
+ # tr:hover {
95
+ # background-color: #f5f5f5;
96
+ # }
97
+ # .event-link {
98
+ # color: #1E90FF;
99
+ # text-decoration: none;
100
+ # }
101
+ # .event-link:hover {
102
+ # text-decoration: underline;
103
+ # }
104
+ # </style>
105
+ # <table>
106
+ # <tr>
107
+ # <th>Title</th>
108
+ # <th>Date and Time</th>
109
+ # <th>Location</th>
110
+ # </tr>
111
+ # """
112
+ # for event in events_results:
113
+ # title = event.get("title", "No title")
114
+ # date_info = event.get("date", {})
115
+ # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
116
+ # location = event.get("address", "No location")
117
+ # if isinstance(location, list):
118
+ # location = " ".join(location)
119
+ # location = location.replace("[", "").replace("]", "")
120
+ # link = event.get("link", "#")
121
+ # events_html += f"""
122
+ # <tr>
123
+ # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
124
+ # <td>{date}</td>
125
+ # <td>{location}</td>
126
+ # </tr>
127
+ # """
128
+ # events_html += "</table>"
129
+ # return events_html
130
+ # else:
131
+ # return "<p>Failed to fetch local events</p>"
132
+
133
+
134
+
135
+
136
+ # def fetch_local_weather():
137
+ # try:
138
+ # api_key = os.environ['WEATHER_API']
139
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
140
+ # response = requests.get(url)
141
+ # response.raise_for_status()
142
+ # jsonData = response.json()
143
+
144
+ # current_conditions = jsonData.get("currentConditions", {})
145
+ # temp_celsius = current_conditions.get("temp", "N/A")
146
+
147
+ # if temp_celsius != "N/A":
148
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
149
+ # else:
150
+ # temp_fahrenheit = "N/A"
151
+
152
+ # condition = current_conditions.get("conditions", "N/A")
153
+ # humidity = current_conditions.get("humidity", "N/A")
154
+
155
+ # weather_html = f"""
156
+ # <div class="weather-theme">
157
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
158
+ # <div class="weather-content">
159
+ # <div class="weather-icon">
160
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
161
+ # </div>
162
+ # <div class="weather-details">
163
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
164
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
165
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
166
+ # </div>
167
+ # </div>
168
+ # </div>
169
+ # <style>
170
+ # .weather-theme {{
171
+ # animation: backgroundAnimation 10s infinite alternate;
172
+ # border-radius: 10px;
173
+ # padding: 10px;
174
+ # margin-bottom: 15px;
175
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
176
+ # background-size: 400% 400%;
177
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
178
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
179
+ # }}
180
+ # .weather-theme:hover {{
181
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
182
+ # background-position: 100% 100%;
183
+ # }}
184
+ # @keyframes backgroundAnimation {{
185
+ # 0% {{ background-position: 0% 50%; }}
186
+ # 100% {{ background-position: 100% 50%; }}
187
+ # }}
188
+ # .weather-content {{
189
+ # display: flex;
190
+ # align-items: center;
191
+ # }}
192
+ # .weather-icon {{
193
+ # flex: 1;
194
+ # }}
195
+ # .weather-details {{
196
+ # flex: 3;
197
+ # }}
198
+ # </style>
199
+ # """
200
+ # return weather_html
201
+ # except requests.exceptions.RequestException as e:
202
+ # return f"<p>Failed to fetch local weather: {e}</p>"
203
+
204
+ # def get_weather_icon(condition):
205
+ # condition_map = {
206
+ # "Clear": "c01d",
207
+ # "Partly Cloudy": "c02d",
208
+ # "Cloudy": "c03d",
209
+ # "Overcast": "c04d",
210
+ # "Mist": "a01d",
211
+ # "Patchy rain possible": "r01d",
212
+ # "Light rain": "r02d",
213
+ # "Moderate rain": "r03d",
214
+ # "Heavy rain": "r04d",
215
+ # "Snow": "s01d",
216
+ # "Thunderstorm": "t01d",
217
+ # "Fog": "a05d",
218
+ # }
219
+ # return condition_map.get(condition, "c04d")
220
+
221
+ # template1 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on weather being a sunny bright day and the today's date is 1st july 2024, use the following pieces of context,
222
+ # memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
223
+ # Use fifteen sentences maximum. Keep the answer as detailed as possible. Always include the address, time, date, and
224
+ # event type and description.And also add this Birmingham,AL at the end of each address, Always say "It was my pleasure!" at the end of the answer.
225
+ # {context}
226
+ # Question: {question}
227
+ # Helpful Answer:"""
228
+
229
+
230
+ # # template2 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on today's weather being a sunny bright day and today's date is 1st july 2024, take the location or address but don't show the location or address on the output prompts. Use the following pieces of context,
231
+ # # memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
232
+ # # Keep the answer short and sweet and crisp. Always say "It was my pleasure!" at the end of the answer.
233
+ # # {context}
234
+ # # Question: {question}
235
+ # # Helpful Answer:"""
236
+
237
+ # template2 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on today's weather being a sunny bright day and today's date is 16th july 2024, take the location or address but don't show the location or address on the output prompts. Use the following pieces of context,
238
+ # memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
239
+ # Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
240
+ # {context}
241
+ # Question: {question}
242
+ # Helpful Answer:"""
243
+
244
+ # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
245
+ # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
246
+
247
+ # def build_qa_chain(prompt_template):
248
+ # qa_chain = RetrievalQA.from_chain_type(
249
+ # llm=chat_model,
250
+ # chain_type="stuff",
251
+ # retriever=retriever,
252
+ # chain_type_kwargs={"prompt": prompt_template}
253
+ # )
254
+ # tools = [
255
+ # Tool(
256
+ # name='Knowledge Base',
257
+ # func=qa_chain,
258
+ # description='Use this tool when answering general knowledge queries to get more information about the topic'
259
+ # )
260
+ # ]
261
+ # return qa_chain, tools
262
+
263
+ # def initialize_agent_with_prompt(prompt_template):
264
+ # qa_chain, tools = build_qa_chain(prompt_template)
265
+ # agent = initialize_agent(
266
+ # agent='chat-conversational-react-description',
267
+ # tools=tools,
268
+ # llm=chat_model,
269
+ # verbose=False,
270
+ # max_iteration=5,
271
+ # early_stopping_method='generate',
272
+ # memory=conversational_memory
273
+ # )
274
+ # return agent
275
+
276
+
277
+ # def generate_answer(message, choice):
278
+ # logging.debug(f"generate_answer called with prompt_choice: {choice}")
279
+
280
+ # if choice == "Details":
281
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
282
+ # elif choice == "Conversational":
283
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
284
+ # else:
285
+ # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
286
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
287
+ # response = agent(message)
288
+
289
+ # addresses = extract_addresses(response['output'])
290
+ # return response['output'], addresses
291
+
292
+
293
+
294
+ # def bot(history, choice, tts_choice, state):
295
+ # if not history:
296
+ # return history
297
+ # response, addresses = generate_answer(history[-1][0], choice)
298
+ # history[-1][1] = ""
299
+
300
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
301
+ # if tts_choice == "Alpha":
302
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
303
+ # elif tts_choice == "Beta":
304
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
305
+ # elif tts_choice == "Gamma":
306
+ # audio_future = executor.submit(generate_audio_mars5, response)
307
+
308
+ # for character in response:
309
+ # history[-1][1] += character
310
+ # time.sleep(0.05)
311
+ # yield history, None
312
+
313
+ # audio_path = audio_future.result()
314
+ # yield history, audio_path
315
+
316
+ # def add_message(history, message):
317
+ # history.append((message, None))
318
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
319
+
320
+
321
+
322
+ # def print_like_dislike(x: gr.LikeData):
323
+ # print(x.index, x.value, x.liked)
324
+
325
+ # def extract_addresses(response):
326
+ # if not isinstance(response, str):
327
+ # response = str(response)
328
+ # address_patterns = [
329
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
330
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
331
+ # r'([A-Z].*,\sAL\s\d{5})',
332
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
333
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
334
+ # r'(\d{2}.*\sStreets)',
335
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
336
+ # r'([a-zA-Z]\s Birmingham)',
337
+ # r'([a-zA-Z].*,\sBirmingham,\sAL)',
338
+ # r'(^Birmingham,AL$)'
339
+ # ]
340
+ # addresses = []
341
+ # for pattern in address_patterns:
342
+ # addresses.extend(re.findall(pattern, response))
343
+ # return addresses
344
+
345
+ # all_addresses = []
346
+
347
+
348
+
349
+ # def generate_map(location_names):
350
+ # global all_addresses
351
+ # all_addresses.extend(location_names)
352
+
353
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
354
+ # gmaps = GoogleMapsClient(key=api_key)
355
+
356
+ # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
357
+
358
+ # for location_name in all_addresses:
359
+ # geocode_result = gmaps.geocode(location_name)
360
+ # if geocode_result:
361
+ # location = geocode_result[0]['geometry']['location']
362
+ # folium.Marker(
363
+ # [location['lat'], location['lng']],
364
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
365
+ # ).add_to(m)
366
+
367
+ # map_html = m._repr_html_()
368
+ # return map_html
369
+
370
+
371
+ # def fetch_local_news():
372
+ # api_key = os.environ['SERP_API']
373
+ # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
374
+ # response = requests.get(url)
375
+ # if response.status_code == 200:
376
+ # results = response.json().get("news_results", [])
377
+ # news_html = """
378
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
379
+ # <style>
380
+ # .news-item {
381
+ # font-family: 'Verdana', sans-serif;
382
+ # color: #333;
383
+ # background-color: #f0f8ff;
384
+ # margin-bottom: 15px;
385
+ # padding: 10px;
386
+ # border-radius: 5px;
387
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
388
+ # font-weight: bold;
389
+ # }
390
+ # .news-item:hover {
391
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
392
+ # background-color: #e6f7ff;
393
+ # }
394
+ # .news-item a {
395
+ # color: #1E90FF;
396
+ # text-decoration: none;
397
+ # font-weight: bold;
398
+ # }
399
+ # .news-item a:hover {
400
+ # text-decoration: underline;
401
+ # }
402
+ # .news-preview {
403
+ # position: absolute;
404
+ # display: none;
405
+ # border: 1px solid #ccc;
406
+ # border-radius: 5px;
407
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
408
+ # background-color: white;
409
+ # z-index: 1000;
410
+ # max-width: 300px;
411
+ # padding: 10px;
412
+ # font-family: 'Verdana', sans-serif;
413
+ # color: #333;
414
+ # }
415
+ # </style>
416
+ # <script>
417
+ # function showPreview(event, previewContent) {
418
+ # var previewBox = document.getElementById('news-preview');
419
+ # previewBox.innerHTML = previewContent;
420
+ # previewBox.style.left = event.pageX + 'px';
421
+ # previewBox.style.top = event.pageY + 'px';
422
+ # previewBox.style.display = 'block';
423
+ # }
424
+ # function hidePreview() {
425
+ # var previewBox = document.getElementById('news-preview');
426
+ # previewBox.style.display = 'none';
427
+ # }
428
+ # </script>
429
+ # <div id="news-preview" class="news-preview"></div>
430
+ # """
431
+ # for index, result in enumerate(results[:7]):
432
+ # title = result.get("title", "No title")
433
+ # link = result.get("link", "#")
434
+ # snippet = result.get("snippet", "")
435
+ # news_html += f"""
436
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
437
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
438
+ # <p>{snippet}</p>
439
+ # </div>
440
+ # """
441
+ # return news_html
442
+ # else:
443
+ # return "<p>Failed to fetch local news</p>"
444
+
445
+ # import numpy as np
446
+ # import torch
447
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
448
+
449
+ # model_id = 'openai/whisper-large-v3'
450
+ # device = "cuda:0" if torch.cuda.is_available() else "cpu"
451
+ # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
452
+ # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
453
+ # processor = AutoProcessor.from_pretrained(model_id)
454
+
455
+ # pipe_asr = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor, max_new_tokens=128, chunk_length_s=15, batch_size=16, torch_dtype=torch_dtype, device=device, return_timestamps=True)
456
+
457
+ # base_audio_drive = "/data/audio"
458
+
459
+ # # def transcribe_function(stream, new_chunk):
460
+ # # try:
461
+ # # sr, y = new_chunk[0], new_chunk[1]
462
+ # # except TypeError:
463
+ # # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
464
+ # # return stream, "", None
465
+
466
+ # # y = y.astype(np.float32) / np.max(np.abs(y))
467
+
468
+ # # if stream is not None:
469
+ # # stream = np.concatenate([stream, y])
470
+ # # else:
471
+ # # stream = y
472
+
473
+ # # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
474
+
475
+ # # full_text = result.get("text","")
476
+
477
+ # # return stream, full_text, result
478
+
479
+
480
+ # def transcribe_function(stream, new_chunk):
481
+ # sr, y = new_chunk[0], new_chunk[1]
482
+ # y = y.astype(np.float32) / np.max(np.abs(y))
483
+ # if stream is not None:
484
+ # stream = np.concatenate([stream, y])
485
+ # else:
486
+ # stream = y
487
+ # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
488
+ # full_text = result.get("text", "")
489
+ # return stream, full_text # Return the transcribed text
490
+
491
+ # def update_map_with_response(history):
492
+ # if not history:
493
+ # return ""
494
+ # response = history[-1][1]
495
+ # addresses = extract_addresses(response)
496
+ # return generate_map(addresses)
497
+
498
+ # def clear_textbox():
499
+ # return ""
500
+
501
+ # def show_map_if_details(history,choice):
502
+ # if choice in ["Details", "Conversational"]:
503
+ # return gr.update(visible=True), update_map_with_response(history)
504
+ # else:
505
+ # return gr.update(visible=False), ""
506
+
507
+ # def generate_audio_elevenlabs(text):
508
+ # XI_API_KEY = os.environ['ELEVENLABS_API']
509
+ # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
510
+ # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
511
+ # headers = {
512
+ # "Accept": "application/json",
513
+ # "xi-api-key": XI_API_KEY
514
+ # }
515
+ # data = {
516
+ # "text": str(text),
517
+ # "model_id": "eleven_multilingual_v2",
518
+ # "voice_settings": {
519
+ # "stability": 1.0,
520
+ # "similarity_boost": 0.0,
521
+ # "style": 0.60,
522
+ # "use_speaker_boost": False
523
+ # }
524
+ # }
525
+ # response = requests.post(tts_url, headers=headers, json=data, stream=True)
526
+ # if response.ok:
527
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
528
+ # for chunk in response.iter_content(chunk_size=1024):
529
+ # f.write(chunk)
530
+ # temp_audio_path = f.name
531
+ # logging.debug(f"Audio saved to {temp_audio_path}")
532
+ # return temp_audio_path
533
+ # else:
534
+ # logging.error(f"Error generating audio: {response.text}")
535
+ # return None
536
+
537
+ # repo_id = "parler-tts/parler-tts-mini-expresso"
538
+
539
+ # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
540
+ # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
541
+ # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
542
+
543
+ # SAMPLE_RATE = parler_feature_extractor.sampling_rate
544
+ # SEED = 42
545
+
546
+ # def preprocess(text):
547
+ # number_normalizer = EnglishNumberNormalizer()
548
+ # text = number_normalizer(text).strip()
549
+ # if text[-1] not in punctuation:
550
+ # text = f"{text}."
551
+
552
+ # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
553
+
554
+ # def separate_abb(chunk):
555
+ # chunk = chunk.replace(".", "")
556
+ # return " ".join(chunk)
557
+
558
+ # abbreviations = re.findall(abbreviations_pattern, text)
559
+ # for abv in abbreviations:
560
+ # if abv in text:
561
+ # text = text.replace(abv, separate_abb(abv))
562
+ # return text
563
+
564
+ # def chunk_text(text, max_length=250):
565
+ # words = text.split()
566
+ # chunks = []
567
+ # current_chunk = []
568
+ # current_length = 0
569
+
570
+ # for word in words:
571
+ # if current_length + len(word) + 1 <= max_length:
572
+ # current_chunk.append(word)
573
+ # current_length += len(word) + 1
574
+ # else:
575
+ # chunks.append(' '.join(current_chunk))
576
+ # current_chunk = [word]
577
+ # current_length = len(word) + 1
578
+
579
+ # if current_chunk:
580
+ # chunks.append(' '.join(current_chunk))
581
+
582
+ # return chunks
583
+
584
+ # def generate_audio_parler_tts(text):
585
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
586
+ # chunks = chunk_text(preprocess(text))
587
+ # audio_segments = []
588
+
589
+ # for chunk in chunks:
590
+ # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
591
+ # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
592
+
593
+ # set_seed(SEED)
594
+ # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
595
+ # audio_arr = generation.cpu().numpy().squeeze()
596
+
597
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
598
+ # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
599
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
600
+
601
+ # combined_audio = sum(audio_segments)
602
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
603
+ # combined_audio.export(combined_audio_path, format="wav")
604
+
605
+ # logging.debug(f"Audio saved to {combined_audio_path}")
606
+ # return combined_audio_path
607
+
608
+ # # Load the MARS5 model
609
+ # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
610
+
611
+ # def generate_audio_mars5(text):
612
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
613
+ # kwargs_dict = {
614
+ # 'temperature': 0.2,
615
+ # 'top_k': -1,
616
+ # 'top_p': 0.2,
617
+ # 'typical_p': 1.0,
618
+ # 'freq_penalty': 2.6,
619
+ # 'presence_penalty': 0.4,
620
+ # 'rep_penalty_window': 100,
621
+ # 'max_prompt_phones': 360,
622
+ # 'deep_clone': True,
623
+ # 'nar_guidance_w': 3
624
+ # }
625
+
626
+ # chunks = chunk_text(preprocess(text))
627
+ # audio_segments = []
628
+
629
+ # for chunk in chunks:
630
+ # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
631
+ # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
632
+ # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
633
+
634
+
635
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
636
+ # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
637
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
638
+
639
+ # combined_audio = sum(audio_segments)
640
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
641
+ # combined_audio.export(combined_audio_path, format="wav")
642
+
643
+ # logging.debug(f"Audio saved to {combined_audio_path}")
644
+ # return combined_audio_path
645
+
646
+ # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
647
+ # pipe.to(device)
648
+
649
+ # def generate_image(prompt):
650
+ # with torch.cuda.amp.autocast():
651
+ # image = pipe(
652
+ # prompt,
653
+ # num_inference_steps=28,
654
+ # guidance_scale=3.0,
655
+ # ).images[0]
656
+ # return image
657
+
658
+ # hardcoded_prompt_1 = "Give a high quality photograph of a great looking red 2026 Toyota coupe against a skyline setting in the night, michael mann style in omaha enticing the consumer to buy this product"
659
+ # hardcoded_prompt_2 = "A vibrant and dynamic football game scene in the style of Peter Paul Rubens, showcasing the intense match between Alabama and Nebraska. The players are depicted with the dramatic, muscular physiques and expressive faces typical of Rubens' style. The Alabama team is wearing their iconic crimson and white uniforms, while the Nebraska team is in their classic red and white attire. The scene is filled with action, with players in mid-motion, tackling, running, and catching the ball. The background features a grand stadium filled with cheering fans, banners, and the natural landscape in the distance. The colors are rich and vibrant, with a strong use of light and shadow to create depth and drama. The overall atmosphere captures the intensity and excitement of the game, infused with the grandeur and dynamism characteristic of Rubens' work."
660
+ # hardcoded_prompt_3 = "Create a high-energy scene of a DJ performing on a large stage with vibrant lights, colorful lasers, a lively dancing crowd, and various electronic equipment in the background."
661
+
662
+ # def update_images():
663
+ # image_1 = generate_image(hardcoded_prompt_1)
664
+ # image_2 = generate_image(hardcoded_prompt_2)
665
+ # image_3 = generate_image(hardcoded_prompt_3)
666
+ # return image_1, image_2, image_3
667
+
668
+ # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
669
+ # with gr.Row():
670
+ # with gr.Column():
671
+ # state = gr.State()
672
+
673
+ # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
674
+ # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
675
+
676
+ # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
677
+
678
+ # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!",placeholder="After Prompt,click Retriever Only")
679
+ # chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input], api_name="voice_query")
680
+ # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
681
+ # retriver_button = gr.Button("Retriever")
682
+
683
+ # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
684
+ # location_output = gr.HTML()
685
+ # retriver_button.click(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input]).then(
686
+ # fn=bot, inputs=[chatbot, choice, tts_choice, state], outputs=[chatbot, gr.Audio(interactive=False, autoplay=True)], api_name="Ask_Retriever").then(
687
+ # fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder")
688
+
689
+ # bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot], api_name="generate_voice_response")
690
+ # bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
691
+ # chatbot.like(print_like_dislike, None, None)
692
+ # clear_button = gr.Button("Clear")
693
+ # clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
694
+
695
+ # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy')
696
+ # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
697
+
698
+
699
+
700
+
701
+
702
+
703
+
704
+ # # with gr.Column():
705
+ # # weather_output = gr.HTML(value=fetch_local_weather())
706
+ # # news_output = gr.HTML(value=fetch_local_news())
707
+ # # news_output = gr.HTML(value=fetch_local_events())
708
+
709
+
710
+ # with gr.Column():
711
+ # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
712
+ # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
713
+ # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
714
+
715
+ # refresh_button = gr.Button("Refresh Images")
716
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
717
+ # location_output = gr.HTML()
718
+ # bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output], api_name="map_finder")
719
+
720
+
721
+
722
+ # demo.queue()
723
+ # demo.launch(share=True)
724
+
725
+
726
+
727
+
728
+
729
  import gradio as gr
730
  import requests
731
  import os
 
791
 
792
  current_time_and_date = get_current_time_and_date()
793
 
 
 
794
  def fetch_local_events():
 
 
795
  api_key = os.environ['SERP_API']
796
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
797
  response = requests.get(url)
 
854
  else:
855
  return "<p>Failed to fetch local events</p>"
856
 
 
 
 
857
  def fetch_local_weather():
858
  try:
859
  api_key = os.environ['WEATHER_API']
 
947
  Question: {question}
948
  Helpful Answer:"""
949
 
 
 
 
 
 
 
 
 
950
  template2 = """You are an expert concierge who is helpful and a renowned guide for Birmingham,Alabama. Based on today's weather being a sunny bright day and today's date is 16th july 2024, take the location or address but don't show the location or address on the output prompts. Use the following pieces of context,
951
  memory, and message history, along with your knowledge of perennial events in Birmingham,Alabama, to answer the question at the end. If you don't know the answer, just say "Homie, I need to get more data for this," and don't try to make up an answer.
952
  Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
 
986
  )
987
  return agent
988
 
 
989
  def generate_answer(message, choice):
990
  logging.debug(f"generate_answer called with prompt_choice: {choice}")
991
 
 
1001
  addresses = extract_addresses(response['output'])
1002
  return response['output'], addresses
1003
 
 
 
1004
  def bot(history, choice, tts_choice, state):
1005
  if not history:
1006
  return history
 
1027
  history.append((message, None))
1028
  return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
1029
 
 
 
1030
  def print_like_dislike(x: gr.LikeData):
1031
  print(x.index, x.value, x.liked)
1032
 
 
1052
 
1053
  all_addresses = []
1054
 
 
 
1055
  def generate_map(location_names):
1056
  global all_addresses
1057
  all_addresses.extend(location_names)
 
1073
  map_html = m._repr_html_()
1074
  return map_html
1075
 
 
1076
  def fetch_local_news():
1077
  api_key = os.environ['SERP_API']
1078
  url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
 
1157
  model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
1158
  processor = AutoProcessor.from_pretrained(model_id)
1159
 
1160
+ pipe_asr = pipeline("automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, feature_extractor=processor.feature_extractor, max_new_tokens=128, chunk_length_s=15, batch_size=16, torch_dtype=torch_dtype, device=device, return_timestamps=False)
1161
 
1162
  base_audio_drive = "/data/audio"
1163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1164
  def transcribe_function(stream, new_chunk):
1165
+ try:
1166
+ sr, y = new_chunk[0], new_chunk[1]
1167
+ except TypeError:
1168
+ print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
1169
+ return stream, ""
1170
+
1171
  y = y.astype(np.float32) / np.max(np.abs(y))
1172
+
1173
  if stream is not None:
1174
  stream = np.concatenate([stream, y])
1175
  else:
1176
  stream = y
1177
+
1178
  result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
1179
+
1180
  full_text = result.get("text", "")
1181
+
1182
+ return stream, full_text
1183
+
1184
+ def update_transcription_state(state, new_text):
1185
+ state = new_text # Update the state with the new transcribed text
1186
+ return state
1187
+
1188
+ def push_to_input(state):
1189
+ return state # Return the state value to push it to the input prompt
1190
 
1191
  def update_map_with_response(history):
1192
  if not history:
 
1198
  def clear_textbox():
1199
  return ""
1200
 
1201
+ def show_map_if_details(history, choice):
1202
  if choice in ["Details", "Conversational"]:
1203
  return gr.update(visible=True), update_map_with_response(history)
1204
  else:
 
1331
  cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
1332
  ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
1333
 
 
1334
  temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
1335
  torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
1336
  audio_segments.append(AudioSegment.from_wav(temp_audio_path))
 
1368
  with gr.Row():
1369
  with gr.Column():
1370
  state = gr.State()
1371
+ transcription_state = gr.State(value="") # Initialize a state to hold the transcribed text
1372
 
1373
  chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
1374
  choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
 
1392
  clear_button = gr.Button("Clear")
1393
  clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
1394
 
1395
+ audio_input = gr.Audio(sources=["microphone"], streaming=False, type='numpy')
1396
+ audio_input.change(fn=transcribe_function, inputs=[transcription_state, audio_input], outputs=[transcription_state, transcription_state], api_name="voice_query_to_text")
 
 
 
 
 
 
1397
 
1398
+ send_chunk_button = gr.Button("Send chunk")
1399
+ send_chunk_button.click(fn=push_to_input, inputs=[transcription_state], outputs=chat_input)
 
 
1400
 
 
1401
  with gr.Column():
1402
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
1403
  image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
 
1407
  refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
1408
  location_output = gr.HTML()
1409
  bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output], api_name="map_finder")
 
 
1410
 
1411
  demo.queue()
1412
  demo.launch(share=True)
 
1414
 
1415
 
1416