elikoy commited on
Commit
f25cc68
·
verified ·
1 Parent(s): a09debb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -29
app.py CHANGED
@@ -1,35 +1,33 @@
1
- from flask import Flask, request, jsonify
2
  import requests
3
  import urllib.parse
4
  import re
 
 
 
 
5
 
6
- app = Flask(__name__)
 
7
 
8
- @app.route('/translate', methods=['POST'])
9
- def handle_translation():
10
- data = request.get_json()
11
- if not data or 'text' not in data:
12
- return jsonify({"error": "Missing 'text' in request"}), 400
13
-
14
- term = data['text'].strip()
15
-
16
- # Validate single word/term
17
- if not term:
18
- return jsonify({"error": "Empty input"}), 400
19
- if re.search(r'\s{2,}', term) or len(term.split()) > 2:
20
- return jsonify({"error": "Input must be a single word or short term (max 2 words)"}), 400
21
-
22
- try:
23
- mestreechs_translation = translate_to_mestreechs(term)
24
- return jsonify({
25
- "dutch_term": term,
26
- "mestreechs_translation": mestreechs_translation
27
- })
28
-
29
- except Exception as e:
30
- return jsonify({"error": str(e)}), 500
31
 
 
32
  def translate_to_mestreechs(dutch_term):
 
 
 
 
 
 
 
33
  try:
34
  # Encode term for URL
35
  encoded_term = urllib.parse.quote(dutch_term)
@@ -42,9 +40,72 @@ def translate_to_mestreechs(dutch_term):
42
  return results[0]['dialects'][0]['translation']
43
  return "Translation not found"
44
  except requests.exceptions.Timeout:
45
- return "API timeout"
46
- except:
47
- return "API error"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
 
49
  if __name__ == "__main__":
50
- app.run(debug=False, host='0.0.0.0', port=7860)
 
1
+ import gradio as gr
2
  import requests
3
  import urllib.parse
4
  import re
5
+ from fastapi import FastAPI, Request, HTTPException
6
+ import uvicorn
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.staticfiles import StaticFiles
9
 
10
+ # Create FastAPI app for API server
11
+ api_app = FastAPI()
12
 
13
+ # Add CORS middleware to allow all origins
14
+ api_app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_credentials=True,
18
+ allow_methods=["*"],
19
+ allow_headers=["*"],
20
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ # Translation function used by both interfaces
23
  def translate_to_mestreechs(dutch_term):
24
+ # Validate input
25
+ if not dutch_term:
26
+ return "Error: Empty input"
27
+
28
+ if re.search(r'\s{2,}', dutch_term) or len(dutch_term.split()) > 2:
29
+ return "Error: Input must be a single word or short term (max 2 words)"
30
+
31
  try:
32
  # Encode term for URL
33
  encoded_term = urllib.parse.quote(dutch_term)
 
40
  return results[0]['dialects'][0]['translation']
41
  return "Translation not found"
42
  except requests.exceptions.Timeout:
43
+ return "API timeout - please try again"
44
+ except Exception as e:
45
+ return f"Error: {str(e)}"
46
+
47
+ # API endpoint
48
+ @api_app.post("/api/translate")
49
+ async def api_translate(request: Request):
50
+ data = await request.json()
51
+ if not data or 'text' not in data:
52
+ raise HTTPException(status_code=400, detail="Missing 'text' in request")
53
+
54
+ term = data['text'].strip()
55
+ translation = translate_to_mestreechs(term)
56
+
57
+ return {
58
+ "dutch_term": term,
59
+ "mestreechs_translation": translation
60
+ }
61
+
62
+ # Gradio interface function
63
+ def gradio_translate(dutch_term):
64
+ return translate_to_mestreechs(dutch_term)
65
+
66
+ # Create Gradio interface
67
+ with gr.Blocks(theme=gr.themes.Soft(), title="Dutch to Mestreechs Translator") as gradio_app:
68
+ gr.Markdown("# 🇳🇱 Dutch to Mestreechs Translator")
69
+ gr.Markdown("Translate Dutch words to the Mestreechs dialect of Limburgish")
70
+
71
+ with gr.Row():
72
+ with gr.Column():
73
+ input_text = gr.Textbox(
74
+ label="Dutch Word/Term",
75
+ placeholder="Enter a Dutch word (e.g. 'huis')",
76
+ max_lines=1
77
+ )
78
+ submit_btn = gr.Button("Translate", variant="primary")
79
+
80
+ gr.Examples(
81
+ examples=["huis", "kerk", "oude", "straat", "oude kerk"],
82
+ inputs=input_text,
83
+ label="Try these examples:"
84
+ )
85
+
86
+ with gr.Column():
87
+ output_text = gr.Textbox(
88
+ label="Mestreechs Translation",
89
+ interactive=False
90
+ )
91
+
92
+ submit_btn.click(
93
+ fn=gradio_translate,
94
+ inputs=input_text,
95
+ outputs=output_text
96
+ )
97
+
98
+ gr.Markdown("""
99
+ ### Notes:
100
+ - Input must be a single word or short term (max 2 words)
101
+ - Translations provided by [limburgs.net](https://www.limburgs.net)
102
+ - Mestreechs is the dialect spoken in Maastricht, Netherlands
103
+ - API endpoint: `/api/translate` (POST)
104
+ """)
105
+
106
+ # Mount Gradio app at root
107
+ api_app.mount("/", gr.routes.App(gradio_app))
108
 
109
+ # For Hugging Face Spaces deployment
110
  if __name__ == "__main__":
111
+ uvicorn.run(api_app, host="0.0.0.0", port=7860)