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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
'''import streamlit as st
import numpy as np
from PIL import Image
import torch
from anomalib.deploy import TorchInferencer
import cv2
import os
import tempfile
import uuid

# Custom Modules
import db
import analytics
import report

# Allow loading pickle models
os.environ["TRUST_REMOTE_CODE"] = "True"

# Initialize DB
db.init_db()

st.set_page_config(page_title="Capsule Defect Detection", layout="wide")

st.title("πŸ’Š Capsule Defect Detection System")

# --- Tabs ---
tab_inference, tab_analytics = st.tabs(["πŸ•΅οΈ Inference & Inspection", "πŸ“Š Analytics & Reporting"])

# --- Model Loading ---
@st.cache_resource
def load_models(anomaly_weights_path, classifier_weights_path):
    models = {}
    
    # 1. Anomaly Model (PatchCore)
    if not os.path.exists(anomaly_weights_path):
        st.error(f"Anomaly weights not found at {anomaly_weights_path}. Please run training first.")
    else:
        models['anomaly'] = TorchInferencer(
            path=anomaly_weights_path,
            device="cpu", 
        )
        
    # 2. Classifier Model (ResNet18)
    if os.path.exists(classifier_weights_path):
        from torchvision import models as tv_models
        from torchvision import transforms
        import torch.nn as nn
        
        # Load checkpoint
        checkpoint = torch.load(classifier_weights_path, map_location=torch.device('cpu'))
        class_names = checkpoint['class_names']
        
        # Re-create model structure
        classifier = tv_models.resnet18(weights=None)
        num_ftrs = classifier.fc.in_features
        classifier.fc = nn.Linear(num_ftrs, len(class_names))
        
        # Load weights
        classifier.load_state_dict(checkpoint['model_state_dict'])
        classifier.eval()
        
        models['classifier'] = classifier
        models['classes'] = class_names
        
        # Transforms for classifier
        models['transforms'] = transforms.Compose([
            transforms.Resize((256, 256)),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
        ])
    else:
        st.warning(f"Classifier weights not found at {classifier_weights_path}. Automatic defect typing disabled.")
        
    return models

# Paths
ANOMALY_MODEL_PATH = "results/weights/weights/torch/model.pt"
CLASSIFIER_MODEL_PATH = "results/classifier.pth"

loaded_models = load_models(ANOMALY_MODEL_PATH, CLASSIFIER_MODEL_PATH)
model = loaded_models.get('anomaly')
classifier = loaded_models.get('classifier')
class_names = loaded_models.get('classes')
classifier_transforms = loaded_models.get('transforms')

# ==========================================
# TAB 1: INFERENCE
# ==========================================
with tab_inference:
    st.markdown("### Real-time Inspection")
    uploaded_file = st.file_uploader("Upload Capsule Image", type=["jpg", "png", "jpeg"])

    if uploaded_file is not None:
        col1, col2 = st.columns(2)
        
        # Preprocessing
        image = Image.open(uploaded_file).convert("RGB")
        image_np = np.array(image)
        
        with col1:
            st.image(image, caption="Original Image", use_column_width=True)

        if st.button("Analyze Image"):
            if model is None:
                st.error("Model not loaded.")
            else:
                with st.spinner("Analyzing..."):
                    # Inference
                    predictions = model.predict(image=image_np)
                    
                    pred_score = predictions.pred_score
                    if isinstance(pred_score, torch.Tensor):
                        pred_score = pred_score.item()

                    anomaly_map = predictions.anomaly_map
                    
                    # --- Thresholding ---
                    # Good images ~25.7, Defects ~70.8. Setting default to 45.0.
                    threshold = st.slider("Anomaly Threshold", min_value=0.0, max_value=100.0, value=45.0, step=0.5)
                    
                    # Logic
                    is_defect = pred_score > threshold
                    pred_label = "Defect" if is_defect else "Good"
                    
                    # Determine Severity based on Score
                    severity = "Normal"
                    if is_defect:
                        if pred_score < 60:
                            severity = "Minor"
                        elif pred_score < 80:
                            severity = "Medium"
                        else:
                            severity = "Critical"
                            
                    # --- Automatic Defect Classification ---
                    final_defect_type = "Normal"
                    
                    if is_defect:
                        if classifier is not None:
                            # Prepare image for classifier (using PIL image)
                            input_tensor = classifier_transforms(image).unsqueeze(0) # Add batch dim
                            
                            with torch.no_grad():
                                outputs = classifier(input_tensor)
                                _, preds = torch.max(outputs, 1)
                                predicted_class = class_names[preds[0]]
                                
                            # Logic: If classifier says "good" but PatchCore says "Defect",
                            # we report "Unclassified" or potential false positive.
                            if predicted_class == "good":
                                final_defect_type = "Unclassified (Potential False Positive)"
                            else:
                                final_defect_type = predicted_class
                        else:
                             final_defect_type = "General Defect"
                    else:
                        final_defect_type = "Normal (Good)"
                    
                    # --- Results ---
                    st.success("Analysis Complete!")
                    
                    # Log to DB
                    inspection_id = str(uuid.uuid4())[:8]
                    db.log_inspection(
                        image_id=inspection_id,
                        status=pred_label,
                        defect_type=final_defect_type,
                        score=pred_score,
                        severity=severity
                    )
                    st.toast(f"Result logged to database (ID: {inspection_id})")
                    
                    # Metrics Display
                    m_col1, m_col2, m_col3 = st.columns(3)
                    m_col1.metric("Status", pred_label, delta_color="inverse" if is_defect else "normal")
                    m_col1.metric("Score", f"{pred_score:.2f}")
                    m_col2.metric("Severity", severity)
                    m_col3.metric("Defect Type", final_defect_type)

                    # Visualization
                    with col2:
                        st.subheader("Segmentation Heatmap")
                        
                        if isinstance(anomaly_map, torch.Tensor):
                             anomaly_map = anomaly_map.cpu().numpy()
                        
                        if anomaly_map.ndim == 3 and anomaly_map.shape[0] == 1:
                            anomaly_map = anomaly_map.squeeze(0)
                        
                        am_min, am_max = anomaly_map.min(), anomaly_map.max()
                        if am_max > am_min:
                            heatmap_norm = (anomaly_map - am_min) / (am_max - am_min)
                        else:
                            heatmap_norm = anomaly_map
                            
                        heatmap_color = cv2.applyColorMap((heatmap_norm * 255).astype(np.uint8), cv2.COLORMAP_JET)
                        heatmap_color = cv2.cvtColor(heatmap_color, cv2.COLOR_BGR2RGB)
                        
                        st.image(heatmap_color, caption="Anomaly Heatmap", use_column_width=True)

# ==========================================
# TAB 2: ANALYTICS
# ==========================================
with tab_analytics:
    st.markdown("### πŸ“Š QA Analytics Dashboard")
    
    # Filters
    period = st.selectbox("Select Time Period", ["All", "Daily", "Weekly", "Monthly"])
    
    if st.button("Refresh Data"):
        st.cache_data.clear()

    # Fetch Data
    df = db.fetch_data(period)
    
    if df.empty:
        st.info("No inspection data found for this period.")
    else:
        # Calculate Stats
        stats = analytics.calculate_stats(df)
        
        # Summary Metrics
        a_col1, a_col2, a_col3, a_col4 = st.columns(4)
        a_col1.metric("Total Inspected", stats['total'])
        a_col2.metric("Defect Rate", f"{stats['defect_rate']:.1f}%")
        a_col3.metric("Defects Found", stats['defect_count'])
        a_col4.metric("Most Frequent", stats['most_frequent_defect'])
        
        st.markdown("---")
        
        # Charts
        c_col1, c_col2 = st.columns(2)
        
        chart_dist = analytics.get_defect_distribution_chart(df)
        chart_status = analytics.get_status_distribution_chart(df)
        chart_trend = analytics.get_trend_chart(df)
        
        with c_col1:
            if chart_status: st.pyplot(chart_status)
        with c_col2:
            if chart_dist: st.pyplot(chart_dist)
            
        st.markdown("#### Defect Trends")
        if chart_trend: st.pyplot(chart_trend)
        
        st.markdown("---")
        st.subheader("πŸ“„ Generate Report")
        
        if st.button("Generate PDF Report"):
            charts = [chart_status, chart_dist, chart_trend]
            df_defects = df[df['status'] == 'Defect']
            
            report_file = report.generate_qa_report(period, stats, df_defects, charts)
            
            with open(report_file, "rb") as f:
                pdf_bytes = f.read()
                
            st.download_button(
                label="πŸ“₯ Download PDF Report",
                data=pdf_bytes,
                file_name=report_file,
                mime="application/pdf"
            )
'''

import streamlit as st
import numpy as np
from PIL import Image
import cv2
import os
import uuid

# Custom Modules
import db
import analytics
import report

# =============================
# INITIAL SETUP
# =============================
st.set_page_config(page_title="Capsule Defect Detection", layout="wide")
st.title("πŸ’Š Capsule Defect Detection System")

db.init_db()

# =============================
# SIMPLE CLOUD-SAFE ANOMALY LOGIC
# =============================
def simple_anomaly_score(image: Image.Image):
    """
    Lightweight demo anomaly logic for cloud deployment.
    (PatchCore used offline for research & training)
    """
    img = np.array(image.resize((256, 256)))
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

    score = np.std(gray)

    heatmap = cv2.GaussianBlur(gray, (21, 21), 0)
    heatmap = cv2.normalize(heatmap, None, 0, 255, cv2.NORM_MINMAX)

    heatmap_color = cv2.applyColorMap(heatmap.astype(np.uint8), cv2.COLORMAP_JET)
    heatmap_color = cv2.cvtColor(heatmap_color, cv2.COLOR_BGR2RGB)

    return score, heatmap_color

# =============================
# TABS
# =============================
tab_inference, tab_analytics = st.tabs([
    "πŸ•΅οΈ Inference & Inspection",
    "πŸ“Š Analytics & Reporting"
])

# =============================
# TAB 1: INFERENCE
# =============================
with tab_inference:
    st.subheader("Real-time Capsule Inspection")

    uploaded_file = st.file_uploader(
        "Upload Capsule Image",
        type=["jpg", "png", "jpeg"]
    )

    if uploaded_file:
        col1, col2 = st.columns(2)

        image = Image.open(uploaded_file).convert("RGB")

        with col1:
            st.image(image, caption="Uploaded Capsule", use_column_width=True)

        threshold = st.slider(
            "Anomaly Threshold",
            min_value=0.0,
            max_value=100.0,
            value=45.0,
            step=0.5
        )

        if st.button("Analyze Image"):
            with st.spinner("Analyzing capsule..."):
                score, heatmap = simple_anomaly_score(image)

                is_defect = score > threshold
                status = "Defect" if is_defect else "Good"

                if score < threshold:
                    severity = "Normal"
                elif score < 60:
                    severity = "Minor"
                elif score < 80:
                    severity = "Medium"
                else:
                    severity = "Critical"

                defect_type = "General Defect" if is_defect else "Normal (Good)"

                inspection_id = str(uuid.uuid4())[:8]
                db.log_inspection(
                    image_id=inspection_id,
                    status=status,
                    defect_type=defect_type,
                    score=score,
                    severity=severity
                )

                st.success("Inspection Complete")

                m1, m2, m3, m4 = st.columns(4)
                m1.metric("Status", status)
                m2.metric("Score", f"{score:.2f}")
                m3.metric("Severity", severity)
                m4.metric("Defect Type", defect_type)

                with col2:
                    st.subheader("Anomaly Heatmap")
                    st.image(heatmap, use_column_width=True)

                st.toast(f"Result logged (ID: {inspection_id})")

# =============================
# TAB 2: ANALYTICS
# =============================
with tab_analytics:
    st.subheader("πŸ“Š QA Analytics Dashboard")

    period = st.selectbox(
        "Select Time Period",
        ["All", "Daily", "Weekly", "Monthly"]
    )

    if st.button("Refresh Data"):
        st.cache_data.clear()

    df = db.fetch_data(period)

    if df.empty:
        st.info("No inspection data available.")
    else:
        stats = analytics.calculate_stats(df)

        a1, a2, a3, a4 = st.columns(4)
        a1.metric("Total Inspected", stats["total"])
        a2.metric("Defect Rate", f"{stats['defect_rate']:.1f}%")
        a3.metric("Defects Found", stats["defect_count"])
        a4.metric("Most Frequent Defect", stats["most_frequent_defect"])

        st.markdown("---")

        c1, c2 = st.columns(2)
        chart_status = analytics.get_status_distribution_chart(df)
        chart_dist = analytics.get_defect_distribution_chart(df)
        chart_trend = analytics.get_trend_chart(df)

        with c1:
            if chart_status:
                st.pyplot(chart_status)
        with c2:
            if chart_dist:
                st.pyplot(chart_dist)

        st.markdown("### Defect Trends")
        if chart_trend:
            st.pyplot(chart_trend)

        st.markdown("---")
        st.subheader("πŸ“„ Generate QA Report")

        if st.button("Generate PDF Report"):
            charts = [chart_status, chart_dist, chart_trend]
            df_defects = df[df["status"] == "Defect"]

            report_file = report.generate_qa_report(
                period, stats, df_defects, charts
            )

            with open(report_file, "rb") as f:
                pdf_bytes = f.read()

            st.download_button(
                "πŸ“₯ Download PDF Report",
                data=pdf_bytes,
                file_name=report_file,
                mime="application/pdf"
            )