Spaces:
Sleeping

LCA_MCP / app.py
Tarekt's picture
Update app.py
c6c0689 verified
Raw History Blame Contribute Delete
13.6 kB
from retry_requests import retry
import matplotlib.pyplot as plt
import openmeteo_requests
import mysql.connector
import requests_cache
from PIL import Image
import pandas as pd
import gradio as gr
import requests
import tempfile
import json
import io
def predict(image: Image.Image):
"""read the figure, then detect the object, and return objects classes, names, and bounding boxes"""
if image is None:
return "No image provided."
# Save image temporarily
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
image.save(tmp.name, format="JPEG")
file_path = tmp.name
with open(file_path, "rb") as f:
response = requests.post("https://predict-6968a0a72e968330c567-dproatj77a-od.a.run.app/predict", headers={"Authorization": "Bearer ul_b5f1de417e3816cc8621ee3ff7a69131a6a5051b"}, data={"conf": 0.25, "iou": 0.3, "imgsz": 1280}, files={"file": f})
if response.status_code != 200:
return f"Request failed with status code {response.status_code}: {response.text}"
try:
response_json = response.json()
results = response_json["images"][0]["results"]
return json.dumps(results, indent=2)
except Exception as e:
return f"Failed to extract results: {str(e)}"
def Carbon_footprint(a, b):
"""Calculate the carbon footprint based on the CO2 factor collected from the database and the units of the product"""
try:
result = float(a) * float(b)
return f"Result: {result:.2f} kg CO2"
except:
return "Error: Invalid numbers"
def Green_light_time_estimator(a):
"""Calculate the required green light time based on the provided number of Passnger Car Unit (PCU)"""
green_light_time = 0
try:
green_light_time = min(60 ,2 + (float(a) * 2.8)) if float(a)!=0 else 0
return f"Result: {green_light_time:.2f} seconds"
except:
return "Error: Invalid numbers"
def Passenger_Car_Unit_Calculator(a,b,c,d):
"""Calculate the number of Passnger Car Unit (PCU)"""
try:
pcu = int(a)*0.5 + int(b)*1 + int(c)*3 + int(d)*3
return f"Result: {pcu:.2f} PCU"
except:
return "Error: Invalid numbers"
def co2_factor():
"""Retrieve all CO2 factors from database (string output only)"""
try:
conn = mysql.connector.connect(host='sql8.freesqldatabase.com', database='sql8813782', user='sql8813782',password='7hch2jMvC7', port=3306)
cursor = conn.cursor(dictionary=True)
cursor.execute("SHOW TABLES;")
tables = [row[list(row.keys())[0]] for row in cursor.fetchall()]
all_data = {}
for table in tables:
cursor.execute(f"SELECT name, co2_factor, unit FROM {table};")
all_data[table] = cursor.fetchall()
cursor.close()
conn.close()
return json.dumps(all_data, indent=2) # ✅ STRING ONLY
except Exception as e:
return f"Database error: {str(e)}"
def plot_pie_chart(labels_str, values_str):
"""Create a pie chart from comma-separated labels and values"""
try:
labels = [label.strip() for label in labels_str.split(',')]
values = [float(value.strip()) for value in values_str.split(',')]
if len(labels) != len(values):
return None, "Error: Number of labels and values must match"
fig, ax = plt.subplots(figsize=(14, 8))
explode = [0.05 if v < 5 else 0 for v in values]
wedges, texts, autotexts = ax.pie(values, labels=None, autopct='%1.2f%%', startangle=90, explode=explode, pctdistance=0.85, textprops={'fontsize': 10, 'weight': 'bold'})
for autotext in autotexts:
autotext.set_color('black')
autotext.set_bbox(dict(boxstyle='round,pad=0.3', facecolor='white', alpha=0.8))
legend_labels = [f'{label}: {value:.2f} kg CO₂' for label, value in zip(labels, values)]
ax.legend(wedges, legend_labels, title="Emission Sources", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1), fontsize=10)
ax.set_title('CO₂ Emissions Distribution', fontsize=16, fontweight='bold', pad=20)
plt.tight_layout()
buf = io.BytesIO()
plt.savefig(buf, format='png', dpi=150, bbox_inches='tight')
buf.seek(0)
plt.close()
img = Image.open(buf)
total = sum(values)
summary = f"Chart created successfully!\n\nTotal CO₂: {total:.2f} kg\n"
summary += "\nBreakdown:\n"
for label, value in sorted(zip(labels, values), key=lambda x: x[1], reverse=True):
percentage = (value / total) * 100
summary += f"• {label}: {value:.2f} kg ({percentage:.2f}%)\n"
return img, summary
except Exception as e:
return None, f"Error: {str(e)}"
def get_coordinates(location_name):
"""
Get latitude and longitude for a location name.
Args:
location_name: Name of the location (city, place, etc.)
Returns:
Tuple of (latitude, longitude, location_info) or None if not found
"""
try:
url = "https://geocoding-api.open-meteo.com/v1/search"
params = {"name": location_name, "count": 1, "language": "en", "format": "json"}
response = requests.get(url, params=params)
data = response.json()
if "results" in data and len(data["results"]) > 0:
result = data["results"][0]
latitude = result["latitude"]
longitude = result["longitude"]
location_info = f"Found: {result['name']}, {result.get('country', 'N/A')}\nLatitude: {latitude}, Longitude: {longitude}"
return latitude, longitude, location_info
else:
return None, None, f"Location '{location_name}' not found"
except Exception as e:
return None, None, f"Error: {str(e)}"
def get_weather_data(latitude, longitude, start_date, end_date, hourly_vars):
"""
Fetch weather data from Open-Meteo API and return statistics.
Args:
latitude: Location latitude
longitude: Location longitude
start_date: Start date (YYYY-MM-DD)
end_date: End date (YYYY-MM-DD)
hourly_vars: List of hourly variables to fetch
Returns:
String with weather data statistics
"""
try:
# Parse hourly variables from comma-separated string
if isinstance(hourly_vars, str):
hourly_vars = [var.strip() for var in hourly_vars.split(',')]
retrived = []
cache_session = requests_cache.CachedSession('.cache', expire_after=-1)
retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
openmeteo = openmeteo_requests.Client(session=retry_session)
params = {
"latitude": latitude,
"longitude": longitude,
"start_date": start_date,
"end_date": end_date,
"hourly": hourly_vars
}
responses = openmeteo.weather_api("https://archive-api.open-meteo.com/v1/archive", params=params)
response = responses[0]
hourly = response.Hourly()
data = {
"date": pd.date_range(
start=pd.to_datetime(hourly.Time(), unit="s", utc=True),
end=pd.to_datetime(hourly.TimeEnd(), unit="s", utc=True),
freq=pd.Timedelta(seconds=hourly.Interval()),
inclusive="left"
)
}
for i, var in enumerate(hourly_vars):
data[var] = hourly.Variables(i).ValuesAsNumpy()
df = pd.DataFrame(data)
retrived.append(f"Total data points: {len(df)}")
retrived.append(f"Date range: {df['date'].min()} to {df['date'].max()}\n")
for var in hourly_vars:
retrived.append(f"Average {var}: {df[var].mean():.2f}")
return "\n".join(retrived)
except Exception as e:
return f"Error fetching weather data: {str(e)}"
def fetch_weather_wrapper(location_name, start_date, end_date, variables):
"""Wrapper function to get coordinates and fetch weather data"""
lat, lon, location_info = get_coordinates(location_name)
if lat is None:
return location_info
result = location_info + "\n\n" + get_weather_data(lat, lon, start_date, end_date, variables)
return result
with gr.Blocks(title="LCA Calculator") as demo:
gr.Markdown("# Carbon Footprint Calculator with Weather Data")
with gr.Tabs():
with gr.Tab("Calculator"):
mult_a = gr.Number(label="CO2 factor", value=5)
mult_b = gr.Number(label="Units", value=3)
mult_btn = gr.Button("Calculate")
mult_output = gr.Textbox(label="Result")
mult_btn.click(Carbon_footprint, [mult_a, mult_b], mult_output)
with gr.Tab("Database Lookup"):
query_btn = gr.Button("Get CO2 Factor")
query_output = gr.Textbox(label="Result")
query_btn.click(co2_factor, [], query_output)
with gr.Tab("Plot Pie Chart"):
gr.Markdown("### Create a CO₂ Emissions Pie Chart")
gr.Markdown("Enter labels and values separated by commas")
with gr.Row():
with gr.Column():
labels_input = gr.Textbox(label="Labels (comma-separated)", value="Materials, Transport, End-of-Life", placeholder="e.g., Manufacturing, Transport, End-of-Life", lines=3)
values_input = gr.Textbox(label="Values (comma-separated)", value="98.76, 0.64, 0.08", placeholder="e.g., 59.4, 2.6, 8.1, 6")
plot_btn = gr.Button("Generate Pie Chart", variant="primary")
with gr.Row():
plot_output = gr.Image(label="Pie Chart", height=500)
with gr.Row():
status_output = gr.Textbox(label="Summary Statistics", lines=10)
plot_btn.click(plot_pie_chart, [labels_input, values_input], [plot_output, status_output])
with gr.Tab("Get Coordinates"):
gr.Markdown("### Find Latitude and Longitude")
gr.Markdown("Enter a location name to get its coordinates")
location_input = gr.Textbox(label="Location Name", placeholder="e.g., Grombalia, Paris, New York", value="Grombalia")
coord_btn = gr.Button("Get Coordinates", variant="primary")
coord_output = gr.Textbox(label="Result", lines=5)
coord_btn.click(lambda loc: get_coordinates(loc)[2], [location_input], coord_output)
with gr.Tab("Weather Data"):
gr.Markdown("### Fetch Historical Weather Data")
gr.Markdown("Get weather statistics for a location and date range")
with gr.Row():
with gr.Column():
weather_location = gr.Textbox(label="Location Name", placeholder="e.g., Grombalia, London, Tokyo", value="Grombalia")
start_date_input = gr.Textbox( label="Start Date (YYYY-MM-DD)", value="2025-01-01")
end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", value="2025-01-07")
variables_input = gr.Textbox(label="Variables (comma-separated)",value="temperature_2m, wind_speed_10m, direct_normal_irradiance", placeholder="e.g., temperature_2m, precipitation, wind_speed_10m", lines=2)
weather_btn = gr.Button("Fetch Weather Data", variant="primary")
with gr.Row():
weather_output = gr.Textbox(label="Weather Statistics", lines=15)
weather_btn.click(fetch_weather_wrapper, [weather_location, start_date_input, end_date_input, variables_input], weather_output)
with gr.Tab("Object Detection"):
gr.Markdown("### Upload an Image for Object Detection")
img_input = gr.Image(type="pil", label="Upload Image")
detect_btn = gr.Button("Run Detection", variant="primary")
detect_output = gr.Textbox(label="Detection Results (JSON)", lines=15)
detect_btn.click(predict, img_input, detect_output)
with gr.Tab("Green Light Time Estimator"):
gr.Markdown("### Estimate Green Light Time")
gr.Markdown("Enter the number of Passenger Car Unit (PCU) to estimate the required green light time")
pcu_input = gr.Number(label="Number of PCU", value=0)
green_light_btn = gr.Button("Estimate Green Light Time", variant="primary")
green_light_output = gr.Textbox(label="Result", lines=1)
green_light_btn.click(Green_light_time_estimator, pcu_input, green_light_output)
with gr.Tab("Passenger Car Unit Calculator"):
gr.Markdown("### Calculate Passenger Car Unit (PCU)")
gr.Markdown("Enter the number of vehicle per class to estimate the number of Passenger Car Unit (PCU)")
Bikes = gr.Number(label="Number of Motorcycles + bikes", value=0)
Cars = gr.Number(label="Number of Cars", value=0)
Busses = gr.Number(label="Number of Busses", value=0)
Trucks = gr.Number(label="Number of Trucks", value=0)
pcu_btn = gr.Button("Calculate PCU", variant="primary")
pcu_output = gr.Textbox(label="Result", lines=1)
pcu_btn.click(Passenger_Car_Unit_Calculator, [Bikes, Cars, Busses, Trucks], pcu_output)
if __name__ == "__main__":
demo.launch(mcp_server=True)