示例#1
0
def start_audio():
    # Initial parameters.
    saw = Waveform(saw_wave)
    sine = Waveform(sine_wave)
    square = Waveform(square_wave)
    sine.magnitude = 0.7
    saw.magnitude = 0.3
    saw.offset = 0.1
    square.magnitude = 0.0
    square.offset = 0.3

    sig_gen = SignalGenerator([sine, saw, square])
    audio = Audio(sig_gen, 5)
    audio.start_audio()
    return audio, sig_gen
示例#2
0
def generate(background_color, color, gap, height, manual_width, maximum_width,
             minimum_width, input_path, output_path):
    """
    \b
    Generating simple waveform image based on the given audio file.
    project home: https://github.com/danielbene/wform-cli

    \b
    usage examples:
        - wform-cli-win.exe c:\\path\\to\\audio.wav c:\\path\\to\\image.png
        - wform-cli-win.exe -bg '#FFFFFF' -c '#494949' c:\\audio.wav c:\\image.png
        - wform-cli-linux /home/user/Music/audio.wav /home/user/image.png
        - wform-cli-linux -manw 75000 /path/to/audio.wav image.png
        - wform-cli-linux -minw 20000 -maxw 200000 -c '#494949' /path/to/audio.wav image.png

    \b
    limitations:
        - audio files fully loaded into memory during generation
        - basic wav files supported out of the box,
            but everything else (mp3, ogg, etc) needs ffmpeg on the system
            (eg.: signed-integer wav encoding is ok, but a-law is not)
        - only png output is supported now (but it allows transparency)
    """
    waveform = Waveform(input_path, gap, height, manual_width, maximum_width,
                        minimum_width)
    wform_image = waveform.generate_waveform_image(background_color, color)
    waveform.save(output_path, wform_image)
示例#3
0
 def __init__(self, DR, SR, Fc, msg_len, Eb):
     self.data_rate = DR
     self.sampling_rate = SR
     self.sampling_frequency = SR * DR
     # samples per sec
     self.sampling_interval = 1.0 / self.sampling_frequency
     self.carrier_frequency = Fc  # (Hz)
     self.time = np.arange(0, self.sampling_interval * msg_len,
                           self.sampling_interval)  # time space
     self.bit_energy = Eb
     self.signal_power = DR * Eb
     self.amplitude = np.sqrt(self.signal_power)
     self.waveform1 = Waveform(self.amplitude, self.carrier_frequency,
                               self.time).cos()
     self.waveform2 = Waveform(self.amplitude, self.carrier_frequency,
                               self.time, np.pi).cos()
示例#4
0
 def __init__(self, configs, exec_manager=None):
     self.configs = configs
     if exec_manager is None:
         exec_manager = MPITaskPool()
     self.exec_manager = exec_manager
     if self.exec_manager.is_parent():
         self.waveforms = [Waveform(*config) for config in configs]
     else:
         self.waveforms = None
示例#5
0
def read_file(f):
    x = []
    y = []
    with open(f, 'r') as csvfile:
        r = csv.reader(csvfile, delimiter='\t')
        for row in r:
            x.append(float(row[0]))
            y.append(float(row[1]))

    return Waveform(x, y, 442 / 0.01, 0.5, 0.001, f)
示例#6
0
 def __init__(self):
     self.wind_speed = 5.0  # default wind speed
     self.coherent_pow_flg = True  # add coherent power
     self.coh_integrate_time = 0.001  # coherent integrateed time
     self.num_angles = 360  # integrated angle resolution
     self.interface_flg = 1  # curvature surface
     self.ddm_cov_factor = 5  # cov mode factor for ddm
     # # atmosphere loss for signal propagation 0.5 dB
     self.atmospheric_loss = pow(10.0, (0.5 / 10.0))
     # # members
     self.geometry = Geometry()
     self.nadir_RF = Antenna()
     self.zenith_RF = Antenna()
     self.signal = Signal()
     self.power_waveform = Waveform(True, 1000)
     self.interface = Interface()
def GetWaveDataR(configFileName,
                 directoryName,
                 fileNum=1,
                 getZeroCrossingIntegral=True):
    startTime = time.time()
    print("Running GetWaveData!")
    print("Starting at " + time.strftime('%H:%M:%S'))
    config = configparser.ConfigParser()
    config.read(configFileName)

    # Setup data info
    # Directories

    data_directory = directoryName  # New

    data_file_name = config['Directories']['data_file_name']
    #pywaves_directory = config['Directories']['pywaves_directory']

    # Digitizer
    dataFormatStr = config['Digitizer']['dataFormat']
    nSamples = int(config['Digitizer']['samples_per_waveform'])
    ns_per_sample = int(config['Digitizer']['ns_per_sample'])
    number_of_bits = int(config['Digitizer']['number_of_bits'])
    dynamic_range_volts = float(config['Digitizer']['dynamic_range_volts'])
    polarity0 = int(
        config['Digitizer']['polarity0'])  # Polarity of first several channels
    p0ch = int(config['Digitizer']
               ['p0ch'])  # Number of channels to apply first polarity to
    polarity1 = int(
        config['Digitizer']['polarity1'])  # Polarity of remaining channels
    baselineOffset = int(config['Digitizer']['baseline_offset'])
    nBaselineSamples = int(config['Digitizer']['baseline_samples'])
    nCh = int(config['Digitizer']['number_of_channels'])

    # nWavesPerLoad = int(config['Data Management']['waves_per_load'])
    nWavesPerLoad = 10000  # Chosen pretty arbitrarily
    # nWaves = int(config['Data Management']['waves_per_folder']) # per folder
    nWaves = 1000000  # Large number
    # Let's just do all of the folders!
    startFolder = int(config['Data Management']['start_folder'])
    nFolders = fileNum
    # nFolders = int(config['Data Management']['number_of_folders'])

    unevenFactor = int(config['Data Management']['uneven_factor'])
    cfdFraction = float(config['Pulse Processing']['cfd_fraction'])
    integralEnd = int(config['Pulse Processing']['integral_end'])
    totalIntegralStart = int(
        config['Pulse Processing']['total_integral_start'])
    tailIntegralStart = int(config['Pulse Processing']['tail_integral_start'])
    applyCRRC4 = bool(int(config['Pulse Processing']['apply_crrc4']))
    CRRC4Tau = float(config['Pulse Processing']['crrc4_shaping_time'])

    # Load pywaves
    # sys.path.extend([pywaves_directory])
    from dataloader import DataLoader
    from waveform import Waveform

    # Pre-calc
    if dataFormatStr == 'DPP_MIXED':
        dataFormat = DataLoader.DAFCA_DPP_MIXED
    elif dataFormatStr == 'STANDARD':
        dataFormat = DataLoader.DAFCA_STD
    if platform.system() is 'Windows':
        directory_separator = '\\'
    else:
        directory_separator = '/'

    # Initialize data arrays
    dataFile1 = data_directory + directory_separator + str(
        1) + directory_separator + data_file_name
    datloader1 = DataLoader(dataFile1, dataFormat, nSamples)
    nWavesIn1 = datloader1.GetNumberOfWavesInFile()
    # print(str(nWavesIn1))

    nLoads = int(nWavesIn1 / nWavesPerLoad)
    if nLoads < 1:
        nLoads = 1
    chBufferSize = int(nFolders * nWavesIn1 * unevenFactor / nCh)
    VperLSB = dynamic_range_volts / (2**number_of_bits)
    fileTimeGap = 2**43  # Note: no more than 3 hours per measurement!

    # Setup channel queues
    ph = np.zeros((nCh, chBufferSize))
    amp = np.zeros((nCh, chBufferSize))
    tailInt = np.zeros((nCh, chBufferSize))
    totalInt = np.zeros((nCh, chBufferSize))
    rms = np.zeros((nCh, chBufferSize))
    ttt = np.zeros((nCh, chBufferSize), dtype=np.uint32)
    extras = np.zeros((nCh, chBufferSize), dtype=np.uint32)
    fullTime = np.zeros((nCh, chBufferSize), dtype=np.uint64)
    cfd = np.zeros((nCh, chBufferSize))
    chCount = np.zeros(nCh, dtype=np.uint32)
    flags = np.zeros((nCh, chBufferSize), dtype=np.uint32)

    # Setup data loader
    waveform = Waveform(np.zeros(nSamples), polarity0, baselineOffset,
                        nBaselineSamples)
    print('polarity0 =' + str(polarity0))
    print('p0ch = ' + str(p0ch))
    print('polarity1 =' + str(polarity1))

    # Queue up waves
    for f in range(startFolder, startFolder + nFolders):
        print('Folder {}:'.format(f))
        fullDFileName = data_directory + directory_separator + str(
            f) + directory_separator + data_file_name
        datloader = DataLoader(fullDFileName, dataFormat, nSamples)
        nWavesInFile = datloader.GetNumberOfWavesInFile()
        nWaves = nWavesInFile + 1
        if (nWavesInFile < nWaves):
            print('Warning: requested more waves than exists in file!')
            loadsInFile = int(np.ceil(nWavesInFile / nWavesPerLoad))
            print('Loading all {} waves instead...'.format(nWavesInFile))
            lastLoad = nWavesInFile - (loadsInFile - 1) * nWavesPerLoad
        else:
            loadsInFile = nLoads
            lastLoad = nWavesPerLoad
        if nWavesInFile % 2 == 0 or nWavesInFile % 2 == 1 or int(nCh) == 2:
            for load in range(loadsInFile):
                if (load == loadsInFile - 1):
                    wavesThisLoad = lastLoad
                else:
                    wavesThisLoad = nWavesPerLoad
                waves = datloader.LoadWaves(wavesThisLoad)
                for w in range(wavesThisLoad):
                    ch = waves[w]['Channel']
                    waveform.SetSamples(waves[w]['Samples'])
                    if (ch >= p0ch):
                        waveform.Polarize(polarity1)
                    else:
                        waveform.Polarize(polarity0)
                    #print(str( waveform.polarity))
                    if applyCRRC4:
                        waveform.ApplyCRRC4(ns_per_sample, CRRC4Tau)
                    if getZeroCrossingIntegral:
                        ph[ch][
                            chCount[ch]] = waveform.GetIntegralToZeroCrossing(
                            ) * VperLSB * ns_per_sample
                    amp[ch][chCount[ch]] = waveform.GetMax()
                    tailInt[ch][chCount[ch]] = waveform.GetIntegralFromPeak(
                        tailIntegralStart,
                        integralEnd) * VperLSB * ns_per_sample
                    totalInt[ch][chCount[ch]] = waveform.GetIntegralFromPeak(
                        totalIntegralStart,
                        integralEnd) * VperLSB * ns_per_sample
                    cfd[ch][chCount[ch]] = waveform.GetCFDTime(
                        cfdFraction) * ns_per_sample
                    ttt[ch][chCount[ch]] = waves[w]['TimeTag']
                    rms[ch][chCount[ch]] = waveform.GetRMSbls(nBaselineSamples)
                    if dataFormatStr == 'DPP_MIXED':
                        extras[ch][chCount[ch]] = waves[w]['Extras']
                        #                    fullTime[ch][chCount[ch]] = ((waves[w]['TimeTag'] +
                        #                                                ((waves[w]['Extras'] & 0xFFFF0000)
                        #                                                << 15)))*ns_per_sample
                        fullTime[ch][chCount[ch]] = (
                            (waves[w]['TimeTag'] +
                             ((waves[w]['Extras'] & 0xFFFF0000) << 15)) +
                            fileTimeGap * f) * ns_per_sample
                    chCount[ch] += 1
    endTime = time.time()
    runTime = endTime - startTime
    print("GetWaveDataR took {} s".format(runTime))
    return chCount, ph, amp, tailInt, totalInt, cfd, ttt, extras, fullTime, flags, rms
示例#8
0
    def load_xml(self, node):
        """
        Initialize the instrument class attributes from XML received from CsPy
        
         Args:
            'node': type is ET.Element. tag should match self.expectedRoot
            node.tag == self.expectedRoot
        """

        self.is_initialized = False

        assert node.tag == self.expectedRoot, "expected node"+\
            f" <{self.expectedRoot}> but received <{node.tag}>"

        if not (self.exit_measurement or self.stop_connections):

            for child in node:

                if self.exit_measurement or self.stop_connections:
                    break

                try:

                    if child.tag == "enable":
                        self.enable = Instrument.str_to_bool(child.text)

                    elif child.tag == "resourceName":
                        self.physicalChannels = child.text

                    elif child.tag == "clockRate":
                        self.clockRate = float(child.text)

                    elif child.tag == "startTrigger":

                        # This is modifying the definitions of the outer for loop child and node. This
                        # seems dangerous.
                        for grandchild in child:

                            if node.text == "waitForStartTrigger":
                                self.startTrigger.wait_for_start_trigger = Instrument.str_to_bool(
                                    grandchild.text)
                            elif grandchild.text == "source":
                                self.startTrigger.source = grandchild.text
                            elif grandchild.text == "edge":
                                try:
                                    # CODO: could make dictionary keys in StartTrigger
                                    # lowercase and then just .lower() the capitalized keys
                                    # passed in elsewhere
                                    text = grandchild.text[0].upper(
                                    ) + grandchild.text[1:]
                                    self.startTrigger.edge = StartTrigger.nidaqmx_edges[
                                        text]
                                except KeyError as e:
                                    raise KeyError(
                                        f"Not a valid {grandchild.tag} value {grandchild.text} \n {e}"
                                    )
                            else:
                                self.logger.warning(
                                    f"Unrecognized XML tag \'{grandchild.tag}\'"
                                    +
                                    f" in <{child.tag}> in <{self.expectedRoot}>"
                                )

                    elif child.tag == "waveform":
                        self.waveform = Waveform()
                        self.waveform.init_from_xml(child)
                        self.samplesPerChannel = self.waveform.length  # the number of transitions

                        # reverse each state array
                        self.numChannels = len(self.waveform.states[0])
                        self.data = np.empty(
                            (self.samplesPerChannel, self.numChannels))
                        for i, state in enumerate(self.waveform.states):
                            self.data[i] = np.flip(state)

                    else:
                        self.logger.warning(
                            f"Unrecognized XML tag \'{child.tag}\' in <{self.expectedRoot}>"
                        )

                except (KeyError, ValueError):
                    raise XMLError(self, child)
示例#9
0
def GetWaveData(configFileName,
                getZeroCrossingIntegral=True,
                getWaves=True,
                loud=False,
                getTail=False,
                getTot=False,
                getPH=False,
                getAmp=False,
                getRMS=False,
                getExtras=False,
                getFullTime=False,
                getCFD=False,
                getflags=False):

    # --------------------------------------------------------------------------------------------------------------------- #
    #    Configuration
    # --------------------------------------------------------------------------------------------------------------------- #

    config = configparser.ConfigParser()
    config.read(configFileName)

    # Setup data info
    # Directories
    data_directory = config['Directories']['data_directory']
    data_file_name = config['Directories']['data_file_name']
    goodInd = False
    if 'goodind_file_name' in config['Directories']:
        goodInd = True
        goodind_file_name = config['Directories']['goodind_file_name']
    pywaves_directory = config['Directories']['pywaves_directory']

    # Load pywaves
    sys.path.extend([pywaves_directory])
    from dataloader import DataLoader
    from waveform import Waveform

    # Digitizer
    global dataFormatStr
    global nSamples
    global ns_per_sample
    global number_of_bits
    global dynamic_range_volts
    global polarity
    global baselineOffset
    global nBaselineSamples
    global nCh
    global nWavesPerLoad
    global nWaves
    global startFolder
    global nFolders
    global unevenFactor
    global cfdFraction
    global integralEnd
    global totalIntegralStart
    global tailIntegralStart
    global applyCRRC4
    global CRRC4Tau

    dataFormatStr = config['Digitizer']['dataFormat']
    nSamples = int(config['Digitizer']['samples_per_waveform'])
    ns_per_sample = int(config['Digitizer']['ns_per_sample'])
    number_of_bits = int(config['Digitizer']['number_of_bits'])
    dynamic_range_volts = float(config['Digitizer']['dynamic_range_volts'])
    polarity = int(config['Digitizer']['polarity'])
    baselineOffset = int(config['Digitizer']['baseline_offset'])
    nBaselineSamples = int(config['Digitizer']['baseline_samples'])
    nCh = int(config['Digitizer']['number_of_channels'])
    nWavesPerLoad = int(config['Data Management']['waves_per_load'])
    nWaves = int(config['Data Management']['waves_per_folder'])  # per folder
    startFolder = int(config['Data Management']['start_folder'])
    nFolders = int(config['Data Management']['number_of_folders'])
    unevenFactor = int(config['Data Management']['uneven_factor'])
    cfdFraction = float(config['Pulse Processing']['cfd_fraction'])
    integralEnd = int(config['Pulse Processing']['integral_end'])
    totalIntegralStart = int(
        config['Pulse Processing']['total_integral_start'])
    tailIntegralStart = int(config['Pulse Processing']['tail_integral_start'])
    applyCRRC4 = bool(int(config['Pulse Processing']['apply_crrc4']))
    CRRC4Tau = float(config['Pulse Processing']['crrc4_shaping_time'])

    # Pre-calc
    if dataFormatStr == 'DPP_MIXED':
        dataFormat = DataLoader.DAFCA_DPP_MIXED
    elif dataFormatStr == 'STANDARD':
        dataFormat = DataLoader.DAFCA_STD
    if platform.system() is 'Windows':
        directory_separator = '\\'
    else:
        directory_separator = '/'
    nLoads = int(nWaves / nWavesPerLoad)
    chBufferSize = int(nFolders * nWaves * unevenFactor / nCh)
    VperLSB = dynamic_range_volts / (2**number_of_bits)
    fileTimeGap = 2**43  # Note: no more than 3 hours per measurement!

    # --------------------------------------------------------------------------------------------------------------------- #
    #    Data structure setup
    # --------------------------------------------------------------------------------------------------------------------- #

    dataGetter = {}
    dataStorage = {}

    if getTail == True:
        dataGetter['tail'] = getWaveTail
        dataStorage['tail'] = np.zeros((nCh, chBufferSize))
    if getTot == True:
        dataGetter['total'] = getWaveTot
        dataStorage['total'] = np.zeros((nCh, chBufferSize))
    if getPH == True:
        dataGetter['ph'] = getWavePH
        dataStorage['ph'] = np.zeros((nCh, chBufferSize))
    if getCFD == True:
        dataGetter['cfd'] = getWaveCFD
        dataStorage['cfd'] = np.zeros((nCh, chBufferSize))
    if getRMS == True:
        dataGetter['rms'] = getWaveRMS
        dataStorage['rms'] = np.zeros((nCh, chBufferSize))
    if getAmp == True:
        dataGetter['amp'] = getWaveAmp
        dataSotage['amp'] = np.zeros((nCh, chBufferSize))

    if getExtras == True and dataFormatStr == 'DPP_MIXED':
        dataSotage['extra'] = np.zeros((nCh, chBufferSize), dtype=np.uint32)
    if getFullTime == True and dataFormatStr == 'DPP_MIXED':
        dataSotage['fulltime'] = np.zeros((nCh, chBufferSize), dtype=np.uint64)

    # Setup mandatory channel queues
    ttt = np.zeros((nCh, chBufferSize), dtype=np.uint32)
    chCount = np.zeros(nCh, dtype=np.uint32)
    flags = np.zeros((nCh, chBufferSize), dtype=np.uint32)

    # --------------------------------------------------------------------------------------------------------------------- #
    #    Data aquisition
    # --------------------------------------------------------------------------------------------------------------------- #

    startTime = time.time()
    print("Running GetWaveData!")
    print("Starting at " + time.strftime('%H:%M:%S'))

    # Setup data loader
    waveform = Waveform(np.zeros(nSamples), polarity, baselineOffset,
                        nBaselineSamples)

    pulses = []
    # Queue up waves
    for f in range(startFolder, startFolder + nFolders):
        print('\n Folder {}:'.format(f))
        fullDFileName = data_directory + directory_separator + str(
            f) + directory_separator + data_file_name
        print(fullDFileName)

        datloader = DataLoader(fullDFileName, dataFormat, nSamples)
        nWavesInFile = datloader.GetNumberOfWavesInFile()

        if (nWavesInFile < nWaves):
            print('Warning: requested more waves than exists in file!')
            loadsInFile = int(np.ceil(nWavesInFile / nWavesPerLoad))
            print('Loading all {} waves instead...'.format(nWavesInFile))
            lastLoad = nWavesInFile - (loadsInFile - 1) * nWavesPerLoad

        else:
            loadsInFile = nLoads
            lastLoad = nWavesPerLoad

        if goodInd == True:
            goodIndFileName = data_directory + directory_separator + str(
                f) + directory_separator + goodind_file_name
            goodIndices = []
            with open(goodIndFileName, "r") as goodfi:
                good_lines = goodfi.readlines()
                for line in good_lines:
                    goodIndices.append(int(line) - 1)
            goodIndices = np.array(goodIndices)
        else:
            goodIndices = np.arange(0, nWavesInFile - 1)

        waveNum = 0
        printProgressBar(0,
                         loadsInFile,
                         prefix='Progress: ',
                         suffix='Complete')
        for load in range(loadsInFile):
            if (load == loadsInFile - 1):
                wavesThisLoad = lastLoad
            else:
                wavesThisLoad = nWavesPerLoad
            waves = datloader.LoadWaves(wavesThisLoad)
            for w in range(0, wavesThisLoad):
                if waveNum == goodIndices[0]:
                    goodIndices = goodIndices[1:]
                    ch = waves[w]['Channel']
                    chCount[ch] += 1

                    # set up waveform structure
                    waveform = Waveform(waves[w]['Samples'],
                                        polarity,
                                        baselineOffset,
                                        nBaselineSamples,
                                        ch=waves[w]['Channel'],
                                        time=waves[w]['TimeTag'])
                    waveform.BaselineSubtract()

                    # CCR4
                    if applyCRRC4:
                        waveform.ApplyCRRC4(ns_per_sample, CRRC4Tau)

                    # add timing data to mandatory channel structure
                    ttt[ch][chCount[ch]] = waves[w]['TimeTag']

                    # populate data structure for optional
                    for key, value in dataGetter.items():
                        dataStorage[key][ch][chCount[ch]] = getGetter[key](
                            waveform)

                        ttt[ch][chCount[ch]] = waves[w]['TimeTag']
                    # get the whole wave
                    if getWaves == True:
                        pulses.append(waveform)

                waveNum += 1  # increment the wave counter in the current load
            # end iteration over waves in load - end load

            # update progress bar following new load
            printProgressBar(load + 1,
                             loadsInFile,
                             prefix='Progress: ',
                             suffix='Complete')

    endTime = time.time()
    runTime = endTime - startTime
    print("\nGetWaveData took {} s".format(runTime))
    if getWaves == False:
        return chCount, ttt, dataStorage
    else:
        return chCount, ttt, dataStorage, pulses
示例#10
0
def upload_route():
    if request.method == 'POST':
        if 'file' not in request.files:
            options = {"noFile": True}
            return render_template("upload.html", **options)

        files = request.files.getlist('file')
        model_file = os.path.join(os.getcwd(), 'model2', 'model')
        identify = classiFier(model_file=model_file, verbose=True)

        matches = []
        file_num = len(files)
        for file in files:
            if file.filename == '':
                options = {"emptyname": True}
                return render_template("upload.html", **options)

            else:
                filename = secure_filename(file.filename)
                user_file_temp = os.path.join(config.env['UPLOAD_FOLDER'],
                                              filename)

                file.save(user_file_temp)

                with open(user_file_temp, 'rb') as file_contents:
                    sample_id = crc32(file_contents.read())

                filename = str(sample_id) + '.WAV'
                user_file = os.path.join(config.env['UPLOAD_FOLDER'], filename)
                os.rename(user_file_temp, user_file)

                result = identify.classFile(user_file,
                                            username=current_user.get_id())
                first_match_name = result["values"][8]
                first_match = [{
                    "name":
                    first_match_name[1:first_match_name.find('_')].title(),
                    "value":
                    float(result["values"][9])
                }, {
                    "name": "Other",
                    "value": 1 - float(result["values"][9])
                }]
                second_match_name = result["values"][10]
                second_match = [{
                    "name":
                    second_match_name[1:second_match_name.find('_')].title(),
                    "value":
                    float(result["values"][11])
                }, {
                    "name": "Other",
                    "value": 1 - float(result["values"][11])
                }]
                third_match_name = result["values"][12]
                third_match = [{
                    "name":
                    third_match_name[1:third_match_name.find('_')].title(),
                    "value":
                    float(result["values"][13])
                }, {
                    "name": "Other",
                    "value": 1 - float(result["values"][13])
                }]

                user_waveform = Waveform(user_file)
                user_waveform.save()
                user_waveform_file = user_file.replace(
                    user_file.split('.')[-1], 'png').replace(os.getcwd(), '')
                user_file = user_file.replace(os.getcwd(), '..')

                activity_file = os.path.join(config.env['UPLOAD_FOLDER'],
                                             'activity/' + filename)
                if os.path.isfile(activity_file):
                    activity_waveform = Waveform(activity_file)
                    activity_waveform.save()
                    activity_waveform_file = activity_file.replace(
                        activity_file.split('.')[-1],
                        'png').replace(os.getcwd(), '')
                    activity_file = activity_file.replace(os.getcwd(), '..')
                else:
                    activity_waveform_file = None
                    activity_file = None

                noise_file = os.path.join(config.env['UPLOAD_FOLDER'],
                                          'noise/' + filename)
                if os.path.isfile(noise_file):
                    noise_waveform = Waveform(noise_file)
                    noise_waveform.save()
                    noise_waveform_file = noise_file.replace(
                        noise_file.split('.')[-1],
                        'png').replace(os.getcwd(), '')
                    noise_file = noise_file.replace(os.getcwd(), '..')
                else:
                    noise_waveform_file = None
                    noise_file = None

                user_clean_file = os.path.join(config.env['UPLOAD_FOLDER'],
                                               'users_clean/' + filename)
                if os.path.isfile(user_clean_file):
                    user_clean_waveform = Waveform(user_clean_file)
                    user_clean_waveform.save()
                    user_clean_waveform_file = user_clean_file.replace(
                        user_clean_file.split('.')[-1],
                        'png').replace(os.getcwd(), '')
                    user_clean_file = user_clean_file.replace(
                        os.getcwd(), '..')
                else:
                    user_clean_waveform_file = None
                    user_clean_file = None

                db = extensions.connect_to_database()

                cur = db.cursor()
                cur.execute("SELECT * FROM sampleInfo WHERE sampleid = %s",
                            (result['sample_id'], ))
                result_sample = cur.fetchall()

                cur.close()

                latitude = result_sample[0]['latitude']
                longitude = result_sample[0]['longitude']
                humidity = result_sample[0]['humidity']
                temp = result_sample[0]['temp']
                if temp:
                    temp = int(round(temp))
                light = result_sample[0]['light']
                if light:
                    light = int(round(light))

                matches.append({
                    'user': user_waveform_file,
                    'filename': user_file,
                    'sample_id': result['sample_id'],
                    'first_match': json.dumps(first_match),
                    'second_match': json.dumps(second_match),
                    'third_match': json.dumps(third_match),
                    'activity': activity_waveform_file,
                    'activity_audio': activity_file,
                    'noise': noise_waveform_file,
                    'noise_audio': noise_file,
                    'user_clean': user_clean_waveform_file,
                    'user_clean_audio': user_clean_file,
                    'file_num': file_num,
                    'latitude': latitude,
                    'longitude': longitude,
                    'humidity': humidity,
                    'temperature': temp,
                    'light': light
                })

        options = {
            'matches': matches,
        }

        return render_template("upload.html", **options)

    return render_template("upload.html")
示例#11
0
def apiUpload_route():
	
		

         	#basically copied and pastedd from ../controllers/upload.py. Difference is missing html rendering right here at the beginning and at end. See end for details. 
		files = request.files.getlist('file')
               
       	 	model_file = os.path.join(os.getcwd(), 'model2', 'model')
        	identify = classiFier(model_file=model_file, verbose=True)

        	matches = []
       		file_num = len(files)
       
                filename = secure_filename(file.filename)
                user_file_temp = os.path.join(config.env['UPLOAD_FOLDER'], filename)
                file.save(user_file_temp)

                with open(user_file_temp, 'rb') as file_contents:
                    sample_id = crc32(file_contents.read())

                filename = str(sample_id) + '.WAV'
                user_file = os.path.join(config.env['UPLOAD_FOLDER'], filename)
                os.rename(user_file_temp, user_file)

                result = identify.classFile(user_file, username=current_user.get_id())
                first_match_name = result["values"][8]
                first_match = [{"name": first_match_name[1:first_match_name.find('_')].title(), "value": float(result["values"][9])}, {"name": "Other", "value": 1 - float(result["values"][9])}]
                second_match_name = result["values"][10]
                second_match = [{"name": second_match_name[1:second_match_name.find('_')].title(), "value": float(result["values"][11])}, {"name": "Other", "value": 1 - float(result["values"][11])}]
                third_match_name = result["values"][12]
                third_match = [{"name": third_match_name[1:third_match_name.find('_')].title(), "value": float(result["values"][13])}, {"name": "Other", "value": 1 - float(result["values"][13])}]

                user_waveform = Waveform(user_file)
                user_waveform.save()
                user_waveform_file = user_file.replace(user_file.split('.')[-1], 'png').replace(os.getcwd(), '')
                user_file = user_file.replace(os.getcwd(), '..')

                activity_file = os.path.join(config.env['UPLOAD_FOLDER'], 'activity/' + filename)
                if os.path.isfile(activity_file):
                    activity_waveform = Waveform(activity_file)
                    activity_waveform.save()
                    activity_waveform_file = activity_file.replace(activity_file.split('.')[-1], 'png').replace(os.getcwd(), '')
                    activity_file = activity_file.replace(os.getcwd(), '..')
                else:
                    activity_waveform_file = None
                    activity_file = None

                noise_file = os.path.join(config.env['UPLOAD_FOLDER'], 'noise/' + filename)
                if os.path.isfile(noise_file):
                    noise_waveform = Waveform(noise_file)
                    noise_waveform.save()
                    noise_waveform_file = noise_file.replace(noise_file.split('.')[-1], 'png').replace(os.getcwd(), '')
                    noise_file = noise_file.replace(os.getcwd(), '..')
                else:
                    noise_waveform_file = None
                    noise_file = None

                user_clean_file = os.path.join(config.env['UPLOAD_FOLDER'], 'users_clean/' + filename)
                if os.path.isfile(user_clean_file):
                    user_clean_waveform = Waveform(user_clean_file)
                    user_clean_waveform.save()
                    user_clean_waveform_file = user_clean_file.replace(user_clean_file.split('.')[-1], 'png').replace(os.getcwd(), '')
                    user_clean_file = user_clean_file.replace(os.getcwd(), '..')
                else:
                    user_clean_waveform_file = None
                    user_clean_file = None

                cur = db.cursor()
                cur.execute("SELECT * FROM sampleInfo WHERE sampleid = %s", (result['sample_id'], ))
                result_sample = cur.fetchall()
                latitude = result_sample[0]['latitude']
                longitude = result_sample[0]['longitude']
                humidity = result_sample[0]['humidity']
                temp = result_sample[0]['temp']
                if temp:
                    temp = int(round(temp))
                light = result_sample[0]['light']
                if light:
                    light = int(round(light))

                matches.append({
                                'user': user_waveform_file,
                                'filename': user_file,
                                'sample_id': result['sample_id'], 
                                'first_match': json.dumps(first_match),
                                'second_match': json.dumps(second_match),
                                'third_match': json.dumps(third_match),
                                'activity': activity_waveform_file,
                                'activity_audio': activity_file,
                                'noise': noise_waveform_file,
                                'noise_audio': noise_file,
                                'user_clean': user_clean_waveform_file,
                                'user_clean_audio': user_clean_file,
                                'file_num': file_num,
                                'latitude': latitude,
                                'longitude': longitude,
                                'humidity': humidity,
                                'temperature': temp,
                                'light': light
                                })
        
        	options = {
        	    'matches': matches,
        	}
		#difference here. Instead of return html, returns file. 
		return jsonify(options)
def load_tmu(infile,song):

	index = 0 

	with open(infile,"rb") as file:
		data = file.read()
		file.close()	
			
		val = data[index]
		index += 1
		song.set_version(val & 0x0f)		# version
		song.set_type(val >> 4)				# type
		
		str = data[index:index+32]			# name
		index += 32		
		song.name = str.decode('utf-8')

		
		str = data[index:index+32]			# by
		index += 32		
		song.by = str.decode('utf-8')

		val = data[index]
		index += 1	
		song.set_speed(val)					#speed
		
		val = data[index]
		index += 1	
		song.restart = val					#order restart	
		
		val = data[index]
		index += 1	
		song.set_length(val)				#order length	
		
		lst = data[index:index+song.length]
		index += song.length
		song.order_list = lst				# order list
		
		for i in range(0,31):				# set 16 instrument names.
			ins = Instrument(i+1)
			str = data[index:index+16]	
			index += 16	
			try:
				ins.name = str.decode('utf-8')	
			except:
				raise SystemExit(f"Error reading instrument name. Invalid data!")
			i += 1
			song.ins.append(ins)

		for i in range(0,31):
			ins = song.ins[i]
			l = data[index]					# length
			ins.set_length(l)
			index += 1	
			r = data[index]					# restart
			ins.restart = r
			index += 1	
			
			if song.type == "SCC":
				w = data[index]				# waveform
				ins.waveform = w
			else:
				v = data[index]				# voice
				ins.voice = v
			index += 1				
			
			ins_data = data[index:index+(l*4)]
			r = 0
			for r in range(0,l):
				row = ins_data[r*4:(r*4)+4]
				ins.rows.append(row)
				r+=1
			index += (l*4)
			i += 1
		
		if song.type == "SCC":				# Waveform data
			for x in range(0,32):
				waveform = Waveform(x)
				waveform.data = data[index:index+32]
				song.waveforms.append(waveform)
				index +=32

		else:
			for x in range(0,16):			# Custom FM voices 
				voice = Voice(x+178)
				voice.data = data[index:index+8]
				song.voices.append(voice)
				index +=8

			
											# Drum names
			for d in range(0,20):
				drum = Drum(d)
				str = data[index:index+16]
				drum.name = str.decode('utf-8')
				d+=1
				index+=16
				song.drums.append(drum)
				
											#drum macros
			for d in range(0,20):
				drum = song.drums[d]
				l = data[index]
				drum.set_length(l)
				index+=1
				drm_data = data[index:index+(l*7)]
				index+=l*7
				r=0
				for r in range(0,l):
					row = drm_data[r*7:(r*7)+7]
					drum.rows.append(row)
					r+=1
				d+=1
				
			# THIS IS TO OVERCOME AN ERROR IN THE FILES
			index = index -1	
			
			
			p = 0							# Patterns
			t = 0
			while p != -1:
				num = data[index]
				if num == 255:
					break
				index+=1
				l = data[index]
				l += ord(data[index+1:index+2])*256
				index+=2
				# decompress pattern
				cmp_pat = data[index:index+l]
				pat = decompress_pattern(cmp_pat)
				index+=l
				# store pattern
				pattern = Pattern(num,t)
				song.patterns.append(pattern)
				#print (pattern.tracks)
				# store tracks
				chan = 0 
				for chan in range(0,8):
					#print(f"Pat:{num} Track: {t}")
					track = Track(t)
					row = 0
					for row in range(0,64):
						note = pat[(chan*4+row*32)+0]
						ins = pat[(chan*4+row*32)+1]
						tmp = int(pat[(chan*4+row*32)+2])
						par = pat[(chan*4+row*32)+3]

						vol = tmp >> 4
						cmd = tmp & 0x0f
						track.rows.append([note,ins,vol,cmd,par])
						row += 1
					chan += 1
					t += 1
					song.tracks.append(track)
示例#13
0
 def setup_waveform(self) -> None:
     self.waveform = Waveform()
     self.layout.addItem(self.waveform)