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
 
 
2c73611
1c7d1c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a54f3a3
 
1c7d1c9
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
"""Gradio demo app for AnomalyMachine-50K dataset anomaly detection."""

import os
import tempfile
from pathlib import Path

import gradio as gr
# Fix Gradio 4.35/4.44 API info crash when JSON schema has boolean (e.g. additionalProperties: true)
import gradio_client.utils as _client_utils
_orig_get_type = _client_utils.get_type
def _get_type_handle_bool(schema):
    if isinstance(schema, bool):
        return "boolean"
    return _orig_get_type(schema)
_client_utils.get_type = _get_type_handle_bool

import librosa
import matplotlib
matplotlib.use("Agg")  # Non-interactive backend
import matplotlib.pyplot as plt
import numpy as np

# Dataset metadata
DATASET_INFO = {
    "total_clips": 50000,
    "machines": ["fan", "pump", "compressor", "conveyor_belt", "electric_motor", "valve"],
    "normal_ratio": 0.6,
    "anomalous_ratio": 0.4,
    "clip_duration_seconds": 10.0,
    "sample_rate": 22050,
    "total_hours": round(50000 * 10.0 / 3600, 2),
}

# Anomaly subtypes mapping
ANOMALY_SUBTYPES = {
    "fan": ["bearing_fault", "imbalance", "obstruction"],
    "pump": ["bearing_fault", "cavitation", "overheating"],
    "compressor": ["bearing_fault", "imbalance", "overheating"],
    "conveyor_belt": ["obstruction"],
    "electric_motor": ["bearing_fault", "imbalance", "overheating"],
    "valve": ["cavitation", "obstruction"],
}

# Placeholder model - replace with actual trained model
MODEL_NAME = "YOUR_HF_USERNAME/AnomalyMachine-Classifier"
model = None


def load_model():
    """Lazy load the audio classification model. Uses placeholder if transformers unavailable."""
    global model
    if model is None:
        try:
            from transformers import pipeline
            model = pipeline(
                "audio-classification",
                model=MODEL_NAME,
            )
        except Exception as e:
            print(f"Using placeholder predictions (no model): {e}")
            model = "placeholder"
    return model


def create_mel_spectrogram(audio_path: str, title: str = "Mel Spectrogram") -> str:
    """Create a mel spectrogram visualization from audio file."""
    try:
        y, sr = librosa.load(audio_path, sr=22050, mono=True)
        mel_spec = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=128, fmax=8000)
        mel_spec_db = librosa.power_to_db(mel_spec, ref=np.max)

        fig, ax = plt.subplots(figsize=(10, 4))
        img = librosa.display.specshow(
            mel_spec_db,
            x_axis="time",
            y_axis="mel",
            sr=sr,
            fmax=8000,
            ax=ax,
            cmap="viridis",
        )
        ax.set_title(title, fontsize=14, fontweight="bold")
        plt.colorbar(img, ax=ax, format="%+2.0f dB")
        plt.tight_layout()

        # Save to temporary file
        temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
        plt.savefig(temp_file.name, dpi=100, bbox_inches="tight")
        plt.close()
        return temp_file.name
    except Exception as e:
        print(f"Error creating spectrogram: {e}")
        return None


def get_reference_audio(machine_type: str) -> str:
    """Get path to reference normal audio for a machine type."""
    examples_dir = Path(__file__).parent / "examples"
    # Look for a normal example (naming convention: {machine}_normal_*.wav)
    ref_pattern = f"{machine_type}_*_normal_*.wav"
    ref_files = list(examples_dir.glob(ref_pattern))
    if not ref_files:
        # Fallback: use any example for this machine
        ref_files = list(examples_dir.glob(f"{machine_type}_*.wav"))
    return str(ref_files[0]) if ref_files else None


def predict_anomaly(audio_file, machine_type):
    """Predict if audio contains an anomaly."""
    if audio_file is None:
        return None, None, None, None, None

    # Load model
    model_instance = load_model()

    # Create spectrograms
    input_spec = create_mel_spectrogram(audio_file, f"Input Audio - {machine_type}")
    ref_audio = get_reference_audio(machine_type)
    ref_spec = None
    if ref_audio:
        ref_spec = create_mel_spectrogram(ref_audio, f"Reference Normal - {machine_type}")

    # Make prediction
    if model_instance == "placeholder":
        # Placeholder predictions for demo
        import random
        is_anomaly = random.random() > 0.5
        confidence = random.uniform(0.7, 0.95)
        if is_anomaly:
            anomaly_subtype = random.choice(ANOMALY_SUBTYPES.get(machine_type, ["unknown"]))
            label = "ANOMALY"
            color = "red"
        else:
            anomaly_subtype = "none"
            label = "NORMAL"
            color = "green"
    else:
        # Real model prediction
        try:
            results = model_instance(audio_file)
            # Assuming model returns list of dicts with 'label' and 'score'
            top_result = results[0] if isinstance(results, list) else results
            label_str = top_result.get("label", "").lower()
            confidence = top_result.get("score", 0.5)

            is_anomaly = "anomaly" in label_str or "anomalous" in label_str
            if is_anomaly:
                label = "ANOMALY"
                color = "red"
                # Try to extract anomaly subtype from label
                anomaly_subtype = "unknown"
                for subtype in ANOMALY_SUBTYPES.get(machine_type, []):
                    if subtype in label_str:
                        anomaly_subtype = subtype
                        break
            else:
                label = "NORMAL"
                color = "green"
                anomaly_subtype = "none"
        except Exception as e:
            print(f"Prediction error: {e}")
            label = "ERROR"
            color = "gray"
            confidence = 0.0
            anomaly_subtype = "none"

    # Format result HTML
    result_html = f"""

    <div style="text-align: center; padding: 20px;">

        <h2 style="color: {color}; font-size: 48px; margin: 20px 0;">

            {label} {'✓' if label == 'NORMAL' else '✗'}

        </h2>

        {f'<p style="font-size: 18px; color: #888;">Anomaly Type: <strong>{anomaly_subtype.replace("_", " ").title()}</strong></p>' if anomaly_subtype != 'none' else ''}

        <p style="font-size: 16px; color: #aaa;">Confidence: {confidence:.1%}</p>

    </div>

    """

    return result_html, confidence, input_spec, ref_spec, audio_file


def create_dataset_gallery():
    """Create gallery of example spectrograms for each machine type."""
    examples_dir = Path(__file__).parent / "examples"
    if not examples_dir.exists():
        return []

    gallery_items = []
    for machine in DATASET_INFO["machines"]:
        # Find normal and anomalous examples
        normal_files = list(examples_dir.glob(f"{machine}_*_normal_*.wav"))
        anomaly_files = list(examples_dir.glob(f"{machine}_*_anomalous_*.wav"))

        normal_spec = None
        anomaly_spec = None

        if normal_files:
            normal_spec = create_mel_spectrogram(str(normal_files[0]), f"{machine} - Normal")
        if anomaly_files:
            anomaly_spec = create_mel_spectrogram(str(anomaly_files[0]), f"{machine} - Anomaly")

        if normal_spec or anomaly_spec:
            gallery_items.append((normal_spec, anomaly_spec, machine))

    return gallery_items


def build_explore_tab():
    """Build the dataset exploration tab."""
    gallery_items = create_dataset_gallery()

    # Populate galleries
    normal_images = [item[0] for item in gallery_items if item[0] and item[0] is not None]
    anomaly_images = [item[1] for item in gallery_items if item[1] and item[1] is not None]

    with gr.Row():
        with gr.Column():
            gr.Markdown("### Normal Examples")
            normal_gallery = gr.Gallery(
                label="Normal Machine Sounds",
                show_label=False,
                elem_id="normal_gallery",
                columns=2,
                rows=3,
                height="auto",
                value=normal_images if normal_images else None,
            )
        with gr.Column():
            gr.Markdown("### Anomaly Examples")
            anomaly_gallery = gr.Gallery(
                label="Anomalous Machine Sounds",
                show_label=False,
                elem_id="anomaly_gallery",
                columns=2,
                rows=3,
                height="auto",
                value=anomaly_images if anomaly_images else None,
            )

    # Dataset statistics
    with gr.Accordion("Dataset Statistics", open=False):
        stats_html = f"""

        <div style="padding: 20px;">

            <h3>AnomalyMachine-50K Dataset</h3>

            <ul style="font-size: 16px; line-height: 2;">

                <li><strong>Total Clips:</strong> {DATASET_INFO['total_clips']:,}</li>

                <li><strong>Total Duration:</strong> {DATASET_INFO['total_hours']} hours</li>

                <li><strong>Machine Types:</strong> {len(DATASET_INFO['machines'])}</li>

                <li><strong>Normal Ratio:</strong> {DATASET_INFO['normal_ratio']:.0%}</li>

                <li><strong>Anomalous Ratio:</strong> {DATASET_INFO['anomalous_ratio']:.0%}</li>

                <li><strong>Sample Rate:</strong> {DATASET_INFO['sample_rate']} Hz</li>

                <li><strong>Clip Duration:</strong> {DATASET_INFO['clip_duration_seconds']} seconds</li>

            </ul>

            <h4>Machine Breakdown:</h4>

            <ul>

                {''.join([f'<li>{m.replace("_", " ").title()}</li>' for m in DATASET_INFO['machines']])}

            </ul>

        </div>

        """
        gr.HTML(stats_html)

    # Download button
    dataset_url = "https://huggingface.co/datasets/mandipgoswami/AnomalyMachine-50K"
    gr.Markdown(f"""

    <div style="text-align: center; padding: 20px;">

        <a href="{dataset_url}" target="_blank">

            <button style="background-color: #007bff; color: white; padding: 15px 30px; 

                          font-size: 18px; border: none; border-radius: 5px; cursor: pointer;">

                📥 Download Dataset

            </button>

        </a>

    </div>

    """)

    return normal_gallery, anomaly_gallery, normal_images, anomaly_images


def build_detect_tab():
    """Build the anomaly detection tab."""
    with gr.Row():
        with gr.Column(scale=1):
            audio_input = gr.Audio(
                label="Upload Audio or Record",
                type="filepath",
                sources=["upload", "microphone"],
            )
            machine_dropdown = gr.Dropdown(
                choices=DATASET_INFO["machines"],
                label="Machine Type",
                value=DATASET_INFO["machines"][0],
                info="Select the type of machine in the audio",
            )
            predict_btn = gr.Button("Detect Anomaly", variant="primary", size="lg")

        with gr.Column(scale=2):
            result_html = gr.HTML(label="Prediction Result")
            confidence_bar = gr.Slider(
                minimum=0,
                maximum=1,
                value=0,
                label="Confidence Score",
                interactive=False,
            )

    with gr.Row():
        with gr.Column():
            input_spec = gr.Image(label="Input Audio Spectrogram")
        with gr.Column():
            ref_spec = gr.Image(label="Reference Normal Spectrogram")

    audio_output = gr.Audio(label="Processed Audio", visible=False)

    predict_btn.click(
        fn=predict_anomaly,
        inputs=[audio_input, machine_dropdown],
        outputs=[result_html, confidence_bar, input_spec, ref_spec, audio_output],
    )

    return (
        audio_input,
        machine_dropdown,
        predict_btn,
        result_html,
        confidence_bar,
        input_spec,
        ref_spec,
        audio_output,
    )


def build_header():
    """Build the app header."""
    return gr.Markdown(
        """

    <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 

                border-radius: 10px; margin-bottom: 20px;">

        <h1 style="color: white; margin: 0;">🏭 AnomalyMachine-50K</h1>

        <p style="color: rgba(255,255,255,0.9); font-size: 18px; margin: 10px 0;">

            Synthetic Industrial Machine Sound Anomaly Detection Dataset

        </p>

        <p style="color: rgba(255,255,255,0.8);">

            <a href="https://huggingface.co/datasets/mandipgoswami/AnomalyMachine-50K" 

               style="color: white; text-decoration: underline;" target="_blank">

                View Dataset on Hugging Face →

            </a>

        </p>

    </div>

    """
    )


def build_footer():
    """Build the app footer."""
    return gr.Markdown(
        """

    <div style="text-align: center; padding: 20px; margin-top: 40px; border-top: 1px solid #333;">

        <p style="color: #888; font-size: 14px;">

            License: <a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" 

                        style="color: #4a9eff;">CC-BY 4.0</a> | 

            Dataset: <a href="https://huggingface.co/datasets/mandipgoswami/AnomalyMachine-50K" target="_blank" 

                        style="color: #4a9eff;">AnomalyMachine-50K</a> |

            GitHub: <a href="https://github.com/mandip42/anomaly-machine-50k" target="_blank" 

                       style="color: #4a9eff;">mandip42/anomaly-machine-50k</a>

        </p>

    </div>

    """
    )


def build_how_it_works():
    """Build the 'How it works' accordion."""
    how_it_works_html = """

    <div style="padding: 20px; line-height: 1.8;">

        <h3>Signal Processing-Based Synthesis</h3>

        <p>

            The AnomalyMachine-50K dataset is generated entirely using deterministic signal processing 

            techniques—no neural audio models are used. This ensures reproducibility, lightweight generation, 

            and freedom from copyright concerns.

        </p>

        

        <h4>1. Base Machine Sound Generation</h4>

        <p>

            Each machine type has a dedicated synthesis model:

        </p>

        <ul>

            <li><strong>Fan:</strong> Broadband noise + rotating blade harmonics (50-200 Hz)</li>

            <li><strong>Pump:</strong> Low-frequency rumble (20-80 Hz) + rhythmic pressure pulses</li>

            <li><strong>Compressor:</strong> 60 Hz motor hum + harmonics with cyclic compression envelope</li>

            <li><strong>Conveyor Belt:</strong> Rhythmic tapping + friction noise</li>

            <li><strong>Electric Motor:</strong> Tonal fundamental (1200-3600 RPM) + harmonics + brush noise</li>

            <li><strong>Valve:</strong> Turbulent flow noise + actuation clicks</li>

        </ul>

        

        <h4>2. Operating Condition Modulation</h4>

        <p>

            Conditions (idle, normal_load, high_load) modulate amplitude and harmonic content.

        </p>

        

        <h4>3. Anomaly Injection</h4>

        <p>

            Anomalies are injected via signal transformations:

        </p>

        <ul>

            <li><strong>Bearing Fault:</strong> Periodic impulsive spikes</li>

            <li><strong>Imbalance:</strong> Sinusoidal amplitude modulation</li>

            <li><strong>Cavitation:</strong> Burst noise events</li>

            <li><strong>Overheating:</strong> Gradually increasing high-frequency noise</li>

            <li><strong>Obstruction:</strong> Intermittent amplitude drops + resonance shifts</li>

        </ul>

        

        <h4>4. Background Noise</h4>

        <p>

            Factory-floor ambience (pink noise + 60/120 Hz hum) is mixed at configurable SNR levels.

        </p>

        

        <p style="margin-top: 20px; font-style: italic;">

            All synthesis is deterministic and reproducible with a fixed random seed.

        </p>

    </div>

    """
    return gr.Accordion("How It Works", open=False).update(
        value=gr.HTML(how_it_works_html)
    )


def main():
    """Main Gradio app entry point."""
    theme = gr.themes.Monochrome(
        primary_hue="red",
        secondary_hue="gray",
        font=("Helvetica", "ui-sans-serif", "system-ui"),
    )

    with gr.Blocks(theme=theme, title="AnomalyMachine-50K Demo") as app:
        build_header()

        with gr.Tabs():
            with gr.Tab("🔍 Detect Anomaly"):
                with gr.Accordion("How It Works", open=False):
                    gr.HTML("""

                    <div style="padding: 20px; line-height: 1.8;">

                        <h3>Signal Processing-Based Synthesis</h3>

                        <p>

                            The AnomalyMachine-50K dataset is generated entirely using deterministic signal processing 

                            techniques—no neural audio models are used. This ensures reproducibility, lightweight generation, 

                            and freedom from copyright concerns.

                        </p>

                        

                        <h4>1. Base Machine Sound Generation</h4>

                        <p>

                            Each machine type has a dedicated synthesis model:

                        </p>

                        <ul>

                            <li><strong>Fan:</strong> Broadband noise + rotating blade harmonics (50-200 Hz)</li>

                            <li><strong>Pump:</strong> Low-frequency rumble (20-80 Hz) + rhythmic pressure pulses</li>

                            <li><strong>Compressor:</strong> 60 Hz motor hum + harmonics with cyclic compression envelope</li>

                            <li><strong>Conveyor Belt:</strong> Rhythmic tapping + friction noise</li>

                            <li><strong>Electric Motor:</strong> Tonal fundamental (1200-3600 RPM) + harmonics + brush noise</li>

                            <li><strong>Valve:</strong> Turbulent flow noise + actuation clicks</li>

                        </ul>

                        

                        <h4>2. Operating Condition Modulation</h4>

                        <p>

                            Conditions (idle, normal_load, high_load) modulate amplitude and harmonic content.

                        </p>

                        

                        <h4>3. Anomaly Injection</h4>

                        <p>

                            Anomalies are injected via signal transformations:

                        </p>

                        <ul>

                            <li><strong>Bearing Fault:</strong> Periodic impulsive spikes</li>

                            <li><strong>Imbalance:</strong> Sinusoidal amplitude modulation</li>

                            <li><strong>Cavitation:</strong> Burst noise events</li>

                            <li><strong>Overheating:</strong> Gradually increasing high-frequency noise</li>

                            <li><strong>Obstruction:</strong> Intermittent amplitude drops + resonance shifts</li>

                        </ul>

                        

                        <h4>4. Background Noise</h4>

                        <p>

                            Factory-floor ambience (pink noise + 60/120 Hz hum) is mixed at configurable SNR levels.

                        </p>

                        

                        <p style="margin-top: 20px; font-style: italic;">

                            All synthesis is deterministic and reproducible with a fixed random seed.

                        </p>

                    </div>

                    """)
                build_detect_tab()

            with gr.Tab("📊 Explore Dataset"):
                normal_gallery, anomaly_gallery, normal_images, anomaly_images = build_explore_tab()

        build_footer()

    app.launch(share=False, server_name="0.0.0.0", server_port=7860)


if __name__ == "__main__":
    main()