feed 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 posixpath
  11. import random
  12. import re
  13. import urllib.request
  14. from argparse import ArgumentParser, ArgumentTypeError
  15. from bisect import bisect
  16. from collections import OrderedDict
  17. from subprocess import CalledProcessError, check_output
  18. from urllib.parse import unquote, urlparse
  19. import requests
  20. from lxml import html
  21. from pytimeparse.timeparse import timeparse
  22. def get_int(s):
  23. return int(re.findall(r"\d+", s)[0])
  24. def DurationType(arg):
  25. if arg.isdecimal():
  26. secs = int(arg)
  27. else:
  28. secs = timeparse(arg)
  29. if secs is None:
  30. raise ArgumentTypeError("%r is not a valid duration" % arg)
  31. return secs
  32. def TimeDeltaType(arg):
  33. if arg.isdecimal():
  34. secs = int(arg)
  35. else:
  36. secs = timeparse(arg)
  37. if secs is None:
  38. raise ArgumentTypeError("%r is not a valid time range" % arg)
  39. return datetime.timedelta(seconds=secs)
  40. def weighted_choice(values, weights):
  41. """
  42. random.choice with weights
  43. weights must be integers greater than 0.
  44. Their meaning is "relative", that is [1,2,3] is the same as [2,4,6]
  45. """
  46. assert len(values) == len(weights)
  47. total = 0
  48. cum_weights = []
  49. for w in weights:
  50. total += w
  51. cum_weights.append(total)
  52. x = random.random() * total
  53. i = bisect(cum_weights, x)
  54. return values[i]
  55. def delta_humanreadable(tdelta):
  56. if tdelta is None:
  57. return ""
  58. days = tdelta.days
  59. hours = (tdelta - datetime.timedelta(days=days)).seconds // 3600
  60. if days:
  61. return "{}d{}h".format(days, hours)
  62. return "{}h".format(hours)
  63. def duration_humanreadable(seconds):
  64. hours = seconds // 3600
  65. minutes = (seconds - hours * 3600) // 60
  66. seconds = seconds % 60
  67. if hours > 0:
  68. return "{}h{}m{}s".format(hours, minutes, seconds)
  69. return "{}m{}s".format(minutes, seconds)
  70. class Audio(object):
  71. def __init__(self, url, duration=None, date=None):
  72. self.url = url
  73. if duration is None:
  74. duration = get_duration(url.encode("utf-8"))
  75. self.duration = duration
  76. self.date = date
  77. self.end_date = datetime.datetime(9999, 12, 31, tzinfo=datetime.timezone.utc)
  78. def __str__(self):
  79. return self.url
  80. def __repr__(self):
  81. return "<Audio {} ({} {})>".format(
  82. self.url,
  83. duration_humanreadable(self.duration),
  84. delta_humanreadable(self.age),
  85. )
  86. @property
  87. def urls(self):
  88. return [self.url]
  89. @property
  90. def age(self):
  91. if self.date is None:
  92. return None
  93. now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
  94. return now - self.date
  95. @property
  96. def valid(self):
  97. return self.end_date >= datetime.datetime.utcnow().replace(
  98. tzinfo=datetime.timezone.utc
  99. )
  100. class AudioGroup(list):
  101. def __init__(self, description=None):
  102. self.description = description or ""
  103. self.audios = []
  104. def __len__(self):
  105. return len(self.audios)
  106. def append(self, arg):
  107. self.audios.append(arg)
  108. def __str__(self):
  109. return "\n".join(str(a) for a in self.audios)
  110. def __repr__(self):
  111. return '<AudioGroup "{}" ({} {})\n{} >'.format(
  112. self.description,
  113. duration_humanreadable(self.duration),
  114. delta_humanreadable(self.age),
  115. "\n".join(" " + repr(a) for a in self.audios),
  116. )
  117. @property
  118. def duration(self):
  119. return sum(a.duration for a in self.audios if a.duration is not None)
  120. @property
  121. def urls(self):
  122. return [a.url for a in self.audios]
  123. @property
  124. def date(self):
  125. for a in self.audios:
  126. if hasattr(a, "date"):
  127. return a.date
  128. return None
  129. @property
  130. def age(self):
  131. if self.date is None:
  132. return None
  133. now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
  134. return now - self.date
  135. @property
  136. def valid(self):
  137. return len(self.audios) > 0
  138. def get_tree(feed_url):
  139. if feed_url.startswith("http:") or feed_url.startswith("https:"):
  140. tree = html.fromstring(requests.get(feed_url).content)
  141. else:
  142. if not os.path.exists(feed_url):
  143. raise ValueError("file not found: {}".format(feed_url))
  144. tree = html.parse(open(feed_url))
  145. return tree
  146. def get_audio_from_description(text):
  147. # non-empty lines
  148. lines = [line.strip() for line in text.split("\n") if line.strip()]
  149. url = lines[0]
  150. duration = None
  151. metadata = {}
  152. for line in text.split("\n")[1:]:
  153. if line.strip() and "=" in line:
  154. metadata[line.split("=")[0]] = line.split("=")[1]
  155. if "durata" in metadata:
  156. metadata["durata"] = get_int(metadata["durata"])
  157. if "txdate" in metadata:
  158. try:
  159. metadata["txdate"] = datetime.datetime.strptime(
  160. metadata["txdate"], "%Y-%m-%dT%H:%M:%S%z"
  161. )
  162. except ValueError:
  163. logging.warning("could not parse txdate %s", metadata["txdate"])
  164. del metadata["txdate"]
  165. a = Audio(
  166. unquote(url),
  167. duration=metadata.get("durata", None),
  168. date=metadata.get("txdate", None),
  169. )
  170. if "txdate" in metadata and "replica" in metadata:
  171. if metadata["replica"].endswith("g"):
  172. a.end_date = metadata["txdate"] + datetime.timedelta(
  173. days=get_int(metadata["replica"])
  174. )
  175. return a
  176. # copied from larigira.fsutils
  177. def scan_dir_audio(dirname, extensions=("mp3", "oga", "wav", "ogg")):
  178. for root, dirnames, filenames in os.walk(dirname):
  179. for fname in filenames:
  180. if fname.split(".")[-1].lower() in extensions:
  181. yield os.path.join(root, fname)
  182. def get_audio_from_dir(dirpath):
  183. fpaths = scan_dir_audio(dirpath)
  184. return [
  185. Audio(
  186. "file://" + os.path.realpath(u),
  187. date=datetime.datetime.fromtimestamp(os.path.getmtime(u)).replace(
  188. tzinfo=datetime.timezone.utc
  189. ),
  190. )
  191. for u in fpaths
  192. ]
  193. def get_item_date(el):
  194. el_date = el.find("pubdate")
  195. if el_date is not None:
  196. return datetime.datetime.strptime(el_date.text, "%Y-%m-%dT%H:%M:%S%z")
  197. return None
  198. def get_urls(tree):
  199. items = tree.xpath("//item")
  200. for it in items:
  201. title = it.find("title").text
  202. el_body = it.find("description")
  203. if el_body is not None:
  204. url = el_body.text
  205. try:
  206. audio = get_audio_from_description(url)
  207. except Exception as exc:
  208. logging.info("error getting duration for `%s`" % title)
  209. continue
  210. if audio.date is None:
  211. audio.date = get_item_date(it)
  212. yield audio
  213. def get_grouped_urls(tree):
  214. groups = OrderedDict()
  215. items = tree.xpath("//item")
  216. for item in items:
  217. guid = item.xpath("guid")[0].text.strip()
  218. if guid not in groups:
  219. groups[guid] = AudioGroup(guid)
  220. audio = get_audio_from_description(item.xpath("description")[0].text)
  221. audio.date = get_item_date(item)
  222. if audio.valid:
  223. groups[guid].append(audio)
  224. return groups
  225. def get_duration(url):
  226. try:
  227. lineout = check_output(
  228. ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-i", url]
  229. ).split(b"\n")
  230. except CalledProcessError as exc:
  231. raise ValueError("error probing `%s`" % url) from exc
  232. duration = next(l for l in lineout if l.startswith(b"duration="))
  233. value = duration.split(b"=")[1]
  234. return int(float(value))
  235. HELP = """
  236. Collect audio informations from multiple sources (XML feeds).
  237. Audios are (in that order):
  238. 1. Collected from feeds; (grouped by article if --group is used)
  239. 2. Filtered; everything that does not match with requirements is excluded
  240. 3. Sorted; even randomly
  241. 4. Sliced; take HOWMANY elements, skipping START elements
  242. 5. (if --copy) Copied
  243. Usage: """
  244. def get_parser():
  245. p = ArgumentParser(HELP)
  246. src = p.add_argument_group("sources", "How to deal with sources")
  247. src.add_argument(
  248. "--source-weights", help='Select only one "source" based on this weights'
  249. )
  250. src.add_argument(
  251. "--group",
  252. default=False,
  253. action="store_true",
  254. help="Group audios that belong to the same article",
  255. )
  256. filters = p.add_argument_group(
  257. "filters", "Select only items that match " "these conditions"
  258. )
  259. filters.add_argument(
  260. "--min-len",
  261. default=0,
  262. type=DurationType,
  263. help="Exclude any audio that is shorter " "than MIN_LEN seconds",
  264. )
  265. filters.add_argument(
  266. "--max-len",
  267. default=0,
  268. type=DurationType,
  269. help="Exclude any audio that is longer " "than MAX_LEN seconds",
  270. )
  271. filters.add_argument(
  272. "--sort-by", default="no", type=str, choices=("random", "date", "duration")
  273. )
  274. filters.add_argument(
  275. "--reverse", default=False, action="store_true", help="Reverse list order"
  276. )
  277. filters.add_argument(
  278. "--min-age",
  279. default=datetime.timedelta(),
  280. type=TimeDeltaType,
  281. help="Exclude audio more recent than MIN_AGE",
  282. )
  283. filters.add_argument(
  284. "--max-age",
  285. default=datetime.timedelta(),
  286. type=TimeDeltaType,
  287. help="Exclude audio older than MAX_AGE",
  288. )
  289. fill = p.add_argument_group(
  290. "fill", "Fill a 'block' with as many contents as possible"
  291. )
  292. fill.add_argument(
  293. "--fill",
  294. default=0,
  295. type=DurationType,
  296. help="Fill a block of duration LEN",
  297. metavar="LEN",
  298. )
  299. fill.add_argument(
  300. "--fill-interleave-dir",
  301. default=None,
  302. type=str, # FIXME: does it even work?
  303. help="Between each item, put a random file from DIR",
  304. )
  305. p.add_argument(
  306. "--start",
  307. default=0,
  308. type=int,
  309. help="0-indexed start number. " "By default, play from most recent",
  310. )
  311. p.add_argument(
  312. "--howmany", default=1, type=int, help="If not specified, only 1 will be played"
  313. )
  314. p.add_argument(
  315. "--slotsize", type=int, help="Seconds between each audio. Still unsupported"
  316. )
  317. general = p.add_argument_group("general", "General options")
  318. general.add_argument(
  319. "--copy", help="Copy files to $TMPDIR", default=False, action="store_true"
  320. )
  321. general.add_argument(
  322. "--debug", help="Debug messages", default=False, action="store_true"
  323. )
  324. p.add_argument("urls", metavar="URL", nargs="+")
  325. return p
  326. def put(audio, copy=False):
  327. if not copy:
  328. for url in audio.urls:
  329. print(url)
  330. else:
  331. for url in audio.urls:
  332. if url.split(":")[0] in ("http", "https"):
  333. destdir = os.environ.get("TMPDIR", ".")
  334. fname = posixpath.basename(urlparse(url).path)
  335. # sanitize
  336. fname = "".join(
  337. c for c in fname if c.isalnum() or c in list("._-")
  338. ).rstrip()
  339. dest = os.path.join(destdir, fname)
  340. os.makedirs(destdir, exist_ok=True)
  341. fname, headers = urllib.request.urlretrieve(url, dest)
  342. print("file://%s" % os.path.realpath(fname))
  343. else:
  344. # FIXME: file:// urls are just copied
  345. print(url)
  346. def retrieve(url, args):
  347. """
  348. returns a list of Audios or a list of AudioGroups
  349. """
  350. if not args.group:
  351. if os.path.isdir(url):
  352. audiodir = get_audio_from_dir(url)
  353. return audiodir
  354. elif url.startswith("http:") or url.startswith("https:") or os.path.isfile(url):
  355. return get_urls(get_tree(url))
  356. else:
  357. logging.info("unsupported url `%s`", url)
  358. return []
  359. else: # group
  360. if os.path.isdir(url):
  361. audiodir = get_audio_from_dir(url)
  362. agroups = []
  363. for a in audiodir:
  364. ag = AudioGroup(os.path.basename(a.url))
  365. ag.append(a)
  366. agroups.append(ag)
  367. return agroups
  368. elif url.startswith("http:") or url.startswith("https:") or os.path.isfile(url):
  369. groups = get_grouped_urls(get_tree(url))
  370. return groups.values()
  371. else:
  372. logging.info("unsupported url `%s`", url)
  373. return []
  374. def audio_passes_filters(audio, args):
  375. if not audio.valid:
  376. return False
  377. if args.max_len and audio.duration > args.max_len:
  378. return False
  379. if args.fill and audio.duration > args.fill:
  380. return False
  381. if args.min_len and audio.duration < args.min_len:
  382. return False
  383. if args.min_age.total_seconds() and audio.age < args.min_age:
  384. return False
  385. if args.max_age.total_seconds() and audio.age > args.max_age:
  386. return False
  387. return True
  388. def main():
  389. parser = get_parser()
  390. args = parser.parse_args()
  391. if not args.debug:
  392. logging.basicConfig(level=logging.WARNING)
  393. else:
  394. logging.basicConfig(level=logging.DEBUG)
  395. sources = args.urls
  396. if args.source_weights:
  397. weights = tuple(map(int, args.source_weights.split(":")))
  398. if len(weights) != len(sources):
  399. parser.exit(
  400. status=2, message="Weight must be in the" " same number as sources\n"
  401. )
  402. sources = [weighted_choice(sources, weights)]
  403. audios = []
  404. for url in sources:
  405. url_audios = retrieve(url, args)
  406. audios += [au for au in url_audios if audio_passes_filters(au, args)]
  407. # sort
  408. if args.sort_by == "random":
  409. random.shuffle(audios)
  410. elif args.sort_by == "date":
  411. audios.sort(key=lambda x: x.age)
  412. elif args.sort_by == "duration":
  413. audios.sort(key=lambda x: x.duration)
  414. if args.reverse:
  415. audios.reverse()
  416. # slice
  417. audios = audios[args.start :]
  418. if not args.fill:
  419. audios = audios[: args.howmany]
  420. if args.fill and audios:
  421. fill_audios = [audios.pop(0)]
  422. duration = fill_audios[0].duration
  423. for next_audio in audios:
  424. next_duration = next_audio.duration
  425. if args.fill_interleave_dir:
  426. interleaving = Audio(
  427. # TODO: factorize "pick file"
  428. "file://"
  429. + os.path.join(
  430. args.fill_interleave_dir,
  431. random.choice(os.listdir(args.fill_interleave_dir)),
  432. )
  433. )
  434. # logging.info("%r", interleaving)
  435. next_duration += interleaving.duration
  436. if args.fill - duration > next_duration:
  437. if args.fill_interleave_dir:
  438. fill_audios.append(interleaving)
  439. fill_audios.append(next_audio)
  440. duration += next_duration
  441. audios = fill_audios
  442. # the for loop excludes the last one
  443. # this is to support the --slotsize option
  444. if not audios:
  445. return
  446. for audio in audios[:-1]:
  447. if args.debug:
  448. print(repr(audio))
  449. else:
  450. put(audio, args.copy)
  451. if args.slotsize is not None:
  452. duration = audio.duration
  453. if duration < args.slotsize:
  454. print("## musica per {} secondi".format(args.slotsize - duration))
  455. # finally, the last one
  456. if args.debug:
  457. print(repr(audios[-1]))
  458. else:
  459. put(audios[-1], args.copy)
  460. # else: # grouping; TODO: support slotsize
  461. # for item in groups:
  462. # if args.debug:
  463. # print('#', item, groups[item].duration)
  464. # print(groups[item])
  465. if __name__ == "__main__":
  466. main()