Spaces:
Runtime error
Runtime error
Update new_app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001 unmodified lineimport 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:arr = np.asarray(img, dtype=np.float32) # no /255.0, no resizereturn 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.")1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341 unmodified lineimport kerasimport numpy as npfrom PIL import Imageimport io, urllib.request, osst.set_page_config(layout="wide")@st.cache_data(show_spinner=False, ttl=600)def fetch_satellite_tile(lat, lng, zoom=16, size="640x640", api_key=""):if not api_key:raise RuntimeError("Missing Google Static Maps API key in env var 'goog_api'.")url = (f"https://maps.googleapis.com/maps/api/staticmap?"f"center={lat},{lng}&zoom={zoom}&size={size}&maptype=satellite&key={api_key}")buffer = io.BytesIO(urllib.request.urlopen(url, timeout=10).read())return Image.open(buffer).convert("RGB")@st.cache_resourcedef get_model():# compile=False skips optimizer/state rebuild, which saves timereturn keras.models.load_model("0.0008-0.92.keras", compile=False)st.markdown("""<style>.block-container {padding-top: 1rem;padding-bottom: 0rem;padding-left: 5rem;padding-right: 5rem;}</style>""", unsafe_allow_html=True)#titlecol1, col2 = st.columns(2)with col1:_, col = st.columns(2)with col:st.header('Overpass Identifier')with col2:_, col, _ = st.columns(3)with col:st.image('overpass.png')st.write("---")#load model and initialize image size required by model. uploaded images are resized to indicated sizeimg_height = 640img_width = 640state = st.session_statestate.loaded_model = get_model()#if "loaded_model" not in state:# with st.spinner('Loading model. This may take a few seconds...'):# state.loaded_model = keras.models.load_model("0.0008-0.92.keras")if "lat" not in state:state.lat = 39.11if "lng" not in state:state.lng = -86.56if "coords_submitted" not in state:state.coords_submitted = Falseif "img" not in state:state.img = None# Preload default image onceif state.img is None:try:api_key = os.getenv("goog_api", "")state.img = fetch_satellite_tile(state.lat, state.lng, api_key=api_key)except Exception as e:st.info(f"Couldn’t fetch default tile: {e}")col1, col2, col3 = st.columns(3)with col3:#headerst.subheader('Enter latitude/longitude coordinates:')coll, colr= st.columns(2)with coll:state.lat = st.number_input('Latitude', value=39.11, min_value=-90., max_value=90., step=.01)st.write('The current lat/long are:')with colr:state.lng = st.number_input('Longitude', value=-86.56, min_value=-180., max_value=180., step=.01)st.write(str(state.lat)+', '+str(state.lng))with st.form("my_form"):submit_button = st.form_submit_button(label="Get Image and Prediction", on_click=lambda: state.update(coords_submitted=True))with col2:if state.coords_submitted:state.coords_submitted = Falsetry:api_key = os.getenv("goog_api", "")state.img = fetch_satellite_tile(state.lat, state.lng, api_key=api_key)except Exception as e:st.error(f"Error fetching image: {e}")if state.img is not None:st.image(state.img, use_container_width = True)with col1:st.subheader("Prediction")if state.img is not None:img_array = np.array(state.img)batch_size = 1img_array = np.reshape(img_array,[batch_size,img_height,img_width,3])with st.spinner("Running inference..."):result = state.loaded_model.predict(img_array)crossing_chance = result[0][1]*100status = Noneif crossing_chance >= 90:status = "extremely likely"elif crossing_chance >= 60:status = "likely"elif crossing_chance >= 40:status = "a coin toss whether"elif crossing_chance >= 10:status = "unlikely"elif crossing_chance >= 0:status = "extremely unlikely"st.write(f"It's {status} there's an overpass here.")st.write("")st.write(f"In fact, the likelihood of at least one overpass is {np.round(crossing_chance,decimals=2)}%.")
new_app.py+107-73