Witaiで音声翻訳ボットを作成する方法
グローバル化した世界では、言語の境界を越えたコミュニケーションがこれまで以上に重要になっています。この記事では、コミュニケーションをより包括的で誰もが利用できるようにするために、このテクノロジーを実装する方法を検討します。
コードはここから入手できます
私のgithubで
最初に行うことは、依存関係をインストールすることです
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
音声からテキストへの変換
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 クラウド テキスト音声
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")
翻訳
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"
音声検出
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 パラメータ:
トークンを作成するには、メタ API (Facebook) にアクセスする必要があります
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()
メインファイル
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: repeat_text = record_audio() if not repeat_text: return jsonify({"error": "No repeated audio detected"}), 400 score = calculate_score(translation, repeat_text) if 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 < 45: message = "Votre score est faible, améliorez-vous en vous entraînant." else: message = "Pas mal! Vous pouvez encore améliorer." return jsonify({ "translated_text": translation, "repeated_text": repeat_text, "score": score, "message": message, "retry": True }) except Exception as e: return jsonify({"error": str(e)}), 500 if __name__ == '__main__': app.run(debug=True) """ tu peux tester avec ce code dans le navigateur, tu decommente, puis tu le met la ou il faut @app.route('/process_audio', methods=['GET', 'POST']) def process_audio(): if request.method == 'GET': return jsonify({"message": "Utilisez une requête POST pour traiter l'audio."}) # Continue avec la logique POST try: 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) target_lang = request.json.get('target_lang', 'sw') translation = translate_text(text, target_lang) speak_translation(translation, lang=target_lang) return jsonify({ "original_text": text, "wit_response": wit_response, "translated_text": translation }), 200 except Exception as e: return jsonify({"error": str(e)}), 500 """
今日、日常生活における複雑な問題を解決するために、ボットの設計がますます簡単になってきています。ただし、これは独学で言語を学ぶことの重要性を排除するものではありません。 BotAI のようなテクノロジーを利用して即時音声翻訳を行うことは、主に複雑な状況における対話を豊かにするために役立つはずです。これらのツールを個人の言語学習と組み合わせることで、個人の言語の豊かさを促進しながら、より効果的なコミュニケーションを促進します。
コードはここから入手できます
私のgithubで
以上がWitaiで音声翻訳ボットを作成する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











Pythonは学習と使用が簡単ですが、Cはより強力ですが複雑です。 1。Python構文は簡潔で初心者に適しています。動的なタイピングと自動メモリ管理により、使いやすくなりますが、ランタイムエラーを引き起こす可能性があります。 2.Cは、高性能アプリケーションに適した低レベルの制御と高度な機能を提供しますが、学習しきい値が高く、手動メモリとタイプの安全管理が必要です。

Pythonを1日2時間学ぶだけで十分ですか?それはあなたの目標と学習方法に依存します。 1)明確な学習計画を策定し、2)適切な学習リソースと方法を選択します。3)実践的な実践とレビューとレビューと統合を練習および統合し、統合すると、この期間中にPythonの基本的な知識と高度な機能を徐々に習得できます。

Pythonは開発効率でCよりも優れていますが、Cは実行パフォーマンスが高くなっています。 1。Pythonの簡潔な構文とリッチライブラリは、開発効率を向上させます。 2.Cのコンピレーションタイプの特性とハードウェア制御により、実行パフォーマンスが向上します。選択を行うときは、プロジェクトのニーズに基づいて開発速度と実行効率を比較検討する必要があります。

PythonとCにはそれぞれ独自の利点があり、選択はプロジェクトの要件に基づいている必要があります。 1)Pythonは、簡潔な構文と動的タイピングのため、迅速な開発とデータ処理に適しています。 2)Cは、静的なタイピングと手動メモリ管理により、高性能およびシステムプログラミングに適しています。

PythonListSarePartOfThestAndardarenot.liestareBuilting-in、versatile、forStoringCollectionsのpythonlistarepart。

Pythonは、自動化、スクリプト、およびタスク管理に優れています。 1)自動化:OSやShutilなどの標準ライブラリを介してファイルバックアップが実現されます。 2)スクリプトの書き込み:Psutilライブラリを使用してシステムリソースを監視します。 3)タスク管理:スケジュールライブラリを使用してタスクをスケジュールします。 Pythonの使いやすさと豊富なライブラリサポートにより、これらの分野で優先ツールになります。

科学コンピューティングにおけるPythonのアプリケーションには、データ分析、機械学習、数値シミュレーション、視覚化が含まれます。 1.numpyは、効率的な多次元配列と数学的関数を提供します。 2。ScipyはNumpy機能を拡張し、最適化と線形代数ツールを提供します。 3. Pandasは、データ処理と分析に使用されます。 4.matplotlibは、さまざまなグラフと視覚的な結果を生成するために使用されます。

Web開発におけるPythonの主要なアプリケーションには、DjangoおよびFlaskフレームワークの使用、API開発、データ分析と視覚化、機械学習とAI、およびパフォーマンスの最適化が含まれます。 1。DjangoandFlask Framework:Djangoは、複雑な用途の迅速な発展に適しており、Flaskは小規模または高度にカスタマイズされたプロジェクトに適しています。 2。API開発:フラスコまたはdjangorestFrameworkを使用して、Restfulapiを構築します。 3。データ分析と視覚化:Pythonを使用してデータを処理し、Webインターフェイスを介して表示します。 4。機械学習とAI:Pythonは、インテリジェントWebアプリケーションを構築するために使用されます。 5。パフォーマンスの最適化:非同期プログラミング、キャッシュ、コードを通じて最適化
