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
 
 
 
 
 
 
 
 
 
 
 
 
 
c8f5637
723ebe4
c8f5637
 
723ebe4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

AI-Driven Polymer Aging Prediction and Classification

Hugging Face Spaces Deployment

This is an adapted version of the Streamlit app optimized for Hugging Face Spaces deployment.

It maintains all the functionality of the original app while being self-contained and cloud-ready.

"""

import os
import sys
from pathlib import Path

# Ensure 'utils' directory is in the Python path
utils_path = Path(__file__).resolve().parent / "utils"
if utils_path.is_dir() and str(utils_path) not in sys.path:
    sys.path.append(str(utils_path))
import streamlit as st
import torch
import numpy as np
import matplotlib
matplotlib.use("Agg") # ensure headless rendering in Spaces
import matplotlib.pyplot as plt
from PIL import Image
import io
from pathlib import Path
import time
import gc
from io import StringIO

# Import local modules
from models.figure2_cnn import Figure2CNN
from models.resnet_cnn import ResNet1D
# Prefer canonical script; fallback to local utils for HF hard-copy scenario
try:
    from scripts.preprocess_dataset import resample_spectrum
except ImportError:
    from utils.preprocessing import resample_spectrum

# Configuration
st.set_page_config(
    page_title="ML Polymer Classification",
    page_icon="πŸ”¬",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Constants
TARGET_LEN = 500
SAMPLE_DATA_DIR = "sample_data"
# Prefer env var, else 'model_weights' if present; else canonical 'outputs'
MODEL_WEIGHTS_DIR = (
    os.getenv("WEIGHTS_DIR")
    or ("model_weights" if os.path.isdir("model_weights") else "outputs")
)

# Model configuration
MODEL_CONFIG = {
    "Figure2CNN (Baseline)": {
        "class": Figure2CNN,
        "path": f"{MODEL_WEIGHTS_DIR}/figure2_model.pth",
        "emoji": "πŸ”¬",
        "description": "Baseline CNN with standard filters",
        "accuracy": "94.80%",
        "f1": "94.30%"
    },
    "ResNet1D (Advanced)": {
        "class": ResNet1D,
        "path": f"{MODEL_WEIGHTS_DIR}/resnet_model.pth",
        "emoji": "🧠", 
        "description": "Residual CNN with deeper feature learning",
        "accuracy": "96.20%",
        "f1": "95.90%"
    }
}

# Label mapping
LABEL_MAP = {0: "Stable (Unweathered)", 1: "Weathered (Degraded)"}

# Utility functions
def label_file(filename: str) -> int:
    """Extract label from filename based on naming convention"""
    name = Path(filename).name.lower()
    if name.startswith("sta"):
        return 0
    elif name.startswith("wea"):
        return 1
    else:
        # Return None for unknown patterns instead of raising error
        return -1  # Default value for unknown patterns

@st.cache_resource
def load_model(model_name):
    """Load and cache the specified model with error handling"""
    try:
        config = MODEL_CONFIG[model_name]
        model_class = config["class"]
        model_path = config["path"]

        # Initialize model
        model = model_class(input_length=TARGET_LEN)

        # Check if model file exists
        if not os.path.exists(model_path):
            st.warning(f"⚠️ Model weights not found: {model_path}")
            st.info("Using randomly initialized model for demonstration purposes.")
            return model, False

        # Load weights
        state_dict = torch.load(model_path, map_location="cpu")
        model.load_state_dict(state_dict, strict=False)
        if model is not None:
            model.eval()
        else:
            raise ValueError("Model is not loaded. Please check the model configuration or weights.")

        return model, True

    except Exception as e:
        st.error(f"❌ Error loading model {model_name}: {str(e)}")
        return None, False

def cleanup_memory():
    """Clean up memory after inference"""
    gc.collect()
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

@st.cache_data
def get_sample_files():
    """Get list of sample files if available"""
    sample_dir = Path(SAMPLE_DATA_DIR)
    if sample_dir.exists():
        return sorted(list(sample_dir.glob("*.txt")))
    return []

def parse_spectrum_data(raw_text):
    """Parse spectrum data from text with robust error handling"""
    x_vals, y_vals = [], []

    for line in raw_text.splitlines():
        line = line.strip()
        if not line or line.startswith('#'):  # Skip empty lines and comments
            continue

        try:
            # Handle different separators
            parts = line.replace(",", " ").split()
            numbers = [p for p in parts if p.replace('.', '', 1).replace('-', '', 1).replace('+', '', 1).isdigit()]

            if len(numbers) >= 2:
                x, y = float(numbers[0]), float(numbers[1])
                x_vals.append(x)
                y_vals.append(y)

        except ValueError:
            # Skip problematic lines but don't fail completely
            continue

    if len(x_vals) < 10:  # Minimum reasonable spectrum length
        raise ValueError(f"Insufficient data points: {len(x_vals)}. Need at least 10 points.")

    return np.array(x_vals), np.array(y_vals)

def create_spectrum_plot(x_raw, y_raw, y_resampled):
    """Create spectrum visualization plot"""
    fig, ax = plt.subplots(1, 2, figsize=(12, 4), dpi=100)

    # Raw spectrum
    ax[0].plot(x_raw, y_raw, label="Raw", color="dimgray", linewidth=1)
    ax[0].set_title("Raw Input Spectrum")
    ax[0].set_xlabel("Wavenumber (cm⁻¹)")
    ax[0].set_ylabel("Intensity")
    ax[0].grid(True, alpha=0.3)
    ax[0].legend()

    # Resampled spectrum  
    x_resampled = np.linspace(min(x_raw), max(x_raw), TARGET_LEN)
    ax[1].plot(x_resampled, y_resampled, label="Resampled", color="steelblue", linewidth=1)
    ax[1].set_title(f"Resampled ({TARGET_LEN} points)")
    ax[1].set_xlabel("Wavenumber (cm⁻¹)")
    ax[1].set_ylabel("Intensity")
    ax[1].grid(True, alpha=0.3)
    ax[1].legend()

    plt.tight_layout()

    # Convert to image
    buf = io.BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight', dpi=100)
    buf.seek(0)
    plt.close(fig)  # Prevent memory leaks

    return Image.open(buf)

def get_confidence_description(logit_margin):
    """Get human-readable confidence description"""
    if logit_margin > 1000:
        return "VERY HIGH", "🟒"
    elif logit_margin > 250:
        return "HIGH", "🟑"
    elif logit_margin > 100:
        return "MODERATE", "🟠"
    else:
        return "LOW", "πŸ”΄"

# Initialize session state
def init_session_state():
    """Initialize session state variables"""
    defaults = {
        'status_message': "Ready to analyze polymer spectra πŸ”¬",
        'status_type': "info",
        'uploaded_file': None,  # legacy; kept for compatibility
        'input_text': None,     # ←←← NEW: canonical store for spectrum text
        'filename': None,
        'inference_run_once': False,
        'x_raw': None,
        'y_raw': None,
        'y_resampled': None
    }

    for key, default_value in defaults.items():
        if key not in st.session_state:
            st.session_state[key] = default_value

# Main app
def main():
    init_session_state()

    # Header
    st.title("πŸ”¬ AI-Driven Polymer Classification")
    st.markdown("**Predict polymer degradation states using Raman spectroscopy and deep learning**")

    # Sidebar
    with st.sidebar:
        st.header("ℹ️ About This App")
        st.markdown("""

        **AIRE 2025 Internship Project**  

        AI-Driven Polymer Aging Prediction and Classification

        

        🎯 **Purpose**: Classify polymer degradation using AI  

        πŸ“Š **Input**: Raman spectroscopy data  

        🧠 **Models**: CNN architectures for binary classification  

        

        **Team**: 

        - **Mentor**: Dr. Sanmukh Kuppannagari

        - **Mentor**: Dr. Metin Karailyan

        - **Author**: Jaser Hasan 

        

        πŸ”— [GitHub Repository](https://github.com/KLab-AI3/ml-polymer-recycling)

        """)

        st.markdown("---")

        # Model selection
        st.subheader("🧠 Model Selection")
        model_labels = [f"{MODEL_CONFIG[name]['emoji']} {name}" for name in MODEL_CONFIG.keys()]
        selected_label = st.selectbox("Choose AI model:", model_labels)
        model_choice = selected_label.split(" ", 1)[1]

        # Model info
        config = MODEL_CONFIG[model_choice]
        st.markdown(f"""

        **πŸ“ˆ {config['emoji']} Model Details**

        

        *{config['description']}*

        

        - **Accuracy**: `{config['accuracy']}`

        - **F1 Score**: `{config['f1']}`

        """)

    # Main content area
    col1, col2 = st.columns([1, 1.5], gap="large")

    with col1:
        st.subheader("πŸ“ Data Input")

        # File upload tabs
        tab1, tab2 = st.tabs(["πŸ“€ Upload File", "πŸ§ͺ Sample Data"])

        uploaded_file = None

        with tab1:
            uploaded_file = st.file_uploader(
                "Upload Raman spectrum (.txt)", 
                type="txt",
                help="Upload a text file with wavenumber and intensity columns",
                key="upload_text"
            )

            if uploaded_file:
                # Read now and persist raw text; avoid holding open buffers in session_state
                raw = uploaded_file.read()
                text = raw.decode("utf-8") if isinstance(raw, bytes) else raw
                st.session_state['input_text'] = text
                st.session_state['filename'] = uploaded_file.name
                st.session_state['uploaded_file'] = None # avoid stale buffers
                st.success(f"βœ… Loaded: {uploaded_file.name}")

        with tab2:
            sample_files = get_sample_files()
            if sample_files:
                sample_options = ["-- Select Sample --"] + [f.name for f in sample_files]
                selected_sample = st.selectbox("Choose sample spectrum:", sample_options, key="sample_select")

                if selected_sample != "-- Select Sample --":
                    selected_path = Path(SAMPLE_DATA_DIR) / selected_sample
                    try:
                        with open(selected_path, "r", encoding="utf-8") as f:
                            file_contents = f.read()
                        # Persist raw text + name; no open file handles in session_state
                        st.session_state['input_text'] = file_contents
                        st.session_state['filename'] = selected_sample
                        st.session_state['uploaded_file'] = None
                        st.success(f"βœ… Loaded sample: {selected_sample}")
                    except (FileNotFoundError, IOError) as e:
                        st.error(f"Error loading sample: {e}")
            else:
                st.info("No sample data available")

        # Update session state
        # If we captured text via either tab, reflect readiness in status
        if st.session_state.get('input_text'):
            st.session_state['status_message'] = f"πŸ“ File '{st.session_state.get('filename', '(unnamed)')}' ready for analysis"
            st.session_state['status_type'] = "success"

        # Status display
        st.subheader("🚦 Status")
        status_msg = st.session_state.get("status_message", "Ready")
        status_type = st.session_state.get("status_type", "info")

        if status_type == "success":
            st.success(status_msg)
        elif status_type == "error":
            st.error(status_msg)
        else:
            st.info(status_msg)

        # Load model
        model, model_loaded = load_model(model_choice)

        # Ready if we have cached text and a model instance
        inference_ready = bool(st.session_state.get('input_text')) and (model is not None)

        if not model_loaded:
            st.warning("⚠️ Model weights not available - using demo mode")

        if st.button("▢️ Run Analysis", disabled=not inference_ready, type="primary", key="run_btn"):
            if inference_ready:
                try:
                    # Use persisted text + filename (works for uploads and samples)
                    raw_text = st.session_state.get('input_text')
                    filename = st.session_state.get('filename') or "unknown.txt"
                    if not raw_text:
                        raise ValueError("No input text available. Please upload or select a sample.")

                    # Parse spectrum
                    with st.spinner("Parsing spectrum data..."):
                        x_raw, y_raw = parse_spectrum_data(raw_text)

                    # Resample spectrum
                    with st.spinner("Resampling spectrum..."):
                        y_resampled = resample_spectrum(x_raw, y_raw, TARGET_LEN)

                    # Store in session state
                    st.session_state['x_raw'] = x_raw
                    st.session_state['y_raw'] = y_raw  
                    st.session_state['y_resampled'] = y_resampled
                    st.session_state['inference_run_once'] = True
                    st.session_state['status_message'] = f"πŸ” Analysis completed for: {filename}"
                    st.session_state['status_type'] = "success"

                    st.rerun()

                except Exception as e:
                    st.error(f"❌ Analysis failed: {str(e)}")
                    st.session_state['status_message'] = f"❌ Error: {str(e)}"
                    st.session_state['status_type'] = "error"

    # Results column
    with col2:
        if st.session_state.get("inference_run_once", False):
            st.subheader("πŸ“Š Analysis Results")

            # Get data from session state
            x_raw = st.session_state.get('x_raw')
            y_raw = st.session_state.get('y_raw')
            y_resampled = st.session_state.get('y_resampled')
            filename = st.session_state.get('filename', 'Unknown')

            if all(v is not None for v in [x_raw, y_raw, y_resampled]):

                # Create and display plot
                try:
                    spectrum_plot = create_spectrum_plot(x_raw, y_raw, y_resampled)
                    st.image(spectrum_plot, caption="Spectrum Preprocessing Results", use_container_width=True)
                except Exception as e:
                    st.warning(f"Could not generate plot: {e}")

                # Run inference
                try:
                    with st.spinner("Running AI inference..."):
                        start_time = time.time()

                        # Prepare input tensor
                        input_tensor = torch.tensor(y_resampled, dtype=torch.float32).unsqueeze(0).unsqueeze(0)

                        # Run inference
                        model.eval()
                        with torch.no_grad():
                            if model is None:
                                raise ValueError("Model is not loaded. Please check the model configuration or weights.")
                            logits = model(input_tensor)
                            prediction = torch.argmax(logits, dim=1).item()
                            logits_list = logits.detach().numpy().tolist()[0]

                        inference_time = time.time() - start_time

                        # Clean up memory
                        cleanup_memory()

                    # Get ground truth if available
                    true_label_idx = label_file(filename)
                    true_label_str = LABEL_MAP.get(true_label_idx, "Unknown") if true_label_idx is not None else "Unknown"

                    # Get prediction
                    predicted_class = LABEL_MAP.get(int(prediction), f"Class {int(prediction)}")

                    # Calculate confidence metrics
                    logit_margin = abs(logits_list[0] - logits_list[1]) if len(logits_list) >= 2 else 0
                    confidence_desc, confidence_emoji = get_confidence_description(logit_margin)

                    # Display results
                    st.markdown("### 🎯 Prediction Results")

                    # Main prediction
                    st.markdown(f"""

                    **πŸ”¬ Sample**: `{filename}`  

                    **🧠 Model**: `{model_choice}`  

                    **⏱️ Processing Time**: `{inference_time:.2f}s`

                    """)

                    # Prediction box
                    if predicted_class == "Stable (Unweathered)":
                        st.success(f"🟒 **Prediction**: {predicted_class}")
                    else:
                        st.warning(f"🟑 **Prediction**: {predicted_class}")

                    # Confidence
                    st.markdown(f"**{confidence_emoji} Confidence**: {confidence_desc} (margin: {logit_margin:.1f})")

                    # Ground truth comparison
                    if true_label_idx is not None:
                        if predicted_class == true_label_str:
                            st.success(f"βœ… **Ground Truth**: {true_label_str} - **Correct!**")
                        else:
                            st.error(f"❌ **Ground Truth**: {true_label_str} - **Incorrect**")
                    else:
                        st.info("ℹ️ **Ground Truth**: Unknown (filename doesn't follow naming convention)")

                    # Detailed results tabs
                    tab1, tab2, tab3 = st.tabs(["πŸ“Š Details", "πŸ”¬ Technical", "πŸ“˜ Explanation"])

                    with tab1:
                        st.markdown("**Model Output (Logits)**")
                        for i, score in enumerate(logits_list):
                            label = LABEL_MAP.get(i, f"Class {i}")
                            st.metric(label, f"{score:.2f}")

                        st.markdown("**Spectrum Statistics**")
                        st.json({
                            "Original Length": len(x_raw) if x_raw is not None else 0,
                            "Resampled Length": TARGET_LEN,
                            "Wavenumber Range": f"{min(x_raw):.1f} - {max(x_raw):.1f} cm⁻¹" if x_raw is not None else "N/A",
                            "Intensity Range": f"{min(y_raw):.1f} - {max(y_raw):.1f}" if y_raw is not None else "N/A",
                            "Model Confidence": confidence_desc
                        })

                    with tab2:
                        st.markdown("**Technical Information**")
                        st.json({
                            "Model Architecture": model_choice,
                            "Input Shape": list(input_tensor.shape),
                            "Output Shape": list(logits.shape),
                            "Inference Time": f"{inference_time:.3f}s",
                            "Device": "CPU",
                            "Model Loaded": model_loaded
                        })

                        if not model_loaded:
                            st.warning("⚠️ Demo mode: Using randomly initialized weights")

                    with tab3:
                        st.markdown("""

                        **πŸ” Analysis Process**

                        

                        1. **Data Upload**: Raman spectrum file loaded

                        2. **Preprocessing**: Data parsed and resampled to 500 points

                        3. **AI Inference**: CNN model analyzes spectral patterns

                        4. **Classification**: Binary prediction with confidence scores

                        

                        **🧠 Model Interpretation**

                        

                        The AI model identifies spectral features indicative of:

                        - **Stable polymers**: Well-preserved molecular structure

                        - **Weathered polymers**: Degraded/oxidized molecular bonds

                        

                        **🎯 Applications**

                        

                        - Material longevity assessment

                        - Recycling viability evaluation  

                        - Quality control in manufacturing

                        - Environmental impact studies

                        """)

                except Exception as e:
                    st.error(f"❌ Inference failed: {str(e)}")

            else:
                st.error("❌ Missing spectrum data. Please upload a file and run analysis.")
        else:
            # Welcome message
            st.markdown("""

            ### πŸ‘‹ Welcome to AI Polymer Classification

            

            **Get started by:**

            1. 🧠 Select an AI model in the sidebar

            2. πŸ“ Upload a Raman spectrum file or choose a sample

            3. ▢️ Click "Run Analysis" to get predictions

            

            **Supported formats:**

            - Text files (.txt) with wavenumber and intensity columns

            - Space or comma-separated values

            - Any length (automatically resampled to 500 points)

            

            **Example applications:**

            - πŸ”¬ Research on polymer degradation

            - ♻️ Recycling feasibility assessment

            - 🌱 Sustainability impact studies

            - 🏭 Quality control in manufacturing

            """)

# Run the application
main()