Update streamlit_app_combined.py
Browse files2 unmodified lines345678910111210 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666 unmodified lines737475767778797 unmodified lines8788899091929394959697989910010110210310410510610710810930 unmodified lines1401411421431441451461472 unmodified linesimport cv2from PIL import Imageimport tensorflow as tfimport requestsimport osst.set_page_config(page_title="Pothole Detection", layout="centered")# 🏢 Add NHAI logo top-right using HTMLst.markdown("""<style>10 unmodified linesunsafe_allow_html=True)st.title("🛣️ AI-Based Pothole Detection & Water Logging")# ✅ TFLite model detailsMODEL_URL = "https://drive.google.com/file/d/1l4UAi3pK65nt7JrKhHTuopPqUfFL8ZcC/view?usp=share_link"MODEL_PATH = "pothole_model.tflite"# ✅ Download the model only if not already presentif not os.path.exists(MODEL_PATH):response = requests.get(MODEL_URL)if response.status_code == 200:with open(MODEL_PATH, "wb") as f:f.write(response.content)print("✅ TFLite model downloaded successfully.")else:raise ValueError(f"❌ Model download failed. Status: {response.status_code}")# ✅ Load the TFLite modelinterpreter = tf.lite.Interpreter(model_path=MODEL_PATH)interpreter.allocate_tensors()# ✅ Get input/output detailsinput_details = interpreter.get_input_details()output_details = interpreter.get_output_details()uploaded_file = st.file_uploader("📤 Upload a road image", type=["jpg", "jpeg", "png"])# Prediction Functiondef predict_pothole(image: Image.Image):img_resized = image.resize((128, 128))img_array = np.array(img_resized, dtype=np.float32) / 255.0img_array = np.expand_dims(img_array, axis=0)interpreter.set_tensor(input_details[0]['index'], img_array)interpreter.invoke()output_data = interpreter.get_tensor(output_details[0]['index'])return output_data[0][0]# Estimate pothole severitydef estimate_severity(img_cv):gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)_, thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)6 unmodified lineselse:return "High"# Bounding box calculationdef bounding_box(img_cv):img_resized = cv2.resize(img_cv, (128, 128))gray = cv2.cvtColor(img_resized, cv2.COLOR_BGR2GRAY)7 unmodified linescv2.rectangle(img_resized, (x, y), (x+w, y+h), (255, 0, 0), 2)return area, (x, y, w, h), img_resized# Water logging detectiondef detect_water_logging(img_cv):img_resized = cv2.resize(img_cv, (128, 128))gray = cv2.cvtColor(img_resized, cv2.COLOR_BGR2GRAY)_, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV)contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)water_detected = Falsetotal_area = 0for c in contours:area = cv2.contourArea(c)if area > 500:total_area += areawater_detected = Truecv2.drawContours(img_resized, [c], -1, (255, 0, 0), 2)return water_detected, int(total_area), img_resized# Streamlit Main Logicif uploaded_file:image = Image.open(uploaded_file).convert("RGB")st.image(image, caption="Uploaded Image", use_column_width=True)30 unmodified lines2 unmodified lines34567891011121310 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636 unmodified lines707172737475767 unmodified lines8485868788899091929394959697989910010110210310410510630 unmodified lines1371381392 unmodified linesimport cv2from PIL import Imageimport tensorflow as tfimport gdownimport os# --- UI SETUP ---st.set_page_config(page_title="Pothole Detection", layout="centered")st.markdown("""<style>10 unmodified linesunsafe_allow_html=True)st.title("🛣️ AI-Based Pothole Detection & Water Logging")st.markdown("Upload a road image to detect potholes, estimate severity, and detect water logging.")# --- DOWNLOAD MODEL FROM GOOGLE DRIVE IF NOT EXISTS ---MODEL_ID = "1l4UAi3pK65nt7JrKhHTuopPqUfFL8ZcC"MODEL_PATH = "pothole_model.tflite"if not os.path.exists(MODEL_PATH):gdown.download(id=MODEL_ID, output=MODEL_PATH, quiet=False)# --- VALIDATE FILE HEADER (MUST START WITH TFL3) ---with open(MODEL_PATH, "rb") as f:if f.read(4) != b'TFL3':raise ValueError("❌ Invalid TFLite model format: Expected header 'TFL3'")# --- LOAD TFLITE MODEL ---interpreter = tf.lite.Interpreter(model_path=MODEL_PATH)interpreter.allocate_tensors()input_details = interpreter.get_input_details()output_details = interpreter.get_output_details()# --- IMAGE UPLOAD ---uploaded_file = st.file_uploader("📤 Upload a road image", type=["jpg", "jpeg", "png"])# --- PREDICTION FUNCTION ---def predict_pothole(image: Image.Image):img_resized = image.resize((128, 128))img_array = np.array(img_resized, dtype=np.float32) / 255.0img_array = np.expand_dims(img_array, axis=0)interpreter.set_tensor(input_details[0]['index'], img_array)interpreter.invoke()return interpreter.get_tensor(output_details[0]['index'])[0][0]# --- SEVERITY ESTIMATION ---def estimate_severity(img_cv):gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)_, thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV)6 unmodified lineselse:return "High"# --- BOUNDING BOX DRAWING ---def bounding_box(img_cv):img_resized = cv2.resize(img_cv, (128, 128))gray = cv2.cvtColor(img_resized, cv2.COLOR_BGR2GRAY)7 unmodified linescv2.rectangle(img_resized, (x, y), (x+w, y+h), (255, 0, 0), 2)return area, (x, y, w, h), img_resized# --- WATER LOGGING DETECTION ---def detect_water_logging(img_cv):img_resized = cv2.resize(img_cv, (128, 128))gray = cv2.cvtColor(img_resized, cv2.COLOR_BGR2GRAY)_, thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY_INV)contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)total_area = 0water_detected = Falsefor c in contours:area = cv2.contourArea(c)if area > 500:total_area += areawater_detected = Truecv2.drawContours(img_resized, [c], -1, (255, 0, 0), 2)return water_detected, total_area, img_resized# --- MAIN LOGIC ---if uploaded_file:image = Image.open(uploaded_file).convert("RGB")st.image(image, caption="Uploaded Image", use_column_width=True)30 unmodified lines
streamlit_app_combined.py+22-30