Pijush2023 commited on
Commit
2a8c075
·
verified ·
1 Parent(s): 2089238

Update app.py

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