from flask import Flask, request, jsonify import requests import urllib.parse import re 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 term = data['text'].strip() # Validate single word/term if not term: return jsonify({"error": "Empty input"}), 400 if re.search(r'\s{2,}', term) or len(term.split()) > 2: return jsonify({"error": "Input must be a single word or short term (max 2 words)"}), 400 try: mestreechs_translation = translate_to_mestreechs(term) return jsonify({ "dutch_term": term, "mestreechs_translation": mestreechs_translation }) except Exception as e: return jsonify({"error": str(e)}), 500 def translate_to_mestreechs(dutch_term): try: # Encode term for URL 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, timeout=5) if response.status_code == 200: results = response.json() if results and isinstance(results, list) and results and results[0].get('dialects'): return results[0]['dialects'][0]['translation'] return "Translation not found" except requests.exceptions.Timeout: return "API timeout" except: return "API error" if __name__ == "__main__": app.run(debug=False, host='0.0.0.0', port=7860)