feed 20 KB

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