feed 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #!/usr/bin/env python3
  2. '''
  3. Feed parser with many features
  4. from a feed, it supports filtering, subslicing, random picking
  5. Beside feeds, it supports picking files from directories
  6. '''
  7. import os
  8. import logging
  9. from argparse import ArgumentParser
  10. from subprocess import check_output
  11. from collections import OrderedDict
  12. import re
  13. import urllib.request
  14. from urllib.parse import urlparse, unquote
  15. import posixpath
  16. import random
  17. from bisect import bisect
  18. from lxml import html
  19. import requests
  20. def weighted_choice(values, weights):
  21. '''
  22. random.choice with weights
  23. weights must be integers greater than 0.
  24. Their meaning is "relative", that is [1,2,3] is the same as [2,4,6]
  25. '''
  26. assert len(values) == len(weights)
  27. total = 0
  28. cum_weights = []
  29. for w in weights:
  30. total += w
  31. cum_weights.append(total)
  32. x = random.random() * total
  33. i = bisect(cum_weights, x)
  34. return values[i]
  35. class Audio(object):
  36. def __init__(self, url, durata=None):
  37. self.url = url
  38. if durata is None:
  39. durata = get_duration(url.encode('utf-8'))
  40. self.durata = durata
  41. def __str__(self):
  42. return self.url
  43. def __repr__(self):
  44. return '<Audio {} ({})>'.format(self.url, self.durata)
  45. @property
  46. def urls(self):
  47. return [self.url]
  48. class AudioGroup(list):
  49. def __init__(self, description=None):
  50. self.description = description or ''
  51. self.audios = []
  52. def __len__(self):
  53. return len(self.audios)
  54. def append(self, arg):
  55. self.audios.append(arg)
  56. def __str__(self):
  57. return '\n'.join(str(a) for a in self.audios)
  58. def __repr__(self):
  59. return '<AudioGroup "{}" ({})\n{} >'.\
  60. format(self.description, self.durata,
  61. '\n'.join(' ' + repr(a) for a in self.audios))
  62. @property
  63. def durata(self):
  64. return sum(a.durata for a in self.audios if a.durata is not None)
  65. @property
  66. def urls(self):
  67. return [a.url for a in self.audios]
  68. def get_tree(feed_url):
  69. if feed_url.startswith('http:') or feed_url.startswith('https:'):
  70. tree = html.fromstring(requests.get(feed_url).content)
  71. else:
  72. if not os.path.exists(feed_url):
  73. raise ValueError("file not found: {}".format(feed_url))
  74. tree = html.parse(open(feed_url))
  75. return tree
  76. def get_audio_from_description(text):
  77. # non-empty lines
  78. lines = [line.strip()
  79. for line in text.split('\n')
  80. if line.strip()]
  81. url = lines[0]
  82. durata = None
  83. if len(lines) > 1:
  84. durata = int(re.findall(r'\d+', lines[1].split('=')[1].strip())[0])
  85. return Audio(unquote(url), durata)
  86. # copied from larigira.fsutils
  87. def scan_dir_audio(dirname, extensions=('mp3', 'oga', 'wav', 'ogg')):
  88. for root, dirnames, filenames in os.walk(dirname):
  89. for fname in filenames:
  90. if fname.split('.')[-1].lower() in extensions:
  91. yield os.path.join(root, fname)
  92. def get_audio_from_dir(dirpath):
  93. fpaths = scan_dir_audio(dirpath)
  94. return [Audio('file://' + os.path.realpath(u)) for u in fpaths]
  95. def get_urls(tree):
  96. urls = tree.xpath('//item/description')
  97. for url_elem in urls:
  98. yield get_audio_from_description(url_elem.text)
  99. def get_grouped_urls(tree):
  100. groups = OrderedDict()
  101. items = tree.xpath('//item')
  102. for item in items:
  103. guid = item.xpath('guid')[0].text.strip()
  104. if guid not in groups:
  105. groups[guid] = AudioGroup(guid)
  106. groups[guid].append(get_audio_from_description(
  107. item.xpath('description')[0].text))
  108. return groups
  109. def get_duration(url):
  110. lineout = check_output(['ffprobe', '-v', 'error',
  111. '-show_entries', 'format=duration',
  112. '-i', url]).split(b'\n')
  113. duration = next(l for l in lineout if l.startswith(b'duration='))
  114. value = duration.split(b'=')[1]
  115. return int(float(value))
  116. def get_parser():
  117. p = ArgumentParser('Get music from a (well-specified) xml feed')
  118. src = p.add_argument_group('sources', 'How to deal with sources')
  119. p.add_argument('--source-weights',
  120. help='Select only one "source" based on this weights')
  121. filters = p.add_argument_group('filters', 'Select only items that match these conditions')
  122. filters.add_argument('--max-len', default=0, type=int,
  123. help='Exclude any audio that is longer than MAXLEN seconds')
  124. filters.add_argument('--random', default=False,
  125. action='store_true', help='Pick randomly')
  126. p.add_argument('--start', default=0, type=int,
  127. help='0-indexed start number. '
  128. 'By default, play from most recent')
  129. p.add_argument('--howmany', default=1, type=int,
  130. help='If not specified, only 1 will be played')
  131. p.add_argument('--slotsize', help='Seconds between each audio', type=int)
  132. p.add_argument('--group', help='Group articles', default=False,
  133. action='store_true')
  134. p.add_argument('--copy', help='Copy files to $TMPDIR', default=False,
  135. action='store_true')
  136. p.add_argument('--debug', help='Debug messages', default=False,
  137. action='store_true')
  138. p.add_argument('urls', metavar='URL', nargs='+')
  139. return p
  140. def put(audio, copy=False):
  141. if not copy:
  142. for url in audio.urls:
  143. print(url)
  144. else:
  145. for url in audio.urls:
  146. if url.split(':')[0] in ('http', 'https'):
  147. destdir = (os.environ.get('TMPDIR', '.'))
  148. fname = posixpath.basename(urlparse(url).path)
  149. # sanitize
  150. fname = "".join(c for c in fname
  151. if c.isalnum() or c in list('._-')).rstrip()
  152. dest = os.path.join(destdir, fname)
  153. os.makedirs(destdir, exist_ok=True)
  154. fname, headers = urllib.request.urlretrieve(url, dest)
  155. print('file://%s' % os.path.realpath(fname))
  156. else:
  157. # FIXME: file:// urls are just copied
  158. print(url)
  159. def main():
  160. parser = get_parser()
  161. args = parser.parse_args()
  162. if not args.debug:
  163. logging.basicConfig(level=logging.WARNING)
  164. else:
  165. logging.basicConfig(level=logging.DEBUG)
  166. sources = args.urls
  167. if args.source_weights:
  168. weights = tuple(map(int, args.source_weights.split(':')))
  169. if len(weights) != len(sources):
  170. parser.exit(status=2, message='Weight must be in the'
  171. ' same number as sources\n')
  172. sources = [weighted_choice(sources, weights)]
  173. audios = []
  174. for url in sources:
  175. if url.startswith('http:') or url.startswith('https:') \
  176. or os.path.isfile(url):
  177. # download the feed
  178. tree = get_tree(url)
  179. if not args.group:
  180. # get audio urls, removing those that are too long
  181. audios += [audio for audio in get_urls(tree)
  182. if args.max_len == 0 or
  183. audio.durata <= args.max_len]
  184. else:
  185. groups = get_grouped_urls(tree)
  186. audios += [groups[g] for g in groups.keys()
  187. if args.max_len == 0 or
  188. groups[g].durata <= args.max_len
  189. ]
  190. elif os.path.isdir(url):
  191. audiodir = get_audio_from_dir(url)
  192. if not args.group:
  193. audios += audiodir
  194. else:
  195. for a in audiodir:
  196. ag = AudioGroup(os.path.basename(a.url))
  197. ag.append(a)
  198. audios.append(ag)
  199. else:
  200. logging.info('unsupported url `%s`', url)
  201. audios = audios[args.start:]
  202. if args.random:
  203. random.shuffle(audios)
  204. audios = audios[:args.howmany]
  205. # the for loop excludes the last one
  206. # this is to support the --slotsize option
  207. if not audios:
  208. return
  209. for audio in audios[:-1]:
  210. if args.debug:
  211. print(repr(audio))
  212. else:
  213. put(audio, args.copy)
  214. if args.slotsize is not None:
  215. duration = audio.durata
  216. if duration < args.slotsize:
  217. print('## musica per {} secondi'
  218. .format(args.slotsize - duration))
  219. # finally, the last one
  220. if args.debug:
  221. print(repr(audios[-1]))
  222. else:
  223. put(audios[-1], args.copy)
  224. # else: # grouping; TODO: support slotsize
  225. # for item in groups:
  226. # if args.debug:
  227. # print('#', item, groups[item].durata)
  228. # print(groups[item])
  229. if __name__ == '__main__':
  230. main()