tstone87 commited on
Commit
b051880
·
verified ·
1 Parent(s): 2682db9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -92
app.py CHANGED
@@ -1,145 +1,143 @@
1
- # Import required libraries
2
- import PIL
3
  import cv2
4
  import streamlit as st
 
5
  from ultralytics import YOLO
6
- import tempfile
7
- import time
8
- import os
9
 
10
- # Replace the relative path to your weight file
11
- model_path = 'https://huggingface.co/spaces/tstone87/ccr-colorado/resolve/main/best.pt' # Your correct model
 
 
 
 
 
 
12
 
13
- # Setting page layout
14
  st.set_page_config(
15
- page_title="WildfireWatch",
16
  page_icon="🔥",
17
  layout="wide",
18
  initial_sidebar_state="expanded"
19
  )
20
 
21
- # Creating sidebar
22
  with st.sidebar:
23
  st.header("IMAGE/VIDEO UPLOAD")
24
  source_file = st.file_uploader(
25
- "Choose an image or video...", type=("jpg", "jpeg", "png", 'bmp', 'webp', 'mp4'))
26
  confidence = float(st.slider("Select Model Confidence", 25, 100, 40)) / 100
27
- sampling_options = {
28
- "Every Frame": 0,
29
- "1 FPS": 1,
30
- "2 FPS": 2,
31
- "5 FPS": 5,
32
- "1 frame / 5s": 5,
33
- "1 frame / 10s": 10,
34
- "1 frame / 15s": 15
35
- }
36
- sampling_rate = st.selectbox("Analysis Rate", list(sampling_options.keys()), index=1)
37
 
38
- # Creating main page heading
39
  st.title("WildfireWatch: Detecting Wildfire using AI")
40
-
41
- # Adding informative pictures and description about the motivation for the app
42
  col1, col2 = st.columns(2)
43
  with col1:
44
- st.image("https://huggingface.co/spaces/ankitkupadhyay/fire_and_smoke/resolve/main/Fire_1.jpeg", use_column_width=True)
45
  with col2:
46
- st.image("https://huggingface.co/spaces/ankitkupadhyay/fire_and_smoke/resolve/main/Fire_2.jpeg", use_column_width=True)
47
 
48
  st.markdown("""
49
- 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.
50
  """)
51
-
52
  st.markdown("---")
 
53
 
54
- st.header("Let's Detect Wildfire")
55
-
56
- # Creating two columns on the main page
57
  col1, col2 = st.columns(2)
 
 
 
 
 
 
 
 
 
 
58
 
59
- # Adding image to the first column if image is uploaded
60
- with col1:
61
- if source_file:
62
- if source_file.type.split('/')[0] == 'image':
63
- uploaded_image = PIL.Image.open(source_file)
64
- st.image(source_file, caption="Uploaded Image", use_column_width=True)
65
- else:
66
- tfile = tempfile.NamedTemporaryFile(delete=False)
67
- tfile.write(source_file.read())
68
- vidcap = cv2.VideoCapture(tfile.name)
69
-
70
  try:
71
  model = YOLO(model_path)
72
  except Exception as ex:
73
  st.error(f"Unable to load model. Check the specified path: {model_path}")
74
  st.error(ex)
75
- st.stop()
76
 
77
- if st.sidebar.button('Let\'s Detect Wildfire'):
78
  if not source_file:
79
- st.error("Please upload a file first!")
80
  elif source_file.type.split('/')[0] == 'image':
 
81
  res = model.predict(uploaded_image, conf=confidence)
82
  boxes = res[0].boxes
83
  res_plotted = res[0].plot()[:, :, ::-1]
84
  with col2:
85
  st.image(res_plotted, caption='Detected Image', use_column_width=True)
86
- try:
87
- with st.expander("Detection Results"):
88
- for box in boxes:
89
- st.write(box.xywh)
90
- except Exception as ex:
91
- st.write("No image is uploaded yet!")
92
  else:
93
- # Frame sampling setup
94
- total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
95
- fps = int(vidcap.get(cv2.CAP_PROP_FPS)) or 30
96
- frame_width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH))
97
- frame_height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
98
- target_rate = sampling_options[sampling_rate]
99
- frame_skip = 1 if target_rate == 0 else max(1, int(fps / target_rate) if target_rate <= 5 else int(fps * target_rate))
100
-
101
- # Output video setup
102
- output_tfile = tempfile.NamedTemporaryFile(delete=False, suffix='_detected.mp4')
103
- fourcc = cv2.VideoWriter_fourcc(*'mp4v')
104
- output_fps = 1 # Fixed for short compilation
105
- out = cv2.VideoWriter(output_tfile.name, fourcc, output_fps, (frame_width, frame_height))
106
-
107
- success, image = vidcap.read()
108
  frame_count = 0
109
- processed_count = 0
 
 
 
 
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  while success:
112
- if frame_count % frame_skip == 0:
113
  res = model.predict(image, conf=confidence)
114
- boxes = res[0].boxes
115
  res_plotted = res[0].plot()[:, :, ::-1]
 
116
  with col2:
117
  st.image(res_plotted, caption=f'Detected Frame {frame_count}', use_column_width=True)
118
- try:
119
- with st.expander("Detection Results"):
120
- for box in boxes:
121
- st.write(box.xywh)
122
- except Exception as ex:
123
- st.write("No detection results available.")
124
- out.write(res_plotted[:, :, ::-1]) # Write only analyzed frame
125
- processed_count += 1
126
- if total_frames > 0:
127
- progress = (frame_count + 1) / total_frames * 100
128
- st.write(f"Progress: {progress:.1f}% (Analyzed {processed_count} frames)")
129
- success, image = vidcap.read()
130
  frame_count += 1
131
- time.sleep(0.05)
132
-
133
- vidcap.release()
134
- out.release()
135
- os.unlink(tfile.name)
136
 
137
- with col2:
138
- with open(output_tfile.name, 'rb') as f:
 
 
 
 
 
 
 
 
139
  st.download_button(
140
- label="Download Analyzed Video",
141
- data=f,
142
- file_name="analyzed_video.mp4",
143
  mime="video/mp4"
144
  )
145
- st.write(f"Video processing complete. Analyzed {processed_count} frames.")
 
 
1
+ import os
2
+ import tempfile
3
  import cv2
4
  import streamlit as st
5
+ import PIL
6
  from ultralytics import YOLO
 
 
 
7
 
8
+ # Required libraries (ensure these are in your requirements.txt):
9
+ # streamlit
10
+ # opencv-python-headless
11
+ # ultralytics
12
+ # Pillow
13
+
14
+ # Replace with your model's URL or local path
15
+ model_path = 'https://huggingface.co/spaces/tstone87/ccr-colorado/blob/main/best.pt'
16
 
17
+ # Configure the page for Hugging Face Spaces
18
  st.set_page_config(
19
+ page_title="Fire Watch using AI vision models",
20
  page_icon="🔥",
21
  layout="wide",
22
  initial_sidebar_state="expanded"
23
  )
24
 
25
+ # Sidebar for file upload and settings
26
  with st.sidebar:
27
  st.header("IMAGE/VIDEO UPLOAD")
28
  source_file = st.file_uploader(
29
+ "Choose an image or video...", type=("jpg", "jpeg", "png", "bmp", "webp", "mp4"))
30
  confidence = float(st.slider("Select Model Confidence", 25, 100, 40)) / 100
31
+ video_option = st.selectbox(
32
+ "Select Video Shortening Option",
33
+ ["Original FPS", "1 fps", "1 frame per 5 seconds", "1 frame per 10 seconds", "1 frame per 15 seconds"]
34
+ )
 
 
 
 
 
 
35
 
36
+ # Main page header and introduction images
37
  st.title("WildfireWatch: Detecting Wildfire using AI")
 
 
38
  col1, col2 = st.columns(2)
39
  with col1:
40
+ st.image("https://huggingface.co/spaces/tstone87/ccr-colorado/resolve/main/Fire_1.jpeg", use_column_width=True)
41
  with col2:
42
+ st.image("https://huggingface.co/spaces/tstone87/ccr-colorado/resolve/main/Fire_3.png", use_column_width=True)
43
 
44
  st.markdown("""
45
+ Fires in Colorado present a serious challenge, threatening urban communities, highways, and even remote areas. Early detection is critical to mitigating risks. WildfireWatch leverages the YOLOv8 model for real-time fire and smoke detection in images and videos.
46
  """)
 
47
  st.markdown("---")
48
+ st.header("Fire Detection:")
49
 
 
 
 
50
  col1, col2 = st.columns(2)
51
+ if source_file:
52
+ if source_file.type.split('/')[0] == 'image':
53
+ uploaded_image = PIL.Image.open(source_file)
54
+ st.image(uploaded_image, caption="Uploaded Image", use_column_width=True)
55
+ else:
56
+ tfile = tempfile.NamedTemporaryFile(delete=False)
57
+ tfile.write(source_file.read())
58
+ vidcap = cv2.VideoCapture(tfile.name)
59
+ else:
60
+ st.info("Please upload an image or video file to begin.")
61
 
62
+ # Load the YOLO model
 
 
 
 
 
 
 
 
 
 
63
  try:
64
  model = YOLO(model_path)
65
  except Exception as ex:
66
  st.error(f"Unable to load model. Check the specified path: {model_path}")
67
  st.error(ex)
 
68
 
69
+ if st.sidebar.button("Let's Detect Wildfire"):
70
  if not source_file:
71
+ st.warning("No file uploaded!")
72
  elif source_file.type.split('/')[0] == 'image':
73
+ # Process image input
74
  res = model.predict(uploaded_image, conf=confidence)
75
  boxes = res[0].boxes
76
  res_plotted = res[0].plot()[:, :, ::-1]
77
  with col2:
78
  st.image(res_plotted, caption='Detected Image', use_column_width=True)
79
+ with st.expander("Detection Results"):
80
+ for box in boxes:
81
+ st.write(box.xywh)
 
 
 
82
  else:
83
+ # Process video input and shorten video based on sampling option
84
+ processed_frames = []
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  frame_count = 0
86
+
87
+ # Video properties
88
+ orig_fps = vidcap.get(cv2.CAP_PROP_FPS)
89
+ width = int(vidcap.get(cv2.CAP_PROP_FRAME_WIDTH))
90
+ height = int(vidcap.get(cv2.CAP_PROP_FRAME_HEIGHT))
91
 
92
+ # Determine sampling interval and output fps
93
+ if video_option == "Original FPS":
94
+ sample_interval = 1 # process every frame
95
+ output_fps = orig_fps
96
+ elif video_option == "1 fps":
97
+ sample_interval = int(orig_fps) if orig_fps > 0 else 1
98
+ output_fps = 1
99
+ elif video_option == "1 frame per 5 seconds":
100
+ sample_interval = int(orig_fps * 5) if orig_fps > 0 else 5
101
+ output_fps = 1
102
+ elif video_option == "1 frame per 10 seconds":
103
+ sample_interval = int(orig_fps * 10) if orig_fps > 0 else 10
104
+ output_fps = 1
105
+ elif video_option == "1 frame per 15 seconds":
106
+ sample_interval = int(orig_fps * 15) if orig_fps > 0 else 15
107
+ output_fps = 1
108
+ else:
109
+ sample_interval = 1
110
+ output_fps = orig_fps
111
+
112
+ success, image = vidcap.read()
113
  while success:
114
+ if frame_count % sample_interval == 0:
115
  res = model.predict(image, conf=confidence)
 
116
  res_plotted = res[0].plot()[:, :, ::-1]
117
+ processed_frames.append(res_plotted)
118
  with col2:
119
  st.image(res_plotted, caption=f'Detected Frame {frame_count}', use_column_width=True)
120
+ with st.expander("Detection Results"):
121
+ for box in res[0].boxes:
122
+ st.write(box.xywh)
 
 
 
 
 
 
 
 
 
123
  frame_count += 1
124
+ success, image = vidcap.read()
 
 
 
 
125
 
126
+ if processed_frames:
127
+ temp_video_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4')
128
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
129
+ out = cv2.VideoWriter(temp_video_file.name, fourcc, output_fps, (width, height))
130
+ for frame in processed_frames:
131
+ out.write(frame)
132
+ out.release()
133
+
134
+ st.success("Shortened video created successfully!")
135
+ with open(temp_video_file.name, 'rb') as video_file:
136
  st.download_button(
137
+ label="Download Shortened Video",
138
+ data=video_file.read(),
139
+ file_name="shortened_video.mp4",
140
  mime="video/mp4"
141
  )
142
+ else:
143
+ st.error("No frames were processed from the video.")