SuriRaja commited on
Commit
fa547a5
·
1 Parent(s): a812c0f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -31
app.py CHANGED
@@ -1,65 +1,134 @@
 
1
  import cv2
2
  import time
3
  import os
4
- from services.video_service import get_random_video_frame
 
 
 
 
5
  from services.thermal_service import detect_thermal_anomalies
6
  from services.overlay_service import overlay_boxes
7
  from services.metrics_service import update_metrics
8
 
9
-
10
  paused = False
11
- frame_rate = 1.0 # seconds
12
-
13
-
14
-
15
 
 
 
16
 
 
17
  def monitor_feed():
18
  global paused
 
19
 
20
-
21
 
22
  if paused:
23
- frame = get_random_video_frame() # Still fetch to keep system active
24
- else:
25
- frame = get_random_video_frame()
26
-
27
-
28
 
 
 
29
 
 
30
  detected_boxes = detect_thermal_anomalies(frame)
31
  frame = overlay_boxes(frame, detected_boxes)
32
-
33
  metrics = update_metrics(detected_boxes)
34
- return frame[:, :, ::-1], metrics # BGR → RGB
35
-
36
-
37
-
38
-
39
- return frame[:, :, ::-1], {"Detections": 0}
40
-
41
-
42
- with gr.Blocks() as app:
43
- gr.Markdown("# 🌡️ Solar Surveillance Thermal Monitoring")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  with gr.Row():
46
  with gr.Column(scale=3):
47
- video_output = gr.Image(label="Live Video Feed", elem_id="video-feed")
48
  with gr.Column(scale=1):
49
- metrics_output = gr.Label(label="Detection Metrics")
 
 
 
 
 
 
50
 
51
  with gr.Row():
52
- pause_btn = gr.Button("⏸️ Pause")
53
- resume_btn = gr.Button("▶️ Resume")
54
- frame_slider = gr.Slider(0.5, 5.0, step=0.1, value=1.0, label="Frame Interval (seconds)")
55
 
56
  def toggle_pause():
57
  global paused
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  def streaming_loop():
60
  while True:
61
- frame, metrics = monitor_feed()
62
- yield frame, metrics
 
 
 
 
 
63
  time.sleep(frame_rate)
64
 
65
- app.load(streaming_loop, outputs=[video_output, metrics_output])
 
 
 
 
1
+ import gradio as gr
2
  import cv2
3
  import time
4
  import os
5
+ import random
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+ from datetime import datetime
9
+ from services.video_service import get_next_video_frame
10
  from services.thermal_service import detect_thermal_anomalies
11
  from services.overlay_service import overlay_boxes
12
  from services.metrics_service import update_metrics
13
 
14
+ # Globals
15
  paused = False
16
+ frame_rate = 1
17
+ frame_count = 0
18
+ log_entries = []
19
+ anomaly_counts = []
20
 
21
+ # Constants
22
+ TEMP_IMAGE_PATH = "temp.jpg"
23
 
24
+ # Core monitor function
25
  def monitor_feed():
26
  global paused
27
+ global frame_count
28
 
29
+ frame = None
30
 
31
  if paused:
32
+ if os.path.exists(TEMP_IMAGE_PATH):
33
+ frame = cv2.imread(TEMP_IMAGE_PATH)
 
 
 
34
 
35
+ if frame is None:
36
+ frame = get_next_video_frame()
37
 
38
+ if not paused:
39
  detected_boxes = detect_thermal_anomalies(frame)
40
  frame = overlay_boxes(frame, detected_boxes)
41
+ cv2.imwrite(TEMP_IMAGE_PATH, frame, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
42
  metrics = update_metrics(detected_boxes)
43
+ else:
44
+ metrics = update_metrics([])
45
+
46
+ frame = cv2.resize(frame, (640, 480)) # Fixed window size
47
+
48
+ # Add frame count and timestamp
49
+ frame_count += 1
50
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
51
+ cv2.putText(frame, f"Frame: {frame_count}", (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
52
+ cv2.putText(frame, f"{timestamp}", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
53
+
54
+ # Update logs and anomaly counts
55
+ anomaly_detected = len(metrics['anomalies']) if 'anomalies' in metrics else 0
56
+ log_entries.append(f"{timestamp} - Frame {frame_count} - Anomalies Detected: {anomaly_detected}")
57
+ anomaly_counts.append(anomaly_detected)
58
+
59
+ if len(log_entries) > 100:
60
+ log_entries.pop(0)
61
+ if len(anomaly_counts) > 100:
62
+ anomaly_counts.pop(0)
63
+
64
+ return frame[:, :, ::-1], metrics, "\n".join(log_entries[-10:]), generate_chart()
65
+
66
+ # Chart generator
67
+ def generate_chart():
68
+ fig, ax = plt.subplots(figsize=(4, 2))
69
+ ax.plot(anomaly_counts[-50:], marker='o')
70
+ ax.set_title("Anomalies Over Time")
71
+ ax.set_xlabel("Frame")
72
+ ax.set_ylabel("Count")
73
+ fig.tight_layout()
74
+ chart_path = "chart_temp.png"
75
+ fig.savefig(chart_path)
76
+ plt.close(fig)
77
+ return chart_path
78
+
79
+ # Gradio UI
80
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
81
+ gr.Markdown("# \ud83c\udf10 Thermal Anomaly Monitoring Dashboard", elem_id="main-title")
82
+
83
+ status_text = gr.Markdown("**Status:** \ud83d\udfe2 Running", elem_id="status-banner")
84
 
85
  with gr.Row():
86
  with gr.Column(scale=3):
87
+ video_output = gr.Image(label="Live Video Feed", elem_id="video-feed", width=640, height=480)
88
  with gr.Column(scale=1):
89
+ metrics_output = gr.Label(label="Live Metrics", elem_id="metrics")
90
+
91
+ with gr.Row():
92
+ with gr.Column():
93
+ logs_output = gr.Textbox(label="Live Logs", lines=10)
94
+ with gr.Column():
95
+ chart_output = gr.Image(label="Detection Trends")
96
 
97
  with gr.Row():
98
+ pause_btn = gr.Button("\u23f8\ufe0f Pause")
99
+ resume_btn = gr.Button("\u25b6\ufe0f Resume")
100
+ frame_slider = gr.Slider(0.2, 5, value=1, label="Frame Interval (seconds)")
101
 
102
  def toggle_pause():
103
  global paused
104
+ paused = True
105
+ return "**Status:** \u23f8\ufe0f Paused"
106
+
107
+ def toggle_resume():
108
+ global paused
109
+ paused = False
110
+ return "**Status:** \ud83d\udfe2 Running"
111
+
112
+ def set_frame_rate(val):
113
+ global frame_rate
114
+ frame_rate = val
115
+
116
+ pause_btn.click(toggle_pause, outputs=status_text)
117
+ resume_btn.click(toggle_resume, outputs=status_text)
118
+ frame_slider.change(set_frame_rate, inputs=[frame_slider])
119
 
120
  def streaming_loop():
121
  while True:
122
+ frame, metrics, logs, chart = monitor_feed()
123
+ # Check for alerts
124
+ if anomaly_counts and anomaly_counts[-1] >= 5:
125
+ status = "**Status:** \ud83d\udd34 Alert: High Anomaly Rate"
126
+ else:
127
+ status = "**Status:** \ud83d\udfe2 Running" if not paused else "**Status:** \u23f8\ufe0f Paused"
128
+ yield [frame, metrics, logs, chart, status]
129
  time.sleep(frame_rate)
130
 
131
+ app.load(streaming_loop, outputs=[video_output, metrics_output, logs_output, chart_output, status_text])
132
+
133
+ if __name__ == "__main__":
134
+ app.launch()