feed 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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 datetime
  8. import logging
  9. import os
  10. import glob
  11. import posixpath
  12. import random
  13. import re
  14. import sys
  15. import urllib.request
  16. from argparse import ArgumentParser, ArgumentTypeError
  17. from bisect import bisect
  18. from collections import OrderedDict
  19. from subprocess import CalledProcessError, check_output
  20. from urllib.parse import unquote, urlparse
  21. import shutil
  22. import requests
  23. from lxml import html
  24. from pytimeparse.timeparse import timeparse
  25. def debug(*args, **kwargs):
  26. kwargs.setdefault("file", sys.stderr)
  27. print(*args, **kwargs)
  28. def get_int(s):
  29. return int(re.findall(r"\d+", s)[0])
  30. def DurationType(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 duration" % arg)
  37. return secs
  38. def TimeDeltaType(arg):
  39. if arg.isdecimal():
  40. secs = int(arg)
  41. else:
  42. secs = timeparse(arg)
  43. if secs is None:
  44. raise ArgumentTypeError("%r is not a valid time range" % arg)
  45. return datetime.timedelta(seconds=secs)
  46. def weighted_choice(values, weights):
  47. """
  48. random.choice with weights
  49. weights must be integers greater than 0.
  50. Their meaning is "relative", that is [1,2,3] is the same as [2,4,6]
  51. """
  52. assert len(values) == len(weights)
  53. if not values:
  54. raise IndexError("Cannot do weighted choice from an empty sequence")
  55. if sum(weights) == 0:
  56. raise IndexError("Cannot do weighted choice where weight=0")
  57. total = 0
  58. cum_weights = []
  59. for w in weights:
  60. total += w
  61. cum_weights.append(total)
  62. x = random.random() * total
  63. i = bisect(cum_weights, x)
  64. return values[i]
  65. def delta_humanreadable(tdelta):
  66. if tdelta is None:
  67. return ""
  68. days = tdelta.days
  69. hours = (tdelta - datetime.timedelta(days=days)).seconds // 3600
  70. if days:
  71. return "{}d{}h".format(days, hours)
  72. return "{}h".format(hours)
  73. def duration_humanreadable(seconds):
  74. hours = seconds // 3600
  75. minutes = (seconds - hours * 3600) // 60
  76. seconds = seconds % 60
  77. if hours > 0:
  78. return "{}h{}m{}s".format(hours, minutes, seconds)
  79. return "{}m{}s".format(minutes, seconds)
  80. class Audio(object):
  81. def __init__(self, url, duration=None, date=None):
  82. self.url = url
  83. self._duration = duration
  84. self.date = date
  85. self.end_date = datetime.datetime(9999, 12, 31, tzinfo=datetime.timezone.utc)
  86. def __str__(self):
  87. return self.url
  88. def __repr__(self):
  89. return "<Audio {} ({} {})>".format(
  90. self.url,
  91. duration_humanreadable(self.duration),
  92. delta_humanreadable(self.age),
  93. )
  94. @property
  95. def duration(self):
  96. if self._duration is None:
  97. self._duration = get_duration(self.url)
  98. return self._duration
  99. @property
  100. def urls(self):
  101. return [self.url]
  102. @property
  103. def age(self):
  104. if self.date is None:
  105. return None
  106. now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
  107. return now - self.date
  108. @property
  109. def valid(self):
  110. return self.end_date >= datetime.datetime.utcnow().replace(
  111. tzinfo=datetime.timezone.utc
  112. )
  113. class AudioGroup(list):
  114. def __init__(self, description=None):
  115. self.description = description or ""
  116. self.audios = []
  117. def __len__(self):
  118. return len(self.audios)
  119. def append(self, arg):
  120. self.audios.append(arg)
  121. def __str__(self):
  122. return "\n".join(str(a) for a in self.audios)
  123. def __repr__(self):
  124. return '<AudioGroup "{}" ({} {})\n{} >'.format(
  125. self.description,
  126. duration_humanreadable(self.duration),
  127. delta_humanreadable(self.age),
  128. "\n".join(" " + repr(a) for a in self.audios),
  129. )
  130. @property
  131. def duration(self):
  132. return sum(a.duration for a in self.audios if a.duration is not None)
  133. @property
  134. def urls(self):
  135. return [a.url for a in self.audios]
  136. @property
  137. def date(self):
  138. for a in self.audios:
  139. if hasattr(a, "date"):
  140. return a.date
  141. return None
  142. @property
  143. def age(self):
  144. if self.date is None:
  145. return None
  146. now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
  147. return now - self.date
  148. @property
  149. def valid(self):
  150. return len(self.audios) > 0
  151. def get_tree(feed_url):
  152. if feed_url.startswith("http:") or feed_url.startswith("https:"):
  153. tree = html.fromstring(requests.get(feed_url).content)
  154. else:
  155. if not os.path.exists(feed_url):
  156. raise ValueError("file not found: {}".format(feed_url))
  157. tree = html.parse(open(feed_url))
  158. return tree
  159. def get_audio_from_description(text):
  160. # non-empty lines
  161. lines = [line.strip() for line in text.split("\n") if line.strip()]
  162. url = lines[0]
  163. duration = None
  164. metadata = {}
  165. for line in text.split("\n")[1:]:
  166. if line.strip() and "=" in line:
  167. metadata[line.split("=")[0]] = line.split("=")[1]
  168. if "durata" in metadata:
  169. metadata["durata"] = get_int(metadata["durata"])
  170. if "txdate" in metadata:
  171. try:
  172. metadata["txdate"] = datetime.datetime.strptime(
  173. metadata["txdate"], "%Y-%m-%dT%H:%M:%S%z"
  174. )
  175. except ValueError:
  176. logging.warning("could not parse txdate %s", metadata["txdate"])
  177. del metadata["txdate"]
  178. a = Audio(
  179. unquote(url),
  180. duration=metadata.get("durata", None),
  181. date=metadata.get("txdate", None),
  182. )
  183. if "txdate" in metadata and "replica" in metadata:
  184. if metadata["replica"].endswith("g"):
  185. a.end_date = metadata["txdate"] + datetime.timedelta(
  186. days=get_int(metadata["replica"])
  187. )
  188. return a
  189. def is_audio_file(fpath, extensions=("mp3", "oga", "wav", "ogg")):
  190. if fpath.split(".")[-1].lower() in extensions:
  191. return True
  192. return False
  193. # copied from larigira.fsutils
  194. def scan_dir_audio(dirname):
  195. for root, dirnames, filenames in os.walk(dirname):
  196. for fname in filenames:
  197. if is_audio_file(fname):
  198. path = os.path.join(root, fname)
  199. yield path
  200. def get_audio_from_file(fpath):
  201. a = Audio(
  202. "file://" + os.path.realpath(fpath),
  203. date=datetime.datetime.fromtimestamp(os.path.getmtime(fpath)).replace(
  204. tzinfo=datetime.timezone.utc
  205. ),
  206. )
  207. return [a]
  208. def get_audio_from_dir(dirpath):
  209. fpaths = scan_dir_audio(dirpath)
  210. ret = []
  211. for u in fpaths:
  212. try:
  213. a = Audio(
  214. "file://" + os.path.realpath(u),
  215. date=datetime.datetime.fromtimestamp(os.path.getmtime(u)).replace(
  216. tzinfo=datetime.timezone.utc
  217. ),
  218. )
  219. except ValueError:
  220. continue
  221. ret.append(a)
  222. return ret
  223. def get_item_date(el):
  224. el_date = el.find("pubdate")
  225. # Wed, 15 Jan 2020 22:45:33 +0000
  226. formats = ["%a, %d %b %Y %H:%M:%S %z", "%Y-%m-%dT%H:%M:%S%z"]
  227. if el_date is not None:
  228. for fmt in formats:
  229. try:
  230. return datetime.datetime.strptime(el_date.text, fmt)
  231. except ValueError:
  232. pass
  233. return None
  234. def get_urls_generic(tree, url_selector="description[text()]", metadata_in_body=True):
  235. items = tree.xpath("//item")
  236. for it in items:
  237. title = it.find("title").text
  238. el_body = it.find("description")
  239. if metadata_in_body and el_body is not None:
  240. url = el_body.text
  241. try:
  242. audio = get_audio_from_description(url)
  243. except Exception as exc:
  244. logging.info("error getting duration for `%s`" % title)
  245. continue
  246. if audio.date is None:
  247. audio.date = get_item_date(it)
  248. yield audio
  249. else:
  250. try:
  251. url = it.xpath(url_selector)[0]
  252. except IndexError:
  253. logging.warning("no audio found in %s", title)
  254. else:
  255. audio = Audio(url)
  256. audio.date = get_item_date(it)
  257. yield audio
  258. def get_urls_from_podcast(tree):
  259. return get_urls_generic(tree, url_selector="enclosure/@url", metadata_in_body=False)
  260. def get_urls_from_custom_feed(tree):
  261. return get_urls_generic(tree, metadata_in_body=True)
  262. def get_urls_factory(url, args):
  263. if args.feed_type == "customrss":
  264. return get_urls_from_custom_feed
  265. if args.feed_type == "podcast":
  266. return get_urls_from_podcast
  267. raise ValueError("unsupported feeedtype %s" % args.feed_type)
  268. def get_grouped_urls(tree):
  269. groups = OrderedDict()
  270. items = tree.xpath("//item")
  271. for item in items:
  272. guid = item.xpath("guid")[0].text.strip()
  273. if guid not in groups:
  274. groups[guid] = AudioGroup(guid)
  275. audio = get_audio_from_description(item.xpath("description")[0].text)
  276. audio.date = get_item_date(item)
  277. if audio.valid:
  278. groups[guid].append(audio)
  279. return groups
  280. def get_duration(url):
  281. try:
  282. lineout = check_output(
  283. ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-i", url]
  284. ).split(b"\n")
  285. except CalledProcessError as exc:
  286. raise ValueError("error probing `%s`" % url) from exc
  287. duration = next(l for l in lineout if l.startswith(b"duration="))
  288. value = duration.split(b"=")[1]
  289. return int(float(value))
  290. HELP = """
  291. Collect audio informations from multiple sources (XML feeds).
  292. Audios are (in that order):
  293. 1. Collected from feeds; (grouped by article if --group is used)
  294. 2. Filtered; everything that does not match with requirements is excluded
  295. 3. Sorted; even randomly
  296. 4. Sliced; take HOWMANY elements, skipping START elements
  297. 5. (if --copy) Copied
  298. Usage: """
  299. def get_parser():
  300. p = ArgumentParser(HELP)
  301. parsing = p.add_argument_group("parsing", "Feed parsing")
  302. parsing.add_argument(
  303. "--feed-type", type=str, choices=["customrss", "podcast"], default="customrss"
  304. )
  305. src = p.add_argument_group("sources", "How to deal with sources")
  306. src.add_argument(
  307. "--source-weights", help='Select only one "source" based on this weights'
  308. )
  309. src.add_argument(
  310. "--group",
  311. default=False,
  312. action="store_true",
  313. help="Group audios that belong to the same article",
  314. )
  315. src.add_argument(
  316. "--glob",
  317. default=False,
  318. action="store_true",
  319. help="Wildcards in filenames are interpreted",
  320. )
  321. filters = p.add_argument_group(
  322. "filters", "Select only items that match " "these conditions"
  323. )
  324. filters.add_argument(
  325. "--min-len",
  326. default=0,
  327. type=DurationType,
  328. help="Exclude any audio that is shorter " "than MIN_LEN seconds",
  329. )
  330. filters.add_argument(
  331. "--max-len",
  332. default=0,
  333. type=DurationType,
  334. help="Exclude any audio that is longer " "than MAX_LEN seconds",
  335. )
  336. filters.add_argument(
  337. "--sort-by", default="no", type=str, choices=("random", "date", "duration")
  338. )
  339. filters.add_argument(
  340. '--random-seed', default=None, help='Initialize the random generator. For debug only')
  341. filters.add_argument(
  342. "--reverse", default=False, action="store_true", help="Reverse list order"
  343. )
  344. filters.add_argument(
  345. "--min-age",
  346. default=datetime.timedelta(),
  347. type=TimeDeltaType,
  348. help="Exclude audio more recent than MIN_AGE",
  349. )
  350. filters.add_argument(
  351. "--max-age",
  352. default=datetime.timedelta(),
  353. type=TimeDeltaType,
  354. help="Exclude audio older than MAX_AGE",
  355. )
  356. fill = p.add_argument_group(
  357. "fill", "Fill a 'block' with as many contents as possible"
  358. )
  359. fill.add_argument(
  360. "--fill",
  361. default=0,
  362. type=DurationType,
  363. help="Fill a block of duration LEN",
  364. metavar="LEN",
  365. )
  366. fill.add_argument(
  367. "--fill-reverse",
  368. default=False,
  369. action="store_true",
  370. help="Reverse list order after the fill algorithm",
  371. )
  372. fill.add_argument(
  373. "--fill-interleave-dir",
  374. default=None,
  375. type=str, # FIXME: does it even work?
  376. help="Between each item, put a random file from DIR",
  377. )
  378. p.add_argument(
  379. "--start",
  380. default=0,
  381. type=int,
  382. help="0-indexed start number. " "By default, play from most recent",
  383. )
  384. p.add_argument(
  385. "--howmany", default=1, type=int, help="If not specified, only 1 will be played"
  386. )
  387. p.add_argument(
  388. "--slotsize", type=int, help="Seconds between each audio. Still unsupported"
  389. )
  390. general = p.add_argument_group("general", "General options")
  391. general.add_argument(
  392. "--copy", help="Copy files to $TMPDIR", default=False, action="store_true"
  393. )
  394. general.add_argument(
  395. "--debug", help="Debug messages", default=False, action="store_true"
  396. )
  397. p.add_argument("urls", metavar="URL", nargs="+")
  398. return p
  399. def downloader(url, dest):
  400. headers = {}
  401. mode = "wb"
  402. if os.path.exists(dest):
  403. headers["Range"] = "bytes=%d-" % os.stat(dest).st_size
  404. mode = "ab"
  405. r = requests.get(url, stream=True, headers=headers)
  406. if r.status_code == 416: # range not satisfiable
  407. return
  408. with open(dest, mode) as f:
  409. for chunk in r.iter_content(chunk_size=1 << 16):
  410. f.write(chunk)
  411. def put(audio, copy=False):
  412. if not copy:
  413. for url in audio.urls:
  414. print(url)
  415. else:
  416. destdir = os.environ.get("TMPDIR", ".")
  417. os.makedirs(destdir, exist_ok=True)
  418. for url in audio.urls:
  419. if url.split(":")[0] in ("http", "https"):
  420. fname = posixpath.basename(urlparse(url).path)
  421. # sanitize
  422. fname = "".join(
  423. c for c in fname if c.isalnum() or c in list("._-")
  424. ).rstrip()
  425. dest = os.path.join(destdir, fname)
  426. downloader(url, dest)
  427. print("file://%s" % os.path.realpath(dest))
  428. elif url.startswith("file:///"):
  429. src = url[len('file://'):]
  430. dest = os.path.join(destdir, os.path.basename(src))
  431. shutil.copy(src, dest)
  432. print("file://%s" % os.path.realpath(dest))
  433. else:
  434. # what's that? let's just copy it
  435. print(url)
  436. def retrieve(url, args):
  437. """
  438. returns a list of Audios or a list of AudioGroups
  439. """
  440. if not args.group:
  441. if os.path.isdir(url):
  442. audiodir = get_audio_from_dir(url)
  443. return audiodir
  444. elif os.path.isfile(url) and is_audio_file(url):
  445. return get_audio_from_file(url)
  446. elif url.startswith("http:") or url.startswith("https:") or os.path.isfile(url):
  447. getter = get_urls_factory(url, args)
  448. tree = get_tree(url)
  449. return getter(tree)
  450. else:
  451. logging.info("unsupported url `%s`", url)
  452. return []
  453. else: # group
  454. if os.path.isdir(url):
  455. audiodir = get_audio_from_dir(url)
  456. agroups = []
  457. for a in audiodir:
  458. ag = AudioGroup(os.path.basename(a.url))
  459. ag.append(a)
  460. agroups.append(ag)
  461. return agroups
  462. elif os.path.isfile(url) and is_audio_file(url):
  463. audio = get_audio_from_file(url)[0]
  464. ag = AudioGroup(url)
  465. ag.append(audio)
  466. return [ag]
  467. elif url.startswith("http:") or url.startswith("https:") or os.path.isfile(url):
  468. groups = get_grouped_urls(get_tree(url))
  469. return groups.values()
  470. else:
  471. logging.info("unsupported url `%s`", url)
  472. return []
  473. def audio_passes_filters(audio, args):
  474. logging.debug(audio.end_date)
  475. if not audio.valid:
  476. return False
  477. if args.max_len and audio.duration > args.max_len:
  478. return False
  479. if args.fill and audio.duration > args.fill:
  480. return False
  481. if args.min_len and audio.duration < args.min_len:
  482. return False
  483. if args.min_age.total_seconds() and audio.age < args.min_age:
  484. return False
  485. if args.max_age.total_seconds() and audio.age > args.max_age:
  486. return False
  487. return True
  488. def expand_glob(sources: list, weights: list) -> tuple:
  489. '''
  490. Let's say that sources=["foo", "bar*"] and weight=["2", "3"] and on filesystem there are bar1 and bar2.
  491. Result: ["foo", "bar1", "bar2"], ["2", "3", "3"]
  492. '''
  493. new_sources = []
  494. new_weights = []
  495. for src, weight in zip(sources, weights):
  496. if not src.startswith('http://') and not src.startswith('https://') and '*' in src:
  497. expanded_source = glob.glob(src)
  498. else:
  499. expanded_source = [src]
  500. logging.debug("glob: %s -> %s", src, expanded_source)
  501. expanded_weight = [weight] * len(expanded_source)
  502. new_sources += expanded_source
  503. new_weights += expanded_weight
  504. return new_sources, new_weights
  505. def get_audio_by_source(args, parser):
  506. sources = args.urls
  507. if args.source_weights:
  508. weights = list(map(int, args.source_weights.split(":")))
  509. if len(weights) != len(sources):
  510. parser.exit(
  511. status=2,
  512. message="Weight must be in the same number as sources\n",
  513. )
  514. else:
  515. weights = [1] * len(sources)
  516. if args.glob:
  517. sources, weights = expand_glob(sources, weights)
  518. audio_by_source = OrderedDict()
  519. for i, url in enumerate(sources):
  520. url_audios = list(retrieve(url, args))
  521. logging.debug("Found %d audios in %s", len(url_audios), url)
  522. url_audios = [au for au in url_audios if audio_passes_filters(au, args)]
  523. logging.debug("%d of those are passing filters", len(url_audios))
  524. audio_by_source[url] = url_audios
  525. if not url_audios:
  526. weights[i] = 0
  527. if sum(weights) == 0:
  528. return
  529. sources = [weighted_choice(sources, weights)]
  530. return audio_by_source, sources
  531. def main():
  532. parser = get_parser()
  533. args = parser.parse_args()
  534. if not args.debug:
  535. logging.basicConfig(level=logging.WARNING)
  536. else:
  537. logging.basicConfig(level=logging.DEBUG)
  538. if args.random_seed is not None:
  539. random.seed(args.random_seed)
  540. audio_by_source, sources = get_audio_by_source(args, parser)
  541. audios = []
  542. for source_url in sources:
  543. audios += audio_by_source[source_url]
  544. logging.debug("Found %d audios", len(audios))
  545. # sort
  546. if args.sort_by == "random":
  547. random.shuffle(audios)
  548. elif args.sort_by == "date":
  549. audios.sort(key=lambda x: x.age)
  550. elif args.sort_by == "duration":
  551. audios.sort(key=lambda x: x.duration)
  552. if args.reverse:
  553. audios.reverse()
  554. # slice
  555. audios = audios[args.start :]
  556. if not args.fill:
  557. audios = audios[: args.howmany]
  558. if args.fill and audios:
  559. fill_audios = [audios.pop(0)]
  560. duration = fill_audios[0].duration
  561. for next_audio in audios:
  562. next_duration = next_audio.duration
  563. if args.fill_interleave_dir:
  564. interleaving = Audio(
  565. "file://"
  566. + random.choice(list(scan_dir_audio(args.fill_interleave_dir)))
  567. )
  568. # logging.info("%r", interleaving)
  569. next_duration += interleaving.duration
  570. if args.fill - duration > next_duration:
  571. if args.fill_interleave_dir:
  572. fill_audios.append(interleaving)
  573. fill_audios.append(next_audio)
  574. duration += next_duration
  575. audios = fill_audios
  576. if args.fill_reverse:
  577. audios.reverse()
  578. # the for loop excludes the last one
  579. # this is to support the --slotsize option
  580. if not audios:
  581. return
  582. for audio in audios[:-1]:
  583. if args.debug:
  584. debug(repr(audio))
  585. else:
  586. put(audio, args.copy)
  587. if args.slotsize is not None:
  588. duration = audio.duration
  589. if duration < args.slotsize:
  590. # TODO: prendi musica da un'altra cartella
  591. print("## musica per {} secondi".format(args.slotsize - duration))
  592. # finally, the last one
  593. if args.debug:
  594. debug(repr(audios[-1]))
  595. else:
  596. put(audios[-1], args.copy)
  597. # else: # grouping; TODO: support slotsize
  598. # for item in groups:
  599. # if args.debug:
  600. # print('#', item, groups[item].duration)
  601. # print(groups[item])
  602. if __name__ == "__main__":
  603. main()