NaveenKumar5 commited on
Commit
e5fa935
Β·
verified Β·
1 Parent(s): 2d455c1

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +32 -40
src/streamlit_app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import streamlit as st
2
  import cv2
3
  import numpy as np
@@ -9,24 +10,23 @@ import torch
9
  from transformers import DetrImageProcessor, DetrForObjectDetection
10
  from huggingface_hub import login
11
 
12
- # Secure token handling
13
- HUGGINGFACE_TOKEN = os.environ.get("HF_TOKEN")
14
- if HUGGINGFACE_TOKEN is None:
15
- raise ValueError("Hugging Face token not found in environment. Please set HF_TOKEN in Space secrets.")
 
16
 
17
- login(token=HUGGINGFACE_TOKEN)
18
-
19
- # === Load Model and Processor ===
20
- processor = DetrImageProcessor.from_pretrained("NaveenKumar5/Solar_panel_fault_detection", use_auth_token=True)
21
- model = DetrForObjectDetection.from_pretrained("NaveenKumar5/Solar_panel_fault_detection", use_auth_token=True)
22
  model.eval()
23
 
24
- # === Streamlit UI Setup ===
25
  st.set_page_config(page_title="Solar Panel Fault Detection", layout="wide")
26
- st.title("πŸ” Solar Panel Fault Detection (Hugging Face Model)")
27
- st.write("Upload a thermal video (MP4). Faults will be detected using your Hugging Face DETR model.")
28
 
29
- # === Fault Detection Function ===
30
  def detect_faults(frame, frame_idx, fps):
31
  image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
32
  inputs = processor(images=image, return_tensors="pt")
@@ -41,14 +41,9 @@ def detect_faults(frame, frame_idx, fps):
41
  for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
42
  x1, y1, x2, y2 = map(int, box.tolist())
43
  conf = score.item()
44
- label_id = label.item()
45
- label_name = f"class_{label_id}" # Customize if label mapping is available
46
-
47
- # Draw on frame
48
- color = (0, 0, 255)
49
- cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
50
- cv2.putText(frame, f"{label_name} ({conf:.2f})", (x1, y1 - 5),
51
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
52
 
53
  faults.append({
54
  "Frame": frame_idx,
@@ -57,10 +52,9 @@ def detect_faults(frame, frame_idx, fps):
57
  "Confidence": round(conf, 2),
58
  "Box": f"({x1},{y1},{x2},{y2})"
59
  })
60
-
61
  return frame, faults
62
 
63
- # === Process Uploaded Video ===
64
  def process_video(video_path):
65
  cap = cv2.VideoCapture(video_path)
66
  fps = int(cap.get(cv2.CAP_PROP_FPS))
@@ -98,27 +92,25 @@ def convert_df(df):
98
  uploaded_file = st.file_uploader("πŸ“€ Upload thermal video", type=["mp4"])
99
  if uploaded_file:
100
  st.video(uploaded_file)
101
-
102
  temp_input_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
103
  with open(temp_input_path, "wb") as f:
104
  f.write(uploaded_file.read())
105
 
106
- try:
107
- output_path, log = process_video(temp_input_path)
108
-
109
- st.subheader("πŸ§ͺ Processed Output")
110
- st.video(output_path)
111
-
112
- if log:
113
- df = pd.DataFrame(log)
114
- st.write("### πŸ“Š Detected Faults Table")
115
- st.dataframe(df)
116
- st.download_button("πŸ“₯ Download Fault Log CSV", convert_df(df), "fault_log.csv", "text/csv")
117
- else:
118
- st.success("βœ… No faults detected.")
119
- finally:
120
- os.unlink(temp_input_path)
121
- os.unlink(output_path)
122
 
123
  st.markdown("---")
124
  st.caption("Built with Streamlit + Hugging Face DETR + OpenCV")
 
1
+ # app.py
2
  import streamlit as st
3
  import cv2
4
  import numpy as np
 
10
  from transformers import DetrImageProcessor, DetrForObjectDetection
11
  from huggingface_hub import login
12
 
13
+ # === Authenticate with Hugging Face Token from Secrets ===
14
+ HF_TOKEN = os.environ.get("HF_TOKEN")
15
+ if HF_TOKEN is None:
16
+ raise ValueError("Hugging Face token not found. Please add it as a Space secret.")
17
+ login(token=HF_TOKEN)
18
 
19
+ # === Load Model ===
20
+ processor = DetrImageProcessor.from_pretrained("NaveenKumar5/Solar_panel_fault_detection")
21
+ model = DetrForObjectDetection.from_pretrained("NaveenKumar5/Solar_panel_fault_detection")
 
 
22
  model.eval()
23
 
24
+ # === Streamlit UI ===
25
  st.set_page_config(page_title="Solar Panel Fault Detection", layout="wide")
26
+ st.title("πŸ” Solar Panel Fault Detection (DETR - Hugging Face)")
27
+ st.write("Upload a thermal video (MP4). Faults will be detected using a DETR model from Hugging Face.")
28
 
29
+ # === Detection Logic ===
30
  def detect_faults(frame, frame_idx, fps):
31
  image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
32
  inputs = processor(images=image, return_tensors="pt")
 
41
  for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
42
  x1, y1, x2, y2 = map(int, box.tolist())
43
  conf = score.item()
44
+ label_name = f"class_{label.item()}"
45
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 2)
46
+ cv2.putText(frame, f"{label_name} ({conf:.2f})", (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
 
 
 
 
 
47
 
48
  faults.append({
49
  "Frame": frame_idx,
 
52
  "Confidence": round(conf, 2),
53
  "Box": f"({x1},{y1},{x2},{y2})"
54
  })
 
55
  return frame, faults
56
 
57
+ # === Process Video ===
58
  def process_video(video_path):
59
  cap = cv2.VideoCapture(video_path)
60
  fps = int(cap.get(cv2.CAP_PROP_FPS))
 
92
  uploaded_file = st.file_uploader("πŸ“€ Upload thermal video", type=["mp4"])
93
  if uploaded_file:
94
  st.video(uploaded_file)
 
95
  temp_input_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
96
  with open(temp_input_path, "wb") as f:
97
  f.write(uploaded_file.read())
98
 
99
+ output_path, log = process_video(temp_input_path)
100
+
101
+ st.subheader("πŸ§ͺ Processed Output")
102
+ st.video(output_path)
103
+
104
+ if log:
105
+ df = pd.DataFrame(log)
106
+ st.write("### πŸ“Š Detected Faults Table")
107
+ st.dataframe(df)
108
+ st.download_button("πŸ“₯ Download Fault Log CSV", convert_df(df), "fault_log.csv", "text/csv")
109
+ else:
110
+ st.success("βœ… No faults detected.")
111
+
112
+ os.unlink(temp_input_path)
113
+ os.unlink(output_path)
 
114
 
115
  st.markdown("---")
116
  st.caption("Built with Streamlit + Hugging Face DETR + OpenCV")