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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
from transformers import MarianMTModel, MarianTokenizer
import os
import torch
import re
import logging
import json
import base64
import sqlite3
import io
from vosk import Model, KaldiRecognizer
from rapidfuzz import fuzz
from datetime import datetime
from pydub import AudioSegment

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__, template_folder='templates')
CORS(app, resources={r"/translate": {"origins": "*"}})

# --- CONFIGURATION ---
MODEL_NAME = "Helsinki-NLP/opus-mt-en-ceb"
SAVE_PATH = "./cebuano_ai_model"
device = "cuda" if torch.cuda.is_available() else "cpu"

logger.info(f"Using device: {device}")

# Vosk & DB Configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_PATH = os.path.join(BASE_DIR, "model")
DB_PATH = os.path.join(BASE_DIR, "Cebuano.db")
SAMPLE_RATE = 16000

# --- 1. DATA LAYER (Post-Processing Dictionary) ---
DICTIONARY_DATA = {
    "eyes": {
        "trans": "mata",
        "type": "Noun",
        "meaning": "The organ of sight; used to see and perceive the world around you",
        "synonyms": "panan-aw, pag-kit",
        "example": "Ang mata ay importante para makita ang kagandahan ng kalikasan."
    },
    "eye": {
        "trans": "mata",
        "type": "Noun",
        "meaning": "The organ of sight; used to see and perceive the world around you",
        "synonyms": "panan-aw, pag-kit",
        "example": "Ang mata ay importante para makita ang kagandahan ng kalikasan."
    },
    "foot": {
        "trans": "tiil",
        "type": "Noun",
        "meaning": "The lower extremity of the leg used for walking and standing",
        "synonyms": "sapakan",
        "example": "Ang tiil ay tumutulong sa atin na maglakad at tumakbo."
    },
    "feet": {
        "trans": "tiil",
        "type": "Noun",
        "meaning": "The lower extremities of the legs used for walking and standing",
        "synonyms": "sapakan",
        "example": "Ang mga tiil ay tumutulong sa atin na maglakad at tumakbo."
    },
    "hand": {
        "trans": "kamot",
        "type": "Noun",
        "meaning": "The upper extremity of the arm with fingers used for grasping and holding",
        "synonyms": "palad, mga daliri",
        "example": "Gumamit siya ng kanyang kamot upang magsulat."
    },
    "hands": {
        "trans": "kamot",
        "type": "Noun",
        "meaning": "The upper extremities of the arms with fingers used for grasping and holding",
        "synonyms": "palad, mga daliri",
        "example": "Gumamit siya ng kanyang mga kamot upang magsulat."
    },
    "beautiful": {
        "trans": "anindot",
        "type": "Adjective",
        "meaning": "Pleasing to the eye; attractive and aesthetically appealing",
        "synonyms": "maganda, napaganda",
        "example": "Ang anindot na bulaklak ay nag-aakit ng mga bubuyog."
    },
    "run": {
        "trans": "dagan",
        "type": "Verb",
        "meaning": "To move quickly on foot at a faster pace than walking",
        "synonyms": "tumakas, dagan-dalian",
        "example": "Siya ay tumatakbo patungo sa paaralan kada umaga."
    },
    "running": {
        "trans": "tumatakbo",
        "type": "Verb",
        "meaning": "Moving quickly on foot at a faster pace than walking",
        "synonyms": "dagan, tumakas",
        "example": "Siya ay tumatakbo patungo sa paaralan kada umaga."
    },
    "head": {
        "trans": "ulo",
        "type": "Noun",
        "meaning": "The upper part of the body containing the brain, eyes, and ears",
        "synonyms": "kaunod, top",
        "example": "Ang ulo ay ang pinakamahalagang bahagi ng katawan."
    },
    "hello": {
        "trans": "hello",
        "type": "Interjection",
        "meaning": "A greeting used to say hi or get someone's attention",
        "synonyms": "hola, kumusta",
        "example": "Hello! Paano ka ngayon?"
    },
    "thank you": {
        "trans": "salamat",
        "type": "Phrase",
        "meaning": "An expression of gratitude or appreciation",
        "synonyms": "maraming salamat, pasalamat",
        "example": "Salamat sa iyong tulong!"
    },
    "thanks": {
        "trans": "salamat",
        "type": "Interjection",
        "meaning": "An expression of gratitude or appreciation",
        "synonyms": "maraming salamat, pasalamat",
        "example": "Salamat sa iyong tulong!"
    },
    "love": {
        "trans": "pag-ibig",
        "type": "Noun",
        "meaning": "A strong feeling of affection and care for someone or something",
        "synonyms": "gugma, alay-pagmamahal",
        "example": "Ang pag-ibig ay ang pinakamahalagang damdamin."
    },
    "friend": {
        "trans": "kaibigan",
        "type": "Noun",
        "meaning": "A person with whom one has a bond of mutual affection",
        "synonyms": "kasama, alagaan",
        "example": "Ang kaibigan ay isang mahalagang bahagi ng buhay."
    },
    "family": {
        "trans": "pamilya",
        "type": "Noun",
        "meaning": "A group of people related by blood or marriage living together",
        "synonyms": "angkan, kaanak",
        "example": "Ang pamilya ay ang pundasyon ng lipunan."
    },
    "food": {
        "trans": "pagkain",
        "type": "Noun",
        "meaning": "Edible substances consumed to provide energy and nutrition",
        "synonyms": "kumain, araw",
        "example": "Ang pagkain ay mahalaga para sa kalusugan."
    },
    "water": {
        "trans": "tubig",
        "type": "Noun",
        "meaning": "A clear, colorless liquid essential for life and hydration",
        "synonyms": "alak, inumin",
        "example": "Ang tubig ay kailangan araw-araw."
    },
    "sun": {
        "trans": "araw",
        "type": "Noun",
        "meaning": "The star at the center of our solar system that provides light and heat",
        "synonyms": "bituin, liwanag",
        "example": "Ang araw ay sumisilang sa umaga."
    },
    "moon": {
        "trans": "buwan",
        "type": "Noun",
        "meaning": "Earth's natural satellite that orbits our planet",
        "synonyms": "bituin, gabi",
        "example": "Ang buwan ay makikita sa gabi."
    },
    "book": {
        "trans": "libro",
        "type": "Noun",
        "meaning": "A set of pages bound together containing written or printed matter",
        "synonyms": "aklat, sulatin",
        "example": "Ang libro ay puno ng kaalaman."
    },
    "school": {
        "trans": "paaralan",
        "type": "Noun",
        "meaning": "An institution for educating children and young people",
        "synonyms": "akademya, gawaran",
        "example": "Ang paaralan ay lugar ng pag-aaral."
    },
    "house": {
        "trans": "bahay",
        "type": "Noun",
        "meaning": "A building where people live; a residence",
        "synonyms": "tahanan, dapan",
        "example": "Ang bahay ay isang ligtas na lugar."
    },
    "car": {
        "trans": "sasakyan",
        "type": "Noun",
        "meaning": "A motor vehicle designed to carry passengers",
        "synonyms": "kotse, mobile",
        "example": "Ang sasakyan ay mabilis at komportable."
    },
    "happy": {
        "trans": "masaya",
        "type": "Adjective",
        "meaning": "Feeling or showing pleasure and contentment",
        "synonyms": "saya, ngiti",
        "example": "Ako ay masaya sa kasama ko."
    },
    "sad": {
        "trans": "malungkot",
        "type": "Adjective",
        "meaning": "Feeling sorrow or unhappiness",
        "synonyms": "alalahanin, lungkot",
        "example": "Siya ay malungkot dahil sa nangyari."
    },
    "strong": {
        "trans": "malakas",
        "type": "Adjective",
        "meaning": "Having great physical power or mental strength",
        "synonyms": "lakas, tibay",
        "example": "Ang malakas na tao ay kaya ng maraming gawain."
    },
    "weak": {
        "trans": "mahina",
        "type": "Adjective",
        "meaning": "Lacking physical strength or power",
        "synonyms": "kulang, payat",
        "example": "Ang mahina na taon ay nangangailangan ng tulong."
    },
    "sleep": {
        "trans": "tulog",
        "type": "Noun",
        "meaning": "A natural state of rest where the body and mind are inactive",
        "synonyms": "pahinga, zzz",
        "example": "Ang tulog ay mahalaga para sa kalusugan."
    },
    "eat": {
        "trans": "kumain",
        "type": "Verb",
        "meaning": "To consume food by putting it in the mouth and swallowing",
        "synonyms": "pagkain, busog",
        "example": "Kumain tayo ng masarap na pagkain."
    },
    "walk": {
        "trans": "lakad",
        "type": "Verb",
        "meaning": "To move forward on foot one step at a time",
        "synonyms": "yugto, bumyahe",
        "example": "Lakad tayo sa parque ngayong hapon."
    },
    "talk": {
        "trans": "magsalita",
        "type": "Verb",
        "meaning": "To communicate by making sounds and words with the mouth",
        "synonyms": "sabi, kwento",
        "example": "Magsalita ka nang maayos sa klase."
    },
    "listen": {
        "trans": "makinig",
        "type": "Verb",
        "meaning": "To pay attention to sound or speech",
        "synonyms": "pakinggan, tunog",
        "example": "Makinig sa mga salita ng guro."
    }
}


# --- 2. PRE-PROCESSING UTILS ---
def expand_contractions(text):
    """Normalization: MarianMT performs better with formal English."""
    contractions = {
        "can't": "cannot", "don't": "do not", "it's": "it is", "i'm": "i am", "won't": "will not",
        "isn't": "is not", "aren't": "are not", "was not": "was not", "weren't": "were not",
        "hasn't": "has not", "haven't": "have not", "hadn't": "had not", "doesn't": "does not",
        "didn't": "did not", "couldn't": "could not", "shouldn't": "should not", "wouldn't": "would not",
        "mightn't": "might not", "mustn't": "must not", "that's": "that is", "what's": "what is",
        "who's": "who is", "where's": "where is", "when's": "when is", "why's": "why is",
        "how's": "how is", "let's": "let us", "you're": "you are", "we're": "we are",
        "they're": "they are", "i've": "i have", "you've": "you have", "we've": "we have",
        "they've": "they have", "i'll": "i will", "you'll": "you will", "he'll": "he will",
        "she'll": "she will", "it'll": "it will", "we'll": "we will", "they'll": "they will",
        "i'd": "i would", "you'd": "you would", "he'd": "he would", "she'd": "she would",
        "we'd": "we would", "they'd": "they would"
    }
    for word, replacement in contractions.items():
        text = text.replace(word, replacement)
    return text


# --- 3. MODEL INITIALIZATION ---

# Vosk Model Initialization
if os.path.exists(MODEL_PATH):
    logger.info("🚀 Loading Speech Model...")
    vosk_model = Model(MODEL_PATH)
else:
    vosk_model = None
    logger.warning(f"Vosk model not found at {MODEL_PATH}. Speech features may be disabled.")


# Database Initialization
def init_db():
    with sqlite3.connect(DB_PATH) as conn:
        conn.execute('''
                     CREATE TABLE IF NOT EXISTS test_results
                     (
                         id
                         INTEGER
                         PRIMARY
                         KEY
                         AUTOINCREMENT,
                         user_name
                         TEXT,
                         target_word
                         TEXT,
                         spoken_text
                         TEXT,
                         accuracy
                         REAL,
                         passed
                         INTEGER,
                         timestamp
                         DATETIME
                     );
                     ''')


init_db()

# Neural Translation Model Initialization
try:
    if not os.path.exists(SAVE_PATH):
        logger.info(f"Loading model from {MODEL_NAME}...")
        tokenizer = MarianTokenizer.from_pretrained(MODEL_NAME)
        translation_model = MarianMTModel.from_pretrained(MODEL_NAME).to(device)
        tokenizer.save_pretrained(SAVE_PATH)
        translation_model.save_pretrained(SAVE_PATH)
        logger.info("Model saved successfully")
    else:
        logger.info(f"Loading model from {SAVE_PATH}...")
        tokenizer = MarianTokenizer.from_pretrained(SAVE_PATH)
        translation_model = MarianMTModel.from_pretrained(SAVE_PATH).to(device)
        logger.info("Model loaded successfully")
except Exception as e:
    logger.error(f"Error loading model: {e}")
    raise


# --- 4. CORE ENGINE UTILS ---
def neural_translate(text):
    """Improved Decoding Strategy"""
    try:
        inputs = tokenizer(text, return_tensors="pt", padding=True).to(device)
        translated_tokens = translation_model.generate(
            **inputs,
            num_beams=8,
            repetition_penalty=1.5,
            length_penalty=1.0,
            no_repeat_ngram_size=2,
            early_stopping=True,
            max_length=128
        )
        result = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
        logger.info(f"Translation result: {text} -> {result}")
        return result
    except Exception as e:
        logger.error(f"Translation error: {e}")
        raise


def process_audio(audio_b64):
    """Converts base64 audio (any format) to Vosk-compatible WAV."""
    try:
        if "," in audio_b64:
            audio_b64 = audio_b64.split(",")[1]
        audio_data = base64.b64decode(audio_b64)
        audio_file = io.BytesIO(audio_data)
        audio = AudioSegment.from_file(audio_file)
        audio = audio.set_frame_rate(SAMPLE_RATE).set_channels(1)
        return audio.raw_data
    except Exception as e:
        logger.error(f"Audio processing error: {e}")
        return None


# --- 5. ROUTES ---
@app.route('/')
def home():
    return render_template('index.html')


@app.route('/translate', methods=['POST', 'OPTIONS'])
def translate_text():
    """Main translation endpoint with dictionary fallback"""
    if request.method == 'OPTIONS':
        return '', 204

    try:
        if not request.is_json:
            return jsonify({"error": "Request must be JSON", "translated": "", "details": None}), 400

        data = request.get_json()
        raw_text = data.get("text", "").strip().lower()

        if not raw_text:
            return jsonify({"translated": "", "details": None})

        # --- STEP A: PRE-PROCESSING ---
        clean_text = expand_contractions(raw_text)

        # --- STEP B: POST-PROCESSING / DICTIONARY FIX ---
        details = {
            "type": "Neural Translation",
            "synonyms": "N/A",
            "meaning": "Unable to determine meaning",
            "example": "N/A",
            "source": "AI Engine"
        }

        if raw_text in DICTIONARY_DATA:
            entry = DICTIONARY_DATA[raw_text]
            translation = entry["trans"]
            details["type"] = entry["type"]
            details["meaning"] = entry["meaning"]
            details["synonyms"] = entry.get("synonyms", "N/A")
            details["example"] = entry.get("example", "N/A")
            details["source"] = "Verified Dictionary"
        else:
            # --- STEP C: NEURAL TRANSLATION ---
            translation = neural_translate(clean_text)

        final_output = translation.strip().capitalize()

        return jsonify({
            "translated": final_output,
            "details": details,
            "metadata": {
                "engine": "MarianMT-Cebuano-v2.1",
                "device": device,
                "model": MODEL_NAME
            }
        }), 200

    except Exception as e:
        logger.error(f"Error in translation: {str(e)}", exc_info=True)
        return jsonify({"error": str(e), "translated": "", "details": None}), 500


@app.route('/rate_pronunciation', methods=['POST'])
def rate_pronunciation():
    try:
        if vosk_model is None:
            return jsonify({"error": "Vosk speech model is not loaded on the server"}), 503

        data = request.json or {}
        target = data.get('target_word', '').lower().strip()
        audio_b64 = data.get('audio_base64', '')
        user = data.get('user_name', 'Student')

        if not audio_b64:
            return jsonify({"error": "No audio data provided"}), 400

        raw_audio = process_audio(audio_b64)
        if not raw_audio:
            return jsonify({"error": "Invalid audio format"}), 400

        # Run Speech-to-Text with Vosk
        rec = KaldiRecognizer(vosk_model, SAMPLE_RATE)
        rec.AcceptWaveform(raw_audio)
        result = json.loads(rec.FinalResult())
        spoken = result.get('text', '').lower().strip()

        if not spoken:
            return jsonify({
                "score": 0,
                "spoken": "[No speech detected]",
                "passed": False,
                "message": "We couldn't hear you. Please try again!"
            })

        # Calculate accuracy/score
        accuracy = fuzz.ratio(spoken, target)
        passed = 1 if accuracy >= 75 else 0

        # Save result to DB
        with sqlite3.connect(DB_PATH) as conn:
            conn.execute(
                "INSERT INTO test_results (user_name, target_word, spoken_text, accuracy, passed, timestamp) VALUES (?,?,?,?,?,?)",
                (user, target, spoken, accuracy, passed, datetime.now())
            )

        return jsonify({
            "score": round(accuracy, 2),
            "spoken": spoken,
            "passed": bool(passed),
            "message": "Excellent pronunciation!" if accuracy > 90 else "Good, keep practicing!" if passed else "Keep trying!"
        })

    except Exception as e:
        logger.error(f"Pronunciation engine error: {e}", exc_info=True)
        return jsonify({"error": "Internal server error"}), 500


@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({
        "status": "healthy",
        "device": device,
        "model_loaded": True
    }), 200


# Error handlers
@app.errorhandler(404)
def not_found(error):
    return jsonify({"error": "Not found"}), 404


@app.errorhandler(500)
def internal_error(error):
    logger.error(f"Internal error: {error}")
    return jsonify({"error": "Internal server error"}), 500


if __name__ == '__main__':
    logger.info("Starting Flask app...")
    app.run(host='0.0.0.0', port=5000, debug=False, threaded=True)