feed 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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, CalledProcessError
  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. parts = lines[1].split('=')
  132. if len(parts) > 1 and parts[1]:
  133. duration = int(re.findall(r'\d+', parts[1].strip())[0])
  134. return Audio(unquote(url), duration)
  135. # copied from larigira.fsutils
  136. def scan_dir_audio(dirname, extensions=('mp3', 'oga', 'wav', 'ogg')):
  137. for root, dirnames, filenames in os.walk(dirname):
  138. for fname in filenames:
  139. if fname.split('.')[-1].lower() in extensions:
  140. yield os.path.join(root, fname)
  141. def get_audio_from_dir(dirpath):
  142. fpaths = scan_dir_audio(dirpath)
  143. return [Audio('file://' + os.path.realpath(u)) for u in fpaths]
  144. def get_item_date(el):
  145. el_date = el.find('pubdate')
  146. if el_date is not None:
  147. return datetime.datetime.strptime(
  148. el_date.text, '%Y-%m-%dT%H:%M:%S%z')
  149. return None
  150. def get_urls(tree):
  151. items = tree.xpath('//item')
  152. for it in items:
  153. title = it.find('title').text
  154. el_body = it.find('description')
  155. if el_body is not None:
  156. url = el_body.text
  157. try:
  158. audio = get_audio_from_description(url)
  159. except Exception as exc:
  160. logging.info('error getting duration for `%s`' % title)
  161. continue
  162. audio.date = get_item_date(it)
  163. yield audio
  164. def get_grouped_urls(tree):
  165. groups = OrderedDict()
  166. items = tree.xpath('//item')
  167. for item in items:
  168. guid = item.xpath('guid')[0].text.strip()
  169. if guid not in groups:
  170. groups[guid] = AudioGroup(guid)
  171. audio = get_audio_from_description(item.xpath('description')[0].text)
  172. audio.date = get_item_date(item)
  173. groups[guid].append(audio)
  174. return groups
  175. def get_duration(url):
  176. try:
  177. lineout = check_output(['ffprobe', '-v', 'error',
  178. '-show_entries', 'format=duration',
  179. '-i', url]).split(b'\n')
  180. except CalledProcessError as exc:
  181. raise ValueError('error probing `%s`' % url) from exc
  182. duration = next(l for l in lineout if l.startswith(b'duration='))
  183. value = duration.split(b'=')[1]
  184. return int(float(value))
  185. HELP = '''
  186. Collect audio informations from multiple sources (XML feeds).
  187. Audios are (in that order):
  188. 1. Collected from feeds; (grouped by article if --group is used)
  189. 2. Filtered; everything that does not match with requirements is excluded
  190. 3. Sorted; even randomly
  191. 4. Sliced; take HOWMANY elements, skipping START elements
  192. 5. (if --copy) Copied
  193. Usage: '''
  194. def get_parser():
  195. p = ArgumentParser(HELP)
  196. src = p.add_argument_group('sources', 'How to deal with sources')
  197. src.add_argument('--source-weights',
  198. help='Select only one "source" based on this weights')
  199. src.add_argument('--group', default=False, action='store_true',
  200. help='Group audios that belong to the same article')
  201. filters = p.add_argument_group('filters', 'Select only items that match '
  202. 'these conditions')
  203. filters.add_argument('--min-len', default=0, type=DurationType,
  204. help='Exclude any audio that is shorter '
  205. 'than MIN_LEN seconds')
  206. filters.add_argument('--max-len', default=0, type=DurationType,
  207. help='Exclude any audio that is longer '
  208. 'than MAX_LEN seconds')
  209. filters.add_argument('--sort-by', default='no', type=str,
  210. choices=('random', 'date', 'duration'))
  211. filters.add_argument('--reverse', default=False,
  212. action='store_true', help='Reverse list order')
  213. filters.add_argument('--min-age', default=datetime.timedelta(),
  214. type=TimeDeltaType,
  215. help='Exclude audio more recent than MIN_AGE')
  216. filters.add_argument('--max-age', default=datetime.timedelta(),
  217. type=TimeDeltaType,
  218. help='Exclude audio older than MAX_AGE')
  219. p.add_argument('--start', default=0, type=int,
  220. help='0-indexed start number. '
  221. 'By default, play from most recent')
  222. p.add_argument('--howmany', default=1, type=int,
  223. help='If not specified, only 1 will be played')
  224. p.add_argument('--slotsize', type=int,
  225. help='Seconds between each audio. Still unsupported')
  226. general = p.add_argument_group('general', 'General options')
  227. general.add_argument('--copy', help='Copy files to $TMPDIR', default=False,
  228. action='store_true')
  229. general.add_argument('--debug', help='Debug messages', default=False,
  230. action='store_true')
  231. p.add_argument('urls', metavar='URL', nargs='+')
  232. return p
  233. def put(audio, copy=False):
  234. if not copy:
  235. for url in audio.urls:
  236. print(url)
  237. else:
  238. for url in audio.urls:
  239. if url.split(':')[0] in ('http', 'https'):
  240. destdir = (os.environ.get('TMPDIR', '.'))
  241. fname = posixpath.basename(urlparse(url).path)
  242. # sanitize
  243. fname = "".join(c for c in fname
  244. if c.isalnum() or c in list('._-')).rstrip()
  245. dest = os.path.join(destdir, fname)
  246. os.makedirs(destdir, exist_ok=True)
  247. fname, headers = urllib.request.urlretrieve(url, dest)
  248. print('file://%s' % os.path.realpath(fname))
  249. else:
  250. # FIXME: file:// urls are just copied
  251. print(url)
  252. def main():
  253. parser = get_parser()
  254. args = parser.parse_args()
  255. if not args.debug:
  256. logging.basicConfig(level=logging.WARNING)
  257. else:
  258. logging.basicConfig(level=logging.DEBUG)
  259. sources = args.urls
  260. if args.source_weights:
  261. weights = tuple(map(int, args.source_weights.split(':')))
  262. if len(weights) != len(sources):
  263. parser.exit(status=2, message='Weight must be in the'
  264. ' same number as sources\n')
  265. sources = [weighted_choice(sources, weights)]
  266. audios = []
  267. for url in sources:
  268. if url.startswith('http:') or url.startswith('https:') \
  269. or os.path.isfile(url):
  270. # download the feed
  271. tree = get_tree(url)
  272. # filtering
  273. if not args.group:
  274. # get audio urls, removing those that are too long
  275. audios += [audio for audio in get_urls(tree) if
  276. (args.max_len == 0 or
  277. audio.duration <= args.max_len) and
  278. (args.min_len == 0 or
  279. audio.duration >= args.min_len) and
  280. (args.min_age.total_seconds() == 0 or
  281. audio.age >= args.min_age) and
  282. (args.max_age.total_seconds() == 0 or
  283. audio.age <= args.max_age)
  284. ]
  285. else:
  286. groups = get_grouped_urls(tree)
  287. audios += [groups[g] for g in groups.keys()
  288. if
  289. (args.max_len == 0 or
  290. groups[g].duration <= args.max_len) and
  291. (args.min_len == 0 or
  292. groups[g].duration >= args.max_len) and
  293. (args.min_age.total_seconds() == 0 or
  294. groups[g].age >= args.min_age) and
  295. (args.max_age.total_seconds() == 0 or
  296. groups[g].age <= args.max_age)
  297. ]
  298. elif os.path.isdir(url):
  299. audiodir = get_audio_from_dir(url)
  300. if not args.group:
  301. audios += audiodir
  302. else:
  303. for a in audiodir:
  304. ag = AudioGroup(os.path.basename(a.url))
  305. ag.append(a)
  306. audios.append(ag)
  307. else:
  308. logging.info('unsupported url `%s`', url)
  309. # sort
  310. if args.sort_by == 'random':
  311. random.shuffle(audios)
  312. elif args.sort_by == 'date':
  313. audios.sort(key=lambda x: x.age)
  314. elif args.sort_by == 'duration':
  315. audios.sort(key=lambda x: x.duration)
  316. if args.reverse:
  317. audios.reverse()
  318. # slice
  319. audios = audios[args.start:]
  320. audios = audios[:args.howmany]
  321. # the for loop excludes the last one
  322. # this is to support the --slotsize option
  323. if not audios:
  324. return
  325. for audio in audios[:-1]:
  326. if args.debug:
  327. print(repr(audio))
  328. else:
  329. put(audio, args.copy)
  330. if args.slotsize is not None:
  331. duration = audio.duration
  332. if duration < args.slotsize:
  333. print('## musica per {} secondi'
  334. .format(args.slotsize - duration))
  335. # finally, the last one
  336. if args.debug:
  337. print(repr(audios[-1]))
  338. else:
  339. put(audios[-1], args.copy)
  340. # else: # grouping; TODO: support slotsize
  341. # for item in groups:
  342. # if args.debug:
  343. # print('#', item, groups[item].duration)
  344. # print(groups[item])
  345. if __name__ == '__main__':
  346. main()