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.

43 lines
1.5 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. def format_to_regex(self, fmt):
  10. r"""
  11. Converts a string like
  12. '%(title)s - %(artist)s'
  13. to a regex like
  14. '(?P<title>.+)\ \-\ (?P<artist>.+)'
  15. """
  16. lastpos = 0
  17. regex = ''
  18. # replace %(..)s with regex group and escape other string parts
  19. for match in re.finditer(r'%\((\w+)\)s', fmt):
  20. regex += re.escape(fmt[lastpos:match.start()])
  21. regex += r'(?P<' + match.group(1) + '>.+)'
  22. lastpos = match.end()
  23. if lastpos < len(fmt):
  24. regex += re.escape(fmt[lastpos:len(fmt)])
  25. return regex
  26. def run(self, info):
  27. title = info['title']
  28. match = re.match(self._titleregex, title)
  29. if match is None:
  30. self._downloader.to_screen('[fromtitle] Could not interpret title of video as "%s"' % self._titleformat)
  31. return [], info
  32. for attribute, value in match.groupdict().items():
  33. value = match.group(attribute)
  34. info[attribute] = value
  35. self._downloader.to_screen('[fromtitle] parsed ' + attribute + ': ' + value)
  36. return [], info