Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,7 @@ import json
|
|
| 6 |
import random
|
| 7 |
import logging
|
| 8 |
import matplotlib.pyplot as plt
|
|
|
|
| 9 |
from datetime import datetime
|
| 10 |
from collections import Counter
|
| 11 |
from typing import Any, Dict, List, Optional, Tuple
|
|
@@ -72,11 +73,15 @@ static_image: Optional[np.ndarray] = None
|
|
| 72 |
|
| 73 |
# Constants
|
| 74 |
DEFAULT_VIDEO_PATH = "sample.mp4"
|
| 75 |
-
TEMP_IMAGE_PATH = "temp.jpg"
|
| 76 |
-
CAPTURED_FRAMES_DIR = "captured_frames"
|
| 77 |
-
OUTPUT_DIR = "outputs"
|
| 78 |
-
os.
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
def initialize_media(media_file: Optional[Any] = None) -> str:
|
| 82 |
global media_loaded, is_video, static_image, log_entries, frame_count
|
|
@@ -84,22 +89,37 @@ def initialize_media(media_file: Optional[Any] = None) -> str:
|
|
| 84 |
static_image = None
|
| 85 |
frame_count = 0 # Reset frame count on new media load
|
| 86 |
|
| 87 |
-
#
|
| 88 |
if media_file is None:
|
| 89 |
media_path = DEFAULT_VIDEO_PATH
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
log_entries.append(status)
|
| 93 |
-
logging.error(status)
|
| 94 |
-
media_loaded = False
|
| 95 |
-
return status
|
| 96 |
else:
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
|
|
|
| 103 |
if not os.path.exists(media_path):
|
| 104 |
status = f"Error: Media file '{media_path}' not found."
|
| 105 |
log_entries.append(status)
|
|
@@ -109,12 +129,12 @@ def initialize_media(media_file: Optional[Any] = None) -> str:
|
|
| 109 |
|
| 110 |
try:
|
| 111 |
# Determine if the file is a video or image
|
| 112 |
-
if
|
| 113 |
is_video = True
|
| 114 |
preload_video(media_path)
|
| 115 |
media_loaded = True
|
| 116 |
status = f"Successfully loaded video: {media_path}"
|
| 117 |
-
elif
|
| 118 |
is_video = False
|
| 119 |
static_image = cv2.imread(media_path)
|
| 120 |
if static_image is None:
|
|
@@ -222,22 +242,36 @@ def monitor_feed() -> Tuple[
|
|
| 222 |
frame = last_frame.copy()
|
| 223 |
metrics = last_metrics.copy()
|
| 224 |
else:
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
if
|
| 229 |
-
# Reset video if it ends
|
| 230 |
-
log_entries.append("Video ended, resetting to start.")
|
| 231 |
-
logging.info("Video ended, resetting to start.")
|
| 232 |
-
reset_video_index()
|
| 233 |
frame = get_next_video_frame()
|
| 234 |
if frame is None:
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
return (
|
| 242 |
None,
|
| 243 |
json.dumps(last_metrics, indent=2),
|
|
|
|
| 6 |
import random
|
| 7 |
import logging
|
| 8 |
import matplotlib.pyplot as plt
|
| 9 |
+
import shutil
|
| 10 |
from datetime import datetime
|
| 11 |
from collections import Counter
|
| 12 |
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
| 73 |
|
| 74 |
# Constants
|
| 75 |
DEFAULT_VIDEO_PATH = "sample.mp4"
|
| 76 |
+
TEMP_IMAGE_PATH = os.path.abspath("temp.jpg")
|
| 77 |
+
CAPTURED_FRAMES_DIR = os.path.abspath("captured_frames")
|
| 78 |
+
OUTPUT_DIR = os.path.abspath("outputs")
|
| 79 |
+
TEMP_MEDIA_DIR = os.path.abspath("temp_media")
|
| 80 |
+
|
| 81 |
+
# Ensure directories exist with write permissions
|
| 82 |
+
for directory in [CAPTURED_FRAMES_DIR, OUTPUT_DIR, TEMP_MEDIA_DIR]:
|
| 83 |
+
os.makedirs(directory, exist_ok=True)
|
| 84 |
+
os.chmod(directory, 0o777) # Ensure write permissions
|
| 85 |
|
| 86 |
def initialize_media(media_file: Optional[Any] = None) -> str:
|
| 87 |
global media_loaded, is_video, static_image, log_entries, frame_count
|
|
|
|
| 89 |
static_image = None
|
| 90 |
frame_count = 0 # Reset frame count on new media load
|
| 91 |
|
| 92 |
+
# If no media file is provided, try the default video
|
| 93 |
if media_file is None:
|
| 94 |
media_path = DEFAULT_VIDEO_PATH
|
| 95 |
+
log_entries.append(f"No media uploaded, attempting to load default: {media_path}")
|
| 96 |
+
logging.info(f"No media uploaded, attempting to load default: {media_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
else:
|
| 98 |
+
# Validate media file
|
| 99 |
+
if not hasattr(media_file, 'name') or not media_file.name:
|
| 100 |
+
status = "Error: Invalid media file uploaded."
|
| 101 |
+
log_entries.append(status)
|
| 102 |
+
logging.error(status)
|
| 103 |
+
media_loaded = False
|
| 104 |
+
return status
|
| 105 |
|
| 106 |
+
# Copy the uploaded file to a known location to avoid path issues
|
| 107 |
+
original_path = media_file.name
|
| 108 |
+
file_extension = os.path.splitext(original_path)[1].lower()
|
| 109 |
+
temp_media_path = os.path.join(TEMP_MEDIA_DIR, f"uploaded_media{file_extension}")
|
| 110 |
+
try:
|
| 111 |
+
shutil.copy(original_path, temp_media_path)
|
| 112 |
+
media_path = temp_media_path
|
| 113 |
+
log_entries.append(f"Copied uploaded file to: {media_path}")
|
| 114 |
+
logging.info(f"Copied uploaded file to: {media_path}")
|
| 115 |
+
except Exception as e:
|
| 116 |
+
status = f"Error copying uploaded file: {str(e)}"
|
| 117 |
+
log_entries.append(status)
|
| 118 |
+
logging.error(status)
|
| 119 |
+
media_loaded = False
|
| 120 |
+
return status
|
| 121 |
|
| 122 |
+
# Verify the file exists
|
| 123 |
if not os.path.exists(media_path):
|
| 124 |
status = f"Error: Media file '{media_path}' not found."
|
| 125 |
log_entries.append(status)
|
|
|
|
| 129 |
|
| 130 |
try:
|
| 131 |
# Determine if the file is a video or image
|
| 132 |
+
if file_extension in (".mp4", ".avi"):
|
| 133 |
is_video = True
|
| 134 |
preload_video(media_path)
|
| 135 |
media_loaded = True
|
| 136 |
status = f"Successfully loaded video: {media_path}"
|
| 137 |
+
elif file_extension in (".jpg", ".jpeg", ".png"):
|
| 138 |
is_video = False
|
| 139 |
static_image = cv2.imread(media_path)
|
| 140 |
if static_image is None:
|
|
|
|
| 242 |
frame = last_frame.copy()
|
| 243 |
metrics = last_metrics.copy()
|
| 244 |
else:
|
| 245 |
+
max_retries = 3
|
| 246 |
+
for attempt in range(max_retries):
|
| 247 |
+
try:
|
| 248 |
+
if is_video:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
frame = get_next_video_frame()
|
| 250 |
if frame is None:
|
| 251 |
+
log_entries.append(f"Frame retrieval failed on attempt {attempt + 1}, resetting video.")
|
| 252 |
+
logging.warning(f"Frame retrieval failed on attempt {attempt + 1}, resetting video.")
|
| 253 |
+
reset_video_index()
|
| 254 |
+
continue
|
| 255 |
+
break
|
| 256 |
+
else:
|
| 257 |
+
frame = static_image.copy()
|
| 258 |
+
break
|
| 259 |
+
except Exception as e:
|
| 260 |
+
log_entries.append(f"Frame retrieval error on attempt {attempt + 1}: {str(e)}")
|
| 261 |
+
logging.error(f"Frame retrieval error on attempt {attempt + 1}: {str(e)}")
|
| 262 |
+
if attempt == max_retries - 1:
|
| 263 |
+
return (
|
| 264 |
+
None,
|
| 265 |
+
json.dumps(last_metrics, indent=2),
|
| 266 |
+
"\n".join(log_entries[-10:]),
|
| 267 |
+
detected_plants,
|
| 268 |
+
detected_issues,
|
| 269 |
+
None,
|
| 270 |
+
None
|
| 271 |
+
)
|
| 272 |
+
else:
|
| 273 |
+
log_entries.append("Failed to retrieve frame after maximum retries.")
|
| 274 |
+
logging.error("Failed to retrieve frame after maximum retries.")
|
| 275 |
return (
|
| 276 |
None,
|
| 277 |
json.dumps(last_metrics, indent=2),
|