tstone87 commited on
Commit
f98a043
·
verified ·
1 Parent(s): f0f9dff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -98
app.py CHANGED
@@ -1,114 +1,112 @@
1
- # Import required libraries
2
- import PIL
3
- import cv2
4
  import streamlit as st
 
 
5
  from ultralytics import YOLO
6
  import tempfile
 
7
 
 
 
 
 
 
 
 
 
8
 
9
- # Replace the relative path to your weight file
10
- model_path = 'https://huggingface.co/spaces/ankitkupadhyay/fire_and_smoke/blob/main/best.pt'
11
-
12
- # Setting page layout
13
  st.set_page_config(
14
- page_title="WildfireWatch", # Setting page title
15
- page_icon="🔥", # Setting page icon
16
- layout="wide", # Setting layout to wide
17
- initial_sidebar_state="expanded" # Expanding sidebar by default
18
  )
19
 
20
- # Creating sidebar
21
- with st.sidebar:
22
- st.header("IMAGE/VIDEO UPLOAD") # Adding header to sidebar
23
- # Adding file uploader to sidebar for selecting images and videos
24
- source_file = st.file_uploader(
25
- "Choose an image or video...", type=("jpg", "jpeg", "png", 'bmp', 'webp', 'mp4'))
26
-
27
- # Model Options
28
- confidence = float(st.slider(
29
- "Select Model Confidence", 25, 100, 40)) / 100
30
-
31
- # Creating main page heading
32
  st.title("WildfireWatch: Detecting Wildfire using AI")
 
 
 
 
 
 
 
33
 
34
- # Adding informative pictures and description about the motivation for the app
35
- col1, col2 = st.columns(2)
36
- with col1:
37
- st.image("https://huggingface.co/spaces/ankitkupadhyay/fire_and_smoke/resolve/main/Fire_1.jpeg", use_column_width=True)
38
- with col2:
39
- st.image("https://huggingface.co/spaces/ankitkupadhyay/fire_and_smoke/resolve/main/Fire_2.jpeg", use_column_width=True)
40
 
41
- st.markdown("""
42
- Wildfires are a major environmental issue, causing substantial losses to ecosystems, human livelihoods, and potentially leading to loss of life. Early detection of wildfires can prevent these losses. Our application, WildfireWatch, uses state-of-the-art YOLOv8 model for real-time wildfire and smoke detection in images and videos.
43
- """)
 
 
 
 
 
 
44
 
45
- st.markdown("---") # Adding a horizontal line
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- st.header("Let's Detect Wildfire")
 
 
 
 
 
 
48
 
49
- # Creating two columns on the main page
50
- col1, col2 = st.columns(2)
 
51
 
52
- # Adding image to the first column if image is uploaded
53
- with col1:
54
- if source_file:
55
- # Check if the file is an image
56
- if source_file.type.split('/')[0] == 'image':
57
- # Opening the uploaded image
58
- uploaded_image = PIL.Image.open(source_file)
59
- # Adding the uploaded image to the page with a caption
60
- st.image(source_file,
61
- caption="Uploaded Image",
62
- use_column_width=True
63
- )
64
- else:
65
- tfile = tempfile.NamedTemporaryFile(delete=False)
66
- tfile.write(source_file.read())
67
- vidcap = cv2.VideoCapture(tfile.name)
68
 
69
- try:
70
- model = YOLO(model_path)
71
- except Exception as ex:
72
- st.error(
73
- f"Unable to load model. Check the specified path: {model_path}")
74
- st.error(ex)
75
-
76
- if st.sidebar.button('Let\'s Detect Wildfire'):
77
- if source_file.type.split('/')[0] == 'image':
78
- res = model.predict(uploaded_image,
79
- conf=confidence
80
- )
81
- boxes = res[0].boxes
82
- res_plotted = res[0].plot()[:, :, ::-1]
83
- with col2:
84
- st.image(res_plotted,
85
- caption='Detected Image',
86
- use_column_width=True
87
- )
88
- try:
89
- with st.expander("Detection Results"):
90
- for box in boxes:
91
- st.write(box.xywh)
92
- except Exception as ex:
93
- st.write("No image is uploaded yet!")
94
- else:
95
- # Open the video file
96
- success, image = vidcap.read()
97
- while success:
98
- res = model.predict(image,
99
- conf=confidence
100
- )
101
- boxes = res[0].boxes
102
- res_plotted = res[0].plot()[:, :, ::-1]
103
- with col2:
104
- st.image(res_plotted,
105
- caption='Detected Frame',
106
- use_column_width=True
107
- )
108
- try:
109
- with st.expander("Detection Results"):
110
- for box in boxes:
111
- st.write(box.xywh)
112
- except Exception as ex:
113
- st.write("No video is uploaded yet!")
114
- success, image = vidcap.read()
 
 
 
 
1
  import streamlit as st
2
+ import cv2
3
+ import PIL
4
  from ultralytics import YOLO
5
  import tempfile
6
+ import time
7
 
8
+ # ----------------------------------------------------------------
9
+ # Load the model (using a URL to your weight file)
10
+ model_path = 'https://huggingface.co/spaces/tstone87/ccr-colorado/blob/main/best.pt'
11
+ try:
12
+ model = YOLO(model_path)
13
+ except Exception as ex:
14
+ st.error(f"Unable to load model. Check the specified path: {model_path}")
15
+ st.error(ex)
16
 
17
+ # ----------------------------------------------------------------
18
+ # Set page configuration
 
 
19
  st.set_page_config(
20
+ page_title="WildfireWatch",
21
+ page_icon="🔥",
22
+ layout="wide",
23
+ initial_sidebar_state="expanded"
24
  )
25
 
26
+ # ----------------------------------------------------------------
27
+ # App Title and Description
 
 
 
 
 
 
 
 
 
 
28
  st.title("WildfireWatch: Detecting Wildfire using AI")
29
+ st.markdown(
30
+ """
31
+ **Wildfires are a critical threat to ecosystems and communities.**
32
+ Early detection can save lives and reduce environmental damage.
33
+ Use this app to analyze images, videos, or live webcam streams for signs of fire.
34
+ """
35
+ )
36
 
37
+ # ----------------------------------------------------------------
38
+ # Create two tabs: one for file uploads and one for live webcam stream detection
39
+ tab_upload, tab_live = st.tabs(["Upload Image/Video", "Live Webcam Stream"])
 
 
 
40
 
41
+ # =========================
42
+ # Tab 1: File Upload for Image/Video Detection
43
+ with tab_upload:
44
+ st.header("Upload an Image or Video")
45
+ uploaded_file = st.file_uploader(
46
+ "Choose an image or video...",
47
+ type=["jpg", "jpeg", "png", "bmp", "webp", "mp4"]
48
+ )
49
+ confidence = st.slider("Select Model Confidence", 25, 100, 40) / 100
50
 
51
+ if uploaded_file is not None:
52
+ if uploaded_file.type.split('/')[0] == 'image':
53
+ # Process uploaded image
54
+ image = PIL.Image.open(uploaded_file)
55
+ st.image(image, caption="Uploaded Image", use_column_width=True)
56
+ if st.button("Detect Wildfire in Image"):
57
+ results = model.predict(image, conf=confidence)
58
+ annotated_image = results[0].plot()[:, :, ::-1]
59
+ st.image(annotated_image, caption="Detection Result", use_column_width=True)
60
+ with st.expander("Detection Details"):
61
+ for box in results[0].boxes:
62
+ st.write("Box coordinates (xywh):", box.xywh)
63
+ elif uploaded_file.type.split('/')[0] == 'video':
64
+ # Process uploaded video
65
+ tfile = tempfile.NamedTemporaryFile(delete=False)
66
+ tfile.write(uploaded_file.read())
67
+ cap = cv2.VideoCapture(tfile.name)
68
+ if st.button("Detect Wildfire in Video"):
69
+ frame_placeholder = st.empty()
70
+ while cap.isOpened():
71
+ ret, frame = cap.read()
72
+ if not ret:
73
+ break
74
+ results = model.predict(frame, conf=confidence)
75
+ annotated_frame = results[0].plot()[:, :, ::-1]
76
+ frame_placeholder.image(annotated_frame, channels="BGR", use_column_width=True)
77
+ time.sleep(0.05) # Adjust delay for processing speed
78
+ cap.release()
79
 
80
+ # =========================
81
+ # Tab 2: Live Webcam Stream Detection
82
+ with tab_live:
83
+ st.header("Live Webcam Stream Detection")
84
+ st.markdown("Enter the URL for your online hosted webcam stream (e.g., an IP camera stream).")
85
+ webcam_url = st.text_input("Webcam Stream URL", value="http://<your_webcam_stream_url>")
86
+ live_confidence = st.slider("Select Live Detection Confidence", 25, 100, 40) / 100
87
 
88
+ # Initialize a session state flag for stopping the live loop
89
+ if "stop_live" not in st.session_state:
90
+ st.session_state.stop_live = False
91
 
92
+ def stop_live_detection():
93
+ st.session_state.stop_live = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
+ if st.button("Start Live Detection"):
96
+ cap = cv2.VideoCapture(webcam_url)
97
+ if not cap.isOpened():
98
+ st.error("Unable to open webcam stream. Please check the URL.")
99
+ else:
100
+ live_frame_placeholder = st.empty()
101
+ st.button("Stop Live Detection", on_click=stop_live_detection)
102
+ while cap.isOpened() and not st.session_state.stop_live:
103
+ ret, frame = cap.read()
104
+ if not ret:
105
+ st.error("Failed to retrieve frame from stream.")
106
+ break
107
+ results = model.predict(frame, conf=live_confidence)
108
+ annotated_frame = results[0].plot()[:, :, ::-1]
109
+ live_frame_placeholder.image(annotated_frame, channels="BGR", use_column_width=True)
110
+ time.sleep(0.05)
111
+ cap.release()
112
+ st.session_state.stop_live = False