# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import wave
import numpy as np
import pylab
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import math

import warnings
warnings.simplefilter("ignore", DeprecationWarning)

# глобальные переменные
delta = 50
reduceCount = 5

types = {
    1: np.int8,
    2: np.int16,
    4: np.int32
}


# -

# Запись массива сэмплов в файл
def printSamples(samples):
    output = open("samples.txt", "w")
    for sample in samples:
        string ='{:.2f}'.format(sample)
        output.write(string + '\n')
    output.close()


def printSamplesInFile(samples, filename):
    output = open(filename, "w")
    for sample in samples:
        string ='{:.2f}'.format(sample)
        output.write(string + '\n')
    output.close()


# Свертка (сжимает массив сэмплов, усредняя значения)
def cutSamples(samples):
    i = 0
    values = []
    while i + delta < samples.size:
        samplesSlice = samples[i:i+delta]
        samplesSlice = list(map(lambda x: abs(x), samplesSlice))
        samplesSlice.sort()
        samplesSlice = samplesSlice[reduceCount : delta - reduceCount]
        value = sum(samplesSlice) / len(samplesSlice)
        values.append(value)
        i = i + delta
    
    return values


# Обрезка файла    
def cutAudio(fileName, source, target, outputName): 
    inputFile = wave.open(fileName, mode="r")
    (channels, sWidth, rate, framesCount, comptype, compname) = inputFile.getparams()
    
    content = inputFile.readframes(framesCount)
    samples = np.fromstring(content, dtype=types[sWidth])
    samples = samples[round(source*rate):round(target*rate)]

    outputFile = wave.open(outputName, mode="w")
    outputFile.setparams((channels, sWidth, rate, samples.size, comptype, compname))
    outputFile.writeframes(samples)
    outputFile.close()
    
    return cutSamples(samples)


# +
values = cutAudio("records/111.wav", 5.22, 5.67, "5,1-5,8.wav")

pylab.plot(values)
pylab.show()

# +
recordName = "records/Шишкина 17.02.15_new.wav"
wav = wave.open(recordName, mode="r")
(nchannels, sampwidth, framerate, nframes, comptype, compname) = wav.getparams()
print(nchannels, sampwidth, framerate, nframes, comptype, compname)

duration = nframes / framerate
content = wav.readframes(nframes)
samples = np.fromstring(content, dtype=types[sampwidth])
values = cutSamples(samples)
printSamples(values)

# нахождение пиков в записи
frameOnCut = []
i = 20
prevResults = i
while i < len(values):
    if values[i] > 10000:
        slice = values[i-prevResults:i]
        minPrevValue = min(slice)
        if values[i] / minPrevValue > 20:
            frameOnCut.append(i)
            i += 150
            continue
    i += 1

# переводим величины массива frameOnCut из порядкового номера фрейма в секунды
frameOnCut = list(map(lambda x: x*delta, frameOnCut))
frameOnCut = list(map(lambda x: x/framerate, frameOnCut))
print(len(frameOnCut))
print(frameOnCut)

# вырезаем аудио-файл с каждым пиком и строим диаграмму
for framePik in frameOnCut:
    endPath = '{:.2f}'.format(framePik)
    path = "results/sounds/result_" + endPath + ".wav"
    imagePath = "results/graphics/result_" + endPath + ".png"
    path = path.replace(".", ",", 1)
    imagePath = imagePath.replace(".", ",", 1)
    values = cutAudio(recordName, framePik-0.05, framePik+0.4, path)
    plt.plot(values)
    plt.savefig(imagePath)
    plt.close()
# -

import os
def convertSoundsInSamples(directory):
    files = os.listdir(directory)
    sounds = filter(lambda x: x.endswith('.wav'), files)

    for sound in sounds:
        wav = wave.open(directory + "/" + sound, mode="r")
        (nchannels, sampwidth, framerate, nframes, comptype, compname) = wav.getparams()

        content = wav.readframes(nframes)
        samples = np.fromstring(content, dtype=types[sampwidth])
        cuttedSamples = cutSamples(samples)
        filename = sound[:-3]
        printSamplesInFile(cuttedSamples, directory + "/samples/" + filename + "txt")


import os
convertSoundsInSamples("results/кашель")
convertSoundsInSamples("results/не кашель")

convertSoundsInSamples("results/test")



StarcoderdataJupyterScriptsDedupFiltered