Spaces:
Runtime error
Runtime error
Update new_app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798import streamlit as stimport kerasimport numpy as npfrom PIL import Imageimport io, os, urllib.requestst.set_page_config(layout="wide")@st.cache_data(show_spinner=False, ttl=3600)def fetch_satellite_tile(lat, lng, zoom=16, size=(640, 640), api_key=""):if not api_key:raise RuntimeError("Google Static Maps API key is missing.")# Build URLsize_str = f"{size[0]}x{size[1]}"url = ("https://maps.googleapis.com/maps/api/staticmap?"f"center={lat},{lng}&zoom={zoom}&size={size_str}&maptype=satellite&scale=2&key={api_key}")# Fetch with timeoutreq = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})with urllib.request.urlopen(req, timeout=10) as resp:buffer = io.BytesIO(resp.read())return Image.open(buffer).convert("RGB")@st.cache_resourcedef get_model():# compile=False speeds loading; prefer model(...) over .predict for TFreturn keras.models.load_model("0.0008-0.92.keras", compile=False)def preprocess(img: Image.Image, size=(640, 640)) -> np.ndarray:img = img.resize(size, Image.BILINEAR)arr = np.asarray(img, dtype=np.float32)# adjust this normalization to match trainingarr = arr / 255.0return np.expand_dims(arr, axis=0)def status_text(pct: float) -> str:if pct >= 90:return "extremely likely"elif pct >= 60:return "likely"elif pct >= 40:return "a coin toss whether"elif pct >= 10:return "unlikely"else:return "extremely unlikely"st.markdown("""<style>.block-container { padding-top: 1rem; padding-bottom: 0rem; padding-left: 5rem; padding-right: 5rem; }</style>""", unsafe_allow_html=True)img_size = (640, 640)model = get_model()col1, col2 = st.columns(2)with col1:st.header("Overpass Identifier")with col2:st.image("overpass.png")st.write("---")# Defaultslat = st.session_state.get("lat", 39.11)lng = st.session_state.get("lng", -86.56)with st.form("coords"):st.subheader("Enter latitude/longitude coordinates:")c1, c2 = st.columns(2)with c1:lat = st.number_input("Latitude", value=float(lat), min_value=-90.0, max_value=90.0, step=0.01, format="%.4f")with c2:lng = st.number_input("Longitude", value=float(lng), min_value=-180.0, max_value=180.0, step=0.01, format="%.4f")submitted = st.form_submit_button("Get Image and Prediction")if submitted:st.session_state.lat, st.session_state.lng = lat, lngapi_key = os.getenv("goog_api", "")try:with st.spinner("Fetching satellite tile..."):img = fetch_satellite_tile(lat, lng, size=img_size, api_key=api_key)st.image(img, caption=f"{lat:.4f}, {lng:.4f}", use_column_width=True)with st.spinner("Running inference..."):x = preprocess(img, size=img_size)# Prefer model(x, training=False) for speed; adjust index if your model output differsy = model(x, training=False).numpy()crossing_chance = float(y[0][1] * 100.0)status = status_text(crossing_chance)st.markdown(f"**It’s {status} that there’s an overpass here.**")st.write(f"In fact, the likelihood of at least one overpass is **{crossing_chance:.2f}%**.")except Exception as e:st.error(f"Error fetching image or running prediction: {e}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import streamlit as stimport kerasimport numpy as npfrom PIL import Imageimport io, os, urllib.requestst.set_page_config(layout="wide")# ---------- Caching & helpers ----------@st.cache_data(show_spinner=False, ttl=3600)def fetch_satellite_tile(lat, lng, zoom=16, size=(640, 640), api_key=""):if not api_key:raise RuntimeError("Google Static Maps API key is missing.")size_str = f"{size[0]}x{size[1]}"url = ("https://maps.googleapis.com/maps/api/staticmap?"f"center={lat},{lng}&zoom={zoom}&size={size_str}&maptype=satellite&scale=2&key={api_key}")req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})with urllib.request.urlopen(req, timeout=10) as resp:buffer = io.BytesIO(resp.read())return Image.open(buffer).convert("RGB")@st.cache_resourcedef get_model():return keras.models.load_model("0.0008-0.92.keras", compile=False)def preprocess(img: Image.Image, size=(640, 640)) -> np.ndarray:img = img.resize(size, Image.BILINEAR)arr = np.asarray(img, dtype=np.float32) / 255.0return np.expand_dims(arr, axis=0)def status_text(pct: float) -> str:if pct >= 90: return "extremely likely"if pct >= 60: return "likely"if pct >= 40: return "a coin toss whether"if pct >= 10: return "unlikely"return "extremely unlikely"# ---------- Styling ----------st.markdown("""<style>.block-container { padding-top: 1rem; padding-bottom: 0rem; padding-left: 5rem; padding-right: 5rem; }</style>""", unsafe_allow_html=True)# ---------- Header row (two columns) ----------h1, h2 = st.columns([1,1], gap="large")with h1:st.header("Overpass Identifier")with h2:st.image("overpass.png")st.write("---")# Defaultsimg_size = (640, 640)model = get_model()lat = st.session_state.get("lat", 39.11)lng = st.session_state.get("lng", -86.56)# ---------- Main content row (three columns: Pred | Image | Inputs) ----------pred_col, img_col, form_col = st.columns([1,1,1], gap="large")# Right: inputs (form to avoid mid-typing reruns)with form_col:st.subheader("Enter latitude/longitude coordinates:")with st.form("coords"):c1, c2 = st.columns(2)with c1:lat = st.number_input("Latitude", value=float(lat), min_value=-90.0, max_value=90.0, step=0.01, format="%.4f")with c2:lng = st.number_input("Longitude", value=float(lng), min_value=-180.0, max_value=180.0, step=0.01, format="%.4f")submitted = st.form_submit_button("Get Image and Prediction")# Center: imageimg = Noneif submitted:st.session_state.lat, st.session_state.lng = lat, lngtry:with st.spinner("Fetching satellite tile..."):img = fetch_satellite_tile(lat, lng, size=img_size, api_key=os.getenv("goog_api", ""))except Exception as e:st.error(f"Error fetching image: {e}")with img_col:if img is not None:st.image(img, caption=f"{lat:.4f}, {lng:.4f}", use_column_width=True)# Left: predictionwith pred_col:st.subheader("Prediction")if img is not None:with st.spinner("Running inference..."):x = preprocess(img, size=img_size)y = model(x, training=False).numpy() # adjust index if your model differscrossing_chance = float(y[0][1] * 100.0)st.markdown(f"**It’s {status_text(crossing_chance)} that there’s an overpass here.**")st.write(f"Estimated probability: **{crossing_chance:.2f}%**.")else:st.caption("Submit coordinates to see the satellite image and prediction.")
new_app.py+101-98