-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathIR.py
More file actions
521 lines (435 loc) · 20.2 KB
/
IR.py
File metadata and controls
521 lines (435 loc) · 20.2 KB
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
from __future__ import annotations
import abc
import typing
import fractions
from Util import *
from AbstractFlagIndex import *
class FramePoint:
def __init__(self, flagIndexType: typing.Type[AbstractFlagIndex], timestamp: int, timeBase: fractions.Fraction):
self.flagIndexType: typing.Type[AbstractFlagIndex] = flagIndexType
self.timestamp: int = timestamp
self.timeBase: fractions.Fraction = timeBase
self.flags: typing.List[typing.Any] = self.flagIndexType.getDefaultFlags()
self.attachments: typing.Dict[type, typing.Any] = {}
self.debugFrame: cv.Mat | None = None
def setFlag(self, index: AbstractFlagIndex, val: typing.Any, inDiskCache: bool = False):
if inDiskCache and val is not None:
val = DiskCacheHandle(val)
self.flags[index] = val
def getFlag(self, index: AbstractFlagIndex) -> typing.Any:
val = self.flags[index]
if isinstance(val, DiskCacheHandle):
return val.get()
return val
def setAttachment(self, key: type, val: typing.Any, inDiskCache: bool = False):
if inDiskCache and val is not None:
val = DiskCacheHandle(val)
self.attachments[key] = val
def getAttachment(self, key: type) -> typing.Any:
val = self.attachments.get(key)
if isinstance(val, DiskCacheHandle):
return val.get()
return val
def setDebugFlag(self, *val: typing.Any):
self.flags[self.flagIndexType.Debug()] = val
def getDebugFlag(self) -> typing.Any:
return self.flags[self.flagIndexType.Debug()]
def setDebugFrame(self, debugFrame):
self.debugFrame = debugFrame
def setDebugFrameHSV(self, debugFrame: cv.Mat):
self.setDebugFrame(cv.cvtColor(debugFrame, cv.COLOR_HSV2BGR))
def clearDebugFrame(self):
self.debugFrame = None
def getDebugFrame(self) -> cv.Mat | None:
return self.debugFrame
def timeString(self) -> str:
return formatTimestamp(self.timeBase, self.timestamp)
def toString(self) -> str:
return "frame {}".format(formatTimestamp(self.timeBase, self.timestamp))
def toStringFull(self) -> str:
return "frame {} {}".format(formatTimestamp(self.timeBase, self.timestamp), self.flags)
class FPIR: # Frame Point Intermediate Representation
def __init__(self, flagIndexType: typing.Type[AbstractFlagIndex], sampleRate: int, timeBase: fractions.Fraction):
self.flagIndexType: typing.Type[AbstractFlagIndex] = flagIndexType
self.framePoints: typing.List[FramePoint] = []
self.sampleRate: int = sampleRate
self.timeBase: fractions.Fraction = timeBase
def genVirtualEnd(self) -> FramePoint:
index: int = len(self.framePoints)
timestamp: int = self.framePoints[-1].timestamp
return FramePoint(self.flagIndexType, timestamp, self.timeBase)
def getFramePointsWithVirtualEnd(self, length: int = 1) -> typing.List[FramePoint]:
return self.framePoints + [self.genVirtualEnd()] * length
def toStringFull(self) -> str:
lines = []
for framePoint in self.framePoints:
lines.append(framePoint.toStringFull() + "\n")
return "".join(lines)
class FPIRPass(abc.ABC):
@abc.abstractmethod
def apply(self, fpir: FPIR):
# returns anything or nothing
pass
class FPIRPassBooleanRemoveNoise(FPIRPass):
def __init__(self, flag: AbstractFlagIndex, trueToFalse: bool = True, minLength: int = 10):
self.flag: AbstractFlagIndex = flag
self.trueToFalse: bool = trueToFalse
self.minLength: int = minLength
def apply(self, fpir: FPIR):
for id, framePoint in enumerate(fpir.framePoints):
if framePoint.getFlag(self.flag) != self.trueToFalse:
continue
l = id - self.minLength
r = id + self.minLength
if l < 0 or r > len(fpir.framePoints) - 1:
continue
length = 1
for i in range(id - 1, l - 1, -1):
if fpir.framePoints[i].getFlag(self.flag) != framePoint.getFlag(self.flag):
break
length += 1
for i in range(id + 1, r + 1):
if fpir.framePoints[i].getFlag(self.flag) != framePoint.getFlag(self.flag):
break
length += 1
if length < self.minLength: # flip
framePoint.setFlag(self.flag, not framePoint.getFlag(self.flag))
class FPIRPassDetectFeatureJump(FPIRPass):
def __init__(self, featFlag: AbstractFlagIndex, dstFlag: AbstractFlagIndex, \
featOpMean: typing.Callable[[typing.List[typing.Any]], typing.Any] = lambda feats : np.mean(feats, axis=0), \
featOpDist: typing.Callable[[typing.Any, typing.Any], float] = lambda lhs, rhs : np.linalg.norm(lhs - rhs), \
threshDist: float = 0.5, \
featOpStd: typing.Callable[[typing.List[typing.Any]], float] = lambda feats: np.mean(np.std(feats, axis=0)), \
threshStd: typing.Optional[float] = 0.0, \
windowSize: int = 3, inverse: bool = False
):
self.featFlag: AbstractFlagIndex = featFlag
self.dstFlag: AbstractFlagIndex = dstFlag
self.featOpMean: typing.Callable[[typing.List[typing.Any]], typing.Any] = featOpMean
self.featOpDist: typing.Callable[[typing.Any, typing.Any], float] = featOpDist
self.threshDist: float = threshDist
self.windowSize: int = windowSize
self.inverse: bool = inverse
self.featOpStd: typing.Callable[[typing.List[typing.Any]], float] = featOpStd
self.threshStd: float = threshStd
def apply(self, fpir: FPIR):
framePointsExt = fpir.getFramePointsWithVirtualEnd(self.windowSize)
for id, framePoint in enumerate(fpir.framePoints):
featsToBeMeant = []
for i in range(id + 1, id + 1 + self.windowSize):
featsToBeMeant.append(framePointsExt[i].getFlag(self.featFlag))
meanFeat = self.featOpMean(featsToBeMeant)
dist = self.featOpDist(framePoint.getFlag(self.featFlag), meanFeat)
if self.threshStd > 0.0:
stdFeat: float = self.featOpStd(featsToBeMeant)
if stdFeat > self.threshStd:
continue
if dist >= self.threshDist:
framePoint.setFlag(self.dstFlag, not self.inverse)
else:
framePoint.setFlag(self.dstFlag, self.inverse)
class FPIRPassShift(FPIRPass):
def __init__(self, tgtFlag: AbstractFlagIndex, refFlag: AbstractFlagIndex, shift: int, padding: typing.Any):
self.tgtFlag: AbstractFlagIndex = tgtFlag
self.refFlag: AbstractFlagIndex = refFlag
self.shift: int = shift
self.padding: typing.Any = padding
def apply(self, fpir: FPIR):
for iTgt, framePoint in enumerate(fpir.framePoints):
iSrc = iTgt - self.shift
if iSrc < 0 or iSrc >= len(fpir.framePoints):
framePoint.setFlag(self.tgtFlag, self.padding)
else:
framePoint.setFlag(self.tgtFlag, fpir.framePoints[iSrc].getFlag(self.refFlag))
class FPIRPassFunctional(FPIRPass):
def __init__(self, func: typing.Callable[[FPIR], typing.Any]):
self.func = func
def apply(self, fpir: FPIR):
return self.func(fpir)
class FPIRPassFramewiseFunctional(FPIRPass):
def __init__(self, func: typing.Callable[[FramePoint], typing.Any]):
self.func = func
def apply(self, fpir: FPIR):
for id, framePoint in enumerate(fpir.framePoints):
self.func(framePoint)
class FPIRPassBuildIntervals(FPIRPass):
@abc.abstractmethod
def apply(self, fpir: FPIR) -> typing.List[Interval]:
pass
class FPIRPassBooleanBuildIntervals(FPIRPassBuildIntervals):
def __init__(self, *flags: AbstractFlagIndex):
self.flags: typing.Tuple[AbstractFlagIndex, ...] = flags
def apply(self, fpir: FPIR) -> typing.List[Interval]:
intervals: typing.List[Interval] = []
lastBegin: typing.List[int] = [0] * len(self.flags)
state: typing.List[bool] = [False] * len(self.flags)
for i, framePoint in enumerate(fpir.getFramePointsWithVirtualEnd()):
for s in range(len(state)):
if not state[s]: # off -> on
if framePoint.getFlag(self.flags[s]):
state[s] = True
lastBegin[s] = i
else: # on - > off
if not framePoint.getFlag(self.flags[s]):
state[s] = False
intervals.append(Interval(self.flags[s].name, fpir.framePoints[lastBegin[s]].timestamp, framePoint.timestamp, framePoint.timeBase, fpir.framePoints[lastBegin[s] : i]))
return intervals
class Interval:
def __init__(
self,
label: str,
begin: int,
end: int,
timeBase: fractions.Fraction,
framePoints: typing.Optional[typing.List[FramePoint]] = None,
):
self.label: str = label
self.framePoints: typing.List[FramePoint] = framePoints if framePoints is not None else []
# begin and end are not promised to align with underlying framePoints after applying IIRPass
self.begin: int = begin # timestamp
self.end: int = end # timestamp
self.timeBase: fractions.Fraction = timeBase
self.style: str = "Default"
self.text: str = ""
self.attachments: typing.Dict[type, typing.Any] = {}
def getName(self, id: int = -1) -> str:
return f"Subtitle_{self.label}_{id}"
def setAttachment(self, key: type, val: typing.Any, inDiskCache: bool = False):
if inDiskCache and val is not None:
val = DiskCacheHandle(val)
self.attachments[key] = val
def getAttachment(self, key: type) -> typing.Any:
val = self.attachments.get(key)
if isinstance(val, DiskCacheHandle):
return val.get()
return val
def isAttachmentInDiskCache(self, key: type) -> bool:
return isinstance(self.attachments.get(key), DiskCacheHandle)
def assEventStr(self, id: int = -1) -> str:
template = "Dialogue: 0,{},{},{},,0,0,0,,{}"
sBegin = formatTimestamp(self.timeBase, self.begin)
sEnd = formatTimestamp(self.timeBase, self.end)
text = self.text
if text == "":
text = self.getName(id)
return template.format(sBegin, sEnd, self.style, text)
def srtEventStr(self, counter: int) -> str:
sBegin = formatTimestampSrt(self.timeBase, self.begin)
sEnd = formatTimestampSrt(self.timeBase, self.end)
text = self.text if self.text else self.getName(counter - 1)
return f"{counter}\n{sBegin} --> {sEnd}\n{text}"
def timeString(self) -> str:
return "[{}, {})".format(formatTimestamp(self.timeBase, self.begin), formatTimestamp(self.timeBase, self.end))
def timeStringBegin(self) -> str:
return formatTimestamp(self.timeBase, self.begin)
def timeStringEnd(self) -> str:
return formatTimestamp(self.timeBase, self.end)
def dist(self, other: Interval) -> int:
l = self
r = other
if self.begin > other.begin:
l = other
r = self
return r.begin - l.end
def distFramePoint(self, framePoint: FramePoint) -> int:
if framePoint.timestamp < self.begin:
return self.begin - framePoint.timestamp
if framePoint.timestamp > self.end:
return framePoint.timestamp - self.end
return 0
def distTimestamp(self, timestamp: int) -> int:
if timestamp < self.begin:
return self.begin - timestamp
if timestamp > self.end:
return timestamp - self.end
return 0
def intersects(self, other: Interval) -> bool:
return self.dist(other) < 0
def touches(self, other: Interval) -> bool:
return self.dist(other) == 0
def getMidPoint(self) -> int:
return int((self.begin + self.end) // 2)
def merge(self, other: Interval) -> Interval:
merged = Interval(self.label, min(self.begin, other.begin), max(self.end, other.end), self.timeBase, self.framePoints + other.framePoints)
later = self if self.end >= other.end else other
# Prefer later's attachments
merged.attachments = dict(later.attachments)
return merged
class IIR: # Interval Intermediate Representation
def __init__(self, fps: fractions.Fraction, timeBase: fractions.Fraction):
self.fps: fractions.Fraction = fps
self.timeBase: fractions.Fraction = timeBase
self.styles: typing.List[str] = []
self.intervals: typing.List[Interval] = []
def appendFromFpir(self, fpir: FPIR, fpirPassBuildIntervals: FPIRPassBuildIntervals):
# does not guarantee that intervals are in order after appending
self.intervals += fpirPassBuildIntervals.apply(fpir)
def sort(self):
self.intervals.sort(key=lambda interval : interval.begin)
def stylesStr(self) -> str:
return "".join(style + "\n" for style in self.styles)
def assEventsStr(self) -> str:
lines: typing.List[str] = []
labelCounter: typing.Dict[str, int] = {}
for _, interval in enumerate(self.intervals):
id = labelCounter.get(interval.label, 0)
labelCounter[interval.label] = id + 1
lines.append(interval.assEventStr(id) + "\n")
return "".join(lines)
def srtEventStr(self) -> str:
blocks: typing.List[str] = []
for counter, interval in enumerate(self.intervals, start=1):
blocks.append(interval.srtEventStr(counter))
return "\n\n".join(blocks) + "\n"
def getMidpoints(self) -> typing.List[typing.Tuple[str, int]]:
midpoints: typing.List[typing.Tuple[str, int]] = []
labelCounter: typing.Dict[str, int] = {}
for _, interval in enumerate(self.intervals):
id = labelCounter.get(interval.label, 0)
labelCounter[interval.label] = id + 1
midpoints.append((interval.getName(id), interval.getMidPoint()))
return midpoints
def ms2Timestamp(self, ms: int) -> int:
return ms2Timestamp(ms, self.timeBase)
class IIRPass(abc.ABC):
@abc.abstractmethod
def apply(self, iir: IIR) -> typing.Any:
# returns anything
pass
class IIRPassFillGap(IIRPass):
def __init__(self, label: str, maxGap: int = 300, meetPoint: float = 0.5):
self.label: str = label
self.maxGap: int = maxGap # in millisecs
self.meetPoint: float = meetPoint
def apply(self, iir: IIR):
for id, interval in enumerate(iir.intervals):
if interval.label != self.label:
continue
otherId = id + 1
while otherId < len(iir.intervals):
otherInterval = iir.intervals[otherId]
if otherInterval.label != self.label:
otherId += 1
continue
if interval.dist(otherInterval) > iir.ms2Timestamp(self.maxGap):
break
if interval.dist(otherInterval) <= 0:
otherId += 1
continue
mid = int(interval.end * (1.0 - self.meetPoint) + otherInterval.begin * self.meetPoint)
interval.end = mid
otherInterval.begin = mid
break
iir.sort()
class IIRPassExtend(IIRPass):
def __init__(self, label: str, front: int = 0, back: int = 0):
self.label: str = label
self.front: int = front # in millisecs
self.back: int = back # in millisecs
def apply(self, iir: IIR):
# Assert sorted
for id, interval in enumerate(iir.intervals):
if interval.label != self.label:
continue
if id == 0:
interval.begin = max(interval.begin - iir.ms2Timestamp(self.front), 0)
else:
interval.begin = max(interval.begin - iir.ms2Timestamp(self.front), iir.intervals[id - 1].end)
if id == len(iir.intervals) - 1:
interval.end += iir.ms2Timestamp(self.back)
else:
interval.end = min(interval.end + iir.ms2Timestamp(self.back), iir.intervals[id + 1].begin)
class IIRPassAlign(IIRPass):
def __init__(self, tgtLabel: str, refLabel: str, maxGap: int = 300):
self.tgtFlag: str = tgtLabel
self.refFlag: str = refLabel
self.maxGap: int = maxGap # in millisecs
def apply(self, iir: IIR):
refPoints: typing.List[int] = []
for _, interval in enumerate(iir.intervals):
if interval.label != self.refFlag:
continue
refPoints.append(interval.begin)
refPoints.append(interval.end)
refPoints.sort()
if len(refPoints) == 0:
return
for _, interval in enumerate(iir.intervals):
if interval.label != self.tgtFlag:
continue
r = 0
while r < len(refPoints) and refPoints[r] < interval.begin:
r = r + 1
l = max(0, r - 1)
r = min(r, len(refPoints) - 1)
lDist = refPoints[l] - interval.begin # <= 0
rDist = refPoints[r] - interval.begin # >= 0
dist = lDist
if rDist < -lDist:
dist = rDist
if abs(dist) <= iir.ms2Timestamp(self.maxGap):
interval.begin += dist
r = 0
while r < len(refPoints) and refPoints[r] < interval.end:
r = r + 1
l = max(0, r - 1)
r = min(r, len(refPoints) - 1)
lDist = refPoints[l] - interval.end # <= 0
rDist = refPoints[r] - interval.end # >= 0
dist = lDist
if rDist < -lDist:
dist = rDist
if abs(dist) <= iir.ms2Timestamp(self.maxGap):
interval.end += dist
iir.sort()
class IIRPassFunctional(IIRPass):
def __init__(self, func: typing.Callable[[IIR], typing.Any]):
self.func = func
def apply(self, iir: IIR):
return self.func(iir)
class IIRPassIntervalwiseFunctional(IIRPass):
def __init__(self, func: typing.Callable[[Interval], typing.Any]):
self.func = func
def apply(self, iir: IIR):
for id, interval in enumerate(iir.intervals):
self.func(interval)
class IIRPassSetStyles(IIRPass):
def __init__(self, styles: typing.List[str]):
self.styles = styles
def apply(self, iir: IIR):
iir.styles = self.styles
class IIRPassOffset(IIRPass):
def __init__(self, offset: int):
self.offset: int = offset
def apply(self, iir: IIR):
for id, interval in enumerate(iir.intervals):
interval.begin += self.offset
interval.end += self.offset
class IIRPassRemovePredicate(IIRPass):
def __init__(self, pred: typing.Callable[[Interval], bool]):
self.pred = pred
def apply(self, iir: IIR):
iir.intervals = [interval for interval in iir.intervals if not self.pred(interval)]
class IIRPassDenoise(IIRPass):
def __init__(self, label: str, minTime: int):
self.label: str = label
self.minTime: int = minTime
def apply(self, iir: IIR):
iir.intervals = [interval for interval in iir.intervals if not (interval.label == self.label and interval.end - interval.begin < iir.ms2Timestamp(self.minTime))]
class IIRPassMerge(IIRPass):
def __init__(self, pred: typing.Callable[[IIR, Interval, Interval], bool], debug: bool = False):
self.debug: bool = debug
self.pred = pred
def apply(self, iir: IIR):
newIntervals: typing.List[Interval] = []
for i in range(len(iir.intervals)):
if len(newIntervals) == 0:
newIntervals.append(iir.intervals[i])
continue
if self.pred(iir, newIntervals[-1], iir.intervals[i]):
if self.debug:
print(f"Merging {newIntervals[-1].timeString()} and {iir.intervals[i].timeString()}")
newIntervals[-1] = newIntervals[-1].merge(iir.intervals[i])
else:
newIntervals.append(iir.intervals[i])
iir.intervals = newIntervals