Zayeemk commited on
Commit
16ea665
·
verified ·
1 Parent(s): 069dbdc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +755 -755
app.py CHANGED
@@ -1,755 +1,755 @@
1
- """
2
- GreenPath - AI & Data Analytics Platform for Reducing Shipment CO₂ Emissions
3
- Professional Streamlit Frontend with Eco-Friendly Design
4
- """
5
-
6
- import streamlit as st
7
- import pandas as pd
8
- import plotly.express as px
9
- import plotly.graph_objects as go
10
- from plotly.subplots import make_subplots
11
- import requests
12
- import sys
13
- import os
14
- from datetime import datetime, timedelta
15
- import numpy as np
16
-
17
- # Add src directory to path
18
- sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
19
-
20
- from emissions.emission_calculator import EmissionCalculator, TransportMode
21
- from route_optimizer.green_route_optimizer import GreenRouteOptimizer
22
-
23
- # Page configuration
24
- st.set_page_config(
25
- page_title="GreenPath - CO₂ Emission Tracker",
26
- page_icon="🌱",
27
- layout="wide",
28
- initial_sidebar_state="expanded"
29
- )
30
-
31
- # Custom CSS for eco-friendly theme
32
- st.markdown("""
33
- <style>
34
-
35
- .main-header {
36
- background: linear-gradient(90deg, #2ECC71 0%, #27AE60 100%);
37
- padding: 2rem;
38
- border-radius: 10px;
39
- color: white;
40
- text-align: center;
41
- margin-bottom: 2rem;
42
- position: relative;
43
- z-index: 1;
44
- }
45
-
46
- .metric-card {
47
- background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
48
- padding: 1.5rem;
49
- border-radius: 10px;
50
- box-shadow: 0 2px 10px rgba(0,0,0,0.1);
51
- border-left: 4px solid #2ECC71;
52
- margin-bottom: 1rem;
53
- }
54
-
55
- .green-button {
56
- background-color: #2ECC71;
57
- color: white;
58
- border: none;
59
- padding: 0.5rem 1rem;
60
- border-radius: 5px;
61
- cursor: pointer;
62
- }
63
-
64
- .sidebar .sidebar-content {
65
- background-color: #F8F9FA;
66
- }
67
-
68
- .stSelectbox > div > div {
69
- background-color: white !important;
70
- border: 1px solid #E0E0E0 !important;
71
- border-radius: 8px !important;
72
- color: #34495E !important;
73
- }
74
-
75
- .stSelectbox > div > div > div {
76
- color: #34495E !important;
77
- font-weight: 500 !important;
78
- }
79
-
80
- .eco-badge {
81
- background-color: #2ECC71;
82
- color: white;
83
- padding: 0.2rem 0.5rem;
84
- border-radius: 15px;
85
- font-size: 0.8rem;
86
- font-weight: bold;
87
- }
88
-
89
-
90
- /* Navigation styling */
91
- .stRadio > div {
92
- background-color: transparent;
93
- padding: 0.5rem;
94
- border-radius: 8px;
95
- }
96
-
97
- .stRadio > div > label {
98
- background-color: #FFFFFF;
99
- border: 1px solid #E0E0E0;
100
- border-radius: 8px;
101
- margin: 4px 0;
102
- padding: 8px 12px;
103
- cursor: pointer;
104
- transition: all 0.3s ease;
105
- display: block;
106
- }
107
-
108
- .stRadio > div > label:hover {
109
- background-color: #E8F5E8;
110
- border-color: #2ECC71;
111
- color: #2ECC71;
112
- }
113
-
114
- .stRadio > div > label > div {
115
- color: #34495E !important;
116
- font-size: 14px !important;
117
- font-weight: 500;
118
- margin: 0;
119
- }
120
-
121
- .stRadio > div > label[data-checked="true"] {
122
- background-color: #2ECC71;
123
- border-color: #2ECC71;
124
- color: white;
125
- }
126
-
127
- .stRadio > div > label[data-checked="true"] > div {
128
- color: white !important;
129
- }
130
-
131
- /* Emoji fix */
132
- .stRadio label {
133
- font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
134
- }
135
-
136
- /* Sidebar styling */
137
- .css-1d391kg {
138
- background-color: #F8F9FA;
139
- }
140
-
141
- /* Metric styling */
142
- [data-testid="metric-container"] {
143
- background-color: white;
144
- border: 1px solid #E0E0E0;
145
- padding: 1rem;
146
- border-radius: 8px;
147
- border-left: 4px solid #2ECC71;
148
- }
149
- </style>
150
- """, unsafe_allow_html=True)
151
-
152
- # Initialize components
153
- @st.cache_resource
154
- def init_components():
155
- calculator = EmissionCalculator()
156
- optimizer = GreenRouteOptimizer()
157
- return calculator, optimizer
158
-
159
- calculator, optimizer = init_components()
160
-
161
- # Header
162
- st.markdown("""
163
- <div class="main-header">
164
- <h1>🌱 GreenPath</h1>
165
- <h3>AI-Powered Platform for Reducing Shipment CO₂ Emissions</h3>
166
- <p>Designed by Sayed Mohd Zayeem Khateeb</p>
167
- </div>
168
- """, unsafe_allow_html=True)
169
-
170
- # Sidebar
171
- with st.sidebar:
172
- # Custom GreenPath logo
173
- st.markdown("""
174
- <div style="text-align: center; padding: 1rem; background: linear-gradient(135deg, #2ECC71, #27AE60); border-radius: 10px; margin-bottom: 1rem;">
175
- <h2 style="color: white; margin: 0; font-size: 24px;">🌱 GreenPath</h2>
176
- <p style="color: #E8F8F5; margin: 0; font-size: 12px;">AI Emission Tracker</p>
177
- </div>
178
- """, unsafe_allow_html=True)
179
-
180
- st.markdown("### 📍 Navigate")
181
-
182
- # Navigation with better visibility
183
- nav_options = {
184
- "🏠 Dashboard": "Dashboard",
185
- "🧮 Emission Calculator": "Emission Calculator",
186
- "🗺️ Route Optimizer": "Route Optimizer",
187
- "📊 Scenario Analysis": "Scenario Analysis",
188
- "📈 Analytics": "Analytics"
189
- }
190
-
191
- page = st.selectbox(
192
- "Choose a page:",
193
- options=list(nav_options.keys()),
194
- label_visibility="collapsed",
195
- key="navigation"
196
- )
197
-
198
- st.markdown("---")
199
- st.markdown("### 🌍 Quick Stats")
200
-
201
- # Sample KPIs
202
- col1, col2 = st.columns(2)
203
- with col1:
204
- st.metric("CO₂ Saved", "2.4t", "↓ 22%")
205
- with col2:
206
- st.metric("Routes Optimized", "156", "↑ 15%")
207
-
208
- # Main content based on selected page
209
- if page == "🏠 Dashboard":
210
- st.markdown("## 📊 Emission Overview Dashboard")
211
-
212
- # Top KPIs
213
- col1, col2, col3, col4 = st.columns(4)
214
-
215
- with col1:
216
- st.markdown("""
217
- <div class="metric-card">
218
- <h3 style="color: #2ECC71; margin: 0;">12.5t</h3>
219
- <p style="margin: 0; color: #7F8C8D;">Total CO₂ Emissions</p>
220
- <small style="color: #E74C3C;">↓ 18% vs last month</small>
221
- </div>
222
- """, unsafe_allow_html=True)
223
-
224
- with col2:
225
- st.markdown("""
226
- <div class="metric-card">
227
- <h3 style="color: #2ECC71; margin: 0;">22%</h3>
228
- <p style="margin: 0; color: #7F8C8D;">Emission Reduction</p>
229
- <small style="color: #27AE60;">Green routes adopted</small>
230
- </div>
231
- """, unsafe_allow_html=True)
232
-
233
- with col3:
234
- st.markdown("""
235
- <div class="metric-card">
236
- <h3 style="color: #2ECC71; margin: 0;">0.08</h3>
237
- <p style="margin: 0; color: #7F8C8D;">Avg. Emission/Shipment (kg)</p>
238
- <small style="color: #27AE60;">Industry best practice</small>
239
- </div>
240
- """, unsafe_allow_html=True)
241
-
242
- with col4:
243
- st.markdown("""
244
- <div class="metric-card">
245
- <h3 style="color: #2ECC71; margin: 0;">$1,250</h3>
246
- <p style="margin: 0; color: #7F8C8D;">Carbon Tax Savings</p>
247
- <small style="color: #27AE60;">Monthly estimate</small>
248
- </div>
249
- """, unsafe_allow_html=True)
250
-
251
- # Charts
252
- col1, col2 = st.columns(2)
253
-
254
- with col1:
255
- st.markdown("### 🚛 Emissions by Transport Mode")
256
-
257
- # Sample data for transport mode comparison
258
- modes_data = pd.DataFrame({
259
- 'Transport Mode': ['Road Truck', 'Rail', 'Ship Container', 'Air Cargo'],
260
- 'CO₂ Emissions (kg)': [62, 22, 11, 602],
261
- 'Usage %': [45, 30, 20, 5]
262
- })
263
-
264
- fig = px.bar(
265
- modes_data,
266
- x='Transport Mode',
267
- y='CO₂ Emissions (kg)',
268
- color='CO₂ Emissions (kg)',
269
- color_continuous_scale=['#2ECC71', '#E74C3C'],
270
- title="Emission Factors by Transport Mode"
271
- )
272
- fig.update_layout(showlegend=False, height=400)
273
- st.plotly_chart(fig, use_container_width=True)
274
-
275
- with col2:
276
- st.markdown("### 📈 Emission Trends")
277
-
278
- # Sample trend data
279
- emissions_data = [15.2, 14.8, 13.9, 13.1, 12.8, 12.3, 11.9, 11.5, 12.5]
280
- dates = pd.date_range(start='2024-01-01', periods=len(emissions_data), freq='M')
281
- trend_data = pd.DataFrame({
282
- 'Date': dates,
283
- 'Emissions (tonnes)': emissions_data,
284
- 'Target': [14.0] * len(emissions_data)
285
- })
286
-
287
- fig = go.Figure()
288
- fig.add_trace(go.Scatter(
289
- x=trend_data['Date'],
290
- y=trend_data['Emissions (tonnes)'],
291
- mode='lines+markers',
292
- name='Actual Emissions',
293
- line=dict(color='#2ECC71', width=3)
294
- ))
295
- fig.add_trace(go.Scatter(
296
- x=trend_data['Date'],
297
- y=trend_data['Target'],
298
- mode='lines',
299
- name='Target',
300
- line=dict(color='#E74C3C', dash='dash')
301
- ))
302
- fig.update_layout(title="Monthly Emission Trends", height=400)
303
- st.plotly_chart(fig, use_container_width=True)
304
-
305
- elif page == "🧮 Emission Calculator":
306
- st.markdown("## 🧮 CO₂ Emission Calculator")
307
- st.markdown("Calculate CO₂ emissions using the formula: **CO₂ = Distance × Weight × EmissionFactor**")
308
-
309
- col1, col2 = st.columns([2, 1])
310
-
311
- with col1:
312
- with st.form("emission_calculator"):
313
- st.markdown("### Input Parameters")
314
-
315
- col_a, col_b = st.columns(2)
316
- with col_a:
317
- distance = st.number_input("Distance (km)", min_value=0.1, value=500.0, step=10.0)
318
- weight = st.number_input("Weight (tonnes)", min_value=0.01, value=2.0, step=0.1)
319
-
320
- with col_b:
321
- transport_mode = st.selectbox(
322
- "Transport Mode",
323
- options=[mode.value for mode in TransportMode],
324
- format_func=lambda x: x.replace('_', ' ').title()
325
- )
326
-
327
- calculate_btn = st.form_submit_button("🧮 Calculate Emissions", type="primary")
328
-
329
- if calculate_btn:
330
- try:
331
- # Convert string to TransportMode enum
332
- mode_mapping = {
333
- 'road_truck': TransportMode.ROAD_TRUCK,
334
- 'road_van': TransportMode.ROAD_VAN,
335
- 'rail': TransportMode.RAIL,
336
- 'air_cargo': TransportMode.AIR_CARGO,
337
- 'ship_container': TransportMode.SHIP_CONTAINER,
338
- 'ship_bulk': TransportMode.SHIP_BULK
339
- }
340
-
341
- if transport_mode in mode_mapping:
342
- mode = mode_mapping[transport_mode]
343
- else:
344
- mode = TransportMode(transport_mode)
345
-
346
- result = calculator.calculate_emissions(distance, weight, mode)
347
-
348
- st.success("✅ Calculation Complete!")
349
-
350
- # Results display
351
- col_r1, col_r2, col_r3 = st.columns(3)
352
-
353
- with col_r1:
354
- st.metric(
355
- "CO₂ Emissions",
356
- f"{result['co2_emissions_kg']:.2f} kg",
357
- f"{result['co2_emissions_tonnes']:.3f} tonnes"
358
- )
359
-
360
- with col_r2:
361
- carbon_tax = calculator.calculate_carbon_tax_cost(result['co2_emissions_kg'])
362
- st.metric(
363
- "Carbon Tax Cost",
364
- f"${carbon_tax['carbon_tax_cost_usd']:.2f}",
365
- "@ $50/tonne CO₂"
366
- )
367
-
368
- with col_r3:
369
- st.metric(
370
- "Emission Factor",
371
- f"{result['emission_factor']:.3f}",
372
- "kg CO₂/tonne-km"
373
- )
374
-
375
- # Comparison with other modes
376
- st.markdown("### 🔄 Transport Mode Comparison")
377
- comparison_df = calculator.compare_transport_modes(distance, weight)
378
-
379
- fig = px.bar(
380
- comparison_df,
381
- x='transport_mode',
382
- y='co2_emissions_kg',
383
- color='co2_emissions_kg',
384
- color_continuous_scale=['#2ECC71', '#E74C3C'],
385
- title="CO₂ Emissions by Transport Mode"
386
- )
387
- fig.update_layout(height=400)
388
- st.plotly_chart(fig, use_container_width=True)
389
-
390
- st.dataframe(comparison_df, use_container_width=True)
391
-
392
- except Exception as e:
393
- st.error(f"❌ Calculation failed: {str(e)}")
394
-
395
- with col2:
396
- st.markdown("### 📋 Emission Factors")
397
- factors_df = calculator.get_emission_factors_table()
398
- st.dataframe(factors_df, use_container_width=True)
399
-
400
- st.markdown("### 🌱 Green Tips")
401
- st.info("""
402
- **Reduce Emissions:**
403
- - Choose rail over road when possible
404
- - Use container ships for long distances
405
- - Optimize load capacity
406
- - Consider multimodal transport
407
- """)
408
-
409
- elif page == "🗺️ Route Optimizer":
410
- st.markdown("## 🗺️ Green Route Optimizer")
411
- st.markdown("Find the most eco-friendly routes for your shipments")
412
-
413
- with st.form("route_optimizer"):
414
- col1, col2 = st.columns(2)
415
-
416
- with col1:
417
- origin = st.text_input("Origin", value="New York, NY", placeholder="Enter origin city")
418
- destination = st.text_input("Destination", value="Los Angeles, CA", placeholder="Enter destination city")
419
-
420
- with col2:
421
- weight = st.number_input("Shipment Weight (tonnes)", min_value=0.01, value=5.0, step=0.1)
422
- max_time_penalty = st.slider("Max Time Penalty (%)", 0, 50, 10)
423
-
424
- optimize_btn = st.form_submit_button("🗺️ Find Green Routes", type="primary")
425
-
426
- if optimize_btn and origin and destination:
427
- with st.spinner("🔍 Finding optimal routes..."):
428
- try:
429
- # Get route recommendations
430
- recommendations = optimizer.recommend_green_routes(origin, destination, weight)
431
-
432
- if 'success' in recommendations and recommendations['success']:
433
- st.success("✅ Route optimization complete!")
434
-
435
- route_data = recommendations['recommendations']
436
-
437
- # Display recommendations
438
- st.markdown("### 🌱 Green Route Recommendations")
439
-
440
- for i, route in enumerate(route_data):
441
- with st.expander(f"Option {i+1}: {route['transport_mode'].replace('_', ' ').title()}", expanded=(i==0)):
442
- col_a, col_b, col_c, col_d = st.columns(4)
443
-
444
- with col_a:
445
- st.metric("CO₂ Emissions", f"{route['co2_emissions_kg']:.1f} kg")
446
- with col_b:
447
- st.metric("Travel Time", f"{route['estimated_travel_time_hours']:.1f} hrs")
448
- with col_c:
449
- st.metric("Carbon Tax", f"${route['carbon_tax_cost_usd']:.2f}")
450
- with col_d:
451
- if route['emission_reduction_percent'] > 0:
452
- st.metric("Emission Reduction", f"{route['emission_reduction_percent']:.1f}%", "vs worst option")
453
- else:
454
- st.metric("Emission Impact", "Baseline", "")
455
-
456
- if i == 0:
457
- st.markdown('<span class="eco-badge">🌱 RECOMMENDED</span>', unsafe_allow_html=True)
458
-
459
- # Visualization
460
- if len(route_data) > 1:
461
- st.markdown("### 📊 Route Comparison")
462
-
463
- df_viz = pd.DataFrame(route_data)
464
-
465
- fig = make_subplots(
466
- rows=1, cols=2,
467
- subplot_titles=('CO₂ Emissions (kg)', 'Travel Time (hours)'),
468
- specs=[[{"secondary_y": False}, {"secondary_y": False}]]
469
- )
470
-
471
- fig.add_trace(
472
- go.Bar(
473
- x=df_viz['transport_mode'],
474
- y=df_viz['co2_emissions_kg'],
475
- name='CO₂ Emissions',
476
- marker_color='#2ECC71'
477
- ),
478
- row=1, col=1
479
- )
480
-
481
- fig.add_trace(
482
- go.Bar(
483
- x=df_viz['transport_mode'],
484
- y=df_viz['estimated_travel_time_hours'],
485
- name='Travel Time',
486
- marker_color='#3498DB'
487
- ),
488
- row=1, col=2
489
- )
490
-
491
- fig.update_layout(height=400, showlegend=False)
492
- st.plotly_chart(fig, use_container_width=True)
493
-
494
- else:
495
- st.error(f"❌ Route optimization failed: {recommendations.get('error', 'Unknown error')}")
496
-
497
- except Exception as e:
498
- st.error(f"❌ Error: {str(e)}")
499
-
500
- elif page == "📊 Scenario Analysis":
501
- st.markdown("## 📊 Business Impact Simulation")
502
- st.markdown("Analyze the potential impact of adopting green shipping practices")
503
-
504
- with st.form("scenario_analysis"):
505
- col1, col2 = st.columns(2)
506
-
507
- with col1:
508
- st.markdown("### 📦 Shipment Parameters")
509
- total_shipments = st.number_input("Total Monthly Shipments", min_value=1, value=1000, step=50)
510
- avg_distance = st.number_input("Average Distance (km)", min_value=1.0, value=800.0, step=50.0)
511
- avg_weight = st.number_input("Average Weight (tonnes)", min_value=0.1, value=3.0, step=0.1)
512
-
513
- with col2:
514
- st.markdown("### ⚙️ Optimization Parameters")
515
- optimization_percent = st.slider("% Shipments Using Green Routes", 0, 100, 50)
516
- current_mode = st.selectbox("Current Transport Mode", [mode.value for mode in TransportMode], index=0)
517
- carbon_tax_rate = st.number_input("Carbon Tax Rate ($/tonne CO₂)", min_value=0.0, value=50.0, step=5.0)
518
-
519
- analyze_btn = st.form_submit_button("📊 Run Scenario Analysis", type="primary")
520
-
521
- if analyze_btn:
522
- with st.spinner("🔄 Running business impact simulation..."):
523
- try:
524
- # Current emissions - use same mapping as before
525
- mode_mapping = {
526
- 'road_truck': TransportMode.ROAD_TRUCK,
527
- 'road_van': TransportMode.ROAD_VAN,
528
- 'rail': TransportMode.RAIL,
529
- 'air_cargo': TransportMode.AIR_CARGO,
530
- 'ship_container': TransportMode.SHIP_CONTAINER,
531
- 'ship_bulk': TransportMode.SHIP_BULK
532
- }
533
-
534
- if current_mode in mode_mapping:
535
- current_mode_enum = mode_mapping[current_mode]
536
- else:
537
- current_mode_enum = TransportMode(current_mode)
538
-
539
- current_emissions = calculator.calculate_emissions(avg_distance, avg_weight, current_mode_enum)
540
-
541
- # Find best green alternative - calculate manually to avoid EmissionOptimizer import
542
- available_modes = [TransportMode.ROAD_TRUCK, TransportMode.RAIL, TransportMode.SHIP_CONTAINER]
543
-
544
- # Calculate emissions for each mode and find the greenest
545
- mode_options = []
546
- for mode in available_modes:
547
- emissions = calculator.calculate_emissions(avg_distance, avg_weight, mode)
548
- mode_options.append({
549
- 'mode': mode,
550
- 'co2_emissions_kg': emissions['co2_emissions_kg'],
551
- 'emission_factor': emissions['emission_factor']
552
- })
553
-
554
- # Sort by emissions (lowest first) to find greenest option
555
- mode_options.sort(key=lambda x: x['co2_emissions_kg'])
556
- green_option = mode_options[0] if mode_options else None
557
-
558
- if not green_option:
559
- st.error("❌ No green alternatives available")
560
- st.stop()
561
-
562
- # Calculate scenario impact
563
- optimized_shipments = int(total_shipments * optimization_percent / 100)
564
- regular_shipments = total_shipments - optimized_shipments
565
-
566
- current_total = current_emissions['co2_emissions_kg'] * total_shipments
567
- optimized_total = (
568
- green_option['co2_emissions_kg'] * optimized_shipments +
569
- current_emissions['co2_emissions_kg'] * regular_shipments
570
- )
571
-
572
- savings_kg = current_total - optimized_total
573
- savings_percent = (savings_kg / current_total) * 100
574
- carbon_tax_savings = (savings_kg / 1000) * carbon_tax_rate
575
-
576
- st.success("✅ Scenario analysis complete!")
577
-
578
- # Results
579
- col1, col2, col3, col4 = st.columns(4)
580
-
581
- with col1:
582
- st.metric("Current Emissions", f"{current_total/1000:.1f} tonnes/month")
583
- with col2:
584
- st.metric("Optimized Emissions", f"{optimized_total/1000:.1f} tonnes/month")
585
- with col3:
586
- st.metric("CO₂ Savings", f"{savings_kg/1000:.1f} tonnes/month", f"{savings_percent:.1f}% reduction")
587
- with col4:
588
- st.metric("Carbon Tax Savings", f"${carbon_tax_savings:.0f}/month", f"${carbon_tax_savings*12:.0f}/year")
589
-
590
- # Visualization
591
- st.markdown("### 📈 Impact Visualization")
592
-
593
- scenario_data = pd.DataFrame({
594
- 'Scenario': ['Current', 'Optimized'],
595
- 'CO₂ Emissions (tonnes)': [current_total/1000, optimized_total/1000],
596
- 'Carbon Tax Cost ($)': [
597
- (current_total/1000) * carbon_tax_rate,
598
- (optimized_total/1000) * carbon_tax_rate
599
- ]
600
- })
601
-
602
- fig = make_subplots(
603
- rows=1, cols=2,
604
- subplot_titles=('CO₂ Emissions', 'Carbon Tax Cost'),
605
- specs=[[{"secondary_y": False}, {"secondary_y": False}]]
606
- )
607
-
608
- fig.add_trace(
609
- go.Bar(
610
- x=scenario_data['Scenario'],
611
- y=scenario_data['CO₂ Emissions (tonnes)'],
612
- name='CO₂ Emissions',
613
- marker_color=['#E74C3C', '#2ECC71']
614
- ),
615
- row=1, col=1
616
- )
617
-
618
- fig.add_trace(
619
- go.Bar(
620
- x=scenario_data['Scenario'],
621
- y=scenario_data['Carbon Tax Cost ($)'],
622
- name='Carbon Tax Cost',
623
- marker_color=['#E74C3C', '#2ECC71']
624
- ),
625
- row=1, col=2
626
- )
627
-
628
- fig.update_layout(height=400, showlegend=False)
629
- st.plotly_chart(fig, use_container_width=True)
630
-
631
- # Business benefits
632
- st.markdown("### 💼 Business Benefits")
633
-
634
- benefits_col1, benefits_col2 = st.columns(2)
635
-
636
- with benefits_col1:
637
- st.markdown("""
638
- **Environmental Impact:**
639
- - ♻️ Reduced carbon footprint
640
- - 🌱 Enhanced sustainability profile
641
- - 📊 ESG score improvement
642
- - 🏆 Industry leadership positioning
643
- """)
644
-
645
- with benefits_col2:
646
- st.markdown(f"""
647
- **Financial Benefits:**
648
- - 💰 ${carbon_tax_savings*12:.0f} annual tax savings
649
- - 📈 Potential green financing access
650
- - 🎯 Regulatory compliance readiness
651
- - 💡 Operational efficiency gains
652
- """)
653
-
654
- except Exception as e:
655
- st.error(f"❌ Analysis failed: {str(e)}")
656
- st.write(f"Debug info: {type(e).__name__}: {e}")
657
- import traceback
658
- st.code(traceback.format_exc())
659
-
660
- elif page == "📈 Analytics":
661
- st.markdown("## 📈 Advanced Analytics")
662
-
663
- # Sample analytics data
664
- st.markdown("### 🎯 Performance Metrics")
665
-
666
- col1, col2, col3 = st.columns(3)
667
-
668
- with col1:
669
- st.markdown("""
670
- <div class="metric-card">
671
- <h4 style="color: #2ECC71; margin: 0;">Route Efficiency Score</h4>
672
- <h2 style="margin: 0;">87/100</h2>
673
- <p style="margin: 0; color: #7F8C8D;">Above industry average</p>
674
- </div>
675
- """, unsafe_allow_html=True)
676
-
677
- with col2:
678
- st.markdown("""
679
- <div class="metric-card">
680
- <h4 style="color: #2ECC71; margin: 0;">Green Route Adoption</h4>
681
- <h2 style="margin: 0;">68%</h2>
682
- <p style="margin: 0; color: #7F8C8D;">Target: 75%</p>
683
- </div>
684
- """, unsafe_allow_html=True)
685
-
686
- with col3:
687
- st.markdown("""
688
- <div class="metric-card">
689
- <h4 style="color: #2ECC71; margin: 0;">Emission Intensity</h4>
690
- <h2 style="margin: 0;">0.045</h2>
691
- <p style="margin: 0; color: #7F8C8D;">kg CO₂/tonne-km</p>
692
- </div>
693
- """, unsafe_allow_html=True)
694
-
695
- # Regional analysis
696
- st.markdown("### 🌍 Regional Emission Analysis")
697
-
698
- regional_data = pd.DataFrame({
699
- 'Region': ['North America', 'Europe', 'Asia Pacific', 'Latin America'],
700
- 'Emissions (tonnes)': [45.2, 32.1, 28.7, 15.3],
701
- 'Shipments': [450, 320, 380, 180],
702
- 'Avg Distance (km)': [1200, 800, 950, 600]
703
- })
704
-
705
- fig = px.scatter(
706
- regional_data,
707
- x='Shipments',
708
- y='Emissions (tonnes)',
709
- size='Avg Distance (km)',
710
- color='Region',
711
- title="Regional Emission vs Shipment Volume"
712
- )
713
- fig.update_layout(height=500)
714
- st.plotly_chart(fig, use_container_width=True)
715
-
716
- st.dataframe(regional_data, use_container_width=True)
717
-
718
-
719
- # Footer
720
- st.markdown("---")
721
- st.markdown("## 👨‍💻 Developer Details")
722
- st.markdown("""
723
- <div style="text-align: center; color: #2C3E50; padding: 2rem; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
724
- <div style="margin-bottom: 1rem;">
725
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" style="width: 60px; height: 60px;">
726
- <defs>
727
- <linearGradient id="zkGradient" x1="0%" y1="0%" x2="100%" y2="100%">
728
- <stop offset="0%" style="stop-color:#2ECC71;stop-opacity:1" />
729
- <stop offset="100%" style="stop-color:#27AE60;stop-opacity:1" />
730
- </linearGradient>
731
- </defs>
732
- <g transform="translate(50, 50)">
733
- <path d="M10 20 L70 20 L70 35 L35 75 L70 75 L70 90 L10 90 L10 75 L45 35 L10 35 Z"
734
- fill="url(#zkGradient)"
735
- stroke="#1E8449"
736
- stroke-width="1"/>
737
- <path d="M80 20 L95 20 L95 50 L110 20 L130 20 L110 55 L130 90 L110 90 L95 65 L95 90 L80 90 Z"
738
- fill="url(#zkGradient)"
739
- stroke="#1E8449"
740
- stroke-width="1"/>
741
- </g>
742
- </svg>
743
- </div>
744
- <p style="font-size: 1.2rem; color: #2C3E50; margin-bottom: 0.5rem;"><strong>GreenPath</strong> - AI-Powered CO₂ Emission Reduction Platform</p>
745
- <p style="font-size: 1.1rem; color: #34495E; margin-bottom: 1rem;">Designed and Developed by <strong>Sayed Mohd Zayeem Khateeb</strong></p>
746
- <div style="margin: 1rem 0;">
747
- <a href="https://github.com/zayeemskhateeb-cloud" target="_blank" style="margin: 0 10px; text-decoration: none; color: #2ECC71; font-weight: bold; font-size: 1rem;">🌐 GitHub</a> |
748
- <a href="https://www.linkedin.com/in/zayeemkhateeb" target="_blank" style="margin: 0 10px; text-decoration: none; color: #2ECC71; font-weight: bold; font-size: 1rem;">💼 LinkedIn</a> |
749
- <a href="mailto:zayeem.s.khateeb@gmail.com" style="margin: 0 10px; text-decoration: none; color: #2ECC71; font-weight: bold; font-size: 1rem;">📧 Email</a>
750
- </div>
751
- <p style="font-size: 1rem; color: #7F8C8D; margin-top: 1rem;">
752
- Specialized in AI/ML, Data Analytics, and Sustainable Technology Solutions
753
- </p>
754
- </div>
755
- """, unsafe_allow_html=True)
 
1
+ """
2
+ GreenPath - AI & Data Analytics Platform for Reducing Shipment CO₂ Emissions
3
+ Professional Streamlit Frontend with Eco-Friendly Design
4
+ """
5
+
6
+ import streamlit as st
7
+ import pandas as pd
8
+ import plotly.express as px
9
+ import plotly.graph_objects as go
10
+ from plotly.subplots import make_subplots
11
+ import requests
12
+ import sys
13
+ import os
14
+ from datetime import datetime, timedelta
15
+ import numpy as np
16
+
17
+ # Add src directory to path
18
+ sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
19
+
20
+ from emissions.emission_calculator import EmissionCalculator, TransportMode
21
+ from route_optimizer.green_route_optimizer import GreenRouteOptimizer
22
+
23
+ # Page configuration
24
+ st.set_page_config(
25
+ page_title="GreenPath - CO₂ Emission Tracker",
26
+ page_icon="🌱",
27
+ layout="wide",
28
+ initial_sidebar_state="expanded"
29
+ )
30
+
31
+ # Custom CSS for eco-friendly theme
32
+ st.markdown("""
33
+ <style>
34
+
35
+ .main-header {
36
+ background: linear-gradient(90deg, #2ECC71 0%, #27AE60 100%);
37
+ padding: 2rem;
38
+ border-radius: 10px;
39
+ color: white;
40
+ text-align: center;
41
+ margin-bottom: 2rem;
42
+ position: relative;
43
+ z-index: 1;
44
+ }
45
+
46
+ .metric-card {
47
+ background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
48
+ padding: 1.5rem;
49
+ border-radius: 10px;
50
+ box-shadow: 0 2px 10px rgba(0,0,0,0.1);
51
+ border-left: 4px solid #2ECC71;
52
+ margin-bottom: 1rem;
53
+ }
54
+
55
+ .green-button {
56
+ background-color: #2ECC71;
57
+ color: white;
58
+ border: none;
59
+ padding: 0.5rem 1rem;
60
+ border-radius: 5px;
61
+ cursor: pointer;
62
+ }
63
+
64
+ .sidebar .sidebar-content {
65
+ background-color: #F8F9FA;
66
+ }
67
+
68
+ .stSelectbox > div > div {
69
+ background-color: white !important;
70
+ border: 1px solid #E0E0E0 !important;
71
+ border-radius: 8px !important;
72
+ color: #34495E !important;
73
+ }
74
+
75
+ .stSelectbox > div > div > div {
76
+ color: #34495E !important;
77
+ font-weight: 500 !important;
78
+ }
79
+
80
+ .eco-badge {
81
+ background-color: #2ECC71;
82
+ color: white;
83
+ padding: 0.2rem 0.5rem;
84
+ border-radius: 15px;
85
+ font-size: 0.8rem;
86
+ font-weight: bold;
87
+ }
88
+
89
+
90
+ /* Navigation styling */
91
+ .stRadio > div {
92
+ background-color: transparent;
93
+ padding: 0.5rem;
94
+ border-radius: 8px;
95
+ }
96
+
97
+ .stRadio > div > label {
98
+ background-color: #FFFFFF;
99
+ border: 1px solid #E0E0E0;
100
+ border-radius: 8px;
101
+ margin: 4px 0;
102
+ padding: 8px 12px;
103
+ cursor: pointer;
104
+ transition: all 0.3s ease;
105
+ display: block;
106
+ }
107
+
108
+ .stRadio > div > label:hover {
109
+ background-color: #E8F5E8;
110
+ border-color: #2ECC71;
111
+ color: #2ECC71;
112
+ }
113
+
114
+ .stRadio > div > label > div {
115
+ color: #34495E !important;
116
+ font-size: 14px !important;
117
+ font-weight: 500;
118
+ margin: 0;
119
+ }
120
+
121
+ .stRadio > div > label[data-checked="true"] {
122
+ background-color: #2ECC71;
123
+ border-color: #2ECC71;
124
+ color: white;
125
+ }
126
+
127
+ .stRadio > div > label[data-checked="true"] > div {
128
+ color: white !important;
129
+ }
130
+
131
+ /* Emoji fix */
132
+ .stRadio label {
133
+ font-family: "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
134
+ }
135
+
136
+ /* Sidebar styling */
137
+ .css-1d391kg {
138
+ background-color: #F8F9FA;
139
+ }
140
+
141
+ /* Metric styling */
142
+ [data-testid="metric-container"] {
143
+ background-color: white;
144
+ border: 1px solid #E0E0E0;
145
+ padding: 1rem;
146
+ border-radius: 8px;
147
+ border-left: 4px solid #2ECC71;
148
+ }
149
+ </style>
150
+ """, unsafe_allow_html=True)
151
+
152
+ # Initialize components
153
+ @st.cache_resource
154
+ def init_components():
155
+ calculator = EmissionCalculator()
156
+ optimizer = GreenRouteOptimizer()
157
+ return calculator, optimizer
158
+
159
+ calculator, optimizer = init_components()
160
+
161
+ # Header
162
+ st.markdown("""
163
+ <div class="main-header">
164
+ <h1>🌱 GreenPath</h1>
165
+ <h3>AI-Powered Platform for Reducing Shipment CO₂ Emissions</h3>
166
+ <p>Designed by Sayed Mohd Zayeem Khateeb</p>
167
+ </div>
168
+ """, unsafe_allow_html=True)
169
+
170
+ # Sidebar
171
+ with st.sidebar:
172
+ # Custom GreenPath logo
173
+ st.markdown("""
174
+ <div style="text-align: center; padding: 1rem; background: linear-gradient(135deg, #2ECC71, #27AE60); border-radius: 10px; margin-bottom: 1rem;">
175
+ <h2 style="color: white; margin: 0; font-size: 24px;">🌱 GreenPath</h2>
176
+ <p style="color: #E8F8F5; margin: 0; font-size: 12px;">AI Emission Tracker</p>
177
+ </div>
178
+ """, unsafe_allow_html=True)
179
+
180
+ st.markdown("### 📍 Navigate")
181
+
182
+ # Navigation with better visibility
183
+ nav_options = {
184
+ "🏠 Dashboard": "Dashboard",
185
+ "🧮 Emission Calculator": "Emission Calculator",
186
+ "🗺️ Route Optimizer": "Route Optimizer",
187
+ "📊 Scenario Analysis": "Scenario Analysis",
188
+ "📈 Analytics": "Analytics"
189
+ }
190
+
191
+ page = st.selectbox(
192
+ "Choose a page:",
193
+ options=list(nav_options.keys()),
194
+ label_visibility="collapsed",
195
+ key="navigation"
196
+ )
197
+
198
+ st.markdown("---")
199
+ st.markdown("### 🌍 Quick Stats")
200
+
201
+ # Sample KPIs
202
+ col1, col2 = st.columns(2)
203
+ with col1:
204
+ st.metric("CO₂ Saved", "2.4t", "↓ 22%")
205
+ with col2:
206
+ st.metric("Routes Optimized", "156", "↑ 15%")
207
+
208
+ # Main content based on selected page
209
+ if page == "🏠 Dashboard":
210
+ st.markdown("## 📊 Emission Overview Dashboard")
211
+
212
+ # Top KPIs
213
+ col1, col2, col3, col4 = st.columns(4)
214
+
215
+ with col1:
216
+ st.markdown("""
217
+ <div class="metric-card">
218
+ <h3 style="color: #2ECC71; margin: 0;">12.5t</h3>
219
+ <p style="margin: 0; color: #7F8C8D;">Total CO₂ Emissions</p>
220
+ <small style="color: #E74C3C;">↓ 18% vs last month</small>
221
+ </div>
222
+ """, unsafe_allow_html=True)
223
+
224
+ with col2:
225
+ st.markdown("""
226
+ <div class="metric-card">
227
+ <h3 style="color: #2ECC71; margin: 0;">22%</h3>
228
+ <p style="margin: 0; color: #7F8C8D;">Emission Reduction</p>
229
+ <small style="color: #27AE60;">Green routes adopted</small>
230
+ </div>
231
+ """, unsafe_allow_html=True)
232
+
233
+ with col3:
234
+ st.markdown("""
235
+ <div class="metric-card">
236
+ <h3 style="color: #2ECC71; margin: 0;">0.08</h3>
237
+ <p style="margin: 0; color: #7F8C8D;">Avg. Emission/Shipment (kg)</p>
238
+ <small style="color: #27AE60;">Industry best practice</small>
239
+ </div>
240
+ """, unsafe_allow_html=True)
241
+
242
+ with col4:
243
+ st.markdown("""
244
+ <div class="metric-card">
245
+ <h3 style="color: #2ECC71; margin: 0;">$1,250</h3>
246
+ <p style="margin: 0; color: #7F8C8D;">Carbon Tax Savings</p>
247
+ <small style="color: #27AE60;">Monthly estimate</small>
248
+ </div>
249
+ """, unsafe_allow_html=True)
250
+
251
+ # Charts
252
+ col1, col2 = st.columns(2)
253
+
254
+ with col1:
255
+ st.markdown("### 🚛 Emissions by Transport Mode")
256
+
257
+ # Sample data for transport mode comparison
258
+ modes_data = pd.DataFrame({
259
+ 'Transport Mode': ['Road Truck', 'Rail', 'Ship Container', 'Air Cargo'],
260
+ 'CO₂ Emissions (kg)': [62, 22, 11, 602],
261
+ 'Usage %': [45, 30, 20, 5]
262
+ })
263
+
264
+ fig = px.bar(
265
+ modes_data,
266
+ x='Transport Mode',
267
+ y='CO₂ Emissions (kg)',
268
+ color='CO₂ Emissions (kg)',
269
+ color_continuous_scale=['#2ECC71', '#E74C3C'],
270
+ title="Emission Factors by Transport Mode"
271
+ )
272
+ fig.update_layout(showlegend=False, height=400)
273
+ st.plotly_chart(fig, use_container_width=True)
274
+
275
+ with col2:
276
+ st.markdown("### 📈 Emission Trends")
277
+
278
+ # Sample trend data
279
+ emissions_data = [15.2, 14.8, 13.9, 13.1, 12.8, 12.3, 11.9, 11.5, 12.5]
280
+ dates = pd.date_range(start='2024-01-01', periods=len(emissions_data), freq='M')
281
+ trend_data = pd.DataFrame({
282
+ 'Date': dates,
283
+ 'Emissions (tonnes)': emissions_data,
284
+ 'Target': [14.0] * len(emissions_data)
285
+ })
286
+
287
+ fig = go.Figure()
288
+ fig.add_trace(go.Scatter(
289
+ x=trend_data['Date'],
290
+ y=trend_data['Emissions (tonnes)'],
291
+ mode='lines+markers',
292
+ name='Actual Emissions',
293
+ line=dict(color='#2ECC71', width=3)
294
+ ))
295
+ fig.add_trace(go.Scatter(
296
+ x=trend_data['Date'],
297
+ y=trend_data['Target'],
298
+ mode='lines',
299
+ name='Target',
300
+ line=dict(color='#E74C3C', dash='dash')
301
+ ))
302
+ fig.update_layout(title="Monthly Emission Trends", height=400)
303
+ st.plotly_chart(fig, use_container_width=True)
304
+
305
+ elif page == "🧮 Emission Calculator":
306
+ st.markdown("## 🧮 CO₂ Emission Calculator")
307
+ st.markdown("Calculate CO₂ emissions using the formula: **CO₂ = Distance × Weight × EmissionFactor**")
308
+
309
+ col1, col2 = st.columns([2, 1])
310
+
311
+ with col1:
312
+ with st.form("emission_calculator"):
313
+ st.markdown("### Input Parameters")
314
+
315
+ col_a, col_b = st.columns(2)
316
+ with col_a:
317
+ distance = st.number_input("Distance (km)", min_value=0.1, value=500.0, step=10.0)
318
+ weight = st.number_input("Weight (tonnes)", min_value=0.01, value=2.0, step=0.1)
319
+
320
+ with col_b:
321
+ transport_mode = st.selectbox(
322
+ "Transport Mode",
323
+ options=[mode.value for mode in TransportMode],
324
+ format_func=lambda x: x.replace('_', ' ').title()
325
+ )
326
+
327
+ calculate_btn = st.form_submit_button("🧮 Calculate Emissions", type="primary")
328
+
329
+ if calculate_btn:
330
+ try:
331
+ # Convert string to TransportMode enum
332
+ mode_mapping = {
333
+ 'road_truck': TransportMode.ROAD_TRUCK,
334
+ 'road_van': TransportMode.ROAD_VAN,
335
+ 'rail': TransportMode.RAIL,
336
+ 'air_cargo': TransportMode.AIR_CARGO,
337
+ 'ship_container': TransportMode.SHIP_CONTAINER,
338
+ 'ship_bulk': TransportMode.SHIP_BULK
339
+ }
340
+
341
+ if transport_mode in mode_mapping:
342
+ mode = mode_mapping[transport_mode]
343
+ else:
344
+ mode = TransportMode(transport_mode)
345
+
346
+ result = calculator.calculate_emissions(distance, weight, mode)
347
+
348
+ st.success("✅ Calculation Complete!")
349
+
350
+ # Results display
351
+ col_r1, col_r2, col_r3 = st.columns(3)
352
+
353
+ with col_r1:
354
+ st.metric(
355
+ "CO₂ Emissions",
356
+ f"{result['co2_emissions_kg']:.2f} kg",
357
+ f"{result['co2_emissions_tonnes']:.3f} tonnes"
358
+ )
359
+
360
+ with col_r2:
361
+ carbon_tax = calculator.calculate_carbon_tax_cost(result['co2_emissions_kg'])
362
+ st.metric(
363
+ "Carbon Tax Cost",
364
+ f"${carbon_tax['carbon_tax_cost_usd']:.2f}",
365
+ "@ $50/tonne CO₂"
366
+ )
367
+
368
+ with col_r3:
369
+ st.metric(
370
+ "Emission Factor",
371
+ f"{result['emission_factor']:.3f}",
372
+ "kg CO₂/tonne-km"
373
+ )
374
+
375
+ # Comparison with other modes
376
+ st.markdown("### 🔄 Transport Mode Comparison")
377
+ comparison_df = calculator.compare_transport_modes(distance, weight)
378
+
379
+ fig = px.bar(
380
+ comparison_df,
381
+ x='transport_mode',
382
+ y='co2_emissions_kg',
383
+ color='co2_emissions_kg',
384
+ color_continuous_scale=['#2ECC71', '#E74C3C'],
385
+ title="CO₂ Emissions by Transport Mode"
386
+ )
387
+ fig.update_layout(height=400)
388
+ st.plotly_chart(fig, use_container_width=True)
389
+
390
+ st.dataframe(comparison_df, use_container_width=True)
391
+
392
+ except Exception as e:
393
+ st.error(f"❌ Calculation failed: {str(e)}")
394
+
395
+ with col2:
396
+ st.markdown("### 📋 Emission Factors")
397
+ factors_df = calculator.get_emission_factors_table()
398
+ st.dataframe(factors_df, use_container_width=True)
399
+
400
+ st.markdown("### 🌱 Green Tips")
401
+ st.info("""
402
+ **Reduce Emissions:**
403
+ - Choose rail over road when possible
404
+ - Use container ships for long distances
405
+ - Optimize load capacity
406
+ - Consider multimodal transport
407
+ """)
408
+
409
+ elif page == "🗺️ Route Optimizer":
410
+ st.markdown("## 🗺️ Green Route Optimizer")
411
+ st.markdown("Find the most eco-friendly routes for your shipments")
412
+
413
+ with st.form("route_optimizer"):
414
+ col1, col2 = st.columns(2)
415
+
416
+ with col1:
417
+ origin = st.text_input("Origin", value="New York, NY", placeholder="Enter origin city")
418
+ destination = st.text_input("Destination", value="Los Angeles, CA", placeholder="Enter destination city")
419
+
420
+ with col2:
421
+ weight = st.number_input("Shipment Weight (tonnes)", min_value=0.01, value=5.0, step=0.1)
422
+ max_time_penalty = st.slider("Max Time Penalty (%)", 0, 50, 10)
423
+
424
+ optimize_btn = st.form_submit_button("🗺️ Find Green Routes", type="primary")
425
+
426
+ if optimize_btn and origin and destination:
427
+ with st.spinner("🔍 Finding optimal routes..."):
428
+ try:
429
+ # Get route recommendations
430
+ recommendations = optimizer.recommend_green_routes(origin, destination, weight)
431
+
432
+ if 'error' not in recommendations::
433
+ st.success("✅ Route optimization complete!")
434
+
435
+ route_data = recommendations['recommendations']
436
+
437
+ # Display recommendations
438
+ st.markdown("### 🌱 Green Route Recommendations")
439
+
440
+ for i, route in enumerate(route_data):
441
+ with st.expander(f"Option {i+1}: {route['transport_mode'].replace('_', ' ').title()}", expanded=(i==0)):
442
+ col_a, col_b, col_c, col_d = st.columns(4)
443
+
444
+ with col_a:
445
+ st.metric("CO₂ Emissions", f"{route['co2_emissions_kg']:.1f} kg")
446
+ with col_b:
447
+ st.metric("Travel Time", f"{route['estimated_travel_time_hours']:.1f} hrs")
448
+ with col_c:
449
+ st.metric("Carbon Tax", f"${route['carbon_tax_cost_usd']:.2f}")
450
+ with col_d:
451
+ if route['emission_reduction_percent'] > 0:
452
+ st.metric("Emission Reduction", f"{route['emission_reduction_percent']:.1f}%", "vs worst option")
453
+ else:
454
+ st.metric("Emission Impact", "Baseline", "")
455
+
456
+ if i == 0:
457
+ st.markdown('<span class="eco-badge">🌱 RECOMMENDED</span>', unsafe_allow_html=True)
458
+
459
+ # Visualization
460
+ if len(route_data) > 1:
461
+ st.markdown("### 📊 Route Comparison")
462
+
463
+ df_viz = pd.DataFrame(route_data)
464
+
465
+ fig = make_subplots(
466
+ rows=1, cols=2,
467
+ subplot_titles=('CO₂ Emissions (kg)', 'Travel Time (hours)'),
468
+ specs=[[{"secondary_y": False}, {"secondary_y": False}]]
469
+ )
470
+
471
+ fig.add_trace(
472
+ go.Bar(
473
+ x=df_viz['transport_mode'],
474
+ y=df_viz['co2_emissions_kg'],
475
+ name='CO₂ Emissions',
476
+ marker_color='#2ECC71'
477
+ ),
478
+ row=1, col=1
479
+ )
480
+
481
+ fig.add_trace(
482
+ go.Bar(
483
+ x=df_viz['transport_mode'],
484
+ y=df_viz['estimated_travel_time_hours'],
485
+ name='Travel Time',
486
+ marker_color='#3498DB'
487
+ ),
488
+ row=1, col=2
489
+ )
490
+
491
+ fig.update_layout(height=400, showlegend=False)
492
+ st.plotly_chart(fig, use_container_width=True)
493
+
494
+ else:
495
+ st.error(f"❌ Route optimization failed: {recommendations.get('error', 'Unknown error')}")
496
+
497
+ except Exception as e:
498
+ st.error(f"❌ Error: {str(e)}")
499
+
500
+ elif page == "📊 Scenario Analysis":
501
+ st.markdown("## 📊 Business Impact Simulation")
502
+ st.markdown("Analyze the potential impact of adopting green shipping practices")
503
+
504
+ with st.form("scenario_analysis"):
505
+ col1, col2 = st.columns(2)
506
+
507
+ with col1:
508
+ st.markdown("### 📦 Shipment Parameters")
509
+ total_shipments = st.number_input("Total Monthly Shipments", min_value=1, value=1000, step=50)
510
+ avg_distance = st.number_input("Average Distance (km)", min_value=1.0, value=800.0, step=50.0)
511
+ avg_weight = st.number_input("Average Weight (tonnes)", min_value=0.1, value=3.0, step=0.1)
512
+
513
+ with col2:
514
+ st.markdown("### ⚙️ Optimization Parameters")
515
+ optimization_percent = st.slider("% Shipments Using Green Routes", 0, 100, 50)
516
+ current_mode = st.selectbox("Current Transport Mode", [mode.value for mode in TransportMode], index=0)
517
+ carbon_tax_rate = st.number_input("Carbon Tax Rate ($/tonne CO₂)", min_value=0.0, value=50.0, step=5.0)
518
+
519
+ analyze_btn = st.form_submit_button("📊 Run Scenario Analysis", type="primary")
520
+
521
+ if analyze_btn:
522
+ with st.spinner("🔄 Running business impact simulation..."):
523
+ try:
524
+ # Current emissions - use same mapping as before
525
+ mode_mapping = {
526
+ 'road_truck': TransportMode.ROAD_TRUCK,
527
+ 'road_van': TransportMode.ROAD_VAN,
528
+ 'rail': TransportMode.RAIL,
529
+ 'air_cargo': TransportMode.AIR_CARGO,
530
+ 'ship_container': TransportMode.SHIP_CONTAINER,
531
+ 'ship_bulk': TransportMode.SHIP_BULK
532
+ }
533
+
534
+ if current_mode in mode_mapping:
535
+ current_mode_enum = mode_mapping[current_mode]
536
+ else:
537
+ current_mode_enum = TransportMode(current_mode)
538
+
539
+ current_emissions = calculator.calculate_emissions(avg_distance, avg_weight, current_mode_enum)
540
+
541
+ # Find best green alternative - calculate manually to avoid EmissionOptimizer import
542
+ available_modes = [TransportMode.ROAD_TRUCK, TransportMode.RAIL, TransportMode.SHIP_CONTAINER]
543
+
544
+ # Calculate emissions for each mode and find the greenest
545
+ mode_options = []
546
+ for mode in available_modes:
547
+ emissions = calculator.calculate_emissions(avg_distance, avg_weight, mode)
548
+ mode_options.append({
549
+ 'mode': mode,
550
+ 'co2_emissions_kg': emissions['co2_emissions_kg'],
551
+ 'emission_factor': emissions['emission_factor']
552
+ })
553
+
554
+ # Sort by emissions (lowest first) to find greenest option
555
+ mode_options.sort(key=lambda x: x['co2_emissions_kg'])
556
+ green_option = mode_options[0] if mode_options else None
557
+
558
+ if not green_option:
559
+ st.error("❌ No green alternatives available")
560
+ st.stop()
561
+
562
+ # Calculate scenario impact
563
+ optimized_shipments = int(total_shipments * optimization_percent / 100)
564
+ regular_shipments = total_shipments - optimized_shipments
565
+
566
+ current_total = current_emissions['co2_emissions_kg'] * total_shipments
567
+ optimized_total = (
568
+ green_option['co2_emissions_kg'] * optimized_shipments +
569
+ current_emissions['co2_emissions_kg'] * regular_shipments
570
+ )
571
+
572
+ savings_kg = current_total - optimized_total
573
+ savings_percent = (savings_kg / current_total) * 100
574
+ carbon_tax_savings = (savings_kg / 1000) * carbon_tax_rate
575
+
576
+ st.success("✅ Scenario analysis complete!")
577
+
578
+ # Results
579
+ col1, col2, col3, col4 = st.columns(4)
580
+
581
+ with col1:
582
+ st.metric("Current Emissions", f"{current_total/1000:.1f} tonnes/month")
583
+ with col2:
584
+ st.metric("Optimized Emissions", f"{optimized_total/1000:.1f} tonnes/month")
585
+ with col3:
586
+ st.metric("CO₂ Savings", f"{savings_kg/1000:.1f} tonnes/month", f"{savings_percent:.1f}% reduction")
587
+ with col4:
588
+ st.metric("Carbon Tax Savings", f"${carbon_tax_savings:.0f}/month", f"${carbon_tax_savings*12:.0f}/year")
589
+
590
+ # Visualization
591
+ st.markdown("### 📈 Impact Visualization")
592
+
593
+ scenario_data = pd.DataFrame({
594
+ 'Scenario': ['Current', 'Optimized'],
595
+ 'CO₂ Emissions (tonnes)': [current_total/1000, optimized_total/1000],
596
+ 'Carbon Tax Cost ($)': [
597
+ (current_total/1000) * carbon_tax_rate,
598
+ (optimized_total/1000) * carbon_tax_rate
599
+ ]
600
+ })
601
+
602
+ fig = make_subplots(
603
+ rows=1, cols=2,
604
+ subplot_titles=('CO₂ Emissions', 'Carbon Tax Cost'),
605
+ specs=[[{"secondary_y": False}, {"secondary_y": False}]]
606
+ )
607
+
608
+ fig.add_trace(
609
+ go.Bar(
610
+ x=scenario_data['Scenario'],
611
+ y=scenario_data['CO₂ Emissions (tonnes)'],
612
+ name='CO₂ Emissions',
613
+ marker_color=['#E74C3C', '#2ECC71']
614
+ ),
615
+ row=1, col=1
616
+ )
617
+
618
+ fig.add_trace(
619
+ go.Bar(
620
+ x=scenario_data['Scenario'],
621
+ y=scenario_data['Carbon Tax Cost ($)'],
622
+ name='Carbon Tax Cost',
623
+ marker_color=['#E74C3C', '#2ECC71']
624
+ ),
625
+ row=1, col=2
626
+ )
627
+
628
+ fig.update_layout(height=400, showlegend=False)
629
+ st.plotly_chart(fig, use_container_width=True)
630
+
631
+ # Business benefits
632
+ st.markdown("### 💼 Business Benefits")
633
+
634
+ benefits_col1, benefits_col2 = st.columns(2)
635
+
636
+ with benefits_col1:
637
+ st.markdown("""
638
+ **Environmental Impact:**
639
+ - ♻️ Reduced carbon footprint
640
+ - 🌱 Enhanced sustainability profile
641
+ - 📊 ESG score improvement
642
+ - 🏆 Industry leadership positioning
643
+ """)
644
+
645
+ with benefits_col2:
646
+ st.markdown(f"""
647
+ **Financial Benefits:**
648
+ - 💰 ${carbon_tax_savings*12:.0f} annual tax savings
649
+ - 📈 Potential green financing access
650
+ - 🎯 Regulatory compliance readiness
651
+ - 💡 Operational efficiency gains
652
+ """)
653
+
654
+ except Exception as e:
655
+ st.error(f"❌ Analysis failed: {str(e)}")
656
+ st.write(f"Debug info: {type(e).__name__}: {e}")
657
+ import traceback
658
+ st.code(traceback.format_exc())
659
+
660
+ elif page == "📈 Analytics":
661
+ st.markdown("## 📈 Advanced Analytics")
662
+
663
+ # Sample analytics data
664
+ st.markdown("### 🎯 Performance Metrics")
665
+
666
+ col1, col2, col3 = st.columns(3)
667
+
668
+ with col1:
669
+ st.markdown("""
670
+ <div class="metric-card">
671
+ <h4 style="color: #2ECC71; margin: 0;">Route Efficiency Score</h4>
672
+ <h2 style="margin: 0;">87/100</h2>
673
+ <p style="margin: 0; color: #7F8C8D;">Above industry average</p>
674
+ </div>
675
+ """, unsafe_allow_html=True)
676
+
677
+ with col2:
678
+ st.markdown("""
679
+ <div class="metric-card">
680
+ <h4 style="color: #2ECC71; margin: 0;">Green Route Adoption</h4>
681
+ <h2 style="margin: 0;">68%</h2>
682
+ <p style="margin: 0; color: #7F8C8D;">Target: 75%</p>
683
+ </div>
684
+ """, unsafe_allow_html=True)
685
+
686
+ with col3:
687
+ st.markdown("""
688
+ <div class="metric-card">
689
+ <h4 style="color: #2ECC71; margin: 0;">Emission Intensity</h4>
690
+ <h2 style="margin: 0;">0.045</h2>
691
+ <p style="margin: 0; color: #7F8C8D;">kg CO₂/tonne-km</p>
692
+ </div>
693
+ """, unsafe_allow_html=True)
694
+
695
+ # Regional analysis
696
+ st.markdown("### 🌍 Regional Emission Analysis")
697
+
698
+ regional_data = pd.DataFrame({
699
+ 'Region': ['North America', 'Europe', 'Asia Pacific', 'Latin America'],
700
+ 'Emissions (tonnes)': [45.2, 32.1, 28.7, 15.3],
701
+ 'Shipments': [450, 320, 380, 180],
702
+ 'Avg Distance (km)': [1200, 800, 950, 600]
703
+ })
704
+
705
+ fig = px.scatter(
706
+ regional_data,
707
+ x='Shipments',
708
+ y='Emissions (tonnes)',
709
+ size='Avg Distance (km)',
710
+ color='Region',
711
+ title="Regional Emission vs Shipment Volume"
712
+ )
713
+ fig.update_layout(height=500)
714
+ st.plotly_chart(fig, use_container_width=True)
715
+
716
+ st.dataframe(regional_data, use_container_width=True)
717
+
718
+
719
+ # Footer
720
+ st.markdown("---")
721
+ st.markdown("## 👨‍💻 Developer Details")
722
+ st.markdown("""
723
+ <div style="text-align: center; color: #2C3E50; padding: 2rem; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
724
+ <div style="margin-bottom: 1rem;">
725
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" style="width: 60px; height: 60px;">
726
+ <defs>
727
+ <linearGradient id="zkGradient" x1="0%" y1="0%" x2="100%" y2="100%">
728
+ <stop offset="0%" style="stop-color:#2ECC71;stop-opacity:1" />
729
+ <stop offset="100%" style="stop-color:#27AE60;stop-opacity:1" />
730
+ </linearGradient>
731
+ </defs>
732
+ <g transform="translate(50, 50)">
733
+ <path d="M10 20 L70 20 L70 35 L35 75 L70 75 L70 90 L10 90 L10 75 L45 35 L10 35 Z"
734
+ fill="url(#zkGradient)"
735
+ stroke="#1E8449"
736
+ stroke-width="1"/>
737
+ <path d="M80 20 L95 20 L95 50 L110 20 L130 20 L110 55 L130 90 L110 90 L95 65 L95 90 L80 90 Z"
738
+ fill="url(#zkGradient)"
739
+ stroke="#1E8449"
740
+ stroke-width="1"/>
741
+ </g>
742
+ </svg>
743
+ </div>
744
+ <p style="font-size: 1.2rem; color: #2C3E50; margin-bottom: 0.5rem;"><strong>GreenPath</strong> - AI-Powered CO₂ Emission Reduction Platform</p>
745
+ <p style="font-size: 1.1rem; color: #34495E; margin-bottom: 1rem;">Designed and Developed by <strong>Sayed Mohd Zayeem Khateeb</strong></p>
746
+ <div style="margin: 1rem 0;">
747
+ <a href="https://github.com/zayeemskhateeb-cloud" target="_blank" style="margin: 0 10px; text-decoration: none; color: #2ECC71; font-weight: bold; font-size: 1rem;">🌐 GitHub</a> |
748
+ <a href="https://www.linkedin.com/in/zayeemkhateeb" target="_blank" style="margin: 0 10px; text-decoration: none; color: #2ECC71; font-weight: bold; font-size: 1rem;">💼 LinkedIn</a> |
749
+ <a href="mailto:zayeem.s.khateeb@gmail.com" style="margin: 0 10px; text-decoration: none; color: #2ECC71; font-weight: bold; font-size: 1rem;">📧 Email</a>
750
+ </div>
751
+ <p style="font-size: 1rem; color: #7F8C8D; margin-top: 1rem;">
752
+ Specialized in AI/ML, Data Analytics, and Sustainable Technology Solutions
753
+ </p>
754
+ </div>
755
+ """, unsafe_allow_html=True)