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.

47 lines
1.5 KiB

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