search
HomeBackend DevelopmentPython TutorialHow to create a voice translation bot with witai

Comment créer un bot de traduction vocale avec witai

In our globalized world, communication across linguistic boundaries is more essential than ever. In this article, we will explore how to implement this technology to make communication more inclusive and accessible to everyone.

The code is available here
on my github

First thing to do is install the dependencies

blinker==1.8.2
cachetools==5.5.0
certifi==2024.8.30
chardet==3.0.4
charset-normalizer==3.4.0
click==8.1.7
colorama==0.4.6
Flask==3.0.3
google-api-core==2.22.0
google-auth==2.36.0
google-cloud-texttospeech==2.21.0
googleapis-common-protos==1.65.0
googletrans==4.0.0rc1
grpcio==1.67.1
grpcio-status==1.67.1
gTTS==2.5.3
h11==0.9.0
h2==3.2.0
hpack==3.0.0
hstspreload==2024.11.1
httpcore==0.9.1
httpx==0.13.3
hyperframe==5.2.0
idna==2.10
itsdangerous==2.2.0
Jinja2==3.1.4
Levenshtein==0.26.1
MarkupSafe==3.0.2
playsound==1.2.2
prompt_toolkit==3.0.48
proto-plus==1.25.0
protobuf==5.28.3
pyasn1==0.6.1
pyasn1_modules==0.4.1
PyAudio==0.2.14
python-Levenshtein==0.26.1
RapidFuzz==3.10.1
requests==2.32.3
rfc3986==1.5.0
rsa==4.9
sniffio==1.3.1
SpeechRecognition==3.11.0
typing_extensions==4.12.2
urllib3==2.2.3
wcwidth==0.2.13
Werkzeug==3.1.2
wit==6.0.1

Audio to text conversion

from gtts import gTTS
import playsound
import os

def speak_translation(text, lang):
    tts = gTTS(text=text, lang=lang)
    filename = "translation.mp3"
    tts.save(filename)
    playsound.playsound(filename)
    os.remove(filename)

Google cloud text Speech

from google.cloud import texttospeech

def synthesize_speech(text, language_code="wo-WO", voice_name="wo-WO-Standard-A", output_file="output.mp3"):
    client = texttospeech.TextToSpeechClient()

    input_text = texttospeech.SynthesisInput(text=text)

    # Configurez la voix pour le Wolof
    voice = texttospeech.VoiceSelectionParams(
        language_code=language_code,
        name=voice_name,
        ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL,
    )

    # Paramètres audio
    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.MP3
    )

    # Synthèse vocale
    response = client.synthesize_speech(
        input=input_text, voice=voice, audio_config=audio_config
    )

    # Sauvegarder le fichier audio
    with open(output_file, "wb") as out:
        out.write(response.audio_content)
        print(f"Audio content written to file {output_file}")

# Utilisez cette fonction avec votre texte
synthesize_speech("Bonjour, je teste la traduction en Wolof.", "wo-WO")

Translation

from googletrans import Translator

def translate_text(text, target_lang):
    try:
        translator = Translator()
        translation = translator.translate(text, dest=target_lang)
        print(f"Traduction : {translation.text}")
        return translation.text
    except Exception as e:
        print(f"Erreur lors de la traduction : {e}")
        return "Traduction non disponible"

Voice detection

import speech_recognition as sr

def record_audio():
    recognizer = sr.Recognizer()
    with sr.Microphone() as source:
        print("Parlez maintenant...")
        audio = recognizer.listen(source)
        try:
            text = recognizer.recognize_google(audio, language="fr-FR")
            print(f"Vous avez dit : {text}")
            return text
        except sr.UnknownValueError:
            print("Désolé, je n'ai pas compris.")
        except sr.RequestError as e:
            print(f"Erreur de service : {e}")

Witai params:
You must go to the Meta API (Facebook) to create your token

import requests

WIT_AI_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

def send_to_wit(text):
    headers = {'Authorization': f'Bearer {WIT_AI_TOKEN}'}
    response = requests.get(f'https://api.wit.ai/message?v=20230414&q={text}', headers=headers)
    return response.json()

The main file

from flask import Flask, request, jsonify
from convertion_audio_to_text import speak_translation
from translation import translate_text
from voice_detection import record_audio
from witai_params import send_to_wit
import Levenshtein

app = Flask(__name__)

# Langues disponibles
AVAILABLE_LANGUAGES = {
    "sw": "Swahili",
    "wo": "Wolof",
    "fon": "Fon",
    "en": "Anglais",
    "fr": "Français"
}

def calculate_score(reference_text, user_text):
    similarity = Levenshtein.ratio(reference_text.lower(), user_text.lower()) * 100
    return round(similarity, 2)

@app.route('/available_languages', methods=['GET'])
def available_languages():
    """Retourne les langues disponibles pour la traduction."""
    return jsonify(AVAILABLE_LANGUAGES)


@app.route('/process_audio', methods=['POST'])
def process_audio():
    """Traite l'audio, traduit le texte et évalue la prononciation."""
    try:
        # Étape 1 : Récupérer la langue cible depuis la requête
        target_lang = request.json.get('target_lang')

        if not target_lang:
            return jsonify({"error": "Paramètre 'target_lang' manquant"}), 400

        if target_lang not in AVAILABLE_LANGUAGES:
            return jsonify({
                "error": f"Langue cible '{target_lang}' non supportée.",
                "available_languages": AVAILABLE_LANGUAGES  # Retourner la liste des langues disponibles
            }), 400

        # Étape 2 : Traduire le texte initial
        text = record_audio()
        if not text:
            return jsonify({"error": "No audio detected or transcription failed"}), 400

        wit_response = send_to_wit(text)
        print("Wit.ai Response:", wit_response)

        translation = translate_text(text, target_lang)
        speak_translation(translation, lang=target_lang)

        # Étape 3 : Boucle de répétition pour évaluer la prononciation
        score = 0
        while score = 80:
                message = "Bravo! Félicitations, vous êtes un génie!"
                return jsonify({
                    "original_text": text,
                    "wit_response": wit_response,
                    "translated_text": translation,
                    "repeated_text": repeat_text,
                    "score": score,
                    "message": message
                }), 200
            elif score 



<p>Designing a bot is becoming easier and easier today to solve complex problems in our daily lives. However, this does not exclude the importance of learning languages ​​on your own. The use of technologies like BotAI for instant voice translation should primarily serve to enrich our interactions in complex contexts. By combining these tools with personal language learning, we promote more effective communication while promoting individual linguistic wealth.</p>

<p>The code is available here <br>
on my github</p>


          

            
        

The above is the detailed content of How to create a voice translation bot with witai. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

How are arrays used in image processing with Python?How are arrays used in image processing with Python?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

For what types of operations are arrays significantly faster than lists?For what types of operations are arrays significantly faster than lists?May 07, 2025 am 12:01 AM

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.