mcpee / app.py
elikoy's picture
Create app.py
6e45d7a verified
raw
history blame
2.06 kB
from flask import Flask, request, jsonify
from googletrans import Translator
import requests
import urllib.parse
from langdetect import detect, DetectorFactory
import os
# Ensure consistent language detection
DetectorFactory.seed = 0
app = Flask(__name__)
@app.route('/translate', methods=['POST'])
def handle_translation():
data = request.get_json()
if not data or 'text' not in data:
return jsonify({"error": "Missing 'text' in request"}), 400
text = data['text'].strip()
if not text:
return jsonify({"error": "Text cannot be empty"}), 400
try:
# Detect language
lang = detect_language(text)
# Translate to Dutch
dutch_translation = translate_to_dutch(text)
# Translate to Mestreechs
mestreechs_translation = translate_to_mestreechs(dutch_translation)
return jsonify({
"detected_language": lang,
"dutch_translation": dutch_translation,
"mestreechs_translation": mestreechs_translation
})
except Exception as e:
return jsonify({"error": str(e)}), 500
def detect_language(text):
try:
return detect(text)
except:
return "unknown"
def translate_to_dutch(text):
translator = Translator()
result = translator.translate(text, dest='nl')
return result.text
def translate_to_mestreechs(dutch_term):
try:
encoded_term = urllib.parse.quote(dutch_term)
url = f"https://www.limburgs.net/api/search/{encoded_term}?dialects=Maastricht&languageDirection=NL-LI&deep=false"
response = requests.get(url)
if response.status_code == 200:
results = response.json()
if results and isinstance(results, list) and len(results) > 0 and results[0].get('dialects'):
return results[0]['dialects'][0]['translation']
return "Translation not found"
except:
return "API error"
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0', port=7860)