Spaces:
Runtime error
Runtime error
File size: 41,622 Bytes
8fe4f21 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 | 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()
|