Pijush2023 commited on
Commit
f6bd90f
·
verified ·
1 Parent(s): bf4a7ab

Update app.py

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