feed 17 KB

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