Naveenkumar1546 commited on
Commit
bbf78d4
·
verified ·
1 Parent(s): 41e7f8a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +110 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,112 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import torch
3
+ from transformers import DetrImageProcessor, DetrForObjectDetection
4
+ from PIL import Image
5
+ import numpy as np
6
+ import cv2
7
+
8
+ # Set page configuration
9
+ st.set_page_config(page_title="Solar Panel Fault Detection", layout="wide")
10
+
11
+ # Title and description
12
+ st.title("Solar Panel Fault Detection PoC")
13
+ st.write("Upload a thermal image of a solar panel to detect thermal, dust, and power generation faults.")
14
+
15
+ # Load model and processor
16
+ @st.cache_resource
17
+ def load_model():
18
+ processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
19
+ model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
20
+ return processor, model
21
+
22
+ processor, model = load_model()
23
+
24
+ # Function to process image and detect faults
25
+ def detect_faults(image):
26
+ # Convert PIL image to numpy array
27
+ img_np = np.array(image)
28
+
29
+ # Convert to RGB if necessary
30
+ if img_np.shape[-1] == 4:
31
+ img_np = img_np[:, :, :3]
32
+
33
+ # Prepare image for model
34
+ inputs = processor(images=img_np, return_tensors="pt")
35
+
36
+ # Run inference
37
+ with torch.no_grad():
38
+ outputs = model(**inputs)
39
+
40
+ # Post-process outputs
41
+ target_sizes = torch.tensor([img_np.shape[:2]])
42
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
43
+
44
+ # Initialize fault detection
45
+ faults = {"Thermal Fault": False, "Dust Fault": False, "Power Generation Fault": False}
46
+ annotated_img = img_np.copy()
47
+
48
+ # Analyze thermal image for faults
49
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
50
+ box = [int(i) for i in box.tolist()]
51
+ # Simulate fault detection based on bounding box and pixel intensity
52
+ roi = img_np[box[1]:box[3], box[0]:box[2]]
53
+ mean_intensity = np.mean(roi)
54
+
55
+ # Thermal Fault: High intensity (hotspot)
56
+ if mean_intensity > 200: # Adjust threshold based on thermal image scale
57
+ faults["Thermal Fault"] = True
58
+ cv2.rectangle(annotated_img, (box[0], box[1]), (box[2], box[3]), (255, 0, 0), 2)
59
+ cv2.putText(annotated_img, "Thermal Fault", (box[0], box[1]-10),
60
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
61
+
62
+ # Dust Fault: Low intensity or irregular patterns
63
+ elif mean_intensity < 100: # Adjust threshold
64
+ faults["Dust Fault"] = True
65
+ cv2.rectangle(annotated_img, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)
66
+ cv2.putText(annotated_img, "Dust Fault", (box[0], box[1]-10),
67
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
68
+
69
+ # Power Generation Fault: Any detected anomaly may indicate reduced efficiency
70
+ if faults["Thermal Fault"] or faults["Dust Fault"]:
71
+ faults["Power Generation Fault"] = True
72
+
73
+ return annotated_img, faults
74
+
75
+ # File uploader
76
+ uploaded_file = st.file_uploader("Upload a thermal image", type=["png", "jpg", "jpeg"])
77
+
78
+ if uploaded_file is not None:
79
+ # Load and display uploaded image
80
+ image = Image.open(uploaded_file).convert("RGB")
81
+ st.image(image, caption="Uploaded Thermal Image", use_column_width=True)
82
+
83
+ # Process image
84
+ with st.spinner("Analyzing image..."):
85
+ annotated_img, faults = detect_faults(image)
86
+
87
+ # Display results
88
+ st.subheader("Fault Detection Results")
89
+ st.image(annotated_img, caption="Annotated Image with Detected Faults", use_column_width=True)
90
+
91
+ # Show fault summary
92
+ st.write("**Detected Faults:**")
93
+ for fault, detected in faults.items():
94
+ status = "Detected" if detected else "Not Detected"
95
+ color = "red" if detected else "green"
96
+ st.markdown(f"- **{fault}**: <span style='color:{color}'>{status}</span>", unsafe_allow_html=True)
97
+
98
+ # Provide recommendations
99
+ if any(faults.values()):
100
+ st.subheader("Recommendations")
101
+ if faults["Thermal Fault"]:
102
+ st.write("- **Thermal Fault**: Inspect for damaged components or overheating issues.")
103
+ if faults["Dust Fault"]:
104
+ st.write("- **Dust Fault**: Schedule cleaning to remove dust accumulation.")
105
+ if faults["Power Generation Fault"]:
106
+ st.write("- **Power Generation Fault**: Investigate efficiency issues due to detected faults.")
107
+ else:
108
+ st.write("No faults detected. The solar panel appears to be functioning normally.")
109
 
110
+ # Footer
111
+ st.markdown("---")
112
+ st.write("Built with Streamlit and Hugging Face Transformers for Solar Panel Fault Detection PoC")