shiv.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 options.almost_all or options.all:
  28. options.number = True
  29. options.groups = True
  30. options.notes = True
  31. options.notes_stream = True
  32. options.histogram = True
  33. options.vel_hist = True
  34. options.duration = True
  35. options.duty_cycle = True
  36. if options.all:
  37. options.aux = True
  38. options.meta = True
  39. options.histogram_tracks= True
  40. options.vel_hist_tracks = True
  41. if options.no_color:
  42. class COL:
  43. NONE=''
  44. RED=''
  45. GREEN=''
  46. BLUE=''
  47. YELLOW=''
  48. MAGENTA=''
  49. CYAN=''
  50. else:
  51. class COL:
  52. NONE='\x1b[0m'
  53. RED='\x1b[31m'
  54. GREEN='\x1b[32m'
  55. BLUE='\x1b[34m'
  56. YELLOW='\x1b[33m'
  57. MAGENTA='\x1b[35m'
  58. CYAN='\x1b[36m'
  59. def show_hist(values, height=None):
  60. if not values:
  61. print '{empty histogram}'
  62. return
  63. if height is None:
  64. height = options.height
  65. xs, ys = values.keys(), values.values()
  66. minx, maxx = min(xs), max(xs)
  67. miny, maxy = min(ys), max(ys)
  68. xv = range(int(math.floor(minx)), int(math.ceil(maxx + 1)))
  69. incs = max((maxy - miny) / height, 1)
  70. print COL.CYAN + '\t --' + '-' * len(xv) + COL.NONE
  71. for ub in range(maxy + incs, miny, -incs):
  72. print '{}{}\t | {}{}{}'.format(COL.CYAN, ub, COL.YELLOW, ''.join(['#' if values.get(x) > (ub - incs) else ' ' for x in xv]), COL.NONE)
  73. print COL.CYAN + '\t |-' + '-' * len(xv) + COL.NONE
  74. xvs = map(str, xv)
  75. for i in range(max(map(len, xvs))):
  76. print COL.CYAN + '\t ' + ''.join([s[i] if len(s) > i else ' ' for s in xvs]) + COL.NONE
  77. print
  78. xcs = map(str, [values.get(x, 0) for x in xv])
  79. for i in range(max(map(len, xcs))):
  80. print COL.YELLOW + '\t ' + ''.join([s[i] if len(s) > i else ' ' for s in xcs]) + COL.NONE
  81. print
  82. if options.total:
  83. tot_note_cnt = 0
  84. max_note_cnt = 0
  85. tot_pitches = {}
  86. tot_velocities = {}
  87. tot_dur = 0
  88. max_dur = 0
  89. tot_streams = 0
  90. max_streams = 0
  91. tot_notestreams = 0
  92. max_notestreams = 0
  93. tot_groups = {}
  94. for fname in args:
  95. print
  96. print 'File :', fname
  97. try:
  98. iv = ET.parse(fname).getroot()
  99. except Exception:
  100. import traceback
  101. traceback.print_exc()
  102. print 'Bad file :', fname, ', skipping...'
  103. continue
  104. print '\t<computing...>'
  105. if options.meta:
  106. print 'Metatrack:',
  107. meta = iv.find('./meta')
  108. if len(meta):
  109. print 'exists'
  110. print '\tBPM track:',
  111. bpms = meta.find('./bpms')
  112. if len(bpms):
  113. print 'exists'
  114. for elem in bpms.iterfind('./bpm'):
  115. print '\t\tAt ticks {}, time {}: {} bpm'.format(elem.get('ticks'), elem.get('time'), elem.get('bpm'))
  116. 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):
  117. continue
  118. streams = iv.findall('./streams/stream')
  119. notestreams = [s for s in streams if s.get('type') == 'ns']
  120. auxstreams = [s for s in streams if s.get('type') == 'aux']
  121. if options.group:
  122. print 'NOTE: Restricting results to groups', options.group, 'as requested'
  123. notestreams = [ns for ns in notestreams if ns.get('group', '<anonymous>') in options.group]
  124. if options.number:
  125. print 'Stream count:'
  126. print '\tNotestreams:', len(notestreams)
  127. print '\tTotal:', len(streams)
  128. if options.total:
  129. tot_streams += len(streams)
  130. max_streams = max(max_streams, len(streams))
  131. tot_notestreams += len(notestreams)
  132. max_notestreams = max(max_notestreams, len(notestreams))
  133. 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):
  134. continue
  135. if options.groups:
  136. groups = {}
  137. for s in notestreams:
  138. group = s.get('group', '<anonymous>')
  139. groups[group] = groups.get(group, 0) + 1
  140. if options.total:
  141. tot_groups[group] = tot_groups.get(group, 0) + 1
  142. print 'Groups:'
  143. for name, cnt in groups.iteritems():
  144. print '\t{} ({} streams)'.format(name, cnt)
  145. if options.aux:
  146. import midi
  147. fr = midi.FileReader()
  148. fr.RunningStatus = None # XXX Hack
  149. print 'Aux stream data:'
  150. for aidx, astream in enumerate(auxstreams):
  151. evs = astream.findall('ev')
  152. failed = 0
  153. print '\tFrom stream {}, {} events:'.format(aidx, len(evs))
  154. for ev in evs:
  155. try:
  156. data = eval(ev.get('data'))
  157. mev = fr.parse_midi_event(iter(data))
  158. except AssertionError:
  159. failed += 1
  160. else:
  161. print '\t\tAt time {}: {}'.format(ev.get('time'), mev)
  162. print '\t\t(...and {} others which failed to parse)'.format(failed)
  163. 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):
  164. continue
  165. if options.notes:
  166. note_cnt = 0
  167. if options.notes_stream:
  168. notes_stream = [0] * len(notestreams)
  169. if options.histogram:
  170. pitches = {}
  171. if options.histogram_tracks:
  172. pitch_tracks = [{} for i in notestreams]
  173. if options.vel_hist:
  174. velocities = {}
  175. if options.vel_hist_tracks:
  176. velocities_tracks = [{} for i in notestreams]
  177. if options.duration or options.duty_cycle:
  178. max_dur = 0
  179. if options.duty_cycle:
  180. cum_dur = [0.0] * len(notestreams)
  181. for sidx, stream in enumerate(notestreams):
  182. notes = stream.findall('note')
  183. for note in notes:
  184. pitch = float(note.get('pitch'))
  185. vel = int(note.get('vel'))
  186. time = float(note.get('time'))
  187. dur = float(note.get('dur'))
  188. if options.notes:
  189. note_cnt += 1
  190. if options.total:
  191. tot_note_cnt += 1
  192. if options.notes_stream:
  193. notes_stream[sidx] += 1
  194. if options.histogram:
  195. pitches[pitch] = pitches.get(pitch, 0) + 1
  196. if options.total:
  197. tot_pitches[pitch] = tot_pitches.get(pitch, 0) + 1
  198. if options.histogram_tracks:
  199. pitch_tracks[sidx][pitch] = pitch_tracks[sidx].get(pitch, 0) + 1
  200. if options.vel_hist:
  201. velocities[vel] = velocities.get(vel, 0) + 1
  202. if options.total:
  203. tot_velocities[vel] = tot_velocities.get(vel, 0) + 1
  204. if options.vel_hist_tracks:
  205. velocities_tracks[sidx][vel] = velocities_tracks[sidx].get(vel, 0) + 1
  206. if (options.duration or options.duty_cycle) and time + dur > max_dur:
  207. max_dur = time + dur
  208. if options.duty_cycle:
  209. cum_dur[sidx] += dur
  210. if options.notes and options.total:
  211. max_note_cnt = max(max_note_cnt, note_cnt)
  212. if options.histogram_tracks:
  213. for sidx, hist in enumerate(pitch_tracks):
  214. print 'Stream {} (group {}) pitch histogram:'.format(sidx, notestreams[sidx].get('group', '<anonymous>'))
  215. show_hist(hist)
  216. if options.vel_hist_tracks:
  217. for sidx, hist in enumerate(velocities_tracks):
  218. print 'Stream {} (group {}) velocity histogram:'.format(sidx, notestreams[sidx].get('group', '<anonymous>'))
  219. show_hist(hist)
  220. if options.notes_stream:
  221. for sidx, value in enumerate(notes_stream):
  222. print 'Stream {} (group {}) note count: {}'.format(sidx, notestreams[sidx].get('group', '<anonymous>'), value)
  223. if options.duty_cycle:
  224. for sidx, value in enumerate(cum_dur):
  225. print 'Stream {} (group {}) duty cycle: {}'.format(sidx, notestreams[sidx].get('group', '<anonymous>'), value / max_dur)
  226. if options.notes:
  227. print 'Total notes: {}'.format(note_cnt)
  228. if options.histogram:
  229. print 'Pitch histogram:'
  230. show_hist(pitches)
  231. if options.vel_hist:
  232. print 'Velocity histogram:'
  233. show_hist(velocities)
  234. if options.duration:
  235. print 'Playing duration: {}'.format(max_dur)
  236. if options.total:
  237. print 'Totals:'
  238. if options.number:
  239. print '\tTotal streams:', tot_streams
  240. print '\tMax streams:', max_streams
  241. print '\tTotal notestreams:', tot_notestreams
  242. print '\tMax notestreams:', max_notestreams
  243. print
  244. if options.notes:
  245. print '\tTotal notes:', tot_note_cnt
  246. print '\tMax notes:', max_note_cnt
  247. print
  248. if options.groups:
  249. print '\tGroups:'
  250. for grp, cnt in tot_groups.iteritems():
  251. print '\t\t', grp, ':', cnt
  252. print
  253. if options.histogram:
  254. print 'Overall pitch histogram:'
  255. show_hist(tot_pitches)
  256. if options.vel_hist:
  257. print 'Overall velocity histogram:'
  258. show_hist(tot_velocities)