feed 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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, ArgumentTypeError
  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. import datetime
  19. from lxml import html
  20. import requests
  21. from pytimeparse.timeparse import timeparse
  22. def TimeDeltaType(arg):
  23. secs = timeparse(arg)
  24. if secs is None:
  25. raise ArgumentTypeError('%r is not a valid time range' % arg)
  26. return datetime.timedelta(seconds=timeparse(arg))
  27. def weighted_choice(values, weights):
  28. '''
  29. random.choice with weights
  30. weights must be integers greater than 0.
  31. Their meaning is "relative", that is [1,2,3] is the same as [2,4,6]
  32. '''
  33. assert len(values) == len(weights)
  34. total = 0
  35. cum_weights = []
  36. for w in weights:
  37. total += w
  38. cum_weights.append(total)
  39. x = random.random() * total
  40. i = bisect(cum_weights, x)
  41. return values[i]
  42. def delta_humanreadable(tdelta):
  43. if tdelta is None:
  44. return ''
  45. days = tdelta.days
  46. hours = (tdelta - datetime.timedelta(days=days)).seconds // 3600
  47. if days:
  48. return '{}d{}h'.format(days, hours)
  49. return '{}h'.format(hours)
  50. class Audio(object):
  51. def __init__(self, url, duration=None, date=None):
  52. self.url = url
  53. if duration is None:
  54. duration = get_duration(url.encode('utf-8'))
  55. self.duration = duration
  56. self.date = date
  57. def __str__(self):
  58. return self.url
  59. def __repr__(self):
  60. return '<Audio {} ({} {})>'.format(self.url, self.duration,
  61. delta_humanreadable(self.age))
  62. @property
  63. def urls(self):
  64. return [self.url]
  65. @property
  66. def age(self):
  67. if self.date is None:
  68. return None
  69. now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
  70. return now - self.date
  71. class AudioGroup(list):
  72. def __init__(self, description=None):
  73. self.description = description or ''
  74. self.audios = []
  75. def __len__(self):
  76. return len(self.audios)
  77. def append(self, arg):
  78. self.audios.append(arg)
  79. def __str__(self):
  80. return '\n'.join(str(a) for a in self.audios)
  81. def __repr__(self):
  82. return '<AudioGroup "{}" ({} {})\n{} >'.\
  83. format(self.description, self.duration,
  84. delta_humanreadable(self.age),
  85. '\n'.join(' ' + repr(a) for a in self.audios))
  86. @property
  87. def duration(self):
  88. return sum(a.duration for a in self.audios if a.duration is not None)
  89. @property
  90. def urls(self):
  91. return [a.url for a in self.audios]
  92. @property
  93. def date(self):
  94. for a in self.audios:
  95. if hasattr(a, 'date'):
  96. return a.date
  97. return None
  98. @property
  99. def age(self):
  100. if self.date is None:
  101. return None
  102. now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
  103. return now - self.date
  104. def get_tree(feed_url):
  105. if feed_url.startswith('http:') or feed_url.startswith('https:'):
  106. tree = html.fromstring(requests.get(feed_url).content)
  107. else:
  108. if not os.path.exists(feed_url):
  109. raise ValueError("file not found: {}".format(feed_url))
  110. tree = html.parse(open(feed_url))
  111. return tree
  112. def get_audio_from_description(text):
  113. # non-empty lines
  114. lines = [line.strip()
  115. for line in text.split('\n')
  116. if line.strip()]
  117. url = lines[0]
  118. duration = None
  119. if len(lines) > 1:
  120. duration = int(re.findall(r'\d+', lines[1].split('=')[1].strip())[0])
  121. return Audio(unquote(url), duration)
  122. # copied from larigira.fsutils
  123. def scan_dir_audio(dirname, extensions=('mp3', 'oga', 'wav', 'ogg')):
  124. for root, dirnames, filenames in os.walk(dirname):
  125. for fname in filenames:
  126. if fname.split('.')[-1].lower() in extensions:
  127. yield os.path.join(root, fname)
  128. def get_audio_from_dir(dirpath):
  129. fpaths = scan_dir_audio(dirpath)
  130. return [Audio('file://' + os.path.realpath(u)) for u in fpaths]
  131. def get_item_date(el):
  132. el_date = el.find('pubdate')
  133. if el_date is not None:
  134. return datetime.datetime.strptime(
  135. el_date.text, '%Y-%m-%dT%H:%M:%S%z')
  136. return None
  137. def get_urls(tree):
  138. items = tree.xpath('//item')
  139. for it in items:
  140. el_body = it.find('description')
  141. if el_body is not None:
  142. audio = get_audio_from_description(el_body.text)
  143. audio.date = get_item_date(it)
  144. yield audio
  145. def get_grouped_urls(tree):
  146. groups = OrderedDict()
  147. items = tree.xpath('//item')
  148. for item in items:
  149. guid = item.xpath('guid')[0].text.strip()
  150. if guid not in groups:
  151. groups[guid] = AudioGroup(guid)
  152. audio = get_audio_from_description(item.xpath('description')[0].text)
  153. audio.date = get_item_date(item)
  154. groups[guid].append(audio)
  155. return groups
  156. def get_duration(url):
  157. lineout = check_output(['ffprobe', '-v', 'error',
  158. '-show_entries', 'format=duration',
  159. '-i', url]).split(b'\n')
  160. duration = next(l for l in lineout if l.startswith(b'duration='))
  161. value = duration.split(b'=')[1]
  162. return int(float(value))
  163. HELP = '''
  164. Collect audio informations from multiple sources (XML feeds).
  165. Audios are (in that order):
  166. 1. Collected from feeds; (grouped by article if --group is used)
  167. 2. Filtered; everything that does not match with requirements is excluded
  168. 3. Sorted; even randomly
  169. 4. Sliced; take HOWMANY elements, skipping START elements
  170. 5. (if --copy) Copied
  171. Usage: '''
  172. def get_parser():
  173. p = ArgumentParser(HELP)
  174. src = p.add_argument_group('sources', 'How to deal with sources')
  175. src.add_argument('--source-weights',
  176. help='Select only one "source" based on this weights')
  177. src.add_argument('--group', default=False, action='store_true',
  178. help='Group audios that belong to the same article')
  179. filters = p.add_argument_group('filters', 'Select only items that match '
  180. 'these conditions')
  181. filters.add_argument('--max-len', default=0, type=int,
  182. help='Exclude any audio that is longer '
  183. 'than MAX_LEN seconds')
  184. filters.add_argument('--sort-by', default='no', type=str,
  185. choices=('random', 'date'))
  186. filters.add_argument('--reverse', default=False,
  187. action='store_true', help='Reverse list order')
  188. filters.add_argument('--min-len', default=0, type=int,
  189. help='Exclude any audio that is shorter '
  190. 'than MIN_LEN seconds')
  191. filters.add_argument('--min-age', default=datetime.timedelta(),
  192. type=TimeDeltaType,
  193. help='Exclude audio more recent than MIN_AGE')
  194. filters.add_argument('--max-age', default=datetime.timedelta(),
  195. type=TimeDeltaType,
  196. help='Exclude audio older than MAX_AGE')
  197. p.add_argument('--start', default=0, type=int,
  198. help='0-indexed start number. '
  199. 'By default, play from most recent')
  200. p.add_argument('--howmany', default=1, type=int,
  201. help='If not specified, only 1 will be played')
  202. p.add_argument('--slotsize', type=int,
  203. help='Seconds between each audio. Still unsupported')
  204. general = p.add_argument_group('general', 'General options')
  205. general.add_argument('--copy', help='Copy files to $TMPDIR', default=False,
  206. action='store_true')
  207. general.add_argument('--debug', help='Debug messages', default=False,
  208. action='store_true')
  209. p.add_argument('urls', metavar='URL', nargs='+')
  210. return p
  211. def put(audio, copy=False):
  212. if not copy:
  213. for url in audio.urls:
  214. print(url)
  215. else:
  216. for url in audio.urls:
  217. if url.split(':')[0] in ('http', 'https'):
  218. destdir = (os.environ.get('TMPDIR', '.'))
  219. fname = posixpath.basename(urlparse(url).path)
  220. # sanitize
  221. fname = "".join(c for c in fname
  222. if c.isalnum() or c in list('._-')).rstrip()
  223. dest = os.path.join(destdir, fname)
  224. os.makedirs(destdir, exist_ok=True)
  225. fname, headers = urllib.request.urlretrieve(url, dest)
  226. print('file://%s' % os.path.realpath(fname))
  227. else:
  228. # FIXME: file:// urls are just copied
  229. print(url)
  230. def main():
  231. parser = get_parser()
  232. args = parser.parse_args()
  233. if not args.debug:
  234. logging.basicConfig(level=logging.WARNING)
  235. else:
  236. logging.basicConfig(level=logging.DEBUG)
  237. sources = args.urls
  238. if args.source_weights:
  239. weights = tuple(map(int, args.source_weights.split(':')))
  240. if len(weights) != len(sources):
  241. parser.exit(status=2, message='Weight must be in the'
  242. ' same number as sources\n')
  243. sources = [weighted_choice(sources, weights)]
  244. audios = []
  245. for url in sources:
  246. if url.startswith('http:') or url.startswith('https:') \
  247. or os.path.isfile(url):
  248. # download the feed
  249. tree = get_tree(url)
  250. # filtering
  251. if not args.group:
  252. # get audio urls, removing those that are too long
  253. audios += [audio for audio in get_urls(tree) if
  254. (args.max_len == 0 or
  255. audio.duration <= args.max_len) and
  256. (args.min_len == 0 or
  257. audio.duration >= args.min_len) and
  258. (args.min_age.total_seconds() == 0 or
  259. audio.age >= args.min_age) and
  260. (args.max_age.total_seconds() == 0 or
  261. audio.age <= args.max_age)
  262. ]
  263. else:
  264. groups = get_grouped_urls(tree)
  265. audios += [groups[g] for g in groups.keys()
  266. if
  267. (args.max_len == 0 or
  268. groups[g].duration <= args.max_len) and
  269. (args.min_len == 0 or
  270. groups[g].duration >= args.max_len) and
  271. (args.min_age.total_seconds() == 0 or
  272. groups[g].age >= args.min_age) and
  273. (args.max_age.total_seconds() == 0 or
  274. groups[g].age <= args.max_age)
  275. ]
  276. elif os.path.isdir(url):
  277. audiodir = get_audio_from_dir(url)
  278. if not args.group:
  279. audios += audiodir
  280. else:
  281. for a in audiodir:
  282. ag = AudioGroup(os.path.basename(a.url))
  283. ag.append(a)
  284. audios.append(ag)
  285. else:
  286. logging.info('unsupported url `%s`', url)
  287. # sort
  288. if args.sort_by == 'random':
  289. random.shuffle(audios)
  290. elif args.sort_by == 'date':
  291. audios.sort(key=lambda x: x.age)
  292. if args.reverse:
  293. audios.reverse()
  294. # slice
  295. audios = audios[args.start:]
  296. audios = audios[:args.howmany]
  297. # the for loop excludes the last one
  298. # this is to support the --slotsize option
  299. if not audios:
  300. return
  301. for audio in audios[:-1]:
  302. if args.debug:
  303. print(repr(audio))
  304. else:
  305. put(audio, args.copy)
  306. if args.slotsize is not None:
  307. duration = audio.duration
  308. if duration < args.slotsize:
  309. print('## musica per {} secondi'
  310. .format(args.slotsize - duration))
  311. # finally, the last one
  312. if args.debug:
  313. print(repr(audios[-1]))
  314. else:
  315. put(audios[-1], args.copy)
  316. # else: # grouping; TODO: support slotsize
  317. # for item in groups:
  318. # if args.debug:
  319. # print('#', item, groups[item].duration)
  320. # print(groups[item])
  321. if __name__ == '__main__':
  322. main()