shiv.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. # IV file viewer
  2. import xml.etree.ElementTree as ET
  3. import optparse
  4. import sys
  5. import math
  6. parser = optparse.OptionParser()
  7. parser.add_option('-n', '--number', dest='number', action='store_true', help='Show number of tracks')
  8. parser.add_option('-g', '--groups', dest='groups', action='store_true', help='Show group names')
  9. parser.add_option('-G', '--group', dest='group', action='append', help='Only compute for this group (may be specified multiple times)')
  10. parser.add_option('-N', '--notes', dest='notes', action='store_true', help='Show number of notes')
  11. parser.add_option('-M', '--notes-stream', dest='notes_stream', action='store_true', help='Show notes per stream')
  12. parser.add_option('-m', '--meta', dest='meta', action='store_true', help='Show meta track information')
  13. parser.add_option('--histogram', dest='histogram', action='store_true', help='Show a histogram distribution of pitches')
  14. parser.add_option('--histogram-tracks', dest='histogram_tracks', action='store_true', help='Show a histogram distribution of pitches per track')
  15. parser.add_option('--vel-hist', dest='vel_hist', action='store_true', help='Show a histogram distribution of velocities')
  16. parser.add_option('--vel-hist-tracks', dest='vel_hist_tracks', action='store_true', help='Show a histogram distributions of velocities per track')
  17. parser.add_option('-d', '--duration', dest='duration', action='store_true', help='Show the duration of the piece')
  18. parser.add_option('-D', '--duty-cycle', dest='duty_cycle', action='store_true', help='Show the duration of the notes within tracks, and as a percentage of the piece duration')
  19. parser.add_option('-H', '--height', dest='height', type='int', help='Height of histograms')
  20. parser.add_option('-C', '--no-color', dest='no_color', action='store_true', help='Don\'t use ANSI color escapes')
  21. parser.add_option('-x', '--aux', dest='aux', action='store_true', help='Show information about the auxiliary streams')
  22. parser.add_option('-a', '--almost-all', dest='almost_all', action='store_true', help='Show useful information')
  23. parser.add_option('-A', '--all', dest='all', action='store_true', help='Show everything')
  24. parser.add_option('-t', '--total', dest='total', action='store_true', help='Make cross-file totals')
  25. parser.set_defaults(height=20, group=[])
  26. options, args = parser.parse_args()
  27. if not any((
  28. options.number,
  29. options.groups,
  30. options.notes,
  31. options.notes_stream,
  32. options.histogram,
  33. options.vel_hist,
  34. options.duration,
  35. options.duty_cycle,
  36. options.aux,
  37. options.meta,
  38. options.histogram_tracks,
  39. options.vel_hist_tracks,
  40. )):
  41. print 'No computations specified! Assuming you meant --almost-all...'
  42. options.almost_all = True
  43. if options.almost_all or options.all:
  44. options.number = True
  45. options.groups = True
  46. options.notes = True
  47. options.notes_stream = True
  48. options.histogram = True
  49. options.vel_hist = True
  50. options.duration = True
  51. options.duty_cycle = True
  52. if options.all:
  53. options.aux = True
  54. options.meta = True
  55. options.histogram_tracks= True
  56. options.vel_hist_tracks = True
  57. if options.no_color:
  58. class COL:
  59. NONE=''
  60. RED=''
  61. GREEN=''
  62. BLUE=''
  63. YELLOW=''
  64. MAGENTA=''
  65. CYAN=''
  66. else:
  67. class COL:
  68. NONE='\x1b[0m'
  69. RED='\x1b[31m'
  70. GREEN='\x1b[32m'
  71. BLUE='\x1b[34m'
  72. YELLOW='\x1b[33m'
  73. MAGENTA='\x1b[35m'
  74. CYAN='\x1b[36m'
  75. def show_hist(values, height=None):
  76. if not values:
  77. print '{empty histogram}'
  78. return
  79. if height is None:
  80. height = options.height
  81. xs, ys = values.keys(), values.values()
  82. minx, maxx = min(xs), max(xs)
  83. miny, maxy = min(ys), max(ys)
  84. xv = range(int(math.floor(minx)), int(math.ceil(maxx + 1)))
  85. incs = max((maxy - miny) / height, 1)
  86. print COL.CYAN + '\t --' + '-' * len(xv) + COL.NONE
  87. for ub in range(maxy + incs, miny, -incs):
  88. print '{}{}\t | {}{}{}'.format(COL.CYAN, ub, COL.YELLOW, ''.join(['#' if values.get(x) > (ub - incs) else ' ' for x in xv]), COL.NONE)
  89. print COL.CYAN + '\t |-' + '-' * len(xv) + COL.NONE
  90. xvs = map(str, xv)
  91. for i in range(max(map(len, xvs))):
  92. print COL.CYAN + '\t ' + ''.join([s[i] if len(s) > i else ' ' for s in xvs]) + COL.NONE
  93. print
  94. xcs = map(str, [values.get(x, 0) for x in xv])
  95. for i in range(max(map(len, xcs))):
  96. print COL.YELLOW + '\t ' + ''.join([s[i] if len(s) > i else ' ' for s in xcs]) + COL.NONE
  97. print
  98. if options.total:
  99. tot_note_cnt = 0
  100. max_note_cnt = 0
  101. tot_pitches = {}
  102. tot_velocities = {}
  103. tot_dur = 0
  104. max_dur = 0
  105. tot_streams = 0
  106. max_streams = 0
  107. tot_notestreams = 0
  108. max_notestreams = 0
  109. tot_groups = {}
  110. for fname in args:
  111. print
  112. print 'File :', fname
  113. try:
  114. iv = ET.parse(fname).getroot()
  115. except Exception:
  116. import traceback
  117. traceback.print_exc()
  118. print 'Bad file :', fname, ', skipping...'
  119. continue
  120. print '\t<computing...>'
  121. if options.meta:
  122. print 'Metatrack:',
  123. meta = iv.find('./meta')
  124. if len(meta):
  125. print 'exists'
  126. print '\tBPM track:',
  127. bpms = meta.find('./bpms')
  128. if len(bpms):
  129. print 'exists'
  130. for elem in bpms.iterfind('./bpm'):
  131. print '\t\tAt ticks {}, time {}: {} bpm'.format(elem.get('ticks'), elem.get('time'), elem.get('bpm'))
  132. if not (options.number or options.groups or options.notes or options.histogram or options.histogram_tracks or options.vel_hist or options.vel_hist_tracks or options.duration or options.duty_cycle or options.aux):
  133. continue
  134. streams = iv.findall('./streams/stream')
  135. notestreams = [s for s in streams if s.get('type') == 'ns']
  136. auxstreams = [s for s in streams if s.get('type') == 'aux']
  137. if options.group:
  138. print 'NOTE: Restricting results to groups', options.group, 'as requested'
  139. notestreams = [ns for ns in notestreams if ns.get('group', '<anonymous>') in options.group]
  140. if options.number:
  141. print 'Stream count:'
  142. print '\tNotestreams:', len(notestreams)
  143. print '\tTotal:', len(streams)
  144. if options.total:
  145. tot_streams += len(streams)
  146. max_streams = max(max_streams, len(streams))
  147. tot_notestreams += len(notestreams)
  148. max_notestreams = max(max_notestreams, len(notestreams))
  149. if not (options.groups or options.notes or options.histogram or options.histogram_tracks or options.vel_hist or options.vel_hist_tracks or options.duration or options.duty_cycle or options.aux):
  150. continue
  151. if options.groups:
  152. groups = {}
  153. for s in notestreams:
  154. group = s.get('group', '<anonymous>')
  155. groups[group] = groups.get(group, 0) + 1
  156. if options.total:
  157. tot_groups[group] = tot_groups.get(group, 0) + 1
  158. print 'Groups:'
  159. for name, cnt in groups.iteritems():
  160. print '\t{} ({} streams)'.format(name, cnt)
  161. if options.aux:
  162. import midi
  163. fr = midi.FileReader()
  164. fr.RunningStatus = None # XXX Hack
  165. print 'Aux stream data:'
  166. for aidx, astream in enumerate(auxstreams):
  167. evs = astream.findall('ev')
  168. failed = 0
  169. print '\tFrom stream {}, {} events:'.format(aidx, len(evs))
  170. for ev in evs:
  171. try:
  172. data = eval(ev.get('data'))
  173. mev = fr.parse_midi_event(iter(data))
  174. except AssertionError:
  175. failed += 1
  176. else:
  177. print '\t\tAt time {}: {}'.format(ev.get('time'), mev)
  178. print '\t\t(...and {} others which failed to parse)'.format(failed)
  179. if not (options.notes or options.notes_stream or options.histogram or options.histogram_tracks or options.vel_hist or options.vel_hist_tracks or options.duration or options.duty_cycle):
  180. continue
  181. if options.notes:
  182. note_cnt = 0
  183. if options.notes_stream:
  184. notes_stream = [0] * len(notestreams)
  185. if options.histogram:
  186. pitches = {}
  187. if options.histogram_tracks:
  188. pitch_tracks = [{} for i in notestreams]
  189. if options.vel_hist:
  190. velocities = {}
  191. if options.vel_hist_tracks:
  192. velocities_tracks = [{} for i in notestreams]
  193. if options.duration or options.duty_cycle:
  194. max_dur = 0
  195. if options.duty_cycle:
  196. cum_dur = [0.0] * len(notestreams)
  197. for sidx, stream in enumerate(notestreams):
  198. notes = stream.findall('note')
  199. for note in notes:
  200. pitch = float(note.get('pitch'))
  201. ampl = float(note.get('ampl', float(note.get('vel', 127.0)) / 127.0))
  202. time = float(note.get('time'))
  203. dur = float(note.get('dur'))
  204. if options.notes:
  205. note_cnt += 1
  206. if options.total:
  207. tot_note_cnt += 1
  208. if options.notes_stream:
  209. notes_stream[sidx] += 1
  210. if options.histogram:
  211. pitches[pitch] = pitches.get(pitch, 0) + 1
  212. if options.total:
  213. tot_pitches[pitch] = tot_pitches.get(pitch, 0) + 1
  214. if options.histogram_tracks:
  215. pitch_tracks[sidx][pitch] = pitch_tracks[sidx].get(pitch, 0) + 1
  216. if options.vel_hist:
  217. velocities[ampl] = velocities.get(ampl, 0) + 1
  218. if options.total:
  219. tot_velocities[ampl] = tot_velocities.get(ampl, 0) + 1
  220. if options.vel_hist_tracks:
  221. velocities_tracks[sidx][ampl] = velocities_tracks[sidx].get(ampl, 0) + 1
  222. if (options.duration or options.duty_cycle) and time + dur > max_dur:
  223. max_dur = time + dur
  224. if options.duty_cycle:
  225. cum_dur[sidx] += dur
  226. if options.notes and options.total:
  227. max_note_cnt = max(max_note_cnt, note_cnt)
  228. if options.histogram_tracks:
  229. for sidx, hist in enumerate(pitch_tracks):
  230. print 'Stream {} (group {}) pitch histogram:'.format(sidx, notestreams[sidx].get('group', '<anonymous>'))
  231. show_hist(hist)
  232. if options.vel_hist_tracks:
  233. for sidx, hist in enumerate(velocities_tracks):
  234. print 'Stream {} (group {}) velocity histogram:'.format(sidx, notestreams[sidx].get('group', '<anonymous>'))
  235. show_hist(hist)
  236. if options.notes_stream:
  237. for sidx, value in enumerate(notes_stream):
  238. print 'Stream {} (group {}) note count: {}'.format(sidx, notestreams[sidx].get('group', '<anonymous>'), value)
  239. if options.duty_cycle:
  240. for sidx, value in enumerate(cum_dur):
  241. print 'Stream {} (group {}) duty cycle: {}'.format(sidx, notestreams[sidx].get('group', '<anonymous>'), value / max_dur)
  242. if options.notes:
  243. print 'Total notes: {}'.format(note_cnt)
  244. if options.histogram:
  245. print 'Pitch histogram:'
  246. show_hist(pitches)
  247. if options.vel_hist:
  248. print 'Velocity histogram:'
  249. show_hist(velocities)
  250. if options.duration:
  251. print 'Playing duration: {}'.format(max_dur)
  252. if options.total:
  253. print 'Totals:'
  254. if options.number:
  255. print '\tTotal streams:', tot_streams
  256. print '\tMax streams:', max_streams
  257. print '\tTotal notestreams:', tot_notestreams
  258. print '\tMax notestreams:', max_notestreams
  259. print
  260. if options.notes:
  261. print '\tTotal notes:', tot_note_cnt
  262. print '\tMax notes:', max_note_cnt
  263. print
  264. if options.groups:
  265. print '\tGroups:'
  266. for grp, cnt in tot_groups.iteritems():
  267. print '\t\t', grp, ':', cnt
  268. print
  269. if options.histogram:
  270. print 'Overall pitch histogram:'
  271. show_hist(tot_pitches)
  272. if options.vel_hist:
  273. print 'Overall velocity histogram:'
  274. show_hist(tot_velocities)