NaveenKumar5 commited on
Commit
3cbd6bb
Β·
verified Β·
1 Parent(s): 32133c5

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -0
app.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import cv2
3
+ import numpy as np
4
+ import tempfile
5
+ import os
6
+ import pandas as pd
7
+ from PIL import Image
8
+ import torch
9
+ from transformers import DetrImageProcessor, DetrForObjectDetection
10
+
11
+ # === Hugging Face Model Configuration ===
12
+ processor = DetrImageProcessor.from_pretrained("NaveenKumar5/Solar_panel_fault_detection")
13
+ model = DetrForObjectDetection.from_pretrained("NaveenKumar5/Solar_panel_fault_detection")
14
+ model.eval()
15
+
16
+ # === Streamlit App Configuration ===
17
+ st.set_page_config(page_title="Solar Panel Fault Detection", layout="wide")
18
+ st.title("πŸ” Solar Panel Fault Detection (DETR - Hugging Face)")
19
+ st.write("Upload a thermal video (MP4). Faults will be detected using your Hugging Face DETR model.")
20
+
21
+ # === Fault Detection Function ===
22
+ def detect_faults(frame, frame_idx, fps):
23
+ image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
24
+ inputs = processor(images=image, return_tensors="pt")
25
+
26
+ with torch.no_grad():
27
+ outputs = model(**inputs)
28
+
29
+ target_sizes = torch.tensor([image.size[::-1]]) # (height, width)
30
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.7)[0]
31
+
32
+ faults = []
33
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
34
+ x1, y1, x2, y2 = map(int, box.tolist())
35
+ conf = score.item()
36
+ label_id = label.item()
37
+ label_name = model.config.id2label[label_id] # Use proper label from config if available
38
+
39
+ # Draw on frame
40
+ color = (0, 0, 255)
41
+ cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
42
+ cv2.putText(frame, f"{label_name} ({conf:.2f})", (x1, y1 - 5),
43
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
44
+
45
+ faults.append({
46
+ "Frame": frame_idx,
47
+ "Time (s)": round(frame_idx / fps, 2),
48
+ "Fault Type": label_name,
49
+ "Confidence": round(conf, 2),
50
+ "Box": f"({x1},{y1},{x2},{y2})"
51
+ })
52
+ return frame, faults
53
+
54
+ # === Video Processing Function ===
55
+ def process_video(video_path):
56
+ cap = cv2.VideoCapture(video_path)
57
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
58
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
59
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
60
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
61
+
62
+ output_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
63
+ writer = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
64
+
65
+ fault_log = []
66
+ progress = st.progress(0)
67
+
68
+ for frame_idx in range(total_frames):
69
+ ret, frame = cap.read()
70
+ if not ret:
71
+ break
72
+
73
+ # Detect every second
74
+ if frame_idx % fps == 0:
75
+ frame, faults = detect_faults(frame, frame_idx, fps)
76
+ fault_log.extend(faults)
77
+
78
+ writer.write(frame)
79
+ progress.progress(min(frame_idx / total_frames, 1.0))
80
+
81
+ cap.release()
82
+ writer.release()
83
+ return output_path, fault_log
84
+
85
+ # === CSV Conversion ===
86
+ def convert_df(df):
87
+ return df.to_csv(index=False).encode('utf-8')
88
+
89
+ # === Streamlit UI ===
90
+ uploaded_file = st.file_uploader("πŸ“€ Upload thermal video", type=["mp4"])
91
+ if uploaded_file:
92
+ st.video(uploaded_file)
93
+
94
+ temp_input_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
95
+ with open(temp_input_path, "wb") as f:
96
+ f.write(uploaded_file.read())
97
+
98
+ output_path, log = process_video(temp_input_path)
99
+
100
+ st.subheader("πŸ§ͺ Processed Output")
101
+ st.video(output_path)
102
+
103
+ if log:
104
+ df = pd.DataFrame(log)
105
+ st.write("### πŸ“Š Detected Faults Table")
106
+ st.dataframe(df)
107
+ st.download_button("πŸ“₯ Download Fault Log CSV", convert_df(df), "fault_log.csv", "text/csv")
108
+ else:
109
+ st.success("βœ… No faults detected.")
110
+
111
+ os.unlink(temp_input_path)
112
+ os.unlink(output_path)
113
+
114
+ st.markdown("---")
115
+ st.caption("Built with Streamlit + Hugging Face DETR + OpenCV")