Pijush2023 commited on
Commit
bd7b484
·
verified ·
1 Parent(s): 28c19c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +616 -17
app.py CHANGED
@@ -1,3 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
@@ -25,6 +633,7 @@ from transformers.models.speecht5.number_normalizer import EnglishNumberNormaliz
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 string import punctuation
29
 
30
  # Check if the token is already set in the environment variables
@@ -318,7 +927,7 @@ def fetch_local_news():
318
  api_key = os.environ['SERP_API']
319
  url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
320
  response = requests.get(url)
321
- if response.status_code == 200:
322
  results = response.json().get("news_results", [])
323
  news_html = """
324
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
@@ -518,7 +1127,7 @@ def chunk_text(text, max_length=250):
518
  def generate_audio_parler_tts(text):
519
  description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
520
  chunks = chunk_text(preprocess(text))
521
- audio_paths = []
522
 
523
  for chunk in chunks:
524
  inputs = parler_tokenizer(description, return_tensors="pt").to(device)
@@ -528,15 +1137,13 @@ def generate_audio_parler_tts(text):
528
  generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
529
  audio_arr = generation.cpu().numpy().squeeze()
530
 
531
- temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_paths)}.wav")
532
  write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
533
- audio_paths.append(temp_audio_path)
534
 
 
535
  combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
536
- with open(combined_audio_path, "wb") as f:
537
- for path in audio_paths:
538
- with open(path, "rb") as part_f:
539
- f.write(part_f.read())
540
 
541
  logging.debug(f"Audio saved to {combined_audio_path}")
542
  return combined_audio_path
@@ -584,15 +1191,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
584
  audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy')
585
  audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="SAMLOne_real_time")
586
 
587
- gr.Markdown("<h1 style='color: red;'>Map</h1>", elem_id="location-markdown")
588
- location_output = gr.HTML()
589
- bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output])
590
-
591
- with gr.Column():
592
- weather_output = gr.HTML(value=fetch_local_weather())
593
- news_output = gr.HTML(value=fetch_local_news())
594
- events_output = gr.HTML(value=fetch_local_events())
595
-
596
  with gr.Column():
597
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
598
  image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
@@ -604,3 +1202,4 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
604
  demo.queue()
605
  demo.launch(share=True)
606
 
 
 
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 string import punctuation
29
+
30
+ # # Check if the token is already set in the environment variables
31
+ # hf_token = os.getenv("HF_TOKEN")
32
+ # if hf_token is None:
33
+ # print("Please set your Hugging Face token in the environment variables.")
34
+ # else:
35
+ # login(token=hf_token)
36
+
37
+ # logging.basicConfig(level=logging.DEBUG)
38
+
39
+ # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
40
+
41
+ # from pinecone import Pinecone
42
+ # pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
43
+
44
+ # index_name = "birmingham-dataset"
45
+ # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
46
+ # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
47
+
48
+ # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
49
+
50
+ # conversational_memory = ConversationBufferWindowMemory(
51
+ # memory_key='chat_history',
52
+ # k=10,
53
+ # return_messages=True
54
+ # )
55
+
56
+ # def get_current_time_and_date():
57
+ # now = datetime.now()
58
+ # return now.strftime("%Y-%m-%d %H:%M:%S")
59
+
60
+ # current_time_and_date = get_current_time_and_date()
61
+
62
+ # def fetch_local_events():
63
+ # api_key = os.environ['SERP_API']
64
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
65
+ # response = requests.get(url)
66
+ # if response.status_code == 200:
67
+ # events_results = response.json().get("events_results", [])
68
+ # events_html = """
69
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
70
+ # <style>
71
+ # .event-item {
72
+ # font-family: 'Verdana', sans-serif;
73
+ # color: #333;
74
+ # margin-bottom: 15px;
75
+ # padding: 10px;
76
+ # font-weight: bold;
77
+ # }
78
+ # .event-item a {
79
+ # color: #1E90FF;
80
+ # text-decoration: none;
81
+ # }
82
+ # .event-item a:hover {
83
+ # text-decoration: underline;
84
+ # }
85
+ # </style>
86
+ # """
87
+ # for index, event in enumerate(events_results):
88
+ # title = event.get("title", "No title")
89
+ # date = event.get("date", "No date")
90
+ # location = event.get("address", "No location")
91
+ # link = event.get("link", "#")
92
+ # events_html += f"""
93
+ # <div class="event-item">
94
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
95
+ # <p>Date: {date}<br>Location: {location}</p>
96
+ # </div>
97
+ # """
98
+ # return events_html
99
+ # else:
100
+ # return "<p>Failed to fetch local events</p>"
101
+
102
+ # def fetch_local_weather():
103
+ # try:
104
+ # api_key = os.environ['WEATHER_API']
105
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
106
+ # response = requests.get(url)
107
+ # response.raise_for_status()
108
+ # jsonData = response.json()
109
+
110
+ # current_conditions = jsonData.get("currentConditions", {})
111
+ # temp_celsius = current_conditions.get("temp", "N/A")
112
+
113
+ # if temp_celsius != "N/A":
114
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
115
+ # else:
116
+ # temp_fahrenheit = "N/A"
117
+
118
+ # condition = current_conditions.get("conditions", "N/A")
119
+ # humidity = current_conditions.get("humidity", "N/A")
120
+
121
+ # weather_html = f"""
122
+ # <div class="weather-theme">
123
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
124
+ # <div class="weather-content">
125
+ # <div class="weather-icon">
126
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
127
+ # </div>
128
+ # <div class="weather-details">
129
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
130
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
131
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
132
+ # </div>
133
+ # </div>
134
+ # </div>
135
+ # <style>
136
+ # .weather-theme {{
137
+ # animation: backgroundAnimation 10s infinite alternate;
138
+ # border-radius: 10px;
139
+ # padding: 10px;
140
+ # margin-bottom: 15px;
141
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
142
+ # background-size: 400% 400%;
143
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
144
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
145
+ # }}
146
+ # .weather-theme:hover {{
147
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
148
+ # background-position: 100% 100%;
149
+ # }}
150
+ # @keyframes backgroundAnimation {{
151
+ # 0% {{ background-position: 0% 50%; }}
152
+ # 100% {{ background-position: 100% 50%; }}
153
+ # }}
154
+ # .weather-content {{
155
+ # display: flex;
156
+ # align-items: center;
157
+ # }}
158
+ # .weather-icon {{
159
+ # flex: 1;
160
+ # }}
161
+ # .weather-details {{
162
+ # flex: 3;
163
+ # }}
164
+ # </style>
165
+ # """
166
+ # return weather_html
167
+ # except requests.exceptions.RequestException as e:
168
+ # return f"<p>Failed to fetch local weather: {e}</p>"
169
+
170
+ # def get_weather_icon(condition):
171
+ # condition_map = {
172
+ # "Clear": "c01d",
173
+ # "Partly Cloudy": "c02d",
174
+ # "Cloudy": "c03d",
175
+ # "Overcast": "c04d",
176
+ # "Mist": "a01d",
177
+ # "Patchy rain possible": "r01d",
178
+ # "Light rain": "r02d",
179
+ # "Moderate rain": "r03d",
180
+ # "Heavy rain": "r04d",
181
+ # "Snow": "s01d",
182
+ # "Thunderstorm": "t01d",
183
+ # "Fog": "a05d",
184
+ # }
185
+ # return condition_map.get(condition, "c04d")
186
+
187
+ # 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,
188
+ # 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.
189
+ # Use fifteen sentences maximum. Keep the answer as detailed as possible. Always include the address, time, date, and
190
+ # event type and description. Always say "It was my pleasure!" at the end of the answer.
191
+ # {context}
192
+ # Question: {question}
193
+ # Helpful Answer:"""
194
+
195
+ # 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,
196
+ # 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.
197
+ # Keep the answer short and sweet and crisp. Always say "It was my pleasure!" at the end of the answer.
198
+ # {context}
199
+ # Question: {question}
200
+ # Helpful Answer:"""
201
+
202
+ # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
203
+ # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
204
+
205
+ # def build_qa_chain(prompt_template):
206
+ # qa_chain = RetrievalQA.from_chain_type(
207
+ # llm=chat_model,
208
+ # chain_type="stuff",
209
+ # retriever=retriever,
210
+ # chain_type_kwargs={"prompt": prompt_template}
211
+ # )
212
+ # tools = [
213
+ # Tool(
214
+ # name='Knowledge Base',
215
+ # func=qa_chain,
216
+ # description='Use this tool when answering general knowledge queries to get more information about the topic'
217
+ # )
218
+ # ]
219
+ # return qa_chain, tools
220
+
221
+ # def initialize_agent_with_prompt(prompt_template):
222
+ # qa_chain, tools = build_qa_chain(prompt_template)
223
+ # agent = initialize_agent(
224
+ # agent='chat-conversational-react-description',
225
+ # tools=tools,
226
+ # llm=chat_model,
227
+ # verbose=False,
228
+ # max_iteration=5,
229
+ # early_stopping_method='generate',
230
+ # memory=conversational_memory
231
+ # )
232
+ # return agent
233
+
234
+ # def generate_answer(message, choice):
235
+ # logging.debug(f"generate_answer called with prompt_choice: {choice}")
236
+
237
+ # if choice == "Details":
238
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
239
+ # elif choice == "Conversational":
240
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
241
+ # else:
242
+ # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
243
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
244
+ # response = agent(message)
245
+
246
+ # addresses = extract_addresses(response['output'])
247
+ # return response['output'], addresses
248
+
249
+ # def bot(history, choice, tts_choice):
250
+ # if not history:
251
+ # return history
252
+ # response, addresses = generate_answer(history[-1][0], choice)
253
+ # history[-1][1] = ""
254
+
255
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
256
+ # if tts_choice == "Eleven Labs":
257
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
258
+ # elif tts_choice == "Parler-TTS":
259
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
260
+
261
+ # for character in response:
262
+ # history[-1][1] += character
263
+ # time.sleep(0.05)
264
+ # yield history, None
265
+
266
+ # audio_path = audio_future.result()
267
+ # yield history, audio_path
268
+
269
+ # def add_message(history, message):
270
+ # history.append((message, None))
271
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
272
+
273
+ # def print_like_dislike(x: gr.LikeData):
274
+ # print(x.index, x.value, x.liked)
275
+
276
+ # def extract_addresses(response):
277
+ # if not isinstance(response, str):
278
+ # response = str(response)
279
+ # address_patterns = [
280
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
281
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
282
+ # r'([A-Z].*,\sAL\s\d{5})',
283
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
284
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
285
+ # r'(\d{2}.*\sStreets)',
286
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
287
+ # r'([a-zA-Z]\s Birmingham)'
288
+ # ]
289
+ # addresses = []
290
+ # for pattern in address_patterns:
291
+ # addresses.extend(re.findall(pattern, response))
292
+ # return addresses
293
+
294
+ # all_addresses = []
295
+
296
+ # def generate_map(location_names):
297
+ # global all_addresses
298
+ # all_addresses.extend(location_names)
299
+
300
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
301
+ # gmaps = GoogleMapsClient(key=api_key)
302
+
303
+ # m = folium.Map(location=[33.5175,-86.809444], zoom_start=16)
304
+
305
+ # for location_name in all_addresses:
306
+ # geocode_result = gmaps.geocode(location_name)
307
+ # if geocode_result:
308
+ # location = geocode_result[0]['geometry']['location']
309
+ # folium.Marker(
310
+ # [location['lat'], location['lng']],
311
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
312
+ # ).add_to(m)
313
+
314
+ # map_html = m._repr_html_()
315
+ # return map_html
316
+
317
+ # def fetch_local_news():
318
+ # api_key = os.environ['SERP_API']
319
+ # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
320
+ # response = requests.get(url)
321
+ # if response.status_code == 200:
322
+ # results = response.json().get("news_results", [])
323
+ # news_html = """
324
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
325
+ # <style>
326
+ # .news-item {
327
+ # font-family: 'Verdana', sans-serif;
328
+ # color: #333;
329
+ # background-color: #f0f8ff;
330
+ # margin-bottom: 15px;
331
+ # padding: 10px;
332
+ # border-radius: 5px;
333
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
334
+ # font-weight: bold;
335
+ # }
336
+ # .news-item:hover {
337
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
338
+ # background-color: #e6f7ff;
339
+ # }
340
+ # .news-item a {
341
+ # color: #1E90FF;
342
+ # text-decoration: none;
343
+ # font-weight: bold;
344
+ # }
345
+ # .news-item a:hover {
346
+ # text-decoration: underline;
347
+ # }
348
+ # .news-preview {
349
+ # position: absolute;
350
+ # display: none;
351
+ # border: 1px solid #ccc;
352
+ # border-radius: 5px;
353
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
354
+ # background-color: white;
355
+ # z-index: 1000;
356
+ # max-width: 300px;
357
+ # padding: 10px;
358
+ # font-family: 'Verdana', sans-serif;
359
+ # color: #333;
360
+ # }
361
+ # </style>
362
+ # <script>
363
+ # function showPreview(event, previewContent) {
364
+ # var previewBox = document.getElementById('news-preview');
365
+ # previewBox.innerHTML = previewContent;
366
+ # previewBox.style.left = event.pageX + 'px';
367
+ # previewBox.style.top = event.pageY + 'px';
368
+ # previewBox.style.display = 'block';
369
+ # }
370
+ # function hidePreview() {
371
+ # var previewBox = document.getElementById('news-preview');
372
+ # previewBox.style.display = 'none';
373
+ # }
374
+ # </script>
375
+ # <div id="news-preview" class="news-preview"></div>
376
+ # """
377
+ # for index, result in enumerate(results[:7]):
378
+ # title = result.get("title", "No title")
379
+ # link = result.get("link", "#")
380
+ # snippet = result.get("snippet", "")
381
+ # news_html += f"""
382
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
383
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
384
+ # <p>{snippet}</p>
385
+ # </div>
386
+ # """
387
+ # return news_html
388
+ # else:
389
+ # return "<p>Failed to fetch local news</p>"
390
+
391
+ # import numpy as np
392
+ # import torch
393
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
394
+
395
+ # model_id = 'openai/whisper-large-v3'
396
+ # device = "cuda:0" if torch.cuda.is_available() else "cpu"
397
+ # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
398
+ # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
399
+ # processor = AutoProcessor.from_pretrained(model_id)
400
+
401
+ # 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)
402
+
403
+ # base_audio_drive = "/data/audio"
404
+
405
+ # def transcribe_function(stream, new_chunk):
406
+ # try:
407
+ # sr, y = new_chunk[0], new_chunk[1]
408
+ # except TypeError:
409
+ # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
410
+ # return stream, "", None
411
+
412
+ # y = y.astype(np.float32) / np.max(np.abs(y))
413
+
414
+ # if stream is not None:
415
+ # stream = np.concatenate([stream, y])
416
+ # else:
417
+ # stream = y
418
+
419
+ # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
420
+
421
+ # full_text = result.get("text", "")
422
+
423
+ # return stream, full_text, result
424
+
425
+ # def update_map_with_response(history):
426
+ # if not history:
427
+ # return ""
428
+ # response = history[-1][1]
429
+ # addresses = extract_addresses(response)
430
+ # return generate_map(addresses)
431
+
432
+ # def clear_textbox():
433
+ # return ""
434
+
435
+ # def show_map_if_details(history,choice):
436
+ # if choice in ["Details", "Conversational"]:
437
+ # return gr.update(visible=True), update_map_with_response(history)
438
+ # else:
439
+ # return gr.update(visible=False), ""
440
+
441
+ # def generate_audio_elevenlabs(text):
442
+ # XI_API_KEY = os.environ['ELEVENLABS_API']
443
+ # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
444
+ # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
445
+ # headers = {
446
+ # "Accept": "application/json",
447
+ # "xi-api-key": XI_API_KEY
448
+ # }
449
+ # data = {
450
+ # "text": str(text),
451
+ # "model_id": "eleven_multilingual_v2",
452
+ # "voice_settings": {
453
+ # "stability": 1.0,
454
+ # "similarity_boost": 0.0,
455
+ # "style": 0.60,
456
+ # "use_speaker_boost": False
457
+ # }
458
+ # }
459
+ # response = requests.post(tts_url, headers=headers, json=data, stream=True)
460
+ # if response.ok:
461
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
462
+ # for chunk in response.iter_content(chunk_size=1024):
463
+ # f.write(chunk)
464
+ # temp_audio_path = f.name
465
+ # logging.debug(f"Audio saved to {temp_audio_path}")
466
+ # return temp_audio_path
467
+ # else:
468
+ # logging.error(f"Error generating audio: {response.text}")
469
+ # return None
470
+
471
+ # repo_id = "parler-tts/parler-tts-mini-expresso"
472
+
473
+ # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
474
+ # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
475
+ # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
476
+
477
+ # SAMPLE_RATE = parler_feature_extractor.sampling_rate
478
+ # SEED = 42
479
+
480
+ # def preprocess(text):
481
+ # number_normalizer = EnglishNumberNormalizer()
482
+ # text = number_normalizer(text).strip()
483
+ # if text[-1] not in punctuation:
484
+ # text = f"{text}."
485
+
486
+ # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
487
+
488
+ # def separate_abb(chunk):
489
+ # chunk = chunk.replace(".", "")
490
+ # return " ".join(chunk)
491
+
492
+ # abbreviations = re.findall(abbreviations_pattern, text)
493
+ # for abv in abbreviations:
494
+ # if abv in text:
495
+ # text = text.replace(abv, separate_abb(abv))
496
+ # return text
497
+
498
+ # def chunk_text(text, max_length=250):
499
+ # words = text.split()
500
+ # chunks = []
501
+ # current_chunk = []
502
+ # current_length = 0
503
+
504
+ # for word in words:
505
+ # if current_length + len(word) + 1 <= max_length:
506
+ # current_chunk.append(word)
507
+ # current_length += len(word) + 1
508
+ # else:
509
+ # chunks.append(' '.join(current_chunk))
510
+ # current_chunk = [word]
511
+ # current_length = len(word) + 1
512
+
513
+ # if current_chunk:
514
+ # chunks.append(' '.join(current_chunk))
515
+
516
+ # return chunks
517
+
518
+ # def generate_audio_parler_tts(text):
519
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
520
+ # chunks = chunk_text(preprocess(text))
521
+ # audio_paths = []
522
+
523
+ # for chunk in chunks:
524
+ # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
525
+ # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
526
+
527
+ # set_seed(SEED)
528
+ # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
529
+ # audio_arr = generation.cpu().numpy().squeeze()
530
+
531
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_paths)}.wav")
532
+ # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
533
+ # audio_paths.append(temp_audio_path)
534
+
535
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
536
+ # with open(combined_audio_path, "wb") as f:
537
+ # for path in audio_paths:
538
+ # with open(path, "rb") as part_f:
539
+ # f.write(part_f.read())
540
+
541
+ # logging.debug(f"Audio saved to {combined_audio_path}")
542
+ # return combined_audio_path
543
+
544
+ # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
545
+ # pipe.to(device)
546
+
547
+ # def generate_image(prompt):
548
+ # with torch.cuda.amp.autocast():
549
+ # image = pipe(
550
+ # prompt,
551
+ # num_inference_steps=28,
552
+ # guidance_scale=3.0,
553
+ # ).images[0]
554
+ # return image
555
+
556
+ # hardcoded_prompt_1 = "Give a high quality photograph of a great looking red 2026 Bentley coupe against a skyline setting in the night, michael mann style in omaha enticing the consumer to buy this product"
557
+ # 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."
558
+ # 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."
559
+
560
+ # def update_images():
561
+ # image_1 = generate_image(hardcoded_prompt_1)
562
+ # image_2 = generate_image(hardcoded_prompt_2)
563
+ # image_3 = generate_image(hardcoded_prompt_3)
564
+ # return image_1, image_2, image_3
565
+
566
+ # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
567
+ # with gr.Row():
568
+ # with gr.Column():
569
+ # state = gr.State()
570
+
571
+ # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
572
+ # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
573
+
574
+ # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
575
+ # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!")
576
+ # chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])
577
+ # tts_choice = gr.Radio(label="Select TTS System", choices=["Eleven Labs", "Parler-TTS"], value="Eleven Labs")
578
+ # bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot, gr.Audio(interactive=False, autoplay=True)])
579
+ # bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
580
+ # chatbot.like(print_like_dislike, None, None)
581
+ # clear_button = gr.Button("Clear")
582
+ # clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
583
+
584
+ # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy')
585
+ # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="SAMLOne_real_time")
586
+
587
+ # # gr.Markdown("<h1 style='color: red;'>Map</h1>", elem_id="location-markdown")
588
+ # # location_output = gr.HTML()
589
+ # # bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output])
590
+
591
+ # # with gr.Column():
592
+ # # weather_output = gr.HTML(value=fetch_local_weather())
593
+ # # news_output = gr.HTML(value=fetch_local_news())
594
+ # # events_output = gr.HTML(value=fetch_local_events())
595
+
596
+ # with gr.Column():
597
+ # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
598
+ # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
599
+ # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
600
+
601
+ # refresh_button = gr.Button("Refresh Images")
602
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
603
+
604
+ # demo.queue()
605
+ # demo.launch(share=True)
606
+
607
+
608
+
609
  import gradio as gr
610
  import requests
611
  import os
 
633
  from parler_tts import ParlerTTSForConditionalGeneration
634
  from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
635
  from scipy.io.wavfile import write as write_wav
636
+ from pydub import AudioSegment
637
  from string import punctuation
638
 
639
  # Check if the token is already set in the environment variables
 
927
  api_key = os.environ['SERP_API']
928
  url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
929
  response = requests.get(url)
930
+ if response.status_code == 200):
931
  results = response.json().get("news_results", [])
932
  news_html = """
933
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
 
1127
  def generate_audio_parler_tts(text):
1128
  description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
1129
  chunks = chunk_text(preprocess(text))
1130
+ audio_segments = []
1131
 
1132
  for chunk in chunks:
1133
  inputs = parler_tokenizer(description, return_tensors="pt").to(device)
 
1137
  generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
1138
  audio_arr = generation.cpu().numpy().squeeze()
1139
 
1140
+ temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
1141
  write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
1142
+ audio_segments.append(AudioSegment.from_wav(temp_audio_path))
1143
 
1144
+ combined_audio = sum(audio_segments)
1145
  combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
1146
+ combined_audio.export(combined_audio_path, format="wav")
 
 
 
1147
 
1148
  logging.debug(f"Audio saved to {combined_audio_path}")
1149
  return combined_audio_path
 
1191
  audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy')
1192
  audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="SAMLOne_real_time")
1193
 
 
 
 
 
 
 
 
 
 
1194
  with gr.Column():
1195
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
1196
  image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
 
1202
  demo.queue()
1203
  demo.launch(share=True)
1204
 
1205
+