Pijush2023 commited on
Commit
626c032
·
verified ·
1 Parent(s): 0b22551

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +656 -2
app.py CHANGED
@@ -27,6 +27,9 @@ 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
 
31
  # Check if the token is already set in the environment variables
32
  hf_token = os.getenv("HF_TOKEN")
@@ -258,6 +261,8 @@ def bot(history, choice, tts_choice):
258
  audio_future = executor.submit(generate_audio_elevenlabs, response)
259
  elif tts_choice == "Parler-TTS":
260
  audio_future = executor.submit(generate_audio_parler_tts, response)
 
 
261
 
262
  for character in response:
263
  history[-1][1] += character
@@ -319,7 +324,7 @@ def fetch_local_news():
319
  api_key = os.environ['SERP_API']
320
  url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
321
  response = requests.get(url)
322
- if response.status_code == 200:
323
  results = response.json().get("news_results", [])
324
  news_html = """
325
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
@@ -540,6 +545,55 @@ def generate_audio_parler_tts(text):
540
  logging.debug(f"Audio saved to {combined_audio_path}")
541
  return combined_audio_path
542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
543
  pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
544
  pipe.to(device)
545
 
@@ -573,7 +627,7 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
573
  gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
574
  chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!")
575
  chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])
576
- tts_choice = gr.Radio(label="Select TTS System", choices=["Eleven Labs", "Parler-TTS"], value="Eleven Labs")
577
  bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot, gr.Audio(interactive=False, autoplay=True)])
578
  bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
579
  chatbot.like(print_like_dislike, None, None)
@@ -595,3 +649,603 @@ demo.queue()
595
  demo.launch(share=True)
596
 
597
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")
 
261
  audio_future = executor.submit(generate_audio_elevenlabs, response)
262
  elif tts_choice == "Parler-TTS":
263
  audio_future = executor.submit(generate_audio_parler_tts, response)
264
+ elif tts_choice == "MARS5":
265
+ audio_future = executor.submit(generate_audio_mars5, response)
266
 
267
  for character in response:
268
  history[-1][1] += character
 
324
  api_key = os.environ['SERP_API']
325
  url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
326
  response = requests.get(url)
327
+ if response.status_code == 200):
328
  results = response.json().get("news_results", [])
329
  news_html = """
330
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
 
545
  logging.debug(f"Audio saved to {combined_audio_path}")
546
  return combined_audio_path
547
 
548
+ # Load the MARS5 model
549
+ mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
550
+ asr_model = pipeline(
551
+ "automatic-speech-recognition",
552
+ model="openai/whisper-tiny",
553
+ chunk_length_s=30,
554
+ device=torch.device("cuda:0"),
555
+ )
556
+
557
+ def transcribe_file(f: str) -> str:
558
+ predictions = asr_model(f, return_timestamps=True)["chunks"]
559
+ return " ".join([prediction["text"] for prediction in predictions])
560
+
561
+ def generate_audio_mars5(text):
562
+ description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
563
+ kwargs_dict = {
564
+ 'temperature': 0.8,
565
+ 'top_k': -1,
566
+ 'top_p': 0.2,
567
+ 'typical_p': 1.0,
568
+ 'freq_penalty': 2.6,
569
+ 'presence_penalty': 0.4,
570
+ 'rep_penalty_window': 100,
571
+ 'max_prompt_phones': 360,
572
+ 'deep_clone': True,
573
+ 'nar_guidance_w': 3
574
+ }
575
+
576
+ chunks = chunk_text(preprocess(text))
577
+ audio_segments = []
578
+
579
+ for chunk in chunks:
580
+ transcript = transcribe_file(audio_path) # Assuming audio_path is the path to the audio file for reference
581
+ wav, sr = librosa.load(audio_path, sr=mars5.sr, mono=True)
582
+ wav = torch.from_numpy(wav)
583
+ cfg = config_class(**kwargs_dict)
584
+ ar_codes, wav_out = mars5.tts(chunk, wav, transcript.strip(), cfg=cfg)
585
+
586
+ temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
587
+ torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
588
+ audio_segments.append(AudioSegment.from_wav(temp_audio_path))
589
+
590
+ combined_audio = sum(audio_segments)
591
+ combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
592
+ combined_audio.export(combined_audio_path, format="wav")
593
+
594
+ logging.debug(f"Audio saved to {combined_audio_path}")
595
+ return combined_audio_path
596
+
597
  pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
598
  pipe.to(device)
599
 
 
627
  gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
628
  chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!")
629
  chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])
630
+ tts_choice = gr.Radio(label="Select TTS System", choices=["Eleven Labs", "Parler-TTS", "MARS5"], value="Eleven Labs")
631
  bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot, gr.Audio(interactive=False, autoplay=True)])
632
  bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
633
  chatbot.like(print_like_dislike, None, None)
 
649
  demo.launch(share=True)
650
 
651
 
652
+
653
+
654
+
655
+ # import gradio as gr
656
+ # import requests
657
+ # import os
658
+ # import time
659
+ # import re
660
+ # import logging
661
+ # import tempfile
662
+ # import folium
663
+ # import concurrent.futures
664
+ # import torch
665
+ # from PIL import Image
666
+ # from datetime import datetime
667
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
668
+ # from googlemaps import Client as GoogleMapsClient
669
+ # from gtts import gTTS
670
+ # from diffusers import StableDiffusionPipeline
671
+ # from langchain_openai import OpenAIEmbeddings, ChatOpenAI
672
+ # from langchain_pinecone import PineconeVectorStore
673
+ # from langchain.prompts import PromptTemplate
674
+ # from langchain.chains import RetrievalQA
675
+ # from langchain.chains.conversation.memory import ConversationBufferWindowMemory
676
+ # from langchain.agents import Tool, initialize_agent
677
+ # from huggingface_hub import login
678
+ # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
679
+ # from parler_tts import ParlerTTSForConditionalGeneration
680
+ # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
681
+ # from scipy.io.wavfile import write as write_wav
682
+ # from pydub import AudioSegment
683
+ # from string import punctuation
684
+
685
+ # # Check if the token is already set in the environment variables
686
+ # hf_token = os.getenv("HF_TOKEN")
687
+ # if hf_token is None:
688
+ # print("Please set your Hugging Face token in the environment variables.")
689
+ # else:
690
+ # login(token=hf_token)
691
+
692
+ # logging.basicConfig(level=logging.DEBUG)
693
+
694
+ # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
695
+
696
+ # from pinecone import Pinecone
697
+ # pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
698
+
699
+ # index_name = "birmingham-dataset"
700
+ # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
701
+ # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
702
+
703
+ # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
704
+
705
+ # conversational_memory = ConversationBufferWindowMemory(
706
+ # memory_key='chat_history',
707
+ # k=10,
708
+ # return_messages=True
709
+ # )
710
+
711
+ # def get_current_time_and_date():
712
+ # now = datetime.now()
713
+ # return now.strftime("%Y-%m-%d %H:%M:%S")
714
+
715
+ # current_time_and_date = get_current_time_and_date()
716
+
717
+ # def fetch_local_events():
718
+ # api_key = os.environ['SERP_API']
719
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
720
+ # response = requests.get(url)
721
+ # if response.status_code == 200:
722
+ # events_results = response.json().get("events_results", [])
723
+ # events_html = """
724
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
725
+ # <style>
726
+ # .event-item {
727
+ # font-family: 'Verdana', sans-serif;
728
+ # color: #333;
729
+ # margin-bottom: 15px;
730
+ # padding: 10px;
731
+ # font-weight: bold;
732
+ # }
733
+ # .event-item a {
734
+ # color: #1E90FF;
735
+ # text-decoration: none;
736
+ # }
737
+ # .event-item a:hover {
738
+ # text-decoration: underline;
739
+ # }
740
+ # </style>
741
+ # """
742
+ # for index, event in enumerate(events_results):
743
+ # title = event.get("title", "No title")
744
+ # date = event.get("date", "No date")
745
+ # location = event.get("address", "No location")
746
+ # link = event.get("link", "#")
747
+ # events_html += f"""
748
+ # <div class="event-item">
749
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
750
+ # <p>Date: {date}<br>Location: {location}</p>
751
+ # </div>
752
+ # """
753
+ # return events_html
754
+ # else:
755
+ # return "<p>Failed to fetch local events</p>"
756
+
757
+ # def fetch_local_weather():
758
+ # try:
759
+ # api_key = os.environ['WEATHER_API']
760
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
761
+ # response = requests.get(url)
762
+ # response.raise_for_status()
763
+ # jsonData = response.json()
764
+
765
+ # current_conditions = jsonData.get("currentConditions", {})
766
+ # temp_celsius = current_conditions.get("temp", "N/A")
767
+
768
+ # if temp_celsius != "N/A":
769
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
770
+ # else:
771
+ # temp_fahrenheit = "N/A"
772
+
773
+ # condition = current_conditions.get("conditions", "N/A")
774
+ # humidity = current_conditions.get("humidity", "N/A")
775
+
776
+ # weather_html = f"""
777
+ # <div class="weather-theme">
778
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
779
+ # <div class="weather-content">
780
+ # <div class="weather-icon">
781
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
782
+ # </div>
783
+ # <div class="weather-details">
784
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
785
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
786
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
787
+ # </div>
788
+ # </div>
789
+ # </div>
790
+ # <style>
791
+ # .weather-theme {{
792
+ # animation: backgroundAnimation 10s infinite alternate;
793
+ # border-radius: 10px;
794
+ # padding: 10px;
795
+ # margin-bottom: 15px;
796
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
797
+ # background-size: 400% 400%;
798
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
799
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
800
+ # }}
801
+ # .weather-theme:hover {{
802
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
803
+ # background-position: 100% 100%;
804
+ # }}
805
+ # @keyframes backgroundAnimation {{
806
+ # 0% {{ background-position: 0% 50%; }}
807
+ # 100% {{ background-position: 100% 50%; }}
808
+ # }}
809
+ # .weather-content {{
810
+ # display: flex;
811
+ # align-items: center;
812
+ # }}
813
+ # .weather-icon {{
814
+ # flex: 1;
815
+ # }}
816
+ # .weather-details {{
817
+ # flex: 3;
818
+ # }}
819
+ # </style>
820
+ # """
821
+ # return weather_html
822
+ # except requests.exceptions.RequestException as e:
823
+ # return f"<p>Failed to fetch local weather: {e}</p>"
824
+
825
+ # def get_weather_icon(condition):
826
+ # condition_map = {
827
+ # "Clear": "c01d",
828
+ # "Partly Cloudy": "c02d",
829
+ # "Cloudy": "c03d",
830
+ # "Overcast": "c04d",
831
+ # "Mist": "a01d",
832
+ # "Patchy rain possible": "r01d",
833
+ # "Light rain": "r02d",
834
+ # "Moderate rain": "r03d",
835
+ # "Heavy rain": "r04d",
836
+ # "Snow": "s01d",
837
+ # "Thunderstorm": "t01d",
838
+ # "Fog": "a05d",
839
+ # }
840
+ # return condition_map.get(condition, "c04d")
841
+
842
+ # 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,
843
+ # 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.
844
+ # Use fifteen sentences maximum. Keep the answer as detailed as possible. Always include the address, time, date, and
845
+ # event type and description. Always say "It was my pleasure!" at the end of the answer.
846
+ # {context}
847
+ # Question: {question}
848
+ # Helpful Answer:"""
849
+
850
+ # 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,
851
+ # 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.
852
+ # Keep the answer short and sweet and crisp. Always say "It was my pleasure!" at the end of the answer.
853
+ # {context}
854
+ # Question: {question}
855
+ # Helpful Answer:"""
856
+
857
+ # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
858
+ # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
859
+
860
+ # def build_qa_chain(prompt_template):
861
+ # qa_chain = RetrievalQA.from_chain_type(
862
+ # llm=chat_model,
863
+ # chain_type="stuff",
864
+ # retriever=retriever,
865
+ # chain_type_kwargs={"prompt": prompt_template}
866
+ # )
867
+ # tools = [
868
+ # Tool(
869
+ # name='Knowledge Base',
870
+ # func=qa_chain,
871
+ # description='Use this tool when answering general knowledge queries to get more information about the topic'
872
+ # )
873
+ # ]
874
+ # return qa_chain, tools
875
+
876
+ # def initialize_agent_with_prompt(prompt_template):
877
+ # qa_chain, tools = build_qa_chain(prompt_template)
878
+ # agent = initialize_agent(
879
+ # agent='chat-conversational-react-description',
880
+ # tools=tools,
881
+ # llm=chat_model,
882
+ # verbose=False,
883
+ # max_iteration=5,
884
+ # early_stopping_method='generate',
885
+ # memory=conversational_memory
886
+ # )
887
+ # return agent
888
+
889
+ # def generate_answer(message, choice):
890
+ # logging.debug(f"generate_answer called with prompt_choice: {choice}")
891
+
892
+ # if choice == "Details":
893
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
894
+ # elif choice == "Conversational":
895
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
896
+ # else:
897
+ # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
898
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
899
+ # response = agent(message)
900
+
901
+ # addresses = extract_addresses(response['output'])
902
+ # return response['output'], addresses
903
+
904
+ # def bot(history, choice, tts_choice):
905
+ # if not history:
906
+ # return history
907
+ # response, addresses = generate_answer(history[-1][0], choice)
908
+ # history[-1][1] = ""
909
+
910
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
911
+ # if tts_choice == "Eleven Labs":
912
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
913
+ # elif tts_choice == "Parler-TTS":
914
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
915
+
916
+ # for character in response:
917
+ # history[-1][1] += character
918
+ # time.sleep(0.05)
919
+ # yield history, None
920
+
921
+ # audio_path = audio_future.result()
922
+ # yield history, audio_path
923
+
924
+ # def add_message(history, message):
925
+ # history.append((message, None))
926
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
927
+
928
+ # def print_like_dislike(x: gr.LikeData):
929
+ # print(x.index, x.value, x.liked)
930
+
931
+ # def extract_addresses(response):
932
+ # if not isinstance(response, str):
933
+ # response = str(response)
934
+ # address_patterns = [
935
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
936
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
937
+ # r'([A-Z].*,\sAL\s\d{5})',
938
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
939
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
940
+ # r'(\d{2}.*\sStreets)',
941
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
942
+ # r'([a-zA-Z]\s Birmingham)'
943
+ # ]
944
+ # addresses = []
945
+ # for pattern in address_patterns:
946
+ # addresses.extend(re.findall(pattern, response))
947
+ # return addresses
948
+
949
+ # all_addresses = []
950
+
951
+ # def generate_map(location_names):
952
+ # global all_addresses
953
+ # all_addresses.extend(location_names)
954
+
955
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
956
+ # gmaps = GoogleMapsClient(key=api_key)
957
+
958
+ # m = folium.Map(location=[33.5175,-86.809444], zoom_start=16)
959
+
960
+ # for location_name in all_addresses:
961
+ # geocode_result = gmaps.geocode(location_name)
962
+ # if geocode_result:
963
+ # location = geocode_result[0]['geometry']['location']
964
+ # folium.Marker(
965
+ # [location['lat'], location['lng']],
966
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
967
+ # ).add_to(m)
968
+
969
+ # map_html = m._repr_html_()
970
+ # return map_html
971
+
972
+ # def fetch_local_news():
973
+ # api_key = os.environ['SERP_API']
974
+ # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
975
+ # response = requests.get(url)
976
+ # if response.status_code == 200:
977
+ # results = response.json().get("news_results", [])
978
+ # news_html = """
979
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
980
+ # <style>
981
+ # .news-item {
982
+ # font-family: 'Verdana', sans-serif;
983
+ # color: #333;
984
+ # background-color: #f0f8ff;
985
+ # margin-bottom: 15px;
986
+ # padding: 10px;
987
+ # border-radius: 5px;
988
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
989
+ # font-weight: bold;
990
+ # }
991
+ # .news-item:hover {
992
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
993
+ # background-color: #e6f7ff;
994
+ # }
995
+ # .news-item a {
996
+ # color: #1E90FF;
997
+ # text-decoration: none;
998
+ # font-weight: bold;
999
+ # }
1000
+ # .news-item a:hover {
1001
+ # text-decoration: underline;
1002
+ # }
1003
+ # .news-preview {
1004
+ # position: absolute;
1005
+ # display: none;
1006
+ # border: 1px solid #ccc;
1007
+ # border-radius: 5px;
1008
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
1009
+ # background-color: white;
1010
+ # z-index: 1000;
1011
+ # max-width: 300px;
1012
+ # padding: 10px;
1013
+ # font-family: 'Verdana', sans-serif;
1014
+ # color: #333;
1015
+ # }
1016
+ # </style>
1017
+ # <script>
1018
+ # function showPreview(event, previewContent) {
1019
+ # var previewBox = document.getElementById('news-preview');
1020
+ # previewBox.innerHTML = previewContent;
1021
+ # previewBox.style.left = event.pageX + 'px';
1022
+ # previewBox.style.top = event.pageY + 'px';
1023
+ # previewBox.style.display = 'block';
1024
+ # }
1025
+ # function hidePreview() {
1026
+ # var previewBox = document.getElementById('news-preview');
1027
+ # previewBox.style.display = 'none';
1028
+ # }
1029
+ # </script>
1030
+ # <div id="news-preview" class="news-preview"></div>
1031
+ # """
1032
+ # for index, result in enumerate(results[:7]):
1033
+ # title = result.get("title", "No title")
1034
+ # link = result.get("link", "#")
1035
+ # snippet = result.get("snippet", "")
1036
+ # news_html += f"""
1037
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
1038
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
1039
+ # <p>{snippet}</p>
1040
+ # </div>
1041
+ # """
1042
+ # return news_html
1043
+ # else:
1044
+ # return "<p>Failed to fetch local news</p>"
1045
+
1046
+ # import numpy as np
1047
+ # import torch
1048
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
1049
+
1050
+ # model_id = 'openai/whisper-large-v3'
1051
+ # device = "cuda:0" if torch.cuda.is_available() else "cpu"
1052
+ # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
1053
+ # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
1054
+ # processor = AutoProcessor.from_pretrained(model_id)
1055
+
1056
+ # 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)
1057
+
1058
+ # base_audio_drive = "/data/audio"
1059
+
1060
+ # def transcribe_function(stream, new_chunk):
1061
+ # try:
1062
+ # sr, y = new_chunk[0], new_chunk[1]
1063
+ # except TypeError:
1064
+ # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
1065
+ # return stream, "", None
1066
+
1067
+ # y = y.astype(np.float32) / np.max(np.abs(y))
1068
+
1069
+ # if stream is not None:
1070
+ # stream = np.concatenate([stream, y])
1071
+ # else:
1072
+ # stream = y
1073
+
1074
+ # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
1075
+
1076
+ # full_text = result.get("text", "")
1077
+
1078
+ # return stream, full_text, result
1079
+
1080
+ # def update_map_with_response(history):
1081
+ # if not history:
1082
+ # return ""
1083
+ # response = history[-1][1]
1084
+ # addresses = extract_addresses(response)
1085
+ # return generate_map(addresses)
1086
+
1087
+ # def clear_textbox():
1088
+ # return ""
1089
+
1090
+ # def show_map_if_details(history,choice):
1091
+ # if choice in ["Details", "Conversational"]:
1092
+ # return gr.update(visible=True), update_map_with_response(history)
1093
+ # else:
1094
+ # return gr.update(visible=False), ""
1095
+
1096
+ # def generate_audio_elevenlabs(text):
1097
+ # XI_API_KEY = os.environ['ELEVENLABS_API']
1098
+ # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
1099
+ # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
1100
+ # headers = {
1101
+ # "Accept": "application/json",
1102
+ # "xi-api-key": XI_API_KEY
1103
+ # }
1104
+ # data = {
1105
+ # "text": str(text),
1106
+ # "model_id": "eleven_multilingual_v2",
1107
+ # "voice_settings": {
1108
+ # "stability": 1.0,
1109
+ # "similarity_boost": 0.0,
1110
+ # "style": 0.60,
1111
+ # "use_speaker_boost": False
1112
+ # }
1113
+ # }
1114
+ # response = requests.post(tts_url, headers=headers, json=data, stream=True)
1115
+ # if response.ok:
1116
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
1117
+ # for chunk in response.iter_content(chunk_size=1024):
1118
+ # f.write(chunk)
1119
+ # temp_audio_path = f.name
1120
+ # logging.debug(f"Audio saved to {temp_audio_path}")
1121
+ # return temp_audio_path
1122
+ # else:
1123
+ # logging.error(f"Error generating audio: {response.text}")
1124
+ # return None
1125
+
1126
+ # repo_id = "parler-tts/parler-tts-mini-expresso"
1127
+
1128
+ # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
1129
+ # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
1130
+ # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
1131
+
1132
+ # SAMPLE_RATE = parler_feature_extractor.sampling_rate
1133
+ # SEED = 42
1134
+
1135
+ # def preprocess(text):
1136
+ # number_normalizer = EnglishNumberNormalizer()
1137
+ # text = number_normalizer(text).strip()
1138
+ # if text[-1] not in punctuation:
1139
+ # text = f"{text}."
1140
+
1141
+ # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
1142
+
1143
+ # def separate_abb(chunk):
1144
+ # chunk = chunk.replace(".", "")
1145
+ # return " ".join(chunk)
1146
+
1147
+ # abbreviations = re.findall(abbreviations_pattern, text)
1148
+ # for abv in abbreviations:
1149
+ # if abv in text:
1150
+ # text = text.replace(abv, separate_abb(abv))
1151
+ # return text
1152
+
1153
+ # def chunk_text(text, max_length=250):
1154
+ # words = text.split()
1155
+ # chunks = []
1156
+ # current_chunk = []
1157
+ # current_length = 0
1158
+
1159
+ # for word in words:
1160
+ # if current_length + len(word) + 1 <= max_length:
1161
+ # current_chunk.append(word)
1162
+ # current_length += len(word) + 1
1163
+ # else:
1164
+ # chunks.append(' '.join(current_chunk))
1165
+ # current_chunk = [word]
1166
+ # current_length = len(word) + 1
1167
+
1168
+ # if current_chunk:
1169
+ # chunks.append(' '.join(current_chunk))
1170
+
1171
+ # return chunks
1172
+
1173
+ # def generate_audio_parler_tts(text):
1174
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
1175
+ # chunks = chunk_text(preprocess(text))
1176
+ # audio_segments = []
1177
+
1178
+ # for chunk in chunks:
1179
+ # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
1180
+ # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
1181
+
1182
+ # set_seed(SEED)
1183
+ # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
1184
+ # audio_arr = generation.cpu().numpy().squeeze()
1185
+
1186
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
1187
+ # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
1188
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
1189
+
1190
+ # combined_audio = sum(audio_segments)
1191
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
1192
+ # combined_audio.export(combined_audio_path, format="wav")
1193
+
1194
+ # logging.debug(f"Audio saved to {combined_audio_path}")
1195
+ # return combined_audio_path
1196
+
1197
+ # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
1198
+ # pipe.to(device)
1199
+
1200
+ # def generate_image(prompt):
1201
+ # with torch.cuda.amp.autocast():
1202
+ # image = pipe(
1203
+ # prompt,
1204
+ # num_inference_steps=28,
1205
+ # guidance_scale=3.0,
1206
+ # ).images[0]
1207
+ # return image
1208
+
1209
+ # 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"
1210
+ # 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."
1211
+ # 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."
1212
+
1213
+ # def update_images():
1214
+ # image_1 = generate_image(hardcoded_prompt_1)
1215
+ # image_2 = generate_image(hardcoded_prompt_2)
1216
+ # image_3 = generate_image(hardcoded_prompt_3)
1217
+ # return image_1, image_2, image_3
1218
+
1219
+ # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1220
+ # with gr.Row():
1221
+ # with gr.Column():
1222
+ # state = gr.State()
1223
+
1224
+ # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
1225
+ # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
1226
+
1227
+ # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
1228
+ # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!")
1229
+ # chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])
1230
+ # tts_choice = gr.Radio(label="Select TTS System", choices=["Eleven Labs", "Parler-TTS"], value="Eleven Labs")
1231
+ # bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot, gr.Audio(interactive=False, autoplay=True)])
1232
+ # bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
1233
+ # chatbot.like(print_like_dislike, None, None)
1234
+ # clear_button = gr.Button("Clear")
1235
+ # clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
1236
+
1237
+ # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy')
1238
+ # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="SAMLOne_real_time")
1239
+
1240
+ # with gr.Column():
1241
+ # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
1242
+ # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
1243
+ # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
1244
+
1245
+ # refresh_button = gr.Button("Refresh Images")
1246
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
1247
+
1248
+ # demo.queue()
1249
+ # demo.launch(share=True)
1250
+
1251
+