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