shiv.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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('-N', '--notes', dest='notes', action='store_true', help='Show number of notes')
  10. parser.add_option('-M', '--notes-stream', dest='notes_stream', action='store_true', help='Show notes per stream')
  11. parser.add_option('-m', '--meta', dest='meta', action='store_true', help='Show meta track information')
  12. parser.add_option('--histogram', dest='histogram', action='store_true', help='Show a histogram distribution of pitches')
  13. parser.add_option('--histogram-tracks', dest='histogram_tracks', action='store_true', help='Show a histogram distribution of pitches per track')
  14. parser.add_option('--vel-hist', dest='vel_hist', action='store_true', help='Show a histogram distribution of velocities')
  15. parser.add_option('--vel-hist-tracks', dest='vel_hist_tracks', action='store_true', help='Show a histogram distributions of velocities per track')
  16. parser.add_option('-d', '--duration', dest='duration', action='store_true', help='Show the duration of the piece')
  17. 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')
  18. parser.add_option('-H', '--height', dest='height', type='int', help='Height of histograms')
  19. parser.add_option('-C', '--no-color', dest='no_color', action='store_true', help='Don\'t use ANSI color escapes')
  20. parser.add_option('-x', '--aux', dest='aux', action='store_true', help='Show information about the auxiliary streams')
  21. parser.add_option('-a', '--almost-all', dest='almost_all', action='store_true', help='Show useful information')
  22. parser.add_option('-A', '--all', dest='all', action='store_true', help='Show everything')
  23. parser.set_defaults(height=20)
  24. options, args = parser.parse_args()
  25. if options.almost_all or options.all:
  26. options.number = True
  27. options.groups = True
  28. options.notes = True
  29. options.notes_stream = True
  30. options.histogram = True
  31. options.vel_hist = True
  32. options.duration = True
  33. options.duty_cycle = True
  34. if options.all:
  35. options.aux = True
  36. options.meta = True
  37. options.histogram_tracks= True
  38. options.vel_hist_tracks = True
  39. if options.no_color:
  40. class COL:
  41. NONE=''
  42. RED=''
  43. GREEN=''
  44. BLUE=''
  45. YELLOW=''
  46. MAGENTA=''
  47. CYAN=''
  48. else:
  49. class COL:
  50. NONE='\x1b[0m'
  51. RED='\x1b[31m'
  52. GREEN='\x1b[32m'
  53. BLUE='\x1b[34m'
  54. YELLOW='\x1b[33m'
  55. MAGENTA='\x1b[35m'
  56. CYAN='\x1b[36m'
  57. def show_hist(values, height=None):
  58. if not values:
  59. print '{empty histogram}'
  60. if height is None:
  61. height = options.height
  62. xs, ys = values.keys(), values.values()
  63. minx, maxx = min(xs), max(xs)
  64. miny, maxy = min(ys), max(ys)
  65. xv = range(int(math.floor(minx)), int(math.ceil(maxx + 1)))
  66. incs = max((maxy - miny) / height, 1)
  67. print COL.CYAN + '\t --' + '-' * len(xv) + COL.NONE
  68. for ub in range(maxy + incs, miny, -incs):
  69. print '{}{}\t | {}{}{}'.format(COL.CYAN, ub, COL.YELLOW, ''.join(['#' if values.get(x) > (ub - incs) else ' ' for x in xv]), COL.NONE)
  70. print COL.CYAN + '\t |-' + '-' * len(xv) + COL.NONE
  71. xvs = map(str, xv)
  72. for i in range(max(map(len, xvs))):
  73. print COL.CYAN + '\t ' + ''.join([s[i] if len(s) > i else ' ' for s in xvs]) + COL.NONE
  74. print
  75. xcs = map(str, [values.get(x, 0) for x in xv])
  76. for i in range(max(map(len, xcs))):
  77. print COL.YELLOW + '\t ' + ''.join([s[i] if len(s) > i else ' ' for s in xcs]) + COL.NONE
  78. print
  79. for fname in args:
  80. try:
  81. iv = ET.parse(fname).getroot()
  82. except IOError:
  83. import traceback
  84. traceback.print_exc()
  85. print 'Bad file :', fname, ', skipping...'
  86. continue
  87. print
  88. print 'File :', fname
  89. print '\t<computing...>'
  90. if options.meta:
  91. print 'Metatrack:',
  92. meta = iv.find('./meta')
  93. if len(meta):
  94. print 'exists'
  95. print '\tBPM track:',
  96. bpms = meta.find('./bpms')
  97. if len(bpms):
  98. print 'exists'
  99. for elem in bpms.iterfind('./bpm'):
  100. print '\t\tAt ticks {}, time {}: {} bpm'.format(elem.get('ticks'), elem.get('time'), elem.get('bpm'))
  101. 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):
  102. continue
  103. streams = iv.findall('./streams/stream')
  104. notestreams = [s for s in streams if s.get('type') == 'ns']
  105. auxstreams = [s for s in streams if s.get('type') == 'aux']
  106. if options.number:
  107. print 'Stream count:'
  108. print '\tNotestreams:', len(notestreams)
  109. print '\tTotal:', len(streams)
  110. 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):
  111. continue
  112. if options.groups:
  113. groups = {}
  114. for s in notestreams:
  115. group = s.get('group', '<anonymous>')
  116. groups[group] = groups.get(group, 0) + 1
  117. print 'Groups:'
  118. for name, cnt in groups.iteritems():
  119. print '\t{} ({} streams)'.format(name, cnt)
  120. if options.aux:
  121. import midi
  122. fr = midi.FileReader()
  123. fr.RunningStatus = None # XXX Hack
  124. print 'Aux stream data:'
  125. for aidx, astream in enumerate(auxstreams):
  126. evs = astream.findall('ev')
  127. failed = 0
  128. print '\tFrom stream {}, {} events:'.format(aidx, len(evs))
  129. for ev in evs:
  130. try:
  131. data = eval(ev.get('data'))
  132. mev = fr.parse_midi_event(iter(data))
  133. except AssertionError:
  134. failed += 1
  135. else:
  136. print '\t\tAt time {}: {}'.format(ev.get('time'), mev)
  137. print '\t\t(...and {} others which failed to parse)'.format(failed)
  138. 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):
  139. continue
  140. if options.notes:
  141. note_cnt = 0
  142. if options.notes_stream:
  143. notes_stream = [0] * len(notestreams)
  144. if options.histogram:
  145. pitches = {}
  146. if options.histogram_tracks:
  147. pitch_tracks = [{} for i in notestreams]
  148. if options.vel_hist:
  149. velocities = {}
  150. if options.vel_hist_tracks:
  151. velocities_tracks = [{} for i in notestreams]
  152. if options.duration or options.duty_cycle:
  153. max_dur = 0
  154. if options.duty_cycle:
  155. cum_dur = [0.0] * len(notestreams)
  156. for sidx, stream in enumerate(notestreams):
  157. notes = stream.findall('note')
  158. for note in notes:
  159. pitch = float(note.get('pitch'))
  160. vel = int(note.get('vel'))
  161. time = float(note.get('time'))
  162. dur = float(note.get('dur'))
  163. if options.notes:
  164. note_cnt += 1
  165. if options.notes_stream:
  166. notes_stream[sidx] += 1
  167. if options.histogram:
  168. pitches[pitch] = pitches.get(pitch, 0) + 1
  169. if options.histogram_tracks:
  170. pitch_tracks[sidx][pitch] = pitch_tracks[sidx].get(pitch, 0) + 1
  171. if options.vel_hist:
  172. velocities[vel] = velocities.get(vel, 0) + 1
  173. if options.vel_hist_tracks:
  174. velocities_tracks[sidx][vel] = velocities_tracks[sidx].get(vel, 0) + 1
  175. if (options.duration or options.duty_cycle) and time + dur > max_dur:
  176. max_dur = time + dur
  177. if options.duty_cycle:
  178. cum_dur[sidx] += dur
  179. if options.histogram_tracks:
  180. for sidx, hist in enumerate(pitch_tracks):
  181. print 'Stream {} (group {}) pitch histogram:'.format(sidx, notestreams[sidx].get('group', '<anonymous>'))
  182. show_hist(hist)
  183. if options.vel_hist_tracks:
  184. for sidx, hist in enumerate(velocities_tracks):
  185. print 'Stream {} (group {}) velocity histogram:'.format(sidx, notestreams[sidx].get('group', '<anonymous>'))
  186. show_hist(hist)
  187. if options.notes_stream:
  188. for sidx, value in enumerate(notes_stream):
  189. print 'Stream {} (group {}) note count: {}'.format(sidx, notestreams[sidx].get('group', '<anonymous>'), value)
  190. if options.duty_cycle:
  191. for sidx, value in enumerate(cum_dur):
  192. print 'Stream {} (group {}) duty cycle: {}'.format(sidx, notestreams[sidx].get('group', '<anonymous>'), value / max_dur)
  193. if options.notes:
  194. print 'Total notes: {}'.format(note_cnt)
  195. if options.histogram:
  196. print 'Pitch histogram:'
  197. show_hist(pitches)
  198. if options.vel_hist:
  199. print 'Velocity histogram:'
  200. show_hist(velocities)
  201. if options.duration:
  202. print 'Playing duration: {}'.format(max_dur)