File size: 25,658 Bytes
ecaf104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a863ff
 
 
ecaf104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b10eff
ecaf104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d93b225
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
import streamlit as st
from google.oauth2 import service_account
from google.cloud import speech
import io
import torch
import numpy as np
from transformers import Wav2Vec2Processor
from transformers.models.wav2vec2 import Wav2Vec2Model
import librosa
from groq import Groq
import sounddevice as sd
import scipy.io.wavfile as wav
import os
from datetime import datetime
from pydub import AudioSegment
from pathlib import Path
from openai import OpenAI
import json
import plotly.graph_objects as go
import os

OpenAI_api_key =os.environ.get('OpenAI_api_key')

Groq_api_key = os.environ.get('Groq_api_key')

credentials_json = os.environ.get('google_creds')

google_creds = json.loads(credentials_json)

# Enhanced UI Styles
CUSTOM_CSS = """
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

/* Base styles */
:root {
    --primary-color: #2563eb;
    --secondary-color: #1d4ed8;
    --success-color: #059669;
    --warning-color: #d97706;
    --danger-color: #dc2626;
    --text-primary: #111827;
    --text-secondary: #4b5563;
    --bg-primary: #ffffff;
    --bg-secondary: #f3f4f6;
}

.stApp {
    font-family: 'Inter', sans-serif;
    color: var(--text-primary);
    background: var(--bg-secondary);
}

/* Header styles */
.app-header {
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    padding: 2rem 1rem;
    text-align: center;
    border-radius: 0 0 1.5rem 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.app-title {
    color: white;
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.app-subtitle {
    color: rgba(255, 255, 255, 0.9);
    font-size: 1.2rem;
    font-weight: 500;
    direction: rtl;
}

/* Card styles */
.card {
    background: var(--bg-primary);
    border-radius: 1rem;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
}

.card-header {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    margin-bottom: 1rem;
    padding-bottom: 0.75rem;
    border-bottom: 1px solid var(--bg-secondary);
}

.card-title {
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

/* Button styles */
.button-container {
    display: flex;
    gap: 1rem;
    margin-bottom: 1rem;
}

.button-primary {
    background-color: var(--primary-color);
    color: white;
    padding: 0.75rem 1.5rem;
    border-radius: 0.5rem;
    border: none;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s ease;
    text-align: center;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
}

.button-primary:hover {
    background-color: var(--secondary-color);
}

.button-danger {
    background-color: var(--danger-color);
    color: white;
    padding: 0.75rem 1.5rem;
    border-radius: 0.5rem;
    border: none;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s ease;
}

/* Progress indicator */
.score-container {
    text-align: center;
    padding: 1.5rem;
    background: var(--bg-secondary);
    border-radius: 1rem;
    margin-bottom: 1.5rem;
}

.score-value {
    font-size: 3rem;
    font-weight: 700;
    color: var(--primary-color);
}

.score-label {
    color: var(--text-secondary);
    font-size: 1.1rem;
    margin-top: 0.5rem;
}

/* Feedback section */
.feedback-section {
    background: var(--bg-secondary);
    border-radius: 1rem;
    padding: 1.5rem;
    margin-top: 1.5rem;
}

.feedback-item {
    background: white;
    border-radius: 0.5rem;
    padding: 1rem;
    margin-bottom: 1rem;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* Status messages */
.success-msg {
    background-color: var(--success-color);
    color: white;
    padding: 1rem;
    border-radius: 0.5rem;
    text-align: center;
    margin-bottom: 1rem;
    animation: slideIn 0.3s ease;
}

.error-msg {
    background-color: var(--danger-color);
    color: white;
    padding: 1rem;
    border-radius: 0.5rem;
    text-align: center;
    margin-bottom: 1rem;
    animation: slideIn 0.3s ease;
}

/* Animations */
@keyframes slideIn {
    from { transform: translateY(-10px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .app-title {
        font-size: 2rem;
    }
    
    .card {
        padding: 1rem;
    }
    
    .button-container {
        flex-direction: column;
    }
    
    .score-value {
        font-size: 2.5rem;
    }
}
</style>
"""


class AzanTrainerApp:
    def __init__(self):
        self.setup_api_clients()
        self.setup_configs()
        self.setup_directories()
        self.initialize_models()

    def setup_api_clients(self):
        """Initialize API clients"""
        self.openai_client = OpenAI(api_key=OpenAI_api_key)
        self.groq_client = Groq(api_key=Groq_api_key)
        self.speech_client = self.init_google_speech()

    def init_google_speech(self):
        """Initialize Google Speech client"""
        credentials = service_account.Credentials.from_service_account_info(google_creds)
        return speech.SpeechClient(credentials=credentials)

    def setup_configs(self):
        """Set up configuration variables"""
        self.SAMPLE_RATE = 48000
        self.DURATION = 6
        self.AUDIO_GAIN = 1.50
        self.IDEAL_TEXT = "ุงู„ู„ู‘ูฐู‡ู ุฃูŽูƒู’ุจูŽุฑูุŒ ุงู„ู„ู‘ูฐู‡ู ุฃูŽูƒู’ุจูŽุฑู"
        self.IDEAL_TEXT_MEANING = "Allah is the Greatest, Allah is the Greatest"

    def setup_directories(self):
        """Create necessary directories"""
        for dir_name in ['recordings', 'feedback_audio']:
            os.makedirs(dir_name, exist_ok=True)

    def initialize_models(self):
        """Initialize ML models"""
        self.processor = Wav2Vec2Processor.from_pretrained("models/wav2vec2-base")
        self.model = Wav2Vec2Model.from_pretrained("models/wav2vec2-base")
        self.ideal_embedding = torch.tensor(np.load("ideal_embedding_part_1.npy"))

    def create_waveform_visualization(self, audio_path, reference_path):
        """Create waveform visualization using Plotly"""
        fig = go.Figure()

        # Process user audio
        y_user, sr_user = librosa.load(audio_path)
        times_user = np.arange(len(y_user)) / sr_user
        fig.add_trace(go.Scatter(
            x=times_user,
            y=y_user,
            name='Your Recording',
            line=dict(color='#1E88E5')
        ))

        # Process reference audio
        y_ref, sr_ref = librosa.load(reference_path)
        times_ref = np.arange(len(y_ref)) / sr_ref
        fig.add_trace(go.Scatter(
            x=times_ref,
            y=y_ref,
            name='Expert Recording',
            line=dict(color='#4CAF50')
        ))

        fig.update_layout(
            title='Waveform Comparison',
            xaxis_title='Time (s)',
            yaxis_title='Amplitude',
            template='plotly_white',
            height=400
        )

        return fig

    def record_audio(self):
        """Record audio from user"""
        try:
            audio_data = sd.rec(
                int(self.DURATION * self.SAMPLE_RATE),
                samplerate=self.SAMPLE_RATE,
                channels=1,
                dtype=np.float32
            )
            sd.wait()
            return self.enhance_audio(audio_data)
        except Exception as e:
            st.error(f"Recording error: {str(e)}")
            return None

    def enhance_audio(self, audio_data):
        """Enhance audio quality"""
        audio_data = audio_data / (np.max(np.abs(audio_data)) + 1e-10)
        audio_data = audio_data * self.AUDIO_GAIN
        noise_threshold = 0.01
        audio_data[np.abs(audio_data) < noise_threshold] = 0
        return audio_data

    def save_audio(self, audio_data):
        """Save audio to file"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"recordings/audio_{timestamp}.wav"
        audio_data = np.clip(audio_data * 32767, -32768, 32767).astype(np.int16)
        wav.write(filename, self.SAMPLE_RATE, audio_data)
        return filename

    def analyze_recording(self, audio_path):
        """Analyze the recording"""
        try:
            # Convert to MP3 for Google Speech API
            mp3_path = audio_path.replace('.wav', '.mp3')
            AudioSegment.from_wav(audio_path).export(mp3_path, format="mp3")

            # Transcribe audio
            with open(mp3_path, 'rb') as f:
                content = f.read()

            audio = speech.RecognitionAudio(content=content)
            config = speech.RecognitionConfig(
                encoding=speech.RecognitionConfig.AudioEncoding.MP3,
                sample_rate_hertz=self.SAMPLE_RATE,
                language_code="ar"
            )

            response = self.speech_client.recognize(config=config, audio=audio)
            transcription = " ".join(result.alternatives[0].transcript 
                                   for result in response.results)

            # Calculate similarity
            user_embedding = self.get_audio_embedding(audio_path)
            similarity_score = self.calculate_similarity(user_embedding, self.ideal_embedding)

            # Generate feedback
            feedback = self.generate_feedback(transcription, similarity_score)

            # Clean up
            os.remove(mp3_path)

            return transcription, similarity_score, feedback

        except Exception as e:
            st.error(f"Analysis error: {str(e)}")
            return None, None, None

    def get_audio_embedding(self, audio_path):
        """Generate audio embedding"""
        audio_input, _ = librosa.load(audio_path, sr=16000)
        inputs = self.processor(audio_input, sampling_rate=16000, 
                              return_tensors="pt", padding=True)
        with torch.no_grad():
            embedding = self.model(inputs.input_values).last_hidden_state.mean(dim=1).squeeze()
        return embedding

    def calculate_similarity(self, embedding1, embedding2):
        """Calculate similarity score"""
        similarity = torch.nn.functional.cosine_similarity(embedding1, embedding2, dim=0)
        return similarity.item() * 100

    def generate_feedback(self, transcription, similarity_score):
        """Generate feedback in natural Roman Urdu using LLM"""
        prompt = f"""
        Is Azan ki tilawat ka jaiza len aur natural Roman Urdu main feedback den:

        Tilawat: {transcription}
        Mutabiqat Score: {similarity_score:.2f}%

        Feedback ko in 3 hisson main takseem karen:

        1. Talaffuz (Pronunciation):
        - Har lafz ka talaffuz kaisa hai
        - Huroof ki tartib theek hai ya nahi
        - Allah ke lafz ka talaffuz kaisa hai
        - Mukammal Azan ki tarteeb kaisi hai

        2. Waqt aur Lehja (Timing):
        - Har hissay ka sahi dohrao
        - Waqfay ki durustagi
        - Aawaz ka utaar chadhao

        3. Behtar Karne Ke Liye Mashwaray:
        - Kahan ghaltiyan hain
        - Kya behtar karna hai
        - Kis cheez par zyada mehnat ki zaroorat hai

        Note: Feedback zabaan-e-urdu main likhen, lekin English huroof istimal karen. 
        Lehja mohtaram aur madadgaar hona chahiye.
        """

        response = self.groq_client.chat.completions.create(
            model="llama3-70b-8192",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.7,
            max_tokens=1000
        )

        return response.choices[0].message.content

    def generate_audio_feedback(self, feedback_text):
        """Generate audio feedback"""
        try:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            audio_path = f"feedback_audio/feedback_{timestamp}.mp3"

            response = self.openai_client.audio.speech.create(
                model="tts-1",
                voice="alloy",
                input=feedback_text
            )

            response.stream_to_file(audio_path)
            return audio_path

        except Exception as e:
            st.error(f"Error generating audio feedback: {str(e)}")
            return None

    def run(self):
        """Run the enhanced Streamlit application with Persian/Masjid-inspired UI"""
        st.set_page_config(
            page_title="Azan Pronunciation Trainer",
            layout="wide",
            initial_sidebar_state="collapsed"
        )
        
        # Custom CSS with Persian/Masjid-inspired theme (Keep your existing CSS here)
        st.markdown("""
            <style>
            /* Global Styles */
            @import url('https://fonts.googleapis.com/css2?family=Amiri:wght@400;700&display=swap');
            
            :root {
                --primary-color: #1F4C6B;
                --secondary-color: #C3934B;
                --accent-color: #E6B17E;
                --background-color: #F7F3E9;
                --text-color: #2C3E50;
                --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }

            .stApp {
                background-color: var(--background-color);
                font-family: 'Amiri', serif;
            }

            /* Header Styles */
            .app-header {
                background: linear-gradient(135deg, var(--primary-color), #2C3E50);
                color: white;
                padding: 2rem;
                border-radius: 15px;
                text-align: center;
                margin-bottom: 2rem;
                box-shadow: var(--card-shadow);
            }

            .app-title {
                font-size: 2.5rem;
                margin-bottom: 0.5rem;
                font-weight: 700;
                background: linear-gradient(45deg, var(--accent-color), #FFD700);
                -webkit-background-clip: text;
                -webkit-text-fill-color: transparent;
            }

            .app-subtitle {
                font-size: 1.2rem;
                opacity: 0.9;
                margin: 0.5rem 0;
            }

            .arabic-text {
                font-family: 'Amiri', serif;
                font-size: 2rem;
                direction: rtl;
                margin: 1rem 0;
                color: var(--secondary-color);
            }

            /* Card Styles */
            .card {
                background: white;
                border-radius: 15px;
                padding: 1.5rem;
                margin-bottom: 1.5rem;
                box-shadow: var(--card-shadow);
                border: 1px solid rgba(195, 147, 75, 0.2);
                transition: transform 0.2s ease;
            }

            .card:hover {
                transform: translateY(-2px);
            }

            .card-header {
                display: flex;
                align-items: center;
                margin-bottom: 1rem;
                border-bottom: 2px solid var(--accent-color);
                padding-bottom: 0.5rem;
            }

            .card-title {
                font-size: 1.3rem;
                margin: 0 0 0 0.5rem;
                color: var(--primary-color);
            }

            /* Button Styles */
            .stButton button {
                background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
                color: white;
                border: none;
                padding: 0.75rem 1.5rem;
                border-radius: 25px;
                font-weight: bold;
                transition: all 0.3s ease;
                width: 100%;
                margin: 0.5rem 0;
            }

            .stButton button:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(31, 76, 107, 0.2);
            }

            /* Score Display */
            .score-container {
                background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
                color: white;
                padding: 2rem;
                border-radius: 15px;
                text-align: center;
                margin: 1.5rem 0;
            }

            .score-value {
                font-size: 3rem;
                font-weight: bold;
                margin-bottom: 0.5rem;
            }

            .score-label {
                font-size: 1.2rem;
                opacity: 0.9;
            }

            /* Feedback Styles */
            .feedback-item {
                background-color: rgba(195, 147, 75, 0.1);
                padding: 1rem;
                border-radius: 10px;
                margin: 1rem 0;
                border-left: 4px solid var(--secondary-color);
            }

            /* Help Section Styling */
            .help-container {
                background: white;
                padding: 1.5rem;
                border-radius: 15px;
                margin-top: 1rem;
            }

            .help-item {
                display: flex;
                align-items: center;
                margin-bottom: 1rem;
                padding: 0.5rem;
                border-radius: 8px;
                background-color: rgba(31, 76, 107, 0.05);
            }

            .help-number {
                background-color: var(--primary-color);
                color: white;
                width: 24px;
                height: 24px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                margin-right: 1rem;
                font-size: 0.9rem;
            }
            </style>
        """, unsafe_allow_html=True)

        # Enhanced Header with Arabic Styling
        st.markdown(f"""
            <div class="app-header">
                <h1 class="app-title">Azan Pronunciation Trainer</h1>
                <p class="app-subtitle">Perfect Your Recitation</p>
                <div class="arabic-text">{self.IDEAL_TEXT}</div>
                <p class="app-subtitle">{self.IDEAL_TEXT_MEANING}</p>
            </div>
        """, unsafe_allow_html=True)

        # Expert demonstration card
        st.markdown("""
            <div class="card">
                <div class="card-header">
                    <span style="font-size: 2rem;">๐Ÿ“น</span>
                    <h2 class="card-title">Expert Demonstration</h2>
                </div>
            """, unsafe_allow_html=True)
        st.video("Sequence 03_1.mp4")
        st.markdown("</div>", unsafe_allow_html=True)

        # Expert audio card
        st.markdown("""
            <div class="card">
                <div class="card-header">
                    <span style="font-size: 2rem;">๐ŸŽต</span>
                    <h2 class="card-title">Reference Audio</h2>
                </div>
            """, unsafe_allow_html=True)
        st.audio("qari_part_1.mp3")
        st.markdown("</div>", unsafe_allow_html=True)

        # Recording controls card
        st.markdown("""
            <div class="card">
                <div class="card-header">
                    <span style="font-size: 2rem;">๐ŸŽ™๏ธ</span>
                    <h2 class="card-title">Recording Controls</h2>
                </div>
            """, unsafe_allow_html=True)
        
        col1, col2 = st.columns(2)
        
        with col1:
            if st.button("Start Recording", help="Click to start recording (6 seconds)", key="start_rec"):
                with st.spinner("Recording in progress..."):
                    audio_data = self.record_audio()
                    if audio_data is not None:
                        audio_path = self.save_audio(audio_data)
                        st.session_state['audio_file'] = audio_path
                        st.markdown("""
                            <div class="feedback-item" style="background-color: rgba(46, 204, 113, 0.1); border-left-color: #2ecc71;">
                                Recording completed successfully! โœ…
                            </div>
                        """, unsafe_allow_html=True)

        with col2:
            if st.button("Clear Recording", key="clear_rec"):
                if 'audio_file' in st.session_state:
                    if os.path.exists(st.session_state['audio_file']):
                        os.remove(st.session_state['audio_file'])
                    st.session_state['audio_file'] = None
                    st.markdown("""
                        <div class="feedback-item" style="background-color: rgba(231, 76, 60, 0.1); border-left-color: #e74c3c;">
                            Recording cleared! ๐Ÿ—‘๏ธ
                        </div>
                    """, unsafe_allow_html=True)
        
        st.markdown("</div>", unsafe_allow_html=True)

        # Analysis section
        if 'audio_file' in st.session_state and st.session_state['audio_file']:
            st.markdown("""
                <div class="card">
                    <div class="card-header">
                        <span style="font-size: 2rem;">๐ŸŽต</span>
                        <h2 class="card-title">Your Recording</h2>
                    </div>
                """, unsafe_allow_html=True)
            
            st.audio(st.session_state['audio_file'])

            if st.button("Analyze Recording", key="analyze"):
                with st.spinner("Analyzing your recitation..."):
                    transcription, similarity, feedback = self.analyze_recording(
                        st.session_state['audio_file']
                    )

                    if all([transcription, similarity, feedback]):
                        # Enhanced similarity score display
                        st.markdown(f"""
                            <div class="score-container">
                                <div class="score-value">{similarity:.1f}%</div>
                                <div class="score-label">Similarity Score</div>
                            </div>
                        """, unsafe_allow_html=True)

                        # Waveform visualization
                        fig = self.create_waveform_visualization(
                            st.session_state['audio_file'],
                            "qari_part_1.mp3"
                        )
                        st.plotly_chart(fig, use_container_width=True)

                        # Feedback display
                        st.markdown(f"""
                            <div class="card">
                                <div class="card-header">
                                    <span style="font-size: 2rem;">๐Ÿ“</span>
                                    <h2 class="card-title">Detailed Feedback</h2>
                                </div>
                                <div class="feedback-item">
                                    {feedback}
                                </div>
                            </div>
                        """, unsafe_allow_html=True)

                        # Audio feedback
                        audio_feedback_path = self.generate_audio_feedback(feedback)
                        if audio_feedback_path:
                            st.markdown("""
                                <div class="card">
                                    <div class="card-header">
                                        <span style="font-size: 2rem;">๐Ÿ”Š</span>
                                        <h2 class="card-title">Audio Feedback</h2>
                                    </div>
                                """, unsafe_allow_html=True)
                            st.audio(audio_feedback_path)
                            st.markdown("</div>", unsafe_allow_html=True)
            
            st.markdown("</div>", unsafe_allow_html=True)

        # Enhanced help section with numbered steps
        with st.expander("โ“ How to Use"):
            st.markdown("""
                <div class="help-container">
                    <div class="help-item">
                        <div class="help-number">1</div>
                        <div>Watch the expert demonstration video carefully</div>
                    </div>
                    <div class="help-item">
                        <div class="help-number">2</div>
                        <div>Listen to the reference audio to understand proper pronunciation</div>
                    </div>
                    <div class="help-item">
                        <div class="help-number">3</div>
                        <div>Click 'Start Recording' and recite the phrase (6 seconds)</div>
                    </div>
                    <div class="help-item">
                        <div class="help-number">4</div>
                        <div>Wait for the recording to complete</div>
                    </div>
                    <div class="help-item">
                        <div class="help-number">5</div>
                        <div>Click 'Analyze Recording' to get detailed feedback</div>
                    </div>
                    <div class="help-item">
                        <div class="help-number">6</div>
                        <div>Review your score and feedback to improve</div>
                    </div>
                    <div class="help-item">
                        <div class="help-number">7</div>
                        <div>Practice until you achieve 90% or higher similarity</div>
                    </div>
                </div>
            """, unsafe_allow_html=True)

if __name__ == "__main__":
    app = AzanTrainerApp()
    app.run()