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

Update app.py

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