def track_bisect(test, song, dest_version=3): """Save song in *n* files, where *n* is number of tracks in song. Resulting tabs have following tracks: - ``*-T01.gp?``: *1st* track - ``*-T02.gp?``: *1st* and *2nd* track - ... - ``*-Tnn.gp?``: *1st*, *2nd*, ..., *nth* track This function helps to find the track where erroneous data was written using bisection method. """ folder, _ = path.splitext(test) try: os.mkdir(path.join(OUTPUT, folder)) except OSError: pass tracks = song.tracks[:] for number, track in enumerate(tracks, 1): dest_path = path.join(OUTPUT, folder, test + '-T%02d.gp%d' % (number, dest_version)) song.tracks = tracks[:number] guitarpro.write(song, dest_path)
def bisect(test, song, dest_version=3): """Save song in *n* files, where *n* is number of measures in song. Resulting tabs have following measures: - ``*-001.gp?``: *1st* measure - ``*-002.gp?``: *1st* and *2nd* measure - ... - ``*-nnn.gp?``: *1st*, *2nd*, ..., *nth* measure This function helps to find the measure where erroneous data was written using bisection method. """ folder, _ = path.splitext(test) try: os.mkdir(path.join(OUTPUT, folder)) except OSError: pass trackMeasures = [track.measures for track in song.tracks] for number, _ in enumerate(trackMeasures[0], 1): dest_path = path.join(OUTPUT, folder, test + '-%03d.gp%d' % (number, dest_version)) for track in song.tracks: track.measures = trackMeasures[track.number - 1][:number] guitarpro.write(song, dest_path)
def save_file(self): fname = QtWidgets.QFileDialog.getSaveFileName( self, 'Open file', 'c:\\', "GuitarPro files (*.gp3 *.gp4 *.gp5)") if fname[0] != '': guitars = [] tab1 = guitarpro.parse(self.path) for i in self.guitarTracksList: for j in tab1.tracks: if i.name == j.name: guitars.append(j) tab = guitarpro.models.Song() tab.tempo = guitars[0].song.tempo tab.version = 'FICHIER GUITAR PRO v3.00' tab.tracks = guitars nnd = Neural_network_drums.NeuralNetwork('weights/rock_drums.h5') nnb = Neural_network_bass.NeuralNetwork('weights/rock_bass.h5') for i in self.drumTracksList: predict = nnd.Predict(self.Tab.guitarTracks[i.baseTrack]) drum_data.addTrack(guitars[0], predict, i.name, tab) for i in self.bassTracksList: predict, first_string, key, mm = nnb.Predict( self.Tab.guitarTracks[i.baseTrack], self.path) bass_data.addTrack(guitars[0], predict, i.name, tab, first_string, key, mm) guitarpro.write(tab, fname[0])
def test_empty(output_folder): empty_a = guitarpro.Song() destpath = path.join(output_folder, 'Empty.gp5') guitarpro.write(empty_a, destpath, version=(5, 2, 0)) empty_b = guitarpro.parse(destpath) assert empty_a == empty_b
def bisect(test, song, destVersion=3): """Save song in *n* files, where *n* is number of measures in song. Resulting tabs have following measures: - ``*-001.gp?``: *1st* measure - ``*-002.gp?``: *1st* and *2nd* measure - ... - ``*-nnn.gp?``: *1st*, *2nd*, ..., *nth* measure This function helps to find the measure where erroneous data was written using bisection method. """ folder, _ = path.splitext(test) try: os.mkdir(path.join(OUTPUT, folder)) except OSError: pass trackMeasures = [track.measures for track in song.tracks] for number, _ in enumerate(trackMeasures[0], 1): destPath = path.join(OUTPUT, folder, test + '-%03d.gp%d' % (number, destVersion)) for track in song.tracks: track.measures = trackMeasures[track.number - 1][:number] gp.write(song, destPath)
def testReadWriteEquals(tmpdir, filename): filepath = path.join(LOCATION, filename) songA = gp.parse(filepath) destpath = str(tmpdir.join(filename)) gp.write(songA, destpath) songB = gp.parse(destpath) assert songA == songB
def testEmpty(tmpdir): emptyA = gp.Song() destpath = str(tmpdir.join('Empty.gp5')) gp.write(emptyA, destpath, version=(5, 2, 0)) emptyB = gp.parse(destpath) assert emptyA == emptyB
def test_empty(tmpdir): empty_a = guitarpro.Song() destpath = str(tmpdir.join('Empty.gp5')) guitarpro.write(empty_a, destpath, version=(5, 2, 0)) empty_b = guitarpro.parse(destpath) assert empty_a == empty_b
def save(self, *args): gp_song = self.gp_song artist, album, song_title = gp_song.artist.title( ), gp_song.album.title(), gp_song.title.title() filepath = self.prep_filepath(artist, album, song_title) # Check if song already exists in database. if slf.get_saved_song_info(artist, album, song_title): self.fileoverwrite_popup = FileOverwritePopup( cancel=self.cancel_overwrite, overwrite=self.overwrite, artist=artist, album=album, song_title=song_title) self.fileoverwrite_popup.open() else: guitarpro.write(self.gp_song, filepath, version=(5, 1, 0), encoding='cp1252') edit_instructions = [] for measure in self.flat_song[0]: edit_instructions.append(str(measure.header.number)) edit_instructions = ','.join(edit_instructions) slf.save_song_to_library(artist, album, song_title, filepath, edit_instructions)
def remove_rests(input_filename, output_filename): """Read a gp file 'input_filename', write to 'output_filename'.""" song = guitarpro.parse(input_filename) song.tracks = [ remove_rests_from_track(track) if track.isPercussionTrack else track for track in song.tracks ] guitarpro.write(song, output_filename)
def test_clipboard(output_folder): filepath = path.join(LOCATION, '2 whole bars.tmp') song_a = guitarpro.parse(filepath) song_a.clipboard = None destpath = path.join(output_folder, '2 whole bars.tmp.gp5') guitarpro.write(song_a, destpath) song_b = guitarpro.parse(destpath) assert song_a == song_b
def test_conversion(output_folder, filename): __, ext = path.splitext(filename) filepath = path.join(LOCATION, filename) song_a = guitarpro.parse(filepath) destpath = path.join(output_folder, filename + ext) guitarpro.write(song_a, destpath) song_b = guitarpro.parse(destpath) assert song_a == song_b
def convert_and_compare(filename): __, ext = path.splitext(filename) filepath = path.join(LOCATION, filename) song_a = guitarpro.parse(filepath) destpath = path.join(OUTPUT, filename + ext) guitarpro.write(song_a, destpath) song_b = guitarpro.parse(destpath) assert song_a == song_b
def testClipboard(tmpdir): filepath = path.join(LOCATION, '2 whole bars.tmp') songA = gp.parse(filepath) songA.clipboard = None destpath = str(tmpdir.join('2 whole bars.tmp.gp5')) gp.write(songA, destpath) songB = gp.parse(destpath) assert songA == songB
def testConversion(tmpdir, source, targetExt): sourcepath = path.join(LOCATION, source) songA = gp.parse(sourcepath) songA.versionTuple = None # Remove the version so it's determined by the extension destpath = str(tmpdir.join(f'{source}.{targetExt}')) gp.write(songA, destpath) songB = gp.parse(destpath) assert songA == songB
def test_clipboard(tmpdir): filepath = path.join(LOCATION, '2 whole bars.tmp') song_a = guitarpro.parse(filepath) song_a.clipboard = None destpath = str(tmpdir.join('2 whole bars.tmp.gp5')) guitarpro.write(song_a, destpath) song_b = guitarpro.parse(destpath) assert song_a == song_b
def standardize(input_filename, output_filename): """Read a gp file 'input_filename', write to 'output_filename'.""" song = guitarpro.parse(input_filename) song.tracks = [ standardize_track(track) if track.isPercussionTrack else track for track in song.tracks ] guitarpro.write(song, output_filename)
def test_chord(tmpdir, filename): filepath = path.join(LOCATION, filename) song = guitarpro.parse(filepath) assert song.tracks[0].measures[0].voices[0].beats[ 0].effect.chord is not None destpath = str(tmpdir.join('no_chord_strings.gp5')) guitarpro.write(song, destpath) song2 = guitarpro.parse(destpath) assert song == song2
def SaveTab(self, g, d, name): t = guitarpro.models.Song() t.tempo = self.tempo t.version = self.version t.tracks = [] self.AddGuitarTrack(self.guitarTracks[g], t) self.AddDrumsTrack(self.drumsTrack[d], t) guitarpro.write(t, name)
def main(source, dest, semitones): # load the file song = guitarpro.parse(source) # go through the to-edit tracks for number in unfold_tracknumber(song.tracks): track = song.tracks[number - 1] # change offset track.offset = semitones if dest is None: dest = 'temp.gp5' # save file guitarpro.write(song, dest)
def test_guess_version(output_folder): filename = 'Effects.gp5' filepath = path.join(LOCATION, filename) song_a = guitarpro.parse(filepath) song_a.version = song_a.versionTuple = None for ext, versionTuple in guitarpro.io._EXT_VERSIONS.items(): if ext == 'tmp': continue destpath = path.join(output_folder, filename + '.' + ext) guitarpro.write(song_a, destpath) song_b = guitarpro.parse(destpath) assert song_b.versionTuple == versionTuple
def main(source, dest, tracks, semitones, stringmaps): if tracks is None: tracks = ['*'] if stringmaps is None: stringmaps = [0x7f] * len(tracks) song = guitarpro.parse(source) for number, semitone, stringmap in zip(tracks, semitones, stringmaps): for number in unfold_tracknumber(number, song.tracks): track = song.tracks[number - 1] transpose(track, semitone, stringmap) if dest is None: dest = '%s-transposed%s' % os.path.splitext(source) guitarpro.write(song, dest)
def main(source, dest, tracks, semitones, stringmaps): if tracks is None: tracks = ['*'] if stringmaps is None: stringmaps = [0x7f] * len(tracks) song = guitarpro.parse(source) for number, semitone, stringmap in zip(tracks, semitones, stringmaps): for number in unfold_tracknumber(number, song.tracks): track = song.tracks[number - 1] transpose(track, semitone, stringmap) if dest is None: dest = '%s-transposed%s' % path.splitext(source) guitarpro.write(song, dest)
def testGuessVersion(tmpdir): filename = 'Effects.gp5' filepath = path.join(LOCATION, filename) songA = gp.parse(filepath) songA.version = songA.versionTuple = None for ext, versionTuple in gp.io._EXT_VERSIONS.items(): if ext == 'tmp': continue destpath = str(tmpdir.join(filename + '.' + ext)) gp.write(songA, destpath) songB = gp.parse(destpath) assert songB.versionTuple == versionTuple
def testChord(tmpdir, caplog, filename): filepath = path.join(LOCATION, filename) song = gp.parse(filepath) assert song.tracks[0].measures[0].voices[0].beats[ 0].effect.chord is not None destpath = str(tmpdir.join('no_chord_strings.gp5')) gp.write(song, destpath) if filename == 'Unknown Chord Extension.gp5': iobase_logs = [ log for log in caplog.records if log.name == 'guitarpro.iobase' ] [record] = iobase_logs assert 'is an unknown ChordExtension' in record.msg song2 = gp.parse(destpath) assert song == song2
def to_guitar_pro(df, path='tarpalsus.g5', tempo=130): """ Write df to g5 file""" values = [tuple(x) for x in df[['Value+String', 'Duration']].values] splits = [] for val in values: splits.append(((re.findall('\d*\D+', val[0])), val[1])) base_song = gm.Song(tracks=[], tempo=tempo) track = gm.Track(base_song) durations = list(zip(*splits))[1] indexes = calculate_measures(durations) chunks = [] shifted = indexes.copy() indexes.insert(0, 0) shifted.append(len(splits)) for index, shift in zip(indexes, shifted): chunks.append([splits[index:shift]]) for i, chunk in enumerate(chunks): new_measure = gm.Measure(track, gm.MeasureHeader(number=i, start=i*1080, timeSignature=gm.TimeSignature(numerator=4, denominator=mock(4)) , tempo=180)) voice = new_measure.voices[0] for i, (notes, duration) in enumerate(chunk[0]): new_duration = gm.Duration(value=duration) new_beat = gm.Beat(voice, duration=new_duration, status=gm.BeatStatus.normal) for note in notes: value=int(''.join(re.findall('[0-9]+', note))) string = int(inverse_mapper[''.join(re.findall('[a-z]+', note))]) new_note = gm.Note(new_beat, value=value, string=string, type=gm.NoteType.normal) new_beat.notes.append(new_note) voice.beats.append(new_beat) track.measures.append(new_measure) base_song.tracks.append(track) g.write(base_song, path) return splits, base_song, chunks
def main(source, dest=None, tracks=None): song = guitarpro.parse(source) if tracks is None: # Process all percussion tracks. tracks = (track for track in song.tracks if track.isPercussionTrack) else: # Get tracks by track numbers. tracks = (song.tracks[n] for n in tracks) for track in tracks: # Map values to Genaral MIDI. for measure in track.measures: for voice in measure.voices: for beat in voice.beats: for note in beat.notes: note.value = MAPPING.get(note.value, note.value) # Extend note durations to remove rests in-between. voiceparts = izip(*(measure.voices for measure in track.measures)) for measures in voiceparts: for measure in measures: last = None newbeats = [] for beat in measure.beats: if beat.notes: last = beat elif last is not None: try: newduration = guitarpro.Duration.fromTime( last.duration.time + beat.duration.time) except ValueError: last = beat else: last.duration = newduration continue newbeats.append(beat) measure.beats = newbeats if dest is None: dest = '%s-generalized%s' % path.splitext(source) guitarpro.write(song, dest)
def main(args): '''Command line interface ''' files = [args.OLDFILE, args.MYFILE, args.YOURFILE] # Parse files songs = [guitarpro.parse(f) for f in files if f is not None] differ = GPDiffer(files, songs) if len(files) == 3: # If output is specified, try to merge if args.output is not None: result = differ.merge() guitarpro.write(result, args.output, format=args.format) if not len(differ.conflicts): return 0 for line in differ.show(): print line if len(files) == 2 or not differ.conflicts: return 0 else: return 1
def testWriteErrorAnnotation(version): fp = io.BytesIO() fp.name = f'beep.{version}' song = gp.Song() song.tracks[0].measures[0].timeSignature.numerator = 'nooo' # writeMeasureHeader with pytest.raises(gp.GPException, match="writing measure 1, got ValueError: invalid"): gp.write(song, fp) song = gp.Song() song.tracks[0].fretCount = 'nooo' # writeTracks with pytest.raises(gp.GPException, match="writing track 1, got ValueError: invalid"): gp.write(song, fp) song = gp.Song() voice = song.tracks[0].measures[0].voices[0] invalidBeat = gp.Beat(voice, status='nooo') voice.beats.append(invalidBeat) # writeMeasures with pytest.raises( gp.GPException, match= "writing track 1, measure 1, voice 1, beat 1, got AttributeError: 'str'" ): gp.write(song, fp)
sys.exit(1) src = sys.argv[1] dst = sys.argv[2] print("Parsing", src) song = guitarpro.parse(src) print("Processing", song.title) indices = [] for s in sys.argv[3:]: indices.append(int(s)) # collect regions regions = utils.flatten_to_regions(song, indices) # create new track flattened = copy.deepcopy(song.tracks[indices[0]]) flattened.number = 1 flattened.name = "Flattened" flattened.measures = [] # fold repeats and add to track for r in regions: flattened.measures.extend(utils.fold_repeats(r)) song.tracks = [] song.addTrack(flattened) print("Writing to", dst) guitarpro.write(song, dst)
def write(self): format = None if self.song.clipboard is None else 'tmp' guitarpro.write(self.song, self.output_file, format=format)
def main(): def txt2songDict(track): ''' Read txt file and go through line by line convert all information into dictionary of measures ''' # myfile =open('xyz.txt', 'r') with open(track) as f: total_dict = {} measures_list = [] measNum = 0 measStart = 0 key = 'CMajor' song_len = 3840 for line in f: if line[:5] == 'strgs': fc1 = line.find('fc') try: strings = line[6:fc1].split() except ValueError: break key1 = line.find('Key') fc = line[fc1+4:key1] len1 = line.find('len') key = line[key1+13:len1-1] tempo1 = line.find('tmpo') song_len = line[len1+4:tempo1] try: tempo = line[tempo1+5:tempo1+7] except ValueError: tempo = line[tempo1+5:tempo1+6] init_dict = {} init_dict['tempo'] = tempo gpStrings = [guitarpro.models.GuitarString(number, string) for number, string in enumerate(strings)] init_dict['string'] = gpStrings init_dict['fretCount'] = fc total_dict['init_dict'] = init_dict elif line[:3] == 'Num': measStart1 = line.find('mst') if measNum > 0: total_dict['measure_'+str(measNum)]['beats'] = beats measNum += 1 measStart += 3840 meas_dict = {} meas_dict['key'] = key meas_dict['mlen'] = song_len meas_dict['mstart'] = measStart measures_list.append(meas_dict) total_dict['measure_'+str(measNum)] = meas_dict beats = [] elif line[:3] == 'vst': beatStart1 = measStart + 221820-int(line[4:11]) beats.append(beatStart1) strings = [] notes = [] elif line[:1] == 'S' and line[2] != 'n': valStart = line.find('V') string = int(line[2]) realVal = int(line[valStart+2:valStart+5]) strings.append(string) notes.append(realVal) total_dict['measure_'+str(measNum)]['strings' + str(beatStart1)] = strings total_dict['measure_'+str(measNum)]['Notes' + str(beatStart1)]= notes return(total_dict) curl = guitarpro.parse('Serenade.gp5') track = curl.tracks[0] for measure in track.measures: for voice in measure.voices: for beat in voice.beats: beat.notes = [] curl.tracks[0] = track songDict = txt2songDict('sample.txt') track = curl.tracks[0] track = transpose2GP5file(track, songDict) curl.tracks[0] = track curl.artist = 'R. N. Net' curl.album = time.strftime("%d %B %Y") curl.title = 'Metallica Style Song' guitarpro.write(curl, 'genMetallica.gp5')
def product(test, song, versions=(3, 4, 5)): """Save song in given format *versions*.""" for dest_version in versions: dest_path = path.join(OUTPUT, test + '.gp%d' % dest_version) guitarpro.write(song, dest_path)
else: output_file = sys.argv[3] src_path = sys.argv[2] output_file = open(output_file, 'w') for file in os.listdir(src_path): gpx_file = gp.parse(os.path.join(src_path, file)) toTxt(output_file, gpx_file.tracks[0], os.path.splitext(file)[1]) output_file.close() elif exec_mode == '--gpx' or exec_mode == '-g': if len(sys.argv) == 3: output_file_name = 'output.gp5' else: output_file_name = sys.argv[3] input_file = open(sys.argv[2], 'r') output_file = gp.parse('input/reference.gp5') # Getting a blank .gp5 file for reference output_file.tracks[0] = toGpx(input_file, output_file.tracks[0]) input_file.close() output_file.artist = 'JW' output_file.title = 'Funky Bass' gp.write(output_file, output_file_name) else: print('### Invalid execution mode!')
print("Parsing", src) song = guitarpro.parse(src) print("Processing", song.title) for track in song.tracks: if track.isPercussionTrack: continue if len(track.strings) != 7 or track.strings[2].value != 52: continue # re-tune 3rd string from E4 to F4 print("* Re-tuning string 3 of track", track.name) track.strings[2].value = track.strings[2].value + 1 for measure in track.measures: for voice in measure.voices: for beat in voice.beats: for note in beat.notes: if note.string != 3: continue if note.value == 0: print( " WARNING: failed to re-tune note in measure", measure.number) note.value = 35 else: note.value = note.value - 1 print("Writing to", dst) guitarpro.write(song, dst)
def writeToBytesIO(song): stream = io.BytesIO() stream.name = f'percusion.{version}' gp.write(song, stream, encoding='cp1252') stream.seek(0) return stream