0

I'm trying to get the content out of the audio file using for loop to iterate through content of the file but what I get is the last line of the text. I'm sure the problem is in the main code which is main.py and I can't figure out what could go wrong. Here is some code:

from flask import Flask, render_template, request, redirect
from google.cloud import speech
import os

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'PATH'
app = Flask(__name__)

@app.route("/", methods=["GET", "POST"])
def index():        

    if request.method == "POST":
        if "file" not in request.files:
            return redirect(request.url)

        file = request.files["file"]
        if file.filename == "":
            return redirect(request.url)
          
        if file:
            client = speech.SpeechClient()

            config = speech.RecognitionConfig(
            encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
            sample_rate_hertz=8000,
            language_code="en-US",
            )  
         
            content = request.files['file'].read()
            audio = speech.RecognitionAudio(content=content)
            response = client.recognize(config=config, audio=audio)

            for result in response.results:
                text = result.alternatives[0].transcript
   
    return render_template('index.html', text=text)


if __name__ == "__main__":
    app.run(debug=True)
Adam
  • 13
  • 6

1 Answers1

0

The problem is in this line:

for result in response.results:
    text = result.alternatives[0].transcript

Text is always the last one. What you can do is append text to a list and return the list like this

lines = []
for result in response.results:
    text = result.alternatives[0].transcript
    lines.append(text)

And change the return to

return render_template('index.html', text=lines)

And don't forget to add a for loop in your jinja template to work with the returned list.

gittert
  • 1,238
  • 2
  • 7
  • 15