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("""
""", 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("""
""", 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("""
๐ค Upload NDT Test Results
Upload your NDT inspection images for AI-powered defect detection and analysis.
Supports JPG, PNG, TIFF, and BMP formats.
""", 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("""
๐ Image Information
""", 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("""
๐ผ๏ธ Preview
""", 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("""
๐ Detection Summary
""", unsafe_allow_html=True)
metric_cols = st.columns(4)
with metric_cols[0]:
st.markdown(f"""
""", unsafe_allow_html=True)
img_col1, img_col2, img_col3 = st.columns(3)
with img_col1:
st.markdown("
Original Image
",
unsafe_allow_html=True)
st.image(analysis_data['original_image'], use_container_width=True)
with img_col2:
st.markdown("
Preprocessed
",
unsafe_allow_html=True)
st.image(analysis_data['preprocessed_image'], use_container_width=True)
with img_col3:
st.markdown("
Detected Defects
",
unsafe_allow_html=True)
st.image(analysis_data['annotated_image'], use_container_width=True)
st.markdown("---")
# Defect list
st.markdown("""
๐ Detected Defects
""", 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:** {defect['severity']}",
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("""
๐ Defect Distribution Analysis
""", 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("""
๐ฏ Confidence Analysis
""", 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("""
๐ Analysis Report
""", unsafe_allow_html=True)
report_col1, report_col2 = st.columns(2)
with report_col1:
st.markdown("""
View all previous analyses performed in this session.
""", 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("""
๐ฌ CompositeDefect AI - Advanced NDT Analysis System