NaveenKumar5 commited on
Commit
6b38c5e
Β·
verified Β·
1 Parent(s): 8daa03e

Delete src

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +0 -116
src/streamlit_app.py DELETED
@@ -1,116 +0,0 @@
1
- # app.py
2
- import streamlit as st
3
- import cv2
4
- import numpy as np
5
- import tempfile
6
- import os
7
- import pandas as pd
8
- from PIL import Image
9
- import torch
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")
33
-
34
- with torch.no_grad():
35
- outputs = model(**inputs)
36
-
37
- target_sizes = torch.tensor([image.size[::-1]])
38
- results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.7)[0]
39
-
40
- faults = []
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,
50
- "Time (s)": round(frame_idx / fps, 2),
51
- "Fault Type": label_name,
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))
61
- total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
62
- width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
63
- height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
64
-
65
- output_path = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4").name
66
- writer = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (width, height))
67
-
68
- fault_log = []
69
- progress = st.progress(0)
70
-
71
- for frame_idx in range(total_frames):
72
- ret, frame = cap.read()
73
- if not ret:
74
- break
75
-
76
- if frame_idx % fps == 0:
77
- frame, faults = detect_faults(frame, frame_idx, fps)
78
- fault_log.extend(faults)
79
-
80
- writer.write(frame)
81
- progress.progress(min(frame_idx / total_frames, 1.0))
82
-
83
- cap.release()
84
- writer.release()
85
- return output_path, fault_log
86
-
87
- # === CSV Helper ===
88
- def convert_df(df):
89
- return df.to_csv(index=False).encode('utf-8')
90
-
91
- # === Streamlit Interface ===
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")