File size: 9,635 Bytes
15526fe
3db0aec
 
9814e5f
3db0aec
 
 
 
d604335
d9a6878
3db0aec
 
 
d604335
 
 
 
 
3db0aec
d604335
 
 
 
 
 
 
3db0aec
 
 
 
 
 
 
 
 
d604335
3db0aec
d604335
 
 
 
 
 
 
 
 
 
 
3db0aec
d604335
3db0aec
 
d604335
 
7030681
d604335
 
3db0aec
 
d604335
 
 
3db0aec
 
 
d604335
 
 
 
 
 
 
 
3db0aec
d604335
 
3db0aec
d604335
 
 
 
 
3db0aec
 
 
 
d604335
3db0aec
 
d604335
dbd2162
60dab82
3db0aec
d604335
3db0aec
7030681
3db0aec
d604335
3db0aec
7030681
d604335
 
3db0aec
 
d604335
 
3db0aec
d9a6878
d604335
 
 
 
 
 
 
 
 
 
d9a6878
d604335
3db0aec
15526fe
d604335
 
3db0aec
d604335
 
dbd2162
d604335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db0aec
d604335
15526fe
9814e5f
d604335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db0aec
d604335
 
 
 
d9a6878
d604335
d9a6878
d604335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3db0aec
d604335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9814e5f
 
d604335
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
import streamlit as st
from transformers import ViTForImageClassification, ViTImageProcessor
from PIL import Image
import torch
import time
import gc
from knowledge_base import KNOWLEDGE_BASE, DAMAGE_TYPES
from rag_utils import RAGSystem
import os

# Constants
MAX_FILE_SIZE = 5 * 1024 * 1024  # 5MB
MAX_IMAGE_SIZE = 1024  # Maximum dimension for images
MODEL_NAME = "google/vit-base-patch16-224"
CACHE_DIR = "/tmp/model_cache"  # HF Spaces compatible cache directory

# Ensure cache directory exists
os.makedirs(CACHE_DIR, exist_ok=True)

# Initialize session state for caching
if 'model' not in st.session_state:
    st.session_state.model = None
if 'processor' not in st.session_state:
    st.session_state.processor = None
if 'rag_system' not in st.session_state:
    st.session_state.rag_system = None

def cleanup_memory():
    """Clean up memory and GPU cache"""
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

@st.cache_resource(show_spinner="Loading AI model...")
def load_model():
    """Load and cache the model and processor with error handling"""
    try:
        # Initialize processor with cache directory
        processor = ViTImageProcessor.from_pretrained(
            MODEL_NAME,
            cache_dir=CACHE_DIR,
            local_files_only=False
        )
        
        # Determine device - prefer CPU on Hugging Face Spaces
        device = "cpu"  # Default to CPU for stability
        
        # Load model with specific configuration
        model = ViTForImageClassification.from_pretrained(
            MODEL_NAME,
            num_labels=len(DAMAGE_TYPES),
            ignore_mismatched_sizes=True,
            cache_dir=CACHE_DIR,
            local_files_only=False
        ).to(device)
        
        model.eval()  # Set to evaluation mode
        return model, processor
    except Exception as e:
        st.error(f"Error loading model: {str(e)}")
        st.info("Attempting to reload model... Please wait.")
        cleanup_memory()
        return None, None

def init_rag_system():
    """Initialize RAG system with error handling"""
    if st.session_state.rag_system is None:
        try:
            st.session_state.rag_system = RAGSystem()
            st.session_state.rag_system.initialize_knowledge_base(KNOWLEDGE_BASE)
        except Exception as e:
            st.error(f"Error initializing RAG system: {str(e)}")
            st.session_state.rag_system = None

def process_image(image):
    """Process and validate image with enhanced error handling"""
    try:
        # Convert to RGB if necessary
        if image.mode != 'RGB':
            image = image.convert('RGB')
        
        # Resize if needed
        if max(image.size) > MAX_IMAGE_SIZE:
            ratio = MAX_IMAGE_SIZE / max(image.size)
            new_size = tuple([int(dim * ratio) for dim in image.size])
            image = image.resize(new_size, Image.Resampling.LANCZOS)
        
        return image
    except Exception as e:
        st.error(f"Error processing image: {str(e)}")
        return None

def analyze_damage(image, model, processor):
    """Analyze structural damage with enhanced error handling and memory management"""
    try:
        device = next(model.parameters()).device
        with torch.no_grad():
            # Process image
            inputs = processor(images=image, return_tensors="pt")
            inputs = {k: v.to(device) for k, v in inputs.items()}
            
            # Run inference
            outputs = model(**inputs)
            probs = torch.nn.functional.softmax(outputs.logits, dim=1)[0]
            
            # Clean up
            cleanup_memory()
            return probs.cpu()
    except RuntimeError as e:
        if "out of memory" in str(e):
            cleanup_memory()
            st.error("Memory error. Processing with reduced image size...")
            # Retry with smaller image
            image = image.resize((224, 224), Image.Resampling.LANCZOS)
            return analyze_damage(image, model, processor)
        else:
            st.error(f"Error during analysis: {str(e)}")
        return None
    except Exception as e:
        st.error(f"Unexpected error: {str(e)}")
        return None

def display_analysis_results(predictions, analysis_time):
    """Display analysis results with enhanced visualization and error handling"""
    try:
        st.markdown("### πŸ“Š Analysis Results")
        st.markdown(f"*Analysis completed in {analysis_time:.2f} seconds*")
        
        detected = False
        for idx, prob in enumerate(predictions):
            confidence = float(prob) * 100
            if confidence > 15:  # Threshold for displaying results
                detected = True
                damage_type = DAMAGE_TYPES[idx]['name']
                risk_level = DAMAGE_TYPES[idx]['risk']
                
                # Create expander with color-coded header
                with st.expander(
                    f"πŸ” {damage_type.replace('_', ' ').title()} - {confidence:.1f}% ({risk_level})",
                    expanded=True
                ):
                    # Display confidence bar
                    st.progress(confidence / 100)
                    
                    # Create tabs for organized information
                    details_tab, repair_tab, action_tab = st.tabs([
                        "πŸ“‹ Details", "πŸ”§ Repair Plan", "⚠️ Actions Needed"
                    ])
                    
                    with details_tab:
                        display_damage_details(damage_type, confidence)
                    
                    with repair_tab:
                        display_repair_plan(damage_type)
                    
                    with action_tab:
                        display_action_items(damage_type)
                    
                    # Display enhanced analysis if RAG system is available
                    if st.session_state.rag_system:
                        display_enhanced_analysis(damage_type, confidence)
        
        if not detected:
            st.success("No significant structural damage detected. Regular maintenance recommended.")
            
    except Exception as e:
        st.error(f"Error displaying results: {str(e)}")

def main():
    """Main application function with enhanced error handling and UI"""
    try:
        # Page configuration
        st.set_page_config(
            page_title="Structural Damage Analyzer Pro",
            page_icon="πŸ—οΈ",
            layout="wide",
            initial_sidebar_state="expanded"
        )
        
        # Custom CSS
        st.markdown(get_custom_css(), unsafe_allow_html=True)
        
        # Header
        display_header()
        
        # Initialize systems
        if st.session_state.model is None or st.session_state.processor is None:
            with st.spinner("Initializing AI model..."):
                model, processor = load_model()
                if model is None:
                    st.error("Failed to initialize model. Please refresh the page.")
                    return
                st.session_state.model = model
                st.session_state.processor = processor
        
        init_rag_system()
        
        # File upload section
        uploaded_file = st.file_uploader(
            "Upload structural image for analysis",
            type=['jpg', 'jpeg', 'png'],
            help="Maximum file size: 5MB"
        )
        
        if uploaded_file:
            process_uploaded_file(uploaded_file)
        
        # Footer
        display_footer()
        
    except Exception as e:
        st.error(f"Application error: {str(e)}")
        st.info("Please refresh the page and try again.")
        cleanup_memory()

def process_uploaded_file(uploaded_file):
    """Process uploaded file with comprehensive error handling"""
    try:
        # Validate file size
        if uploaded_file.size > MAX_FILE_SIZE:
            st.error("File too large. Please upload an image smaller than 5MB.")
            return
        
        # Process image
        image = Image.open(uploaded_file)
        processed_image = process_image(image)
        if processed_image is None:
            return
        
        # Display layout
        col1, col2 = st.columns([1, 1])
        with col1:
            st.image(processed_image, caption="Uploaded Structure", use_column_width=True)
        
        with col2:
            with st.spinner("πŸ” Analyzing structural damage..."):
                start_time = time.time()
                predictions = analyze_damage(
                    processed_image,
                    st.session_state.model,
                    st.session_state.processor
                )
                if predictions is not None:
                    analysis_time = time.time() - start_time
                    display_analysis_results(predictions, analysis_time)
                
    except Exception as e:
        st.error(f"Error processing upload: {str(e)}")
        cleanup_memory()

def get_custom_css():
    """Return custom CSS for enhanced UI"""
    return """
    <style>
    .main {
        padding: 1rem;
    }
    .stProgress > div > div > div > div {
        background-image: linear-gradient(to right, #ff6b6b, #f06595);
    }
    .damage-card {
        padding: 1rem;
        border-radius: 0.5rem;
        background: var(--background-color, #ffffff);
        margin-bottom: 1rem;
        border: 1px solid var(--border-color, #e0e0e0);
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    </style>
    """

if __name__ == "__main__":
    main()