Pijush2023 commited on
Commit
9b5f7bf
·
verified ·
1 Parent(s): db143b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +850 -6
app.py CHANGED
@@ -1,3 +1,848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
@@ -54,9 +899,12 @@ else:
54
  logging.basicConfig(level=logging.DEBUG)
55
 
56
  embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
 
57
  from pinecone import Pinecone
58
  pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
59
 
 
 
60
  index_name = "radardata07242024"
61
  vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
62
  retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
@@ -219,7 +1067,6 @@ _search_query = RunnableBranch(
219
 
220
  template = """Answer the question based only on the following context:
221
  {context}
222
-
223
  Question: {question}
224
  Use natural language and be concise.
225
  Answer:"""
@@ -826,11 +1673,6 @@ with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
826
  audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
827
  audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
828
 
829
- # with gr.Column():
830
- # weather_output = gr.HTML(value=fetch_local_weather())
831
- # news_output = gr.HTML(value=fetch_local_news())
832
- # events_output = gr.HTML(value=fetch_local_events())
833
-
834
  with gr.Column():
835
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
836
  image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
@@ -843,3 +1685,5 @@ demo.queue()
843
  demo.launch(share=True)
844
 
845
 
 
 
 
1
+ # import gradio as gr
2
+ # import requests
3
+ # import os
4
+ # import time
5
+ # import re
6
+ # import logging
7
+ # import tempfile
8
+ # import folium
9
+ # import concurrent.futures
10
+ # import torch
11
+ # from PIL import Image
12
+ # from datetime import datetime
13
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
14
+ # from googlemaps import Client as GoogleMapsClient
15
+ # from gtts import gTTS
16
+ # from diffusers import StableDiffusionPipeline
17
+ # from langchain_openai import OpenAIEmbeddings, ChatOpenAI
18
+ # from langchain_pinecone import PineconeVectorStore
19
+ # from langchain.prompts import PromptTemplate
20
+ # from langchain.chains import RetrievalQA
21
+ # from langchain.chains.conversation.memory import ConversationBufferWindowMemory
22
+ # from langchain.agents import Tool, initialize_agent
23
+ # from huggingface_hub import login
24
+ # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
25
+ # from parler_tts import ParlerTTSForConditionalGeneration
26
+ # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
27
+ # from scipy.io.wavfile import write as write_wav
28
+ # from pydub import AudioSegment
29
+ # from string import punctuation
30
+ # import librosa
31
+ # from pathlib import Path
32
+ # import torchaudio
33
+ # import numpy as np
34
+
35
+ # # Neo4j imports
36
+ # from langchain.chains import GraphCypherQAChain
37
+ # from langchain_community.graphs import Neo4jGraph
38
+ # from langchain_community.document_loaders import HuggingFaceDatasetLoader
39
+ # from langchain_text_splitters import CharacterTextSplitter
40
+ # from langchain_experimental.graph_transformers import LLMGraphTransformer
41
+ # from langchain_core.prompts import ChatPromptTemplate
42
+ # from langchain_core.pydantic_v1 import BaseModel, Field
43
+ # from langchain_core.messages import AIMessage, HumanMessage
44
+ # from langchain_core.output_parsers import StrOutputParser
45
+ # from langchain_core.runnables import RunnableBranch, RunnableLambda, RunnableParallel, RunnablePassthrough
46
+
47
+ # # Pinecone setup
48
+ # hf_token = os.getenv("HF_TOKEN")
49
+ # if hf_token is None:
50
+ # print("Please set your Hugging Face token in the environment variables.")
51
+ # else:
52
+ # login(token=hf_token)
53
+
54
+ # logging.basicConfig(level=logging.DEBUG)
55
+
56
+ # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
57
+ # from pinecone import Pinecone
58
+ # pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
59
+
60
+ # index_name = "radardata07242024"
61
+ # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
62
+ # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
63
+
64
+ # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
65
+
66
+ # conversational_memory = ConversationBufferWindowMemory(
67
+ # memory_key='chat_history',
68
+ # k=10,
69
+ # return_messages=True
70
+ # )
71
+
72
+ # # Prompt templates
73
+ # def get_current_date():
74
+ # return datetime.now().strftime("%B %d, %Y")
75
+
76
+ # current_date = get_current_date()
77
+
78
+ # template1 = f"""As an expert concierge in Birmingham, Alabama, known for being a helpful and renowned guide, I am here to assist you on this sunny bright day of {current_date}. Given the current weather conditions and date, I have access to a plethora of information regarding events, places, and activities in Birmingham that can enhance your experience.
79
+ # If you have any questions or need recommendations, feel free to ask. I have a wealth of knowledge of perennial events in Birmingham and can provide detailed information to ensure you make the most of your time here. Remember, I am here to assist you in any way possible.
80
+ # Now, let me guide you through some of the exciting events happening today in Birmingham, Alabama:
81
+ # Address: >>, Birmingham, AL
82
+ # Time: >>__
83
+ # Date: >>__
84
+ # Description: >>__
85
+ # Address: >>, Birmingham, AL
86
+ # Time: >>__
87
+ # Date: >>__
88
+ # Description: >>__
89
+ # Address: >>, Birmingham, AL
90
+ # Time: >>__
91
+ # Date: >>__
92
+ # Description: >>__
93
+ # Address: >>, Birmingham, AL
94
+ # Time: >>__
95
+ # Date: >>__
96
+ # Description: >>__
97
+ # Address: >>, Birmingham, AL
98
+ # Time: >>__
99
+ # Date: >>__
100
+ # Description: >>__
101
+ # If you have any specific preferences or questions about these events or any other inquiries, please feel free to ask. Remember, I am here to ensure you have a memorable and enjoyable experience in Birmingham, AL.
102
+ # It was my pleasure!
103
+ # {{context}}
104
+ # Question: {{question}}
105
+ # Helpful Answer:"""
106
+
107
+ # template2 = f"""As an expert concierge known for being helpful and a renowned guide for Birmingham, Alabama, I assist visitors in discovering the best that the city has to offer. Given today's sunny and bright weather on {current_date}, I am well-equipped to provide valuable insights and recommendations without revealing specific locations. I draw upon my extensive knowledge of the area, including perennial events and historical context.
108
+ # In light of this, how can I assist you today? Feel free to ask any questions or seek recommendations for your day in Birmingham. If there's anything specific you'd like to know or experience, please share, and I'll be glad to help. Remember, keep the question concise for a quick and accurate response.
109
+ # "It was my pleasure!"
110
+ # {{context}}
111
+ # Question: {{question}}
112
+ # Helpful Answer:"""
113
+
114
+ # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
115
+ # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
116
+
117
+ # # Neo4j setup
118
+ # graph = Neo4jGraph(
119
+ # url="neo4j+s://98f45cc0.databases.neo4j.io",
120
+ # username="neo4j",
121
+ # password="B_sZbapCTZoQDWj1JrhwqElsNa-jm5Zq1m_mAnyPYog"
122
+ # )
123
+
124
+ # # Avoid pushing the graph documents to Neo4j every time
125
+ # # Only push the documents once and comment the code below after the initial push
126
+ # # dataset_name = "Pijush2023/birmindata07312024"
127
+ # # page_content_column = 'events_description'
128
+ # # loader = HuggingFaceDatasetLoader(dataset_name, page_content_column)
129
+ # # data = loader.load()
130
+
131
+ # # text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=50)
132
+ # # documents = text_splitter.split_documents(data)
133
+
134
+ # # llm_transformer = LLMGraphTransformer(llm=chat_model)
135
+ # # graph_documents = llm_transformer.convert_to_graph_documents(documents)
136
+ # # graph.add_graph_documents(graph_documents, baseEntityLabel=True, include_source=True)
137
+
138
+ # class Entities(BaseModel):
139
+ # names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
140
+
141
+ # entity_prompt = ChatPromptTemplate.from_messages([
142
+ # ("system", "You are extracting organization and person entities from the text."),
143
+ # ("human", "Use the given format to extract information from the following input: {question}"),
144
+ # ])
145
+
146
+ # entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
147
+
148
+ # def remove_lucene_chars(input: str) -> str:
149
+ # return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
150
+ # "(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
151
+ # "^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
152
+ # ";": r"\;", " ": r"\ "}))
153
+
154
+ # def generate_full_text_query(input: str) -> str:
155
+ # full_text_query = ""
156
+ # words = [el for el in remove_lucene_chars(input).split() if el]
157
+ # for word in words[:-1]:
158
+ # full_text_query += f" {word}~2 AND"
159
+ # full_text_query += f" {words[-1]}~2"
160
+ # return full_text_query.strip()
161
+
162
+ # def structured_retriever(question: str) -> str:
163
+ # result = ""
164
+ # entities = entity_chain.invoke({"question": question})
165
+ # for entity in entities.names:
166
+ # response = graph.query(
167
+ # """CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
168
+ # YIELD node,score
169
+ # CALL {
170
+ # WITH node
171
+ # MATCH (node)-[r:!MENTIONS]->(neighbor)
172
+ # RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
173
+ # UNION ALL
174
+ # WITH node
175
+ # MATCH (node)<-[r:!MENTIONS]-(neighbor)
176
+ # RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
177
+ # }
178
+ # RETURN output LIMIT 50
179
+ # """,
180
+ # {"query": generate_full_text_query(entity)},
181
+ # )
182
+ # result += "\n".join([el['output'] for el in response])
183
+ # return result
184
+
185
+ # def retriever_neo4j(question: str):
186
+ # structured_data = structured_retriever(question)
187
+ # return structured_data
188
+
189
+ # _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
190
+ # in its original language.
191
+ # Chat History:
192
+ # {chat_history}
193
+ # Follow Up Input: {question}
194
+ # Standalone question:"""
195
+
196
+ # CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
197
+
198
+ # def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
199
+ # buffer = []
200
+ # for human, ai in chat_history:
201
+ # buffer.append(HumanMessage(content=human))
202
+ # buffer.append(AIMessage(content=ai))
203
+ # return buffer
204
+
205
+ # _search_query = RunnableBranch(
206
+ # (
207
+ # RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
208
+ # run_name="HasChatHistoryCheck"
209
+ # ),
210
+ # RunnablePassthrough.assign(
211
+ # chat_history=lambda x: _format_chat_history(x["chat_history"])
212
+ # )
213
+ # | CONDENSE_QUESTION_PROMPT
214
+ # | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
215
+ # | StrOutputParser(),
216
+ # ),
217
+ # RunnableLambda(lambda x : x["question"]),
218
+ # )
219
+
220
+ # template = """Answer the question based only on the following context:
221
+ # {context}
222
+
223
+ # Question: {question}
224
+ # Use natural language and be concise.
225
+ # Answer:"""
226
+
227
+ # qa_prompt = ChatPromptTemplate.from_template(template)
228
+
229
+ # chain_neo4j = (
230
+ # RunnableParallel(
231
+ # {
232
+ # "context": _search_query | retriever_neo4j,
233
+ # "question": RunnablePassthrough(),
234
+ # }
235
+ # )
236
+ # | qa_prompt
237
+ # | chat_model
238
+ # | StrOutputParser()
239
+ # )
240
+
241
+ # # Define a function to select between Pinecone and Neo4j
242
+ # def generate_answer(message, choice, retrieval_mode):
243
+ # logging.debug(f"generate_answer called with choice: {choice} and retrieval_mode: {retrieval_mode}")
244
+
245
+ # prompt_template = QA_CHAIN_PROMPT_1 if choice == "Details" else QA_CHAIN_PROMPT_2
246
+
247
+ # if retrieval_mode == "Vector":
248
+ # qa_chain = RetrievalQA.from_chain_type(
249
+ # llm=chat_model,
250
+ # chain_type="stuff",
251
+ # retriever=retriever,
252
+ # chain_type_kwargs={"prompt": prompt_template}
253
+ # )
254
+ # response = qa_chain({"query": message})
255
+ # return response['output'], extract_addresses(response['output'])
256
+ # elif retrieval_mode == "Knowledge-Graph":
257
+ # response = chain_neo4j.invoke({"question": message})
258
+ # return response, extract_addresses(response)
259
+ # else:
260
+ # return "Invalid retrieval mode selected.", []
261
+
262
+ # def bot(history, choice, tts_choice, retrieval_mode):
263
+ # if not history:
264
+ # return history
265
+
266
+ # response, addresses = generate_answer(history[-1][0], choice, retrieval_mode)
267
+ # history[-1][1] = ""
268
+
269
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
270
+ # if tts_choice == "Alpha":
271
+ # audio_future = executor.submit(generate_audio_elevenlabs, response)
272
+ # elif tts_choice == "Beta":
273
+ # audio_future = executor.submit(generate_audio_parler_tts, response)
274
+ # elif tts_choice == "Gamma":
275
+ # audio_future = executor.submit(generate_audio_mars5, response)
276
+
277
+ # for character in response:
278
+ # history[-1][1] += character
279
+ # time.sleep(0.05)
280
+ # yield history, None
281
+
282
+ # audio_path = audio_future.result()
283
+ # yield history, audio_path
284
+
285
+ # history.append([response, None]) # Ensure the response is added in the correct format
286
+
287
+ # def add_message(history, message):
288
+ # history.append((message, None))
289
+ # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
290
+
291
+ # def print_like_dislike(x: gr.LikeData):
292
+ # print(x.index, x.value, x.liked)
293
+
294
+ # def extract_addresses(response):
295
+ # if not isinstance(response, str):
296
+ # response = str(response)
297
+ # address_patterns = [
298
+ # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
299
+ # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
300
+ # r'([A-Z].*,\sAL\s\d{5})',
301
+ # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
302
+ # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
303
+ # r'(\d{2}.*\sStreets)',
304
+ # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
305
+ # r'([a-zA-Z]\s Birmingham)',
306
+ # r'([a-zA-Z].*,\sBirmingham,\sAL)',
307
+ # r'(^Birmingham,AL$)'
308
+ # ]
309
+ # addresses = []
310
+ # for pattern in address_patterns:
311
+ # addresses.extend(re.findall(pattern, response))
312
+ # return addresses
313
+
314
+ # all_addresses = []
315
+
316
+ # def generate_map(location_names):
317
+ # global all_addresses
318
+ # all_addresses.extend(location_names)
319
+
320
+ # api_key = os.environ['GOOGLEMAPS_API_KEY']
321
+ # gmaps = GoogleMapsClient(key=api_key)
322
+
323
+ # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
324
+
325
+ # for location_name in all_addresses:
326
+ # geocode_result = gmaps.geocode(location_name)
327
+ # if geocode_result:
328
+ # location = geocode_result[0]['geometry']['location']
329
+ # folium.Marker(
330
+ # [location['lat'], location['lng']],
331
+ # tooltip=f"{geocode_result[0]['formatted_address']}"
332
+ # ).add_to(m)
333
+
334
+ # map_html = m._repr_html_()
335
+ # return map_html
336
+
337
+ # def fetch_local_news():
338
+ # api_key = os.environ['SERP_API']
339
+ # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
340
+ # response = requests.get(url)
341
+ # if response.status_code == 200:
342
+ # results = response.json().get("news_results", [])
343
+ # news_html = """
344
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
345
+ # <style>
346
+ # .news-item {
347
+ # font-family: 'Verdana', sans-serif;
348
+ # color: #333;
349
+ # background-color: #f0f8ff;
350
+ # margin-bottom: 15px;
351
+ # padding: 10px;
352
+ # border-radius: 5px;
353
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
354
+ # font-weight: bold;
355
+ # }
356
+ # .news-item:hover {
357
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
358
+ # background-color: #e6f7ff;
359
+ # }
360
+ # .news-item a {
361
+ # color: #1E90FF;
362
+ # text-decoration: none;
363
+ # font-weight: bold;
364
+ # }
365
+ # .news-item a:hover {
366
+ # text-decoration: underline;
367
+ # }
368
+ # .news-preview {
369
+ # position: absolute;
370
+ # display: none;
371
+ # border: 1px solid #ccc;
372
+ # border-radius: 5px;
373
+ # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
374
+ # background-color: white;
375
+ # z-index: 1000;
376
+ # max-width: 300px;
377
+ # padding: 10px;
378
+ # font-family: 'Verdana', sans-serif;
379
+ # color: #333;
380
+ # }
381
+ # </style>
382
+ # <script>
383
+ # function showPreview(event, previewContent) {
384
+ # var previewBox = document.getElementById('news-preview');
385
+ # previewBox.innerHTML = previewContent;
386
+ # previewBox.style.left = event.pageX + 'px';
387
+ # previewBox.style.top = event.pageY + 'px';
388
+ # previewBox.style.display = 'block';
389
+ # }
390
+ # function hidePreview() {
391
+ # var previewBox = document.getElementById('news-preview');
392
+ # previewBox.style.display = 'none';
393
+ # }
394
+ # </script>
395
+ # <div id="news-preview" class="news-preview"></div>
396
+ # """
397
+ # for index, result in enumerate(results[:7]):
398
+ # title = result.get("title", "No title")
399
+ # link = result.get("link", "#")
400
+ # snippet = result.get("snippet", "")
401
+ # news_html += f"""
402
+ # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
403
+ # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
404
+ # <p>{snippet}</p>
405
+ # </div>
406
+ # """
407
+ # return news_html
408
+ # else:
409
+ # return "<p>Failed to fetch local news</p>"
410
+
411
+ # import numpy as np
412
+ # import torch
413
+ # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
414
+
415
+ # model_id = 'openai/whisper-large-v3'
416
+ # device = "cuda:0" if torch.cuda.is_available() else "cpu"
417
+ # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
418
+ # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
419
+ # processor = AutoProcessor.from_pretrained(model_id)
420
+
421
+ # 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)
422
+
423
+ # base_audio_drive = "/data/audio"
424
+
425
+ # def transcribe_function(stream, new_chunk):
426
+ # try:
427
+ # sr, y = new_chunk[0], new_chunk[1]
428
+ # except TypeError:
429
+ # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
430
+ # return stream, "", None
431
+
432
+ # y = y.astype(np.float32) / np.max(np.abs(y))
433
+
434
+ # if stream is not None:
435
+ # stream = np.concatenate([stream, y])
436
+ # else:
437
+ # stream = y
438
+
439
+ # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
440
+
441
+ # full_text = result.get("text","")
442
+
443
+ # return stream, full_text, result
444
+
445
+ # def update_map_with_response(history):
446
+ # if not history:
447
+ # return ""
448
+ # response = history[-1][1]
449
+ # addresses = extract_addresses(response)
450
+ # return generate_map(addresses)
451
+
452
+ # def clear_textbox():
453
+ # return ""
454
+
455
+ # def show_map_if_details(history, choice):
456
+ # if choice in ["Details", "Conversational"]:
457
+ # return gr.update(visible=True), update_map_with_response(history)
458
+ # else:
459
+ # return gr.update(visible=False), ""
460
+
461
+ # def generate_audio_elevenlabs(text):
462
+ # XI_API_KEY = os.environ['ELEVENLABS_API']
463
+ # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
464
+ # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
465
+ # headers = {
466
+ # "Accept": "application/json",
467
+ # "xi-api-key": XI_API_KEY
468
+ # }
469
+ # data = {
470
+ # "text": str(text),
471
+ # "model_id": "eleven_multilingual_v2",
472
+ # "voice_settings": {
473
+ # "stability": 1.0,
474
+ # "similarity_boost": 0.0,
475
+ # "style": 0.60,
476
+ # "use_speaker_boost": False
477
+ # }
478
+ # }
479
+ # response = requests.post(tts_url, headers=headers, json=data, stream=True)
480
+ # if response.ok:
481
+ # audio_segments = []
482
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
483
+ # for chunk in response.iter_content(chunk_size=1024):
484
+ # if chunk:
485
+ # f.write(chunk)
486
+ # audio_segments.append(chunk)
487
+ # temp_audio_path = f.name
488
+
489
+ # # Combine all audio chunks into a single file
490
+ # combined_audio = AudioSegment.from_file(temp_audio_path, format="mp3")
491
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "elevenlabs_combined_audio.mp3")
492
+ # combined_audio.export(combined_audio_path, format="mp3")
493
+
494
+ # logging.debug(f"Audio saved to {combined_audio_path}")
495
+ # return combined_audio_path
496
+ # else:
497
+ # logging.error(f"Error generating audio: {response.text}")
498
+ # return None
499
+
500
+
501
+ # repo_id = "parler-tts/parler-tts-mini-expresso"
502
+
503
+ # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
504
+ # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
505
+ # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
506
+
507
+ # SAMPLE_RATE = parler_feature_extractor.sampling_rate
508
+ # SEED = 42
509
+
510
+ # def preprocess(text):
511
+ # number_normalizer = EnglishNumberNormalizer()
512
+ # text = number_normalizer(text).strip()
513
+ # if text[-1] not in punctuation:
514
+ # text = f"{text}."
515
+
516
+ # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
517
+
518
+ # def separate_abb(chunk):
519
+ # chunk = chunk.replace(".", "")
520
+ # return " ".join(chunk)
521
+
522
+ # abbreviations = re.findall(abbreviations_pattern, text)
523
+ # for abv in abbreviations:
524
+ # if abv in text:
525
+ # text is text.replace(abv, separate_abb(abv))
526
+ # return text
527
+
528
+ # def chunk_text(text, max_length=250):
529
+ # words = text.split()
530
+ # chunks = []
531
+ # current_chunk = []
532
+ # current_length = 0
533
+
534
+ # for word in words:
535
+ # if current_length + len(word) + 1 <= max_length:
536
+ # current_chunk.append(word)
537
+ # current_length += len(word) + 1
538
+ # else:
539
+ # chunks.append(' '.join(current_chunk))
540
+ # current_chunk = [word]
541
+ # current_length = len(word) + 1
542
+
543
+ # if current_chunk:
544
+ # chunks.append(' '.join(current_chunk))
545
+
546
+ # return chunks
547
+
548
+ # def generate_audio_parler_tts(text):
549
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
550
+ # chunks = chunk_text(preprocess(text))
551
+ # audio_segments = []
552
+
553
+ # for chunk in chunks:
554
+ # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
555
+ # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
556
+
557
+ # set_seed(SEED)
558
+ # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
559
+ # audio_arr = generation.cpu().numpy().squeeze()
560
+
561
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
562
+ # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
563
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
564
+
565
+ # combined_audio = sum(audio_segments)
566
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
567
+ # combined_audio.export(combined_audio_path, format="wav")
568
+
569
+ # logging.debug(f"Audio saved to {combined_audio_path}")
570
+ # return combined_audio_path
571
+
572
+ # # Load the MARS5 model
573
+ # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
574
+
575
+ # def generate_audio_mars5(text):
576
+ # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
577
+ # kwargs_dict = {
578
+ # 'temperature': 0.2,
579
+ # 'top_k': -1,
580
+ # 'top_p': 0.2,
581
+ # 'typical_p': 1.0,
582
+ # 'freq_penalty': 2.6,
583
+ # 'presence_penalty': 0.4,
584
+ # 'rep_penalty_window': 100,
585
+ # 'max_prompt_phones': 360,
586
+ # 'deep_clone': True,
587
+ # 'nar_guidance_w': 3
588
+ # }
589
+
590
+ # chunks = chunk_text(preprocess(text))
591
+ # audio_segments = []
592
+
593
+ # for chunk in chunks:
594
+ # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
595
+ # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
596
+ # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
597
+
598
+ # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
599
+ # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
600
+ # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
601
+
602
+ # combined_audio = sum(audio_segments)
603
+ # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
604
+ # combined_audio.export(combined_audio_path, format="wav")
605
+
606
+ # logging.debug(f"Audio saved to {combined_audio_path}")
607
+ # return combined_audio_path
608
+
609
+ # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
610
+ # pipe.to(device)
611
+
612
+ # def generate_image(prompt):
613
+ # with torch.cuda.amp.autocast():
614
+ # image = pipe(
615
+ # prompt,
616
+ # num_inference_steps=28,
617
+ # guidance_scale=3.0,
618
+ # ).images[0]
619
+ # return image
620
+
621
+ # 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"
622
+ # 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."
623
+ # 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."
624
+
625
+ # def update_images():
626
+ # image_1 = generate_image(hardcoded_prompt_1)
627
+ # image_2 = generate_image(hardcoded_prompt_2)
628
+ # image_3 = generate_image(hardcoded_prompt_3)
629
+ # return image_1, image_2, image_3
630
+
631
+ # def fetch_local_events():
632
+ # api_key = os.environ['SERP_API']
633
+ # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
634
+ # response = requests.get(url)
635
+ # if response.status_code == 200:
636
+ # events_results = response.json().get("events_results", [])
637
+ # events_html = """
638
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
639
+ # <style>
640
+ # table {
641
+ # font-family: 'Verdana', sans-serif;
642
+ # color: #333;
643
+ # border-collapse: collapse;
644
+ # width: 100%;
645
+ # }
646
+ # th, td {
647
+ # border: 1px solid #fff !important;
648
+ # padding: 8px;
649
+ # }
650
+ # th {
651
+ # background-color: #f2f2f2;
652
+ # color: #333;
653
+ # text-align: left;
654
+ # }
655
+ # tr:hover {
656
+ # background-color: #f5f5f5;
657
+ # }
658
+ # .event-link {
659
+ # color: #1E90FF;
660
+ # text-decoration: none;
661
+ # }
662
+ # .event-link:hover {
663
+ # text-decoration: underline;
664
+ # }
665
+ # </style>
666
+ # <table>
667
+ # <tr>
668
+ # <th>Title</th>
669
+ # <th>Date and Time</th>
670
+ # <th>Location</th>
671
+ # </tr>
672
+ # """
673
+ # for event in events_results:
674
+ # title = event.get("title", "No title")
675
+ # date_info = event.get("date", {})
676
+ # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
677
+ # location = event.get("address", "No location")
678
+ # if isinstance(location, list):
679
+ # location = " ".join(location)
680
+ # location = location.replace("[", "").replace("]", "")
681
+ # link = event.get("link", "#")
682
+ # events_html += f"""
683
+ # <tr>
684
+ # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
685
+ # <td>{date}</td>
686
+ # <td>{location}</td>
687
+ # </tr>
688
+ # """
689
+ # events_html += "</table>"
690
+ # return events_html
691
+ # else:
692
+ # return "<p>Failed to fetch local events</p>"
693
+
694
+ # def get_weather_icon(condition):
695
+ # condition_map = {
696
+ # "Clear": "c01d",
697
+ # "Partly Cloudy": "c02d",
698
+ # "Cloudy": "c03d",
699
+ # "Overcast": "c04d",
700
+ # "Mist": "a01d",
701
+ # "Patchy rain possible": "r01d",
702
+ # "Light rain": "r02d",
703
+ # "Moderate rain": "r03d",
704
+ # "Heavy rain": "r04d",
705
+ # "Snow": "s01d",
706
+ # "Thunderstorm": "t01d",
707
+ # "Fog": "a05d",
708
+ # }
709
+ # return condition_map.get(condition, "c04d")
710
+
711
+ # def fetch_local_weather():
712
+ # try:
713
+ # api_key = os.environ['WEATHER_API']
714
+ # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
715
+ # response = requests.get(url)
716
+ # response.raise_for_status()
717
+ # jsonData = response.json()
718
+
719
+ # current_conditions = jsonData.get("currentConditions", {})
720
+ # temp_celsius = current_conditions.get("temp", "N/A")
721
+
722
+ # if temp_celsius != "N/A":
723
+ # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
724
+ # else:
725
+ # temp_fahrenheit = "N/A"
726
+
727
+ # condition = current_conditions.get("conditions", "N/A")
728
+ # humidity = current_conditions.get("humidity", "N/A")
729
+
730
+ # weather_html = f"""
731
+ # <div class="weather-theme">
732
+ # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
733
+ # <div class="weather-content">
734
+ # <div class="weather-icon">
735
+ # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
736
+ # </div>
737
+ # <div class="weather-details">
738
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
739
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
740
+ # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
741
+ # </div>
742
+ # </div>
743
+ # </div>
744
+ # <style>
745
+ # .weather-theme {{
746
+ # animation: backgroundAnimation 10s infinite alternate;
747
+ # border-radius: 10px;
748
+ # padding: 10px;
749
+ # margin-bottom: 15px;
750
+ # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
751
+ # background-size: 400% 400%;
752
+ # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
753
+ # transition: box-shadow 0.3s ease, background-color 0.3s ease;
754
+ # }}
755
+ # .weather-theme:hover {{
756
+ # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
757
+ # background-position: 100% 100%;
758
+ # }}
759
+ # @keyframes backgroundAnimation {{
760
+ # 0% {{ background-position: 0% 50%; }}
761
+ # 100% {{ background-position: 100% 50%; }}
762
+ # }}
763
+ # .weather-content {{
764
+ # display: flex;
765
+ # align-items: center;
766
+ # }}
767
+ # .weather-icon {{
768
+ # flex: 1;
769
+ # }}
770
+ # .weather-details {{
771
+ # flex 3;
772
+ # }}
773
+ # </style>
774
+ # """
775
+ # return weather_html
776
+ # except requests.exceptions.RequestException as e:
777
+ # return f"<p>Failed to fetch local weather: {e}</p>"
778
+
779
+ # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
780
+ # with gr.Row():
781
+ # with gr.Column():
782
+ # state = gr.State()
783
+
784
+ # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
785
+ # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
786
+ # retrieval_mode = gr.Radio(label="Retrieval Mode", choices=["Vector", "Knowledge-Graph"], value="Vector")
787
+
788
+ # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
789
+
790
+ # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!", placeholder="After Prompt,click Retriever Only")
791
+ # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
792
+ # retriever_button = gr.Button("Retriever")
793
+
794
+ # clear_button = gr.Button("Clear")
795
+ # clear_button.click(lambda:[None,None] ,outputs=[chat_input, state])
796
+
797
+ # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
798
+ # location_output = gr.HTML()
799
+
800
+ # # Define a single audio component
801
+ # audio_output = gr.Audio(interactive=False, autoplay=True)
802
+
803
+ # def stop_audio():
804
+ # audio_output.stop()
805
+ # return None
806
+
807
+ # # Define the sequence of actions for the "Retriever" button
808
+ # retriever_sequence = (
809
+ # retriever_button.click(fn=stop_audio, inputs=[], outputs=[audio_output],api_name="Ask_Retriever")
810
+ # .then(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query")
811
+ # .then(fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output],api_name="generate_voice_response" )
812
+ # .then(fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder")
813
+ # .then(fn=clear_textbox, inputs=[], outputs=[chat_input])
814
+ # )
815
+
816
+ # # Link the "Enter" key (submit event) to the same sequence of actions
817
+ # chat_input.submit(fn=stop_audio, inputs=[], outputs=[audio_output])
818
+ # chat_input.submit(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query").then(
819
+ # fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output], api_name="generate_voice_response"
820
+ # ).then(
821
+ # fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder"
822
+ # ).then(
823
+ # fn=clear_textbox, inputs=[], outputs=[chat_input]
824
+ # )
825
+
826
+ # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
827
+ # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
828
+
829
+ # # with gr.Column():
830
+ # # weather_output = gr.HTML(value=fetch_local_weather())
831
+ # # news_output = gr.HTML(value=fetch_local_news())
832
+ # # events_output = gr.HTML(value=fetch_local_events())
833
+
834
+ # with gr.Column():
835
+ # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
836
+ # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
837
+ # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
838
+
839
+ # refresh_button = gr.Button("Refresh Images")
840
+ # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3], api_name="update_image")
841
+
842
+ # demo.queue()
843
+ # demo.launch(share=True)
844
+
845
+
846
  import gradio as gr
847
  import requests
848
  import os
 
899
  logging.basicConfig(level=logging.DEBUG)
900
 
901
  embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
902
+
903
  from pinecone import Pinecone
904
  pc = Pinecone(api_key=os.environ['PINECONE_API_KEY'])
905
 
906
+
907
+
908
  index_name = "radardata07242024"
909
  vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
910
  retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
 
1067
 
1068
  template = """Answer the question based only on the following context:
1069
  {context}
 
1070
  Question: {question}
1071
  Use natural language and be concise.
1072
  Answer:"""
 
1673
  audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
1674
  audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
1675
 
 
 
 
 
 
1676
  with gr.Column():
1677
  image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
1678
  image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
 
1685
  demo.launch(share=True)
1686
 
1687
 
1688
+
1689
+