Pijush2023 commited on
Commit
2120faf
·
verified ·
1 Parent(s): 3da746f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -856
app.py CHANGED
@@ -1,845 +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 huggingface_hub import login
23
- # from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
24
- # from parler_tts import ParlerTTSForConditionalGeneration
25
- # from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
26
- # from scipy.io.wavfile import write as write_wav
27
- # from pydub import AudioSegment
28
- # from string import punctuation
29
- # import librosa
30
- # from pathlib import Path
31
- # import torchaudio
32
- # import numpy as np
33
-
34
- # # Neo4j imports
35
- # from langchain.chains import GraphCypherQAChain
36
- # from langchain_community.graphs import Neo4jGraph
37
- # from langchain_community.document_loaders import HuggingFaceDatasetLoader
38
- # from langchain_text_splitters import CharacterTextSplitter
39
- # from langchain_experimental.graph_transformers import LLMGraphTransformer
40
- # from langchain_core.prompts import ChatPromptTemplate
41
- # from langchain_core.pydantic_v1 import BaseModel, Field
42
- # from langchain_core.messages import AIMessage, HumanMessage
43
- # from langchain_core.output_parsers import StrOutputParser
44
- # from langchain_core.runnables import RunnableBranch, RunnableLambda, RunnableParallel, RunnablePassthrough
45
-
46
- # # Pinecone setup
47
- # hf_token = os.getenv("HF_TOKEN")
48
- # if hf_token is None:
49
- # print("Please set your Hugging Face token in the environment variables.")
50
- # else:
51
- # login(token=hf_token)
52
-
53
- # logging.basicConfig(level=logging.DEBUG)
54
-
55
- # embeddings = OpenAIEmbeddings(api_key=os.environ['OPENAI_API_KEY'])
56
-
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
- # logging.debug(f"Structured data: {structured_data}")
188
- # return structured_data
189
-
190
- # _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
191
- # in its original language.
192
- # Chat History:
193
- # {chat_history}
194
- # Follow Up Input: {question}
195
- # Standalone question:"""
196
-
197
- # CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
198
-
199
- # def _format_chat_history(chat_history: list[tuple[str, str]]) -> list:
200
- # buffer = []
201
- # for human, ai in chat_history:
202
- # buffer.append(HumanMessage(content=human))
203
- # buffer.append(AIMessage(content=ai))
204
- # return buffer
205
-
206
- # _search_query = RunnableBranch(
207
- # (
208
- # RunnableLambda(lambda x: bool(x.get("chat_history"))).with_config(
209
- # run_name="HasChatHistoryCheck"
210
- # ),
211
- # RunnablePassthrough.assign(
212
- # chat_history=lambda x: _format_chat_history(x["chat_history"])
213
- # )
214
- # | CONDENSE_QUESTION_PROMPT
215
- # | ChatOpenAI(temperature=0, api_key=os.environ['OPENAI_API_KEY'])
216
- # | StrOutputParser(),
217
- # ),
218
- # RunnableLambda(lambda x : x["question"]),
219
- # )
220
-
221
- # template = """Answer the question based only on the following context:
222
- # {context}
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
- # logging.debug(f"Vector response: {response}")
256
- # return response['result'], extract_addresses(response['result'])
257
- # elif retrieval_mode == "Knowledge-Graph":
258
- # response = chain_neo4j.invoke({"question": message})
259
- # logging.debug(f"Knowledge-Graph response: {response}")
260
- # return response, extract_addresses(response)
261
- # else:
262
- # return "Invalid retrieval mode selected.", []
263
-
264
- # def bot(history, choice, tts_choice, retrieval_mode):
265
- # if not history:
266
- # return history
267
-
268
- # response, addresses = generate_answer(history[-1][0], choice, retrieval_mode)
269
- # history[-1][1] = ""
270
-
271
- # with concurrent.futures.ThreadPoolExecutor() as executor:
272
- # if tts_choice == "Alpha":
273
- # audio_future = executor.submit(generate_audio_elevenlabs, response)
274
- # elif tts_choice == "Beta":
275
- # audio_future = executor.submit(generate_audio_parler_tts, response)
276
- # elif tts_choice == "Gamma":
277
- # audio_future = executor.submit(generate_audio_mars5, response)
278
-
279
- # for character in response:
280
- # history[-1][1] += character
281
- # time.sleep(0.05)
282
- # yield history, None
283
-
284
- # audio_path = audio_future.result()
285
- # yield history, audio_path
286
-
287
- # history.append([response, None]) # Ensure the response is added in the correct format
288
-
289
- # def add_message(history, message):
290
- # history.append((message, None))
291
- # return history, gr.Textbox(value="", interactive=True, placeholder="Enter message or upload file...", show_label=False)
292
-
293
- # def print_like_dislike(x: gr.LikeData):
294
- # print(x.index, x.value, x.liked)
295
-
296
- # def extract_addresses(response):
297
- # if not isinstance(response, str):
298
- # response = str(response)
299
- # address_patterns = [
300
- # r'([A-Z].*,\sBirmingham,\sAL\s\d{5})',
301
- # r'(\d{4}\s.*,\sBirmingham,\sAL\s\d{5})',
302
- # r'([A-Z].*,\sAL\s\d{5})',
303
- # r'([A-Z].*,.*\sSt,\sBirmingham,\sAL\s\d{5})',
304
- # r'([A-Z].*,.*\sStreets,\sBirmingham,\sAL\s\d{5})',
305
- # r'(\d{2}.*\sStreets)',
306
- # r'([A-Z].*\s\d{2},\sBirmingham,\sAL\s\d{5})',
307
- # r'([a-zA-Z]\s Birmingham)',
308
- # r'([a-zA-Z].*,\sBirmingham,\sAL)',
309
- # r'(^Birmingham,AL$)'
310
- # ]
311
- # addresses = []
312
- # for pattern in address_patterns:
313
- # addresses.extend(re.findall(pattern, response))
314
- # return addresses
315
-
316
- # all_addresses = []
317
-
318
- # def generate_map(location_names):
319
- # global all_addresses
320
- # all_addresses.extend(location_names)
321
-
322
- # api_key = os.environ['GOOGLEMAPS_API_KEY']
323
- # gmaps = GoogleMapsClient(key=api_key)
324
-
325
- # m = folium.Map(location=[33.5175, -86.809444], zoom_start=12)
326
-
327
- # for location_name in all_addresses:
328
- # geocode_result = gmaps.geocode(location_name)
329
- # if geocode_result:
330
- # location = geocode_result[0]['geometry']['location']
331
- # folium.Marker(
332
- # [location['lat'], location['lng']],
333
- # tooltip=f"{geocode_result[0]['formatted_address']}"
334
- # ).add_to(m)
335
-
336
- # map_html = m._repr_html_()
337
- # return map_html
338
-
339
- # def fetch_local_news():
340
- # api_key = os.environ['SERP_API']
341
- # url = f'https://serpapi.com/search.json?engine=google_news&q=birmingham headline&api_key={api_key}'
342
- # response = requests.get(url)
343
- # if response.status_code == 200:
344
- # results = response.json().get("news_results", [])
345
- # news_html = """
346
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Birmingham Today</h2>
347
- # <style>
348
- # .news-item {
349
- # font-family: 'Verdana', sans-serif;
350
- # color: #333;
351
- # background-color: #f0f8ff;
352
- # margin-bottom: 15px;
353
- # padding: 10px;
354
- # border-radius: 5px;
355
- # transition: box-shadow 0.3s ease, background-color 0.3s ease;
356
- # font-weight: bold;
357
- # }
358
- # .news-item:hover {
359
- # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
360
- # background-color: #e6f7ff;
361
- # }
362
- # .news-item a {
363
- # color: #1E90FF;
364
- # text-decoration: none;
365
- # font-weight: bold;
366
- # }
367
- # .news-item a:hover {
368
- # text-decoration: underline;
369
- # }
370
- # .news-preview {
371
- # position: absolute;
372
- # display: none;
373
- # border: 1px solid #ccc;
374
- # border-radius: 5px;
375
- # box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
376
- # background-color: white;
377
- # z-index: 1000;
378
- # max-width: 300px;
379
- # padding: 10px;
380
- # font-family: 'Verdana', sans-serif;
381
- # color: #333;
382
- # }
383
- # </style>
384
- # <script>
385
- # function showPreview(event, previewContent) {
386
- # var previewBox = document.getElementById('news-preview');
387
- # previewBox.innerHTML = previewContent;
388
- # previewBox.style.left = event.pageX + 'px';
389
- # previewBox.style.top = event.pageY + 'px';
390
- # previewBox.style.display = 'block';
391
- # }
392
- # function hidePreview() {
393
- # var previewBox = document.getElementById('news-preview');
394
- # previewBox.style.display = 'none';
395
- # }
396
- # </script>
397
- # <div id="news-preview" class="news-preview"></div>
398
- # """
399
- # for index, result in enumerate(results[:7]):
400
- # title = result.get("title", "No title")
401
- # link = result.get("link", "#")
402
- # snippet = result.get("snippet", "")
403
- # news_html += f"""
404
- # <div class="news-item" onmouseover="showPreview(event, '{snippet}')" onmouseout="hidePreview()">
405
- # <a href='{link}' target='_blank'>{index + 1}. {title}</a>
406
- # <p>{snippet}</p>
407
- # </div>
408
- # """
409
- # return news_html
410
- # else:
411
- # return "<p>Failed to fetch local news</p>"
412
-
413
- # import numpy as np
414
- # import torch
415
- # from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
416
-
417
- # model_id = 'openai/whisper-large-v3'
418
- # device = "cuda:0" if torch.cuda.is_available() else "cpu"
419
- # torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
420
- # model = AutoModelForSpeechSeq2Seq.from_pretrained(model_id, torch_dtype=torch_dtype).to(device)
421
- # processor = AutoProcessor.from_pretrained(model_id)
422
-
423
- # 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)
424
-
425
- # base_audio_drive = "/data/audio"
426
-
427
- # def transcribe_function(stream, new_chunk):
428
- # try:
429
- # sr, y = new_chunk[0], new_chunk[1]
430
- # except TypeError:
431
- # print(f"Error chunk structure: {type(new_chunk)}, content: {new_chunk}")
432
- # return stream, "", None
433
-
434
- # y = y.astype(np.float32) / np.max(np.abs(y))
435
-
436
- # if stream is not None:
437
- # stream = np.concatenate([stream, y])
438
- # else:
439
- # stream = y
440
-
441
- # result = pipe_asr({"array": stream, "sampling_rate": sr}, return_timestamps=False)
442
-
443
- # full_text = result.get("text","")
444
-
445
- # return stream, full_text, result
446
-
447
- # def update_map_with_response(history):
448
- # if not history:
449
- # return ""
450
- # response = history[-1][1]
451
- # addresses = extract_addresses(response)
452
- # return generate_map(addresses)
453
-
454
- # def clear_textbox():
455
- # return ""
456
-
457
- # def show_map_if_details(history, choice):
458
- # if choice in ["Details", "Conversational"]:
459
- # return gr.update(visible=True), update_map_with_response(history)
460
- # else:
461
- # return gr.update(visible=False), ""
462
-
463
- # def generate_audio_elevenlabs(text):
464
- # XI_API_KEY = os.environ['ELEVENLABS_API']
465
- # VOICE_ID = 'd9MIrwLnvDeH7aZb61E9'
466
- # tts_url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/stream"
467
- # headers = {
468
- # "Accept": "application/json",
469
- # "xi-api-key": XI_API_KEY
470
- # }
471
- # data = {
472
- # "text": str(text),
473
- # "model_id": "eleven_multilingual_v2",
474
- # "voice_settings": {
475
- # "stability": 1.0,
476
- # "similarity_boost": 0.0,
477
- # "style": 0.60,
478
- # "use_speaker_boost": False
479
- # }
480
- # }
481
- # response = requests.post(tts_url, headers=headers, json=data, stream=True)
482
- # if response.ok:
483
- # audio_segments = []
484
- # with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as f:
485
- # for chunk in response.iter_content(chunk_size=1024):
486
- # if chunk:
487
- # f.write(chunk)
488
- # audio_segments.append(chunk)
489
- # temp_audio_path = f.name
490
-
491
- # # Combine all audio chunks into a single file
492
- # combined_audio = AudioSegment.from_file(temp_audio_path, format="mp3")
493
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "elevenlabs_combined_audio.mp3")
494
- # combined_audio.export(combined_audio_path, format="mp3")
495
-
496
- # logging.debug(f"Audio saved to {combined_audio_path}")
497
- # return combined_audio_path
498
- # else:
499
- # logging.error(f"Error generating audio: {response.text}")
500
- # return None
501
-
502
-
503
- # repo_id = "parler-tts/parler-tts-mini-expresso"
504
-
505
- # parler_model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device)
506
- # parler_tokenizer = AutoTokenizer.from_pretrained(repo_id)
507
- # parler_feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
508
-
509
- # SAMPLE_RATE = parler_feature_extractor.sampling_rate
510
- # SEED = 42
511
-
512
- # def preprocess(text):
513
- # number_normalizer = EnglishNumberNormalizer()
514
- # text = number_normalizer(text).strip()
515
- # if text[-1] not in punctuation:
516
- # text = f"{text}."
517
-
518
- # abbreviations_pattern = r'\b[A-Z][A-Z\.]+\b'
519
-
520
- # def separate_abb(chunk):
521
- # chunk = chunk.replace(".", "")
522
- # return " ".join(chunk)
523
-
524
- # abbreviations = re.findall(abbreviations_pattern, text)
525
- # for abv in abbreviations:
526
- # if abv in text:
527
- # text is text.replace(abv, separate_abb(abv))
528
- # return text
529
-
530
- # def chunk_text(text, max_length=250):
531
- # words = text.split()
532
- # chunks = []
533
- # current_chunk = []
534
- # current_length = 0
535
-
536
- # for word in words:
537
- # if current_length + len(word) + 1 <= max_length:
538
- # current_chunk.append(word)
539
- # current_length += len(word) + 1
540
- # else:
541
- # chunks.append(' '.join(current_chunk))
542
- # current_chunk = [word]
543
- # current_length = len(word) + 1
544
-
545
- # if current_chunk:
546
- # chunks.append(' '.join(current_chunk))
547
-
548
- # return chunks
549
-
550
- # def generate_audio_parler_tts(text):
551
- # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
552
- # chunks = chunk_text(preprocess(text))
553
- # audio_segments = []
554
-
555
- # for chunk in chunks:
556
- # inputs = parler_tokenizer(description, return_tensors="pt").to(device)
557
- # prompt = parler_tokenizer(chunk, return_tensors="pt").to(device)
558
-
559
- # set_seed(SEED)
560
- # generation = parler_model.generate(input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids)
561
- # audio_arr = generation.cpu().numpy().squeeze()
562
-
563
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"parler_tts_audio_{len(audio_segments)}.wav")
564
- # write_wav(temp_audio_path, SAMPLE_RATE, audio_arr)
565
- # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
566
-
567
- # combined_audio = sum(audio_segments)
568
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "parler_tts_combined_audio.wav")
569
- # combined_audio.export(combined_audio_path, format="wav")
570
-
571
- # logging.debug(f"Audio saved to {combined_audio_path}")
572
- # return combined_audio_path
573
-
574
- # # Load the MARS5 model
575
- # mars5, config_class = torch.hub.load('Camb-ai/mars5-tts', 'mars5_english', trust_repo=True)
576
-
577
- # def generate_audio_mars5(text):
578
- # description = "Thomas speaks with emphasis and excitement at a moderate pace with high quality."
579
- # kwargs_dict = {
580
- # 'temperature': 0.2,
581
- # 'top_k': -1,
582
- # 'top_p': 0.2,
583
- # 'typical_p': 1.0,
584
- # 'freq_penalty': 2.6,
585
- # 'presence_penalty': 0.4,
586
- # 'rep_penalty_window': 100,
587
- # 'max_prompt_phones': 360,
588
- # 'deep_clone': True,
589
- # 'nar_guidance_w': 3
590
- # }
591
-
592
- # chunks = chunk_text(preprocess(text))
593
- # audio_segments = []
594
-
595
- # for chunk in chunks:
596
- # wav = torch.zeros(1, mars5.sr) # Use a placeholder silent audio for the reference
597
- # cfg = config_class(**{k: kwargs_dict[k] for k in kwargs_dict if k in config_class.__dataclass_fields__})
598
- # ar_codes, wav_out = mars5.tts(chunk, wav, "", cfg=cfg)
599
-
600
- # temp_audio_path = os.path.join(tempfile.gettempdir(), f"mars5_audio_{len(audio_segments)}.wav")
601
- # torchaudio.save(temp_audio_path, wav_out.unsqueeze(0), mars5.sr)
602
- # audio_segments.append(AudioSegment.from_wav(temp_audio_path))
603
-
604
- # combined_audio = sum(audio_segments)
605
- # combined_audio_path = os.path.join(tempfile.gettempdir(), "mars5_combined_audio.wav")
606
- # combined_audio.export(combined_audio_path, format="wav")
607
-
608
- # logging.debug(f"Audio saved to {combined_audio_path}")
609
- # return combined_audio_path
610
-
611
- # pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2", torch_dtype=torch.float16)
612
- # pipe.to(device)
613
-
614
- # def generate_image(prompt):
615
- # with torch.cuda.amp.autocast():
616
- # image = pipe(
617
- # prompt,
618
- # num_inference_steps=28,
619
- # guidance_scale=3.0,
620
- # ).images[0]
621
- # return image
622
-
623
- # 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"
624
- # 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."
625
- # 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."
626
-
627
- # def update_images():
628
- # image_1 = generate_image(hardcoded_prompt_1)
629
- # image_2 = generate_image(hardcoded_prompt_2)
630
- # image_3 = generate_image(hardcoded_prompt_3)
631
- # return image_1, image_2, image_3
632
-
633
- # def fetch_local_events():
634
- # api_key = os.environ['SERP_API']
635
- # url = f'https://serpapi.com/search.json?engine=google_events&q=Events+in+Birmingham&hl=en&gl=us&api_key={api_key}'
636
- # response = requests.get(url)
637
- # if response.status_code == 200:
638
- # events_results = response.json().get("events_results", [])
639
- # events_html = """
640
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Events</h2>
641
- # <style>
642
- # table {
643
- # font-family: 'Verdana', sans-serif;
644
- # color: #333;
645
- # border-collapse: collapse;
646
- # width: 100%;
647
- # }
648
- # th, td {
649
- # border: 1px solid #fff !important;
650
- # padding: 8px;
651
- # }
652
- # th {
653
- # background-color: #f2f2f2;
654
- # color: #333;
655
- # text-align: left;
656
- # }
657
- # tr:hover {
658
- # background-color: #f5f5f5;
659
- # }
660
- # .event-link {
661
- # color: #1E90FF;
662
- # text-decoration: none;
663
- # }
664
- # .event-link:hover {
665
- # text-decoration: underline;
666
- # }
667
- # </style>
668
- # <table>
669
- # <tr>
670
- # <th>Title</th>
671
- # <th>Date and Time</th>
672
- # <th>Location</th>
673
- # </tr>
674
- # """
675
- # for event in events_results:
676
- # title = event.get("title", "No title")
677
- # date_info = event.get("date", {})
678
- # date = f"{date_info.get('start_date', '')} {date_info.get('when', '')}".replace("{", "").replace("}", "")
679
- # location = event.get("address", "No location")
680
- # if isinstance(location, list):
681
- # location = " ".join(location)
682
- # location = location.replace("[", "").replace("]", "")
683
- # link = event.get("link", "#")
684
- # events_html += f"""
685
- # <tr>
686
- # <td><a class='event-link' href='{link}' target='_blank'>{title}</a></td>
687
- # <td>{date}</td>
688
- # <td>{location}</td>
689
- # </tr>
690
- # """
691
- # events_html += "</table>"
692
- # return events_html
693
- # else:
694
- # return "<p>Failed to fetch local events</p>"
695
-
696
- # def get_weather_icon(condition):
697
- # condition_map = {
698
- # "Clear": "c01d",
699
- # "Partly Cloudy": "c02d",
700
- # "Cloudy": "c03d",
701
- # "Overcast": "c04d",
702
- # "Mist": "a01d",
703
- # "Patchy rain possible": "r01d",
704
- # "Light rain": "r02d",
705
- # "Moderate rain": "r03d",
706
- # "Heavy rain": "r04d",
707
- # "Snow": "s01d",
708
- # "Thunderstorm": "t01d",
709
- # "Fog": "a05d",
710
- # }
711
- # return condition_map.get(condition, "c04d")
712
-
713
- # def fetch_local_weather():
714
- # try:
715
- # api_key = os.environ['WEATHER_API']
716
- # url = f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/birmingham?unitGroup=metric&include=events%2Calerts%2Chours%2Cdays%2Ccurrent&key={api_key}'
717
- # response = requests.get(url)
718
- # response.raise_for_status()
719
- # jsonData = response.json()
720
-
721
- # current_conditions = jsonData.get("currentConditions", {})
722
- # temp_celsius = current_conditions.get("temp", "N/A")
723
-
724
- # if temp_celsius != "N/A":
725
- # temp_fahrenheit = int((temp_celsius * 9/5) + 32)
726
- # else:
727
- # temp_fahrenheit = "N/A"
728
-
729
- # condition = current_conditions.get("conditions", "N/A")
730
- # humidity = current_conditions.get("humidity", "N/A")
731
-
732
- # weather_html = f"""
733
- # <div class="weather-theme">
734
- # <h2 style="font-family: 'Georgia', serif; color: #ff0000; background-color: #f8f8f8; padding: 10px; border-radius: 10px;">Local Weather</h2>
735
- # <div class="weather-content">
736
- # <div class="weather-icon">
737
- # <img src="https://www.weatherbit.io/static/img/icons/{get_weather_icon(condition)}.png" alt="{condition}" style="width: 100px; height: 100px;">
738
- # </div>
739
- # <div class="weather-details">
740
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Temperature: {temp_fahrenheit}°F</p>
741
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Condition: {condition}</p>
742
- # <p style="font-family: 'Verdana', sans-serif; color: #333; font-size: 1.2em;">Humidity: {humidity}%</p>
743
- # </div>
744
- # </div>
745
- # </div>
746
- # <style>
747
- # .weather-theme {{
748
- # animation: backgroundAnimation 10s infinite alternate;
749
- # border-radius: 10px;
750
- # padding: 10px;
751
- # margin-bottom: 15px;
752
- # background: linear-gradient(45deg, #ffcc33, #ff6666, #ffcc33, #ff6666);
753
- # background-size: 400% 400%;
754
- # box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
755
- # transition: box-shadow 0.3s ease, background-color 0.3s ease;
756
- # }}
757
- # .weather-theme:hover {{
758
- # box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
759
- # background-position: 100% 100%;
760
- # }}
761
- # @keyframes backgroundAnimation {{
762
- # 0% {{ background-position: 0% 50%; }}
763
- # 100% {{ background-position: 100% 50%; }}
764
- # }}
765
- # .weather-content {{
766
- # display: flex;
767
- # align-items: center;
768
- # }}
769
- # .weather-icon {{
770
- # flex: 1;
771
- # }}
772
- # .weather-details {{
773
- # flex 3;
774
- # }}
775
- # </style>
776
- # """
777
- # return weather_html
778
- # except requests.exceptions.RequestException as e:
779
- # return f"<p>Failed to fetch local weather: {e}</p>"
780
-
781
- # with gr.Blocks(theme='Pijush2023/scikit-learn-pijush') as demo:
782
- # with gr.Row():
783
- # with gr.Column():
784
- # state = gr.State()
785
-
786
- # chatbot = gr.Chatbot([], elem_id="RADAR:Channel 94.1", bubble_full_width=False)
787
- # choice = gr.Radio(label="Select Style", choices=["Details", "Conversational"], value="Conversational")
788
- # retrieval_mode = gr.Radio(label="Retrieval Mode", choices=["Vector", "Knowledge-Graph"], value="Vector")
789
-
790
- # gr.Markdown("<h1 style='color: red;'>Talk to RADAR</h1>", elem_id="voice-markdown")
791
-
792
- # chat_input = gr.Textbox(show_copy_button=True, interactive=True, show_label=False, label="ASK Radar !!!", placeholder="After Prompt,click Retriever Only")
793
- # tts_choice = gr.Radio(label="Select TTS System", choices=["Alpha", "Beta", "Gamma"], value="Alpha")
794
- # retriever_button = gr.Button("Retriever")
795
-
796
- # clear_button = gr.Button("Clear")
797
- # clear_button.click(lambda:[None,None] ,outputs=[chat_input, state])
798
-
799
- # gr.Markdown("<h1 style='color: red;'>Radar Map</h1>", elem_id="Map-Radar")
800
- # location_output = gr.HTML()
801
-
802
- # # Define a single audio component
803
- # audio_output = gr.Audio(interactive=False, autoplay=True)
804
-
805
- # def stop_audio():
806
- # audio_output.stop()
807
- # return None
808
-
809
- # # Define the sequence of actions for the "Retriever" button
810
- # retriever_sequence = (
811
- # retriever_button.click(fn=stop_audio, inputs=[], outputs=[audio_output],api_name="Ask_Retriever")
812
- # .then(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query")
813
- # .then(fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output],api_name="generate_voice_response" )
814
- # .then(fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder")
815
- # .then(fn=clear_textbox, inputs=[], outputs=[chat_input])
816
- # )
817
-
818
- # # Link the "Enter" key (submit event) to the same sequence of actions
819
- # chat_input.submit(fn=stop_audio, inputs=[], outputs=[audio_output])
820
- # chat_input.submit(fn=add_message, inputs=[chatbot, chat_input], outputs=[chatbot, chat_input],api_name="voice_query").then(
821
- # fn=bot, inputs=[chatbot, choice, tts_choice, retrieval_mode], outputs=[chatbot, audio_output], api_name="generate_voice_response"
822
- # ).then(
823
- # fn=show_map_if_details, inputs=[chatbot, choice], outputs=[location_output, location_output], api_name="map_finder"
824
- # ).then(
825
- # fn=clear_textbox, inputs=[], outputs=[chat_input]
826
- # )
827
-
828
- # audio_input = gr.Audio(sources=["microphone"], streaming=True, type='numpy', every=0.1)
829
- # audio_input.stream(transcribe_function, inputs=[state, audio_input], outputs=[state, chat_input], api_name="voice_query_to_text")
830
-
831
- # with gr.Column():
832
- # image_output_1 = gr.Image(value=generate_image(hardcoded_prompt_1), width=400, height=400)
833
- # image_output_2 = gr.Image(value=generate_image(hardcoded_prompt_2), width=400, height=400)
834
- # image_output_3 = gr.Image(value=generate_image(hardcoded_prompt_3), width=400, height=400)
835
-
836
- # refresh_button = gr.Button("Refresh Images")
837
- # refresh_button.click(fn=update_images, inputs=None, outputs=[image_output_1, image_output_2, image_output_3], api_name="update_image")
838
-
839
- # demo.queue()
840
- # demo.launch(share=True)
841
-
842
-
843
  import gradio as gr
844
  import requests
845
  import os
@@ -861,7 +19,6 @@ from langchain_pinecone import PineconeVectorStore
861
  from langchain.prompts import PromptTemplate
862
  from langchain.chains import RetrievalQA
863
  from langchain.chains.conversation.memory import ConversationBufferWindowMemory
864
- from langchain.agents import Tool, initialize_agent
865
  from huggingface_hub import login
866
  from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
867
  from parler_tts import ParlerTTSForConditionalGeneration
@@ -964,6 +121,20 @@ graph = Neo4jGraph(
964
  password="B_sZbapCTZoQDWj1JrhwqElsNa-jm5Zq1m_mAnyPYog"
965
  )
966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
967
  class Entities(BaseModel):
968
  names: list[str] = Field(..., description="All the person, organization, or business entities that appear in the text")
969
 
@@ -1013,6 +184,7 @@ def structured_retriever(question: str) -> str:
1013
 
1014
  def retriever_neo4j(question: str):
1015
  structured_data = structured_retriever(question)
 
1016
  return structured_data
1017
 
1018
  _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
@@ -1046,6 +218,27 @@ _search_query = RunnableBranch(
1046
  RunnableLambda(lambda x : x["question"]),
1047
  )
1048
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1049
  def generate_answer(message, choice, retrieval_mode):
1050
  logging.debug(f"generate_answer called with choice: {choice} and retrieval_mode: {retrieval_mode}")
1051
 
@@ -1059,21 +252,12 @@ def generate_answer(message, choice, retrieval_mode):
1059
  chain_type_kwargs={"prompt": prompt_template}
1060
  )
1061
  response = qa_chain({"query": message})
1062
- return response['output'], extract_addresses(response['output'])
 
1063
  elif retrieval_mode == "Knowledge-Graph":
1064
- chain_neo4j = (
1065
- RunnableParallel(
1066
- {
1067
- "context": _search_query | retriever_neo4j,
1068
- "question": RunnablePassthrough(),
1069
- }
1070
- )
1071
- | prompt_template
1072
- | chat_model
1073
- | StrOutputParser()
1074
- )
1075
  response = chain_neo4j.invoke({"question": message})
1076
- return response['output'], extract_addresses(response['output'])
 
1077
  else:
1078
  return "Invalid retrieval mode selected.", []
1079
 
@@ -1658,3 +842,6 @@ demo.launch(share=True)
1658
 
1659
 
1660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import requests
3
  import os
 
19
  from langchain.prompts import PromptTemplate
20
  from langchain.chains import RetrievalQA
21
  from langchain.chains.conversation.memory import ConversationBufferWindowMemory
 
22
  from huggingface_hub import login
23
  from transformers.models.speecht5.number_normalizer import EnglishNumberNormalizer
24
  from parler_tts import ParlerTTSForConditionalGeneration
 
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
 
 
184
 
185
  def retriever_neo4j(question: str):
186
  structured_data = structured_retriever(question)
187
+ logging.debug(f"Structured data: {structured_data}")
188
  return structured_data
189
 
190
  _template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a standalone question,
 
218
  RunnableLambda(lambda x : x["question"]),
219
  )
220
 
221
+ template = """Answer the question based only on the following context:
222
+ {context}
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
 
 
252
  chain_type_kwargs={"prompt": prompt_template}
253
  )
254
  response = qa_chain({"query": message})
255
+ logging.debug(f"Vector response: {response}")
256
+ return response['result'], extract_addresses(response['result'])
257
  elif retrieval_mode == "Knowledge-Graph":
 
 
 
 
 
 
 
 
 
 
 
258
  response = chain_neo4j.invoke({"question": message})
259
+ logging.debug(f"Knowledge-Graph response: {response}")
260
+ return response, extract_addresses(response)
261
  else:
262
  return "Invalid retrieval mode selected.", []
263
 
 
842
 
843
 
844
 
845
+
846
+
847
+