File size: 28,413 Bytes
d64cd8c
 
 
 
47cda52
d64cd8c
 
 
 
6c4755b
ad60e6c
d64cd8c
 
d5decbb
d64cd8c
 
6c4755b
d64cd8c
0ecae4e
d64cd8c
9cdcbb7
0ecae4e
d64cd8c
9cdcbb7
0ecae4e
9cdcbb7
 
0ecae4e
9cdcbb7
d64cd8c
 
 
 
7f2af85
dfb3fcb
 
6c4755b
 
 
 
 
dfb3fcb
7f2af85
6c4755b
 
 
 
 
dfb3fcb
7f2af85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3fcb
7f2af85
 
 
 
 
 
dfb3fcb
7f2af85
 
 
 
 
 
 
 
6c4755b
 
 
dfb3fcb
 
7f2af85
 
 
 
 
dfb3fcb
 
96a8fca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c839c1
06e108c
8c839c1
 
 
 
 
 
 
 
 
 
 
06e108c
8c839c1
06e108c
 
8c839c1
06e108c
 
8c839c1
 
06e108c
 
8c839c1
8b2bd94
 
 
 
 
 
8c839c1
06e108c
3f35e3c
8c839c1
06e108c
8c839c1
 
06e108c
ddaedae
06e108c
ddaedae
06e108c
ddaedae
06e108c
 
ddaedae
 
06e108c
 
ddaedae
06e108c
 
ddaedae
06e108c
 
 
 
 
47cda52
 
06e108c
 
 
 
 
 
 
 
ddaedae
06e108c
ddaedae
 
06e108c
ddaedae
06e108c
ddaedae
06e108c
ddaedae
06e108c
 
ddaedae
06e108c
 
47cda52
06e108c
 
3f35e3c
06e108c
47cda52
06e108c
 
 
8c839c1
1cc3bcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d64cd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfb3fcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05e012d
96a8fca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1adf337
96a8fca
 
 
 
 
 
 
1adf337
96a8fca
 
1adf337
96a8fca
9cdcbb7
 
d64cd8c
 
 
 
9cdcbb7
6f2d3bb
 
 
 
d64cd8c
6f2d3bb
d64cd8c
 
dfb3fcb
ff86f87
dfb3fcb
 
 
 
ff86f87
6f2d3bb
 
 
 
dfb3fcb
ff86f87
 
dfb3fcb
d64cd8c
 
 
dfb3fcb
 
 
 
 
 
 
 
 
 
 
d64cd8c
06e108c
 
8c839c1
 
 
 
06e108c
 
8c839c1
d64cd8c
06e108c
 
 
d64cd8c
1cc3bcb
 
 
 
8dac9df
ff86f87
 
8dac9df
 
1cc3bcb
 
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
 
 
 
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
 
6c4755b
1cc3bcb
 
9ad6024
1cc3bcb
 
 
 
 
 
 
 
9ad6024
1cc3bcb
 
 
d5decbb
1cc3bcb
 
 
 
9ad6024
1cc3bcb
 
 
 
 
 
 
9ad6024
1cc3bcb
 
 
 
 
 
 
9ad6024
1cc3bcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b83ce1
 
 
0ecae4e
 
9ad6024
8c839c1
d64cd8c
 
 
f0c1948
d64cd8c
 
18336fd
f0c1948
d64cd8c
858d077
d64cd8c
 
f0c1948
d64cd8c
 
 
 
 
dfb3fcb
 
bd81378
 
 
d0ad062
bd81378
3634d7e
bd81378
cb59396
bd81378
f0c1948
0e058c1
9407829
4daa244
8c839c1
bd81378
8dac9df
dfb3fcb
d64cd8c
 
24dc47e
 
06e108c
dfb3fcb
 
d64cd8c
1dc80ce
 
d64cd8c
dfb3fcb
 
 
 
 
ff86f87
96a8fca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12520c3
1adf337
96a8fca
06e108c
 
8c839c1
06e108c
 
 
4daa244
06e108c
 
 
 
 
 
 
 
 
 
8c839c1
06e108c
 
8c839c1
 
 
06e108c
 
 
 
 
 
8c839c1
06e108c
ff86f87
 
 
 
 
 
 
 
 
d64cd8c
 
 
 
 
 
 
 
dfb3fcb
 
 
 
 
 
d64cd8c
9cdcbb7
d64cd8c
dfb3fcb
 
 
06e108c
 
8c839c1
06e108c
d64cd8c
 
 
 
 
dfb3fcb
 
 
 
 
 
 
d64cd8c
8c839c1
 
06e108c
8c839c1
06e108c
 
96a8fca
 
 
 
 
1adf337
96a8fca
06e108c
 
 
 
 
 
8c839c1
 
06e108c
 
 
 
8c839c1
9cdcbb7
d64cd8c
 
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
import gradio as gr
from gtts import gTTS
import tempfile
import os
from deep_translator import GoogleTranslator

# Enhanced transliteration map with proper Arabic characters
translit_map = {
    # Two-character combinations (must be checked first)
    "TH": "ุซ", "KH": "ุฎ", "DH": "ุฐ", "SH": "ุด", "GH": "ุบ",
    "AA": "ุข", "EE": "ูŠ", "OO": "ูˆ", "UU": "ูˆ", "II": "ูŠ",
    
    # Single characters
    "a": "ุง", "b": "ุจ", "c": "ูƒ", "t": "ุช", "j": "ุฌ", "H": "ุญ", 
    "d": "ุฏ", "r": "ุฑ", "z": "ุฒ", "s": "ุณ",
    "S": "ุต", "D": "ุถ", "T": "ุท", "Z": "ุธ", 
    "'": "ุน", "f": "ู", "q": "ู‚", "k": "ูƒ", 
    "l": "ู„", "m": "ู…", "n": "ู†", "h": "ู‡",
    "w": "ูˆ", "y": "ูŠ", "x": "ุก", 
    
    # Initial vowels (hamza with vowel for word beginnings)
    "i": "ุฅู", "u": "ุฃู", "e": "ุฃ", "o": "ุฃู",
    
    # Short vowels (diacritics)
    "I": "ู", "U": "ู","O": "ู", "A": "ูŽ", "~": "ู‘", "^": "ู’",
    
    # Tanween (double diacritics)
    "AN": "ู‹", "UN": "ูŒ","ON": "ูŒ", "IN": "ู",
    
    # Space and punctuation
    " ": " ", ".": ".", ",": "ุŒ", "?": "ุŸ", "!": "!"
}

# Proper Arabic romanization to IPA mapping
latin_to_ipa = {
    # Two-character combinations (must be checked first)
    "TH": "ฮธ",    # ุซ - voiceless dental fricative
    "KH": "x",    # ุฎ - voiceless velar fricative  
    "DH": "รฐ",    # ุฐ - voiced dental fricative
    "SH": "สƒ",    # ุด - voiceless postalveolar fricative
    "GH": "ษฃ",    # ุบ - voiced velar fricative
    
    # Long vowels
    "AA": "aห",   # ุข - long a
    "EE": "iห",   # long i
    "OO": "uห",   # long u
    "UU": "uห",   # long u (alternative)
    "II": "iห",   # long i (alternative)
    
    # Consonants
    "b": "b",     # ุจ
    "t": "t",     # ุช
    "j": "dส’",    # ุฌ
    "H": "ฤง",     # ุญ - voiceless pharyngeal fricative
    "d": "d",     # ุฏ
    "r": "r",     # ุฑ - trill
    "z": "z",     # ุฒ
    "s": "s",     # ุณ
    "S": "sหค",    # ุต - emphatic s
    "D": "dหค",    # ุถ - emphatic d
    "T": "tหค",    # ุท - emphatic t
    "Z": "รฐหค",    # ุธ - emphatic dh
    "'": "ส•",     # ุน - voiced pharyngeal fricative
    "f": "f",     # ู
    "q": "q",     # ู‚ - uvular stop
    "k": "k",     # ูƒ
    "l": "l",     # ู„
    "m": "m",     # ู…
    "n": "n",     # ู†
    "h": "h",     # ู‡
    "w": "w",     # ูˆ
    "y": "j",     # ูŠ
    "x": "ส”",     # ุก - glottal stop
    
    # Short vowels (context-dependent)
    "a": "a",     # ูุชุญุฉ
    "i": "i",     # ูƒุณุฑุฉ  
    "u": "u",     # ุถู…ุฉ
    "e": "a",     # often represents fatha
    "o": "u",     # often represents damma
    
    # Diacritics when explicitly marked
    "A": "a",     # explicit fatha
    "I": "i",     # explicit kasra
    "U": "u",     # explicit damma
    "~": "ห",     # shadda (gemination)
    "^": "",      # sukun (no vowel)
    
    # Tanween
    "AN": "an",   # ูุชุญุชุงู†
    "UN": "un",   # ุถู…ุชุงู†
    "IN": "in",   # ูƒุณุฑุชุงู†
    
    # Space and punctuation
    " ": " ", 
    ".": ".", 
    ",": ",", 
    "?": "?", 
    "!": "!"
}

# Buckwalter transliteration mappings
arabic_to_buckwalter = {
    # Basic letters
    'ุง': 'A', 'ุจ': 'b', 'ุช': 't', 'ุซ': 'v', 'ุฌ': 'j', 'ุญ': 'H', 'ุฎ': 'x',
    'ุฏ': 'd', 'ุฐ': '*', 'ุฑ': 'r', 'ุฒ': 'z', 'ุณ': 's', 'ุด': '$', 'ุต': 'S',
    'ุถ': 'D', 'ุท': 'T', 'ุธ': 'Z', 'ุน': 'E', 'ุบ': 'g', 'ู': 'f', 'ู‚': 'q',
    'ูƒ': 'k', 'ู„': 'l', 'ู…': 'm', 'ู†': 'n', 'ู‡': 'h', 'ูˆ': 'w', 'ูŠ': 'y',
    
    # Hamza variants
    'ุก': "'", 'ุฃ': '>', 'ุฅ': '<', 'ุข': '|', 'ุค': '&', 'ุฆ': '}',
    
    # Taa marbuta
    'ุฉ': 'p',
    
    # Alif maqsura
    'ู‰': 'Y',
    
    # Diacritics
    'ูŽ': 'a', 'ู': 'u', 'ู': 'i', 'ู‹': 'F', 'ูŒ': 'N', 'ู': 'K',
    'ู‘': '~', 'ู’': 'o',
    
    # Punctuation
    'ุŒ': ',', 'ุ›': ';', 'ุŸ': '?', 'ยซ': '"', 'ยป': '"',
    
    # Spaces and numbers
    ' ': ' ', 'ู ': '0', 'ูก': '1', 'ูข': '2', 'ูฃ': '3', 'ูค': '4',
    'ูฅ': '5', 'ูฆ': '6', 'ูง': '7', 'ูจ': '8', 'ูฉ': '9'
}

# Reverse mapping for Buckwalter to Arabic
buckwalter_to_arabic = {v: k for k, v in arabic_to_buckwalter.items()}

def clean_arabic_text(text):
    """Remove diacritics from Arabic text for translation"""
    if not text:
        return ""
    
    # Remove common Arabic diacritics
    diacritics = "ู‹ูŒููŽููู‘ู’"
    cleaned = text
    for diacritic in diacritics:
        cleaned = cleaned.replace(diacritic, "")
    
    return cleaned.strip()

def google_translate_arabic(arabic_text):
    """
    Translate Arabic text to English using Google Translate
    Returns translation and detected language info
    """
    if not arabic_text or not arabic_text.strip():
        return "No text provided for translation."
    
    try:
        # Clean the text
        clean_text = clean_arabic_text(arabic_text)
        
        try:
            translation_text = GoogleTranslator(source='ar', target='en').translate(clean_text)
            detection_lang = GoogleTranslator(source='auto', target='en').detect(clean_text)
        except:
            detection_lang = 'ar'
            translation_text = GoogleTranslator(source='ar', target='en').translate(clean_text)
        
        # Format the result
        result = translation_text
        
        return result
        
    except Exception as e:
        return f"โŒ Google Translate error: {str(e)}\n\nPlease check your internet connection and try again."

def translate_multiple_words(arabic_text):
    """
    Translate multiple Arabic words - both individually and as a whole phrase
    """
    if not arabic_text or not arabic_text.strip():
        return "No text provided for translation."
    
    try:
        # First translate the whole phrase
        full_translation = google_translate_arabic(arabic_text)
        
        # Then translate individual words if there are multiple words
        words = arabic_text.strip().split()
        
        if len(words) > 1:
            individual_translations = []
            for i, word in enumerate(words[:5], 1):  # Limit to first 5 words
                if len(word.strip()) > 1:  # Skip single characters
                    try:
                        word_translation = GoogleTranslator(source='ar', target='en').translate(clean_arabic_text(word))
                        individual_translations.append(f"**{i}. {word}** โ†’ {word_translation}")
                    except:
                        individual_translations.append(f"**{i}. {word}** โ†’ (translation failed)")
            
            if individual_translations:
                result = full_translation + "\n\n" + "โ”€"*50 + "\n\n"
                result += "๐Ÿ“ **Individual Word Translations:**\n\n"
                result += "\n".join(individual_translations)
                return result
        
        return full_translation
        
    except Exception as e:
        return f"โŒ Translation error: {str(e)}"

def reverse_translate_english(english_text):
    """
    Translate English text to Arabic using Google Translate
    """
    if not english_text or not english_text.strip():
        return "No text provided for translation."
    
    try:
        # Translate to Arabic
        translation_text = GoogleTranslator(source='en', target='ar').translate(english_text)
        
        # Format the result
        result = translation_text
        
        return result, translation_text
        
    except Exception as e:
        return f"โŒ Translation error: {str(e)}", ""

def generate_letter_audio(arabic_letter):
    """Generate TTS audio for a single Arabic letter or character."""
    if not arabic_letter or not arabic_letter.strip():
        return None
    
    try:
        tts = gTTS(text=arabic_letter, lang='ar', slow=True)
        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
            temp_path = tmp_file.name
        tts.save(temp_path)
        return temp_path
    except Exception as e:
        print(f"Letter TTS Error: {e}")
        return None

def transliterate(text):
    """Convert Latin text to Arabic script using transliteration mapping."""
    if not text:
        return ""
    
    output = ""
    i = 0
    
    while i < len(text):
        # Check for two-character combinations first
        if i + 1 < len(text) and text[i:i+2] in translit_map:
            output += translit_map[text[i:i+2]]
            i += 2
        # Then check for single characters
        elif text[i] in translit_map:
            output += translit_map[text[i]]
            i += 1
        else:
            # Keep unknown characters as-is
            output += text[i]
            i += 1
    
    return output

def latin_to_ipa_conversion(latin_text):
    """Convert Latin text directly to IPA phonetic transcription."""
    if not latin_text:
        return ""
    
    output = ""
    i = 0
    
    while i < len(latin_text):
        # Check for two-character combinations first
        if i + 1 < len(latin_text) and latin_text[i:i+2] in latin_to_ipa:
            output += latin_to_ipa[latin_text[i:i+2]]
            i += 2
        # Then check for single characters
        elif latin_text[i] in latin_to_ipa:
            output += latin_to_ipa[latin_text[i]]
            i += 1
        else:
            # Keep unknown characters as-is
            output += latin_text[i]
            i += 1
    
    return output

def arabic_to_buckwalter_convert(arabic_text):
    """Convert Arabic text to Buckwalter transliteration."""
    if not arabic_text:
        return ""
    
    result = ""
    for char in arabic_text:
        if char in arabic_to_buckwalter:
            result += arabic_to_buckwalter[char]
        else:
            result += char  # Keep unknown characters as-is
    
    return result

def buckwalter_to_arabic_convert(buckwalter_text):
    """Convert Buckwalter transliteration to Arabic text."""
    if not buckwalter_text:
        return ""
    
    result = ""
    for char in buckwalter_text:
        if char in buckwalter_to_arabic:
            result += buckwalter_to_arabic[char]
        else:
            result += char  # Keep unknown characters as-is
    
    return result

def bidirectional_buckwalter_convert(input_text):
    """Automatically detect and convert between Arabic and Buckwalter."""
    if not input_text.strip():
        return ""
    
    # Simple detection: if text contains Arabic characters, convert to Buckwalter
    # Otherwise, assume it's Buckwalter and convert to Arabic
    has_arabic = any('\u0600' <= char <= '\u06FF' for char in input_text)
    
    if has_arabic:
        # Arabic to Buckwalter
        return arabic_to_buckwalter_convert(input_text)
    else:
        # Buckwalter to Arabic
        return buckwalter_to_arabic_convert(input_text)

def arabic_tts(arabic_text):
    """Generate TTS audio for Arabic text."""
    if not arabic_text or not arabic_text.strip():
        return None
    
    try:
        tts = gTTS(text=arabic_text, lang='ar', slow=False)
        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
            temp_path = tmp_file.name
        tts.save(temp_path)
        return temp_path
    except Exception as e:
        print(f"Arabic TTS Error: {e}")
        return None

def ipa_tts(ipa_text):
    """Generate TTS audio for IPA text using English TTS."""
    if not ipa_text or not ipa_text.strip():
        return None
    
    try:
        tts = gTTS(text=ipa_text, lang='en', slow=True)
        with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
            temp_path = tmp_file.name
        tts.save(temp_path)
        return temp_path
    except Exception as e:
        print(f"IPA TTS Error: {e}")
        return None

def transliterate_and_speak(latin_text):
    """Combined function to transliterate and generate audio."""
    arabic_text = transliterate(latin_text)
    ipa_text = latin_to_ipa_conversion(latin_text)
    arabic_audio = arabic_tts(arabic_text)
    return arabic_text, ipa_text, arabic_audio

def full_process_with_ipa_audio(latin_text):
    """Process text and generate both Arabic and IPA audio."""
    arabic_text = transliterate(latin_text)
    ipa_text = latin_to_ipa_conversion(latin_text)
    arabic_audio = arabic_tts(arabic_text)
    ipa_audio = ipa_tts(ipa_text)
    return arabic_text, ipa_text, arabic_audio, ipa_audio

def full_process_with_translation(latin_text):
    """Complete processing: transliterate, generate audio, and translate with Google."""
    arabic_text = transliterate(latin_text)
    ipa_text = latin_to_ipa_conversion(latin_text)
    arabic_audio = arabic_tts(arabic_text)
    ipa_audio = ipa_tts(ipa_text)
    translation_result = translate_multiple_words(arabic_text)
    return arabic_text, ipa_text, arabic_audio, ipa_audio, translation_result

# Create Gradio interface
with gr.Blocks(title="Arabic Transliterator with Google Translate") as demo:
    gr.Markdown("## ๐Ÿ“ Latin-to-Arabic Transliterator with Google Translate")
    gr.Markdown("Enter Latin characters to convert to Arabic script, generate audio, and get translations using Google Translate.")
    
    # Full-width transliteration guide with audio buttons
    with gr.Accordion("๐Ÿ“– Interactive Transliteration Guide with Audio", open=False):
        gr.Markdown("### Click the speaker buttons to hear each letter's pronunciation:")
        
        gr.Markdown("""
        **๐Ÿ’ก Note:** The built-in IPA audio uses English TTS reading of IPA symbols.
        For accurate Arabic phoneme pronunciation, see the links below the IPA output.
        """)
        
        # Two-character combinations
        gr.Markdown("#### Two-Character Combinations:")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š TH โ†’ ุซ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ุซ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š KH โ†’ ุฎ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ุฎ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š DH โ†’ ุฐ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ุฐ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š SH โ†’ ุด", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ุด"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š GH โ†’ ุบ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ุบ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
        
        # Long vowels
        gr.Markdown("#### Long Vowels:")
        with gr.Row():
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š AA โ†’ ุข", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ุข"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š EE โ†’ ูŠ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ูŠ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š OO โ†’ ูˆ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ูˆ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š UU โ†’ ูˆ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ูˆ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
            with gr.Column(scale=1):
                gr.Button("๐Ÿ”Š II โ†’ ูŠ", size="sm").click(
                    fn=generate_letter_audio, inputs=gr.State("ูŠ"), outputs=gr.Audio(visible=False, autoplay=True)
                )
        
        # Basic consonants (Row 1)
        gr.Markdown("#### Basic Consonants:")
        with gr.Row():
            gr.Button("๐Ÿ”Š a โ†’ ุง", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุง"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š b โ†’ ุจ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุจ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š t โ†’ ุช", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุช"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š j โ†’ ุฌ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฌ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š H โ†’ ุญ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุญ"), outputs=gr.Audio(visible=False, autoplay=True))
        
        # Basic consonants (Row 2)
        with gr.Row():
            gr.Button("๐Ÿ”Š d โ†’ ุฏ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฏ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š c โ†’ ูƒ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ูƒ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š r โ†’ ุฑ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฑ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š z โ†’ ุฒ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฒ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š s โ†’ ุณ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุณ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š f โ†’ ู", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ู"), outputs=gr.Audio(visible=False, autoplay=True))
        
        # Basic consonants (Row 3)
        with gr.Row():
            gr.Button("๐Ÿ”Š q โ†’ ู‚", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ู‚"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š k โ†’ ูƒ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ูƒ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š l โ†’ ู„", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ู„"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š m โ†’ ู…", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ู…"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š n โ†’ ู†", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ู†"), outputs=gr.Audio(visible=False, autoplay=True))
        
        # Basic consonants (Row 4)
        with gr.Row():
            gr.Button("๐Ÿ”Š h โ†’ ู‡", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ู‡"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š w โ†’ ูˆ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ูˆ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š y โ†’ ูŠ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ูŠ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š ' โ†’ ุน", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุน"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š x โ†’ ุก", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุก"), outputs=gr.Audio(visible=False, autoplay=True))
        
        # Emphatic consonants
        gr.Markdown("#### Emphatic Consonants (Capital Letters):")
        with gr.Row():
            gr.Button("๐Ÿ”Š S โ†’ ุต", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุต"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š D โ†’ ุถ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุถ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š T โ†’ ุท", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุท"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š Z โ†’ ุธ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุธ"), outputs=gr.Audio(visible=False, autoplay=True))
        
        # Initial vowels
        gr.Markdown("#### Initial Vowels (Word Beginnings):")
        with gr.Row():
            gr.Button("๐Ÿ”Š i โ†’ ุฅู", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฅู"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š u โ†’ ุฃู", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฃู"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š e โ†’ ุฃ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฃ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š o โ†’ ุฃู", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุฃู"), outputs=gr.Audio(visible=False, autoplay=True))
        
        # Tanween
        gr.Markdown("#### Tanween (Double Diacritics):")
        with gr.Row():
            gr.Button("๐Ÿ”Š AN โ†’ ู‹", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุจู‹"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š UN โ†’ ูŒ", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุจูŒ"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š IN โ†’ ู", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุจู"), outputs=gr.Audio(visible=False, autoplay=True))
            gr.Button("๐Ÿ”Š ON โ†’ ู", size="sm").click(fn=generate_letter_audio, inputs=gr.State("ุจูŒ"), outputs=gr.Audio(visible=False, autoplay=True))

    
    # Main interface
    with gr.Row():
        with gr.Column():
            latin_input = gr.Textbox(
                show_copy_button=True,
                label="Enter Latin-encoded Arabic", 
                lines=3,
                placeholder="Example: ehlaAN w sAhlaAN (ุฃู‡ู„ุง ูˆุณู‡ู„ุง)"
                
            )
        
        with gr.Column():
            arabic_output = gr.Textbox(
                show_copy_button=True,
                label="Arabic Script", 
                lines=3,
                rtl=True  # Right-to-left text direction for Arabic
            )
    
    # IPA output row
    with gr.Row():
        with gr.Column():
            ipa_output = gr.Textbox(
                show_copy_button=True,
                label="IPA Phonetic Transcription", 
                lines=2,
                placeholder="Shows how the Arabic sounds should be pronounced using IPA symbols"
            )
        with gr.Column():
            translation_output = gr.Textbox(
            show_copy_button=True,
            label="Google Translate Results", 
            lines=2,
            placeholder="Translations will appear here...",
        )
            
    
    # Button controls
    with gr.Row():
        convert_btn = gr.Button("๐Ÿ”„ Transliterate", variant="primary")
        tts_btn = gr.Button("๐Ÿ”Š Generate Arabic Sound", variant="secondary")
        ipa_btn = gr.Button("๐Ÿ”ค Generate IPA Text", variant="secondary")
        translate_btn = gr.Button("๐ŸŒ Google Translate", variant="secondary")
    
    with gr.Row():
        combined_btn = gr.Button("๐Ÿ”„๐Ÿ”Š Transliterate & Speak", variant="secondary")
        full_process_btn = gr.Button("๐Ÿ”„๐Ÿ”ค๐Ÿ”Š Full Process (IPA Audio)", variant="secondary")
        complete_btn = gr.Button("๐Ÿ”„๐ŸŒ๐Ÿ”Š Complete Process (IPA Audio + Translation)", variant="primary")
    
    # Audio outputs
    with gr.Row():
        with gr.Column():
            arabic_audio = gr.Audio(label="Arabic Audio", type="filepath")
        with gr.Column():
            ipa_audio = gr.Audio(label="IPA Pronunciation Audio (English reading)", type="filepath")

    # Buckwalter transliteration section
    with gr.Accordion("๐Ÿ”„ Buckwalter Transliteration", open=False):
        gr.Markdown("**Bi-directional Arabic โ†” Buckwalter transliteration**")
        gr.Markdown("Enter Arabic text or Buckwalter notation. The system will auto-detect and convert.")
        
        with gr.Row():
            with gr.Column():
                buckwalter_input = gr.Textbox(
                    label="Input (Arabic or Buckwalter)",
                    lines=3,
                    show_copy_button=True
                )
            
            with gr.Column():
                buckwalter_output = gr.Textbox(
                    label="Converted Output",
                    lines=3,
                    show_copy_button=True
                )
        
        buckwalter_convert_btn = gr.Button("๐Ÿ”„ Convert", variant="primary")
            
            
    # Manual translation section
    with gr.Accordion("๐Ÿ” Manual Translation", open=False):
        with gr.Row():
            with gr.Column():
                manual_arabic_input = gr.Textbox(
                    label="Enter Arabic text to translate",
                    placeholder="Enter Arabic text for English translation",
                    rtl=True
                )
                manual_translate_btn = gr.Button("๐ŸŒ Translate to English", variant="secondary")
            
            with gr.Column():
                manual_english_input = gr.Textbox(
                    label="Enter English text to translate",
                    placeholder="Enter English text for Arabic translation"
                )
                reverse_translate_btn = gr.Button("๐ŸŒ Translate to Arabic", variant="secondary")
        
        manual_translation_output = gr.Textbox(
            label="Manual Translation Results",
            lines=6,
            show_copy_button=True
        )
        
        manual_arabic_result = gr.Textbox(
            label="Translated Arabic Text",
            rtl=True,
            visible=False
        )
    
    # External IPA resources
    with gr.Accordion("๐ŸŽฏ Free IPA Pronunciation Tools (More Accurate)", open=False):
        gr.Markdown("""
        **๐ŸŒ Online (No Download Required):**
        โ€ข **[IPA Reader](https://ipa-reader.com/)** - Copy/paste IPA for high-quality speech
        โ€ข **[Phoneme Synthesis](https://itinerarium.github.io/phoneme-synthesis/)** - Real-time IPA โ†’ audio
        โ€ข **[Seeing Speech](https://www.seeingspeech.ac.uk/ipa-charts/)** - University tool with visual articulation
        
        **๐Ÿ’ก How to use:** Copy the IPA text from above and paste it into any of these tools for accurate Arabic phoneme pronunciation!
        """)
    
    # Event handlers
    convert_btn.click(
        fn=transliterate, 
        inputs=latin_input, 
        outputs=arabic_output
    )
    
    ipa_btn.click(
        fn=latin_to_ipa_conversion,
        inputs=latin_input,
        outputs=ipa_output
    )
    
    tts_btn.click(
        fn=arabic_tts, 
        inputs=arabic_output, 
        outputs=arabic_audio
    )
    
    translate_btn.click(
        fn=translate_multiple_words,
        inputs=arabic_output,
        outputs=translation_output
    )
    
    combined_btn.click(
        fn=transliterate_and_speak,
        inputs=latin_input,
        outputs=[arabic_output, ipa_output, arabic_audio]
    )
    
    full_process_btn.click(
        fn=full_process_with_ipa_audio,
        inputs=latin_input,
        outputs=[arabic_output, ipa_output, arabic_audio, ipa_audio]
    )
    
    complete_btn.click(
        fn=full_process_with_translation,
        inputs=latin_input,
        outputs=[arabic_output, ipa_output, arabic_audio, ipa_audio, translation_output]
    )

    # Buckwalter conversion handler
    buckwalter_convert_btn.click(
        fn=bidirectional_buckwalter_convert,
        inputs=buckwalter_input,
        outputs=[buckwalter_output]
    )
    
    # Manual translation handlers
    manual_translate_btn.click(
        fn=translate_multiple_words,
        inputs=manual_arabic_input,
        outputs=manual_translation_output
    )
    
    reverse_translate_btn.click(
        fn=reverse_translate_english,
        inputs=manual_english_input,
        outputs=[manual_translation_output, manual_arabic_result]
    )

if __name__ == "__main__":
    demo.launch()