Spaces:
No application file

cebuano / app.py
R0vert's picture
Create app.py
25dab93 verified
Raw History Blame Contribute Delete
18.5 kB
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)