简体   繁体   中英

How can I run two different tasks of Flask simultaneously

I'm working on my flask project. First, Look at the below code.

def video_1() :
    try :
        # Response is used to display a flow of information
        #SER = speechEmotionRecognition()
        SER = speechEmotionRecognition()
        # Voice Recording
        rec_duration = 16 # in sec
        rec_sub_dir = os.path.join('tmp','voice_recording.wav')
        SER.voice_recording(rec_sub_dir, duration=rec_duration)
        
        return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame')
   
    except :
        return None

In the try block, the lines above the return statement should execute with the expression of the return statement. The lines before the return statement are used to record the audio while the last return statement is for real-time video capturing and saving emotions of each frame in a CSV file. I want to do both these processes at once like recording video and audio at the same time. How can I modify the code to do so?

I know the concept of threading I tried to make two processes and run them but it's still not working, Look at the below code:

@app.route('/fun1', methods=("POST", "GET"))
def fun1():
    SER = speechEmotionRecognition()
    rec_duration = 16
    rec_sub_dir = os.path.join('tmp','voice_recording.wav')
    SER.voice_recording(rec_sub_dir, duration=rec_duration)
    return None

@app.route('/fun2', methods=("POST", "GET"))
def fun2():
    return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame') 

@app.route('/video_1', methods=['POST'])
def video_1() :
    try :
        p1 = Process(target = fun1)
        p1.start()
        p2 = Process(target = fun2)
        p2.start()
        return "dummy"
    except :
        return None

As mentioned by Ayaan you can use threading or multiprocessing to perform tasks "simultaneously", BUT there a huge caveat here the Global Interpreter Lock (GIL).

The GIL prevents a single python process performing two tasks concurrently. Usually there's enough going on to cause things to block and control to pass between threads within a single process; however, what you want to do (record video and audio separately) will probably require separate processes.

You really should look for a library that has implemented this outside of Python, but this is the gist of how to start up another process:

from multiprocessing import Process
audio_process = Process(target=SER.voice_recording, args=[rec_sub_dir], kwargs={"duration": rec_duration})
audio_process.start()

You should probably add some process management around that.

Additionally, while using os.path is better than concatenating strings you could further modernize your code using pathlib . Pathlike objects include a lot of functionality and override the division method to allow them to be combined using / (as seen in the example below).

from pathlib import Path
recording_directory = Path('tmp')
audio_file = recording_directory / 'voice_recording.wav'

Lastly, please try to adhere to PEP8 .
Your class names should be camel case and start with a capital (if you can, then change speechEmotionRecognition to SpeechEmotionRecognition). Also, common variable should be snake case and lowercase (SER should be ser, but maybe using a descriptive word is better... speech_recognize perhaps?).

You can use the threading module or multiprocessing module in Python, I would check out both. Basically, what they do is well, they run multiple processes/functions at once, which is exactly what you wanna do. I believe there are a few extra steps if you wanna get that working with Flask, but yeah. Here's a tutorial on the threading module,https://www.tutorialspoint.com/python/python_multithreading.htm , and here's a tutorial on the multiprocessing module, https://www.geeksforgeeks.org/multiprocessing-python-set-1/

The problem has been resolved, I just used the below code

@app.route('/fun1', methods=("POST", "GET"))
def fun1():
    SER = speechEmotionRecognition()
    rec_duration = 16
    rec_sub_dir = os.path.join('tmp','voice_recording.wav')
    SER.voice_recording(rec_sub_dir, duration=rec_duration)
    return None

@app.route('/fun2', methods=("POST", "GET"))
def fun2():
    return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame') 

@app.route('/video_1', methods=['POST'])
def video_1() :
    try :
        p1 = Process(target = fun1)
        p1.start()
        p2 = Process(target = fun2)
        p2.start()
        return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame')
    except :
        return None

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM