play.py 13.3 KB
Newer Older
Christian Orellana's avatar
Christian Orellana committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
#!/usr/bin/python
# -*- coding: utf-8 -*-

import cgi, cgitb, os, sys, subprocess, json, urllib
from datetime import datetime
from random import randrange
from urllib.request import urlopen
import subprocess

#from urlparse import urlparse, parse_qs
try:
    from urllib.parse import urlparse
    from urllib.parse import parse_qs
except ImportError:
    from urlparse import urlparse, parse_qs

UPLOAD_DIR = 'files/sessions'
if not os.path.isdir(UPLOAD_DIR):
    cmd = 'mkdir -p "' + UPLOAD_DIR + '"'
    stream = os.popen(cmd)

form = cgi.FieldStorage()

def print_html_head():
    print ('Content-Type: text/html; charset=UTF-8')
    print ('')
    print ('''
    <html>
    <head>
      <title>Upload File</title>
    </head>
    <body>
''')

def print_json_head():
    print ("Content-Type: application/json; charset=UTF-8\n")

def print_form():
    print ('''
  <h1>Upload File</h1>
  <form action="play.py" method="POST" enctype="multipart/form-data">
	Pass: <input name="pass" type="password"><br><br>
    File: <input name="file" type="file">
    <br><br>
    <input name="submit" type="submit">
  </form>
''')

def save_offsets():
    jstr = ''
    output = ''
    for key in form.keys():
        if key != 'action' and key != 'sessionid':
# Shift audio offset in json file
            fpath = os.path.join(UPLOAD_DIR, SESSIONID, key + ".16.json")
            value = float(form.getvalue(key))
            if os.path.isfile(fpath):
                    jstr = jstr + ', "' + key + '": ' + str(value)
                    f = open(fpath)
                    data = json.load(f)
                    data['offset'] = value
                    f.close()
                    json_object = json.dumps(data, indent=4)
                    with open(fpath, 'w') as fout:
                        fout.write (json_object)
# Now shift subtitles in vtt file
            fpath = os.path.join(UPLOAD_DIR, SESSIONID, key + ".16.vtt")
            if os.path.isfile(fpath):
                opath = os.path.join(UPLOAD_DIR, SESSIONID, key + ".16.orig.vtt")
# Copy original file for future shifts if it does not exist
                if not os.path.isfile(opath):
                    cmd = 'cp "' + fpath + '" "' + opath + '"'
                    stream = os.popen(cmd)
# Copy original file to new file for processing
                else:
                    cmd = 'cp "' + opath + '" "' + fpath + '"'
                    stream = os.popen(cmd)
# Do the actual shifting using pysubs2
                cmd = "shift"
                val = value
                if value < 0:
                    cmd = "shift-back"
                    val = -1 * value

                cmd = '/usr/local/bin/pysubs2 --' + cmd + ' ' + str(val) + 's "' + fpath + '"'
                stream = os.popen(cmd)
                output = stream.read()


    return '{"status": "OK" ' + jstr + '}' + output

def save_uploaded_file():
    if not 'file' in form:
        print ('{"status": "Error", "message": "No file"}')
        return
    form_file = form['file']
    if not form_file.file:
        print ('{"status": "Error", "message": "No file"}')
        return
    if not 'pass' in form:
        print ('{"status": "Error", "message": "No pass"}')
        return
    form_pass = form['pass'].value
    if not form_pass or (form_pass != 'stadionalle'):
        print ('{"status": "Error", "message": "Please provide a valid pass"}')
        return
    if not form_file.filename:
        print ('{"status": "Error", "message": "No file name"}')
        return
    if not ( form_file.filename.endswith(".wav")
             or form_file.filename.endswith(".mp4")
             or form_file.filename.endswith(".mp3") ):
        print ('{"status": "Error", "message": "No file name"}')
        return

    fname = os.path.basename(form_file.filename.replace(" ", "_"))
    fname = fname.replace(":", "-")
    uploaded_file_path = os.path.join(UPLOAD_DIR, fname)
    with open(uploaded_file_path, 'wb') as fout:
        i = 0
        mess = '{"status": "OK", "message": "File uploaded"}'
        while True:
            chunk = form_file.file.read(100 * 1024)
            if not chunk:
                break
            fout.write (chunk)
            i = i+1
            if i>10 * 20:
                mess = '{"status": "Error", "message": "File is too big (> 20mb)"}'
                fout.close
                cmd = 'cd ' + UPLOAD_DIR + ' && rm "' + fname+ '"'
                stream = os.popen(cmd)
                break
        print (mess)
    # try:
	#     subprocess.check_output(['/bin/bash', '/home/stabile/upload/s3.sh', 'files/' + form_file.filename.replace(" ", "_")])
    # except subprocess.CalledProcessError:
    # 	print "Got an error"
    #
    # print ('<h1>Completed S3 upload</h1>')

def list_files(path):
    datetime_object = datetime.fromtimestamp(os.path.getmtime(path))
    d = {'name': os.path.basename(os.path.splitext(path)[0]), 'date':datetime_object.strftime("%d/%m/%Y, %H:%M:%S"), 'action': '', 'lang': '', 'offset': 0}
    if os.path.isdir(path):
        d['type'] = "directory"
        d['size'] = 0
        d['children'] = []
        for x in os.listdir (path):
            type = os.path.splitext(x)[1][1:]
            if os.path.isdir(os.path.join(path, x)): # Stop recursion
                d['children'].append({'name': x, 'type': 'directory', 'size': 0, 'date': 0, 'lang': ''})
            if (type == 'mp4' or type == 'mp3' or type == 'wav') and not '.16.wav' in x:
                d['children'].append(list_files(os.path.join(path, x)))
    else:
        file_size = os.path.getsize(path)
        type = os.path.splitext(path)[1][1:]
        d['offset'] = 0
        if type == 'wav' and os.path.isfile(path.replace(".wav", ".16.vtt")):
            d['processed'] = True
        if type == 'mp3' and os.path.isfile(path.replace(".mp3", ".16.vtt")):
            d['processed'] = True
        if type == 'wav' and os.path.isfile(path.replace(".wav", ".16.json")):
            f = open(path.replace(".wav", ".16.json"))
            data = json.load(f)
            d['lang'] = data['language']
            if "offset" in data:
                d['offset'] = data['offset']
            f.close()
        if type == 'mp3' and os.path.isfile(path.replace(".mp3", ".16.json")):
            f = open(path.replace(".mp3", ".16.json"))
            data = json.load(f)
            d['lang'] = data['language']
            if "offset" in data:
                d['offset'] = data['offset']
            f.close()
        d['type'] = type
        d['size'] = file_size
    return d

def delete_file(file):
    file = file.replace("..", "") # a bit of sanitizing
    file = file.replace("/", "")
    msg = ""
    status = "Error"
    type = os.path.splitext(file)[1][1:]
    try:
        subprocess.check_output(['/usr/bin/rm', UPLOAD_DIR + "/" + file])
        fname = ''
        if type == 'wav' and os.path.isfile(UPLOAD_DIR + "/" + file.replace('.wav', '.16.wav')):
            fname = file.replace('.wav','')
        if type == 'mp3' and os.path.isfile(UPLOAD_DIR + "/" + file.replace('.mp3', '.16.wav')):
            fname = file.replace('.mp3','')
        if fname != '':
            subprocess.check_output(['/usr/bin/rm', UPLOAD_DIR + "/" + fname + '.16.wav'])
            subprocess.check_output(['/usr/bin/rm', UPLOAD_DIR + "/" + fname + '.16.json'])
            subprocess.check_output(['/usr/bin/rm', UPLOAD_DIR + "/" + fname + '.16.vtt'])
            subprocess.check_output(['/usr/bin/rm', UPLOAD_DIR + "/" + fname + '.16.srt'])
            subprocess.check_output(['/usr/bin/rm', UPLOAD_DIR + "/" + fname + '.16.txt'])
            subprocess.check_output(['/usr/bin/rm', UPLOAD_DIR + "/" + fname + '.16.tsv'])
        status = "OK"
        msg = file + " was removed"
    except subprocess.CalledProcessError:
        msg = "Got an error"
    return '{"status": "' + status + '", "message": "' + msg + '"}'

def download_video():
    msg = ""
    status = "Error"
    purl = "https://pixabay.com/api/videos/?key=36793478-80856bd1430647d240abec315&q=soccer"
    try:
        data = urlopen(purl).read()
        jdata = json.loads(data)
        url = jdata['hits'][randrange(20)]['videos']['medium']['url']
        cmd = 'cd ' + UPLOAD_DIR + ' && curl -k -L -O -J "' + url + '"'
        stream = os.popen(cmd)
        output = stream.read()
        status = "OK"
        msg = url + " was downloaded. " + output
    except subprocess.CalledProcessError:
        msg = "Got an error"
    return '{"status": "' + status + '", "message": "' + msg + '", "url": "' + url + '"}'

def download_audio():
    cmd = './podcast.sh'
    stream = os.popen(cmd)
    purl = stream.read()
    try:
        filename = "audio" + str(randrange(1000))
        cmd = 'cd ' + UPLOAD_DIR + ' && wget -O "' + filename + '.mp3" "' + purl + '"'
#        subprocess.run([cmd])
        stream = os.popen(cmd)
        output = stream.read()
        cmd = 'ffmpeg -ss 20 -to 50 -i "' + UPLOAD_DIR + '/' + filename + '.mp3" "' + UPLOAD_DIR + '/' + filename + '-30.mp3"'
#        subprocess.run([cmd])
        stream = os.popen(cmd)
        output = stream.read()
        os.remove(UPLOAD_DIR + '/' + filename + '.mp3')
        status = "OK"
        msg = purl + " was downloaded. " + output
    except subprocess.CalledProcessError:
        msg = "Got an error"
    return '{"status": "' + status + '", "message": "' + msg + '", "url": "' + purl + '"}'

def process_audio(file):
    file = file.replace("..", "") # a bit of sanitizing
    file = file.replace("/", "")
    msg = ""
    status = "Error"
    try:
        file16 = file.replace("wav","16.wav")
        file16 = file16.replace("mp3","16.wav")
        cmd = 'echo -y | /usr/bin/ffmpeg -i "' + UPLOAD_DIR + '/' + file + '" -acodec pcm_s16le -ac 1 -ar 16000 "' + UPLOAD_DIR + '/' + file16 + '"'
#        os.system(cmd)
        stream = os.popen(cmd)
#        output = stream.read()
        cmd = 'cd ' + UPLOAD_DIR +  '; /usr/local/bin/whisper "' + file16 + '"'
        stream = os.popen(cmd)
        status = "OK"
        msg = file + " was processed"
    except subprocess.CalledProcessError:
        msg = "Got an error"
    return '{"status": "' + status + '", "message": "' + msg + '"}'

cgitb.enable()
SESSIONID = ''
method = os.environ.get('REQUEST_METHOD', '')
query_string = os.environ.get('QUERY_STRING', '')
content_len = os.environ.get('CONTENT_LENGTH', '0')
args = parse_qs(query_string)

if method == 'POST':
    if not 'sessionid' in form:
        print_json_head()
        print ('{"status": "Error", "message": "No sessionid"}')
    else:
        SESSIONID = form['sessionid'].value
        if query_string:
            if args['action'] and args['action'][0] == 'saveoffsets':
                print_json_head()
                print (save_offsets() )
        else:
                UPLOAD_DIR = UPLOAD_DIR + "/" +  SESSIONID
                print_json_head()
                save_uploaded_file()
elif method == 'GET':
    if 'action' in args and args['action'] == ['listsessions']:
        print_json_head()
        print (json.dumps(list_files(UPLOAD_DIR)))
    else:
        if not 'sessionid' in args:
            print_json_head()
            print ('{"status": "Error", "message": "No sessionid"}')
        else:
            if args['sessionid'] == '':
                print_json_head()
                print ('{"status": "Error", "message": "Empty sessionid"}')
            else:
                SESSIONID = args['sessionid'][0]
                SESSIONID =  SESSIONID.replace(".", "")
                SESSIONID =  SESSIONID.replace("/", "-")
                SESSIONID =  SESSIONID.replace(" ", "-")
                UPLOAD_DIR = UPLOAD_DIR + "/" + SESSIONID
                if 'action' in args:
                    if args['action'] == ['createsession']:
                        print_json_head()
                        if os.path.isdir(UPLOAD_DIR + "/" + SESSIONID):
                            print ('{"status": "Error", "message": "Session with this name already exists"}')
                        else:
                            subprocess.check_output(['mkdir', UPLOAD_DIR])
                            print ('{"status": "OK", "message": "Session created", "sessionid": "' + SESSIONID + '"}')
                    if args['action'] == ['deletesession']:
                        print_json_head()
                        if not os.path.isdir(UPLOAD_DIR):
                            print ('{"status": "Error", "message": "Session with this does not exist: ' + SESSIONID + '"}')
                        else:
                            stream = os.popen('rm -rf ' + UPLOAD_DIR)
                            print ('{"status": "OK", "message": "Session deleted", "sessionid": "' + SESSIONID + '"}')
                    elif args['action'] == ['list']:
                        print_json_head()
                        print (json.dumps(list_files(UPLOAD_DIR)) )
                    elif args['action'] == ['downloadvideo']:
                        print_json_head()
                        print (download_video() )
                    elif args['action'] == ['downloadaudio']:
                        print_json_head()
                        print (download_audio() )
                    elif args['action'] == ['deletefile']:
                        print_json_head()
                        print (delete_file(args['file'][0]) )
                    elif args['action'] == ['processaudio']:
                        print_json_head()
                        print (process_audio(args['file'][0]) )
                else:
                    print_html_head()
                    print_form()