You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask JSON响应仅返回首个语言检测结果的问题求助

Fixing Your Flask Language Detection API

Hey there! I noticed a couple of key issues with your code that are causing it to only return the first English result (or behave unexpectedly) — plus, it looks like your current implementation doesn’t match your original goal of detecting languages like English, Hindi, or Marathi in mixed text. Let’s break this down and fix it step by step.

First, What’s Wrong With Your Current Code?

  1. Mismatched Goal vs. Implementation: You want to detect languages present in the input, but your code is trying to translate every word to English instead.
  2. No Error Handling: When TextBlob.translate() gets a word that’s already in English, it throws a NotTranslated exception. Since you don’t catch this error, the API crashes early, which is why you’re only seeing the first result.
  3. Unused Language Model: You mentioned having a custom language detection model, but your code doesn’t load or use it at all!

Solution 1: Build a Language Detection API with TextBlob

If you want to use TextBlob for language detection (instead of your custom model for now), here’s a revised version that returns a unique list of languages in your input:

from flask import Flask, jsonify, request
from textblob import TextBlob

app = Flask(__name__)

# Map language codes to human-readable names (add more as needed)
LANGUAGE_MAP = {
    "en": "English",
    "hi": "Hindi",
    "mr": "Marathi"
}

@app.route('/res', methods=['POST'])
def detect_languages():
    if request.method == 'POST':
        posted_data = request.get_json()
        text = posted_data.get("text", "")
        
        # Validate input
        if not text:
            return jsonify({"error": "Please provide a 'text' field in your request"}), 400
        
        detected_languages = set()  # Use a set to avoid duplicate languages
        words = text.split()
        
        for word in words:
            try:
                blob = TextBlob(word.strip())
                lang_code = blob.detect_language()
                # Convert code to name, or keep the code if we don't have a mapping
                language_name = LANGUAGE_MAP.get(lang_code, lang_code)
                detected_languages.add(language_name)
            except Exception as e:
                # Skip words we can't detect (like punctuation or gibberish)
                print(f"Could not detect language for word '{word}': {str(e)}")
                continue
        
        # Return the sorted list of detected languages
        return jsonify({"detected_languages": sorted(detected_languages)})

if __name__ == '__main__':
    app.run(host='127.0.0.1', port='5000', debug=False)

Solution 2: Use Your Custom Language Detection Model

If you want to leverage the model you mentioned (assuming it’s saved as a pickle file), modify the code to load and use your model instead of TextBlob:

from flask import Flask, jsonify, request
import pickle

app = Flask(__name__)

# Load your custom language detection model once when the app starts
with open("your_model_filename.pkl", "rb") as model_file:
    language_detector = pickle.load(model_file)

def get_language_from_model(text):
    # Replace this with your model's actual prediction logic
    # Example: If your model takes a text string and returns a language name
    return language_detector.predict([text])[0]

@app.route('/res', methods=['POST'])
def detect_languages():
    if request.method == 'POST':
        posted_data = request.get_json()
        text = posted_data.get("text", "")
        
        if not text:
            return jsonify({"error": "Missing 'text' parameter"}), 400
        
        detected_languages = set()
        words = text.split()
        
        for word in words:
            try:
                language = get_language_from_model(word.strip())
                detected_languages.add(language)
            except Exception as e:
                print(f"Error processing word '{word}': {str(e)}")
                continue
        
        return jsonify({"detected_languages": sorted(detected_languages)})

if __name__ == '__main__':
    app.run(host='127.0.0.1', port='5000', debug=False)

If You Actually Wanted a Translation API (Not Detection)

If your original code was meant to translate mixed-language text to English (not detect languages), here’s a fixed version with error handling to avoid crashing:

from flask import Flask, jsonify, request
from textblob import TextBlob

app = Flask(__name__)

@app.route('/res', methods=['POST'])
def translate_to_english():
    if request.method == 'POST':
        posted_data = request.get_json()
        text = posted_data.get("text", "")
        
        if not text:
            return jsonify({"error": "No text provided"}), 400
        
        translated_words = []
        words = text.split()
        
        for word in words:
            try:
                blob = TextBlob(word.strip())
                # Skip translation if the word is already in English
                if blob.detect_language() == "en":
                    translated_words.append(word)
                else:
                    translated = blob.translate(to="en")
                    translated_words.append(str(translated))
            except Exception as e:
                # If translation fails, keep the original word
                translated_words.append(word)
                print(f"Failed to translate '{word}': {str(e)}")
        
        translated_text = " ".join(translated_words)
        return jsonify({"response": translated_text})

if __name__ == '__main__':
    app.run(host='127.0.0.1', port='5000', debug=False)

Why Your Original Code Crashed

The main issue was missing error handling for TextBlob.translate(). When it encounters an English word, it can’t translate it to English, so it throws an exception. Without a try/except block, the API stops executing immediately, which is why you only saw the first result.

内容的提问来源于stack exchange,提问作者manju badiger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:00:07