MLDeveloper's picture
Update app.py
b73a0cb verified
import streamlit as st
import requests
import firebase_admin
from firebase_admin import credentials, db, auth
from PIL import Image
import numpy as np
from geopy.geocoders import Nominatim
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input
import json
# Initialize Firebase
if not firebase_admin._apps:
cred = credentials.Certificate("firebase_credentials.json")
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://binsight-beda0-default-rtdb.asia-southeast1.firebasedatabase.app/'
})
# Load MobileNetV2 pre-trained model
mobilenet_model = MobileNetV2(weights="imagenet")
# Function to classify the uploaded image using MobileNetV2
def classify_image_with_mobilenet(image):
try:
img = image.resize((224, 224))
img_array = np.array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
predictions = mobilenet_model.predict(img_array)
labels = decode_predictions(predictions, top=5)[0]
return {label[1]: float(label[2]) for label in labels}
except Exception as e:
st.error(f"Error during image classification: {e}")
return {}
# Function to get user's location using geolocation API
def get_user_location():
st.write("Fetching location, please allow location access in your browser.")
geolocator = Nominatim(user_agent="binsight")
try:
ip_info = requests.get("https://ipinfo.io/json").json()
loc = ip_info.get("loc", "").split(",")
latitude, longitude = loc[0], loc[1] if len(loc) == 2 else (None, None)
if latitude and longitude:
address = geolocator.reverse(f"{latitude}, {longitude}").address
return latitude, longitude, address
except Exception as e:
st.error(f"Error retrieving location: {e}")
return None, None, None
# User Login
st.sidebar.header("User Login")
user_email = st.sidebar.text_input("Enter your email")
login_button = st.sidebar.button("Login")
if login_button:
if user_email:
st.session_state["user_email"] = user_email
st.sidebar.success(f"Logged in as {user_email}")
if "user_email" not in st.session_state:
st.warning("Please log in first.")
st.stop()
# Get user location and display details
latitude, longitude, address = get_user_location()
if latitude and longitude:
st.success(f"Location detected: {address}")
else:
st.warning("Unable to fetch location, please ensure location access is enabled.")
st.stop()
# Streamlit App
st.title("BinSight: Upload Dustbin Image")
uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"])
submit_button = st.button("Analyze and Upload")
if submit_button and uploaded_file:
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded Image", use_container_width=True)
classification_results = classify_image_with_mobilenet(image)
if classification_results:
db_ref = db.reference("dustbins")
dustbin_data = {
"user_email": st.session_state["user_email"],
"latitude": latitude,
"longitude": longitude,
"address": address,
"classification": classification_results,
"allocated_truck": None,
"status": "Pending"
}
db_ref.push(dustbin_data)
st.success("Dustbin data uploaded successfully!")
st.write(f"**Location:** {address}")
st.write(f"**Latitude:** {latitude}, **Longitude:** {longitude}")
else:
st.error("Missing classification details. Cannot upload.")