Pijush2023 commited on
Commit
623472f
·
verified ·
1 Parent(s): fb210e5

Update app.py

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