File size: 18,566 Bytes
7a1c9b8
ab2028a
a3ff20d
 
b2112fe
 
a09b6d4
a2cc35d
 
7a1263d
e4660a4
 
 
 
 
32e0205
21b79b9
 
 
e4660a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55b6a72
b2112fe
 
06a38bb
a3ff20d
8001ff3
 
 
 
 
 
 
 
 
8761650
9b427c0
df15024
 
9b427c0
ed2227d
e3fd3dc
9b427c0
 
8001ff3
ed2227d
434909e
8001ff3
 
 
 
 
 
 
 
 
 
a09b6d4
 
 
 
 
ff28ea7
06a38bb
 
 
 
 
ff28ea7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f98abe0
8bb3175
 
 
 
 
 
 
 
 
 
7a50d25
e74a6d5
7a50d25
 
 
 
 
dec3ffb
7a50d25
 
dec3ffb
8bb3175
7a50d25
a3ff20d
 
 
 
f98abe0
 
 
 
 
ca883bf
f98abe0
 
662683c
a3ff20d
 
 
 
f98abe0
a2ef30f
29dc5a5
a2ef30f
f49c4dc
d4b4467
 
3c12ec8
d4b4467
 
 
0cd86bb
3c12ec8
e71a574
3c12ec8
 
 
 
92bdd1d
f1d9431
72edae7
3f84de1
3c12ec8
 
cdd7baf
3c12ec8
 
 
 
 
 
cdd7baf
 
3c12ec8
8750972
3c12ec8
8750972
 
 
 
3c12ec8
8750972
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c12ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f84de1
3c12ec8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f84de1
 
 
3c12ec8
 
d4b4467
 
 
a2cc35d
06a38bb
ff28ea7
a3ff20d
ff28ea7
a3ff20d
 
 
ff28ea7
a3ff20d
06a38bb
e4660a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff28ea7
a3ff20d
 
ff28ea7
06a38bb
ff28ea7
 
 
7d98fee
ff28ea7
55b6a72
ff28ea7
 
 
 
 
 
 
 
a3ff20d
 
b6dfb48
700258a
8e5029d
 
5b25129
8e5029d
 
23028aa
8e5029d
5b25129
23028aa
 
8e5029d
 
8f67fbb
8e5029d
5b25129
23028aa
 
8e5029d
700258a
a3ff20d
 
ff28ea7
55b6a72
f49c4dc
 
 
714d3fb
 
e074b34
 
a162b85
 
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
2bf93a0
a162b85
 
 
da4372a
 
d945d64
da4372a
 
 
 
 
 
 
 
f49c4dc
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
import os
import streamlit as st
import json
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.animation as animation
import time
from PIL import Image
from streamlit_image_comparison import image_comparison
import numpy as np
#import chromadb

from textwrap import dedent
import google.generativeai as genai

api_key = os.environ["OPENAI_API_KEY"]
from openai import OpenAI

oai_client = OpenAI()

import numpy as np
# Assuming chromadb and TruLens are correctly installed and configured
#from chromadb.utils.embedding_functions import

# Google Langchain
from langchain_google_genai import GoogleGenerativeAI

#Crew imports
from crewai import Agent, Task, Crew, Process

# Retrieve API Key from Environment Variable
GOOGLE_AI_STUDIO = os.environ.get('GOOGLE_API_KEY')

# Ensure the API key is available
if not GOOGLE_AI_STUDIO:
    raise ValueError("API key not found. Please set the GOOGLE_AI_STUDIO2 environment variable.")

# Set gemini_llm
gemini_llm = GoogleGenerativeAI(model="gemini-pro", google_api_key=GOOGLE_AI_STUDIO)



# CrewAI ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


def crewai_process_gemini(research_topic):
    # Define your agents with roles and goals
    GeminiAgent = Agent(
        role='Story Writer',
        goal='To create a story from bullet points.',
        backstory="""You are an expert writer that understands how to make the average extraordinary on paper """,
        verbose=True,
        allow_delegation=False,
        llm = gemini_llm,
        tools=[
                GeminiSearchTools.gemini_search
                   
      ]

    )


    # Create tasks for your agents
    task1 = Task(
        description=f"""From {research_topic} create your story by writing at least one sentence about each bullet point 
        and make sure you have a transitional statement between scenes . BE VERBOSE.""",
        agent=GeminiAgent
    )

    # Instantiate your crew with a sequential process
    crew = Crew(
        agents=[GeminiAgent],
        tasks=[task1],
        verbose=2,
        process=Process.sequential
    )

    # Get your crew to work!
    result = crew.kickoff()
    
    return result




# Tool import
from crewai.tools.gemini_tools import GeminiSearchTools
from crewai.tools.mixtral_tools import MixtralSearchTools
from crewai.tools.zephyr_tools import ZephyrSearchTools





st.set_page_config(layout="wide")


# Animation Code +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Set up the duration for your animation
t0=0 # [hrs]
t_end=2 # [hrs]
dt=0.005 # [hrs]
# Create array for time
t=np.arange(t0,t_end+dt,dt)
frame_amount=len(t)


# Subplot 1
fig2=plt.figure(figsize=(16,9),dpi=120,facecolor=(0.8,0.8,0.8))
gs=gridspec.GridSpec(2,2)
ax0=fig2.add_subplot(gs[0,:],facecolor=(0.9,0.9,0.9))
box_object=dict(boxstyle='circle',fc=(0.1,0.9,0.9),ec='r',lw=10)
stopwatch0=ax0.text(1400,0.65,'',size=20,color='g',bbox=box_object)



def update_plot(num):

    # 1st subplot

    stopwatch0.set_text(str(round(t[num],1))+' hrs')

    return stopwatch0,



# HIN Number +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
from SPARQLWrapper import SPARQLWrapper, JSON
from streamlit_agraph import agraph, TripleStore, Node, Edge, Config
import json

# Function to load JSON data
def load_data(filename):
    with open(filename, 'r') as file:
        data = json.load(file)
    return data

# Dictionary for color codes
color_codes = {
    "residential": "#ADD8E6",
    "commercial": "#90EE90",
    "community_facilities": "#FFFF00",
    "school": "#FFFF00",
    "healthcare_facility": "#FFFF00",
    "green_space": "#90EE90",
    "utility_infrastructure": "#90EE90",
    "emergency_services": "#FF0000",
    "cultural_facilities": "#D8BFD8",
    "recreational_facilities": "#D8BFD8",
    "innovation_center": "#90EE90",
    "elderly_care_home": "#FFFF00",
    "childcare_centers": "#FFFF00",
    "places_of_worship": "#D8BFD8",
    "event_spaces": "#D8BFD8",
    "guest_housing": "#FFA500",
    "pet_care_facilities": "#FFA500",
    "public_sanitation_facilities": "#A0A0A0",
    "environmental_monitoring_stations": "#90EE90",
    "disaster_preparedness_center": "#A0A0A0",
    "outdoor_community_spaces": "#90EE90",
    # Add other types with their corresponding colors
}

# Function to draw the grid with optional highlighting

def draw_grid(data, highlight_coords=None):
    fig, ax = plt.subplots(figsize=(12, 12))
    nrows, ncols = data['size']['rows'], data['size']['columns']
    ax.set_xlim(0, ncols)
    ax.set_ylim(0, nrows)
    ax.set_xticks(range(ncols+1))
    ax.set_yticks(range(nrows+1))
    ax.grid(True)

    # Draw roads with a specified grey color
    road_color = "#606060"  # Light grey; change to "#505050" for dark grey
    for road in data.get('roads', []):  # Check for roads in the data
        start, end = road['start'], road['end']
        # Determine if the road is vertical or horizontal based on start and end coordinates
        if start[0] == end[0]:  # Vertical road
            for y in range(min(start[1], end[1]), max(start[1], end[1]) + 1):
                ax.add_patch(plt.Rectangle((start[0], nrows-y-1), 1, 1, color=road['color']))
        else:  # Horizontal road
            for x in range(min(start[0], end[0]), max(start[0], end[0]) + 1):
                ax.add_patch(plt.Rectangle((x, nrows-start[1]-1), 1, 1, color=road['color']))

    # Draw buildings
    for building in data['buildings']:
        coords = building['coords']
        b_type = building['type']
        size = building['size']
        color = color_codes.get(b_type, '#FFFFFF')  # Default color is white if not specified
        
        if highlight_coords and (coords[0], coords[1]) == tuple(highlight_coords):
            highlighted_color = "#FFD700"  # Gold for highlighting
            ax.add_patch(plt.Rectangle((coords[1], nrows-coords[0]-size), size, size, color=highlighted_color, edgecolor='black', linewidth=2))
        else:
            ax.add_patch(plt.Rectangle((coords[1], nrows-coords[0]-size), size, size, color=color, edgecolor='black', linewidth=1))
            ax.text(coords[1]+0.5*size, nrows-coords[0]-0.5*size, b_type, ha='center', va='center', fontsize=8, color='black')

    ax.set_xlabel('Columns')
    ax.set_ylabel('Rows')
    ax.set_title('Village Layout with Color Coding')
    return fig

# Title ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    
# Tabs +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# Create the main app with three tabs
tab1, tab2, tab3 = st.tabs(["Introduction","Green Village", "Control Room"])


with tab1:
    
    st.header("RAGE - A day in the Life of Aya City")

    # Creating columns for the layout
    col1, col2 = st.columns([1, 2])
    
    # Displaying the image in the left column
    with col1:
        image = Image.open('./data/intro_image.jpg')
        st.image(image, caption='Green Open Data City Aya')

    # Displaying the text above on the right
    with col2:
        query = '''
        On his first day at Quantum Data Institute in Green Open Data City Aya, Elian marveled at the city’s harmonious blend of technology and nature. 
        Guided to his mentor, Dr. Maya Lior, a pioneer in urban data ecosystems, their discussion quickly centered on Aya’s innovative design. 
        Dr. Lior explained data analytics and green technologies were intricately woven into the city's infrastructure, and how they used
        a Custom GPT called Green Data City to create the design.
    
        To interact with the Green Data City design tool click the button below.
        '''
        st.markdown(query)
    
        # Displaying the audio player below the text
    
        voice_option = st.selectbox(
        'Choose a voice:',
        ['alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer']
        )
    
        if st.button('Convert to Speech'):
            if query:
                try:
                    response = oai_client.audio.speech.create(
                        model="tts-1",
                        voice=voice_option,
                        input=query,
                    )
                    
                    # Stream or save the response as needed
                    # For demonstration, let's assume we save then provide a link for downloading
                    audio_file_path = "output.mp3"
                    response.stream_to_file(audio_file_path)
                    
                    # Display audio file to download
                    st.audio(audio_file_path, format='audio/mp3')
                    st.success("Conversion successful!")
                    
                    # Displaying the image with the same name as the selected scene
                    image_file_path = f"./data/{selected_scene}.jpg"  # Adjust the directory as needed
                    try:
                        st.image(image_file_path, caption=f"Scene: {selected_scene}")
                        """All images generated by Dall-E"""
                    except Exception as e:
                        st.error(f"An error occurred while displaying the image: {e}")
                        
                except Exception as e:
                    st.error(f"An error occurred: {e}")
            else:
                st.error("Please enter some text to convert.")
        #st.audio('intro_audio.mp3')
        
        
        st.header("Custom GPT Engineering Tools")
        st.link_button("Create JSON Data for a Green Data Village Population 10,000", "https://chat.openai.com/g/g-4bPJUaHS8-create-a-green-data-village")
        
    st.write("Explanation of the Custom GPT")
    st.write("""
    On clicking "Create Data Village" create a Green Data Village following the 4 Steps below.   Output a JSON file similar to the Example by complete the four Steps.
    To generate the provided JSON code, I would instruct a custom GPT to create a detailed description of a hypothetical smart city layout, named "Green Smart Village", with a population of 10,000. This layout should include a grid size of 21x21, a list of buildings and roads, each with specific attributes:
    
    Step 1:  General Instructions:
    Generate a smart city layout for "Green Smart Village" with a 21x21 grid. Include a population of 10,000.
    
    Step 2:  Buildings:
    For each building, specify its coordinates on the grid, type (e.g., residential, commercial, healthcare facility), size (in terms of the grid), color, and equipped sensors (e.g., smart meters, water flow sensors).
    Types of buildings should vary and include residential, commercial, community facilities, school, healthcare facility, green space, utility infrastructure, emergency services, cultural facilities, recreational facilities, innovation center, elderly care home, childcare centers, places of worship, event spaces, guest housing, pet care facilities, public sanitation facilities, environmental monitoring stations, disaster preparedness center, outdoor community spaces, typical road, and typical road crossing.
    
    Step 3: Assign each building unique sensors based on its type, ensuring a mix of technology like smart meters, occupancy sensors, smart lighting systems, and environmental monitoring sensors.
    
    Step 4: Roads:
    Detail the roads' start and end coordinates, color, and sensors installed.
    Ensure roads connect significant areas of the city, providing access to all buildings. Equip roads with sensors for traffic flow, smart streetlights, and pollution monitoring.  MAKE SURE ALL BUILDINGS HAVE ACCESS TO A ROAD.
    
    This test scenario would evaluate the model's ability to creatively assemble a smart city plan with diverse infrastructure and technology implementations, reflecting real-world urban planning challenges and the integration of smart technologies for sustainable and efficient city management.
    
    Example: 
    {
      "city": "City Name",
      "population": "Population Size",
      "size": {
        "rows": "Number of Rows",
        "columns": "Number of Columns"
      },
      "buildings": [
        {
          "coords": ["X", "Y"],
          "type": "Building Type",
          "size": "Building Size",
          "color": "Building Color",
          "sensors": ["Sensor Types"]
        }
      ],
      "roads": [
        {
          "start": ["X Start", "Y Start"],
          "end": ["X End", "Y End"],
          "color": "Road Color",
          "sensors": ["Sensor Types"]
        }
      ]
    }
        
        
    
    """)

with tab2:

    st.header("Green Smart Village Application")

    # Divide the page into three columns
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.header("Today's Agenda")
        st.write("1. Morning Meeting\n2. Review Project Plans\n3. Lunch Break\n4. Site Visit\n5. Evening Wrap-up")
        
        st.header("Agent Advisors")
        st.write("Would you like to optimize your HIN number?")

        # Selection box for the function to execute
        process_selection = st.selectbox(
            'Choose the process to run:',
            ('crewai_process_gemini', 'crewai_process_mixtral_crazy', 'crewai_process_mixtral_normal', 'crewai_process_zephyr_normal', 'crewai_process_phi2')
        )
    
        # Button to execute the chosen function
        if st.button('Run Process'):
            if research_topic:  # Ensure there's a topic provided
                if process_selection == 'crewai_process_gemini':
                    result = crewai_process_gemini(research_topic)
                elif process_selection == 'crewai_process_mixtral_crazy':
                    result = crewai_process_mixtral_crazy(research_topic)
                elif process_selection == 'crewai_process_mixtral_normal':
                    result = crewai_process_mixtral_normal(research_topic)
                elif process_selection == 'crewai_process_zephyr_normal':
                    result = crewai_process_zephyr_normal(research_topic)
                elif process_selection == 'crewai_process_phi2':
                    result = crewai_process_phi2(research_topic)
                st.write(result)
            else:
                st.warning('Please enter a research topic.')
            
            st.header("My Incentive")
            st.write("Total incentive for HIN optimization")
    
    with col2:
        st.header("Green Smart Village Layout")
        data = load_data('grid.json')  # Ensure this path is correct
        
        # Dropdown for selecting a building
        building_options = [f"{bld['type']} at ({bld['coords'][0]}, {bld['coords'][1]})" for bld in data['buildings']]
        selected_building = st.selectbox("Select a building to highlight:", options=building_options)
        selected_index = building_options.index(selected_building)
        selected_building_coords = data['buildings'][selected_index]['coords']

        # Draw the grid with the selected building highlighted
        fig = draw_grid(data, highlight_coords=selected_building_coords)
        st.pyplot(fig)
        
        # Assuming sensors are defined in your data, display them
        sensors = data['buildings'][selected_index].get('sensors', [])
        st.write(f"Sensors in selected building: {', '.join(sensors)}")
        
    with col3:
        st.header("Check Your HIN Number")
        # config = Config(height=400, width=400, nodeHighlightBehavior=True, highlightColor="#F7A7A6", directed=True, collapsible=True)


        if sensors:  # Check if there are sensors to display
            graph_store = TripleStore()
            building_name = f"{data['buildings'][selected_index]['type']} ({selected_building_coords[0]}, {selected_building_coords[1]})"
            
            # Iterate through each sensor and create a triple linking it to the building
            for sensor in sensors:
                sensor_id = f"Sensor: {sensor}"  # Label for sensor nodes
                # Correctly add the triple without named arguments
                graph_store.add_triple(building_name, "has_sensor", sensor_id)
        
            # Configuration for the graph visualization
            agraph_config = Config(height=300, width=300, nodeHighlightBehavior=True, highlightColor="#F7A7A6", directed=True, collapsible=True)
        
            # Display the graph
            agraph(nodes=graph_store.getNodes(), edges=graph_store.getEdges(), config=agraph_config)

    

        hin_number = st.text_input("Enter your HIN number:")
        if hin_number:
            st.write("HIN number details...")  # Placeholder for actual HIN number check

with tab3:
   
    st.header("Control Room")
    st.write("Synthetic data should be used to drive control room")



    """
    Smart meters
    
    Water flow sensors
    
    Temperature and humidity sensors
    
    Occupancy sensors
    
    HVAC control systems
    
    Smart lighting
    
    Security cameras
    
    Indoor air quality sensors
    
    Smart lighting systems
    
    Energy consumption monitors
    
    Patient monitoring systems
    
    Environmental monitoring sensors
    
    Energy management systems
    
    Soil moisture sensors
    
    Smart irrigation systems
    
    Leak detection sensors
    
    Grid monitoring sensors
    
    GPS tracking for vehicles
    
    Smart building sensors
    
    Dispatch management systems
    
    High-speed internet connectivity
    
    Energy consumption monitoring
    
    Smart security systems
    
    Environmental control systems
    
    Security systems
    
    Smart HVAC systems
    
    Smart locks
    
    Water usage monitoring
    
    Smart inventory management systems
    
    Waste level sensors
    
    Fleet management systems for sanitation vehicles
    
    Air quality sensors
    
    Weather stations
    
    Pollution monitors
    
    Early warning systems
    
    Communication networks
    
    Adaptive lighting systems
    
    Traffic flow sensors
    
    Smart streetlights 
    
    """


    """
    Animation Code ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    fig2=plt.figure(figsize=(16,9),dpi=120,facecolor=(0.8,0.8,0.8))
    gs=gridspec.GridSpec(2,2)
    stopwatch_ani=animation.FuncAnimation(fig2,update_plot,frames=frame_amount,interval=20,repeat=True,blit=True)
    st.pyplot(fig2)
    """