File size: 3,714 Bytes
7b6f1ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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.")