Learn Language Detection APIs for Seamless Application Integration

Introduction to Language-Detect

Language-detect is a powerful utility that enables developers to identify the language of a given text. This is crucial for applications that handle multilingual content, as it allows for seamless integration and improved user experience.

Key APIs and Code Examples

1. Detecting Language of a Text

You can easily detect the language of a text using the detect function:

  import language_detect
  from language_detect import detect
  text = "Bonjour tout le monde"
  language = detect(text)
  print(f'The detected language is: {language}')

2. Getting Probabilities of Detected Languages

The detect_langs function returns a list of detected languages with probabilities:

  from language_detect import detect_langs
  text = "Ciao a tutti"
  languages = detect_langs(text)
  for lang in languages:
    print(f"Language: {lang.lang}, Probability: {lang.prob}")

3. Detecting Language with Confidence Scores

You can get a confidence score for each detected language as follows:

  from language_detect import detect_conf
  text = "Hola Mundo"
  lang, conf = detect_conf(text)
  print(f"Language: {lang}, Confidence: {conf}")

Practical Application Example

Let’s build a small app that reads a user’s input, detects the language, and provides the probable languages with confidence scores.

  from flask import Flask, request, jsonify
  from language_detect import detect, detect_langs, detect_conf

  app = Flask(__name__)

  @app.route('/detect', methods=['POST'])
  def detect_language():
      data = request.json
      text = data.get('text', '')
      language = detect(text)
      return jsonify({'language': language})

  @app.route('/detect_langs', methods=['POST'])
  def detect_probabilities():
      data = request.json
      text = data.get('text', '')
      languages = detect_langs(text)
      result = [{'language': lang.lang, 'probability': lang.prob} for lang in languages]
      return jsonify(result)

  @app.route('/detect_conf', methods=['POST'])
  def detect_with_confidence():
      data = request.json
      text = data.get('text', '')
      lang, conf = detect_conf(text)
      return jsonify({'language': lang, 'confidence': conf})

  if __name__ == '__main__':
      app.run(debug=True)

With the provided APIs, you can swiftly add language detection functionality to your applications, enhancing their multilingual capabilities and making them more user-friendly.

Hash: e14d684b9aae0ff3889c63a4a9304eeb0940498f226e8f541780398f1e9a10f3

Leave a Reply

Your email address will not be published. Required fields are marked *