0

I get litteraly mad about my issue.

what i'm trying to do :

  • upload a ".flac" file to my server (it works)
  • use à php script to launch à python script (doesn't work)
  • Python script call the google speech API to convert voice to text (work when launched directely from terminal
  • Insert in data base the result of my python processing (it works)

I tried with exec() system() and passthru() command.

I search hours long on internet to find a solution, and i'm definitively blocked at the point that my php doesn't seems to wait for my python proceesing to occur (between 10 sec and 5 min).

when i try with another python script that only insert value in database everything works fine, that let me really suppose that my php exec() kill my python process before end or something like that. So my code is as following.

PHP code:

<?php
#Define target of uploaded file
$target_dir = "/var/www/voice/voice_file/";

#create unique new name for file
$var_name = md5(uniqid(rand(), true));

#define file extension for new file
$var_name .= ".flac";

#define (temporalily) comment value --> will be replaced by form "comment"
$commentaire = "\"test d'un commentaire\"";

# define target
$target_file = $target_dir . basename($var_name);


#moove flac file to target
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);


#execute python script to convert audio to text
ob_start();
passthru("python voice_file/convert_audio.py $target_file $commentaire");
$output = ob_get_clean();

?>

Python script.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 17 14:09:32 2017

@author: flo-linux
"""
###### parameters ###########
from pydub import AudioSegment
import MySQLdb as my
#from pydub.utils import mediainfo
from pydub.utils import make_chunks
import math
import speech_recognition as sr
import os
import sys
#################################
#%%########define variables######

commentaire_result=str(sys.argv[2])
text_result =""
GOOGLECREDENTIALS = r"""{MYAPIGOOGLECREDENTIALS}"""

####### Format audio file and grep audio parameters #####

flac_audio = AudioSegment.from_file(sys.argv[1], "flac")    
flac_audio.export("short.wav", format="wav")                
myaudio = AudioSegment.from_file("short.wav" , "wav")        
channel_count = myaudio.channels    #Get channels
sample_width = myaudio.sample_width #Get sample width
duration_in_sec = len(myaudio) / 1000 #Length of audio in sec
sample_rate = myaudio.frame_rate
bit_rate =16   
wav_file_size = (sample_rate * bit_rate * channel_count * duration_in_sec) / 8


#%%## Split audio for Google API limitataion #############

file_split_size = 10000000  # 10Mb OR 10, 000, 000 bytes
total_chunks =  wav_file_size // file_split_size + 1


chunk_length_in_sec = math.ceil((duration_in_sec * 10000000 ) /wav_file_size)   #in sec
chunk_length_ms = chunk_length_in_sec * 1000
chunks = make_chunks(myaudio, chunk_length_ms)


#%%##Export all of the individual chunks as wav files #######


for i, chunk in enumerate(chunks):
    chunk_name = "chunk{0}.flac".format(i)
    chunk.export(chunk_name, format="flac")
    ## Process each chunk in google Speech API.
    r = sr.Recognizer()
    with sr.AudioFile(chunk_name) as source:
        audio = r.record(source)
        try:
            text_result += (r.recognize_google_cloud(audio, credentials_json=GOOGLECREDENTIALS,language="fr-FR"))

        except sr.UnknownValueError:
            text_result += ("Google Cloud Speech could not understand audio")
        except sr.RequestError as e:
            text_result += ("Could not request results from Google Cloud Speech service; {0}".format(e))
    os.remove (chunk_name)
os.remove(short.wav)

#%% Insert result of voice to text in data base ##########
db = my.connect(host="localhost",user="my_user", passwd="my_passwd", db="my_db")
cursor = db.cursor()
try:
    cursor.execute("INSERT into data (Comment, Result) values (%s,%s)",(commentaire_result, text_result))
    db.commit()
except:
   db.rollback()

db.close()

I'll really appreciate a hand. Thanks a lot

floprm
  • 72
  • 2
  • 11
  • Do you get any error message from php? You might have to need to use absolute paths. `/some/dir/convert_audio.py ...` The script should be executed with python3. If you call it like this: `python convert_audio.py`, you might be using python 2, if that's the system default. – Håken Lid Apr 22 '17 at 16:23
  • So if the script is executable, you don't need `python` in your exec statement. – Håken Lid Apr 22 '17 at 16:26
  • have you find the solution? I am facing same problem – Rajinder Feb 28 '18 at 10:59

0 Answers0