abhi2400's picture
Upload folder using huggingface_hub
04f98c3 verified
from flask import Flask, request, jsonify
import speech_recognition as sr
from deep_translator import GoogleTranslator
from gtts import gTTS
import pygame
import os
app = Flask(__name__)
recognizer = sr.Recognizer()
microphone = sr.Microphone()
audio_data = None
translated_text_global = ""
@app.route('/start-recording', methods=['POST'])
def start_recording():
global audio_data
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio_data = recognizer.listen(source)
return "Recording started..."
@app.route('/stop-recording', methods=['POST'])
def stop_recording():
global audio_data, translated_text_global
if audio_data is None:
return jsonify({"recognizedText": "", "translatedText": "No recording found. Please try again."})
target_language = request.json.get('targetLanguage')
try:
text = recognizer.recognize_google(audio_data)
translated_text = translate_text(text, target_language)
translated_text_global = translated_text
return jsonify({"recognizedText": text, "translatedText": translated_text})
except sr.UnknownValueError:
return jsonify({"recognizedText": "", "translatedText": "Sorry, I could not understand your speech."})
except sr.RequestError as e:
return jsonify({"recognizedText": "", "translatedText": f"Could not request results; {e}"})
@app.route('/speak-translation', methods=['POST'])
def speak_translation():
global translated_text_global
target_language = request.json.get('targetLanguage')
if translated_text_global:
tts = gTTS(text=translated_text_global, lang=target_language)
tts.save("translated_audio.mp3")
pygame.mixer.init()
pygame.mixer.music.load("translated_audio.mp3")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
pygame.mixer.music.unload()
os.remove("translated_audio.mp3")
return "Speaking translated text..."
else:
return "No translated text available to speak."
@app.route('/get-supported-languages', methods=['GET'])
def get_supported_languages():
languages = GoogleTranslator().get_supported_languages(as_dict=True)
return jsonify(languages)
def translate_text(input_text, target_language):
translator = GoogleTranslator(source='auto', target=target_language)
translated = translator.translate(text=input_text)
return translated
if __name__ == '__main__':
app.run(debug=True)