|
from flask import Flask, request, jsonify |
|
from googletrans import Translator |
|
import requests |
|
import urllib.parse |
|
from langdetect import detect, DetectorFactory |
|
import os |
|
|
|
|
|
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: |
|
|
|
lang = detect_language(text) |
|
|
|
|
|
dutch_translation = translate_to_dutch(text) |
|
|
|
|
|
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) |