Update app.py
#12
by
MLDeveloper
- opened
app.py
CHANGED
@@ -1,17 +1,16 @@
|
|
|
|
1 |
import streamlit as st
|
2 |
-
import requests
|
3 |
import firebase_admin
|
4 |
-
from firebase_admin import credentials, db
|
5 |
from PIL import Image
|
6 |
import numpy as np
|
7 |
from geopy.geocoders import Nominatim
|
8 |
from tensorflow.keras.applications import MobileNetV2
|
9 |
from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input
|
10 |
-
import json
|
11 |
import base64
|
12 |
from io import BytesIO
|
13 |
|
14 |
-
# Initialize Firebase
|
15 |
if not firebase_admin._apps:
|
16 |
cred = credentials.Certificate("firebase_credentials.json")
|
17 |
firebase_admin.initialize_app(cred, {
|
@@ -35,57 +34,86 @@ def classify_image_with_mobilenet(image):
|
|
35 |
st.error(f"Error during image classification: {e}")
|
36 |
return {}
|
37 |
|
38 |
-
# Function to get user's location
|
39 |
-
def get_user_location():
|
40 |
-
st.write("Fetching location, please allow location access in your browser.")
|
41 |
-
geolocator = Nominatim(user_agent="binsight")
|
42 |
-
try:
|
43 |
-
ip_info = requests.get("https://ipinfo.io/json").json()
|
44 |
-
loc = ip_info.get("loc", "").split(",")
|
45 |
-
latitude, longitude = loc[0], loc[1] if len(loc) == 2 else (None, None)
|
46 |
-
if latitude and longitude:
|
47 |
-
address = geolocator.reverse(f"{latitude}, {longitude}").address
|
48 |
-
return latitude, longitude, address
|
49 |
-
except Exception as e:
|
50 |
-
st.error(f"Error retrieving location: {e}")
|
51 |
-
return None, None, None
|
52 |
-
|
53 |
# Function to convert image to Base64
|
54 |
def convert_image_to_base64(image):
|
55 |
buffered = BytesIO()
|
56 |
-
image.save(buffered, format="PNG")
|
57 |
-
img_str = base64.b64encode(buffered.getvalue()).decode()
|
58 |
return img_str
|
59 |
|
60 |
-
#
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
if
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
-
|
71 |
-
|
72 |
-
st.stop()
|
73 |
|
74 |
-
#
|
75 |
-
|
76 |
-
|
77 |
-
st.success(f"Location detected: {address}")
|
78 |
-
else:
|
79 |
-
st.warning("Unable to fetch location, please enable location access.")
|
80 |
-
st.stop()
|
81 |
|
82 |
# Streamlit App
|
83 |
st.title("BinSight: Upload Dustbin Image")
|
84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"])
|
86 |
submit_button = st.button("Analyze and Upload")
|
87 |
|
88 |
-
if submit_button and uploaded_file:
|
89 |
image = Image.open(uploaded_file)
|
90 |
st.image(image, caption="Uploaded Image", use_container_width=True)
|
91 |
|
@@ -98,19 +126,15 @@ if submit_button and uploaded_file:
|
|
98 |
if classification_results:
|
99 |
db_ref = db.reference("dustbins")
|
100 |
dustbin_data = {
|
101 |
-
"user_email": st.session_state["user_email"],
|
102 |
"latitude": latitude,
|
103 |
"longitude": longitude,
|
104 |
-
"
|
105 |
"classification": classification_results,
|
106 |
-
"allocated_truck": None,
|
107 |
"status": "Pending",
|
108 |
"image": image_base64 # Store image as Base64 string
|
109 |
}
|
110 |
db_ref.push(dustbin_data)
|
111 |
st.success("Dustbin data uploaded successfully!")
|
112 |
-
st.write(f"**Location:** {address}")
|
113 |
-
st.write(f"**Latitude:** {latitude}, **Longitude:** {longitude}")
|
114 |
else:
|
115 |
st.error("Missing classification details. Cannot upload.")
|
116 |
|
@@ -118,9 +142,6 @@ if submit_button and uploaded_file:
|
|
118 |
|
119 |
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
# best without image
|
125 |
|
126 |
# import streamlit as st
|
|
|
1 |
+
|
2 |
import streamlit as st
|
|
|
3 |
import firebase_admin
|
4 |
+
from firebase_admin import credentials, db
|
5 |
from PIL import Image
|
6 |
import numpy as np
|
7 |
from geopy.geocoders import Nominatim
|
8 |
from tensorflow.keras.applications import MobileNetV2
|
9 |
from tensorflow.keras.applications.mobilenet_v2 import decode_predictions, preprocess_input
|
|
|
10 |
import base64
|
11 |
from io import BytesIO
|
12 |
|
13 |
+
# Initialize Firebase
|
14 |
if not firebase_admin._apps:
|
15 |
cred = credentials.Certificate("firebase_credentials.json")
|
16 |
firebase_admin.initialize_app(cred, {
|
|
|
34 |
st.error(f"Error during image classification: {e}")
|
35 |
return {}
|
36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
# Function to convert image to Base64
|
38 |
def convert_image_to_base64(image):
|
39 |
buffered = BytesIO()
|
40 |
+
image.save(buffered, format="PNG")
|
41 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
42 |
return img_str
|
43 |
|
44 |
+
# Function to get detailed location info from latitude & longitude
|
45 |
+
def get_location_details(lat, lon):
|
46 |
+
try:
|
47 |
+
geolocator = Nominatim(user_agent="binsight")
|
48 |
+
location = geolocator.reverse((lat, lon), exactly_one=True)
|
49 |
+
if location:
|
50 |
+
address = location.raw.get('address', {})
|
51 |
+
return {
|
52 |
+
"road": address.get("road", "Unknown"),
|
53 |
+
"city": address.get("city", address.get("town", "Unknown")),
|
54 |
+
"state": address.get("state", "Unknown"),
|
55 |
+
"country": address.get("country", "Unknown"),
|
56 |
+
"full_address": location.address
|
57 |
+
}
|
58 |
+
except Exception as e:
|
59 |
+
st.error(f"Error retrieving location details: {e}")
|
60 |
+
return {}
|
61 |
+
|
62 |
+
# JavaScript to get live location and send it to Streamlit
|
63 |
+
get_location_js = """
|
64 |
+
<script>
|
65 |
+
function sendLocation() {
|
66 |
+
navigator.geolocation.getCurrentPosition(
|
67 |
+
(position) => {
|
68 |
+
const latitude = position.coords.latitude;
|
69 |
+
const longitude = position.coords.longitude;
|
70 |
+
const locationData = latitude + "," + longitude;
|
71 |
+
fetch('/_stcore/', {
|
72 |
+
method: 'POST',
|
73 |
+
headers: {'Content-Type': 'application/json'},
|
74 |
+
body: JSON.stringify({latlon: locationData})
|
75 |
+
}).then(response => response.json())
|
76 |
+
.then(data => console.log("Location sent:", data));
|
77 |
+
},
|
78 |
+
(error) => {
|
79 |
+
console.log("Error getting location:", error);
|
80 |
+
}
|
81 |
+
);
|
82 |
+
}
|
83 |
+
sendLocation();
|
84 |
+
</script>
|
85 |
+
"""
|
86 |
|
87 |
+
# Run JavaScript in Streamlit
|
88 |
+
st.components.v1.html(get_location_js, height=0)
|
|
|
89 |
|
90 |
+
# Capture location from Streamlit session state
|
91 |
+
if "latlon" not in st.session_state:
|
92 |
+
st.session_state.latlon = None
|
|
|
|
|
|
|
|
|
93 |
|
94 |
# Streamlit App
|
95 |
st.title("BinSight: Upload Dustbin Image")
|
96 |
|
97 |
+
# Fetch live location
|
98 |
+
if st.session_state.latlon:
|
99 |
+
try:
|
100 |
+
latitude, longitude = map(float, st.session_state.latlon.split(","))
|
101 |
+
location_details = get_location_details(latitude, longitude)
|
102 |
+
st.success(f"Detected Location: {location_details['full_address']}")
|
103 |
+
st.write(f"**State:** {location_details['state']}")
|
104 |
+
st.write(f"**City:** {location_details['city']}")
|
105 |
+
st.write(f"**Road:** {location_details['road']}")
|
106 |
+
st.write(f"**Country:** {location_details['country']}")
|
107 |
+
except Exception as e:
|
108 |
+
st.error(f"Error processing location: {e}")
|
109 |
+
else:
|
110 |
+
st.warning("Fetching live location... Please allow location access.")
|
111 |
+
|
112 |
+
# File uploader for dustbin images
|
113 |
uploaded_file = st.file_uploader("Upload an image of the dustbin", type=["jpg", "jpeg", "png"])
|
114 |
submit_button = st.button("Analyze and Upload")
|
115 |
|
116 |
+
if submit_button and uploaded_file and st.session_state.latlon:
|
117 |
image = Image.open(uploaded_file)
|
118 |
st.image(image, caption="Uploaded Image", use_container_width=True)
|
119 |
|
|
|
126 |
if classification_results:
|
127 |
db_ref = db.reference("dustbins")
|
128 |
dustbin_data = {
|
|
|
129 |
"latitude": latitude,
|
130 |
"longitude": longitude,
|
131 |
+
"location_details": location_details,
|
132 |
"classification": classification_results,
|
|
|
133 |
"status": "Pending",
|
134 |
"image": image_base64 # Store image as Base64 string
|
135 |
}
|
136 |
db_ref.push(dustbin_data)
|
137 |
st.success("Dustbin data uploaded successfully!")
|
|
|
|
|
138 |
else:
|
139 |
st.error("Missing classification details. Cannot upload.")
|
140 |
|
|
|
142 |
|
143 |
|
144 |
|
|
|
|
|
|
|
145 |
# best without image
|
146 |
|
147 |
# import streamlit as st
|