Exemple #1
0
def test_1():

    print("[%s:%d] test_1()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    #ref https://librosa.github.io/librosa/tutorial.html
    # 1. Get the file path to the included audio example
    filename = librosa.util.example_audio_file()

    # 2. Load the audio as a waveform `y`
    #    Store the sampling rate as `sr`
    y, sr = librosa.load(filename)

    # 3. Run the default beat tracker
    tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)

    print("[%s:%d] file => %s" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , filename
        ), file=sys.stderr)
    print("[%s:%d] tempo = %0.2f / len(beat_frames) = %d" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , tempo, len(beat_frames)
        ), file=sys.stderr)

    #     print('Estimated tempo: {:.2f} beats per minute'.format(tempo))

    # 4. Convert the frame indices of beat events into timestamps
    beat_times = librosa.frames_to_time(beat_frames, sr=sr)

    print('Saving output to beat_times.csv')
    librosa.output.times_csv('beat_times.csv', beat_times)
    '''###################
        file : 2        
    ###################'''
    filename = "C:\\WORKS_2\\WS\\WS_Others\\JVEMV6\\46_art\\3_sound-prog\\2_\\2_\\data\\audio.wav"

    # 2. Load the audio as a waveform `y`
    #    Store the sampling rate as `sr`
    y, sr = librosa.load(filename)

    # 3. Run the default beat tracker
    tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)

    print("[%s:%d] file => %s" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , filename
        ), file=sys.stderr)
    print("[%s:%d] tempo = %0.2f / len(beat_frames) = %d" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , tempo, len(beat_frames)
        ), file=sys.stderr)
Exemple #2
0
def test_4():

    print("[%s:%d] test_4()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    # Create a PrettyMIDI object
    cello_c_chord = pretty_midi.PrettyMIDI()
    # Create an Instrument instance for a cello instrument
    cello_program = pretty_midi.instrument_name_to_program('Cello')
    cello = pretty_midi.Instrument(program=cello_program)
    # Iterate over note names, which will be converted to note number later
    for note_name in ['C5', 'E5', 'G5']:
        # Retrieve the MIDI note number for this note name
        note_number = pretty_midi.note_name_to_number(note_name)
        # Create a Note instance for this note, starting at 0s and ending at .5s
        note = pretty_midi.Note(velocity=100,
                                pitch=note_number,
                                start=0,
                                end=.5)
        # Add it to our cello instrument
        cello.notes.append(note)
    # Add the cello instrument to the PrettyMIDI object
    cello_c_chord.instruments.append(cello)
    # Write out the MIDI data
    cello_c_chord.write('cello-C-chord.mid')
Exemple #3
0
def test_1():

    print("[%s:%d] test_1()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    file = "test.mid"

    pattern = midi.Pattern(resolution=960)  #このパターンがmidiファイルに対応しています。

    track = midi.Track()  #トラックを作ります
    pattern.append(track)  #パターンに作ったトラックを追加します。

    ev = midi.SetTempoEvent(tick=0, bpm=120)  #テンポを設定するイベントを作ります
    track.append(ev)  #イベントをトラックに追加します。

    e = midi.NoteOnEvent(tick=0, velocity=100,
                         pitch=midi.G_4)  #ソの音を鳴らし始めるイベントを作ります。
    track.append(e)

    e = midi.NoteOffEvent(tick=960, velocity=100,
                          pitch=midi.G_4)  #ソの音を鳴らし終えるイベントを作ります。
    track.append(e)

    eot = midi.EndOfTrackEvent(tick=1)  #トラックを終えるイベントを作ります
    track.append(eot)

    midi.write_midifile(file, pattern)  #パターンをファイルに書き込みます。
def test_2():
    
    w = 640
    h = 640
    
    center_X = w / 2
    center_Y = h / 2
    
    radius = 200
#     radius = 50
    
    col_R = randint(0, 255)
    col_G = randint(0, 255)
    col_B = randint(0, 255)
    
    colsOf_ImageNew = (col_R, col_G, col_B)
    
    sizeOf_Canvas = (w, h)
    
    dataOf_Ellipse = (center_X - radius, center_Y - radius,
                      center_X + radius, center_X + radius)
    
    im = Image.new("RGB", sizeOf_Canvas, colsOf_ImageNew)
#     im = Image.new("RGB", sizeOf_Canvas, (128, 128, 128))
#     im = Image.new("RGB", (512, 512), (128, 128, 128))
    
    draw = ImageDraw.Draw(im)
    
    #ref https://stackoverflow.com/questions/4789894/python-pil-how-to-draw-an-ellipse-in-the-middle-of-an-image#4790962
    #ref outline https://endoyuta.com/2015/09/27/python3-pillowの使い方/
    draw.ellipse(dataOf_Ellipse, outline=(0,0,0))
#     draw.ellipse(dataOf_Ellipse, fill=(0, 0, 255))
#     draw.ellipse((250, 300, 450, 400), fill=(0, 0, 255))
    
    '''###################
        file        
    ###################'''

    dpath_Out = "C:/WORKS_2/WS/WS_Others.Art/JVEMV6/46_art/6_visual-arts/3_free-drawing/1_use-gimp/2_/data2"
    
    fname = "image_%s.jpg" % libs.get_TimeLabel_Now()
    
    fpath_Out = "%s/%s" % (dpath_Out, fname)
    
    #ref https://endoyuta.com/2015/09/27/python3-pillowの使い方/
    res = im.save(fpath_Out)
    
    print()
    print("[%s:%d] save image => %s" % \
            (os.path.basename(libs.thisfile()), libs.linenum()
            , res
            ), file=sys.stderr)
    
    
    print()
    print ("[%s:%d] test_1 => done")
def exec_prog():
    '''###################
        ops        
    ###################'''
    test_1()

    print("[%s:%d] exec_prog() => done" % \
            (os.path.basename(libs.thisfile()), libs.linenum()

            ), file=sys.stderr)
Exemple #6
0
def test_5():

    print("[%s:%d] test_5()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    for i in range(128):

        name_Inst = pretty_midi.program_to_instrument_name(i)

        print("num = %d / %s" % (i, name_Inst))
def exec_prog(): # from : 
    
    '''###################
        ops        
    ###################'''
    test_3()
#     test_2()
#     test_1()
    
    '''###################
        Report        
    ###################'''
    print ("[%s:%d] exec_prog => done" % (os.path.basename(libs.thisfile()), libs.linenum()))
def test_1():

    A = 1  #振幅
    fs = 16000  #サンプリング周波数
    #     fs = 8000 #サンプリング周波数
    f0 = 392  #周波数
    #     f0 = 262  #周波数
    #     f0 = 440  #周波数
    sec = 5  #秒

    phase_Param = 0
    #     phase_Param = 4

    phase = f0 * (phase_Param / 2)
    #     phase = f0 * (4 / 2)
    #     phase = f0 / 2

    # bin data
    phase = np.pi * (1 / 4)

    binwave = wablibs.gen_WaveData(fs, f0, phase, sec, A)
    #     binwave = gen_WaveData(fs, f0, phase, sec, A)

    #     #サイン波をwavファイルとして書き出し
    wave_Params = (1, 2, fs, len(binwave), 'NONE', 'not compressed')
    #     wave_Params = (1, 2, 8000, len(binwave), 'NONE', 'not compressed')
    '''###################
        dirs, paths        
    ###################'''
    dname_Audios = "data.46_1\\audios"

    if not os.path.isdir(dname_Audios): os.makedirs(dname_Audios)

    #     fname_Out = "audio/output_%s.sin.fs-%d_f0-%d_phase-%s_sec-%d.wav" % \

    fname_Out = "%s\\output_%s.sin.fs-%d_f0-%d_phase-%s_sec-%d.wav" % \
                (dname_Audios
                , libs.get_TimeLabel_Now()
                , fs, f0
                , "%1.2f" % (phase_Param / 4.0) + "pi", sec)
    '''###################
        save        
    ###################'''
    wablibs.save_Wave(fname_Out, wave_Params, binwave)
    #     save_Wave(fname_Out, wave_Params, binwave)

    print()
    print("[%s:%d] save wave => done : %s" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , fname_Out
        ), file=sys.stderr)
Exemple #9
0
def show_WavInfos(fpath):

    wr = wave.open(fpath, "rb")
    '''###################
        infos        
    ###################'''
    print("[%s:%d] file : %s" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , fpath
        ), file=sys.stderr)

    print("channel : ", wr.getnchannels())
    print("sample size : ", wr.getsampwidth())
    print("getframerate() : ", wr.getframerate())
    print("getnframes() : ", wr.getnframes())
    print("getnframes() : ", wr.getparams())

    nchan = wr.getparams()

    print("nchan => %s (type = %s)" % (nchan, type(nchan)))
def test_1():
    
    im = Image.new("RGB", (512, 512), (128, 128, 128))
    
    dpath_Out = "C:/WORKS_2/WS/WS_Others.Art/JVEMV6/46_art/6_visual-arts/3_free-drawing/1_use-gimp/2_/data2"
    
    fname = "image_%s.jpg" % libs.get_TimeLabel_Now()
    
    fpath_Out = "%s/%s" % (dpath_Out, fname)
    
    #ref https://endoyuta.com/2015/09/27/python3-pillowの使い方/
    res = im.save(fpath_Out)
    
    print()
    print("[%s:%d] save image => %s" % \
            (os.path.basename(libs.thisfile()), libs.linenum()
            , res
            ), file=sys.stderr)
    
    
    print()
    print ("[%s:%d] test_1 => done")
Exemple #11
0
    print("[%s:%d] exec_prog() => done" % \
            (os.path.basename(libs.thisfile()), libs.linenum()

            ), file=sys.stderr)


'''
<usage>
test_1.py [-fXXX]  #=> frequency
test_1.py -f402
'''
if __name__ == "__main__":
    '''###################
    	validate : help option		
    ###################'''
    '''###################
    	get options		
    ###################'''
    '''###################
    	evecute		
    ###################'''
    exec_prog()

    print()

    print("[%s:%d] all done" % \
            (os.path.basename(libs.thisfile()), libs.linenum()

            ), file=sys.stderr)
#     print "[%s:%d] done" % (thisfile(), linenum())
    
    '''###################
        Report        
    ###################'''
    print ("[%s:%d] exec_prog => done" % (os.path.basename(libs.thisfile()), libs.linenum()))
 
#/def exec_prog(): # from : 20180116_103908

'''
<usage>
'''
if __name__ == "__main__" :

    '''###################
        validate : help option        
    ###################'''

    '''###################
        get options        
    ###################'''

    '''###################
        evecute        
    ###################'''
    exec_prog()

    print()
    
    print ("[%s:%d] all done" % (os.path.basename(os.path.basename(libs.thisfile())), libs.linenum()))

Exemple #13
0
def test_1():

    print("[%s:%d] test_1()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    #ref http://nbviewer.jupyter.org/github/librosa/librosa/blob/master/examples/LibROSA%20demo.ipynb
    audio_path = librosa.util.example_audio_file()

    print("[%s:%d] audio_path => %s" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , audio_path
        ), file=sys.stderr)

    y, sr = librosa.load(audio_path)

    print("[%s:%d] type(y) => %s (size = %d)" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , type(y), len(y)
        ), file=sys.stderr)
    #     [1_1.py:152] type(y) => <class 'numpy.ndarray'>

    print("[%s:%d] type(sr) => %s (int = %d)" % \
            (os.path.basename(libs.thisfile()), libs.linenum()
            , type(sr), sr
            ), file=sys.stderr)
    '''###################
        mel        
        #ref http://nbviewer.jupyter.org/github/librosa/librosa/blob/master/examples/LibROSA%20demo.ipynb
    ###################'''
    # Let's make and display a mel-scaled power (energy-squared) spectrogram
    S = librosa.feature.melspectrogram(y, sr=sr, n_mels=128)

    print("[%s:%d] type(S) => %s (S[0] = %s)" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , type(S), type(S[0])
        ), file=sys.stderr)
    #     [1_1.py:169] type(S) => <class 'numpy.ndarray'> (S[0] = <class 'numpy.ndarray'>)

    print("[%s:%d] type(S[0][0]) => %s" % \
        (os.path.basename(libs.thisfile()), libs.linenum()
        , type(S[0][0])
        ), file=sys.stderr)
    #     [1_1.py:174] type(S[0][0]) => <class 'numpy.float64'>

    # Convert to log scale (dB). We'll use the peak power (max) as reference.
    log_S = librosa.power_to_db(S, ref=np.max)

    # Make a new figure
    plt.figure(figsize=(12, 4))

    # Display the spectrogram on a mel scale
    # sample rate and hop length parameters are used to render the time axis
    librosa.display.specshow(log_S, sr=sr, x_axis='time', y_axis='mel')

    # Put a descriptive title on the plot
    plt.title('mel power spectrogram')

    # draw a color bar
    plt.colorbar(format='%+02.0f dB')

    # Make the figure layout compact
    plt.tight_layout()

    plt.show()
def test_3():
    
    '''###################
        params        
    ###################'''
    w = 640
    h = 640
    
    center_X = w / 2
    center_Y = h / 2
    
    r = 200
#     r = 50
    
    col_R = randint(0, 255)
    col_G = randint(0, 255)
    col_B = randint(0, 255)
    
    colsOf_ImageNew = (col_R, col_G, col_B)
    
    sizeOf_Canvas = (w, h)
    
    dataOf_Ellipse = (center_X - r, center_Y - r,
                      center_X + r, center_X + r)
    
    im = Image.new("RGB", sizeOf_Canvas, colsOf_ImageNew)
#     im = Image.new("RGB", sizeOf_Canvas, (128, 128, 128))
#     im = Image.new("RGB", (512, 512), (128, 128, 128))
    
    '''###################
        ellipse        
    ###################'''
    draw = ImageDraw.Draw(im)
    
    #ref https://stackoverflow.com/questions/4789894/python-pil-how-to-draw-an-ellipse-in-the-middle-of-an-image#4790962
    #ref outline https://endoyuta.com/2015/09/27/python3-pillowの使い方/
    draw.ellipse(dataOf_Ellipse, outline=(0,0,0))
#     draw.ellipse(dataOf_Ellipse, fill=(0, 0, 255))
#     draw.ellipse((250, 300, 450, 400), fill=(0, 0, 255))
    
    '''###################
        lines
    ###################'''
    coords_L1 = (w/2 - r, h/2, w/2 + r, h/2)
    draw.line(coords_L1, fill=(255, 0, 0), width=2)
#     draw.line(coords_L1, fill=(255, 0, 0), width=8)
#     draw.line((0, im.height, im.width, 0), fill=(255, 0, 0), width=8)

    coords_L2 = (w/2, h/2 - r, w/2, h/2 + r)
    draw.line(coords_L2, fill=(255, 0, 0), width=2)
    
#     # 45 degrees
#     th = np.pi / 4
#     
#     dx = r * np.cos(th)
#     dy = r * np.sin(th)
#     
#     coords_L3 = (w/2 + dx, h/2 - dy, w/2 - dx, h/2 + dy)
#     draw.line(coords_L3, fill=(255, 0, 0), width=2)
    
    for i in (1,2, 4, 5) :
#     for i in (1,2) :

        th = np.pi * i / 6
        
        dx = r * np.cos(th)
        dy = r * np.sin(th)
        
        coords_L4 = (w/2 + dx, h/2 - dy, w/2 - dx, h/2 + dy)
        draw.line(coords_L4, fill=(255, 0, 0), width=2)
        
    '''###################
        file        
    ###################'''

    dpath_Out = "C:/WORKS_2/WS/WS_Others.Art/JVEMV6/46_art/6_visual-arts/3_free-drawing/1_use-gimp/2_/data2"
    
    fname = "image_%s.jpg" % libs.get_TimeLabel_Now()
    
    fpath_Out = "%s/%s" % (dpath_Out, fname)
    
    #ref https://endoyuta.com/2015/09/27/python3-pillowの使い方/
    res = im.save(fpath_Out)
    
    print()
    print("[%s:%d] save image => %s" % \
            (os.path.basename(libs.thisfile()), libs.linenum()
            , res
            ), file=sys.stderr)
    
    
    print()
    print ("[%s:%d] test_3 => done")
Exemple #15
0
def test_3():

    print("[%s:%d] test_3()" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)

    #     fname = "test.%s.mid" % (libs.get_TimeLabel_Now())

    pitch_1 = midi.A_4
    pitch_2 = midi.G_4
    pitch_3 = midi.F_4
    pitch_4 = midi.E_4
    pitch_5 = midi.D_4
    pitch_6 = midi.C_4
    pitch_7 = midi.B_4

    ps = [
        midi.A_4,
        midi.G_4,
        midi.F_4,
        midi.E_4,
        midi.D_4,
        midi.C_4,
        midi.B_4,
    ]
    #     ps = [pitch_1, pitch_2, pitch_3, pitch_4]

    lenOf_PS = len(ps)

    numOf_Notes = 32

    # file name
    fname = "test.%s.ps-%02d.notes-%02d.mid" %\
         (libs.get_TimeLabel_Now(), len(ps), numOf_Notes)

    pattern = midi.Pattern(resolution=960)  #このパターンがmidiファイルに対応しています。

    track = midi.Track()  #トラックを作ります
    pattern.append(track)  #パターンに作ったトラックを追加します。

    ev = midi.SetTempoEvent(tick=0, bpm=120)  #テンポを設定するイベントを作ります
    track.append(ev)  #イベントをトラックに追加します。
    '''###################
        set : notes        
    ###################'''
    for i in range(numOf_Notes):
        #     for i in range(8):

        num = rnd.randint(0, lenOf_PS - 1)

        #         print("[%s:%d] num => %d" % \
        #         (os.path.basename(libs.thisfile()), libs.linenum()
        #         , num
        #         ), file=sys.stderr)
        #         num = rnd.randint(1, lenOf_PS)

        e = midi.NoteOnEvent(tick=0, velocity=100,
                             pitch=ps[num])  #ソの音を鳴らし始めるイベントを作ります。
        track.append(e)

        e = midi.NoteOffEvent(tick=960, velocity=100,
                              pitch=ps[num])  #ソの音を鳴らし終えるイベントを作ります。
        track.append(e)
#         e = midi.NoteOnEvent(tick=0, velocity=100, pitch= pitch_1) #ソの音を鳴らし始めるイベントを作ります。
#         track.append(e)
#
#         e = midi.NoteOffEvent(tick=960, velocity=100, pitch= pitch_1) #ソの音を鳴らし終えるイベントを作ります。
#         track.append(e)

#/for i in range(8):
    '''###################
        track : end        
    ###################'''
    eot = midi.EndOfTrackEvent(tick=1)  #トラックを終えるイベントを作ります
    track.append(eot)

    midi.write_midifile(fname, pattern)  #パターンをファイルに書き込みます。
    '''###################
def test_1():

    #ref https://qiita.com/kinpira/items/75513eaab6eed19da9a3
    #     path = 'audio_sample_amivoice.raw'
    path = '20181008 151334.16bit-16khz.aiff'
    #     path = '20181008 151334.16bit-16khz.wav'
    #     path = '20181008-151334.wav'
    #     path = '/home/pi/test.wav'

    #APIKEY = "58362f467950765273456f4652485a516c6258465a75794e79794a4835386869412f33576876774c767631"
    APIKEY = "71596d4e512e752e4e7a44507463445767694c70485254485251674174384c4a33576a7253457478495431"

    #ref https://dev.smt.docomo.ne.jp/?p=docs.api.page&api_name=speech_recognition&p_name=api_amivoice_1#tag01
    #     https://api.apigw.smt.docomo.ne.jp/amiVoice/v1/recognize

    url = "https://api.apigw.smt.docomo.ne.jp/amiVoice/v1/recognize?APIKEY={}".format(
        APIKEY)

    print("[%s:%d] url = %s" % \
                                (os.path.basename(libs.thisfile()), libs.linenum()
                                , url
                                ), file=sys.stderr)

    print("[%s:%d] path = %s" % \
                                (os.path.basename(libs.thisfile()), libs.linenum()
                                , path
                                ), file=sys.stderr)

    #     [voice_recog.py:148]
    # url = https://api.apigw.smt.docomo.ne.jp/amiVoice/v1/recognize?APIKEY=58362f467950765273456f4652485a516c6258465a75794e79794a4835386869412f33576876774c767631

    # validate
    #     f = open(path, "rb")

    if not os.path.isfile(path):  #if のtos.path.isfile(path)

        print("[%s:%d] file not exist : %s" % \
            (os.path.basename(libs.thisfile()), libs.linenum()
            , path
            ), file=sys.stderr)

        return

    #/if のtos.path.isfile(path)

    files = {"a": open(path, 'rb'), "v": "on"}

    r = requests.post(url, files=files)

    print("r =>")
    print(r)

    #     r =>
    # <Response [401]>

    #     print (r.json())
    #     print (r.json()['text'])

    #     r =>
    # <Response [200]>
    # {'utteranceid': '20181008/docomo-dds-test@1841153612-LOHwlMQ', 'results': [{'end
    # time': 6410, 'tokens': [{'endtime': 1970, 'confidence': 0.87, 'spoken': 'はー',
    # 'starttime': 1430, 'written': 'はあ'}, {'endtime': 2240, 'confidence': 0.3, 'spo
    # ken': '_', 'starttime': 1970, 'written': '。'}, {'endtime': 2710, 'confidence':
    # 0.67, 'spoken': 'はー', 'starttime': 2240, 'written': 'はあ'}, {'endtime': 2900,
    #  'confidence': 0.86, 'spoken': '_', 'starttime': 2710, 'written': '。'}, {'endti
    # me': 4130, 'confidence': 0.94, 'spoken': 'か', 'starttime': 3600, 'written': '下
    # '}, {'endtime': 4850, 'confidence': 1.0, 'spoken': 'か', 'starttime': 4340, 'wri
    # tten': 'か'}, {'endtime': 5540, 'confidence': 0.99, 'spoken': 'か', 'starttime':
    #  5080, 'written': '下'}, {'endtime': 6120, 'confidence': 0.99, 'spoken': 'か', '
    # starttime': 5590, 'written': 'か'}, {'endtime': 6410, 'confidence': 0.22, 'spoke
    # n': '_', 'starttime': 6120, 'written': '。'}], 'rulename': '', 'confidence': 0.6
    # 39, 'tags': [], 'starttime': 0, 'text': 'はあ。はあ。下か下か。'}], 'message': '
    # ', 'code': '', 'text': 'はあ。はあ。下か下か。'}

    # get keys
    #ref https://stackoverflow.com/questions/15789059/python-json-only-get-keys-in-first-level#15789236
    json = r.json()

    keys = json.keys()

    for item in keys:

        print(item)

    #/for item in keys:

    for item in keys:

        print("%s =>" % item)
        print(json[item])

        #/for item in keys:

    # results
    print()

    results = json['results']

    #     keys_results = results.keys()

    #     print("tokens => %d tokens" % len(results[0]['tokens']))
    #     print(results[0]['tokens'])

    for item in results[0]['tokens']:

        print(item)

    #/for item in results[0]['tokens']:
    # {'starttime': 1430, 'endtime': 1970, 'confidence': 0.87, 'spoken': 'はー', 'writ
    # ten': 'はあ'}
    # {'starttime': 1970, 'endtime': 2240, 'confidence': 0.3, 'spoken': '_', 'written'
    # : '。'}
    # {'starttime': 2240, 'endtime': 2710, 'confidence': 0.67, 'spoken': 'はー', 'writ
    # ten': 'はあ'}
    # {'starttime': 2710, 'endtime': 2900, 'confidence': 0.86, 'spoken': '_', 'written
    # ': '。'}
    # {'starttime': 3600, 'endtime': 4130, 'confidence': 0.94, 'spoken': 'か', 'writte
    # n': '下'}
    # {'starttime': 4340, 'endtime': 4850, 'confidence': 1.0, 'spoken': 'か', 'written
    # ': 'か'}
    # {'starttime': 5080, 'endtime': 5540, 'confidence': 0.99, 'spoken': 'か', 'writte
    # n': '下'}
    # {'starttime': 5590, 'endtime': 6120, 'confidence': 0.99, 'spoken': 'か', 'writte
    # n': 'か'}
    # {'starttime': 6120, 'endtime': 6410, 'confidence': 0.22, 'spoken': '_', 'written
    # ': '。'}

# #     for item in keys_results:
#     for item in results:
#
#         print(item)
#
# #         print("[%s:%d] keys_results : %s" % \
# #                 (os.path.basename(libs.thisfile()), libs.linenum()
# #                 , item
# #                 ), file=sys.stderr)

#/for item in keys_results:

#     for item in json['results']:
#
#         print(item)
#
#     #/for item in json['results']:


    print("[%s:%d] test_1 : done" % \
        (os.path.basename(libs.thisfile()), libs.linenum()

        ), file=sys.stderr)
Exemple #17
0
def test_1():
    '''###################
        step: 1
            vars
    ###################'''
    dpath_Main = "C:\\WORKS_2\\WS\\WS_Others.Art\\JVEMV6\\46_art\\11_guitar"

    dpath_Target_Dir = "C:\\WORKS_2\\WS\\WS_Others.Art\\JVEMV6\\46_art\\11_guitar\\for_conversion.dir"

    fname_ListOf_Data = "list_of_data.dat"
    '''###################
        step: 2
            get : list of : dir list in dpath_Target_Dir
    ###################'''
    strOf_M4A_Ext = "m4a"

    #ref https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
    #ref https://www.tutorialspoint.com/python/string_endswith.htm
    lo_Source_M4A_Files = [
        f for f in os.listdir(dpath_Target_Dir) if f.endswith(strOf_M4A_Ext)
    ]

    if SWITCH_DEBUG == True:

        #debug
        msg = "[%s:%d] lo_Source_M4A_Files ==> " % (os.path.basename(
            libs.thisfile()), libs.linenum())

        print("%s" % (msg), file=sys.stderr)

        print(lo_Source_M4A_Files)
        print("total : %d" % len(lo_Source_M4A_Files))
    '''###################
        step: 3
            build : list of final fnames set
    ###################'''
    '''###################
        step: 3 : 1
            dat file : read lines
    ###################'''
    # file : open
    f_in_dat = open(os.path.join(dpath_Target_Dir, fname_ListOf_Data), "r")

    lo_Dat_File_Lines = f_in_dat.readlines()

    if SWITCH_DEBUG == True:

        #debug
        msg = "[%s:%d] lo_Dat_File_Lines ==> " % (os.path.basename(
            libs.thisfile()), libs.linenum())

        print("%s" % (msg), file=sys.stderr)

        print(lo_Dat_File_Lines)
        print("total : %d" % len(lo_Dat_File_Lines))
    '''###################
        step: 3 : X
            close : file
    ###################'''
    # file : open
    f_in_dat.close()
    '''###################
        step: 3 : 2
            build : each line ==> tokenise
    ###################'''
    lo_Dat_File_Lines__Tokenized = []

    for item in lo_Dat_File_Lines:

        lo_Dat_File_Lines__Tokenized.append((item.strip()).split("\t"))
#         lo_Dat_File_Lines__Tokenized.append(item.split("\t"))

#/for item in lo_Dat_File_Lines:

    if SWITCH_DEBUG == True:

        #debug
        msg = "[%s:%d] lo_Dat_File_Lines__Tokenized ==> " % (os.path.basename(
            libs.thisfile()), libs.linenum())

        print("%s" % (msg), file=sys.stderr)

        for item in lo_Dat_File_Lines__Tokenized:

            print(item)

        #/for item in lo_Dat_File_Lines__Tokenized:

        print("total : %d" % len(lo_Dat_File_Lines__Tokenized))

    #_20190816_153352:tmp
    '''###################
        step: 3 : 3
            build : lo_Final
    ###################'''
    lo_Final = []

    for item in lo_Dat_File_Lines__Tokenized:

        # item ==> ['21', '20190815 180358.m4a', 'g-0815-6']
        lenOf_Item = len(item)

        if lenOf_Item == 3:  #if lenOf_Item == 3

            # new file name
            tokens = item[1].split(".")  # 20190815 171714.m4a

            tokens_2 = tokens[0].split(" ")  #=> "20190815" "171714"

            fname_New = "%s.[%s_%s].m4a" % (item[2], tokens_2[0], tokens_2[1])
            #             fname_New = "%s.[%s].m4a" % (item[2], item[1])

            # build the final set
            setOf_Final_Entries = [
                item[1]  # '20190815 180358.m4a' (source file name)
                ,
                fname_New
                #                     , "%s.[%s].m4a" % (item[2], item[1])
            ]

            # append
            lo_Final.append(setOf_Final_Entries)

        #/if lenOf_Item == 3

    #/for item in lo_Dat_File_Lines__Tokenized:

    #debug
    msg = "[%s:%d] lo_Final ==> "

    print("%s" % (msg), file=sys.stderr)

    for item in lo_Final:

        print(item)

    #/for item in lo_Dat_File_Lines__Tokenized:

    print("total : %d" % len(lo_Final))
    '''###################
        step: 4
            copy : new files
    ###################'''
    cntOf_Copy = 0

    for item in lo_Final:

        #_20190816_154557:tmp

        # fpath : src
        fpath_Src = os.path.join(dpath_Target_Dir, item[0])
        fpath_Dst = os.path.join(dpath_Target_Dir, item[1])

        #ref https://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python
        res = shutil.copyfile(fpath_Src, fpath_Dst)
        # [manage_voicememos_20190816_143728.py:203] res => C:\WORKS_2\WS\WS_Others.Art\JV
        # EMV6\46_art\11_guitar\for_conversion.dir\g-0815-5.[20190815_174452].m4a

        #         msg = "[%s:%d] res => %s" % \
        #                 (os.path.basename(libs.thisfile()), libs.linenum(), res)
        #
        #         print("%s" % (msg), file=sys.stderr)

        # count
        cntOf_Copy += 1

    #/for item in lo_Final:

#     if True :

#debug
    msg = "[%s:%d] cntOf_Copy ==> %d" % \
            (os.path.basename(libs.thisfile()), libs.linenum(), cntOf_Copy)

    print("%s" % (msg), file=sys.stderr)

    #     for item in lo_Dat_File_Lines__Tokenized:
    #
    #         print(item)
    #
    #     #/for item in lo_Dat_File_Lines__Tokenized:
    #
    #     print("total : %d" % len(lo_Dat_File_Lines__Tokenized))

    #     '''###################
    #         step: 3 : X
    #             close : file
    #     ###################'''
    #     # file : open
    #     f_in_dat.close()


    msg = "[%s:%d] test_1 : done" % \
        (os.path.basename(libs.thisfile()), libs.linenum())

    print("%s" % (msg), file=sys.stderr)