Pijush2023 commited on
Commit
f27ce50
·
verified ·
1 Parent(s): 06736fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +699 -11
app.py CHANGED
@@ -1419,6 +1419,695 @@
1419
  # demo.launch(share=True)
1420
 
1421
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1422
  import gradio as gr
1423
  import requests
1424
  import os
@@ -1488,7 +2177,7 @@ def fetch_local_events():
1488
  api_key = os.environ['SERP_API']
1489
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
1490
  response = requests.get(url)
1491
- if response.status_code == 200:
1492
  events_results = response.json().get("events_results", [])
1493
  events_html = """
1494
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
@@ -1770,7 +2459,7 @@ def fetch_local_news():
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>
@@ -1944,6 +2633,7 @@ def preprocess(text):
1944
  abbreviations = re.findall(abbreviations_pattern, text)
1945
  for abv in abbreviations:
1946
  if abv in text:
 
1947
  text = text.replace(abv, separate_abb(abv))
1948
  return text
1949
 
@@ -2054,9 +2744,9 @@ def clear_state_and_textbox():
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():
@@ -2088,12 +2778,11 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
2088
  clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
2089
 
2090
  # Recorder section
2091
-
2092
- gr.Markdown("<h2>Hey Radar</h2>")
2093
- audio_input = gr.Audio(sources=["microphone"], type='numpy')
2094
- transcribe_button = gr.Button("Transcribe")
2095
- # transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input, chat_input], outputs=[transcribe_output, chat_input])
2096
- transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input], outputs=[chat_input])
2097
 
2098
  with gr.Column():
2099
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
@@ -2110,4 +2799,3 @@ demo.launch(share=True)
2110
 
2111
 
2112
 
2113
-
 
1419
  # demo.launch(share=True)
1420
 
1421
 
1422
+ # import gradio as gr
1423
+ # import requests
1424
+ # import os
1425
+ # import time
1426
+ # import re
1427
+ # import logging
1428
+ # import tempfile
1429
+ # import folium
1430
+ # import concurrent.futures
1431
+ # import torch
1432
+ # from PIL import Image
1433
+ # from datetime import datetime
1434
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
1435
+ # from googlemaps import Client as GoogleMapsClient
1436
+ # from gtts import gTTS
1437
+ # from diffusers import StableDiffusionPipeline
1438
+ # from langchain_openai import OpenAIEmbeddings, ChatOpenAI
1439
+ # from langchain_pinecone import PineconeVectorStore
1440
+ # from langchain.prompts import PromptTemplate
1441
+ # from langchain.chains import RetrievalQA
1442
+ # from langchain.chains.conversation.memory import ConversationBufferWindowMemory
1443
+ # from langchain.agents import Tool, initialize_agent
1444
+ # from huggingface_hub import login
1445
+ # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
1446
+ # from parler_tts import ParlerTTSForConditionalGeneration
1447
+ # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
1448
+ # from scipy.io.wavfile import write as write_wav
1449
+ # from pydub import AudioSegment
1450
+ # from string import punctuation
1451
+ # import librosa
1452
+ # from pathlib import Path
1453
+ # import torchaudio
1454
+
1455
+ # # Check if the token is already set in the environment variables
1456
+ # hf_token = os.getenv("HF_TOKEN")
1457
+ # if hf_token is None:
1458
+ # print("Please set your Hugging Face token in the environment variables.")
1459
+ # else:
1460
+ # login(token=hf_token)
1461
+
1462
+ # logging.basicConfig(level=logging.DEBUG)
1463
+
1464
+ # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
1465
+
1466
+ # from pinecone import Pinecone
1467
+ # pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
1468
+
1469
+ # index_name = "birminghumsummary1"
1470
+ # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
1471
+ # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
1472
+
1473
+ # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
1474
+
1475
+ # conversational_memory = ConversationBufferWindowMemory(
1476
+ # memory_key='chat_history',
1477
+ # k=10,
1478
+ # return_messages=True
1479
+ # )
1480
+
1481
+ # def get_current_time_and_date():
1482
+ # now = datetime.now()
1483
+ # return now.strftime("%Y-%m-%d %H:%M:%S")
1484
+
1485
+ # current_time_and_date = get_current_time_and_date()
1486
+
1487
+ # def fetch_local_events():
1488
+ # api_key = os.environ['SERP_API']
1489
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
1490
+ # response = requests.get(url)
1491
+ # if response.status_code == 200:
1492
+ # events_results = response.json().get("events_results", [])
1493
+ # events_html = """
1494
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
1495
+ # <style>
1496
+ # table {
1497
+ # font-family: 'Verdana', sans-serif;
1498
+ # color: #333;
1499
+ # border-collapse: collapse;
1500
+ # width: 100%;
1501
+ # }
1502
+ # th, td {
1503
+ # border: 1px solid #fff !important;
1504
+ # padding: 8px;
1505
+ # }
1506
+ # th {
1507
+ # background-color: #f2f2f2;
1508
+ # color: #333;
1509
+ # text-align: left;
1510
+ # }
1511
+ # tr:hover {
1512
+ # background-color: #f5f5f5;
1513
+ # }
1514
+ # .event-link {
1515
+ # color: #1E90FF;
1516
+ # text-decoration: none;
1517
+ # }
1518
+ # .event-link:hover {
1519
+ # text-decoration: underline;
1520
+ # }
1521
+ # </style>
1522
+ # <table>
1523
+ # <tr>
1524
+ # <th>Title</th>
1525
+ # <th>Date and Time</th>
1526
+ # <th>Location</th>
1527
+ # </tr>
1528
+ # """
1529
+ # for event in events_results:
1530
+ # title = event.get("title", "No title")
1531
+ # date_info = event.get("date", {})
1532
+ # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
1533
+ # location = event.get("address", "No location")
1534
+ # if isinstance(location, list):
1535
+ # location = " ".join(location)
1536
+ # location = location.replace("[", "").replace("]", "")
1537
+ # link = event.get("link", "#")
1538
+ # events_html += f"""
1539
+ # <tr>
1540
+ # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
1541
+ # <td>{date}</td>
1542
+ # <td>{location}</td>
1543
+ # </tr>
1544
+ # """
1545
+ # events_html += "</table>"
1546
+ # return events_html
1547
+ # else:
1548
+ # return "<p>Failed to fetch local events</p>"
1549
+
1550
+ # def fetch_local_weather():
1551
+ # try:
1552
+ # api_key = os.environ['WEATHER_API']
1553
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
1554
+ # response = requests.get(url)
1555
+ # response.raise_for_status()
1556
+ # jsonData = response.json()
1557
+
1558
+ # current_conditions = jsonData.get("currentConditions", {})
1559
+ # temp_celsius = current_conditions.get("temp", "N/A")
1560
+
1561
+ # if temp_celsius != "N/A":
1562
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
1563
+ # else:
1564
+ # temp_fahrenheit = "N/A"
1565
+
1566
+ # condition = current_conditions.get("conditions", "N/A")
1567
+ # humidity = current_conditions.get("humidity", "N/A")
1568
+
1569
+ # weather_html = f"""
1570
+ # <div class="weather-theme">
1571
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
1572
+ # <div class="weather-content">
1573
+ # <div class="weather-icon">
1574
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
1575
+ # </div>
1576
+ # <div class="weather-details">
1577
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
1578
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
1579
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
1580
+ # </div>
1581
+ # </div>
1582
+ # </div>
1583
+ # <style>
1584
+ # .weather-theme {{
1585
+ # animation: backgroundAnimation 10s infinite alternate;
1586
+ # border-radius: 10px;
1587
+ # padding: 10px;
1588
+ # margin-bottom: 15px;
1589
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
1590
+ # background-size: 400% 400%;
1591
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
1592
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
1593
+ # }}
1594
+ # .weather-theme:hover {{
1595
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
1596
+ # background-position: 100% 100%;
1597
+ # }}
1598
+ # @keyframes backgroundAnimation {{
1599
+ # 0% {{ background-position: 0% 50%; }}
1600
+ # 100% {{ background-position: 100% 50%; }}
1601
+ # }}
1602
+ # .weather-content {{
1603
+ # display: flex;
1604
+ # align-items: center;
1605
+ # }}
1606
+ # .weather-icon {{
1607
+ # flex: 1;
1608
+ # }}
1609
+ # .weather-details {{
1610
+ # flex: 3;
1611
+ # }}
1612
+ # </style>
1613
+ # """
1614
+ # return weather_html
1615
+ # except requests.exceptions.RequestException as e:
1616
+ # return f"<p>Failed to fetch local weather: {e}</p>"
1617
+
1618
+ # def get_weather_icon(condition):
1619
+ # condition_map = {
1620
+ # "Clear": "c01d",
1621
+ # "Partly Cloudy": "c02d",
1622
+ # "Cloudy": "c03d",
1623
+ # "Overcast": "c04d",
1624
+ # "Mist": "a01d",
1625
+ # "Patchy rain possible": "r01d",
1626
+ # "Light rain": "r02d",
1627
+ # "Moderate rain": "r03d",
1628
+ # "Heavy rain": "r04d",
1629
+ # "Snow": "s01d",
1630
+ # "Thunderstorm": "t01d",
1631
+ # "Fog": "a05d",
1632
+ # }
1633
+ # return condition_map.get(condition, "c04d")
1634
+
1635
+ # 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,
1636
+ # 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.
1637
+ # Use fifteen sentences maximum. Keep the answer as detailed as possible. Always include the address, time, date, and
1638
+ # 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.
1639
+ # {context}
1640
+ # Question: {question}
1641
+ # Helpful Answer:"""
1642
+
1643
+ # 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,
1644
+ # 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.
1645
+ # Keep the answer short ,sweet and crisp and in one shot. Always say "It was my pleasure!" at the end of the answer.
1646
+ # {context}
1647
+ # Question: {question}
1648
+ # Helpful Answer:"""
1649
+
1650
+ # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
1651
+ # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
1652
+
1653
+ # def build_qa_chain(prompt_template):
1654
+ # qa_chain = RetrievalQA.from_chain_type(
1655
+ # llm=chat_model,
1656
+ # chain_type="stuff",
1657
+ # retriever=retriever,
1658
+ # chain_type_kwargs={"prompt": prompt_template}
1659
+ # )
1660
+ # tools = [
1661
+ # Tool(
1662
+ # name='Knowledge Base',
1663
+ # func=qa_chain,
1664
+ # description='Use this tool when answering general knowledge queries to get more information about the topic'
1665
+ # )
1666
+ # ]
1667
+ # return qa_chain, tools
1668
+
1669
+ # def initialize_agent_with_prompt(prompt_template):
1670
+ # qa_chain, tools = build_qa_chain(prompt_template)
1671
+ # agent = initialize_agent(
1672
+ # agent='chat-conversational-react-description',
1673
+ # tools=tools,
1674
+ # llm=chat_model,
1675
+ # verbose=False,
1676
+ # max_iteration=5,
1677
+ # early_stopping_method='generate',
1678
+ # memory=conversational_memory
1679
+ # )
1680
+ # return agent
1681
+
1682
+ # def generate_answer(message, choice):
1683
+ # logging.debug(f"generate_answer called with prompt_choice: {choice}")
1684
+
1685
+ # if choice == "Details":
1686
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_1)
1687
+ # elif choice == "Conversational":
1688
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
1689
+ # else:
1690
+ # logging.error(f"Invalid prompt_choice: {choice}. Defaulting to 'Conversational'")
1691
+ # agent = initialize_agent_with_prompt(QA_CHAIN_PROMPT_2)
1692
+ # response = agent(message)
1693
+
1694
+ # addresses = extract_addresses(response['output'])
1695
+ # return response['output'], addresses
1696
+
1697
+ # def bot(history, choice, tts_choice, state):
1698
+ # if not history:
1699
+ # return history
1700
+ # response, addresses = generate_answer(history[-1][0], choice)
1701
+ # history[-1][1] = ""
1702
+
1703
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
1704
+ # if tts_choice == "Alpha":
1705
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
1706
+ # elif tts_choice == "Beta":
1707
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
1708
+ # elif tts_choice == "Gamma":
1709
+ # audio_future = executor.submit(generate_audio_mars5, response)
1710
+
1711
+ # for character in response:
1712
+ # history[-1][1] += character
1713
+ # time.sleep(0.05)
1714
+ # yield history, None
1715
+
1716
+ # audio_path = audio_future.result()
1717
+ # yield history, audio_path
1718
+
1719
+ # def add_message(history, message):
1720
+ # history.append((message, None))
1721
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
1722
+
1723
+ # def print_like_dislike(x: gr.LikeData):
1724
+ # print(x.index, x.value, x.liked)
1725
+
1726
+ # def extract_addresses(response):
1727
+ # if not isinstance(response, str):
1728
+ # response = str(response)
1729
+ # address_patterns = [
1730
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
1731
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
1732
+ # r'([A-Z].*,\sAL\s\d{5})',
1733
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
1734
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
1735
+ # r'(\d{2}.*\sStreets)',
1736
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
1737
+ # r'([a-zA-Z]\s Birmingham)',
1738
+ # r'([a-zA-Z].*,\sBirmingham,\sAL)',
1739
+ # r'(^Birmingham,AL$)'
1740
+ # ]
1741
+ # addresses = []
1742
+ # for pattern in address_patterns:
1743
+ # addresses.extend(re.findall(pattern, response))
1744
+ # return addresses
1745
+
1746
+ # all_addresses = []
1747
+
1748
+ # def generate_map(location_names):
1749
+ # global all_addresses
1750
+ # all_addresses.extend(location_names)
1751
+
1752
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
1753
+ # gmaps = GoogleMapsClient(key=api_key)
1754
+
1755
+ # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
1756
+
1757
+ # for location_name in all_addresses:
1758
+ # geocode_result = gmaps.geocode(location_name)
1759
+ # if geocode_result:
1760
+ # location = geocode_result[0]['geometry']['location']
1761
+ # folium.Marker(
1762
+ # [location['lat'], location['lng']],
1763
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
1764
+ # ).add_to(m)
1765
+
1766
+ # map_html = m._repr_html_()
1767
+ # return map_html
1768
+
1769
+ # def fetch_local_news():
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>
1777
+ # <style>
1778
+ # .news-item {
1779
+ # font-family: 'Verdana', sans-serif;
1780
+ # color: #333;
1781
+ # background-color: #f0f8ff;
1782
+ # margin-bottom: 15px;
1783
+ # padding: 10px;
1784
+ # border-radius: 5px;
1785
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
1786
+ # font-weight: bold;
1787
+ # }
1788
+ # .news-item:hover {
1789
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
1790
+ # background-color: #e6f7ff;
1791
+ # }
1792
+ # .news-item a {
1793
+ # color: #1E90FF;
1794
+ # text-decoration: none;
1795
+ # font-weight: bold;
1796
+ # }
1797
+ # .news-item a:hover {
1798
+ # text-decoration: underline;
1799
+ # }
1800
+ # .news-preview {
1801
+ # position: absolute;
1802
+ # display: none;
1803
+ # border: 1px solid #ccc;
1804
+ # border-radius: 5px;
1805
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
1806
+ # background-color: white;
1807
+ # z-index: 1000;
1808
+ # max-width: 300px;
1809
+ # padding: 10px;
1810
+ # font-family: 'Verdana', sans-serif;
1811
+ # color: #333;
1812
+ # }
1813
+ # </style>
1814
+ # <script>
1815
+ # function showPreview(event, previewContent) {
1816
+ # var previewBox = document.getElementById('news-preview');
1817
+ # previewBox.innerHTML = previewContent;
1818
+ # previewBox.style.left = event.pageX + 'px';
1819
+ # previewBox.style.top = event.pageY + 'px';
1820
+ # previewBox.style.display = 'block';
1821
+ # }
1822
+ # function hidePreview() {
1823
+ # var previewBox = document.getElementById('news-preview');
1824
+ # previewBox.style.display = 'none';
1825
+ # }
1826
+ # </script>
1827
+ # <div id="news-preview" class="news-preview"></div>
1828
+ # """
1829
+ # for index, result in enumerate(results[:7]):
1830
+ # title = result.get("title", "No title")
1831
+ # link = result.get("link", "#")
1832
+ # snippet = result.get("snippet", "")
1833
+ # news_html += f"""
1834
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
1835
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
1836
+ # <p>{snippet}</p>
1837
+ # </div>
1838
+ # """
1839
+ # return news_html
1840
+ # else:
1841
+ # return "<p>Failed to fetch local news</p>"
1842
+
1843
+ # import numpy as np
1844
+ # import torch
1845
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
1846
+
1847
+ # model_id = 'openai/whisper-large-v3'
1848
+ # device = "cuda:0" if torch.cuda.is_available() else "cpu"
1849
+ # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
1850
+ # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
1851
+ # processor = AutoProcessor.from_pretrained(model_id)
1852
+
1853
+ # 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)
1854
+
1855
+ # base_audio_drive = "/data/audio"
1856
+
1857
+ # # Integrate the transcriber function
1858
+ # transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")
1859
+
1860
+ # def transcribe(audio):
1861
+ # sr, y = audio
1862
+ # y = y.astype(np.float32)
1863
+ # y /= np.max(np.abs(y))
1864
+ # return transcriber({"sampling_rate": sr, "raw": y})["text"] # type: ignore
1865
+
1866
+ # def transcribe_function(stream, new_chunk):
1867
+ # sr, y = new_chunk[0], new_chunk[1]
1868
+ # y = y.astype(np.float32) / np.max(np.abs(y))
1869
+ # if stream is not None:
1870
+ # stream = np.concatenate([stream, y])
1871
+ # else:
1872
+ # stream = y
1873
+ # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
1874
+ # full_text = result.get("text", "")
1875
+ # return stream, full_text # Return the transcribed text
1876
+
1877
+ # def update_map_with_response(history):
1878
+ # if not history:
1879
+ # return ""
1880
+ # response = history[-1][1]
1881
+ # addresses = extract_addresses(response)
1882
+ # return generate_map(addresses)
1883
+
1884
+ # def clear_textbox():
1885
+ # return ""
1886
+
1887
+ # def show_map_if_details(history, choice):
1888
+ # if choice in ["Details", "Conversational"]:
1889
+ # return gr.update(visible=True), update_map_with_response(history)
1890
+ # else:
1891
+ # return gr.update(visible=False), ""
1892
+
1893
+ # def generate_audio_elevenlabs(text):
1894
+ # XI_API_KEY = os.environ['ELEVENLABS_API']
1895
+ # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
1896
+ # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
1897
+ # headers = {
1898
+ # "Accept": "application/json",
1899
+ # "xi-api-key": XI_API_KEY
1900
+ # }
1901
+ # data = {
1902
+ # "text": str(text),
1903
+ # "model_id": "eleven_multilingual_v2",
1904
+ # "voice_settings": {
1905
+ # "stability": 1.0,
1906
+ # "similarity_boost": 0.0,
1907
+ # "style": 0.60,
1908
+ # "use_speaker_boost": False
1909
+ # }
1910
+ # }
1911
+ # response = requests.post(tts_url, headers=headers, json=data, stream=True)
1912
+ # if response.ok:
1913
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
1914
+ # for chunk in response.iter_content(chunk_size=1024):
1915
+ # f.write(chunk)
1916
+ # temp_audio_path = f.name
1917
+ # logging.debug(f"Audio saved to {temp_audio_path}")
1918
+ # return temp_audio_path
1919
+ # else:
1920
+ # logging.error(f"Error generating audio: {response.text}")
1921
+ # return None
1922
+
1923
+ # repo_id = "parler-tts/parler-tts-mini-expresso"
1924
+
1925
+ # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
1926
+ # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
1927
+ # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
1928
+
1929
+ # SAMPLE_RATE = parler_feature_extractor.sampling_rate
1930
+ # SEED = 42
1931
+
1932
+ # def preprocess(text):
1933
+ # number_normalizer = EnglishNumberNormalizer()
1934
+ # text = number_normalizer(text).strip()
1935
+ # if text[-1] not in punctuation:
1936
+ # text = f"{text}."
1937
+
1938
+ # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
1939
+
1940
+ # def separate_abb(chunk):
1941
+ # chunk = chunk.replace(".", "")
1942
+ # return " ".join(chunk)
1943
+
1944
+ # abbreviations = re.findall(abbreviations_pattern, text)
1945
+ # for abv in abbreviations:
1946
+ # if abv in text:
1947
+ # text = text.replace(abv, separate_abb(abv))
1948
+ # return text
1949
+
1950
+ # def chunk_text(text, max_length=250):
1951
+ # words = text.split()
1952
+ # chunks = []
1953
+ # current_chunk = []
1954
+ # current_length = 0
1955
+
1956
+ # for word in words:
1957
+ # if current_length + len(word) + 1 <= max_length:
1958
+ # current_chunk.append(word)
1959
+ # current_length += len(word) + 1
1960
+ # else:
1961
+ # chunks.append(' '.join(current_chunk))
1962
+ # current_chunk = [word]
1963
+ # current_length = len(word) + 1
1964
+
1965
+ # if current_chunk:
1966
+ # chunks.append(' '.join(current_chunk))
1967
+
1968
+ # return chunks
1969
+
1970
+ # def generate_audio_parler_tts(text):
1971
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
1972
+ # chunks = chunk_text(preprocess(text))
1973
+ # audio_segments = []
1974
+
1975
+ # for chunk in chunks:
1976
+ # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
1977
+ # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
1978
+
1979
+ # set_seed(SEED)
1980
+ # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
1981
+ # audio_arr = generation.cpu().numpy().squeeze()
1982
+
1983
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
1984
+ # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
1985
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
1986
+
1987
+ # combined_audio = sum(audio_segments)
1988
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
1989
+ # combined_audio.export(combined_audio_path, format="wav")
1990
+
1991
+ # logging.debug(f"Audio saved to {combined_audio_path}")
1992
+ # return combined_audio_path
1993
+
1994
+ # # Load the MARS5 model
1995
+ # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
1996
+
1997
+ # def generate_audio_mars5(text):
1998
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
1999
+ # kwargs_dict = {
2000
+ # 'temperature': 0.2,
2001
+ # 'top_k': -1,
2002
+ # 'top_p': 0.2,
2003
+ # 'typical_p': 1.0,
2004
+ # 'freq_penalty': 2.6,
2005
+ # 'presence_penalty': 0.4,
2006
+ # 'rep_penalty_window': 100,
2007
+ # 'max_prompt_phones': 360,
2008
+ # 'deep_clone': True,
2009
+ # 'nar_guidance_w': 3
2010
+ # }
2011
+
2012
+ # chunks = chunk_text(preprocess(text))
2013
+ # audio_segments = []
2014
+
2015
+ # for chunk in chunks:
2016
+ # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
2017
+ # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
2018
+ # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
2019
+
2020
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
2021
+ # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
2022
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
2023
+
2024
+ # combined_audio = sum(audio_segments)
2025
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
2026
+ # combined_audio.export(combined_audio_path, format="wav")
2027
+
2028
+ # logging.debug(f"Audio saved to {combined_audio_path}")
2029
+ # return combined_audio_path
2030
+
2031
+ # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
2032
+ # pipe.to(device)
2033
+
2034
+ # def generate_image(prompt):
2035
+ # with torch.cuda.amp.autocast():
2036
+ # image = pipe(
2037
+ # prompt,
2038
+ # num_inference_steps=28,
2039
+ # guidance_scale=3.0,
2040
+ # ).images[0]
2041
+ # return image
2042
+
2043
+ # 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"
2044
+ # 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."
2045
+ # 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."
2046
+
2047
+ # def update_images():
2048
+ # image_1 = generate_image(hardcoded_prompt_1)
2049
+ # image_2 = generate_image(hardcoded_prompt_2)
2050
+ # image_3 = generate_image(hardcoded_prompt_3)
2051
+ # return image_1, image_2, image_3
2052
+
2053
+ # def clear_state_and_textbox():
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():
2064
+ # state = gr.State()
2065
+
2066
+ # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
2067
+ # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
2068
+
2069
+ # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
2070
+
2071
+ # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!", placeholder="After Prompt, click Retriever Only")
2072
+ # chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input], api_name="voice_query")
2073
+ # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
2074
+ # retriever_button = gr.Button("Retriever")
2075
+
2076
+ # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
2077
+ # location_output = gr.HTML()
2078
+ # retriever_button.click(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input]).then(
2079
+ # fn=bot, inputs=[chatbot, choice, tts_choice, state], outputs=[chatbot, gr.Audio(interactive=False, autoplay=True)], api_name="Ask_Retriever").then(
2080
+ # fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder").then(
2081
+ # fn=clear_state_and_textbox, inputs=[], outputs=[chat_input]
2082
+ # )
2083
+
2084
+ # bot_msg = chat_msg.then(bot, [chatbot, choice, tts_choice], [chatbot], api_name="generate_voice_response")
2085
+ # bot_msg.then(lambda: gr.Textbox(value="", interactive=True, placeholder="Ask Radar!!!...", show_label=False), None, [chat_input])
2086
+ # chatbot.like(print_like_dislike, None, None)
2087
+ # clear_button = gr.Button("Clear")
2088
+ # clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
2089
+
2090
+ # # Recorder section
2091
+
2092
+ # gr.Markdown("<h2>Hey Radar</h2>")
2093
+ # audio_input = gr.Audio(sources=["microphone"], type='numpy')
2094
+ # transcribe_button = gr.Button("Transcribe")
2095
+ # # transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input, chat_input], outputs=[transcribe_output, chat_input])
2096
+ # transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input], outputs=[chat_input])
2097
+
2098
+ # with gr.Column():
2099
+ # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
2100
+ # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
2101
+ # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
2102
+
2103
+ # refresh_button = gr.Button("Refresh Images")
2104
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3])
2105
+ # location_output = gr.HTML()
2106
+ # bot_msg.then(show_map_if_details, [chatbot, choice], [location_output, location_output], api_name="map_finder")
2107
+
2108
+ # demo.queue()
2109
+ # demo.launch(share=True)
2110
+
2111
  import gradio as gr
2112
  import requests
2113
  import os
 
2177
  api_key = os.environ['SERP_API']
2178
  url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
2179
  response = requests.get(url)
2180
+ if response.status_code == 200):
2181
  events_results = response.json().get("events_results", [])
2182
  events_html = """
2183
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
 
2459
  api_key = os.environ['SERP_API']
2460
  url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
2461
  response = requests.get(url)
2462
+ if response.status_code == 200):
2463
  results = response.json().get("news_results", [])
2464
  news_html = """
2465
  <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
 
2633
  abbreviations = re.findall(abbreviations_pattern, text)
2634
  for abv in abbreviations:
2635
  if abv in text:
2636
+ text is now processed using updated Whisper Model
2637
  text = text.replace(abv, separate_abb(abv))
2638
  return text
2639
 
 
2744
  conversational_memory.clear()
2745
  return "", ""
2746
 
2747
+ def transcribe_and_update_textbox(audio):
2748
  transcribed_text = transcribe(audio)
2749
+ return "", transcribed_text
2750
 
2751
  with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
2752
  with gr.Row():
 
2778
  clear_button.click(fn=clear_textbox, inputs=None, outputs=chat_input)
2779
 
2780
  # Recorder section
2781
+ with gr.Group():
2782
+ gr.Markdown("<h2>Audio Recorder</h2>")
2783
+ audio_input = gr.Audio(sources=["microphone"], type='numpy')
2784
+ transcribe_button = gr.Button("Transcribe")
2785
+ transcribe_button.click(fn=transcribe_and_update_textbox, inputs=[audio_input], outputs=[chat_input, chat_input])
 
2786
 
2787
  with gr.Column():
2788
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
 
2799
 
2800
 
2801