elikoy commited on
Commit
6e45d7a
·
verified ·
1 Parent(s): e4592f3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from googletrans import Translator
3
+ import requests
4
+ import urllib.parse
5
+ from langdetect import detect, DetectorFactory
6
+ import os
7
+
8
+ # Ensure consistent language detection
9
+ DetectorFactory.seed = 0
10
+
11
+ app = Flask(__name__)
12
+
13
+ @app.route('/translate', methods=['POST'])
14
+ def handle_translation():
15
+ data = request.get_json()
16
+ if not data or 'text' not in data:
17
+ return jsonify({"error": "Missing 'text' in request"}), 400
18
+
19
+ text = data['text'].strip()
20
+ if not text:
21
+ return jsonify({"error": "Text cannot be empty"}), 400
22
+
23
+ try:
24
+ # Detect language
25
+ lang = detect_language(text)
26
+
27
+ # Translate to Dutch
28
+ dutch_translation = translate_to_dutch(text)
29
+
30
+ # Translate to Mestreechs
31
+ mestreechs_translation = translate_to_mestreechs(dutch_translation)
32
+
33
+ return jsonify({
34
+ "detected_language": lang,
35
+ "dutch_translation": dutch_translation,
36
+ "mestreechs_translation": mestreechs_translation
37
+ })
38
+
39
+ except Exception as e:
40
+ return jsonify({"error": str(e)}), 500
41
+
42
+ def detect_language(text):
43
+ try:
44
+ return detect(text)
45
+ except:
46
+ return "unknown"
47
+
48
+ def translate_to_dutch(text):
49
+ translator = Translator()
50
+ result = translator.translate(text, dest='nl')
51
+ return result.text
52
+
53
+ def translate_to_mestreechs(dutch_term):
54
+ try:
55
+ encoded_term = urllib.parse.quote(dutch_term)
56
+ url = f"https://www.limburgs.net/api/search/{encoded_term}?dialects=Maastricht&languageDirection=NL-LI&deep=false"
57
+
58
+ response = requests.get(url)
59
+ if response.status_code == 200:
60
+ results = response.json()
61
+ if results and isinstance(results, list) and len(results) > 0 and results[0].get('dialects'):
62
+ return results[0]['dialects'][0]['translation']
63
+ return "Translation not found"
64
+ except:
65
+ return "API error"
66
+
67
+ if __name__ == "__main__":
68
+ app.run(debug=False, host='0.0.0.0', port=7860)