-
Notifications
You must be signed in to change notification settings - Fork 1
/
beatricetools.py
308 lines (236 loc) · 8.96 KB
/
beatricetools.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import ast
from functools import singledispatch
import re
from typing import Any, List, Optional, overload, Tuple
import vapoursynth as vs
from vapoursynth import core
class ExprStr(ast.NodeVisitor):
"""
Drop-in wrapper for Expr() string in infix form.
Usage:
``core.std.Expr((clip1, clip2), ExprStr('x * 0.5 + y * 0.5'))``
``ExprStr((clip1, clip2), 'x * 0.5 + y * 0.5')``
Almost all operators and functions of Expr are supported,
but input string must contain a valid Python expression,
therefore syntax slightly differs:
1. Parentheses ``()`` are used to order operations.
2. Equality operator is ``==``.
3. Python conditional expression ``b if a else c`` replaces
conditional operator ``?``.
4. Stack manipulation functions swap() and dup() are not supported.
5. XOR (exclusive-or) logical operator is not supported.
More examples:
``>>> print(ExprStr('50 if a < b and b < c else 0'))``
``a b > c < d >=``
``>>> print(ExprStr('abs(sqrt(a) * (0 if b < 100 else c), e)'))``
``a sqrt b 100 < 0 c ? * e abs``
"""
variables = 'abcdefghijklmnopqrstuvwxyz'
# Available operators and their Expr respresentation
operators = {
ast.Add: '+',
ast.Sub: '-',
ast.Mult: '*',
ast.Div: '/',
ast.Eq: '=',
ast.Gt: '>',
ast.Lt: '<',
ast.GtE: '>=',
ast.LtE: '<=',
ast.Not: 'not',
ast.And: 'and',
ast.Or: 'or',
# ???: 'xor',
}
# Avaialable fixed-name functions and number of their arguments
functions = {
'abs': 1,
'exp': 1,
'log': 1,
'sqrt': 1,
'max': 2,
'min': 2,
'pow': 2,
}
# Available functions with names defined as regexp and number of their
# arguments
functions_re = {
# re.compile(r'dup\d*') : 1,
# re.compile(r'swap\d*'): 2,
}
@overload
def __new__(cls, string: str) -> 'ExprStr': ...
@overload
def __new__(cls, *args: Any, **kwargs: Any) -> vs.VideoNode: ...
def __new__(cls, *args, **kwargs):
if len(args) == 0 and len(kwargs) == 0:
raise TypeError
if len(args) == 1 and isinstance(args[0], str):
filter_mode = False
string = args[0]
elif len(kwargs) == 1 and 'string' in kwargs:
filter_mode = False
string = kwargs['string']
else:
filter_mode = True
if len(args) > 1:
string = args[1]
else:
string = kwargs['string']
obj = object.__new__(cls)
obj.__init__(string)
if filter_mode:
if len(args) > 1:
new_args = list(args)
new_args[1] = str(obj)
return core.std.Expr(*new_args, **kwargs)
else:
kwargs['string'] = str(obj)
return core.std.Expr(*args, **kwargs)
else:
return obj
def __init__(self, string: str):
self.stack: List[str] = []
# 'eval' mode takes care of assignment operator
self.visit(ast.parse(string, mode='eval'))
def visit_Num(self, node: ast.Num) -> None:
self.stack.append(str(node.n))
def visit_Name(self, node: ast.Name) -> None:
if (len(node.id) > 1
or node.id not in self.variables):
raise SyntaxError(
'ExprStr: clip name "{}" at column {} is not valid.'
.format(node.id, node.col_offset))
self.stack.append(node.id)
def visit_Compare(self, node: ast.Compare) -> Any:
if len(node.ops) > 1:
raise SyntaxError(
'ExprStr: chaining of comparison operators at column {}'
' is not supported'.format(node.col_offset))
op = node.ops[0]
if type(op) not in self.operators:
raise SyntaxError(
'ExprStr: operator "{}" at column {} is not supported.'
.format(op, node.col_offset))
self.stack.append(self.operators[type(op)])
self.visit(node.comparators[0])
self.visit(node.left)
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any:
if type(node.op) not in self.operators:
raise SyntaxError(
'ExprStr: operator "{}" at column {} is not supported.'
.format(type(node.op), node.col_offset))
self.stack.append(self.operators[type(node.op)])
self.visit(node.operand)
def visit_BoolOp(self, node: ast.BoolOp) -> Any:
if type(node.op) not in self.operators:
raise SyntaxError(
'ExprStr: operator "{}" at column {} is not supported.'
.format(type(node.op), node.col_offset))
self.stack.append(self.operators[type(node.op)])
self.visit(node.values[0])
self.visit(node.values[1])
def visit_BinOp(self, node: ast.BinOp) -> Any:
if type(node.op) not in self.operators:
raise SyntaxError(
'ExprStr: operator "{}" at column {} is not supported.'
.format(type(node.op), node.col_offset))
self.stack.append(self.operators[type(node.op)])
self.visit(node.right)
self.visit(node.left)
def visit_Call(self, node: ast.Call) -> Any:
import re
is_re_function = False
args_required = 0
if node.func.id not in self.functions:
for pattern, args_count in self.functions_re.items():
if pattern.fullmatch(node.func.id):
is_re_function = True
args_required = args_count
break
if not is_re_function:
raise SyntaxError(
'ExprStr: function "{}" at column {} is not supported.'
.format(node.func.id, node.col_offset))
if not is_re_function:
args_required = self.functions[node.func.id]
if len(node.args) != args_required:
raise SyntaxError(
'ExprStr: function "{}" at column {}'
' takes exactly {} arguments, but {} provided.'
.format(node.func.id, node.col_offset, args_required,
len(node.args)))
self.stack.append(node.func.id)
for arg in node.args[::-1]:
self.visit(arg)
def visit_IfExp(self, node: ast.IfExp) -> Any:
self.stack.append('?')
self.visit(node.orelse)
self.visit(node.body)
self.visit(node.test)
def __str__(self) -> str:
return ' '.join(self.stack[::-1])
def extract_planes(clip: vs.VideoNode, plane_format: vs.Format = vs.GRAY) \
-> List[vs.VideoNode]:
"""
Extracts clip's planes as list.
Usage:
``y, u, v = extract_planes(clip)``
``y, *_ = extract_planes(clip)``
``_, u, v = extract_planes(clip)``
:param VideoNode clip: Clip to work with.
:param Format plane_format: Format to use for each extracted plane.
:return: List with every plane of clip in order they're stored.
"""
return [core.std.ShufflePlanes(clip, i, plane_format)
for i in range(clip.format.num_planes)]
def get_subsampling(w: int, h: int, separator='') -> str:
'''
Converts VapourSynth chroma subsampling notation to human-readable form.
Opposite of ``get_vs_subsampling()``.
Usage:
``get_subsampling(1, 1) => '420'``
``get_subsampling(0, 0, ':') => '4:4:4'``
'''
j = 4
a = j if w == 0 else j // (w * 2)
b = a if h == 0 else 0
return separator.join(j, a, b)
@singledispatch
def get_vs_subsampling(subsampling: str) -> Tuple[int, int]:
'''
Converts human-readable chroma subsampling notation to VapourSynth form.
Opposite of ``get_subsampling()``.
Usage:
``w, h = get_vs_subsampling('420')``
``_, h = get_vs_subsampling('YUV420P10')``
``w, _ = get_vs_subsampling(444)``
``w, h = get_vs_subsampling(4, 1, 1)``
'''
pattern = re.compile(r'\d\d\d')
subsampling = pattern.search(subsampling)[0]
return get_vs_subsampling(int(subsampling))
@get_vs_subsampling.register
def _(subsampling: int, chroma_w: Optional[int] = None,
chroma_h: Optional[int] = None) -> Tuple[int, int]:
from math import log2
if chroma_w is not None and chroma_h is None:
raise TypeError("No enough arguments: 'chroma_h' is missing")
elif chroma_w is None and chroma_h is not None:
raise TypeError("No enough arguments: 'chroma_w' is missing")
elif chroma_w is None and chroma_h is None:
j = subsampling // 100
a = subsampling // 10
b = subsampling % 10
else:
j = subsampling
a = chroma_w
b = chroma_h
w = int(log2(j // a))
h = 0 if a == b else 1
# To my understanding of semantics of this values, h can't be 2.
# Yet we have it for 4:1:0. so returning 2 when all luma pixels on both
# rows shares the same chroma pixel (X:1:0 subsampling schemas).
if (a, b) == (1, 0):
h = 2
return w, h