vladsaveliev commited on
Commit
cbcb7a0
·
1 Parent(s): e3e44b4

Parse tex directly

Browse files
Files changed (1) hide show
  1. guitar_tab.py +67 -112
guitar_tab.py CHANGED
@@ -1,9 +1,8 @@
 
1
  import os
2
  from pathlib import Path
3
  import datasets
4
  from typing import Optional
5
- import guitarpro as gp
6
- import itertools
7
  from tqdm import tqdm
8
  from pathlib import Path
9
  import re
@@ -183,118 +182,74 @@ class Builder(datasets.GeneratorBasedBuilder):
183
 
184
  def _generate_examples(self, filepaths):
185
  for idx, path in enumerate(filepaths):
186
- try:
187
- song: gp.Song = gp.parse(path)
188
- except Exception as e:
189
- print(f"failed to parse {path}: {e}")
190
- continue
191
- for track in song.tracks:
192
- try:
193
- tex = track_to_alphatex(track)
194
- except Exception as e:
195
- print(f"failed to convert {path} to alphaTex: {e}")
196
- continue
197
- key = f"{idx}-{track.number}"
198
- yield key, {
199
- "text": tex,
200
- "title": path.stem,
201
- "track": track.number,
202
- "instrument": INSTRUMENT_MAP.get(
203
- track.channel.instrument, "unknown"
204
- ),
205
- }
206
 
207
 
208
- def track_to_alphatex(track: gp.Track) -> str:
209
  """
210
- Convert a GuitarPro track to the alphaTex flat text format
211
  """
212
- header = []
213
- header.append(f'\\title "{track.song.title}"')
214
- if track.song.subtitle:
215
- header.append(f'\\subtitle "{track.name}"')
216
- header.append(f"\\tempo {track.song.tempo}")
217
- if track.channel and track.channel.instrument is not None:
218
- header.append(f"\\instument {INSTRUMENT_MAP[track.channel.instrument]}")
219
- if track.strings:
220
- header.append(f"\\strings {len(track.strings)}")
221
- if track.fretCount:
222
- header.append(f"\\frets {track.fretCount}")
223
- header.append(".")
224
 
225
- mstrs = []
226
- curduration = None
227
- for measure in track.measures:
228
- mstr = ""
229
- beats = measure.voices[0].beats
230
- if beats and beats[0].duration != curduration:
231
- curduration = beats[0].duration
232
- mstr += f":{curduration.value} "
233
- for beat in beats:
234
- if not beat.notes:
235
- bstr = "r"
236
- if beat.duration != curduration:
237
- bstr += f".{beat.duration.value}"
238
- mstr += bstr + " "
239
- continue
240
- bstr = ""
241
- nstrs = []
242
- bdur = None
243
- for note in beat.notes:
244
- nstrs.append(f"{note.value}.{note.string}")
245
- ef = []
246
- if note.beat.duration.isDotted:
247
- ef.append("d")
248
- if note.effect.vibrato:
249
- ef.append("v")
250
- if note.effect.hammer:
251
- ef.append("h")
252
- if note.effect.trill is not None:
253
- ef.append("tr")
254
- if note.effect.palmMute:
255
- ef.append("pm")
256
- if note.effect.harmonic is not None:
257
- if isinstance(note.effect.harmonic, gp.NaturalHarmonic):
258
- ef.append("nh")
259
- elif isinstance(note.effect.harmonic, gp.ArtificialHarmonic):
260
- ef.append("ah")
261
- elif isinstance(note.effect.harmonic, gp.TappedHarmonic):
262
- ef.append("th")
263
- elif isinstance(note.effect.harmonic, gp.PinchHarmonic):
264
- ef.append("ph")
265
- elif isinstance(note.effect.harmonic, gp.SemiHarmonic):
266
- ef.append("sh")
267
- if note.effect.isBend:
268
- ef.append("be")
269
- ef.append(
270
- "("
271
- + " ".join(
272
- f"{p.position} {p.value}" for p in note.effect.bend.points
273
- )
274
- + ")"
275
- )
276
- if note.effect.staccato:
277
- ef.append("st")
278
- if note.effect.letRing:
279
- ef.append("lr")
280
- if note.effect.ghostNote:
281
- ef.append("g")
282
- if beat.effect.fadeIn:
283
- ef.append("f")
284
- if beat.duration.tuplet.enters != 1:
285
- ef.append(f"tu {beat.duration.tuplet.enters}")
286
- # Finished parsing effects
287
- if ef:
288
- nstrs[-1] += "{" + " ".join(ef) + "}"
289
- if beat.duration != curduration:
290
- bdur = beat.duration.value
291
- if len(nstrs) > 1:
292
- bstr += "(" + " ".join(nstrs) + ")"
293
- elif len(nstrs) == 1:
294
- bstr = nstrs[0]
295
- if bdur is not None:
296
- bstr += f".{bdur}"
297
- mstr += bstr + " "
298
- if mstr := mstr.strip():
299
- mstrs.append(mstr)
300
- return "\n".join(header) + "\n" + " | \n".join(mstrs)
 
1
+ import itertools
2
  import os
3
  from pathlib import Path
4
  import datasets
5
  from typing import Optional
 
 
6
  from tqdm import tqdm
7
  from pathlib import Path
8
  import re
 
182
 
183
  def _generate_examples(self, filepaths):
184
  for idx, path in enumerate(filepaths):
185
+ with open(path) as f:
186
+ examples = _parse_examples(f.read())
187
+ for example in examples:
188
+ example['file'] = path.name
189
+ yield f"{idx}-{example['number']}", example
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
 
192
+ def _parse_examples(tex):
193
  """
194
+ Returns a dictionary for each track
195
  """
196
+ tracks = [{}]
197
+
198
+ def _parse_track_header(k, v):
199
+ if k == "instrument":
200
+ tracks[-1][k] = INSTRUMENT_MAP.get(int(v), "unknown")
201
+ elif k == "tuning":
202
+ tracks[-1][k] = v.split(" ")
203
+ elif k == "frets":
204
+ tracks[-1][k] = int(v)
 
 
 
205
 
206
+ lines = (l.strip() for l in tex.splitlines() if l.strip())
207
+ for line in itertools.takewhile(lambda l: l != ".", lines):
208
+ assert line.startswith("\\")
209
+ line = line.lstrip("\\")
210
+ kv = line.split(" ", 1)
211
+ if len(kv) == 1:
212
+ continue
213
+ k, v = kv
214
+ if k in [
215
+ "title",
216
+ "subtitle",
217
+ "artist",
218
+ "album",
219
+ "words",
220
+ "music",
221
+ "copyright",
222
+ "tab",
223
+ "instructions",
224
+ ]:
225
+ tracks[-1][k] = v.strip('"').strip("'")
226
+ elif k == "tempo":
227
+ tracks[-1][k] = int(v)
228
+ else:
229
+ _parse_track_header(k, v)
230
+
231
+ track_lines = []
232
+ for line in lines:
233
+ if line.startswith("\\"):
234
+ line = line.lstrip("\\")
235
+ kv = line.split(" ", 1)
236
+ if len(kv) == 2:
237
+ k = kv[0]
238
+ v = kv[1].strip('"').strip("'")
239
+ else:
240
+ k = kv[0]
241
+ v = None
242
+ if k == "track":
243
+ if track_lines:
244
+ tracks[-1]["tex"] = " ".join(track_lines)
245
+ track_lines = []
246
+ tracks.append({})
247
+ tracks[-1]["number"] = len(tracks) + 1
248
+ tracks[-1]["name"] = v if v else f"Track {tracks[-1]['number']}"
249
+ else:
250
+ _parse_track_header(k, v)
251
+ else:
252
+ track_lines.append(line)
253
+ if track_lines:
254
+ tracks[-1]["tex"] = " ".join(track_lines)
255
+ return tracks