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