You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.6 KiB

  1. from __future__ import unicode_literals
  2. import re
  3. from .common import PostProcessor
  4. class MetadataFromTitlePP(PostProcessor):
  5. def __init__(self, downloader, titleformat):
  6. super(MetadataFromTitlePP, self).__init__(downloader)
  7. self._titleformat = titleformat
  8. self._titleregex = (self.format_to_regex(titleformat)
  9. if re.search(r'%\(\w+\)s', titleformat)
  10. else titleformat)
  11. def format_to_regex(self, fmt):
  12. r"""
  13. Converts a string like
  14. '%(title)s - %(artist)s'
  15. to a regex like
  16. '(?P<title>.+)\ \-\ (?P<artist>.+)'
  17. """
  18. lastpos = 0
  19. regex = ''
  20. # replace %(..)s with regex group and escape other string parts
  21. for match in re.finditer(r'%\((\w+)\)s', fmt):
  22. regex += re.escape(fmt[lastpos:match.start()])
  23. regex += r'(?P<' + match.group(1) + '>.+)'
  24. lastpos = match.end()
  25. if lastpos < len(fmt):
  26. regex += re.escape(fmt[lastpos:])
  27. return regex
  28. def run(self, info):
  29. title = info['title']
  30. match = re.match(self._titleregex, title)
  31. if match is None:
  32. self._downloader.to_screen(
  33. '[fromtitle] Could not interpret title of video as "%s"'
  34. % self._titleformat)
  35. return [], info
  36. for attribute, value in match.groupdict().items():
  37. info[attribute] = value
  38. self._downloader.to_screen(
  39. '[fromtitle] parsed %s: %s'
  40. % (attribute, value if value is not None else 'NA'))
  41. return [], info