How to retrieve mediainfo from raw data in Flask app?

104 Views Asked by At

I'm uploading an audio file via Flask's FileField form and I want to get to its mediainfo. Uploaded audio is available in the form of bytrs.

To obtain a path for pydub.utils.mediainfo function, I was trying:

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    audiofile = form.file.data.read()
    # type(audiofile) == bytes

    with tempfile.NamedTemporaryFile(mode='w+b', suffix='.mp3') as tmp:
        tmp.write(audiofile)
        # tmp.name == C:\Users\JUSTME~1\AppData\Local\Temp\tmp0wky2_wq.mp3
        print(pydub.utils.mediainfo(tmp.name))

But pydub.utils.mediainfo returns an empty dict object. Is it possible to solve the problem?

Inspired by this quastion.

2

There are 2 best solutions below

1
sakiodre On BEST ANSWER

The issue is that you're trying to read from a file that is also being written to. You can try to use tempfile.mkstemp instead:

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    audiofile = form.file.data.read()

    fd, path = tempfile.mkstemp(suffix='.mp3')

    try:
        with os.fdopen(fd, 'wb') as tmp:
            tmp.write(audiofile)

        print(pydub.utils.mediainfo(path))
    finally:
        # Manually clean up the temporary file
        os.remove(path)
0
Adarsh puri On

In a Flask app, use the python-mediainfo library to retrieve media information from raw data. Parse raw data with BytesIO, then use MediaInfo.parse() to extract details. Handle file uploads or direct data input, facilitating dynamic media analysis in your Flask application.