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"""
ChatEasy swa-eng Translation API
ChatEasy swa-eng Translation API
Welcome to the ChatEasy swa-eng Translation API documentation.
To use the API, send a POST request to /translate
.
Request Payload
{
"text" : "Siku njema",
"target" : "en"
}
Expected Response
{ "translated_text" : "A good day" }
"""
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)