Pijush2023 commited on
Commit
d472d97
·
verified ·
1 Parent(s): dc08ddd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1674
app.py CHANGED
@@ -1,1677 +1,3 @@
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
849
- # import time
850
- # import re
851
- # import logging
852
- # import tempfile
853
- # import folium
854
- # import concurrent.futures
855
- # import torch
856
- # from PIL import Image
857
- # from datetime import datetime
858
- # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
859
- # from googlemaps import Client as GoogleMapsClient
860
- # from gtts import gTTS
861
- # from diffusers import StableDiffusionPipeline
862
- # from langchain_openai import OpenAIEmbeddings, ChatOpenAI
863
- # from langchain_pinecone import PineconeVectorStore
864
- # from langchain.prompts import PromptTemplate
865
- # from langchain.chains import RetrievalQA
866
- # from langchain.chains.conversation.memory import ConversationBufferWindowMemory
867
- # from langchain.agents import Tool, initialize_agent
868
- # from huggingface_hub import login
869
- # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
870
- # from parler_tts import ParlerTTSForConditionalGeneration
871
- # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
872
- # from scipy.io.wavfile import write as write_wav
873
- # from pydub import AudioSegment
874
- # from string import punctuation
875
- # import librosa
876
- # from pathlib import Path
877
- # import torchaudio
878
- # import numpy as np
879
-
880
- # # Neo4j imports
881
- # from langchain.chains import GraphCypherQAChain
882
- # from langchain_community.graphs import Neo4jGraph
883
- # from langchain_community.document_loaders import HuggingFaceDatasetLoader
884
- # from langchain_text_splitters import CharacterTextSplitter
885
- # from langchain_experimental.graph_transformers import LLMGraphTransformer
886
- # from langchain_core.prompts import ChatPromptTemplate
887
- # from langchain_core.pydantic_v1 import BaseModel, Field
888
- # from langchain_core.messages import AIMessage, HumanMessage
889
- # from langchain_core.output_parsers import StrOutputParser
890
- # from langchain_core.runnables import RunnableBranch, RunnableLambda, RunnableParallel, RunnablePassthrough
891
-
892
- # # Pinecone setup
893
- # hf_token = os.getenv("HF_TOKEN")
894
- # if hf_token is None:
895
- # print("Please set your Hugging Face token in the environment variables.")
896
- # else:
897
- # login(token=hf_token)
898
-
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
- # index_name = "radardata07242024"
907
- # vectorstore = PineconeVectorStore(index_name=index_name, embedding=embeddings)
908
- # retriever = vectorstore.as_retriever(search_kwargs={'k': 5})
909
-
910
- # chat_model = ChatOpenAI(api_key=os.environ['OPENAI_API_KEY'], temperature=0, model='gpt-4o')
911
-
912
- # conversational_memory = ConversationBufferWindowMemory(
913
- # memory_key='chat_history',
914
- # k=10,
915
- # return_messages=True
916
- # )
917
-
918
- # # Prompt templates
919
- # def get_current_date():
920
- # return datetime.now().strftime("%B %d, %Y")
921
-
922
- # current_date = get_current_date()
923
-
924
- # 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.
925
- # 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.
926
- # Now, let me guide you through some of the exciting events happening today in Birmingham, Alabama:
927
- # Address: >>, Birmingham, AL
928
- # Time: >>__
929
- # Date: >>__
930
- # Description: >>__
931
- # Address: >>, Birmingham, AL
932
- # Time: >>__
933
- # Date: >>__
934
- # Description: >>__
935
- # Address: >>, Birmingham, AL
936
- # Time: >>__
937
- # Date: >>__
938
- # Description: >>__
939
- # Address: >>, Birmingham, AL
940
- # Time: >>__
941
- # Date: >>__
942
- # Description: >>__
943
- # Address: >>, Birmingham, AL
944
- # Time: >>__
945
- # Date: >>__
946
- # Description: >>__
947
- # 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.
948
- # It was my pleasure!
949
- # {{context}}
950
- # Question: {{question}}
951
- # Helpful Answer:"""
952
-
953
- # 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.
954
- # 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.
955
- # "It was my pleasure!"
956
- # {{context}}
957
- # Question: {{question}}
958
- # Helpful Answer:"""
959
-
960
- # QA_CHAIN_PROMPT_1 = PromptTemplate(input_variables=["context", "question"], template=template1)
961
- # QA_CHAIN_PROMPT_2 = PromptTemplate(input_variables=["context", "question"], template=template2)
962
-
963
- # # Neo4j setup
964
- # graph = Neo4jGraph(
965
- # url="neo4j+s://98f45cc0.databases.neo4j.io",
966
- # username="neo4j",
967
- # password="B_sZbapCTZoQDWj1JrhwqElsNa-jm5Zq1m_mAnyPYog"
968
- # )
969
-
970
- # class Entities(BaseModel):
971
- # names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
972
-
973
- # entity_prompt = ChatPromptTemplate.from_messages([
974
- # ("system", "You are extracting organization and person entities from the text."),
975
- # ("human", "Use the given format to extract information from the following input: {question}"),
976
- # ])
977
-
978
- # entity_chain = entity_prompt | chat_model.with_structured_output(Entities)
979
-
980
- # def remove_lucene_chars(input: str) -> str:
981
- # return input.translate(str.maketrans({"\\": r"\\", "+": r"\+", "-": r"\-", "&": r"\&", "|": r"\|", "!": r"\!",
982
- # "(": r"\(", ")": r"\)", "{": r"\{", "}": r"\}", "[": r"\[", "]": r"\]",
983
- # "^": r"\^", "~": r"\~", "*": r"\*", "?": r"\?", ":": r"\:", '"': r'\"',
984
- # ";": r"\;", " ": r"\ "}))
985
-
986
- # def generate_full_text_query(input: str) -> str:
987
- # full_text_query = ""
988
- # words = [el for el in remove_lucene_chars(input).split() if el]
989
- # for word in words[:-1]:
990
- # full_text_query += f" {word}~2 AND"
991
- # full_text_query += f" {words[-1]}~2"
992
- # return full_text_query.strip()
993
-
994
- # def structured_retriever(question: str) -> str:
995
- # result = ""
996
- # entities = entity_chain.invoke({"question": question})
997
- # for entity in entities.names:
998
- # response = graph.query(
999
- # """CALL db.index.fulltext.queryNodes('entity', $query, {limit:2})
1000
- # YIELD node,score
1001
- # CALL {
1002
- # WITH node
1003
- # MATCH (node)-[r:!MENTIONS]->(neighbor)
1004
- # RETURN node.id + ' - ' + type(r) + ' -> ' + neighbor.id AS output
1005
- # UNION ALL
1006
- # WITH node
1007
- # MATCH (node)<-[r:!MENTIONS]-(neighbor)
1008
- # RETURN neighbor.id + ' - ' + type(r) + ' -> ' + node.id AS output
1009
- # }
1010
- # RETURN output LIMIT 50
1011
- # """,
1012
- # {"query": generate_full_text_query(entity)},
1013
- # )
1014
- # result += "\n".join([el['output'] for el in response])
1015
- # return result
1016
-
1017
- # def retriever_neo4j(question: str):
1018
- # structured_data = structured_retriever(question)
1019
- # return structured_data
1020
-
1021
- # _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
1022
- # in its original language.
1023
- # Chat History:
1024
- # {chat_history}
1025
- # Follow Up Input: {question}
1026
- # Standalone question:"""
1027
-
1028
- # CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
1029
-
1030
- # def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
1031
- # buffer = []
1032
- # for human, ai in chat_history:
1033
- # buffer.append(HumanMessage(content=human))
1034
- # buffer.append(AIMessage(content=ai))
1035
- # return buffer
1036
-
1037
- # _search_query = RunnableBranch(
1038
- # (
1039
- # RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
1040
- # run_name="HasChatHistoryCheck"
1041
- # ),
1042
- # RunnablePassthrough.assign(
1043
- # chat_history=lambda x: _format_chat_history(x["chat_history"])
1044
- # )
1045
- # | CONDENSE_QUESTION_PROMPT
1046
- # | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
1047
- # | StrOutputParser(),
1048
- # ),
1049
- # RunnableLambda(lambda x : x["question"]),
1050
- # )
1051
-
1052
- # template = """Answer the question based only on the following context:
1053
- # {context}
1054
- # Question: {question}
1055
- # Use natural language and be concise.
1056
- # Answer:"""
1057
-
1058
- # qa_prompt = ChatPromptTemplate.from_template(template)
1059
-
1060
- # chain_neo4j = (
1061
- # RunnableParallel(
1062
- # {
1063
- # "context": _search_query | retriever_neo4j,
1064
- # "question": RunnablePassthrough(),
1065
- # }
1066
- # )
1067
- # | qa_prompt
1068
- # | chat_model
1069
- # | StrOutputParser()
1070
- # )
1071
-
1072
- # # Define a function to select between Pinecone and Neo4j
1073
- # def generate_answer(message, choice, retrieval_mode):
1074
- # logging.debug(f"generate_answer called with choice: {choice} and retrieval_mode: {retrieval_mode}")
1075
-
1076
- # prompt_template = QA_CHAIN_PROMPT_1 if choice == "Details" else QA_CHAIN_PROMPT_2
1077
-
1078
- # if retrieval_mode == "Vector":
1079
- # qa_chain = RetrievalQA.from_chain_type(
1080
- # llm=chat_model,
1081
- # chain_type="stuff",
1082
- # retriever=retriever,
1083
- # chain_type_kwargs={"prompt": prompt_template}
1084
- # )
1085
- # response = qa_chain({"query": message})
1086
- # logging.debug(f"Vector response: {response}")
1087
- # return response['result'], extract_addresses(response['result'])
1088
- # elif retrieval_mode == "Knowledge-Graph":
1089
- # response = chain_neo4j.invoke({"question": message})
1090
- # logging.debug(f"Knowledge-Graph response: {response}")
1091
- # return response, extract_addresses(response)
1092
- # else:
1093
- # return "Invalid retrieval mode selected.", []
1094
-
1095
- # def bot(history, choice, tts_choice, retrieval_mode):
1096
- # if not history:
1097
- # return history
1098
-
1099
- # response, addresses = generate_answer(history[-1][0], choice, retrieval_mode)
1100
- # history[-1][1] = ""
1101
-
1102
- # with concurrent.futures.ThreadPoolExecutor() as executor:
1103
- # if tts_choice == "Alpha":
1104
- # audio_future = executor.submit(generate_audio_elevenlabs, response)
1105
- # elif tts_choice == "Beta":
1106
- # audio_future = executor.submit(generate_audio_parler_tts, response)
1107
- # elif tts_choice == "Gamma":
1108
- # audio_future = executor.submit(generate_audio_mars5, response)
1109
-
1110
- # for character in response:
1111
- # history[-1][1] += character
1112
- # time.sleep(0.05)
1113
- # yield history, None
1114
-
1115
- # audio_path = audio_future.result()
1116
- # yield history, audio_path
1117
-
1118
- # history.append([response, None]) # Ensure the response is added in the correct format
1119
-
1120
- # def add_message(history, message):
1121
- # history.append((message, None))
1122
- # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
1123
-
1124
- # def print_like_dislike(x: gr.LikeData):
1125
- # print(x.index, x.value, x.liked)
1126
-
1127
- # def extract_addresses(response):
1128
- # if not isinstance(response, str):
1129
- # response = str(response)
1130
- # address_patterns = [
1131
- # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
1132
- # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
1133
- # r'([A-Z].*,\sAL\s\d{5})',
1134
- # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
1135
- # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
1136
- # r'(\d{2}.*\sStreets)',
1137
- # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
1138
- # r'([a-zA-Z]\s Birmingham)',
1139
- # r'([a-zA-Z].*,\sBirmingham,\sAL)',
1140
- # r'(^Birmingham,AL$)'
1141
- # ]
1142
- # addresses = []
1143
- # for pattern in address_patterns:
1144
- # addresses.extend(re.findall(pattern, response))
1145
- # return addresses
1146
-
1147
- # all_addresses = []
1148
-
1149
- # def generate_map(location_names):
1150
- # global all_addresses
1151
- # all_addresses.extend(location_names)
1152
-
1153
- # api_key = os.environ['GOOGLEMAPS_API_KEY']
1154
- # gmaps = GoogleMapsClient(key=api_key)
1155
-
1156
- # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
1157
-
1158
- # for location_name in all_addresses:
1159
- # geocode_result = gmaps.geocode(location_name)
1160
- # if geocode_result:
1161
- # location = geocode_result[0]['geometry']['location']
1162
- # folium.Marker(
1163
- # [location['lat'], location['lng']],
1164
- # tooltip=f"{geocode_result[0]['formatted_address']}"
1165
- # ).add_to(m)
1166
-
1167
- # map_html = m._repr_html_()
1168
- # return map_html
1169
-
1170
- # def fetch_local_news():
1171
- # api_key = os.environ['SERP_API']
1172
- # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
1173
- # response = requests.get(url)
1174
- # if response.status_code == 200:
1175
- # results = response.json().get("news_results", [])
1176
- # news_html = """
1177
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
1178
- # <style>
1179
- # .news-item {
1180
- # font-family: 'Verdana', sans-serif;
1181
- # color: #333;
1182
- # background-color: #f0f8ff;
1183
- # margin-bottom: 15px;
1184
- # padding: 10px;
1185
- # border-radius: 5px;
1186
- # transition: box-shadow 0.3s ease, background-color 0.3s ease;
1187
- # font-weight: bold;
1188
- # }
1189
- # .news-item:hover {
1190
- # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
1191
- # background-color: #e6f7ff;
1192
- # }
1193
- # .news-item a {
1194
- # color: #1E90FF;
1195
- # text-decoration: none;
1196
- # font-weight: bold;
1197
- # }
1198
- # .news-item a:hover {
1199
- # text-decoration: underline;
1200
- # }
1201
- # .news-preview {
1202
- # position: absolute;
1203
- # display: none;
1204
- # border: 1px solid #ccc;
1205
- # border-radius: 5px;
1206
- # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
1207
- # background-color: white;
1208
- # z-index: 1000;
1209
- # max-width: 300px;
1210
- # padding: 10px;
1211
- # font-family: 'Verdana', sans-serif;
1212
- # color: #333;
1213
- # }
1214
- # </style>
1215
- # <script>
1216
- # function showPreview(event, previewContent) {
1217
- # var previewBox = document.getElementById('news-preview');
1218
- # previewBox.innerHTML = previewContent;
1219
- # previewBox.style.left = event.pageX + 'px';
1220
- # previewBox.style.top = event.pageY + 'px';
1221
- # previewBox.style.display = 'block';
1222
- # }
1223
- # function hidePreview() {
1224
- # var previewBox = document.getElementById('news-preview');
1225
- # previewBox.style.display = 'none';
1226
- # }
1227
- # </script>
1228
- # <div id="news-preview" class="news-preview"></div>
1229
- # """
1230
- # for index, result in enumerate(results[:7]):
1231
- # title = result.get("title", "No title")
1232
- # link = result.get("link", "#")
1233
- # snippet = result.get("snippet", "")
1234
- # news_html += f"""
1235
- # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
1236
- # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
1237
- # <p>{snippet}</p>
1238
- # </div>
1239
- # """
1240
- # return news_html
1241
- # else:
1242
- # return "<p>Failed to fetch local news</p>"
1243
-
1244
- # import numpy as np
1245
- # import torch
1246
- # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
1247
-
1248
- # model_id = 'openai/whisper-large-v3'
1249
- # device = "cuda:0" if torch.cuda.is_available() else "cpu"
1250
- # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
1251
- # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
1252
- # processor = AutoProcessor.from_pretrained(model_id)
1253
-
1254
- # 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)
1255
-
1256
- # base_audio_drive = "/data/audio"
1257
-
1258
- # def transcribe_function(stream, new_chunk):
1259
- # try:
1260
- # sr, y = new_chunk[0], new_chunk[1]
1261
- # except TypeError:
1262
- # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
1263
- # return stream, "", None
1264
-
1265
- # y = y.astype(np.float32) / np.max(np.abs(y))
1266
-
1267
- # if stream is not None:
1268
- # stream = np.concatenate([stream, y])
1269
- # else:
1270
- # stream = y
1271
-
1272
- # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
1273
-
1274
- # full_text = result.get("text","")
1275
-
1276
- # return stream, full_text, result
1277
-
1278
- # def update_map_with_response(history):
1279
- # if not history:
1280
- # return ""
1281
- # response = history[-1][1]
1282
- # addresses = extract_addresses(response)
1283
- # return generate_map(addresses)
1284
-
1285
- # def clear_textbox():
1286
- # return ""
1287
-
1288
- # def show_map_if_details(history, choice):
1289
- # if choice in ["Details", "Conversational"]:
1290
- # return gr.update(visible=True), update_map_with_response(history)
1291
- # else:
1292
- # return gr.update(visible=False), ""
1293
-
1294
- # def generate_audio_elevenlabs(text):
1295
- # XI_API_KEY = os.environ['ELEVENLABS_API']
1296
- # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
1297
- # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
1298
- # headers = {
1299
- # "Accept": "application/json",
1300
- # "xi-api-key": XI_API_KEY
1301
- # }
1302
- # data = {
1303
- # "text": str(text),
1304
- # "model_id": "eleven_multilingual_v2",
1305
- # "voice_settings": {
1306
- # "stability": 1.0,
1307
- # "similarity_boost": 0.0,
1308
- # "style": 0.60,
1309
- # "use_speaker_boost": False
1310
- # }
1311
- # }
1312
- # response = requests.post(tts_url, headers=headers, json=data, stream=True)
1313
- # if response.ok:
1314
- # audio_segments = []
1315
- # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
1316
- # for chunk in response.iter_content(chunk_size=1024):
1317
- # if chunk:
1318
- # f.write(chunk)
1319
- # audio_segments.append(chunk)
1320
- # temp_audio_path = f.name
1321
-
1322
- # # Combine all audio chunks into a single file
1323
- # combined_audio = AudioSegment.from_file(temp_audio_path, format="mp3")
1324
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "elevenlabs_combined_audio.mp3")
1325
- # combined_audio.export(combined_audio_path, format="mp3")
1326
-
1327
- # logging.debug(f"Audio saved to {combined_audio_path}")
1328
- # return combined_audio_path
1329
- # else:
1330
- # logging.error(f"Error generating audio: {response.text}")
1331
- # return None
1332
-
1333
-
1334
- # repo_id = "parler-tts/parler-tts-mini-expresso"
1335
-
1336
- # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
1337
- # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
1338
- # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
1339
-
1340
- # SAMPLE_RATE = parler_feature_extractor.sampling_rate
1341
- # SEED = 42
1342
-
1343
- # def preprocess(text):
1344
- # number_normalizer = EnglishNumberNormalizer()
1345
- # text = number_normalizer(text).strip()
1346
- # if text[-1] not in punctuation:
1347
- # text = f"{text}."
1348
-
1349
- # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
1350
-
1351
- # def separate_abb(chunk):
1352
- # chunk = chunk.replace(".", "")
1353
- # return " ".join(chunk)
1354
-
1355
- # abbreviations = re.findall(abbreviations_pattern, text)
1356
- # for abv in abbreviations:
1357
- # if abv in text:
1358
- # text is text.replace(abv, separate_abb(abv))
1359
- # return text
1360
-
1361
- # def chunk_text(text, max_length=250):
1362
- # words = text.split()
1363
- # chunks = []
1364
- # current_chunk = []
1365
- # current_length = 0
1366
-
1367
- # for word in words:
1368
- # if current_length + len(word) + 1 <= max_length:
1369
- # current_chunk.append(word)
1370
- # current_length += len(word) + 1
1371
- # else:
1372
- # chunks.append(' '.join(current_chunk))
1373
- # current_chunk = [word]
1374
- # current_length = len(word) + 1
1375
-
1376
- # if current_chunk:
1377
- # chunks.append(' '.join(current_chunk))
1378
-
1379
- # return chunks
1380
-
1381
- # def generate_audio_parler_tts(text):
1382
- # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
1383
- # chunks = chunk_text(preprocess(text))
1384
- # audio_segments = []
1385
-
1386
- # for chunk in chunks:
1387
- # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
1388
- # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
1389
-
1390
- # set_seed(SEED)
1391
- # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
1392
- # audio_arr = generation.cpu().numpy().squeeze()
1393
-
1394
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
1395
- # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
1396
- # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
1397
-
1398
- # combined_audio = sum(audio_segments)
1399
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
1400
- # combined_audio.export(combined_audio_path, format="wav")
1401
-
1402
- # logging.debug(f"Audio saved to {combined_audio_path}")
1403
- # return combined_audio_path
1404
-
1405
- # # Load the MARS5 model
1406
- # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
1407
-
1408
- # def generate_audio_mars5(text):
1409
- # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
1410
- # kwargs_dict = {
1411
- # 'temperature': 0.2,
1412
- # 'top_k': -1,
1413
- # 'top_p': 0.2,
1414
- # 'typical_p': 1.0,
1415
- # 'freq_penalty': 2.6,
1416
- # 'presence_penalty': 0.4,
1417
- # 'rep_penalty_window': 100,
1418
- # 'max_prompt_phones': 360,
1419
- # 'deep_clone': True,
1420
- # 'nar_guidance_w': 3
1421
- # }
1422
-
1423
- # chunks = chunk_text(preprocess(text))
1424
- # audio_segments = []
1425
-
1426
- # for chunk in chunks:
1427
- # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
1428
- # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
1429
- # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
1430
-
1431
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
1432
- # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
1433
- # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
1434
-
1435
- # combined_audio = sum(audio_segments)
1436
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
1437
- # combined_audio.export(combined_audio_path, format="wav")
1438
-
1439
- # logging.debug(f"Audio saved to {combined_audio_path}")
1440
- # return combined_audio_path
1441
-
1442
- # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
1443
- # pipe.to(device)
1444
-
1445
- # def generate_image(prompt):
1446
- # with torch.cuda.amp.autocast():
1447
- # image = pipe(
1448
- # prompt,
1449
- # num_inference_steps=28,
1450
- # guidance_scale=3.0,
1451
- # ).images[0]
1452
- # return image
1453
-
1454
- # 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"
1455
- # 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."
1456
- # 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."
1457
-
1458
- # def update_images():
1459
- # image_1 = generate_image(hardcoded_prompt_1)
1460
- # image_2 = generate_image(hardcoded_prompt_2)
1461
- # image_3 = generate_image(hardcoded_prompt_3)
1462
- # return image_1, image_2, image_3
1463
-
1464
- # def fetch_local_events():
1465
- # api_key = os.environ['SERP_API']
1466
- # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
1467
- # response = requests.get(url)
1468
- # if response.status_code == 200:
1469
- # events_results = response.json().get("events_results", [])
1470
- # events_html = """
1471
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
1472
- # <style>
1473
- # table {
1474
- # font-family: 'Verdana', sans-serif;
1475
- # color: #333;
1476
- # border-collapse: collapse;
1477
- # width: 100%;
1478
- # }
1479
- # th, td {
1480
- # border: 1px solid #fff !important;
1481
- # padding: 8px;
1482
- # }
1483
- # th {
1484
- # background-color: #f2f2f2;
1485
- # color: #333;
1486
- # text-align: left;
1487
- # }
1488
- # tr:hover {
1489
- # background-color: #f5f5f5;
1490
- # }
1491
- # .event-link {
1492
- # color: #1E90FF;
1493
- # text-decoration: none;
1494
- # }
1495
- # .event-link:hover {
1496
- # text-decoration: underline;
1497
- # }
1498
- # </style>
1499
- # <table>
1500
- # <tr>
1501
- # <th>Title</th>
1502
- # <th>Date and Time</th>
1503
- # <th>Location</th>
1504
- # </tr>
1505
- # """
1506
- # for event in events_results:
1507
- # title = event.get("title", "No title")
1508
- # date_info = event.get("date", {})
1509
- # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
1510
- # location = event.get("address", "No location")
1511
- # if isinstance(location, list):
1512
- # location = " ".join(location)
1513
- # location = location.replace("[", "").replace("]", "")
1514
- # link = event.get("link", "#")
1515
- # events_html += f"""
1516
- # <tr>
1517
- # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
1518
- # <td>{date}</td>
1519
- # <td>{location}</td>
1520
- # </tr>
1521
- # """
1522
- # events_html += "</table>"
1523
- # return events_html
1524
- # else:
1525
- # return "<p>Failed to fetch local events</p>"
1526
-
1527
- # def get_weather_icon(condition):
1528
- # condition_map = {
1529
- # "Clear": "c01d",
1530
- # "Partly Cloudy": "c02d",
1531
- # "Cloudy": "c03d",
1532
- # "Overcast": "c04d",
1533
- # "Mist": "a01d",
1534
- # "Patchy rain possible": "r01d",
1535
- # "Light rain": "r02d",
1536
- # "Moderate rain": "r03d",
1537
- # "Heavy rain": "r04d",
1538
- # "Snow": "s01d",
1539
- # "Thunderstorm": "t01d",
1540
- # "Fog": "a05d",
1541
- # }
1542
- # return condition_map.get(condition, "c04d")
1543
-
1544
- # def fetch_local_weather():
1545
- # try:
1546
- # api_key = os.environ['WEATHER_API']
1547
- # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
1548
- # response = requests.get(url)
1549
- # response.raise_for_status()
1550
- # jsonData = response.json()
1551
-
1552
- # current_conditions = jsonData.get("currentConditions", {})
1553
- # temp_celsius = current_conditions.get("temp", "N/A")
1554
-
1555
- # if temp_celsius != "N/A":
1556
- # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
1557
- # else:
1558
- # temp_fahrenheit = "N/A"
1559
-
1560
- # condition = current_conditions.get("conditions", "N/A")
1561
- # humidity = current_conditions.get("humidity", "N/A")
1562
-
1563
- # weather_html = f"""
1564
- # <div class="weather-theme">
1565
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
1566
- # <div class="weather-content">
1567
- # <div class="weather-icon">
1568
- # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
1569
- # </div>
1570
- # <div class="weather-details">
1571
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
1572
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
1573
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
1574
- # </div>
1575
- # </div>
1576
- # </div>
1577
- # <style>
1578
- # .weather-theme {{
1579
- # animation: backgroundAnimation 10s infinite alternate;
1580
- # border-radius: 10px;
1581
- # padding: 10px;
1582
- # margin-bottom: 15px;
1583
- # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
1584
- # background-size: 400% 400%;
1585
- # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
1586
- # transition: box-shadow 0.3s ease, background-color 0.3s ease;
1587
- # }}
1588
- # .weather-theme:hover {{
1589
- # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
1590
- # background-position: 100% 100%;
1591
- # }}
1592
- # @keyframes backgroundAnimation {{
1593
- # 0% {{ background-position: 0% 50%; }}
1594
- # 100% {{ background-position: 100% 50%; }}
1595
- # }}
1596
- # .weather-content {{
1597
- # display: flex;
1598
- # align-items: center;
1599
- # }}
1600
- # .weather-icon {{
1601
- # flex: 1;
1602
- # }}
1603
- # .weather-details {{
1604
- # flex 3;
1605
- # }}
1606
- # </style>
1607
- # """
1608
- # return weather_html
1609
- # except requests.exceptions.RequestException as e:
1610
- # return f"<p>Failed to fetch local weather: {e}</p>"
1611
-
1612
- # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
1613
- # with gr.Row():
1614
- # with gr.Column():
1615
- # state = gr.State()
1616
-
1617
- # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
1618
- # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
1619
- # retrieval_mode = gr.Radio(label="Retrieval Mode", choices=["Vector", "Knowledge-Graph"], value="Vector")
1620
-
1621
- # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
1622
-
1623
- # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!", placeholder="After Prompt,click Retriever Only")
1624
- # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
1625
- # retriever_button = gr.Button("Retriever")
1626
-
1627
- # clear_button = gr.Button("Clear")
1628
- # clear_button.click(lambda:[None,None] ,outputs=[chat_input, state])
1629
-
1630
- # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
1631
- # location_output = gr.HTML()
1632
-
1633
- # # Define a single audio component
1634
- # audio_output = gr.Audio(interactive=False, autoplay=True)
1635
-
1636
- # def stop_audio():
1637
- # audio_output.stop()
1638
- # return None
1639
-
1640
- # # Define the sequence of actions for the "Retriever" button
1641
- # retriever_sequence = (
1642
- # retriever_button.click(fn=stop_audio, inputs=[], outputs=[audio_output],api_name="Ask_Retriever")
1643
- # .then(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query")
1644
- # .then(fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output],api_name="generate_voice_response" )
1645
- # .then(fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder")
1646
- # .then(fn=clear_textbox, inputs=[], outputs=[chat_input])
1647
- # )
1648
-
1649
- # # Link the "Enter" key (submit event) to the same sequence of actions
1650
- # chat_input.submit(fn=stop_audio, inputs=[], outputs=[audio_output])
1651
- # chat_input.submit(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query").then(
1652
- # fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output], api_name="generate_voice_response"
1653
- # ).then(
1654
- # fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder"
1655
- # ).then(
1656
- # fn=clear_textbox, inputs=[], outputs=[chat_input]
1657
- # )
1658
-
1659
- # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
1660
- # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
1661
-
1662
- # with gr.Column():
1663
- # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
1664
- # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
1665
- # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
1666
-
1667
- # refresh_button = gr.Button("Refresh Images")
1668
- # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3], api_name="update_image")
1669
-
1670
- # demo.queue()
1671
- # demo.launch(share=True)
1672
-
1673
-
1674
-
1675
  import gradio as gr
1676
  import requests
1677
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os