NeoCityAI / app.py
Dxulz's picture
Create app.py
1fc4a27 verified
Raw History Blame Contribute Delete
4.69 kB
# NeoCity AI – Smart Environmental City Classifier for Asir Hackathon
import numpy as np
import gradio as gr
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import uuid
import csv
# Training data
X = np.array([
[28, 25, 2.0, 60],
[35, 90, 5.5, 45],
[22, 15, 1.3, 70],
[40, 110, 8.0, 42],
[30, 40, 3.1, 55],
[25, 20, 0.9, 68],
[37, 95, 6.7, 48],
[29, 35, 2.6, 63],
])
y = np.array([0, 1, 0, 1, 0, 0, 1, 0]) # 0 = Friendly, 1 = Needs Help
# Model
model = Pipeline([
("scaler", StandardScaler()),
("clf", LogisticRegression())
])
model.fit(X, y)
# Score calculator
def sustainability_score(temp, pollution, pop, humidity):
score = 100
if temp > 35: score -= 15
if pollution > 80: score -= 30
if pop > 5: score -= 20
if humidity < 30 or humidity > 80: score -= 10
return max(score, 0)
# Bar chart
def make_bar_chart(temp, pollution, pop, humidity, theme="light"):
labels = ['Temperature', 'Pollution', 'Population', 'Humidity']
values = [temp, pollution, pop, humidity]
file_path = f"/tmp/env_chart_{uuid.uuid4().hex}.png"
plt.figure(figsize=(6, 4))
colors = "#2c3e50" if theme == "dark" else "#3498db"
bg = "#1e1e1e" if theme == "dark" else "#ffffff"
text = "white" if theme == "dark" else "black"
plt.rcParams['axes.facecolor'] = bg
plt.bar(labels, values, color=colors)
plt.title("Environmental Factors", color=text)
plt.xticks(color=text)
plt.yticks(color=text)
plt.tight_layout()
plt.savefig(file_path, dpi=150, facecolor=bg)
plt.close()
return file_path
# Logging
def log_prediction(name, temp, pollution, pop, humidity, pred, score):
with open("logs.csv", "a", newline="") as f:
writer = csv.writer(f)
writer.writerow([name, temp, pollution, pop, humidity, pred, score])
# SDG match
def match_sdg_goals(score):
if score > 80:
return "🌍 SDG 11 Achieved"
elif score > 60:
return "🚧 Progress toward SDG 11"
else:
return "❌ SDG 11 Not Met"
# Main function
def predict_city(temp, pollution, pop, humidity, name, size, climate, terrain, theme, feedback):
input_data = np.array([[temp, pollution, pop, humidity]])
pred = model.predict(input_data)[0]
proba = model.predict_proba(input_data)[0][pred]
score = sustainability_score(temp, pollution, pop, humidity)
chart = make_bar_chart(temp, pollution, pop, humidity, theme)
classification = "✅ Environmentally Friendly" if pred == 0 else "⚠️ Needs Environmental Intervention"
tips = (
"- Improve transport\n- Add green areas\n- Monitor air quality"
if pred == 0 else
"- Reduce emissions\n- Expand greenery\n- Use renewable energy"
)
if terrain == "Desert":
tips += "\n- Use solar power and water recycling"
elif terrain == "Coastal":
tips += "\n- Prevent marine pollution and flooding"
elif terrain == "Mountain":
tips += "\n- Monitor landslides and apply vertical farming"
security_tip = "🔒 Secure smart sensors and data."
summary = (
f"🏙️ City: {name}\n📐 Size: {size} | ☁️ Climate: {climate} | 🌍 Terrain: {terrain}\n"
f"📊 Classification: {classification}\n✅ Score: {score}/100\n"
f"🎯 SDG: {match_sdg_goals(score)}\n🔎 Confidence: {proba*100:.1f}%\n{security_tip}"
)
log_prediction(name, temp, pollution, pop, humidity, classification, score)
return summary, tips, chart, f"📩 Feedback received: {feedback}"
# Gradio Interface
inputs = [
gr.Slider(10, 50, value=30, label="🌡️ Temperature (°C)"),
gr.Slider(0, 150, value=50, label="💨 Pollution (PM2.5)"),
gr.Slider(0.1, 20, value=3.0, step=0.1, label="👥 Population (Millions)"),
gr.Slider(10, 100, value=55, label="💧 Humidity (%)"),
gr.Textbox(label="🏙️ City Name"),
gr.Radio(["Small", "Medium", "Large", "Mega"], label="📐 City Size"),
gr.Radio(["Hot", "Moderate", "Cold"], label="☁️ Climate"),
gr.Radio(["Desert", "Mountain", "Coastal", "Mixed"], label="🌍 Terrain"),
gr.Radio(["light", "dark"], value="light", label="🎨 Theme"),
gr.Textbox(label="💬 Feedback")
]
outputs = [
gr.Textbox(label="📋 Summary"),
gr.Textbox(label="🛠️ Recommendations"),
gr.Image(label="📊 Chart"),
gr.Textbox(label="🙋 Feedback Received")
]
gr.Interface(
fn=predict_city,
inputs=inputs,
outputs=outputs,
title="🌆 NeoCity AI",
description="Smart city classifier for Asir Hackathon"
).launch()