feed 13 KB

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