#!/usr/bin/env python3
from flask import Flask, render_template, request, url_for

import random
import os
import fnmatch
import argparse
from moviepy.audio.io import AudioFileClip

from librosa.core import get_duration

BASE_DIR = os.path.relpath(os.path.curdir)
AUDIO_DIR = os.path.join(BASE_DIR, 'audios/')
STATIC_DIR = os.path.join(BASE_DIR, 'static/')
CLASSES = ["Не речь","Злость","Радость","Грусть","Нейтральная"]


## Returns duration of any media file using ffprobe
def media_duration(media_path):
    return get_duration(filename=media_path)

## Creating a list of every media file in the "media" directory
media_paths=[]

for root, dirnames, filenames in os.walk(AUDIO_DIR):
    for filename in fnmatch.filter(filenames, '*'):
        media_paths.append(os.path.join(root, filename))

media_paths = [item for item in media_paths if item.lower()[-4:] in ('.mp3','.mp4','.wav')]

# Initialize the Flask application
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0


# Define a route for the default URL, which loads the form
@app.route('/',methods=['POST','GET'])
def form():

    ## Dealing with form data from the last round, if applicable
    try:
        classname=request.form['classname']

        write_classname = request.form['button']
        audio_file_id=request.form['audio_file_id']
        start_time=request.form['start_time']
        output_csv_path=os.path.join(AUDIO_DIR,'output_table.csv')
        with open(output_csv_path,'a') as fo:
            label_duration = 1
            fo.write(audio_file_id + ',' + \
            str(float(start_time)) + ',' + \
            str(float(label_duration)) + ',' + \
            '''"''' + write_classname + '''"\n''')
    except:
        classname=''

    try:
        os.remove(os.path.join(STATIC_DIR,request.form['temp_wav_filename']))
    except:
        pass

    ## Launching new round
    if media_paths:
        media_path = random.choice(media_paths)
        audio_file_id = media_path.split('/')[-1][:-4]
        duration = media_duration(media_path)
        start_time = int((random.random()*(duration-5.0)))
        snd = AudioFileClip.AudioFileClip(media_path)
        temp_wav_filename = str(random.random())[2:] + '.wav'
        snd.subclip(start_time,start_time + 5).write_audiofile(os.path.join(STATIC_DIR, temp_wav_filename))
        response = render_template('form_audio.html', audio_file_id=audio_file_id, \
                    start_time=start_time, classname=classname, temp_wav_filename=temp_wav_filename, \
                    media_path=media_path, label_counts=CLASSES)
    else:
        response = 'Положите в /audios файлы перед запуском'
    return response


# Run the app
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Разметчик аудио')
    parser.add_argument('--port', default=8000, type=int, help='Порт')
    opt = parser.parse_args()

    app.run(threaded=True,
        host="0.0.0.0",
        port=opt.port
    )

#!/usr/bin/env python3
from flask import Flask, render_template, request, url_for

import random
import os
import fnmatch
import argparse
from moviepy.audio.io import AudioFileClip

from librosa.core import get_duration

BASE_DIR = os.path.relpath(os.path.curdir)
AUDIO_DIR = os.path.join(BASE_DIR, 'audios/')
STATIC_DIR = os.path.join(BASE_DIR, 'static/')
CLASSES = ["Не речь","Злость","Радость","Грусть","Нейтральная"]


## Returns duration of any media file using ffprobe
def media_duration(media_path):
    return get_duration(filename=media_path)

## Creating a list of every media file in the "media" directory
media_paths=[]

for root, dirnames, filenames in os.walk(AUDIO_DIR):
    for filename in fnmatch.filter(filenames, '*'):
        media_paths.append(os.path.join(root, filename))

media_paths = [item for item in media_paths if item.lower()[-4:] in ('.mp3','.mp4','.wav')]

# Initialize the Flask application
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0


# Define a route for the default URL, which loads the form
@app.route('/',methods=['POST','GET'])
def form():

    ## Dealing with form data from the last round, if applicable
    try:
        classname=request.form['classname']

        write_classname = request.form['button']
        audio_file_id=request.form['audio_file_id']
        start_time=request.form['start_time']
        output_csv_path=os.path.join(AUDIO_DIR,'output_table.csv')
        with open(output_csv_path,'a') as fo:
            label_duration = 1
            fo.write(audio_file_id + ',' + \
            str(float(start_time)) + ',' + \
            str(float(label_duration)) + ',' + \
            '''"''' + write_classname + '''"\n''')
    except:
        classname=''

    try:
        os.remove(os.path.join(STATIC_DIR,request.form['temp_wav_filename']))
    except:
        pass

    ## Launching new round
    if media_paths:
        media_path = random.choice(media_paths)
        audio_file_id = media_path.split('/')[-1][:-4]
        duration = media_duration(media_path)
        start_time = int((random.random()*(duration-5.0)))
        snd = AudioFileClip.AudioFileClip(media_path)
        temp_wav_filename = str(random.random())[2:] + '.wav'
        snd.subclip(start_time,start_time + 5).write_audiofile(os.path.join(STATIC_DIR, temp_wav_filename))
        response = render_template('form_audio.html', audio_file_id=audio_file_id, \
                    start_time=start_time, classname=classname, temp_wav_filename=temp_wav_filename, \
                    media_path=media_path, label_counts=CLASSES)
    else:
        response = 'Положите в /audios файлы перед запуском'
    return response


# Run the app
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Разметчик аудио')
    parser.add_argument('--port', default=8000, type=int, help='Порт')
    opt = parser.parse_args()

    app.run(threaded=True,
        host="0.0.0.0",
        port=opt.port
    )

#!/usr/bin/env python3 ## Returns duration of any media file using ffprobe ## Creating a list of every media file in the "media" directory # Initialize the Flask application # Define a route for the default URL, which loads the form ## Dealing with form data from the last round, if applicable " "\n ## Launching new round # Run the app