-
Notifications
You must be signed in to change notification settings - Fork 0
/
midentify.py
95 lines (73 loc) · 2.39 KB
/
midentify.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
Get video information from a file using mplayer's midentify script
The function you want is midentify
@author Abhishek Mukherjee
@email [email protected]
"""
from subprocess import Popen, PIPE
import re
import ast
MIDENTIFY_CMD = 'midentify'
PAIR_REGEX = re.compile(r"^(?P<key>[^=\n]+)=(?P<value>(\\\n|.)*)$",
flags=re.MULTILINE)
UNESCAPE_REGEX = re.compile(r"\\(.)", flags=re.DOTALL)
class MidentifyFile(object):
"""
Holds the metadata for a movie file created by midentify() call. Keys for
the metadata can be accessed either through [] or simple . notation and
will be named after their midentify counterparts, lowercased, with ID_
removed from the beginning
>>> f = MidentifyFile("ID_VIDEO_WIDTH=1920\\nID_VIDEO_HEIGHT=1080")
>>> f.video_width
1920
>>> f.video_height
1080
"""
def __init__(self, information_string):
""" Create an object based on output from midentify
information_string should be similar to:
ID_VIDEO_WIDTH=1920
ID_VIDEO_HEIGHT=1080
"""
self.keys = []
for match in PAIR_REGEX.finditer(information_string):
key = match.groupdict()['key']
value = UNESCAPE_REGEX.sub(lambda m: m.groups()[0],
match.groupdict()['value'])
value = self._guess_type(value)
key = key.lower().lstrip('id_')
self.__dict__[key] = value
self.keys.append(key)
@staticmethod
def _guess_type(val):
""" Try to interpret a result from midentify
>>> MidentifyFile._guess_type("5")
5
>>> MidentifyFile._guess_type("5.5")
5.5
>>> MidentifyFile._guess_type("foo") == unicode('foo')
True
"""
try:
return ast.literal_eval(val)
except Exception:
return unicode(val)
def __getitem__(self, key):
if key not in self.keys:
return None
return self.__dict__[key]
def __iter__(self):
for key in self.keys:
yield (key, self[key])
def midentify(filename):
"""Returns a MidentifyFile object for the file at filename"""
output = Popen([MIDENTIFY_CMD, filename], stdout=PIPE).communicate()[0]
return MidentifyFile(output)
def _test():
"""
Tests this module
"""
import doctest
doctest.testmod()
if __name__ == '__main__':
_test()