Spaces:
Sleeping
Sleeping
import streamlit as st | |
import google.generativeai as genai | |
import requests | |
from datetime import datetime | |
from PIL import Image as PILImage | |
import folium | |
from streamlit_folium import folium_static | |
import os | |
from streamlit_option_menu import option_menu | |
import plotly.graph_objs as go | |
import base64 | |
import re | |
# Initialize APIs | |
MAPTILER_API_KEY = "bK9j55GlT3HtekZ95TkH" | |
# Configure the page | |
st.set_page_config( | |
page_title="TerraPulse", | |
page_icon="π", | |
layout="wide", | |
initial_sidebar_state="expanded" | |
) | |
def get_base64_image(image_path): | |
with open(image_path, "rb") as img_file: | |
return base64.b64encode(img_file.read()).decode() | |
img_base64 = get_base64_image("bg.jpg") | |
st.markdown( | |
f""" | |
<style> | |
header {{visibility: hidden;}} | |
footer {{visibility: hidden;}} | |
body {{ | |
background-color: #f5f7fa; | |
font-family: 'Poppins', sans-serif; | |
}} | |
h1, h2, h3 {{ | |
color: #00287a; | |
font-weight: 700; | |
}} | |
h1 {{ | |
font-size: 3em; | |
text-align: center; | |
margin-bottom: 20px; | |
}} | |
h2 {{ | |
font-size: 2.2em; | |
margin-top: 20px; | |
}} | |
h3 {{ | |
font-size: 1.8em; | |
}} | |
.stApp {{ | |
min-height: 100vh; | |
padding: 20px; | |
border-radius: 10px; | |
background-image: url("data:image/jpeg;base64,{img_base64}"); | |
background-size: cover; | |
background-position: center; | |
background-repeat: no-repeat; | |
}} | |
.stButton>button {{ | |
background-color: #00a05c; | |
color: white; | |
border: none; | |
padding: 12px 24px; | |
font-size: 18px; | |
border-radius: 10px; | |
transition: background-color 0.3s, color 0.3s; | |
}} | |
.stButton>button:hover {{ | |
background-color: #00bd4b; | |
color: #ffffff; | |
}} | |
.stTextInput>div>div>input {{ | |
border-radius: 10px; | |
border: 1px solid #ccc; | |
padding: 12px; | |
font-size: 18px; | |
}} | |
.stSidebar > div {{ | |
background-color: rgba(255, 255, 255, 0.95); | |
padding: 20px; | |
border-radius: 10px; | |
}} | |
.chat-message {{ | |
font-size: 18px; | |
font-weight: bold; | |
color: #008080; | |
}} | |
</style> | |
""", | |
unsafe_allow_html=True | |
) | |
selected_option = option_menu( | |
menu_title="TerraPulse", | |
options=["Home", "Waste-wise", "EcoRoute: Sustainable Travel Planner"], | |
icons=["house", "recycle", "globe"], | |
menu_icon="globe", | |
default_index=0, | |
orientation="horizontal", | |
styles={ | |
"container": {"padding": "5!important", "background-color": "#ffffff00"}, | |
"icon": {"color": "#000000", "font-size": "25px"}, | |
"nav-link": {"font-size": "18px", "text-align": "center", "--hover-color": "#ffffff50", "border-radius": "12px", "font-family": "'Segoe UI', sans-serif", "padding": "4px 20px 8px 20px",}, | |
"nav-link-selected": {"background-color": "#00845873", "border-radius": "12px", "font-family": "'Segoe UI', sans-serif", "padding": "4px 20px 10px 20px",}, | |
} | |
) | |
if selected_option == "Home": | |
st.title("π Welcome to TerraPulse") | |
st.markdown( | |
""" | |
**TerraPulse** is your go-to application for a sustainable future. π± | |
Whether you're looking to classify waste for proper disposal or planning an eco-friendly route for your next trip, TerraPulse has got you covered. | |
**Features:** | |
- **β»οΈ Waste-wise:** Upload images of trash items, and TerraPulse will classify them into recyclables, compostables, hazardous materials, and general waste. | |
- **π EcoRoute:** Plan your travel with the environment in mind. Get the most sustainable routes, transportation suggestions, and carbon footprint estimates. | |
**Let's work together for a cleaner and greener planet!** ππ | |
""" | |
) | |
def load_model(api_key): | |
if not api_key: | |
st.error("Please Enter Google API Key") | |
st.stop() | |
try: | |
genai.configure(api_key=api_key) | |
model = genai.GenerativeModel('gemini-1.5-flash') | |
model.generate_content("Ping") | |
return model | |
except: | |
st.error("Please Enter Valid API Key") | |
st.stop() | |
def analyze_image(image, prompt, api_key): | |
model = load_model(api_key) | |
try: | |
response = model.generate_content([prompt, image]) | |
return response.text | |
except Exception as e: | |
st.error(f"An error occurred during analysis: {str(e)}") | |
return None | |
def parse_modes_and_footprints(response_text): | |
row_pattern = re.compile(r'\| (.+?) \| ([\d.]+) \|') | |
matches = row_pattern.findall(response_text) | |
modes, carbon_footprints = [], [] | |
for match in matches: | |
modes.append(match[0].strip()) | |
carbon_footprints.append(float(match[1].strip())) | |
if not modes or not carbon_footprints: | |
raise ValueError("No valid data found in the response text") | |
return modes, carbon_footprints | |
def geocode_location_maptiler(location): | |
if not MAPTILER_API_KEY: | |
st.error("MapTiler API key missing. Please add it to your .env file.") | |
return None | |
response = requests.get( | |
f"https://api.maptiler.com/geocoding/{location}.json?key={MAPTILER_API_KEY}" | |
) | |
if response.status_code != 200: | |
st.error(f"MapTiler Geocoding API error: {response.status_code}") | |
return None | |
data = response.json() | |
if data.get("features"): | |
coords = data["features"][0]["geometry"]["coordinates"] | |
return {"lat": coords[1], "lng": coords[0]} | |
return None | |
if selected_option == "Waste-wise": | |
st.title("β»οΈ Waste-wise") | |
api_key = st.text_input("Enter your Google API key:", type="password") | |
st.subheader("π€ Upload Image") | |
uploaded_files = st.file_uploader("Choose trash images...", type=["jpg", "jpeg", "png"], accept_multiple_files=True) | |
prompt = "Analyze the image of trash items. Classify the waste into categories such as recyclables, compostables, hazardous materials, and general waste. Based on the classification, guide the user on which specific color dustbin (e.g., recycling, compost, hazardous, or landfill) to dispose of the items." | |
if uploaded_files: | |
analyze_button = st.button("π Analyze Image") | |
for uploaded_file in uploaded_files: | |
col1, col2 = st.columns(2) | |
with col1: | |
st.subheader("πΌοΈ Uploaded Image") | |
image = PILImage.open(uploaded_file) | |
st.image(image, caption="Uploaded Image", use_column_width=True) | |
with col2: | |
st.subheader("π§ Image Analysis") | |
if analyze_button: | |
with st.spinner("Analyzing the image..."): | |
analysis = analyze_image(image, prompt, api_key) | |
if analysis: | |
st.markdown(analysis) | |
else: | |
st.info("Click 'Analyze Image' to start the analysis.") | |
def parse_modes_and_footprints(response_text): | |
lines = response_text.strip().split('\n') | |
modes = [] | |
carbon_footprints = [] | |
for line in lines: | |
line = line.strip() | |
if (line.startswith('|') and '-' in line) or line.lower().startswith('| mode'): | |
continue | |
if line.startswith('|') and line.endswith('|'): | |
parts = [part.strip() for part in line.strip('|').split('|')] | |
if len(parts) >= 2: | |
mode = parts[0] | |
footprint_str = parts[1] | |
try: | |
footprint = float(footprint_str) | |
modes.append(mode) | |
carbon_footprints.append(footprint) | |
except ValueError: | |
continue | |
if not modes or not carbon_footprints: | |
raise ValueError("No valid data found in the response text") | |
return modes, carbon_footprints | |
if selected_option == "EcoRoute: Sustainable Travel Planner": | |
api_key = st.text_input("Enter your Google API key:", type="password") | |
st.title("π EcoRoute: Sustainable Travel Planner") | |
model = load_model(api_key) | |
start_location = st.text_input("Enter your start location") | |
destination_location = st.text_input("Enter your destination location") | |
no_of_people = st.selectbox("Choose the number of people", ["1", "2", "3-6", "6-10", "10+"]) | |
if st.button("Find Eco-Friendly Route"): | |
if start_location and destination_location: | |
start_coords = geocode_location_maptiler(start_location) | |
end_coords = geocode_location_maptiler(destination_location) | |
if start_coords and end_coords: | |
prompt = f""" | |
You are an eco-friendly travel advisor. | |
Given: | |
- Start location: {start_location} | |
- Destination location: {destination_location} | |
- Number of people traveling: {no_of_people} | |
First, write 2-3 sentences recommending the most sustainable option and explaining briefly why it's preferred. Then, respond with a markdown table listing transport modes and their estimated carbon footprints (in kg CO2e) per passenger, formatted exactly like this: | |
| Mode | Carbon Footprint | | |
|--------------|------------------| | |
| Walking | 0 | | |
| Cycling | 0 | | |
| Train | 15 | | |
| Electric Car | 10 | | |
Make sure the table comes **after** the recommendation text. | |
""" | |
try: | |
response = model.generate_content([prompt]) | |
eco_friendly_modes = response.text.strip() | |
# Split into recommendation and table | |
table_start = eco_friendly_modes.find("| Mode") | |
if table_start == -1: | |
raise ValueError("No markdown table found in the response.") | |
recommendation_text = eco_friendly_modes[:table_start].strip() | |
markdown_table = eco_friendly_modes[table_start:].strip() | |
st.markdown(f"**AI Recommendation:**\n\n{recommendation_text}") | |
st.markdown(markdown_table) | |
# Parse the markdown table | |
modes, carbon_footprints = parse_modes_and_footprints(markdown_table) | |
if modes and carbon_footprints: | |
fig = go.Figure(data=[go.Pie(labels=modes, values=carbon_footprints)]) | |
fig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20) | |
fig.update_layout(title="Carbon Footprint Distribution by Mode of Transport", margin=dict(l=0, r=0, t=40, b=0)) | |
col1, col2 = st.columns([2, 1]) | |
with col1: | |
st.subheader("EcoRoute Map View") | |
midpoint = [(start_coords['lat'] + end_coords['lat']) / 2, (start_coords['lng'] + end_coords['lng']) / 2] | |
m = folium.Map( | |
location=midpoint, | |
zoom_start=8, | |
tiles=f"https://api.maptiler.com/maps/streets-v2/256/{{z}}/{{x}}/{{y}}.png?key={MAPTILER_API_KEY}", | |
attr="MapTiler" | |
) | |
folium.Marker([start_coords['lat'], start_coords['lng']], popup=start_location, icon=folium.Icon(color='green')).add_to(m) | |
folium.Marker([end_coords['lat'], end_coords['lng']], popup=destination_location, icon=folium.Icon(color='red')).add_to(m) | |
folium.PolyLine(locations=[(start_coords['lat'], start_coords['lng']), (end_coords['lat'], end_coords['lng'])], color='blue').add_to(m) | |
folium_static(m) | |
with col2: | |
st.plotly_chart(fig, use_container_width=True) | |
except Exception as e: | |
st.error(f"Error processing the eco-route suggestion: {str(e)}") | |
else: | |
st.error("Could not geocode one or both locations. Please check the location names.") | |
else: | |
st.warning("Please enter both start and destination locations.") | |