demo / app.py
Aboge's picture
Update app.py
93928ba verified
from flask import Flask, request, jsonify
from transformers import pipeline
app = Flask(__name__)
# Initialize the translation pipeline
sw_to_en = pipeline("translation", model="Bildad/Swahili-English_Translation")
en_to_sw = pipeline("translation", model="Bildad/English-Swahili_Translation")
@app.route("/", methods=["GET"])
def home():
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatEasy swa-eng Translation API</title>
<style>
body {{
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}}
.container {{
width: 80%;
margin: auto;
margin-top: 50px;
overflow: hidden;
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}}
h1 {{
color: #333;
}}
h2 {{
color: #555;
margin-top: 20px;
}}
pre {{
background-color: #f9f9f9;
border: 1px solid #ddd;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
}}
code {{
background-color: #f4f4f4;
padding: 2px 4px;
border-radius: 4px;
color: #d14;
}}
.payload-key {{
color: #d14;
}}
.payload-value {{
color: green;
}}
</style>
</head>
<body>
<div class="container">
<h1>ChatEasy swa-eng Translation API</h1>
<p>Welcome to the ChatEasy swa-eng Translation API documentation.</p>
<p>To use the API, send a POST request to <code>/translate</code>.</p>
<h2>Request Payload</h2>
<pre>
&#123;
"<span class="payload-key">text</span>" : "<span class="payload-value">Siku njema</span>",
"<span class="payload-key">target</span>" : "<span class="payload-value">en</span>"
&#125;
</pre>
<h2>Expected Response</h2>
<pre>&#123; "<span class="payload-key">translated_text</span>" : "<span class="payload-value">A good day</span>" &#125;</pre>
</div>
</body>
</html>
"""
return html_content
@app.route("/translate", methods=["POST"])
def translate():
data = request.get_json()
if "text" not in data:
return jsonify({"error": "No text provided"}), 400
if "target" not in data:
return jsonify({"error": "No Target Language Provided"}), 400
text_to_translate = data["text"]
target_language = data["target"]
if target_language == "sw":
translation = en_to_sw(text_to_translate)[0]
elif target_language == "en":
translation = sw_to_en(text_to_translate)[0]
else:
return jsonify({"error": "Invalid Target Language"}), 400
translated_text = translation["translation_text"]
return jsonify({"translated_text": translated_text})
if __name__ == "__main__":
app.run(debug=True)