Ejemplo n.º 1
0
def audio_matching(audio, folder):
    '''find matching video files for audio and define the video resolution'''
    ### Get Values ###
    values = 'static/audioClips' + folder + '/values.txt'

    with open(values) as f:
        duration = f.readline().strip()
        arousal_string = f.readline().strip()
        valence_string = f.readline().strip()

    arousal = [float(value.strip()) for value in arousal_string.split(', ')]
    valence = [float(value.strip()) for value in valence_string.split(', ')]

    ########## Matching ##########
    matching_method = session['files']['matching']

    if "approx" in matching_method:
        mode = "standard" if matching_method == "approx" else "mse"

        if matching_method == "approx_w":
            mode = "weighted"

        matching_files, matching_indexes = approximation_matching(
            folder, "audio", mode)

    elif "offline" in matching_method:
        mode = "standard" if matching_method == "offline" else "mse"

        if matching_method == "offline_w":
            mode = "weighted"

        matching_files, matching_indexes = offline_matching(
            folder, "audio", mode)

    else:
        matching_files, matching_indexes = random_matching(folder, "audio")

    for i in range(0, len(matching_files)):
        matching_files[i] = encode(matching_files[i])

    session['files'] = {
        'matching_files': matching_files,
        'matching_indexes': matching_indexes
    }

    ########## Get video resolution ##########
    max_width = 0.0
    max_height = 0.0

    for video in session['files']['matching_files']:
        props = get_video_properties('static/datasets/video/' + decode(video) +
                                     '.mp4')
        if props['width'] > max_width:
            max_width = props['width']
        if props['height'] > max_height:
            max_height = props['height']

    resolution = {"width": max_width, "height": max_height}

    return merge_audio_result(audio, resolution)
def display_encrypted(txt,ent):
	print ("Encrypted Message")
	txt.configure(state='normal')
	txt.delete(1.0, TK.END )
	txt.update()
	txt.insert(TK.CURRENT , encryption.encode(ent.get()))
	txt.configure(state='disabled')
Ejemplo n.º 3
0
def getstarted():
    if current_user.is_authenticated:
        u = current_user.user_auth
        if u.credentials == 1:
            key = decode(u.api_key)
            print key
        else:
            key = " "
        if request.method == 'POST':
            if request.form.get('key'):
                if (request.form.get('key').startswith('sk_live') or request.form.get('key').startswith('sk_test'))\
                        and len(request.form.get('key')) == 32:
                    u.api_key = encode(request.form.get('key'))
                    u.credentials = 1
                    session['api_key'] = request.form.get('key')
                    db.session.commit()

                    #flash(_('Successfully updated API credentials'), 'success')
                    stripe.api_key = session['api_key']
                    events, current, per, churn, ltv = run()
                    return render_template('pages/index.html',
                                           events=events,
                                           mrr=current[0],
                                           refunds=current[1],
                                           net_revenue=current[2],
                                           annual=current[3],
                                           customers=current[4],
                                           new_customers=current[5],
                                           arpu=current[6],
                                           canceled=current[7],
                                           upgrades=current[8],
                                           downgrades=current[9],
                                           mrrP=per[0],
                                           refundsP=per[1],
                                           net_revenueP=per[2],
                                           annualP=per[3],
                                           customersP=per[4],
                                           new_customersP=per[5],
                                           arpuP=per[6],
                                           canceledP=per[7],
                                           upgradesP=per[8],
                                           downgradesP=per[9],
                                           churn=churn,
                                           ltv=ltv)
                else:
                    u.credentials = 0
                    session['api_key'] = ""
                    db.session.commit()
                    flash(
                        _('Your API credentials were invalid, please enter them again.'
                          ), 'error')
                    return render_template('pages/getstarted.html')
            else:
                flash(_('API credentials required.'), 'error')
                return render_template('pages/getstarted.html')

        return render_template('pages/getstarted.html', key=key)
    else:
        return redirect(url_for('user.login'))
Ejemplo n.º 4
0
def charge():
    # Set the api key to Simple Metrics to create the customer and charge their card
    stripe.api_key = stripe_keys['secret_key']

    if current_user.is_authenticated:
        if current_user.user_auth.paying == 0:
            plan = request.form.get('plan')
            email = current_user.email

            customer = stripe.Customer.create(
                email=email,
                card=request.form['stripeToken']
            )

            # Create plan
            customer.subscriptions.create(plan=plan)

            # Write customer to db
            current_user.user_auth.customer = encode(customer.id)
            current_user.user_auth.paying = 1
            current_user.user_auth.plan = plan

            db.session.commit()

            send_welcome_email(email, plan.title())

            # Reset the stripe key
            stripe.api_key = ""

            flash(_('You have successfully signed up! Please enter your Stripe credentials below.'), 'success')
            return render_template('pages/getstarted.html')
        else:
            plan = request.form.get('plan')
            email = current_user.email

            #change the customer's plan
            customer = stripe.Customer.retrieve(decode(current_user.user_auth.customer))
            subscription = customer.subscriptions.retrieve(customer.subscriptions.data[0].id)
            subscription.plan = plan
            subscription.save()

            #update the db
            current_user.user_auth.plan = plan

            db.session.commit()

            flash(_('You have successfully switched to the ' + plan.title() + " plan."), 'success')
            send_plan_change_email(email, plan.title())

            # Reset the stripe key
            stripe.api_key = ""

            return render_template('pages/index.html')

    else:
        flash(_('Please login first.'), 'error')
        return render_template('pages/index.html')
Ejemplo n.º 5
0
def reset_camera():
    '''resetting the camera'''
    global video_camera

    if video_camera != None:
        if video_camera.name != None:
            session['files'] = {
                'recording_name': encode(video_camera.name),
                'matching': session['files']['matching']
            }
        video_camera = None
Ejemplo n.º 6
0
def video_matching(video, folder):
    '''Find matching audi files for video'''
    ########## Get values ##########
    values = 'static/frames' + folder + '/values.txt'

    with open(values) as f:
        duration = f.readline().strip()
        arousal_string = f.readline().strip()
        valence_string = f.readline().strip()

    arousal = [float(value.strip()) for value in arousal_string.split(', ')]
    valence = [float(value.strip()) for value in valence_string.split(', ')]

    ########## Matching ##########
    matching_method = session['files']['matching']

    if "approx" in matching_method:
        mode = "standard" if matching_method == "approx" else "mse"

        if matching_method == "approx_w":
            mode = "weighted"

        matching_files, matching_indexes = approximation_matching(
            folder, "video", mode)

    elif "offline" in matching_method:
        mode = "standard" if matching_method == "offline" else "mse"

        if matching_method == "offline_w":
            mode = "weighted"

        matching_files, matching_indexes = offline_matching(
            folder, "video", mode)

    else:
        matching_files, matching_indexes = random_matching(folder, "video")

    for i in range(0, len(matching_files)):
        matching_files[i] = encode(matching_files[i])

    session['files'] = {
        'matching_files': matching_files,
        'matching_indexes': matching_indexes
    }

    return merge_video_result(video)
Ejemplo n.º 7
0
def confirm_recording():
    '''rout to watch and confirm webcam recording'''
    reset_camera()
    if request.user_agent.browser == 'safari':
        return render_template('page_not_found.html')

    if not 'files' in session or not 'recording_name' in session[
            'files'] or not 'matching' in session['files']:
        return render_template('no_access.html')

    recording = decode(session['files']['recording_name'])
    session['files'] = {'matching': session['files']['matching']}
    encoded = encode(recording)

    return render_template("confirm_recording.html",
                           recording=recording,
                           encoded=encoded)
Ejemplo n.º 8
0
def getstarted():
    if current_user.is_authenticated:
        u = current_user.user_auth
        if u.credentials == 1:
            key = decode(u.api_key)
            print key
        else:
            key = " "
        if request.method == 'POST':
            if request.form.get('key'):
                if (request.form.get('key').startswith('sk_live') or request.form.get('key').startswith('sk_test'))\
                        and len(request.form.get('key')) == 32:
                    u.api_key = encode(request.form.get('key'))
                    u.credentials = 1
                    session['api_key'] = request.form.get('key')
                    db.session.commit()

                    #flash(_('Successfully updated API credentials'), 'success')
                    stripe.api_key = session['api_key']
                    events, current, per, churn, ltv = run()
                    return render_template('pages/index.html', events=events, mrr=current[0], refunds=current[1],
                                           net_revenue=current[2],
                                           annual=current[3], customers=current[4], new_customers=current[5],
                                           arpu=current[6],
                                           canceled=current[7], upgrades=current[8], downgrades=current[9], mrrP=per[0],
                                           refundsP=per[1],
                                           net_revenueP=per[2], annualP=per[3], customersP=per[4],
                                           new_customersP=per[5], arpuP=per[6],
                                           canceledP=per[7], upgradesP=per[8], downgradesP=per[9], churn=churn, ltv=ltv)
                else:
                    u.credentials = 0
                    session['api_key'] = ""
                    db.session.commit()
                    flash(_('Your API credentials were invalid, please enter them again.'), 'error')
                    return render_template('pages/getstarted.html')
            else:
                flash(_('API credentials required.'), 'error')
                return render_template('pages/getstarted.html')

        return render_template('pages/getstarted.html', key=key)
    else:
        return redirect(url_for('user.login'))
Ejemplo n.º 9
0
Archivo: Esim.py Proyecto: wanggor/afis
    def send(self):

        config =  self.get_config()   
        code = self.ui.lineEdit_code_send.text()
        msg = encryption.encode(code, self.ui.textEdit_msg_send.toPlainText())
        # url = "http://192.168.4.1/text?="+msg #AFIS 1.0
        
        # url = "http://192.168.4.1/text?2"+str(config["mode"])+str(config["color"])+msg
        # self.senderHttp = sender.SendHttp(parent=self, url=url)
        # self.senderHttp.respon.connect(self.getRespon)
        # self.senderHttp.start()
        # self.ui.pushButton_send.setEnabled(False)

        baudrate = int(self.ui.lineEdit_baudrate.text())
        port = self.ui.comboBox_port.currentText()

        self.senderSerial= sender.SendSerial(parent=self, port=port, baudrate=baudrate, msg=msg)
        self.senderSerial.respon.connect(self.getRespon)
        self.senderSerial.start()
        self.ui.pushButton_send.setEnabled(False)
Ejemplo n.º 10
0
 def helper_assert(self, w, expected_result):
     result = ecp.encode(w)
     self.assertEqual(expected_result, result)
Ejemplo n.º 11
0
def charge():
    # Set the api key to Simple Metrics to create the customer and charge their card
    stripe.api_key = stripe_keys['secret_key']

    if current_user.is_authenticated:
        if current_user.user_auth.paying == 0:
            plan = request.form.get('plan')
            email = current_user.email

            customer = stripe.Customer.create(email=email,
                                              card=request.form['stripeToken'])

            # Create plan
            customer.subscriptions.create(plan=plan)

            # Write customer to db
            current_user.user_auth.customer = encode(customer.id)
            current_user.user_auth.paying = 1
            current_user.user_auth.plan = plan

            db.session.commit()

            send_welcome_email(email, plan.title())

            # Reset the stripe key
            stripe.api_key = ""

            flash(
                _('You have successfully signed up! Please enter your Stripe credentials below.'
                  ), 'success')
            return render_template('pages/getstarted.html')
        else:
            plan = request.form.get('plan')
            email = current_user.email

            #change the customer's plan
            customer = stripe.Customer.retrieve(
                decode(current_user.user_auth.customer))
            subscription = customer.subscriptions.retrieve(
                customer.subscriptions.data[0].id)
            subscription.plan = plan
            subscription.save()

            #update the db
            current_user.user_auth.plan = plan

            db.session.commit()

            flash(
                _('You have successfully switched to the ' + plan.title() +
                  " plan."), 'success')
            send_plan_change_email(email, plan.title())

            # Reset the stripe key
            stripe.api_key = ""

            return render_template('pages/index.html')

    else:
        flash(_('Please login first.'), 'error')
        return render_template('pages/index.html')
Ejemplo n.º 12
0
def merge_video_result(video):
    '''merging files to final result

    merging audio files of matching result to one audio file
    merging this audio and the user input to final result
    '''
    if not 'files' in session or not 'matching_files' in session[
            'files'] or not 'matching_indexes' in session['files']:
        return render_template('no_access.html')

    ########## Merge matching audio files ##########
    matching_audio_segments = []

    for i in range(0, len(session['files']['matching_files'])):
        j = 1
        file = 'static/matching_audio/matching_audio(' + str(j) + ').mp3'

        while os.path.isfile(file):
            j += 1
            file = 'static/matching_audio/matching_audio(' + str(j) + ').mp3'

        start_time = str(session['files']['matching_indexes'][i][0] * 5) + '.0'
        duration = (session['files']['matching_indexes'][i][1] -
                    session['files']['matching_indexes'][i][0] + 1) * 5
        end_time = str(duration) + '.0'
        subprocess.call([
            'ffmpeg', '-ss', start_time, '-i', 'static/datasets/audio/' +
            decode(session['files']['matching_files'][i]) + '.mp3', '-c',
            'copy', '-t', end_time, file
        ])
        set_delete_timer(file)
        matching_audio_segments.append(file)

    matching_audio = AudioSegment.from_file(matching_audio_segments[0])
    input_audio_file = matching_audio_segments[0]

    if len(session['files']['matching_files']) > 1:

        for i in range(1, len(session['files']['matching_files'])):
            matching_audio += AudioSegment.from_file(
                matching_audio_segments[i])

        i = 1
        input_audio_file = 'static/uploads/audio/matching_audio(' + str(
            i) + ').mp3'

        while os.path.isfile(input_audio_file):
            i += 1
            input_audio_file = 'static/uploads/audio/matching_audio(' + str(
                i) + ').mp3'

        matching_audio.export(input_audio_file, format='mp3')
        set_delete_timer(input_audio_file)

    ########## Merge final result ##########
    input_audio = ffmpeg.input(input_audio_file).audio
    input_video = ffmpeg.input('static/uploads/video/' + video).video
    i = 1
    filename = "matching_result(" + str(i) + ")"

    while os.path.isfile('static/results/' + filename + '.mp4'):
        i += 1
        filename = "matching_result(" + str(i) + ")"

    session['files'] = {
        'matching_files': session['files']['matching_files'],
        'result': encode(filename)
    }
    ffmpeg.output(input_audio,
                  input_video,
                  'static/results/' + filename + '.mp4',
                  shortest=None).run()
    set_delete_timer('static/results/' + filename + '.mp4')

    return jsonify(status="video")
Ejemplo n.º 13
0
def merge_audio_result(audio, resolution):
    '''merging files to final result

    merging video files of matching result to one video
    merging this video and the user input to final result
    '''
    if not 'files' in session or not 'matching_files' in session['files']:
        return render_template('no_access.html')

    ########## Merge matching video files ##########
    input_video_file_name = ""

    if len(session['files']['matching_files']) > 1:
        command = ["ffmpeg"]

        for video in session['files']['matching_files']:
            command += [
                "-i", "static/datasets/video/" + decode(video) + ".mp4"
            ]

        command.append("-filter_complex")
        scaling = ""

        ########## Construct command for merging video files ##########
        for i in range(0, len(session['files']['matching_files'])):
            start_time = str(
                int(session['files']['matching_indexes'][i][0] * 5))
            end_time = str(int(session['files']['matching_indexes'][i][1] * 5))
            scale = str(resolution["width"]) + ":" + str(resolution["height"])
            scaling += "[" + str(
                i
            ) + "]trim=" + start_time + ":" + end_time + ",setpts=PTS-STARTPTS,scale=" + scale + ":force_original_aspect_ratio=decrease,pad=" + scale + ":(ow-iw)/2:(oh-ih)/2,setsar=1[" + str(
                i) + "v];"

            if i < len(session['files']['matching_files']) - 1:
                scaling += " "

        for i in range(0, len(session['files']['matching_files'])):
            scaling += "[" + str(i) + "v] "

        scaling += "concat=n=" + str(len(
            session['files']['matching_files'])) + ":v=1 [v]"
        i = 1
        input_video_file_name = "matching_video(" + str(i) + ")"

        while os.path.isfile('static/uploads/video/' + input_video_file_name +
                             '.mp4'):
            i += 1
            input_video_file_name = "matching_video(" + str(i) + ")"

        command += [
            scaling, "-map", "[v]", "-vsync", "2",
            "static/uploads/video/" + input_video_file_name + ".mp4"
        ]
        subprocess.call(command)
        set_delete_timer("static/uploads/video/" + input_video_file_name +
                         ".mp4")
        folder = "/uploads"

    else:
        folder = "/datasets"
        input_video_file_name = decode(session['files']['matching_files'][0])

    ########## Merge final result ##########
    input_audio = ffmpeg.input('static/uploads/audio/' + audio).audio
    input_video = ffmpeg.input('static' + folder + '/video/' +
                               input_video_file_name + '.mp4').video
    i = 1
    filename = "matching_result(" + str(i) + ")"

    while os.path.isfile('static/results/' + filename + '.mp4'):
        i += 1
        filename = "matching_result(" + str(i) + ")"

    session['files'] = {
        'matching_files': session['files']['matching_files'],
        'result': encode(filename)
    }
    ffmpeg.output(input_audio,
                  input_video,
                  'static/results/' + filename + '.mp4',
                  shortest=None).run()
    set_delete_timer('static/results/' + filename + '.mp4')

    return jsonify(status="audio")
Ejemplo n.º 14
0
def song():
    '''route to upload an audio file'''
    if request.method == 'GET':
        if 'files' in session and 'matching' in session['files']:
            return render_template("audio.html",
                                   user_upload="",
                                   error="",
                                   song_link="",
                                   linked_song="")
        return render_template("no_access.html")

    elif 'uploadSongForm' in request.files:
        uploaded_song = request.files['uploadSongForm']
        filename = uploaded_song.filename
        filename = "".join(i for i in filename if i not in "/\\:*?<>|.'")
        filename = filename[:-3] + '.' + filename[-3:]

        if filename != '':
            ########## Save file on server ##########
            dot_index = filename.rfind('.')
            raw_filename = filename[0:dot_index]
            file_format = filename[dot_index:len(filename) + 1]  #.mp3

            if os.path.isfile('static/uploads/audio/' + filename):
                i = 1

                while os.path.isfile('static/uploads/audio/' + raw_filename +
                                     '(' + str(i) + ')' + file_format):
                    i += 1

                raw_filename += '(' + str(i) + ')'
                filename = raw_filename + file_format

            uploaded_song.save(os.path.join('static/uploads/audio', filename))

            ########## Convert to .mp3 if needed ##########
            if file_format != '.mp3':
                conversions.convert_to_mp3(filename)
                os.remove(os.path.join('static/uploads/audio', filename))
                filename = raw_filename + '.mp3'
            else:
                set_delete_timer(os.path.join('static/uploads/audio',
                                              filename))

            encoded = encode(filename)
            duration = MP3('static/uploads/audio/' + filename).info.length

            if duration > 300:
                os.remove(os.path.join('static/uploads/audio', filename))
                error = "Audio is longer than 5 minutes"
            elif duration < 5:
                os.remove(os.path.join('static/uploads/audio', filename))
                error = "Audio is shorter than 5 seconds"
            else:
                error = ""
            return render_template("audio.html",
                                   user_upload=filename,
                                   encoded=encoded,
                                   error=error,
                                   song_link="",
                                   linked_song="")
        else:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("audio.html",
                                   user_upload="",
                                   encoded="",
                                   error="",
                                   song_link="",
                                   linked_song="")

    elif 'linkSongForm' in request.form:
        link = request.form['linkSongForm']

        try:
            youtube = YouTube(link)
            if YouTube(link).length > 300:
                session['files'] = {'matching': session['files']['matching']}
                return render_template("audio.html",
                                       user_upload="",
                                       encoded="",
                                       error="Audio is longer than 5 minutes",
                                       song_link=link,
                                       linked_song="")
            elif YouTube(link).length < 5:
                session['files'] = {'matching': session['files']['matching']}
                return render_template("audio.html",
                                       user_upload="",
                                       encoded="",
                                       error="Audio is shorter than 5 seconds",
                                       song_link=link,
                                       linked_song="")
            else:
                ########## Save file on server ##########
                title = YouTube(link).streams.first().title
                title = "".join(i for i in title if i not in "/\\:*?<>|.'")
                video_title = title

                if os.path.isfile('static/uploads/video/' + video_title +
                                  '.mp4'):
                    i = 1

                    while os.path.isfile('static/uploads/video/' +
                                         video_title + '(' + str(i) + ')' +
                                         '.mp4'):
                        i += 1

                    video_title += '(' + str(i) + ')'

                resolutions = ["1080p", "720p", "360p", "240p", "144p"]
                res = ""
                videos = []

                for resolution in resolutions:
                    videos = YouTube(link).streams.filter(res=resolution,
                                                          progressive=True)

                    if len(videos) > 0:
                        res = resolution
                        break

                video = videos[0].download(output_path='static/uploads/video/',
                                           filename=video_title)

                ########## Convert YouTube video to .mp3 ##########
                audio_title = title

                if os.path.isfile('static/uploads/audio/' + audio_title +
                                  '.mp3'):
                    i = 1

                    while os.path.isfile('static/uploads/audio/' +
                                         audio_title + '(' + str(i) + ')' +
                                         '.mp3'):
                        i += 1

                    audio_title += '(' + str(i) + ')'

                raw_audio = ffmpeg.input('static/uploads/video/' +
                                         video_title + '.mp4')
                processed_video = ffmpeg.output(
                    raw_audio, 'static/uploads/audio/' + audio_title + '.mp3')
                encoded = encode(audio_title + '.mp3')
                ffmpeg.run(processed_video)
                os.remove('static/uploads/video/' + video_title + '.mp4')
                set_delete_timer('static/uploads/audio/' + audio_title +
                                 '.mp3')
                return render_template("audio.html",
                                       user_upload="",
                                       encoded=encoded,
                                       error="",
                                       song_link="",
                                       linked_song=audio_title + '.mp3')

        except pytube.exceptions.RegexMatchError:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("audio.html",
                                   user_upload="",
                                   encoded="",
                                   error="Invalid link",
                                   song_link=link,
                                   linked_song="")

        except pytube.exceptions.ExtractError:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("audio.html",
                                   user_upload="",
                                   encoded="",
                                   error="An extraction Error occurred",
                                   song_link=link,
                                   linked_song="")

        except pytube.exceptions.VideoUnavailable:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("audio.html",
                                   user_upload="",
                                   encoded="",
                                   error="The video is unavailabe",
                                   song_link=link,
                                   linked_song="")
    else:
        session['files'] = {'matching': session['files']['matching']}
        return redirect(url_for('audio'))
Ejemplo n.º 15
0
def video():
    '''route to upload a video file'''
    safari = str(request.user_agent.browser == "safari")
    reset_camera()
    if request.method == 'GET':
        if 'files' in session and 'matching' in session['files']:
            return render_template("video.html",
                                   matching="",
                                   user_upload="",
                                   error="",
                                   video_link="",
                                   linked_video="",
                                   safari=safari)
        return render_template("no_access.html")
    elif 'matching' in request.form:
        matching = request.form.get('matching')
        return render_template("video.html",
                               matching=matching,
                               user_upload="",
                               error="",
                               video_link="",
                               linked_video="",
                               safari=safari)
    elif 'userUpload' in request.files:
        uploaded_video = request.files['userUpload']
        filename = uploaded_video.filename
        filename = "".join(i for i in filename if i not in "/\\:*?<>|.'")
        filename = filename[:-3] + '.' + filename[-3:]

        if filename != '':
            ########## Save file on server ##########
            dot_index = filename.rfind('.')
            raw_filename = filename[0:dot_index]
            file_format = filename[dot_index:len(filename) + 1]  #.mp4

            if os.path.isfile('static/uploads/video/' + filename):
                i = 1

                while os.path.isfile('static/uploads/video/' + raw_filename +
                                     '(' + str(i) + ')' + file_format):
                    i += 1

                raw_filename += '(' + str(i) + ')'
                filename = raw_filename + file_format

            uploaded_video.save(os.path.join('static/uploads/video/',
                                             filename))

            duration = subprocess.run([
                "ffprobe", "-v", "error", "-show_entries", "format=duration",
                "-of", "default=noprint_wrappers=1:nokey=1",
                "static/uploads/video/" + filename
            ],
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT)

            if float(duration.stdout) > 300:
                os.remove(os.path.join('static/uploads/video/', filename))
                error = "Video is longer than 5 minutes"
            elif float(duration.stdout) < 5:
                os.remove(os.path.join('static/uploads/video/', filename))
                error = "Video is shorter than 5 seconds"
            else:
                ########## Convert to .mp4 if needed ##########
                if file_format != '.mp4':
                    conversions.convert_to_mp4(filename)
                    os.remove(os.path.join('static/uploads/video/', filename))
                    filename = raw_filename + '.mp4'
                else:
                    set_delete_timer(
                        os.path.join('static/uploads/video/', filename))

                error = ""

            encoded = encode(filename)

            return render_template("video.html",
                                   user_upload=filename,
                                   encoded=encoded,
                                   error=error,
                                   video_link="",
                                   linked_video="",
                                   safari=safari)
        else:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("video.html",
                                   user_upload="",
                                   encoded="",
                                   error="",
                                   video_link="",
                                   linked_video="",
                                   safari=safari)
    elif 'videoLink' in request.form:
        link = request.form['videoLink']

        try:
            youtube = YouTube(link)

            if YouTube(link).length > 300:
                session['files'] = {'matching': session['files']['matching']}
                return render_template("video.html",
                                       user_upload="",
                                       encoded="",
                                       error="Video is longer than 5 minutes",
                                       video_link=link,
                                       linked_video="",
                                       safari=safari)
            elif YouTube(link).length < 5:
                session['files'] = {'matching': session['files']['matching']}
                return render_template("video.html",
                                       user_upload="",
                                       encoded="",
                                       error="Video is shorter than 5 seconds",
                                       video_link=link,
                                       linked_video="",
                                       safari=safari)
            else:
                ########## Save file on server ##########
                title = YouTube(link).streams.first().title
                title = "".join(i for i in title if i not in "/\\:*?<>|.'")

                if os.path.isfile('static/uploads/video/' + title + '.mp4'):
                    i = 1

                    while os.path.isfile('static/uploads/video/' + title +
                                         '(' + str(i) + ')' + '.mp4'):
                        i += 1
                    title += '(' + str(i) + ')'

                resolutions = ["1080p", "720p", "360p", "240p", "144p"]
                res = ""
                videos = []

                for resolution in resolutions:
                    videos = YouTube(link).streams.filter(res=resolution,
                                                          progressive=True)

                    if len(videos) > 0:
                        res = resolution
                        break

                video = videos[0].download(output_path='static/uploads/video/',
                                           filename=title)
                set_delete_timer('static/uploads/video/' + title + '.mp4')
                encoded = encode(title + '.mp4')

                return render_template("video.html",
                                       user_upload="",
                                       encoded=encoded,
                                       error="",
                                       video_link="",
                                       linked_video=title + '.mp4',
                                       safari=safari)

        except pytube.exceptions.RegexMatchError:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("video.html",
                                   user_upload="",
                                   encoded="",
                                   error="Invalid link",
                                   video_link=link,
                                   linked_video="",
                                   safari=safari)

        except pytube.exceptions.ExtractError:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("video.html",
                                   user_upload="",
                                   encoded="",
                                   error="An extraction Error occurred",
                                   video_link=link,
                                   linked_video="",
                                   safari=safari)

        except pytube.exceptions.VideoUnavailable:
            session['files'] = {'matching': session['files']['matching']}
            return render_template("video.html",
                                   user_upload="",
                                   encoded="",
                                   error="The video is unavailabe",
                                   video_link=link,
                                   linked_video="",
                                   safari=safari)
    else:
        session['files'] = {'matching': session['files']['matching']}
        return redirect(url_for('video'))