예제 #1
0
def delete_account():
    if request.method == 'GET':
        if current_user.is_authenticated:

            # Delete stripe subscription
            customer = stripe.Customer.retrieve(
                decode(current_user.user_auth.customer))
            customer.cancel_subscription()

            # delete user from database
            id = current_user.user_auth.id
            email = current_user.email
            user = UserAuth.query.filter_by(id=id).first()
            db.session.delete(user)
            db.session.delete(current_user)

            # commit database changes
            db.session.commit()

            #send the email
            send_cancel_email(email)
            flash(_('Your subscription has been successfully canceled.'),
                  'error')
            return logout()
        else:
            flash(_('Please login first.'), 'error')
            return render_template('pages/index.html')
    else:
        return redirect('/')
예제 #2
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)
예제 #3
0
파일: views.py 프로젝트: rcharp/Simple
def delete_account():
    if request.method == 'GET':
        if current_user.is_authenticated:

            # Delete stripe subscription
            customer = stripe.Customer.retrieve(decode(current_user.user_auth.customer))
            customer.cancel_subscription()

            # delete user from database
            id = current_user.user_auth.id
            email = current_user.email
            user = UserAuth.query.filter_by(id=id).first()
            db.session.delete(user)
            db.session.delete(current_user)

            # commit database changes
            db.session.commit()

            #send the email
            send_cancel_email(email)
            flash(_('Your subscription has been successfully canceled.'), 'error')
            return logout()
        else:
            flash(_('Please login first.'), 'error')
            return render_template('pages/index.html')
    else:
        return redirect('/')
예제 #4
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'))
예제 #5
0
파일: views.py 프로젝트: rcharp/Simple
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')
예제 #6
0
파일: Esim.py 프로젝트: wanggor/afis
 def update_data(self,data):
     if self.isreading:
         keys = sorted(list(data.keys()))
         for key in keys:
             textvalue = "".join([ str(i[0]) for i in data[key][:-1]]) + " " + str(data[key][-1]) 
             if key not in self.itemList.keys():
                 self.itemList[key] = self.addMsgWidget( key ,textvalue)
                 self.encrypeList[key] = {
                     "code" : ""
                 }
             else:
                 if self.encrypeList[key]["code"] != "":
                     textvalue = f'[{self.encrypeList[key]["code"]}] ' + encryption.decode(self.encrypeList[key]["code"], textvalue.lower())
                 self.itemList[key].plainTextEdit.setPlainText(textvalue.upper())
예제 #7
0
def waiting(data_type, name):
    '''waiting route returning a loading screen to the user'''
    filename = decode(name)

    if not os.path.isfile('static/uploads/' + data_type + '/' + filename):
        return render_template("page_not_found.html")

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

    return render_template("waiting.html",
                           type=data_type,
                           name=filename,
                           result="")
예제 #8
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)
예제 #9
0
파일: views.py 프로젝트: rcharp/Simple
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'))
예제 #10
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')
예제 #11
0
def video_result():
    '''route for presenting result of matching for video input'''
    if 'files' not in session or 'result' not in session[
            'files'] or 'matching_files' not in session['files']:
        return render_template("no_access.html")

    ########## Get files found in matching ##########
    filenames = []

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

        with open('static/datasets/audio/metadata.csv',
                  newline='') as csv_file:
            reader = csv.reader(csv_file)

            for row in reader:
                if row[0] == decode(
                        session['files']['matching_files'][0]) + '.mp3':
                    filenames = [{
                        "name":
                        decode(session['files']['matching_files'][0]),
                        "number":
                        "",
                        "title":
                        row[1],
                        "artist":
                        row[2]
                    }]
    else:
        numbers = [
            "first ", "second ", "third ", "fourth ", "fifth ", "sixth ",
            "seventh ", "eighth ", "ninth ", "tenth "
        ]
        matching_files_decoded = []

        for i in range(0, len(session['files']['matching_files'])):
            matching_files.append(
                decode(session['files']['matching_files'][i]) + '.mp3')

        song_properties = {}

        with open('static/datasets/audio/metadata.csv',
                  newline='') as csv_file:
            reader = csv.reader(csv_file)

            for row in reader:
                if row[0] in matching_files_decoded:
                    song_properties[row[0]] = {
                        'title': row[1],
                        'artist': row[2]
                    }

        for i in range(0, len(session['files']['matching_files'])):
            name = decode(session['files']['matching_files'][i])
            filenames.append({
                "name": name,
                "number": numbers[i],
                "title": song_properties[name]['title'],
                "artist": song_properties[name]['artist']
            })

    result_saved = decode(session['files']['result'])

    return render_template("video_result.html",
                           files=filenames,
                           result=result_saved + '.mp4')
예제 #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")
예제 #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")
예제 #14
0
def download_video(filename):
    '''route for downloading the matched video file'''
    path = decode(path)
    uploads = os.path.join('static/datasets/video')

    return send_from_directory(uploads, path, as_attachment=True)
예제 #15
0
def download_result(filename):
    '''route for downloading the final result'''
    path = decode(path)
    uploads = os.path.join('static/results')

    return send_from_directory(uploads, path, as_attachment=True)