Esempio n. 1
0
def client_connect(ccname):
    env = get_env()

    vpn = DB.Vpn(env['HOSTNAME'])
    if not vpn in DB.vpns:
        register_vpn()

    user = DB.users[env['COMMON_NAME']]
    if not user or not user.exists():
        user = create_user(vpn, env)

    addr = Address(env['TRUSTED_IP'], env['TRUSTED_PORT'])
    cluster = DB.Cluster(user, vpn.chal)
    connection = DB.Connection(addr)
    cluster.connections.add(connection)
    connection.update(addr=addr,
                      vpn=vpn,
                      user=user,
                      cluster=cluster,
                      alive=True)

    if CONNECTION_TTL is not None:
        connection.expire(alive=CONNECTION_TTL)

    logging.info("New connection from {cn}@{ip}:{port} on vlan {vlan}".format(
        cn=env['COMMON_NAME'], vlan=user.vlan, ip=addr.ip, port=addr.port))

    with open(ccname, 'w') as ccfile:
        ccfile.write(CCTEMPLATE.format(vlan=user.vlan))
        if env["PUSH_ADDR"] and env["PUSH_MASK"]:
            ccfile.write(
                IFCONFIG.format(addr=env["PUSH_ADDR"], mask=env["PUSH_MASK"]))
Esempio n. 2
0
    def _get_initial_narrow_environment(self, proc, argv, ctx={}):
        """char** _get_initial_narrow_environment ()"""

        ptr_size = self.get_ptr_size()
        env = common.get_env(proc.emu)
        total = ptr_size
        sptr = total
        pptr = 0
        fmt_env = []
        for k, v in env.items():
            envstr = '%s=%s\x00' % (k, v)
            envstr = envstr.encode('utf-8')
            total += len(envstr)
            fmt_env.append(envstr)
            total += ptr_size
            sptr += ptr_size

        pMem = proc.default_heap_alloc(self.ptr_size * 2)

        pptr = pMem
        sptr += pMem

        for v in fmt_env:
            common.mem_write(proc.uc_eng, pptr,
                             sptr.to_bytes(ptr_size, 'little'))
            pptr += ptr_size
            common.mem_write(proc.uc_eng, sptr, v)
            sptr += len(v)

        return pMem
Esempio n. 3
0
    def _get_initial_narrow_environment(self, proc, argv, ctx={}):
        """char** _get_initial_narrow_environment ()"""

        ptr_size = self.win_emu.get_ptr_size()
        env = common.get_env(self.win_emu)
        total = ptr_size
        sptr = total
        pptr = 0
        fmt_env = []
        for k, v in env.items():
            envstr = '%s=%s\x00' % (k, v)
            envstr = envstr.encode('utf-8')
            total += len(envstr)
            fmt_env.append(envstr)
            total += ptr_size
            sptr += ptr_size

        pMem = self.win_emu.mem_manager.alloc_heap(proc.proc_default_heap,
                                                   ptr_size * 2)
        pptr = pMem
        sptr += pMem

        for v in fmt_env:
            proc.write_mem_self(pptr, sptr.to_bytes(ptr_size, 'little'))
            pptr += ptr_size
            proc.write_mem_self(sptr, v)
            sptr += len(v)

        return pMem
Esempio n. 4
0
def main():
    env = get_env()

    with xmlrpc.client.ServerProxy(mgm_uri(env)) as client:
        vlan = client.connect_user(env['NAUM_CHAL'], env['COMMON_NAME'], env['TRUSTED_IP'], int(env['TRUSTED_PORT']))

    with open(sys.argv[1], 'w') as ovpn_dyn:
        ovpn_dyn.write(OVPN_DYN_TEMPLATE.format(vlan=vlan))
Esempio n. 5
0
def client_disconnect():
    env = get_env()
    client = '{TRUSTED_IP}:{TRUSTED_PORT}'.format(**env)

    connection = DB.Connection(Address(env['TRUSTED_IP'], env['TRUSTED_PORT']))
    if connection.exists():
        connection.delete('alive')
    else:
        logging.warn("Connection {} removed from Redis prior to disconnect".format(client))
Esempio n. 6
0
def register_vpn():
    env = get_env()

    chal = DB.Challenge(env['NAUM_CHAL'])
    if len(chal.files) == 0:
        chal.files.extend(env['NAUM_FILES'])

    vpn = DB.Vpn(env['HOSTNAME'])

    vpn.update(veth=env['NAUM_VETHHOST'], veth_state='down', chal=chal)

    DB.vpns.add(vpn)
Esempio n. 7
0
def client_disconnect():
    env = get_env()
    client = '{TRUSTED_IP}:{TRUSTED_PORT}'.format(**env)

    connection = DB.Connection(Address(env['TRUSTED_IP'], env['TRUSTED_PORT']))
    try:
        connection.user.connections.remove(connection)  # That's a mouthful
        if len(connection.user.connections) == 0:
            connection.user.status = 'disconnected'
        connection.alive = False
    except RedisKeyError:
        logging.warn(
            "Connection {} removed from Redis prior to disconnect".format(
                client))
Esempio n. 8
0
def register_vpn():
    env = get_env()

    chal = DB.Challenge(env['NAUM_CHAL'])

    # Assign the list of files for this challenge.
    chal.files.clear()
    chal.files.extend(env['NAUM_FILES'])

    vpn = DB.Vpn(env['HOSTNAME'])
    vpn.update(veth=env['NAUM_VETHHOST'],
               veth_state=DB.Vpn.VETH_DOWN,
               chal=chal)

    DB.vpns.add(vpn)
Esempio n. 9
0
    def GetTempPath(self, proc, argv, ctx={}):
        '''
        DWORD GetTempPathA(
        DWORD nBufferLength,
        LPSTR lpBuffer
        );
        '''

        nBufferLength, lpBuffer = argv
        rv = 0
        cw = common.get_char_width(ctx)
        tempdir = common.get_env(proc.emu).get('temp', 'C:\\Windows\\temp\\')
        if cw == 2:
            new = (tempdir).encode('utf-16le') + b'\x00\x00'
        else:
            new = (tempdir).encode('utf-8') + b'\x00'
        rv = len(tempdir)
        if lpBuffer:
            argv[1] = tempdir
            proc.uc_eng.mem_write(lpBuffer, new)
        return rv
Esempio n. 10
0
def client_connect(ccname):
    env = get_env()

    vpn = DB.Vpn(env['HOSTNAME'])
    if not vpn in DB.vpns:
        register_vpn()

    user = DB.users[env['COMMON_NAME']]
    if user:
        user.status = 'active'

    else:
        user = create_user(vpn, env)

    addr = Address(env['TRUSTED_IP'], env['TRUSTED_PORT'])
    connection = DB.Connection(addr)
    connection.update(addr=addr, vpn=vpn, user=user, alive=True)
    user.connections.add(connection)

    logging.info("New connection from {cn}@{ip}:{port} on vlan {vlan}".format(
        cn=env['COMMON_NAME'], vlan=user.vlan, ip=addr.ip, port=addr.port))

    with open(args.ccname, 'w') as ccfile:
        ccfile.write(CCTEMPLATE.format(vlan=user.vlan))
import matplotlib.pyplot as plt
import common

# This should give a Fourier transform with a frequency spectrum that is
# entirely real, starts at 1 and goes to 0 at 0.5 the sample rate


def est_autocorr(x):
    """ Estimate autocorrelation by inverse transforming the powerspectrum """
    X = np.fft.fft(x)
    S = X * np.conj(X)
    r = np.fft.ifft(X)
    return r


N = common.get_env('N', default=512, conv=int)
n = np.arange(N)
t = np.arange(-N / 2 + 0.5, N / 2)
t_eval = np.concatenate((np.arange(N / 2), np.arange(1, N / 2 + 1)[::-1] * -1))
a = common.get_env('a', default=0.5, conv=float)
x = a * np.power(np.sinc(t_eval * a), 2)
X = np.fft.fft(x)
r = est_autocorr(x)
fig, axs = plt.subplots(3, 1)
axs[0].plot(n, x)
axs[1].plot(n, np.real(X))
axs[2].plot(n, np.abs(r))
# It really seems that the square of the sinc is its own autocorrelation
# function
print(np.sum(np.abs(x - r)))
Esempio n. 12
0
File: views.py Progetto: amsaha/don
def ping(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = PingForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            src_ip = form.cleaned_data['src_ip']
            dst_ip = form.cleaned_data['dst_ip']
            router = form.cleaned_data['router']
            #html = '<html><body>SIP: %s DIP: %s router: %s</body></html>' % (src_ip, dst_ip, router)
            #return HttpResponse(html)
            static_path = settings.STATIC_ROOT
            pwd = settings.ROOT_PATH
            JSON_FILE = pwd + '/don/ovs/don.json'

            params = {
                    'json_file' : pwd + '/don/ovs/don.json',
                    'src_ip'    : src_ip,
                    'dst_ip'    : dst_ip,
                    'router'    : router,
                    'path_file' : static_path + '/don/ping.html',
                    'username'  : 'cirros',
                    'passwd'    : 'cubswin:)',
                    'count'     : 2,
                    'timeout'   : 2,
                    'debug'     : True,
                    'plot'      : False,
                    }
            response = path.path(params)
            if response:
                error_text = response
                messages.error(request,error_text)
                return render(request, 'don/ovs/ping.html', {'form': form})

            JSON_FILE = pwd + '/don/ovs/don.json'
            COMPUTE_DOT_FILE  = None
            COMPUTE_SVG_FILE  = None
            NETWORK_DOT_FILE  = None
            NETWORK_SVG_FILE  = None
            COMBINED_DOT_FILE = static_path + '/don/ping.dot'
            COMBINED_SVG_FILE = static_path + '/don/ping.svg'
            # HIGHLIGHT_FILE    = pwd + '/don/ovs/static/ping.html'
            HIGHLIGHT_FILE    = static_path + '/don/ping.html'


            plotter = DotGenerator(JSON_FILE,
                                   COMPUTE_DOT_FILE,
                                   COMPUTE_SVG_FILE,
                                   NETWORK_DOT_FILE,
                                   NETWORK_SVG_FILE,
                                   COMBINED_DOT_FILE,
                                   COMBINED_SVG_FILE,
                                   HIGHLIGHT_FILE,
                                   )
            plotter.plot_combined()
            plotter.generate_combined_svg()

            # return HttpResponseRedirect('/static/path.html')
            return render(request, 'don/ovs/path.html')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = PingForm()
        BASE_DIR = settings.ROOT_PATH + '/don/ovs/'
        myenv = os.environ.copy()
        myenv.update(get_env(BASE_DIR + 'admin-openrc.sh'))
        output = execute_cmd(['nova', 'list'], sudo=False, shell=False, env=myenv).split('\n');
        ip_list = get_instance_ips(output)
        ip_list.sort()
        router_op = execute_cmd(['neutron', 'router-list'], sudo=False, shell=False, env=myenv).split('\n');
        router_list = get_router_names(router_op)
        router_list.sort()
        # insert first value of select menu
        ip_opt = zip(ip_list,ip_list)
        router_opt = zip(router_list,router_list)
        # ip_opt.insert(0,('','Select IP address'))
        # router_opt.insert(0,('','Select Router'))
        form.fields['src_ip'].widget.choices = ip_opt
        form.fields['dst_ip'].widget.choices = ip_opt
        form.fields['router'].widget.choices = router_opt

    return render(request, 'don/ovs/ping.html', {'form': form})
import math


def spectral_flux(x, H, W, window_type='hann'):
    if W >= 4:
        w = signal.get_window(window_type, W)
    else:
        w = np.ones(W)
    w /= np.sum(W)
    spec_flux_i = 0
    X = np.fft.fft(common.frame(x, H, W) * w[:, None], axis=0)
    spec_flux = np.sum(np.abs(np.diff(np.abs(X), axis=0)), axis=0)
    return spec_flux


INPUT = common.get_env('INPUT', check_if_none=True)
WINDOW_TYPE = common.get_env('WINDOW_TYPE', default='hann')
SAMPLE_RATE = common.get_env('SAMPLE_RATE', conv=float, default=16e3)
ATTACK_THRESH = common.get_env('ATTACK_THRESH', conv=float, default=0.05)
H = common.get_env('H', conv=int, default=2)
W = common.get_env('W', conv=int, default=8)
ALPHA = common.get_env('ALPHA', conv=float, default=.01)
x = np.fromfile(INPUT)

filter_co_hz = 2000
filter_order = 16
filter_ripple = 3
b, a = signal.cheby1(filter_order,
                     filter_ripple,
                     filter_co_hz,
                     btype='highpass',
Esempio n. 14
0
__doc__ = """
take a soundfile and the score used to render it (see scripts/synth_af_score.py)
and use this score to determine the points that are fixed in a time stretch.
Produce a file that is the time-stretched version of the input file, but with
the attacks preserved.
"""

import classic_puckette_timestretch
import synth_af_score
import common
import time_map_tstretch
import numpy as np

if __name__ == '__main__':
    SCORE_FILE = common.get_env('SCORE_FILE', check_if_none=True)
    SOUND_FILE = common.get_env('SOUND_FILE', check_if_none=True)
    OUTPUT = common.get_env('OUTPUT', check_if_none=True)
    # smaller numbers mean longer file
    TSTRETCH_FACTOR = common.get_env('TSTRETCH_FACTOR', default=1, conv=float)
    # move the locked points forward or backward in time by a fixed amount
    LOCK_OFFSET = common.get_env('LOCK_OFFSET', default=0, conv=int)
    # a time after the lock time within which all the points are locked
    # this value is multiplied by H+W because we cannot lock 2 points closer
    # than that amount of time
    LOCK_WINDOW = common.get_env('LOCK_WINDOW', default=0, conv=int)

    H = common.get_env('H', default=256, conv=int)
    W = common.get_env('W', default=1024, conv=int)
    SAMPLE_RATE = common.get_env('SAMPLE_RATE', 16000, float)
    x = np.fromfile(SOUND_FILE, 'float64')
    orig_len_x = len(x)
Esempio n. 15
0
def extract_ts_samps(scorefile,sample_rate):
    ts_samps=[ts_to_ts_samps(ts,sample_rate) for ts in extract_ts(scorefile)]
    return ts_samps

def render_score_to_array(scorefile,sample_rate,sample_file_directory=None):
    fundisp=const_sr_fun_dispatcher(sample_rate)
    sound_files=score_extract_unique_filenames(scorefile)
    sound_segs=load_files_into_arrays(sound_files,sample_file_directory)
    longest_seg_len=get_length_longest_array([sound_segs[k] for k in sound_segs.keys()])
    max_ts=score_extract_maximum_timestamp(scorefile)
    len_output=int(np.ceil(max_ts*sample_rate)+longest_seg_len)
    y=np.zeros(len_output)
    with open(scorefile,'r') as f:
        for line in f.readlines():
            filename,ts,proc=extract_score_fields(line)
            x=run_procs_on_array(sound_segs[filename],proc,fundisp)
            ts_samps=ts_to_ts_samps(ts,sample_rate)
            y[ts_samps:ts_samps+len(x)]+=x
    return y

if __name__ == '__main__':
    SAMPLE_FILE_DIRECTORY=common.get_env('SAMPLE_FILE_DIRECTORY')
    SAMPLE_RATE=common.get_env('SAMPLE_RATE',16000,float)
    SCORE_FILE=common.get_env('SCORE_FILE',check_if_none=True)
    OUTPUT=common.get_env('OUTPUT',check_if_none=True)
    y=render_score_to_array(SCORE_FILE,SAMPLE_RATE,sample_file_directory=SAMPLE_FILE_DIRECTORY)
    y=common.normalize(y)
    y.tofile(OUTPUT)
    
Esempio n. 16
0
def main():
    env = get_env()

    with xmlrpc.client.ServerProxy(mgm_uri(env)) as client:
        client.register_challenge(env['NAUM_CHAL'], env['NAUM_VETHHOST'],
                                  env['NAUM_FILES'])
def gei(n, i):
    return common.get_env(n, default=i, conv=int)
Esempio n. 18
0
def ping(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = PingForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            src_ip = form.cleaned_data['src_ip']
            dst_ip = form.cleaned_data['dst_ip']
            router = form.cleaned_data['router']
            # html = '<html><body>SIP: %s DIP: %s router: %s</body></html>' % (src_ip, dst_ip, router)
            # return HttpResponse(html)
            static_path = settings.STATIC_ROOT
            pwd = settings.ROOT_PATH
            JSON_FILE = pwd + '/don/ovs/don.json'

            params = {
                'json_file': pwd + '/don/ovs/don.json',
                'src_ip': src_ip,
                'dst_ip': dst_ip,
                'router': router,
                'path_file': static_path + '/don/ping.html',
                'username': '******',
                'passwd': 'cubswin:)',
                'count': 2,
                'timeout': 2,
                'debug': True,
                'plot': False,
            }
            response = path.path(params)
            if response:
                error_text = response
                messages.error(request, error_text)
                return render(request, 'don/ovs/ping.html', {'form': form})

            JSON_FILE = pwd + '/don/ovs/don.json'
            COMPUTE_DOT_FILE = None
            COMPUTE_SVG_FILE = None
            NETWORK_DOT_FILE = None
            NETWORK_SVG_FILE = None
            COMBINED_DOT_FILE = static_path + '/don/ping.dot'
            COMBINED_SVG_FILE = static_path + '/don/ping.svg'
            # HIGHLIGHT_FILE    = pwd + '/don/ovs/static/ping.html'
            HIGHLIGHT_FILE = static_path + '/don/ping.html'

            plotter = DotGenerator(
                JSON_FILE,
                COMPUTE_DOT_FILE,
                COMPUTE_SVG_FILE,
                NETWORK_DOT_FILE,
                NETWORK_SVG_FILE,
                COMBINED_DOT_FILE,
                COMBINED_SVG_FILE,
                HIGHLIGHT_FILE,
            )
            plotter.plot_combined()
            plotter.generate_combined_svg()

            # return HttpResponseRedirect('/static/path.html')
            return render(request, 'don/ovs/path.html')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = PingForm()
        BASE_DIR = settings.ROOT_PATH + '/don/ovs/'
        myenv = os.environ.copy()
        myenv.update(get_env(BASE_DIR + 'admin-openrc.sh'))
        output = execute_cmd(['nova', 'list'],
                             sudo=False,
                             shell=False,
                             env=myenv).split('\n')
        ip_list = get_instance_ips(output)
        ip_list.sort()
        router_op = execute_cmd(['neutron', 'router-list'],
                                sudo=False,
                                shell=False,
                                env=myenv).split('\n')
        router_list = get_router_names(router_op)
        router_list.sort()
        # insert first value of select menu
        ip_opt = zip(ip_list, ip_list)
        router_opt = zip(router_list, router_list)
        # ip_opt.insert(0,('','Select IP address'))
        # router_opt.insert(0,('','Select Router'))
        form.fields['src_ip'].widget.choices = ip_opt
        form.fields['dst_ip'].widget.choices = ip_opt
        form.fields['router'].widget.choices = router_opt

    return render(request, 'don/ovs/ping.html', {'form': form})
    a = a.copy()
    a = a / a[0]
    a = a[1:]
    p = len(a)
    r = np.zeros_like(a)
    r[-1] = a[-1]
    for j in np.arange(p - 1)[::-1]:
        s = 1 / (1 - r[j + 1] * np.conj(r[j + 1]))
        a[:j + 1] = s * (a[:j + 1] - r[j + 1] * np.conj(a[:j + 1][::-1]))
        r[j] = a[j]
    return r


# From test/attack_estimation_studies/tri_freq_response.py it seems sinc^2 is
# its own autocorrelation, so we use this for the filter design number of poles
P = common.get_env('P', default=2, conv=int)
acc_mult = common.get_env('acc_mult', default=1, conv=int)


def fit_allpole_triangular_lowpass(
    # number of poles
    P,
    # length multiplier (because a longer autocorrelation sequence might give a
    # better fit, but it seems like actually not)
    acc_mult=1):

    # It seems the feedforward coefficients other than the first one often get
    # forced to 0, so we just use an allpole model
    Q = 0

    # length of autocorrelation sequence we need
def gef(n, f):
    return common.get_env(n, default=f, conv=float)
# Compare the performance of the DFT and IIR implementations of the high
# frequency weighting filter

import numpy as np
from scipy import signal
import common
import spectral_difference
import subprocess
import high_freq_weighting_filter
import matplotlib.pyplot as plt

INPUT = common.get_env('INPUT', check_if_none=True)
WINDOW_TYPE = common.get_env('WINDOW_TYPE', default='hann')
SAMPLE_RATE = common.get_env('SAMPLE_RATE', conv=float, default=16e3)
# hop size of DFT implementation
H = common.get_env('H', conv=int, default=2)
# window size of DFT implementation
W = common.get_env('W', conv=int, default=8)
# number of poles in IIR implementation
P = common.get_env('P', conv=int, default=2)
X_LIM = common.get_env('X_LIM', conv=eval, default=(0, 2))
# Max search window sizes
H_LMAX = common.get_env('H_LMAX', conv=int, default=5)
W_LMAX = common.get_env('W_LMAX', conv=int, default=10)
# How many times greater the max has to be to get counted
A_LMAX = common.get_env('A_LMAX', conv=float, default=1.5)
# Coefficient of smoothing filter
A_SMOOTH = common.get_env('A_SMOOTH', conv=float, default=1e-2)
# Max search window sizes for averaging filter
H_ASLMAX = common.get_env('H_ASLMAX', conv=int, default=5)
W_ASLMAX = common.get_env('W_ASLMAX', conv=int, default=10)
#!/usr/bin/env python3
from os import system, chdir, path, mkdir
from os.path import join
from common import WORKSPACE_ROOT, get_env

GROUTE_PATH = path.join(WORKSPACE_ROOT, "groute")
GROUTE_BUILD_PATH = path.join(GROUTE_PATH, "build")

chdir(WORKSPACE_ROOT)

if not path.exists(GROUTE_PATH):
    system("git clone --recursive https://github.com/groute/groute.git")
    chdir(GROUTE_PATH)
    system("git checkout 7a77c467867b55c92110bad019447eb305fe6ec1")
    system("git apply %s" % (join(WORKSPACE_ROOT, "groute.patch")))

chdir(GROUTE_PATH)

if not path.exists(GROUTE_BUILD_PATH):
    mkdir(GROUTE_BUILD_PATH)

chdir(GROUTE_BUILD_PATH)

env_dict = get_env()
CMAKE_PATH = env_dict["cmake_path"]
GCC_PATH = env_dict["gcc_path"]
GPP_PATH = env_dict["gpp_path"]

system("cmake .. -DCMAKE_C_COMPILER=%s -DCMAKE_CXX_COMPILER=%s" % (GCC_PATH, GPP_PATH))
system("n=$(nproc) && make -j $n")
Esempio n. 23
0
# The time-stretcher uses the audio-rate time-stretch and pitch-shift signals
import numpy as np
from scipy import signal
from pitch_shift import pitch_shifter
import window_tools
from classic_puckette_timestretch import pvoc_synth
import matplotlib.pyplot as plt
import rel_del_line
from time_map_tstretch import attack_avoider
import attack_finder
import common
import envelopes
import lfo

# Environment variables
SR = common.get_env('SR', default=16000, conv=int)
W = common.get_env('W', default=1024, conv=int)
H = common.get_env('H', default=256, conv=int)
IN_FILE = common.get_env('IN_FILE', default='/tmp/in.f64')
OUT_FILE = common.get_env('OUT_FILE', default='/tmp/out.f64')
LMAX_FILT_RATE = common.get_env('LMAX_FILT_RATE', default=SR, conv=float)
# Gate parameters
GATE_F0 = common.get_env('GATE_F0', default=1, conv=float) / SR
GATE_F1 = common.get_env('GATE_F1', default=GATE_F0 * SR, conv=float) / SR
# Time-stretch LFO parameters
TS_FM0 = common.get_env('TS_FM0', default=0.5, conv=float) / SR
TS_FM1 = common.get_env('TS_FM1', default=TS_FM0 * SR, conv=float) / SR
TS_MIN = common.get_env('TS_MIN', default=0.5, conv=float)
TS_MAX = common.get_env('TS_MAX', default=1.5, conv=float)
# Pitch-shift LFO parameters
PS_FM0 = common.get_env('PS_FM0', default=0.75, conv=float) / SR
Esempio n. 24
0
import numpy as np
import matplotlib.pyplot as plt
import common

IN_FILE = common.get_env('IN_FILE', default='/tmp/out.f64')
SR = common.get_env('SR', default=16000, conv=int)

x = np.fromfile(IN_FILE, dtype='float64')
N = len(x)
n = np.arange(N)
t = n / SR

plt.plot(t, x)
plt.show()
Esempio n. 25
0
import math


def spectral_flux(x, H, W, window_type='hann'):
    if W >= 4:
        w = signal.get_window(window_type, W)
    else:
        w = np.ones(W)
    w /= np.sum(W)
    spec_flux_i = 0
    X = np.fft.fft(common.frame(x, H, W) * w[:, None], axis=0)
    spec_flux = np.sum(np.abs(np.diff(np.abs(X), axis=0)), axis=0)
    return spec_flux


INPUT = common.get_env('INPUT', check_if_none=True)
WINDOW_TYPE = common.get_env('WINDOW_TYPE', default='hann')
SAMPLE_RATE = common.get_env('SAMPLE_RATE', conv=float, default=16e3)
ATTACK_THRESH = common.get_env('ATTACK_THRESH', conv=float, default=0.05)
H = common.get_env('H', conv=int, default=2)
W = common.get_env('W', conv=int, default=8)
ALPHA = common.get_env('ALPHA', conv=float, default=.01)
# whether or not to normalize the spectral flux
NORMALIZE = common.get_env('NORMALIZE', conv=int, default=0)
# filter coefficient for smoothing the instantaneous amplitude
ALPHA_NORMALIZE = common.get_env('ALPHA_NORMALIZE', conv=float, default=0.01)
# threshold for the instantaneous amplitude below which no normalization is
# carried out (because very small amplitudes will cause huge values)
# value in dB
THRESH_NORMALIZE = common.get_env('THRESH_NORMALIZE', conv=float, default=-60)
X_LIM = common.get_env('X_LIM', conv=eval, default=(0, 2))
# Test avoiding attacks while time stretching using attack_avoider

import numpy as np
import matplotlib.pyplot as plt
import time_map_tstretch
import classic_puckette_timestretch
import common
import attack_finder

SAMPLE_RATE=16000
W=common.get_env('W',default=2048,conv=int)
H=common.get_env('H',default=512,conv=int)
S=common.get_env('S',default=0.5,conv=float)
NG_TH=common.get_env('NG_TH',default=-30,conv=float)

attack_times=np.array([0.5,1.,1.25])
attack_times=(attack_times*SAMPLE_RATE).astype('int')

av=time_map_tstretch.attack_avoider(
attack_times,
-3*H,
W+2*H,
H)

# make signal

sigs=[]
for fname in [
    '/tmp/piano_adj_beg/60.f64',
    '/tmp/piano_adj_beg/64.f64',
    '/tmp/piano_adj_beg/67.f64']:
Esempio n. 27
0
import common
import numpy as np
from scipy.interpolate import interp1d

INPUT = common.get_env('INPUT', default='/tmp/in.f64')
OUTPUT = common.get_env('OUTPUT', default='/tmp/out.f64')
S = common.get_env('S', default=1., conv=float)

x = np.fromfile(INPUT, dtype='float64')
n = np.arange(len(x))
t = np.arange(0, len(x) - 1, S)

interp = interp1d(n, x, kind='cubic')
y = interp(t)

y.tofile(OUTPUT)
Esempio n. 28
0
# Take a sound file
# Do some processing to get the attacks, be it spectral flux or high-frequency weighting
# Look for the local peaks. In order to filter out spurious peaks, we do a sort
# of noise-gating of the spectral flux signal by looking at the RMS amplitude

import numpy as np
from scipy import signal
import common
import spectral_difference
import subprocess
import high_freq_weighting_filter
import matplotlib.pyplot as plt
import window_tools

SAMPLE_RATE = common.get_env('SAMPLE_RATE', conv=float, default=16e3)
INPUT = common.get_env('INPUT', check_if_none=True)
OUTPUT = common.get_env('OUTPUT', default='/tmp/cut-%d.f64')
OUTPUT_SUMMARY = common.get_env('OUTPUT_SUMMARY',
                                default='/tmp/cut_summary.txt')

# window type for the spectral flux
WINDOW_TYPE_SF = common.get_env('WINDOW_TYPE_SF', default='hann')
# hop size of spectral flux
H_SF = common.get_env('H_SF', conv=int, default=256)
# window size of DFT implementation
W_SF = common.get_env('W_SF', conv=int, default=1024)
# smoothing factor (0-1) for SF
SMOOTH_SF = common.get_env('SMOOTH_SF', conv=float, default=1)
SF_THRESH = common.get_env('SF_THRESH', conv=float, default=0.01)
MAX_SEG_LEN = common.get_env('MAX_SEG_LEN', conv=float, default=float('inf'))
# If not None, Instead of using the most recent local minimum in the spectral
import attack_finder
import numpy as np
import mir_eval
import common
import matplotlib.pyplot as plt


def gef(n, f):
    return common.get_env(n, default=f, conv=float)


def gei(n, i):
    return common.get_env(n, default=i, conv=int)


SOUNDFILE = common.get_env('SOUNDFILE', check_if_none=True)
SAMPLE_RATE = common.get_env('SAMPLE_RATE', default=16e3, conv=float)
SCOREFILE = common.get_env('SCOREFILE', check_if_none=True)

# true time stamps in seconds
ts = synth_af_score.extract_ts(SCOREFILE)
ts = np.sort(np.array(ts))

x = np.fromfile(SOUNDFILE)
# estimated time stamps
H = gei('H', 256)
W = gei('W', 256)
alpha = gef('ALPHA', 1)
thresh = gef('THRESH', 3e-3)
ts_est, a = attack_finder.attack_region_estimation(x, H, W, alpha, thresh)
a_ts = ts_est[:-1][(np.diff(a) > 0)] / SAMPLE_RATE
import numpy as np
from scipy import signal
from pitch_shift import pitch_shifter
import window_tools
from classic_puckette_timestretch import pvoc_synth
import matplotlib.pyplot as plt
import rel_del_line
from time_map_tstretch import attack_avoider
import attack_finder
import common

REAL_TIME = False
from_file = True
adjust_for_attacks = True
SR = common.get_env('SR', default=16000, conv=int)

W = 1024
H = 256
if from_file:
    x = np.fromfile('/tmp/me.f64', dtype='float64')
    N = 0
    while N < (len(x) - H):
        N += H
    x = x[:N]
    n = np.arange(N)
    x += np.random.standard_normal(N) * 1e-8
    attack_time_pairs = attack_finder.attacks_from_spectral_diff(
        x, lmax_filt_rate=SR)
    attack_times = np.array([b for a, b in attack_time_pairs])
else:
Esempio n. 31
0
@author: mingrui
"""

import sys
import torch
from common import get_env, play
from dqn_agent import Agent

if __name__ == '__main__':
    if len(sys.argv) == 1:
        dqn_fname = None
    else:
        dqn_fname = sys.argv[1]

    # get env
    env, state_size, action_size = get_env()

    # load and play with trained agent
    agent = None
    if dqn_fname is not None:
        agent = Agent(state_size, action_size, seed=0)
        agent.dqn_local.load_state_dict(torch.load(dqn_fname))

        print('Playing with agent {}...'.format(dqn_fname))
        play(env, agent)
    else:
        # play ranomly
        print('Playing randomly...')
        play(env)

    env.close()