fxcue 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fxcue/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """fxcue: turn a video into a timestamped, explained effects plan."""
2
+
3
+ from .media import MediaError
4
+ from .models import AUDIO_EFFECTS, EFFECTS, SCHEMA_VERSION, VISUAL_EFFECTS, Cue, Event, Plan
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ from .core import plan, register_detector, unregister_detector # noqa: E402
9
+ from .detectors import Detector, Media # noqa: E402
10
+ from .rules import Rule # noqa: E402
11
+ from .styles import STYLES, Style # noqa: E402
12
+
13
+ __all__ = [
14
+ "AUDIO_EFFECTS",
15
+ "EFFECTS",
16
+ "SCHEMA_VERSION",
17
+ "VISUAL_EFFECTS",
18
+ "STYLES",
19
+ "Cue",
20
+ "Detector",
21
+ "Event",
22
+ "Media",
23
+ "MediaError",
24
+ "Plan",
25
+ "Rule",
26
+ "Style",
27
+ "__version__",
28
+ "plan",
29
+ "register_detector",
30
+ "unregister_detector",
31
+ ]
fxcue/cli.py ADDED
@@ -0,0 +1,47 @@
1
+ """Command line: ``fxcue VIDEO [-o plan.json] [--style energetic]``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import __version__
9
+ from .core import plan as make_plan
10
+ from .media import MediaError
11
+ from .styles import STYLES
12
+
13
+
14
+ def _clock(t: float) -> str:
15
+ minutes, seconds = divmod(t, 60)
16
+ return f"{int(minutes)}:{seconds:04.1f}"
17
+
18
+
19
+ def main(argv: list[str] | None = None) -> int:
20
+ parser = argparse.ArgumentParser(
21
+ prog="fxcue", description="Suggest where effects should go in a video."
22
+ )
23
+ parser.add_argument("video", help="video file to analyse")
24
+ parser.add_argument("-o", "--output", help="write the plan as JSON to this file")
25
+ parser.add_argument("--style", default="energetic", choices=list(STYLES))
26
+ parser.add_argument("--version", action="version", version=f"fxcue {__version__}")
27
+ args = parser.parse_args(argv)
28
+
29
+ try:
30
+ result = make_plan(args.video, style=args.style)
31
+ except (FileNotFoundError, MediaError) as exc:
32
+ print(f"fxcue: {exc}", file=sys.stderr)
33
+ return 1
34
+
35
+ if args.output:
36
+ result.save(args.output)
37
+ print(f"Wrote {len(result.cues)} cues to {args.output}")
38
+ else:
39
+ if not result.cues:
40
+ print("No effects suggested for this video.")
41
+ for c in result.cues:
42
+ print(f"{_clock(c.time):>8} {c.effect:<11} {c.strength:.1f} {c.reason}")
43
+ return 0
44
+
45
+
46
+ if __name__ == "__main__": # pragma: no cover
47
+ sys.exit(main())
fxcue/core.py ADDED
@@ -0,0 +1,63 @@
1
+ """The main entry point: video in, effects plan out."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from os import PathLike
6
+ from pathlib import Path
7
+
8
+ from .detectors import BeatDetector, Detector, LoudnessDetector, Media, SceneDetector
9
+ from .media import load_audio, probe_duration
10
+ from .models import Cue, Plan
11
+ from .rules import Rule, space_cues
12
+ from .styles import Style, get_style
13
+
14
+ _registered: list[Detector] = []
15
+
16
+
17
+ def default_detectors() -> list[Detector]:
18
+ """The built-in detectors plus any added with :func:`register_detector`."""
19
+ return [SceneDetector(), LoudnessDetector(), BeatDetector(), *_registered]
20
+
21
+
22
+ def register_detector(detector: Detector) -> None:
23
+ """Add a detector that every later :func:`plan` call uses by default."""
24
+ if not isinstance(detector, Detector):
25
+ raise TypeError("A detector needs `name`, `needs` ('audio' or 'video') and `detect(media)`.")
26
+ unregister_detector(detector.name)
27
+ _registered.append(detector)
28
+
29
+
30
+ def unregister_detector(name: str) -> None:
31
+ """Remove a detector added with :func:`register_detector` (no error if absent)."""
32
+ _registered[:] = [d for d in _registered if d.name != name]
33
+
34
+
35
+ def plan(
36
+ path: str | PathLike,
37
+ style: str | Style = "energetic",
38
+ detectors: list[Detector] | None = None,
39
+ rules: list[Rule] | None = None,
40
+ ) -> Plan:
41
+ """Analyse a video and return an effects plan.
42
+
43
+ Args:
44
+ path: video file to analyse.
45
+ style: ``"calm"``, ``"energetic"`` (default), ``"vlog"`` or a custom :class:`Style`.
46
+ detectors: replaces the default detectors when given.
47
+ rules: replaces the style's rules (the style's spacing limits still apply).
48
+ """
49
+ path = str(path)
50
+ if not Path(path).is_file():
51
+ raise FileNotFoundError(f"Video file not found: {path}")
52
+ chosen = get_style(style)
53
+ dets = list(detectors) if detectors is not None else default_detectors()
54
+
55
+ duration = probe_duration(path)
56
+ audio = load_audio(path) if any(d.needs == "audio" for d in dets) else None
57
+ media = Media(path, audio, duration)
58
+
59
+ events = [e for d in dets for e in d.detect(media) if 0.0 <= e.time <= duration]
60
+ active_rules = rules if rules is not None else chosen.rules
61
+ cues: list[Cue] = [c for e in events for r in active_rules for c in r.apply(e)]
62
+ cues = space_cues(cues, chosen.min_gap, chosen.max_per_minute, duration)
63
+ return Plan(duration, chosen.name, cues)
@@ -0,0 +1,33 @@
1
+ """Detectors find moments in a video (scene changes, loud peaks, beats) and emit Events."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal, Protocol, runtime_checkable
7
+
8
+ import numpy as np
9
+
10
+ from ..models import Event
11
+
12
+
13
+ @dataclass
14
+ class Media:
15
+ """What detectors receive: the file path, decoded mono audio (or None) and duration."""
16
+
17
+ path: str
18
+ audio: tuple[np.ndarray, int] | None
19
+ duration: float
20
+
21
+
22
+ @runtime_checkable
23
+ class Detector(Protocol):
24
+ name: str
25
+ needs: Literal["audio", "video"]
26
+
27
+ def detect(self, media: Media) -> list[Event]: ...
28
+
29
+
30
+ from .audio import BeatDetector, LoudnessDetector # noqa: E402
31
+ from .video import SceneDetector # noqa: E402
32
+
33
+ __all__ = ["BeatDetector", "Detector", "LoudnessDetector", "Media", "SceneDetector"]
@@ -0,0 +1,114 @@
1
+ """Audio detectors: sudden loud moments and music beats (librosa)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from ..models import Event
8
+
9
+ HOP = 512
10
+ SILENCE_RMS = 1e-4 # below this the whole clip is treated as silent
11
+
12
+
13
+ def _is_silent(y: np.ndarray) -> bool:
14
+ return y.size == 0 or float(np.sqrt(np.mean(y.astype(np.float64) ** 2))) < SILENCE_RMS
15
+
16
+
17
+ class LoudnessDetector:
18
+ """Finds moments much louder than the clip's own typical level.
19
+
20
+ A frame counts as loud when its RMS level is at least ``threshold_db`` above the
21
+ clip's typical level: the median of its *active* frames (within ``active_range_db`` of
22
+ the loudest frame), so pauses and room tone don't make ordinary speech look loud. Loud regions closer than ``merge_gap`` seconds are merged, and
23
+ each region is reported once, at its start.
24
+ """
25
+
26
+ name = "loudness"
27
+ needs = "audio"
28
+
29
+ def __init__(self, threshold_db: float = 6.0, merge_gap: float = 0.5,
30
+ active_range_db: float = 30.0):
31
+ self.threshold_db = threshold_db
32
+ self.active_range_db = active_range_db
33
+ self.merge_gap = merge_gap
34
+
35
+ def detect(self, media) -> list[Event]:
36
+ if media.audio is None:
37
+ return []
38
+ y, sr = media.audio
39
+ if _is_silent(y):
40
+ return []
41
+ import librosa
42
+
43
+ rms = librosa.feature.rms(y=y, hop_length=HOP)[0]
44
+ db = librosa.amplitude_to_db(np.maximum(rms, 1e-10), ref=1.0)
45
+ active = db[db >= db.max() - self.active_range_db]
46
+ median = float(np.median(active))
47
+ excess = db - median
48
+ loud = excess >= self.threshold_db
49
+ if not loud.any():
50
+ return []
51
+ times = librosa.frames_to_time(np.arange(len(db)), sr=sr, hop_length=HOP)
52
+
53
+ events: list[Event] = []
54
+ start = peak = None
55
+ last_t = -1e9
56
+ for t, is_loud, ex in zip(times, loud, excess):
57
+ if not is_loud:
58
+ continue
59
+ if start is not None and t - last_t <= self.merge_gap:
60
+ peak = max(peak, ex)
61
+ else:
62
+ if start is not None:
63
+ events.append(self._event(start, peak))
64
+ start, peak = t, ex
65
+ last_t = t
66
+ if start is not None:
67
+ events.append(self._event(start, peak))
68
+ return events
69
+
70
+ def _event(self, t: float, excess_db: float) -> Event:
71
+ # 6 dB over the median -> 0.25, 24 dB or more -> 1.0
72
+ return Event(float(t), "loud_peak", excess_db / 24.0, self.name)
73
+
74
+
75
+ class BeatDetector:
76
+ """Music beats (``kind="beat"``) and strong hits (``kind="onset"``)."""
77
+
78
+ name = "beats"
79
+ needs = "audio"
80
+
81
+ def __init__(self, onset_threshold: float = 0.6, min_seconds: float = 2.0):
82
+ self.onset_threshold = onset_threshold
83
+ self.min_seconds = min_seconds # beat tracking is meaningless on very short clips
84
+
85
+ def detect(self, media) -> list[Event]:
86
+ if media.audio is None:
87
+ return []
88
+ y, sr = media.audio
89
+ if _is_silent(y) or len(y) < self.min_seconds * sr:
90
+ return []
91
+ import librosa
92
+
93
+ env = librosa.onset.onset_strength(y=y, sr=sr, hop_length=HOP)
94
+ top = float(env.max())
95
+ if top <= 0:
96
+ return []
97
+ norm = env / top
98
+
99
+ _, beat_frames = librosa.beat.beat_track(onset_envelope=env, sr=sr, hop_length=HOP)
100
+ events = [
101
+ Event(float(librosa.frames_to_time(f, sr=sr, hop_length=HOP)), "beat",
102
+ float(norm[f]), self.name)
103
+ for f in np.atleast_1d(beat_frames)
104
+ ]
105
+ onset_frames = librosa.onset.onset_detect(
106
+ onset_envelope=env, sr=sr, hop_length=HOP, backtrack=False
107
+ )
108
+ events += [
109
+ Event(float(librosa.frames_to_time(f, sr=sr, hop_length=HOP)), "onset",
110
+ float(norm[f]), self.name)
111
+ for f in onset_frames
112
+ if norm[f] >= self.onset_threshold
113
+ ]
114
+ return sorted(events, key=lambda e: e.time)
@@ -0,0 +1,48 @@
1
+ """Video detectors: scene changes (PySceneDetect)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ..media import MediaError
6
+ from ..models import Event
7
+
8
+
9
+ def _seconds(timecode) -> float:
10
+ # PySceneDetect 0.7 has a ``seconds`` property; 0.6 only has ``get_seconds()``.
11
+ secs = getattr(timecode, "seconds", None)
12
+ return float(secs if secs is not None else timecode.get_seconds())
13
+
14
+
15
+ class SceneDetector:
16
+ """Hard cuts between shots, using PySceneDetect's content detector.
17
+
18
+ ``threshold`` is PySceneDetect's content threshold (lower finds more cuts).
19
+ Each cut is reported at the first frame of the new shot; the start of the video
20
+ is not a cut.
21
+ """
22
+
23
+ name = "scenes"
24
+ needs = "video"
25
+
26
+ def __init__(self, threshold: float = 27.0, min_scene_len: float = 0.5):
27
+ self.threshold = threshold
28
+ self.min_scene_len = min_scene_len
29
+
30
+ def detect(self, media) -> list[Event]:
31
+ from scenedetect import ContentDetector, SceneManager, open_video
32
+
33
+ try:
34
+ video = open_video(media.path)
35
+ except Exception as exc: # PySceneDetect raises several types
36
+ raise MediaError(f"Could not read video frames from {media.path}: {exc}") from exc
37
+ fps = float(video.frame_rate) or 25.0
38
+ manager = SceneManager()
39
+ manager.add_detector(
40
+ ContentDetector(threshold=self.threshold,
41
+ min_scene_len=max(1, int(round(self.min_scene_len * fps))))
42
+ )
43
+ manager.detect_scenes(video, show_progress=False)
44
+ scenes = manager.get_scene_list(start_in_scene=True)
45
+ return [
46
+ Event(_seconds(start), "scene_change", 1.0, self.name)
47
+ for start, _end in scenes[1:]
48
+ ]
fxcue/media.py ADDED
@@ -0,0 +1,99 @@
1
+ """Reading video files through FFmpeg (system install, or the one bundled by imageio-ffmpeg)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+ INSTALL_HINT = (
13
+ "fxcue needs FFmpeg to read video files. Install it (https://ffmpeg.org/download.html, "
14
+ "'brew install ffmpeg', 'sudo apt install ffmpeg', 'winget install ffmpeg') "
15
+ "or run 'pip install imageio-ffmpeg'."
16
+ )
17
+
18
+
19
+ class MediaError(Exception):
20
+ """A video could not be read, or FFmpeg is unavailable."""
21
+
22
+
23
+ def _bundled_ffmpeg() -> str | None:
24
+ try:
25
+ import imageio_ffmpeg
26
+
27
+ return imageio_ffmpeg.get_ffmpeg_exe()
28
+ except Exception:
29
+ return None
30
+
31
+
32
+ def ffmpeg_path() -> str:
33
+ """Path to an FFmpeg executable: the system one first, then imageio-ffmpeg's."""
34
+ path = shutil.which("ffmpeg") or _bundled_ffmpeg()
35
+ if not path:
36
+ raise MediaError("FFmpeg was not found. " + INSTALL_HINT)
37
+ return path
38
+
39
+
40
+ def _check_exists(path: str) -> None:
41
+ if not Path(path).is_file():
42
+ raise FileNotFoundError(f"Video file not found: {path}")
43
+
44
+
45
+ def _probe_text(path: str) -> str:
46
+ """FFmpeg's stream description for the file (it prints this to stderr)."""
47
+ _check_exists(path)
48
+ proc = subprocess.run(
49
+ [ffmpeg_path(), "-hide_banner", "-i", str(path)],
50
+ capture_output=True,
51
+ text=True,
52
+ errors="replace",
53
+ )
54
+ return proc.stderr
55
+
56
+
57
+ def probe_duration(path: str) -> float:
58
+ """Duration of the video in seconds."""
59
+ text = _probe_text(path)
60
+ if "Duration:" not in text:
61
+ raise MediaError(f"Could not read video file: {path}")
62
+ m = re.search(r"Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)", text)
63
+ if m:
64
+ return _hms(*m.groups())
65
+ # Live/streamed files (e.g. browser recordings) have "Duration: N/A": decode to measure.
66
+ proc = subprocess.run(
67
+ [ffmpeg_path(), "-hide_banner", "-i", str(path), "-f", "null", "-"],
68
+ capture_output=True, text=True, errors="replace",
69
+ )
70
+ times = re.findall(r"time=(\d+):(\d+):(\d+(?:\.\d+)?)", proc.stderr)
71
+ if not times:
72
+ raise MediaError(f"Could not work out the length of video file: {path}")
73
+ return _hms(*times[-1])
74
+
75
+
76
+ def _hms(h: str, m: str, s: str) -> float:
77
+ return int(h) * 3600 + int(m) * 60 + float(s)
78
+
79
+
80
+ def has_audio(path: str) -> bool:
81
+ return bool(re.search(r"Stream #\S+.*: Audio:", _probe_text(path)))
82
+
83
+
84
+ def load_audio(path: str, sr: int = 22050) -> tuple[np.ndarray, int] | None:
85
+ """Decode the audio track to mono float32 at ``sr`` Hz. Returns None if there is no audio."""
86
+ text = _probe_text(path)
87
+ if "Duration:" not in text:
88
+ raise MediaError(f"Could not read video file: {path}")
89
+ if not re.search(r"Stream #\S+.*: Audio:", text):
90
+ return None
91
+ proc = subprocess.run(
92
+ [ffmpeg_path(), "-v", "error", "-i", str(path), "-vn", "-ac", "1",
93
+ "-ar", str(sr), "-f", "f32le", "-"],
94
+ capture_output=True,
95
+ )
96
+ if proc.returncode != 0:
97
+ msg = proc.stderr.decode(errors="replace").strip()
98
+ raise MediaError(f"Could not decode audio from {path}: {msg}")
99
+ return np.frombuffer(proc.stdout, dtype=np.float32).copy(), sr
fxcue/models.py ADDED
@@ -0,0 +1,97 @@
1
+ """Core data types: detector events, effect cues and the effects plan."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import asdict, dataclass, field
7
+ from os import PathLike
8
+ from pathlib import Path
9
+
10
+ SCHEMA_VERSION = 1
11
+
12
+ VISUAL_EFFECTS = frozenset({"transition", "zoom_in", "punch_zoom", "shake", "flash"})
13
+ AUDIO_EFFECTS = frozenset({"whoosh_sfx", "impact_sfx"})
14
+ EFFECTS = VISUAL_EFFECTS | AUDIO_EFFECTS
15
+
16
+
17
+ def _clamp(x: float) -> float:
18
+ return max(0.0, min(1.0, float(x)))
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Event:
23
+ """Something a detector found in the video, e.g. a scene change at 2.0 s."""
24
+
25
+ time: float
26
+ kind: str
27
+ strength: float
28
+ source: str
29
+
30
+ def __post_init__(self) -> None:
31
+ object.__setattr__(self, "time", float(self.time))
32
+ object.__setattr__(self, "strength", _clamp(self.strength))
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Cue:
37
+ """One suggested effect: what, when, how strong, and why."""
38
+
39
+ time: float
40
+ effect: str
41
+ strength: float
42
+ reason: str
43
+ source: str
44
+ duration: float = 0.0
45
+
46
+ def __post_init__(self) -> None:
47
+ if self.effect not in EFFECTS:
48
+ raise ValueError(
49
+ f"Unknown effect {self.effect!r}. Valid effects: {', '.join(sorted(EFFECTS))}"
50
+ )
51
+ if not self.reason or not self.source:
52
+ raise ValueError("A cue needs a non-empty reason and source.")
53
+ object.__setattr__(self, "time", round(float(self.time), 3))
54
+ object.__setattr__(self, "strength", round(_clamp(self.strength), 3))
55
+ object.__setattr__(self, "duration", round(float(self.duration), 3))
56
+
57
+ @property
58
+ def is_visual(self) -> bool:
59
+ return self.effect in VISUAL_EFFECTS
60
+
61
+
62
+ @dataclass
63
+ class Plan:
64
+ """An effects plan for one video. Cues are always kept sorted by time."""
65
+
66
+ duration: float
67
+ style: str
68
+ cues: list[Cue] = field(default_factory=list)
69
+
70
+ def __post_init__(self) -> None:
71
+ self.duration = round(float(self.duration), 3)
72
+ self.cues = sorted(self.cues, key=lambda c: (c.time, not c.is_visual, c.effect))
73
+
74
+ def to_dict(self) -> dict:
75
+ return {
76
+ "schema_version": SCHEMA_VERSION,
77
+ "duration": self.duration,
78
+ "style": self.style,
79
+ "cues": [asdict(c) for c in self.cues],
80
+ }
81
+
82
+ def to_json(self, indent: int | None = 2) -> str:
83
+ return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
84
+
85
+ def save(self, path: str | PathLike) -> None:
86
+ Path(path).write_text(self.to_json(), encoding="utf-8")
87
+
88
+ @classmethod
89
+ def from_dict(cls, data: dict) -> "Plan":
90
+ version = data.get("schema_version")
91
+ if version != SCHEMA_VERSION:
92
+ raise ValueError(f"Unsupported fxcue schema_version {version!r}")
93
+ return cls(data["duration"], data["style"], [Cue(**c) for c in data["cues"]])
94
+
95
+ @classmethod
96
+ def load(cls, path: str | PathLike) -> "Plan":
97
+ return cls.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))
fxcue/rules.py ADDED
@@ -0,0 +1,107 @@
1
+ """Rules turn detector Events into effect Cues; the spacing pass keeps plans uncluttered."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ from dataclasses import dataclass, field
7
+
8
+ from .models import EFFECTS, Cue, Event
9
+
10
+ REASONS = {
11
+ "scene_change": "scene change",
12
+ "loud_peak": "loud moment",
13
+ "beat": "music beat",
14
+ "onset": "strong hit",
15
+ }
16
+
17
+ #: Suggested effect lengths in seconds (apps may ignore them).
18
+ DEFAULT_DURATIONS = {
19
+ "transition": 0.5,
20
+ "zoom_in": 0.4,
21
+ "punch_zoom": 0.25,
22
+ "shake": 0.3,
23
+ "flash": 0.1,
24
+ "whoosh_sfx": 0.6,
25
+ "impact_sfx": 0.4,
26
+ }
27
+
28
+ PAIR_WINDOW = 0.1 # seconds: an audio cue this close to a visual cue from the same source belongs to it
29
+
30
+
31
+ @dataclass
32
+ class Rule:
33
+ """When an event of ``kind`` with at least ``min_strength`` occurs, suggest ``effects``.
34
+
35
+ If ``strong_effect`` is set and the event's strength is at least ``strong_at``, the first
36
+ visual effect in ``effects`` is replaced by ``strong_effect``.
37
+ """
38
+
39
+ kind: str
40
+ effects: list[str]
41
+ min_strength: float = 0.0
42
+ strong_effect: str | None = None
43
+ strong_at: float = 0.85
44
+ durations: dict[str, float] = field(default_factory=lambda: dict(DEFAULT_DURATIONS))
45
+
46
+ def __post_init__(self) -> None:
47
+ for name in [*self.effects, *([self.strong_effect] if self.strong_effect else [])]:
48
+ if name not in EFFECTS:
49
+ raise ValueError(f"Unknown effect {name!r} in rule for {self.kind!r}")
50
+
51
+ def apply(self, event: Event) -> list[Cue]:
52
+ if event.kind != self.kind or event.strength < self.min_strength:
53
+ return []
54
+ effects = list(self.effects)
55
+ if self.strong_effect and event.strength >= self.strong_at:
56
+ for i, name in enumerate(effects):
57
+ if name not in ("whoosh_sfx", "impact_sfx"):
58
+ effects[i] = self.strong_effect
59
+ break
60
+ reason = REASONS.get(event.kind, event.kind.replace("_", " "))
61
+ return [
62
+ Cue(event.time, name, event.strength, reason, event.source,
63
+ duration=self.durations.get(name, 0.0))
64
+ for name in effects
65
+ ]
66
+
67
+
68
+ def space_cues(cues: list[Cue], min_gap: float, max_per_minute: int, duration: float) -> list[Cue]:
69
+ """Remove collisions so effects never pile up.
70
+
71
+ 1. Visual cues are accepted strongest-first; a visual cue is dropped if an accepted one is
72
+ within ``min_gap`` seconds (and two visual cues never share a moment).
73
+ 2. In each minute of the video at most ``max_per_minute`` visual cues survive (strongest kept).
74
+ 3. An audio cue paired with a visual cue (same source, within 0.1 s) survives only if that
75
+ visual cue survived; an unpaired audio cue survives unless a visual cue sits on top of it.
76
+ At most one audio cue is kept per 0.1 s.
77
+ """
78
+ visuals = [c for c in cues if c.is_visual]
79
+ audios = [c for c in cues if not c.is_visual]
80
+
81
+ accepted: list[Cue] = []
82
+ for cue in sorted(visuals, key=lambda c: (-c.strength, c.time)):
83
+ if all(abs(cue.time - a.time) >= max(min_gap, 1e-6) for a in accepted):
84
+ accepted.append(cue)
85
+
86
+ by_minute: dict[int, list[Cue]] = defaultdict(list)
87
+ for cue in accepted:
88
+ by_minute[int(cue.time // 60)].append(cue)
89
+ kept_visuals: list[Cue] = []
90
+ for bucket in by_minute.values():
91
+ bucket.sort(key=lambda c: (-c.strength, c.time))
92
+ kept_visuals.extend(bucket[:max_per_minute])
93
+
94
+ def near(a: Cue, b: Cue) -> bool:
95
+ return abs(a.time - b.time) <= PAIR_WINDOW
96
+
97
+ kept_audio: list[Cue] = []
98
+ for cue in sorted(audios, key=lambda c: (-c.strength, c.time)):
99
+ partners = [v for v in visuals if v.source == cue.source and near(v, cue)]
100
+ if partners:
101
+ keep = any(v in kept_visuals for v in partners)
102
+ else:
103
+ keep = not any(near(v, cue) for v in kept_visuals)
104
+ if keep and not any(near(a, cue) for a in kept_audio):
105
+ kept_audio.append(cue)
106
+
107
+ return sorted(kept_visuals + kept_audio, key=lambda c: (c.time, not c.is_visual))
fxcue/styles.py ADDED
@@ -0,0 +1,60 @@
1
+ """Named styles: which rules apply and how dense the effects may be."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from .rules import Rule
8
+
9
+
10
+ @dataclass
11
+ class Style:
12
+ name: str
13
+ rules: list[Rule]
14
+ min_gap: float # seconds between visual effects
15
+ max_per_minute: int # visual effects per minute of video
16
+
17
+
18
+ STYLES: dict[str, Style] = {
19
+ "calm": Style(
20
+ "calm",
21
+ [
22
+ Rule("scene_change", ["transition"]),
23
+ Rule("loud_peak", ["zoom_in"], min_strength=0.7),
24
+ ],
25
+ min_gap=4.0,
26
+ max_per_minute=6,
27
+ ),
28
+ "energetic": Style(
29
+ "energetic",
30
+ [
31
+ Rule("scene_change", ["transition", "whoosh_sfx"]),
32
+ Rule("loud_peak", ["zoom_in"], strong_effect="punch_zoom"),
33
+ Rule("loud_peak", ["impact_sfx"], min_strength=0.85),
34
+ Rule("onset", ["shake"], min_strength=0.6),
35
+ Rule("beat", ["flash"], min_strength=0.8),
36
+ ],
37
+ min_gap=1.5,
38
+ max_per_minute=20,
39
+ ),
40
+ "vlog": Style(
41
+ "vlog",
42
+ [
43
+ Rule("scene_change", ["transition", "whoosh_sfx"]),
44
+ Rule("loud_peak", ["zoom_in"]),
45
+ ],
46
+ min_gap=2.5,
47
+ max_per_minute=12,
48
+ ),
49
+ }
50
+
51
+
52
+ def get_style(style: str | Style) -> Style:
53
+ if isinstance(style, Style):
54
+ return style
55
+ try:
56
+ return STYLES[style]
57
+ except KeyError:
58
+ raise ValueError(
59
+ f"Unknown style {style!r}. Choose one of: {', '.join(STYLES)}"
60
+ ) from None
@@ -0,0 +1,171 @@
1
+ Metadata-Version: 2.5
2
+ Name: fxcue
3
+ Version: 0.1.0
4
+ Summary: Turn a video into a timestamped, explained effects plan (zooms, transitions, shakes, whooshes) for beginner-friendly editing apps.
5
+ Project-URL: Homepage, https://github.com/roy13dec-droid/fxcue
6
+ Project-URL: Issues, https://github.com/roy13dec-droid/fxcue/issues
7
+ Author: Anal Kanti Roy
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: beats,editing,effects,ffmpeg,scene-detection,video
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Multimedia :: Video
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: imageio-ffmpeg>=0.5
17
+ Requires-Dist: librosa>=0.10
18
+ Requires-Dist: numpy>=1.24
19
+ Requires-Dist: opencv-python-headless>=4.8
20
+ Requires-Dist: scenedetect>=0.6.4
21
+ Provides-Extra: dev
22
+ Requires-Dist: build; extra == 'dev'
23
+ Requires-Dist: pytest>=8; extra == 'dev'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # fxcue
27
+
28
+ **Tell your users where the effects go.**
29
+
30
+ `fxcue` analyses a video and returns an **effects plan**: a list of timestamped
31
+ effect cues (zooms, transitions, shakes, whooshes…), each with the reason it was
32
+ placed there. It is built for developers making beginner-friendly editing apps,
33
+ auto-clippers and video tools. Your app decides how to show or apply each cue.
34
+
35
+ ```
36
+ 0:02.0 transition 1.0 scene change
37
+ 0:02.0 whoosh_sfx 1.0 scene change
38
+ 0:12.4 zoom_in 0.6 loud moment
39
+ 0:45.2 shake 0.7 strong hit
40
+ ```
41
+
42
+ - Fast, offline and lightweight. No GPU and no AI model downloads.
43
+ - Explainable: every cue says *why* it was placed.
44
+ - Never cluttered: built-in spacing keeps effects from piling up.
45
+ - Pluggable: add your own detectors and rules.
46
+ - Plain JSON output that any language can read.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pip install fxcue
52
+ ```
53
+
54
+ fxcue reads video through [FFmpeg](https://ffmpeg.org). If FFmpeg isn't on your
55
+ system, the bundled `imageio-ffmpeg` binary is used automatically.
56
+
57
+ ## Quickstart
58
+
59
+ ```python
60
+ import fxcue
61
+
62
+ plan = fxcue.plan("video.mp4", style="energetic")
63
+ for cue in plan.cues:
64
+ print(cue.time, cue.effect, cue.reason)
65
+ plan.save("plan.json")
66
+ ```
67
+
68
+ Or from the command line:
69
+
70
+ ```bash
71
+ fxcue video.mp4 # print the plan
72
+ fxcue video.mp4 -o plan.json # save it as JSON
73
+ fxcue video.mp4 --style calm
74
+ ```
75
+
76
+ ## Effects
77
+
78
+ Effect names are generic, so your app can map each one to its own assets.
79
+
80
+ | Effect | Kind | Placed on (energetic style) |
81
+ |---------------|--------|--------------------------------------|
82
+ | `transition` | visual | scene changes |
83
+ | `whoosh_sfx` | audio | scene changes |
84
+ | `zoom_in` | visual | loud moments |
85
+ | `punch_zoom` | visual | very loud moments (replaces zoom_in) |
86
+ | `impact_sfx` | audio | very loud moments |
87
+ | `shake` | visual | strong hits |
88
+ | `flash` | visual | strong music beats |
89
+
90
+ ## Styles
91
+
92
+ | Style | Min gap between visual effects | Max visual effects per minute | Uses |
93
+ |-------------|----|----|-----------------------------------------------|
94
+ | `calm` | 4 s | 6 | transitions, zooms on very loud moments |
95
+ | `energetic` | 1.5 s | 20 | everything above (default) |
96
+ | `vlog` | 2.5 s | 12 | transitions + whooshes, zooms |
97
+
98
+ There is never more than one visual effect at the same moment. A sound effect
99
+ is dropped when the visual effect it belongs to is dropped.
100
+
101
+ ## JSON output
102
+
103
+ ```json
104
+ {
105
+ "schema_version": 1,
106
+ "duration": 6.0,
107
+ "style": "energetic",
108
+ "cues": [
109
+ {"time": 2.0, "effect": "transition", "strength": 1.0,
110
+ "reason": "scene change", "source": "scenes", "duration": 0.5}
111
+ ]
112
+ }
113
+ ```
114
+
115
+ `duration` is a suggested length in seconds; apps may ignore it. Load a saved
116
+ plan with `fxcue.Plan.load("plan.json")`.
117
+
118
+ ## Customise
119
+
120
+ **Your own rules** replace the style's rules but keep its spacing:
121
+
122
+ ```python
123
+ from fxcue import Rule
124
+
125
+ plan = fxcue.plan("video.mp4", rules=[
126
+ Rule("scene_change", ["flash", "whoosh_sfx"]),
127
+ Rule("loud_peak", ["shake"], min_strength=0.5),
128
+ ])
129
+ ```
130
+
131
+ Event kinds from the built-in detectors are `scene_change`, `loud_peak`, `beat` and `onset`.
132
+
133
+ **Your own detector**, for example one using an AI model:
134
+
135
+ ```python
136
+ from fxcue import Event
137
+
138
+ class LaughDetector:
139
+ name = "laughs"
140
+ needs = "audio" # or "video"
141
+
142
+ def detect(self, media): # media.path, media.audio (samples, rate) or None, media.duration
143
+ return [Event(time=12.3, kind="loud_peak", strength=0.9, source=self.name)]
144
+
145
+ fxcue.register_detector(LaughDetector()) # used by every plan() call from now on
146
+ ```
147
+
148
+ ## How it works
149
+
150
+ ```
151
+ video ─► detectors ─► events ─► style rules ─► spacing pass ─► plan
152
+ ```
153
+
154
+ - **scenes**: hard cuts, found with [PySceneDetect](https://www.scenedetect.com/)
155
+ - **loudness**: moments much louder than the clip's own typical level ([librosa](https://librosa.org/))
156
+ - **beats**: music beats and strong hits (librosa)
157
+
158
+ ## Roadmap
159
+
160
+ - Optional preview render, so you can see a plan applied
161
+ - Optional AI detectors (speech emphasis, laughter, faces)
162
+ - More effects and styles, contributed by the community
163
+
164
+ ## Contributing
165
+
166
+ Contributions are welcome, especially new detectors, styles and effect ideas.
167
+ See [CONTRIBUTING.md](CONTRIBUTING.md).
168
+
169
+ ## Licence
170
+
171
+ MIT © Anal Kanti Roy. See [LICENSE](LICENSE).
@@ -0,0 +1,15 @@
1
+ fxcue/__init__.py,sha256=DdXY_Tn22jcrl2SEqjZujDg6XgEUcmILa-NhTE0GFh0,734
2
+ fxcue/cli.py,sha256=J1xAK_Zqm01BX8T8RYlKqU8McGGRhBoh7qzzK6Liow0,1490
3
+ fxcue/core.py,sha256=hJx131IRDVVAuSosuhBHrswW_leAoPKFfDYEkv7m8R8,2415
4
+ fxcue/media.py,sha256=5G9jum9TVYx5nuGFnPGpwvY4-WXQ_qq6JU_7TCL3zNc,3223
5
+ fxcue/models.py,sha256=9226LoVoOyEphtno_mIP0zUECmA2AEGsnVWP9M8Dx8M,3026
6
+ fxcue/rules.py,sha256=IKonhv_AKUiDQMAfX6XG-ahAgGLPV6QYaRMutnk0NxM,4099
7
+ fxcue/styles.py,sha256=Tc7JT-2tWbEbS5bbBfS3C6YkWDIf0-l3sdXSUF1qyxQ,1533
8
+ fxcue/detectors/__init__.py,sha256=03OULuxuzFOeVpht4foh2Dox8V61SywXR0wWwZ1SttE,814
9
+ fxcue/detectors/audio.py,sha256=E9zX0ZRiltqJYRbrjwqMJEPw3Qq56BgfykRy64Y4SRQ,4015
10
+ fxcue/detectors/video.py,sha256=foHSMLL-AD8SiTSeB8fbGxsQ9TbD7GuYSRdyRSWJ9G0,1726
11
+ fxcue-0.1.0.dist-info/METADATA,sha256=_NrGzQ4xcijJsVPC7p5W7llBCm7aGY3Vc60Lm6pPgtw,5421
12
+ fxcue-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ fxcue-0.1.0.dist-info/entry_points.txt,sha256=hBG3EZHXrOJ2l_X0zcgXaJ40lON6gTLMrSVU2nq30AA,41
14
+ fxcue-0.1.0.dist-info/licenses/LICENSE,sha256=zjNRPUR6dbop0ofCK6iVYNhB7m6Z3i87B9CDfHJ4uiw,1071
15
+ fxcue-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fxcue = fxcue.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anal Kanti Roy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.