Spaces:
Runtime error
Runtime error
Download app.py from randomnameplease/3D: direct link, hf CLI and curl.
- Browser
- Download file 41.6 kB
-
https://huggingface.co/spaces/randomnameplease/3D/resolve/main/app.py
- Command line
-
hf download hf://spaces/randomnameplease/3D/app.py
-
curl -L -o app.py https://huggingface.co/spaces/randomnameplease/3D/resolve/main/app.py
41.6 kB
import streamlit as st
import numpy as np
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
from datetime import datetime
import json
import os
from collections import Counter
import base64
from io import BytesIO
# Page configuration
st.set_page_config(
page_title="CompositeDefect AI - NDT Analysis System",
page_icon="π¬",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for black/white/grey/blue/purple theme
st.markdown("""
<style>
/* Main theme colors */
:root {
--bg-primary: #0a0a0a;
--bg-secondary: #141414;
--bg-tertiary: #1e1e1e;
--text-primary: #ffffff;
--text-secondary: #b0b0b0;
--accent-blue: #3b82f6;
--accent-purple: #8b5cf6;
--accent-cyan: #06b6d4;
--border-color: #2a2a2a;
}
/* Global styles */
.stApp {
background: linear-gradient(135deg, #0a0a0a 0%, #141414 50%, #0f0f23 100%);
}
/* Sidebar styling */
.css-1d391kg, .css-1lcbmhc {
background: linear-gradient(180deg, #141414 0%, #1a1a2e 100%) !important;
}
/* Headers */
h1 {
background: linear-gradient(90deg, #3b82f6, #8b5cf6, #06b6d4);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-weight: 700 !important;
}
h2, h3 {
color: #ffffff !important;
font-weight: 600 !important;
}
/* Cards */
.defect-card {
background: linear-gradient(145deg, #1e1e1e, #252525);
border: 1px solid #2a2a2a;
border-radius: 12px;
padding: 20px;
margin: 10px 0;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
transition: all 0.3s ease;
}
.defect-card:hover {
border-color: #3b82f6;
box-shadow: 0 4px 20px rgba(59, 130, 246, 0.2);
}
/* Metric cards */
.metric-container {
background: linear-gradient(145deg, #1e1e1e, #252525);
border-left: 4px solid #3b82f6;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
}
.metric-value {
font-size: 2rem;
font-weight: 700;
color: #3b82f6;
}
.metric-label {
color: #b0b0b0;
font-size: 0.9rem;
}
/* Buttons */
.stButton > button {
background: linear-gradient(90deg, #3b82f6, #8b5cf6) !important;
color: white !important;
border: none !important;
border-radius: 8px !important;
padding: 12px 24px !important;
font-weight: 600 !important;
transition: all 0.3s ease !important;
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 20px rgba(59, 130, 246, 0.4) !important;
}
/* File uploader */
.stFileUploader {
background: #1e1e1e !important;
border: 2px dashed #3b82f6 !important;
border-radius: 12px !important;
}
/* Tabs */
.stTabs [data-baseweb="tab-list"] {
background: #1e1e1e !important;
border-radius: 8px !important;
}
.stTabs [data-baseweb="tab"] {
color: #b0b0b0 !important;
}
.stTabs [aria-selected="true"] {
background: linear-gradient(90deg, #3b82f6, #8b5cf6) !important;
color: white !important;
}
/* Progress bar */
.stProgress > div > div {
background: linear-gradient(90deg, #3b82f6, #8b5cf6) !important;
}
/* Selectbox */
.stSelectbox > div > div {
background: #1e1e1e !important;
border: 1px solid #2a2a2a !important;
color: white !important;
}
/* Slider */
.stSlider > div > div > div {
background: #3b82f6 !important;
}
/* Dataframe */
.stDataFrame {
background: #1e1e1e !important;
}
/* Custom badge */
.badge {
display: inline-block;
padding: 4px 12px;
border-radius: 20px;
font-size: 0.75rem;
font-weight: 600;
margin: 2px;
}
.badge-blue {
background: rgba(59, 130, 246, 0.2);
color: #3b82f6;
border: 1px solid #3b82f6;
}
.badge-purple {
background: rgba(139, 92, 246, 0.2);
color: #8b5cf6;
border: 1px solid #8b5cf6;
}
.badge-cyan {
background: rgba(6, 182, 212, 0.2);
color: #06b6d4;
border: 1px solid #06b6d4;
}
/* Glow effect */
.glow {
box-shadow: 0 0 20px rgba(59, 130, 246, 0.3);
}
/* Analysis result box */
.result-box {
background: linear-gradient(145deg, #1e1e1e, #252525);
border: 1px solid #3b82f6;
border-radius: 12px;
padding: 20px;
margin: 15px 0;
}
/* Defect severity indicators */
.severity-critical {
color: #ef4444;
font-weight: 700;
}
.severity-high {
color: #f97316;
font-weight: 700;
}
.severity-medium {
color: #eab308;
font-weight: 700;
}
.severity-low {
color: #22c55e;
font-weight: 700;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
if 'analysis_history' not in st.session_state:
st.session_state.analysis_history = []
if 'current_analysis' not in st.session_state:
st.session_state.current_analysis = None
# Sidebar configuration
with st.sidebar:
st.markdown("""
<div style="text-align: center; padding: 20px 0;">
<h2 style="color: #3b82f6; margin: 0;">π¬ CompositeDefect AI</h2>
<p style="color: #8b5cf6; font-size: 0.9rem;">NDT Analysis System</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# NDT Method Selection
st.markdown("### π‘ NDT Method")
ndt_method = st.selectbox(
"Select Testing Method",
[
"Visual Testing (VT)",
"Ultrasonic Testing (UT)",
"Magnetic Particle Testing (MPT)",
"Radiographic Testing (RT)",
"Liquid Penetrant Testing (LPT)",
"Eddy Current Testing (ECT)",
"Thermal/Infrared Testing (IRT)",
"Microwave NDT",
"Vibration Analysis"
],
help="Choose the non-destructive testing method used"
)
st.markdown("---")
# Material Selection
st.markdown("### π§ͺ Material Type")
material_type = st.selectbox(
"Select Composite Material",
[
"Carbon Fibre Reinforced Polymer (CFRP)",
"Glass Fibre Reinforced Polymer (GFRP)",
"Aramid Fibre Reinforced Polymer (AFRP)",
"Hybrid Composite"
],
help="Select the composite material being analyzed"
)
st.markdown("---")
# Analysis Parameters
st.markdown("### βοΈ Analysis Parameters")
sensitivity = st.slider(
"Detection Sensitivity",
min_value=0.1,
max_value=1.0,
value=0.75,
step=0.05,
help="Adjust the sensitivity of defect detection"
)
confidence_threshold = st.slider(
"Confidence Threshold",
min_value=0.5,
max_value=0.95,
value=0.70,
step=0.05,
help="Minimum confidence level for defect classification"
)
st.markdown("---")
# Defect Types to Detect
st.markdown("### π― Target Defects")
detect_delamination = st.checkbox("Delamination", value=True)
detect_cracks = st.checkbox("Cracks", value=True)
detect_voids = st.checkbox("Voids", value=True)
detect_fibre_misalignment = st.checkbox("Fibre Misalignment", value=True)
detect_resin_issues = st.checkbox("Resin Rich/Starved Areas", value=True)
st.markdown("---")
# About section
with st.expander("βΉοΈ About"):
st.markdown("""
**CompositeDefect AI** uses advanced machine learning algorithms
to detect and analyze defects in composite materials.
**Supported NDT Methods:**
- Visual Testing
- Ultrasonic Testing
- Radiography
- Thermal/Infrared
- And more...
**Version:** 2.0.0
""")
# Main content area
col_header1, col_header2 = st.columns([3, 1])
with col_header1:
st.title("π¬ CompositeDefect AI")
st.markdown("""
<p style="color: #b0b0b0; font-size: 1.1rem;">
Advanced Machine Learning-Based Defect Detection & Analysis for Composite Materials
</p>
""", unsafe_allow_html=True)
with col_header2:
st.markdown(f"""
<div style="text-align: right; padding-top: 10px;">
<span class="badge badge-blue">{ndt_method.split('(')[0].strip()}</span><br>
<span class="badge badge-purple">{material_type.split('(')[0].strip()}</span>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Create tabs for different sections
tab_upload, tab_analysis, tab_results, tab_history = st.tabs([
"π€ Upload & Analyze",
"π Detection Results",
"π Detailed Analysis",
"π History"
])
# Simulated ML Model for Defect Detection
class DefectDetectionModel:
def __init__(self):
self.defect_types = {
'delamination': {'color': (255, 0, 0), 'severity_weights': [0.3, 0.5, 0.7, 0.9]},
'crack': {'color': (0, 255, 0), 'severity_weights': [0.4, 0.6, 0.8, 1.0]},
'void': {'color': (0, 0, 255), 'severity_weights': [0.2, 0.4, 0.6, 0.8]},
'fibre_misalignment': {'color': (255, 255, 0), 'severity_weights': [0.2, 0.3, 0.5, 0.7]},
'resin_rich': {'color': (255, 0, 255), 'severity_weights': [0.1, 0.2, 0.4, 0.6]},
'resin_starved': {'color': (0, 255, 255), 'severity_weights': [0.2, 0.4, 0.6, 0.8]}
}
def preprocess_image(self, image, ndt_method):
"""Preprocess image based on NDT method"""
img_array = np.array(image)
if ndt_method == "Ultrasonic Testing (UT)":
# Enhance contrast for ultrasonic C-scan
if len(img_array.shape) == 3:
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
else:
gray = img_array
enhanced = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8)).apply(gray)
return cv2.cvtColor(enhanced, cv2.COLOR_GRAY2RGB)
elif ndt_method == "Thermal/Infrared Testing (IRT)":
# Apply colormap for thermal images
if len(img_array.shape) == 3:
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
else:
gray = img_array
thermal = cv2.applyColorMap(gray, cv2.COLORMAP_JET)
return cv2.cvtColor(thermal, cv2.COLOR_BGR2RGB)
elif ndt_method == "Radiographic Testing (RT)":
# Enhance radiographic images
if len(img_array.shape) == 3:
gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
else:
gray = img_array
enhanced = cv2.equalizeHist(gray)
return cv2.cvtColor(enhanced, cv2.COLOR_GRAY2RGB)
else:
return img_array
def detect_defects(self, image, ndt_method, material_type, sensitivity,
confidence_threshold, active_defects):
"""Simulate defect detection with ML model"""
np.random.seed(42)
img_array = np.array(image)
height, width = img_array.shape[:2]
detected_defects = []
annotated_image = img_array.copy()
# Simulate defect detection based on image characteristics
for defect_type, config in self.defect_types.items():
if defect_type not in active_defects:
continue
# Simulate detection probability based on sensitivity
num_defects = np.random.poisson(2 * sensitivity)
for i in range(num_defects):
# Random position
x = np.random.randint(50, width - 50)
y = np.random.randint(50, height - 50)
# Random size based on defect type
if defect_type == 'delamination':
w, h = np.random.randint(30, 100), np.random.randint(30, 100)
elif defect_type == 'crack':
w, h = np.random.randint(5, 15), np.random.randint(40, 150)
elif defect_type == 'void':
w, h = np.random.randint(10, 40), np.random.randint(10, 40)
else:
w, h = np.random.randint(20, 80), np.random.randint(20, 80)
# Calculate confidence
confidence = np.random.uniform(confidence_threshold, 0.98)
# Determine severity
severity_idx = np.random.choice(4, p=config['severity_weights'])
severity_levels = ['Low', 'Medium', 'High', 'Critical']
severity = severity_levels[severity_idx]
# Calculate area
area_mm2 = (w * h) * 0.01 # Simulated conversion to mmΒ²
defect_info = {
'type': defect_type.replace('_', ' ').title(),
'confidence': confidence,
'severity': severity,
'position': (x, y, w, h),
'area_mm2': round(area_mm2, 2),
'ndt_method': ndt_method
}
detected_defects.append(defect_info)
# Draw bounding box on annotated image
color = config['color']
cv2.rectangle(annotated_image, (x, y), (x+w, y+h), color, 2)
cv2.putText(annotated_image, f"{defect_type[:3].upper()} {confidence:.2f}",
(x, y-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
# Sort by confidence
detected_defects.sort(key=lambda x: x['confidence'], reverse=True)
return detected_defects, Image.fromarray(annotated_image)
def analyze_defect_characteristics(self, defects):
"""Analyze defect characteristics for reporting"""
if not defects:
return {}
analysis = {
'total_defects': len(defects),
'defect_types': Counter([d['type'] for d in defects]),
'severity_distribution': Counter([d['severity'] for d in defects]),
'avg_confidence': np.mean([d['confidence'] for d in defects]),
'critical_defects': len([d for d in defects if d['severity'] == 'Critical']),
'high_defects': len([d for d in defects if d['severity'] == 'High']),
'total_area': sum([d['area_mm2'] for d in defects])
}
return analysis
# Initialize model
model = DefectDetectionModel()
# Tab 1: Upload & Analyze
with tab_upload:
st.markdown("""
<div class="defect-card">
<h3>π€ Upload NDT Test Results</h3>
<p style="color: #b0b0b0;">
Upload your NDT inspection images for AI-powered defect detection and analysis.
Supports JPG, PNG, TIFF, and BMP formats.
</p>
</div>
""", unsafe_allow_html=True)
col1, col2 = st.columns([1, 1])
with col1:
uploaded_file = st.file_uploader(
"Choose an image file",
type=['jpg', 'jpeg', 'png', 'tiff', 'bmp'],
help="Upload NDT inspection image"
)
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.session_state.uploaded_image = image
st.markdown("""
<div class="result-box">
<h4>π Image Information</h4>
</div>
""", unsafe_allow_html=True)
info_col1, info_col2, info_col3 = st.columns(3)
with info_col1:
st.metric("Width", f"{image.size[0]} px")
with info_col2:
st.metric("Height", f"{image.size[1]} px")
with info_col3:
st.metric("Mode", image.mode)
with col2:
if uploaded_file is not None:
st.markdown("""
<div class="defect-card">
<h4>πΌοΈ Preview</h4>
</div>
""", unsafe_allow_html=True)
st.image(image, use_container_width=True)
if uploaded_file is not None:
st.markdown("---")
if st.button("π Start AI Analysis", use_container_width=True):
with st.spinner("π€ AI Model is analyzing the image..."):
# Progress bar
progress_bar = st.progress(0)
# Simulate processing steps
steps = [
"Preprocessing image...",
"Applying NDT-specific filters...",
"Running defect detection...",
"Classifying defect types...",
"Generating analysis report..."
]
for i, step in enumerate(steps):
st.text(f"β³ {step}")
progress_bar.progress((i + 1) / len(steps))
# Prepare active defects list
active_defects = []
if detect_delamination:
active_defects.append('delamination')
if detect_cracks:
active_defects.append('crack')
if detect_voids:
active_defects.append('void')
if detect_fibre_misalignment:
active_defects.append('fibre_misalignment')
if detect_resin_issues:
active_defects.append('resin_rich')
active_defects.append('resin_starved')
# Preprocess image
preprocessed = model.preprocess_image(image, ndt_method)
# Detect defects
defects, annotated_img = model.detect_defects(
preprocessed, ndt_method, material_type,
sensitivity, confidence_threshold, active_defects
)
# Analyze characteristics
analysis = model.analyze_defect_characteristics(defects)
# Store results
st.session_state.current_analysis = {
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
'ndt_method': ndt_method,
'material_type': material_type,
'original_image': image,
'annotated_image': annotated_img,
'preprocessed_image': Image.fromarray(preprocessed),
'defects': defects,
'analysis': analysis,
'parameters': {
'sensitivity': sensitivity,
'confidence_threshold': confidence_threshold
}
}
st.session_state.analysis_history.append(st.session_state.current_analysis)
progress_bar.empty()
st.success("β
Analysis Complete! Navigate to 'Detection Results' tab to view findings.")
st.balloons()
# Tab 2: Detection Results
with tab_analysis:
if st.session_state.current_analysis is None:
st.info("π Please upload and analyze an image first to see detection results.")
else:
analysis_data = st.session_state.current_analysis
# Summary metrics
st.markdown("""
<div class="defect-card">
<h3>π Detection Summary</h3>
</div>
""", unsafe_allow_html=True)
metric_cols = st.columns(4)
with metric_cols[0]:
st.markdown(f"""
<div class="metric-container">
<div class="metric-value">{analysis_data['analysis'].get('total_defects', 0)}</div>
<div class="metric-label">Total Defects</div>
</div>
""", unsafe_allow_html=True)
with metric_cols[1]:
critical = analysis_data['analysis'].get('critical_defects', 0)
severity_class = "severity-critical" if critical > 0 else "severity-low"
st.markdown(f"""
<div class="metric-container">
<div class="metric-value {severity_class}">{critical}</div>
<div class="metric-label">Critical Defects</div>
</div>
""", unsafe_allow_html=True)
with metric_cols[2]:
avg_conf = analysis_data['analysis'].get('avg_confidence', 0) * 100
st.markdown(f"""
<div class="metric-container">
<div class="metric-value">{avg_conf:.1f}%</div>
<div class="metric-label">Avg Confidence</div>
</div>
""", unsafe_allow_html=True)
with metric_cols[3]:
total_area = analysis_data['analysis'].get('total_area', 0)
st.markdown(f"""
<div class="metric-container">
<div class="metric-value">{total_area:.2f}</div>
<div class="metric-label">Total Area (mmΒ²)</div>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Image comparison
st.markdown("""
<div class="defect-card">
<h3>πΌοΈ Image Analysis</h3>
</div>
""", unsafe_allow_html=True)
img_col1, img_col2, img_col3 = st.columns(3)
with img_col1:
st.markdown("<p style='color: #b0b0b0; text-align: center;'><b>Original Image</b></p>",
unsafe_allow_html=True)
st.image(analysis_data['original_image'], use_container_width=True)
with img_col2:
st.markdown("<p style='color: #b0b0b0; text-align: center;'><b>Preprocessed</b></p>",
unsafe_allow_html=True)
st.image(analysis_data['preprocessed_image'], use_container_width=True)
with img_col3:
st.markdown("<p style='color: #b0b0b0; text-align: center;'><b>Detected Defects</b></p>",
unsafe_allow_html=True)
st.image(analysis_data['annotated_image'], use_container_width=True)
st.markdown("---")
# Defect list
st.markdown("""
<div class="defect-card">
<h3>π Detected Defects</h3>
</div>
""", unsafe_allow_html=True)
if analysis_data['defects']:
for i, defect in enumerate(analysis_data['defects'][:10], 1):
severity_colors = {
'Low': '#22c55e',
'Medium': '#eab308',
'High': '#f97316',
'Critical': '#ef4444'
}
color = severity_colors.get(defect['severity'], '#b0b0b0')
with st.expander(f"Defect #{i}: {defect['type']} - Confidence: {defect['confidence']:.2%}"):
col_d1, col_d2, col_d3 = st.columns(3)
with col_d1:
st.markdown(f"**Type:** {defect['type']}")
st.markdown(f"**Confidence:** {defect['confidence']:.2%}")
with col_d2:
st.markdown(f"**Severity:** <span style='color: {color}; font-weight: bold;'>{defect['severity']}</span>",
unsafe_allow_html=True)
st.markdown(f"**Area:** {defect['area_mm2']} mmΒ²")
with col_d3:
x, y, w, h = defect['position']
st.markdown(f"**Position:** ({x}, {y})")
st.markdown(f"**Size:** {w}Γ{h} px")
else:
st.success("β
No defects detected in this image!")
# Tab 3: Detailed Analysis
with tab_results:
if st.session_state.current_analysis is None:
st.info("π Please upload and analyze an image first to see detailed analysis.")
else:
analysis_data = st.session_state.current_analysis
# Create visualizations
st.markdown("""
<div class="defect-card">
<h3>π Defect Distribution Analysis</h3>
</div>
""", unsafe_allow_html=True)
viz_col1, viz_col2 = st.columns(2)
with viz_col1:
# Defect types pie chart
defect_types = analysis_data['analysis'].get('defect_types', {})
if defect_types:
fig_types = px.pie(
values=list(defect_types.values()),
names=list(defect_types.keys()),
title="Defect Types Distribution",
color_discrete_sequence=['#3b82f6', '#8b5cf6', '#06b6d4', '#ec4899', '#f97316', '#22c55e']
)
fig_types.update_layout(
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font_color='white'
)
st.plotly_chart(fig_types, use_container_width=True)
with viz_col2:
# Severity distribution bar chart
severity_dist = analysis_data['analysis'].get('severity_distribution', {})
if severity_dist:
severity_order = ['Low', 'Medium', 'High', 'Critical']
severity_colors = {'Low': '#22c55e', 'Medium': '#eab308', 'High': '#f97316', 'Critical': '#ef4444'}
fig_severity = go.Figure()
for sev in severity_order:
if sev in severity_dist:
fig_severity.add_trace(go.Bar(
x=[sev],
y=[severity_dist[sev]],
name=sev,
marker_color=severity_colors[sev]
))
fig_severity.update_layout(
title="Severity Distribution",
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font_color='white',
showlegend=False,
xaxis_title="Severity Level",
yaxis_title="Count"
)
st.plotly_chart(fig_severity, use_container_width=True)
st.markdown("---")
# Confidence distribution
st.markdown("""
<div class="defect-card">
<h3>π― Confidence Analysis</h3>
</div>
""", unsafe_allow_html=True)
if analysis_data['defects']:
confidences = [d['confidence'] for d in analysis_data['defects']]
fig_conf = go.Figure()
fig_conf.add_trace(go.Histogram(
x=confidences,
nbinsx=10,
marker_color='#3b82f6',
opacity=0.8
))
fig_conf.update_layout(
title="Confidence Score Distribution",
xaxis_title="Confidence Score",
yaxis_title="Frequency",
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font_color='white'
)
st.plotly_chart(fig_conf, use_container_width=True)
st.markdown("---")
# Generate report
st.markdown("""
<div class="defect-card">
<h3>π Analysis Report</h3>
</div>
""", unsafe_allow_html=True)
report_col1, report_col2 = st.columns(2)
with report_col1:
st.markdown("""
<div class="result-box">
<h4>Test Information</h4>
</div>
""", unsafe_allow_html=True)
report_data = {
'Parameter': ['Date & Time', 'NDT Method', 'Material Type', 'Sensitivity',
'Confidence Threshold', 'Total Defects', 'Critical Defects'],
'Value': [
analysis_data['timestamp'],
analysis_data['ndt_method'],
analysis_data['material_type'],
f"{analysis_data['parameters']['sensitivity']:.2f}",
f"{analysis_data['parameters']['confidence_threshold']:.2f}",
str(analysis_data['analysis'].get('total_defects', 0)),
str(analysis_data['analysis'].get('critical_defects', 0))
]
}
df_report = pd.DataFrame(report_data)
st.dataframe(df_report, use_container_width=True, hide_index=True)
with report_col2:
st.markdown("""
<div class="result-box">
<h4>Recommendations</h4>
</div>
""", unsafe_allow_html=True)
critical_count = analysis_data['analysis'].get('critical_defects', 0)
high_count = analysis_data['analysis'].get('high_defects', 0)
if critical_count > 0:
st.markdown(f"""
<div style="background: rgba(239, 68, 68, 0.1); border-left: 4px solid #ef4444; padding: 15px; border-radius: 8px;">
<h5 style="color: #ef4444; margin: 0;">β οΈ CRITICAL ACTION REQUIRED</h5>
<p style="color: #b0b0b0; margin: 10px 0 0 0;">
{critical_count} critical defect(s) detected. Immediate inspection and
potential repair/replacement recommended.
</p>
</div>
""", unsafe_allow_html=True)
elif high_count > 0:
st.markdown(f"""
<div style="background: rgba(249, 115, 22, 0.1); border-left: 4px solid #f97316; padding: 15px; border-radius: 8px;">
<h5 style="color: #f97316; margin: 0;">β‘ ATTENTION REQUIRED</h5>
<p style="color: #b0b0b0; margin: 10px 0 0 0;">
{high_count} high severity defect(s) detected. Schedule maintenance
and monitoring.
</p>
</div>
""", unsafe_allow_html=True)
else:
st.markdown("""
<div style="background: rgba(34, 197, 94, 0.1); border-left: 4px solid #22c55e; padding: 15px; border-radius: 8px;">
<h5 style="color: #22c55e; margin: 0;">β
PASSED</h5>
<p style="color: #b0b0b0; margin: 10px 0 0 0;">
No critical or high severity defects detected. Component meets
quality standards.
</p>
</div>
""", unsafe_allow_html=True)
# Export options
st.markdown("---")
st.markdown("""
<div class="defect-card">
<h3>πΎ Export Results</h3>
</div>
""", unsafe_allow_html=True)
export_col1, export_col2, export_col3 = st.columns(3)
with export_col1:
if st.button("π₯ Download Annotated Image", use_container_width=True):
buf = BytesIO()
analysis_data['annotated_image'].save(buf, format='PNG')
buf.seek(0)
b64 = base64.b64encode(buf.read()).decode()
href = f'<a href="data:image/png;base64,{b64}" download="annotated_defects.png" style="text-decoration: none;"><button style="width: 100%; padding: 10px; background: linear-gradient(90deg, #3b82f6, #8b5cf6); color: white; border: none; border-radius: 8px; cursor: pointer;">Download PNG</button></a>'
st.markdown(href, unsafe_allow_html=True)
with export_col2:
if st.button("π Export CSV Report", use_container_width=True):
if analysis_data['defects']:
df_export = pd.DataFrame(analysis_data['defects'])
df_export['position'] = df_export['position'].apply(str)
csv = df_export.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}" download="defect_report.csv" style="text-decoration: none;"><button style="width: 100%; padding: 10px; background: linear-gradient(90deg, #3b82f6, #8b5cf6); color: white; border: none; border-radius: 8px; cursor: pointer;">Download CSV</button></a>'
st.markdown(href, unsafe_allow_html=True)
with export_col3:
if st.button("π Generate JSON Report", use_container_width=True):
json_report = {
'test_info': {
'timestamp': analysis_data['timestamp'],
'ndt_method': analysis_data['ndt_method'],
'material_type': analysis_data['material_type'],
'parameters': analysis_data['parameters']
},
'summary': analysis_data['analysis'],
'defects': analysis_data['defects']
}
json_str = json.dumps(json_report, indent=2, default=str)
b64 = base64.b64encode(json_str.encode()).decode()
href = f'<a href="data:file/json;base64,{b64}" download="analysis_report.json" style="text-decoration: none;"><button style="width: 100%; padding: 10px; background: linear-gradient(90deg, #3b82f6, #8b5cf6); color: white; border: none; border-radius: 8px; cursor: pointer;">Download JSON</button></a>'
st.markdown(href, unsafe_allow_html=True)
# Tab 4: History
with tab_history:
st.markdown("""
<div class="defect-card">
<h3>π Analysis History</h3>
<p style="color: #b0b0b0;">
View all previous analyses performed in this session.
</p>
</div>
""", unsafe_allow_html=True)
if not st.session_state.analysis_history:
st.info("No analysis history available. Perform an analysis to see it here.")
else:
st.markdown(f"**Total Analyses:** {len(st.session_state.analysis_history)}")
for i, hist in enumerate(reversed(st.session_state.analysis_history), 1):
with st.expander(f"Analysis #{len(st.session_state.analysis_history) - i + 1}: {hist['timestamp']}"):
hist_col1, hist_col2, hist_col3 = st.columns(3)
with hist_col1:
st.markdown(f"**NDT Method:** {hist['ndt_method']}")
st.markdown(f"**Material:** {hist['material_type']}")
with hist_col2:
st.markdown(f"**Total Defects:** {hist['analysis'].get('total_defects', 0)}")
st.markdown(f"**Critical:** {hist['analysis'].get('critical_defects', 0)}")
with hist_col3:
st.markdown(f"**Avg Confidence:** {hist['analysis'].get('avg_confidence', 0):.2%}")
st.markdown(f"**Total Area:** {hist['analysis'].get('total_area', 0):.2f} mmΒ²")
st.image(hist['annotated_image'], use_container_width=True)
# Footer
st.markdown("---")
st.markdown("""
<div style="text-align: center; padding: 20px; color: #666;">
<p>π¬ <b>CompositeDefect AI</b> - Advanced NDT Analysis System</p>
<p style="font-size: 0.8rem;">Powered by Machine Learning | Β© 2024</p>
</div>
""", unsafe_allow_html=True)
"""
Sample image generator for testing CompositeDefect AI
Generates synthetic NDT-style images with simulated defects
"""
import numpy as np
from PIL import Image, ImageDraw
import random
def generate_ultrasonic_cscan(size=(512, 512), num_defects=5):
"""Generate a synthetic ultrasonic C-scan image"""
# Create base gradient background
img = np.zeros((size[1], size[0]), dtype=np.uint8)
# Add gradient
for y in range(size[1]):
img[y, :] = int(128 + 50 * np.sin(y / 50))
# Add noise
noise = np.random.normal(0, 10, (size[1], size[0])).astype(np.int16)
img = np.clip(img.astype(np.int16) + noise, 0, 255).astype(np.uint8)
# Add simulated defects (darker regions)
img_color = np.stack([img, img, img], axis=2)
pil_img = Image.fromarray(img_color)
draw = ImageDraw.Draw(pil_img)
for _ in range(num_defects):
x = random.randint(50, size[0] - 100)
y = random.randint(50, size[1] - 100)
w = random.randint(30, 80)
h = random.randint(30, 80)
# Draw dark ellipse for defect
draw.ellipse([x, y, x+w, y+h], fill=(40, 40, 60))
return pil_img
def generate_thermal_image(size=(512, 512), num_hotspots=4):
"""Generate a synthetic thermal/infrared image"""
img = np.zeros((size[1], size[0], 3), dtype=np.uint8)
# Base temperature (cool = blue)
img[:, :] = [30, 30, 80]
# Add hotspots (warm = red/yellow)
pil_img = Image.fromarray(img)
draw = ImageDraw.Draw(pil_img)
for _ in range(num_hotspots):
x = random.randint(50, size[0] - 100)
y = random.randint(50, size[1] - 100)
radius = random.randint(20, 60)
# Hotspot gradient
for r in range(radius, 0, -2):
intensity = int(255 * (1 - r/radius))
color = (255, intensity, 0) if intensity > 128 else (255, 0, 255-intensity)
draw.ellipse([x-r, y-r, x+r, y+r], fill=color)
return pil_img
def generate_radiograph(size=(512, 512), num_defects=3):
"""Generate a synthetic X-ray/radiographic image"""
# Base grey
img = np.full((size[1], size[0]), 180, dtype=np.uint8)
# Add structure lines (fibre orientation)
for i in range(0, size[0], 20):
img[:, i:i+2] = np.clip(img[:, i:i+2] - 20, 0, 255)
# Add defects (darker regions = less dense)
pil_img = Image.fromarray(img)
draw = ImageDraw.Draw(pil_img)
for _ in range(num_defects):
x = random.randint(50, size[0] - 150)
y = random.randint(50, size[1] - 150)
# Crack-like defect
if random.random() > 0.5:
x2 = x + random.randint(50, 150)
y2 = y + random.randint(-30, 30)
draw.line([(x, y), (x2, y2)], fill=80, width=3)
else:
# Void
w = random.randint(20, 50)
h = random.randint(20, 50)
draw.ellipse([x, y, x+w, y+h], fill=100)
return pil_img
def generate_visual_inspection(size=(512, 512), num_defects=4):
"""Generate a synthetic visual inspection image"""
# Carbon fibre weave pattern
img = np.zeros((size[1], size[0], 3), dtype=np.uint8)
img[:, :] = [40, 40, 40] # Dark carbon fibre base
# Add weave pattern
for i in range(0, size[0], 8):
img[:, i:i+4] = [60, 60, 60]
for i in range(0, size[1], 8):
img[i:i+4, :] = [50, 50, 50]
pil_img = Image.fromarray(img)
draw = ImageDraw.Draw(pil_img)
for _ in range(num_defects):
x = random.randint(50, size[0] - 100)
y = random.randint(50, size[1] - 100)
defect_type = random.choice(['delamination', 'scratch', 'discoloration'])
if defect_type == 'delamination':
# Delamination - lighter area
w = random.randint(40, 100)
h = random.randint(40, 100)
draw.ellipse([x, y, x+w, y+h], fill=(100, 100, 100, 128))
elif defect_type == 'scratch':
# Scratch line
x2 = x + random.randint(30, 100)
y2 = y + random.randint(-20, 20)
draw.line([(x, y), (x2, y2)], fill=(150, 150, 150), width=2)
else:
# Discoloration
w = random.randint(30, 80)
h = random.randint(30, 80)
draw.rectangle([x, y, x+w, y+h], fill=(80, 60, 40))
return pil_img
def main():
"""Generate sample images for testing"""
print("π¬ Generating sample NDT images for testing...")
# Generate different types of NDT images
ultrasonic = generate_ultrasonic_cscan(num_defects=6)
ultrasonic.save('sample_ultrasonic.png')
print("β
Generated: sample_ultrasonic.png")
thermal = generate_thermal_image(num_hotspots=5)
thermal.save('sample_thermal.png')
print("β
Generated: sample_thermal.png")
radiograph = generate_radiograph(num_defects=4)
radiograph.save('sample_radiograph.png')
print("β
Generated: sample_radiograph.png")
visual = generate_visual_inspection(num_defects=5)
visual.save('sample_visual.png')
print("β
Generated: sample_visual.png")
print("\nπ Sample images saved in current directory")
print("π You can now test the CompositeDefect AI application!")
if __name__ == "__main__":
main()
import streamlit as st
import numpy as np
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
from datetime import datetime
import json
import os
from collections import Counter
import base64
from io import BytesIO
# Page configuration
st.set_page_config(
page_title="CompositeDefect AI - NDT Analysis System",
page_icon="π¬",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for black/white/grey/blue/purple theme
st.markdown("""
<style>
/* Main theme colors */
:root {
--bg-primary: #0a0a0a;
--bg-secondary: #141414;
--bg-tertiary: #1e1e1e;
--text-primary: #ffffff;
--text-secondary: #b0b0b0;
--accent-blue: #3b82f6;
--accent-purple: #8b5cf6;
--accent-cyan: #06b6d4;
--border-color: #2a2a2a;
}
/* Global styles */
.stApp {
background: linear-gradient(135deg, #0a0a0a 0%, #141414 50%, #0f0f23 100%);
}
/* Sidebar styling */
.css-1d391kg, .css-1lcbmhc {
background: linear-gradient(180deg, #141414 0%, #1a1a2e 100%) !important;
}
/* Headers */
h1 {
background: linear-gradient(90deg, #3b82f6, #8b5cf6, #06b6d4);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-weight: 700 !important;
}
h2, h3 {
color: #ffffff !important;
font-weight: 600 !important;
}
/* Cards */
.defect-card {
background: linear-gradient(145deg, #1e1e1e, #252525);
border: 1px solid #2a2a2a;
border-radius: 12px;
padding: 20px;
margin: 10px 0;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
transition: all 0.3s ease;
}
.defect-card:hover {
border-color: #3b82f6;
box-shadow: 0 4px 20px rgba(59, 130, 246, 0.2);
}
/* Metric cards */
.metric-container {
background: linear-gradient(145deg, #1e1e1e, #252525);
border-left: 4px solid #3b82f6;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
}
.metric-value {
font-size: 2rem;
font-weight: 700;
color: #3b82f6;
}
.metric-label {
color: #b0b0b0;
font-size: 0.9rem;
}