videolyzer 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.
@@ -0,0 +1,183 @@
1
+ Metadata-Version: 2.4
2
+ Name: videolyzer
3
+ Version: 0.1.0
4
+ Summary: give agents the ability to understand and deep analyze videos
5
+ Author: Neguiolidas
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Neguiolidas/videolyzer
8
+ Project-URL: Repository, https://github.com/Neguiolidas/videolyzer
9
+ Project-URL: Issues, https://github.com/Neguiolidas/videolyzer/issues
10
+ Keywords: video,video-analysis,ai-agents,multimodal,gemini
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Multimedia :: Video
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: opencv-python>=4.8
23
+ Requires-Dist: numpy>=1.24
24
+ Dynamic: license-file
25
+
26
+ # Videolyzer
27
+
28
+ **Give agents the ability to understand and deep analyze videos.**
29
+
30
+ A single CLI that turns a video (YouTube URL or local file) into a structured Markdown report: detected scenes with timestamps, transcript aligned per scene, key moments, tone/emotion, and temporal verification. Built for agents that need to *watch* video, not just transcribe it.
31
+
32
+ ## Quick start
33
+
34
+ ```bash
35
+ pip install -r requirements.txt # opencv + numpy (only needed for the subtle-motion pass)
36
+
37
+ export VIDEOLYZER_API_KEY="your-key"
38
+
39
+ # URL mode (gemini only, no download)
40
+ python videolyzer.py "https://www.youtube.com/watch?v=..." --out report.md
41
+
42
+ # Local file mode
43
+ python videolyzer.py ./my-video.mp4 --out report.md
44
+
45
+ # Any OpenAI-compatible provider (Groq, Together, OpenAI, ...)
46
+ python videolyzer.py ./my-video.mp4 --provider openai --model gpt-4o \
47
+ --base-url https://api.groq.com/openai/v1 --out report.md
48
+
49
+ # Auxiliary model (any OpenAI-compatible vision endpoint)
50
+ export VIDEOLYZER_AUX_MODEL="your-vision-model"
51
+ export VIDEOLYZER_AUX_BASE_URL="https://your-endpoint/v1"
52
+ export VIDEOLYZER_AUX_API_KEY="your-key"
53
+
54
+ # Modo Rapido: fast keyframe analysis on the aux model (no full upload)
55
+ python videolyzer.py ./my-video.mp4 --fast --out report.md
56
+
57
+ # Second opinion: primary analysis + aux model cross-check
58
+ python videolyzer.py ./my-video.mp4 --verify --out report.md
59
+ ```
60
+
61
+ ## Modes: URL vs local file
62
+
63
+ | | URL mode | Local file mode |
64
+ |---|---|---|
65
+ | Providers | `gemini` only | `gemini` and `openai` |
66
+ | Download | None. The URL goes straight to the model (`file_data`) | None for gemini (full upload via Files API); keyframes extracted locally for openai |
67
+ | Temporal understanding | Native: the model samples the timeline itself | Native (gemini) / keyframe-based (openai) |
68
+ | Subtle-motion detection | **Not available** (would require downloading the video) | Available: optical-flow pass flags small-amplitude motion segments and injects them into the prompt as an explicit hint |
69
+ | Cut detection | **Not available** (would require downloading the video) | Available: ffmpeg scene detection finds exact hard-cut timestamps (`--cut-threshold`, default 0.4); they go into the prompt as scene-boundary anchors |
70
+ | Speed | Fastest | Slower (upload + optional motion/cut passes) |
71
+
72
+ ### URL mode (gemini only)
73
+
74
+ No download, no frame extraction. The video URL is passed to the model and it does its own temporal sampling. Best for quick overviews of online videos. Limitation: subtle motion (small-amplitude movement) can be missed, because the pre-analysis optical-flow pass cannot run without the pixels.
75
+
76
+ ### Local file mode
77
+
78
+ The file is validated with `ffprobe` (codec, duration, integrity — no frames extracted), then two deterministic passes run locally before the model sees anything:
79
+
80
+ - **Cut detection** (ffmpeg scene detection, `--cut-threshold` default 0.4, skip with `--no-cuts`): finds exact hard-cut timestamps. They go into the prompt as scene-boundary anchors ("a new scene starts at each cut timestamp — do NOT merge scenes across a cut"), so the model aligns on measured cuts instead of guessing approximate boundaries.
81
+ - **Subtle-motion pass** (Farneback optical flow, 2 fps sampling, 3×3 grid): measures motion magnitude per segment and flags anything above background noise (median + 4·1.4826·MAD, robust to outliers). The flagged timestamps, region and dominant axis go into the prompt as an explicit hint ("do NOT say these segments are static").
82
+
83
+ Then:
84
+
85
+ - **gemini:** the whole file is uploaded through the Files API; the model samples the timeline itself.
86
+ - **openai (any OpenAI-compatible API):** `N` evenly spaced keyframes (`--keyframes`, default 8) are extracted with ffmpeg and sent as images through `/v1/chat/completions` (vision). URL input is not supported with this provider.
87
+
88
+ ## Auxiliary model & Modo Rapido
89
+
90
+ The auxiliary model is a second, independent multimodal model — any OpenAI-compatible vision endpoint (no provider hardcoded). It plays three roles:
91
+
92
+ | Role | How |
93
+ |---|---|
94
+ | **Second opinion** (`--verify`) | After the primary analysis, the aux model reviews the report against keyframes: agrees/disagrees per scene, flags temporal-order mistakes. Appended as a "Second opinion" section. |
95
+ | **Temporal verifier** | Built into every aux pass: the prompt forces motion verbs and event-order checks across keyframes. |
96
+ | **Fallback** | If the primary analysis fails and an aux model is configured, Videolyzer automatically retries with the aux model on keyframes. |
97
+
98
+ **Modo Rapido** (`--fast`) skips the full video upload entirely and runs the whole analysis on the auxiliary model with evenly spaced keyframes (+ the optical-flow subtle-motion hints). Much faster and cheaper than the native path — best when only "what appears" matters and fine motion detail is not critical. Requires the aux model to be configured.
99
+
100
+ Configuration (flags take precedence over env vars):
101
+
102
+ | Flag | Env var | Default |
103
+ |---|---|---|
104
+ | `--aux-model` | `VIDEOLYZER_AUX_MODEL` | — (required to enable) |
105
+ | `--aux-base-url` | `VIDEOLYZER_AUX_BASE_URL` | `https://api.openai.com/v1` |
106
+ | `--aux-api-key` | `VIDEOLYZER_AUX_API_KEY` | — (required) |
107
+
108
+ ```bash
109
+ # One-off
110
+ python videolyzer.py video.mp4 --fast \
111
+ --aux-model my-vision-model \
112
+ --aux-base-url https://my-endpoint/v1 \
113
+ --aux-api-key sk-...
114
+
115
+ # Or via env vars (then just --fast / --verify)
116
+ export VIDEOLYZER_AUX_MODEL="my-vision-model"
117
+ export VIDEOLYZER_AUX_BASE_URL="https://my-endpoint/v1"
118
+ export VIDEOLYZER_AUX_API_KEY="sk-..."
119
+ ```
120
+
121
+ ## CLI reference
122
+
123
+ ```
124
+ videolyzer.py <source> [--provider gemini|openai] [--model NAME]
125
+ [--base-url URL] [--api-key KEY]
126
+ [--aux-model NAME] [--aux-base-url URL] [--aux-api-key KEY]
127
+ [--fast] [--verify]
128
+ [--out report.md] [--prompt "..."] [--no-motion] [--no-cuts]
129
+ [--cut-threshold 0.4] [--keyframes 8]
130
+ ```
131
+
132
+ | Flag | Default | Description |
133
+ |---|---|---|
134
+ | `source` | — | YouTube URL (gemini only) or local file path |
135
+ | `--provider` | `gemini` | `gemini` (Google AI Studio) or `openai` (any OpenAI-compatible API) |
136
+ | `--model` | `gemini-3.1-flash-lite` | Model name. For `openai`, pass a vision-capable model of your provider |
137
+ | `--base-url` | — | Custom API base URL (openai provider). Default `https://api.openai.com/v1` |
138
+ | `--api-key` | — | API key. Or set `VIDEOLYZER_API_KEY` (`GEMINI_API_KEY` / `OPENAI_API_KEY` also work) |
139
+ | `--aux-model` | — | Aux multimodal model name (any OpenAI-compatible vision endpoint; or `VIDEOLYZER_AUX_MODEL`) |
140
+ | `--aux-base-url` | `https://api.openai.com/v1` | Aux model endpoint (or `VIDEOLYZER_AUX_BASE_URL`) |
141
+ | `--aux-api-key` | — | Aux model key (or `VIDEOLYZER_AUX_API_KEY`) |
142
+ | `--fast` | off | **Modo Rapido**: full analysis on the aux model via keyframes (no upload). Requires `--aux-model` |
143
+ | `--verify` | off | Second opinion: aux model cross-checks the primary report. Requires `--aux-model` |
144
+ | `--out` | stdout | Output `.md` file |
145
+ | `--prompt` | built-in | Custom analysis prompt (overrides the default) |
146
+ | `--no-motion` | off | Skip the optical-flow subtle-motion pass |
147
+ | `--cut-threshold` | 0.4 | Scene-detection threshold for deterministic cut detection. Lower = more sensitive |
148
+ | `--no-cuts` | off | Skip deterministic cut detection |
149
+ | `--keyframes` | 8 | Keyframes for the openai provider / aux model |
150
+
151
+ ## Requirements
152
+
153
+ - Python 3.10+
154
+ - `ffmpeg` / `ffprobe` on PATH (system package)
155
+ - `pip install -r requirements.txt` → `opencv-python`, `numpy` (only needed for the subtle-motion pass; the tool degrades gracefully without them)
156
+
157
+ ## Report format
158
+
159
+ ```markdown
160
+ # Video Analysis
161
+ ## Summary
162
+ ## Scenes (| # | Start | End | Visual description | Audio/speech |)
163
+ ## Aligned transcript
164
+ ## Key moments
165
+ ## Tone and emotion
166
+ ## Temporal verification (motion described with action verbs, cause-effect order checked)
167
+ ```
168
+
169
+ ## How it differs from frame extraction
170
+
171
+ Classic pipelines extract N frames and ask a vision model about each still image. That loses motion: a bouncing ball becomes "ball at left" / "ball at right", and anything between sampled frames is invisible (or hallucinated).
172
+
173
+ Videolyzer instead hands the *video* to the model:
174
+
175
+ 1. **Native temporal sampling** — the model, not our code, decides what to look at along the timeline.
176
+ 2. **Temporal verification** — the prompt forces motion verbs per scene and cause-effect order checks, plus an explicit "motion undetermined" escape hatch instead of invention.
177
+ 3. **Hybrid subtle-motion pass** (local files) — classical CV finds what the model's sampling might skip, and the model is told exactly where to look.
178
+
179
+ See `docs/` for the comparative tests that motivated this design.
180
+
181
+ ## License
182
+
183
+ Apache 2.0 — see [LICENSE](LICENSE).
@@ -0,0 +1,7 @@
1
+ videolyzer.py,sha256=hm9q_gNbsVbwOB0OUIYHB6yFy_RWIxwxIg5Y_eHZdU8,35745
2
+ videolyzer-0.1.0.dist-info/licenses/LICENSE,sha256=amtaDRiZW7jevKbEYBmrE0hMY-7oEErc7_UrzJOTsuQ,11417
3
+ videolyzer-0.1.0.dist-info/METADATA,sha256=8AGRDyuwFXYxE_UibKbJeeycJnD7R85SvxMRjdfH3og,9726
4
+ videolyzer-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
5
+ videolyzer-0.1.0.dist-info/entry_points.txt,sha256=PeRNeq55MDiFMS5EPMkJJJUZM98oDk0TkuQjDj5Fwyk,47
6
+ videolyzer-0.1.0.dist-info/top_level.txt,sha256=OfZDZDdKeomZMyrwAAVsArktnAajZArUJRQEXZ4pRHY,11
7
+ videolyzer-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ videolyzer = videolyzer:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
@@ -0,0 +1 @@
1
+ videolyzer
videolyzer.py ADDED
@@ -0,0 +1,842 @@
1
+ #!/usr/bin/env python3
2
+ """Videolyzer - give agents the ability to understand and deep analyze videos.
3
+
4
+ Usage:
5
+ videolyzer.py <youtube-url-or-file> [--provider gemini] [--out report.md]
6
+ [--model gemini-3.1-flash-lite] [--base-url URL] [--api-key KEY]
7
+ [--prompt "..."] [--no-motion] [--no-cuts] [--cut-threshold 0.4]
8
+ [--keyframes 8]
9
+ [--aux-model NAME] [--aux-base-url URL] [--aux-api-key KEY] [--fast]
10
+
11
+ Providers:
12
+ gemini - Google AI Studio. Native video understanding, YouTube URLs
13
+ supported without download. Local files go through the Files
14
+ API (full upload, model samples the timeline itself).
15
+ (default, key via VIDEOLYZER_API_KEY, GEMINI_API_KEY or --api-key)
16
+ openai - Any OpenAI-compatible API (OpenAI, Groq, Together, etc.).
17
+ Local files only: keyframes are extracted with ffmpeg and sent
18
+ as images through /v1/chat/completions (vision).
19
+ URL input is not supported with this provider.
20
+ (key via VIDEOLYZER_API_KEY, OPENAI_API_KEY or --api-key,
21
+ endpoint via --base-url, default https://api.openai.com/v1)
22
+
23
+ Auxiliary model (--aux-model):
24
+ Any OpenAI-compatible vision endpoint used as a frame-by-frame analysis
25
+ layer. Roles:
26
+ - Second opinion: cross-check the scenes the primary model reported.
27
+ - Temporal verifier: confirm event order across keyframes.
28
+ - Fallback: automatically used (keyframes) when the primary analysis
29
+ fails, if configured.
30
+ Configured via --aux-model NAME, --aux-base-url URL, --aux-api-key KEY,
31
+ or env vars VIDEOLYZER_AUX_MODEL, VIDEOLYZER_AUX_BASE_URL,
32
+ VIDEOLYZER_AUX_API_KEY. No provider is hardcoded; any endpoint speaking
33
+ the OpenAI chat-completions dialect with vision support works.
34
+
35
+ Modo Rapido (--fast):
36
+ Skips the full video upload and runs the whole analysis on the
37
+ auxiliary model with evenly spaced keyframes (+ the optical-flow
38
+ subtle-motion hints). Much faster and cheaper than the native path;
39
+ best when only "what appears" matters and fine motion detail is not
40
+ critical. Requires the auxiliary model to be configured.
41
+
42
+ Modes:
43
+ URL (http, gemini only): the URL is sent straight to the model
44
+ (file_data), no download. Fast. No subtle-motion detection and
45
+ no cut detection (both would require downloading the video).
46
+ Local file: validated with ffprobe, then analyzed natively.
47
+ With --provider gemini the whole file is uploaded and the model
48
+ does its own temporal sampling (no frame extraction by us).
49
+ Before upload, two deterministic passes run locally:
50
+ - cut detection (ffmpeg scene detection, --cut-threshold):
51
+ exact hard-cut timestamps go into the prompt as anchors so
52
+ the model aligns scene boundaries on them instead of guessing;
53
+ - subtle-motion pass (Farneback optical flow): flags segments
54
+ with small-amplitude motion above background noise; the
55
+ timestamps go into the prompt as an explicit hint
56
+ (hybrid two-pass).
57
+ With --provider openai, evenly spaced keyframes are extracted
58
+ and sent as images; both local passes still run and feed the
59
+ same hint sections into the prompt.
60
+
61
+ Output: Markdown report with detected scenes (timestamps), transcript
62
+ aligned per scene, key moments, tone/emotion, and temporal verification.
63
+
64
+ Zero pip dependencies for the core path (stdlib + ffmpeg/ffprobe).
65
+ opencv-python + numpy only needed for the subtle-motion pass.
66
+ """
67
+ from __future__ import annotations
68
+
69
+ import argparse
70
+ import base64
71
+ import json
72
+ import mimetypes
73
+ import os
74
+ import re
75
+ import subprocess
76
+ import sys
77
+ import tempfile
78
+ import time
79
+ import urllib.error
80
+ import urllib.request
81
+
82
+ DEFAULT_PROVIDER = "gemini"
83
+ DEFAULT_MODEL = "gemini-3.1-flash-lite"
84
+ GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
85
+ OPENAI_API_BASE = "https://api.openai.com/v1"
86
+ MAX_RETRIES = 3
87
+ RETRY_DELAYS = [2, 5, 10]
88
+ KEYFRAME_COUNT = 8
89
+ # Auxiliary model (any OpenAI-compatible vision endpoint). Nothing hardcoded.
90
+ AUX_ENV_MODEL = "VIDEOLYZER_AUX_MODEL"
91
+ AUX_ENV_BASE_URL = "VIDEOLYZER_AUX_BASE_URL"
92
+ AUX_ENV_API_KEY = "VIDEOLYZER_AUX_API_KEY"
93
+
94
+ ANALYZE_PROMPT = """Analyze this video in depth and return a Markdown report with the following sections:
95
+
96
+ # Video Analysis
97
+
98
+ ## Summary
99
+ 2-3 sentences about the overall content of the video.
100
+
101
+ ## Scenes
102
+ Table with each detected scene:
103
+ | # | Start | End | Visual description | Audio/speech |
104
+ Use mm:ss timestamps. Detect scene changes by visual change (place, angle, action).
105
+
106
+ ## Aligned transcript
107
+ Faithful transcript of speech, organized by scene/timestamp. If there is no speech, say "no dialogue".
108
+
109
+ ## Key moments
110
+ List of the 3-5 most important moments with timestamp and why.
111
+
112
+ ## Tone and emotion
113
+ Overall tone, dominant emotions, pacing (slow/fast), and how that serves the video's purpose.
114
+
115
+ ## Temporal verification
116
+ For each scene with visible motion, describe the MOTION (action verb: crosses, spins, falls, approaches, etc.), not just the static state. If there is a cause-effect sequence (someone picks up an object AND THEN uses it), confirm the temporal order of events. If some motion cannot be determined, say explicitly "motion undetermined" instead of inventing it.
117
+
118
+ Return ONLY the Markdown, no extra commentary."""
119
+
120
+ MOTION_HINT_SECTION = """
121
+ ## Subtle motion detected (optical flow, automatic pass)
122
+ The segments below contain small-amplitude motion CONFIRMED by optical-flow
123
+ measurement. Describe EXACTLY what moves in each segment: which object,
124
+ direction, approximate amplitude and rhythm. Do NOT say these segments are
125
+ static. If the motion is ambiguous, describe what the measurement indicates
126
+ without inventing a cause.
127
+ {items}
128
+ """
129
+
130
+ CUT_HINT_SECTION = """
131
+ ## Detected cuts (deterministic, ffmpeg scene detection)
132
+ The hard cuts below were detected by frame-difference analysis and are
133
+ EXACT, not approximate. Anchor your scene boundaries on these timestamps:
134
+ a new scene starts at each cut timestamp. Do NOT merge scenes across a cut,
135
+ and do NOT invent scene boundaries between cuts unless there is a clear
136
+ visual change (camera angle, location) without a hard cut.
137
+ {items}
138
+ """
139
+
140
+
141
+ def is_url(s: str) -> bool:
142
+ return s.startswith("http://") or s.startswith("https://")
143
+
144
+
145
+ def get_api_key(args) -> str:
146
+ for src in (args.api_key, os.environ.get("VIDEOLYZER_API_KEY"),
147
+ os.environ.get("GEMINI_API_KEY"),
148
+ os.environ.get("OPENAI_API_KEY")):
149
+ if src and src.strip():
150
+ return src.strip()
151
+ print(
152
+ "error: no API key. Use --api-key or set VIDEOLYZER_API_KEY "
153
+ "(or GEMINI_API_KEY / OPENAI_API_KEY).",
154
+ file=sys.stderr,
155
+ )
156
+ sys.exit(3)
157
+
158
+
159
+ def get_aux_config(args) -> dict | None:
160
+ """Auxiliary multimodal model config. None when not configured.
161
+
162
+ Accepts any OpenAI-compatible vision endpoint; nothing provider-specific.
163
+ Precedence: flags > VIDEOLYZER_AUX_* env vars.
164
+ """
165
+ model = args.aux_model or os.environ.get(AUX_ENV_MODEL)
166
+ if not model or not model.strip():
167
+ return None
168
+ base_url = (args.aux_base_url or os.environ.get(AUX_ENV_BASE_URL)
169
+ or OPENAI_API_BASE).rstrip("/")
170
+ api_key = args.aux_api_key or os.environ.get(AUX_ENV_API_KEY)
171
+ if not api_key or not api_key.strip():
172
+ print(
173
+ f"error: --aux-model set but no aux API key. Use --aux-api-key "
174
+ f"or set {AUX_ENV_API_KEY}.",
175
+ file=sys.stderr,
176
+ )
177
+ sys.exit(3)
178
+ return {"model": model.strip(), "base_url": base_url,
179
+ "api_key": api_key.strip()}
180
+
181
+
182
+ def fmt_ts(s: float) -> str:
183
+ return f"{int(s // 60):02d}:{int(s % 60):02d}"
184
+
185
+
186
+ def http_json(url: str, headers: dict, data: bytes | None = None,
187
+ timeout: int = 600, method: str = "POST") -> dict | None:
188
+ """Request with retry on 429/5xx. Returns parsed JSON or None."""
189
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
190
+ last_err = None
191
+ for attempt in range(MAX_RETRIES):
192
+ try:
193
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
194
+ return json.load(resp)
195
+ except urllib.error.HTTPError as e:
196
+ if e.code in (429, 500, 502, 503):
197
+ last_err = e
198
+ else:
199
+ body = e.read().decode(errors="replace")[:300]
200
+ print(f"error: API {e.code}: {body}", file=sys.stderr)
201
+ return None
202
+ except Exception as e: # noqa: BLE001
203
+ last_err = e
204
+ if attempt < MAX_RETRIES - 1:
205
+ time.sleep(RETRY_DELAYS[attempt])
206
+ print(f"warn: failed after {MAX_RETRIES} tries: {last_err}", file=sys.stderr)
207
+ return None
208
+
209
+
210
+ # ---------------- subtle-motion detection (provider-agnostic) ----------------
211
+
212
+ def detect_subtle_motion(path: str, sample_fps: float = 2.0) -> list:
213
+ """Pass 1: optical flow (Farneback) flags segments with subtle motion.
214
+
215
+ Samples frame pairs, computes mean flow magnitude per cell (3x3 grid)
216
+ and flags segments where the most active cell beats background noise
217
+ (median + 4*1.4826*MAD, robust to outliers, with absolute floor).
218
+ Returns list of {start, end, region, magnitude, axis}. Fails silent.
219
+ """
220
+ try:
221
+ import cv2
222
+ import numpy as np
223
+ except ImportError:
224
+ print("note: opencv unavailable, skipping subtle-motion detection",
225
+ file=sys.stderr)
226
+ return []
227
+ cap = cv2.VideoCapture(path)
228
+ if not cap.isOpened():
229
+ print("note: could not open video for optical flow", file=sys.stderr)
230
+ return []
231
+ try:
232
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
233
+ step = max(1, int(round(fps / sample_fps)))
234
+ W = 320
235
+ samples = [] # (t_s, max_cell_mag, (row, col), mean|vx|, mean|vy|)
236
+ prev_gray = None
237
+ idx = 0
238
+ while True:
239
+ ok, frame = cap.read()
240
+ if not ok:
241
+ break
242
+ if idx % step == 0:
243
+ h, w = frame.shape[:2]
244
+ small = cv2.resize(frame, (W, max(1, int(h * W / w))))
245
+ gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
246
+ t = idx / fps
247
+ if prev_gray is not None and prev_gray.shape == gray.shape:
248
+ flow = cv2.calcOpticalFlowFarneback(
249
+ prev_gray, gray, None, 0.5, 3, 15, 3, 5, 1.2, 0)
250
+ mag, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
251
+ gh, gw = mag.shape
252
+ ch, cw = max(1, gh // 3), max(1, gw // 3)
253
+ best = (0.0, (1, 1), 0.0, 0.0)
254
+ for r in range(3):
255
+ for c in range(3):
256
+ cell = mag[r * ch:(r + 1) * ch, c * cw:(c + 1) * cw]
257
+ m = float(cell.mean()) if cell.size else 0.0
258
+ if m > best[0]:
259
+ fx = flow[r * ch:(r + 1) * ch, c * cw:(c + 1) * cw, 0]
260
+ fy = flow[r * ch:(r + 1) * ch, c * cw:(c + 1) * cw, 1]
261
+ best = (m, (r, c),
262
+ float(np.abs(fx).mean()),
263
+ float(np.abs(fy).mean()))
264
+ samples.append((t, best[0], best[1], best[2], best[3]))
265
+ prev_gray = gray
266
+ idx += 1
267
+ finally:
268
+ cap.release()
269
+
270
+ if len(samples) < 3:
271
+ return []
272
+ mags = np.array([a[1] for a in samples])
273
+ base = float(np.median(mags))
274
+ # MAD instead of std: std is inflated by the outliers (the signal
275
+ # itself), which would push the threshold above the signal. MAD is robust.
276
+ mad = float(np.median(np.abs(mags - base)))
277
+ threshold = base + max(4 * 1.4826 * mad, 0.25)
278
+
279
+ blocks = []
280
+ start_i = None
281
+ last = -10
282
+ for i, (t, m, _cell, _vx, _vy) in enumerate(samples):
283
+ if m >= threshold:
284
+ if start_i is None:
285
+ start_i = i
286
+ elif i - last > 2:
287
+ blocks.append((start_i, last))
288
+ start_i = i
289
+ last = i
290
+ if start_i is not None:
291
+ blocks.append((start_i, last))
292
+
293
+ names = {
294
+ (0, 0): "top-left corner", (0, 1): "top-center third",
295
+ (0, 2): "top-right corner", (1, 0): "middle-left third",
296
+ (1, 1): "center", (1, 2): "middle-right third",
297
+ (2, 0): "bottom-left corner", (2, 1): "bottom-center third",
298
+ (2, 2): "bottom-right corner",
299
+ }
300
+ dt = step / fps
301
+ result = []
302
+ for a, b in blocks:
303
+ t0 = max(0.0, samples[a][0] - dt)
304
+ t1 = samples[b][0] + dt
305
+ regs = [samples[i][2] for i in range(a, b + 1)]
306
+ dom = max(set(regs), key=regs.count)
307
+ mag_mean = float(np.mean([samples[i][1] for i in range(a, b + 1)]))
308
+ vxm = float(np.mean([samples[i][3] for i in range(a, b + 1)]))
309
+ vym = float(np.mean([samples[i][4] for i in range(a, b + 1)]))
310
+ if vym > 2 * vxm:
311
+ axis = "vertical"
312
+ elif vxm > 2 * vym:
313
+ axis = "horizontal"
314
+ else:
315
+ axis = "mixed"
316
+ result.append({
317
+ "start": t0, "end": t1,
318
+ "region": names[dom],
319
+ "magnitude": round(mag_mean, 3),
320
+ "axis": axis,
321
+ })
322
+ return result
323
+
324
+
325
+ def build_prompt(segments: list, base_prompt: str, cuts: list | None = None) -> str:
326
+ prompt = base_prompt
327
+ if cuts:
328
+ items = "\n".join(f"- cut at {fmt_ts(c)} ({c:.2f}s)" for c in cuts)
329
+ prompt = prompt + CUT_HINT_SECTION.format(items=items)
330
+ if not segments:
331
+ return prompt
332
+ items = "\n".join(
333
+ f"- {fmt_ts(s['start'])}-{fmt_ts(s['end'])} (region: {s['region']}, "
334
+ f"dominant motion axis: {s['axis']}, "
335
+ f"mean magnitude {s['magnitude']} px/frame)"
336
+ for s in segments
337
+ )
338
+ return prompt + MOTION_HINT_SECTION.format(items=items)
339
+
340
+
341
+ # ---------------- deterministic cut detection (provider-agnostic) ----------------
342
+
343
+ def detect_cuts(path: str, threshold: float = 0.4) -> list:
344
+ """Detect hard cuts via ffmpeg scene detection.
345
+
346
+ Runs the `select` filter with `gt(scene,threshold)` and parses the
347
+ `showinfo` pts_time of each selected frame. Returns sorted timestamps
348
+ in seconds. Fails silent (returns []) on ffmpeg error.
349
+ """
350
+ r = subprocess.run(
351
+ ["ffmpeg", "-v", "info", "-i", path,
352
+ "-filter:v", f"select='gt(scene,{threshold})',showinfo",
353
+ "-f", "null", "-"],
354
+ capture_output=True, text=True,
355
+ )
356
+ cuts = []
357
+ for line in (r.stderr or "").splitlines():
358
+ if "showinfo" not in line:
359
+ continue
360
+ m = re.search(r"pts_time:([0-9.]+)", line)
361
+ if m:
362
+ cuts.append(float(m.group(1)))
363
+ # Drop the t=0 selection (first frame always "selected") and dedupe.
364
+ cuts = sorted({c for c in cuts if c > 0.05})
365
+ return cuts
366
+
367
+
368
+ # ---------------- Gemini provider ----------------
369
+
370
+ def gemini_generate(base: str, key: str, model: str, parts: list) -> str | None:
371
+ url = f"{base}/models/{model}:generateContent?key={key}"
372
+ data = http_json(url, {"Content-Type": "application/json"},
373
+ json.dumps({"contents": [{"parts": parts}]}).encode())
374
+ if not data:
375
+ return None
376
+ try:
377
+ return data["candidates"][0]["content"]["parts"][0]["text"].strip()
378
+ except (KeyError, IndexError, TypeError):
379
+ print(f"error: unexpected response: {json.dumps(data)[:300]}",
380
+ file=sys.stderr)
381
+ return None
382
+
383
+
384
+ def gemini_upload(base: str, key: str, path: str, mime: str) -> str | None:
385
+ """Direct upload to the Gemini Files API. Returns the file name."""
386
+ with open(path, "rb") as f:
387
+ body = f.read()
388
+ url = f"https://generativelanguage.googleapis.com/upload/v1beta/files?key={key}"
389
+ data = http_json(url, {"Content-Type": mime}, body, timeout=600)
390
+ if not data:
391
+ return None
392
+ try:
393
+ return data["file"]["name"]
394
+ except (KeyError, TypeError):
395
+ print(f"error: upload failed: {json.dumps(data)[:300]}",
396
+ file=sys.stderr)
397
+ return None
398
+
399
+
400
+ def gemini_wait_active(base: str, key: str, file_name: str,
401
+ timeout_s: int = 300) -> str | None:
402
+ """Wait for the file to leave PROCESSING. Returns the file URI."""
403
+ url = f"{base}/{file_name}?key={key}"
404
+ deadline = time.time() + timeout_s
405
+ while time.time() < deadline:
406
+ req = urllib.request.Request(url, method="GET")
407
+ try:
408
+ with urllib.request.urlopen(req, timeout=60) as resp:
409
+ data = json.load(resp)
410
+ except urllib.error.HTTPError as e:
411
+ # transient 400 while the file is still being indexed
412
+ print(f"note: GET {e.code}, retrying...", file=sys.stderr)
413
+ time.sleep(10)
414
+ continue
415
+ except Exception as e: # noqa: BLE001
416
+ print(f"note: {e}, retrying...", file=sys.stderr)
417
+ time.sleep(10)
418
+ continue
419
+ state = data.get("state")
420
+ if state == "ACTIVE":
421
+ return data["uri"]
422
+ if state == "FAILED":
423
+ print(f"error: file processing failed: {json.dumps(data)[:300]}",
424
+ file=sys.stderr)
425
+ return None
426
+ print(f"note: file {state}, waiting...", file=sys.stderr)
427
+ time.sleep(10)
428
+ print("error: timeout waiting for file processing", file=sys.stderr)
429
+ return None
430
+
431
+
432
+ def validate_video(path: str) -> dict:
433
+ """ffprobe: validate codec, duration, streams, integrity. No frame extraction."""
434
+ r = subprocess.run(
435
+ ["ffprobe", "-v", "error", "-print_format", "json",
436
+ "-show_format", "-show_streams", path],
437
+ capture_output=True, text=True,
438
+ )
439
+ if r.returncode != 0 or not r.stdout.strip():
440
+ raise RuntimeError(f"ffprobe failed (invalid or corrupt file): {r.stderr[:200]}")
441
+ info = json.loads(r.stdout)
442
+ streams = info.get("streams", [])
443
+ video = [s for s in streams if s.get("codec_type") == "video"]
444
+ audio = [s for s in streams if s.get("codec_type") == "audio"]
445
+ if not video:
446
+ raise RuntimeError("file has no video stream")
447
+ fmt = info.get("format", {})
448
+ return {
449
+ "duration": float(fmt.get("duration", 0)),
450
+ "size": int(fmt.get("size", 0)),
451
+ "video_codec": video[0].get("codec_name"),
452
+ "has_audio": bool(audio),
453
+ }
454
+
455
+
456
+ # ---------------- OpenAI-compatible provider ----------------
457
+
458
+ def extract_keyframes(path: str, count: int, duration: float) -> list:
459
+ """Extract `count` evenly spaced JPEG keyframes. Returns temp paths."""
460
+ paths = []
461
+ for i in range(count):
462
+ t = duration * (i + 0.5) / count if duration > 0 else i
463
+ tmp = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
464
+ tmp.close()
465
+ r = subprocess.run(
466
+ ["ffmpeg", "-y", "-v", "error", "-ss", f"{t:.2f}", "-i", path,
467
+ "-frames:v", "1", "-vf", "scale=1024:-1", "-q:v", "4", tmp.name],
468
+ capture_output=True,
469
+ )
470
+ if r.returncode == 0 and os.path.getsize(tmp.name) > 0:
471
+ paths.append(tmp.name)
472
+ else:
473
+ os.unlink(tmp.name)
474
+ return paths
475
+
476
+
477
+ def openai_chat(base: str, key: str, model: str, messages: list) -> str | None:
478
+ url = f"{base.rstrip('/')}/chat/completions"
479
+ payload = {"model": model, "messages": messages, "max_tokens": 4096}
480
+ data = http_json(url,
481
+ {"Content-Type": "application/json",
482
+ "Authorization": f"Bearer {key}"},
483
+ json.dumps(payload).encode())
484
+ if not data:
485
+ return None
486
+ try:
487
+ return data["choices"][0]["message"]["content"].strip()
488
+ except (KeyError, IndexError, TypeError):
489
+ print(f"error: unexpected response: {json.dumps(data)[:300]}",
490
+ file=sys.stderr)
491
+ return None
492
+
493
+
494
+ # ---------------- analysis flows ----------------
495
+
496
+ def analyze_url_gemini(base: str, key: str, model: str, url: str,
497
+ prompt: str) -> str | None:
498
+ # URL mode: no download, no optical-flow pass (documented limitation).
499
+ parts = [{"text": prompt}, {"file_data": {"file_uri": url}}]
500
+ return gemini_generate(base, key, model, parts)
501
+
502
+
503
+ def analyze_file_gemini(base: str, key: str, model: str, path: str,
504
+ prompt: str, want_motion: bool,
505
+ cut_threshold: float | None) -> str | None:
506
+ info = validate_video(path)
507
+ print(f"validated: {info['video_codec']}, {info['duration']:.0f}s, "
508
+ f"audio={'yes' if info['has_audio'] else 'no'}", file=sys.stderr)
509
+ mime, _ = mimetypes.guess_type(path)
510
+ mime = mime or "video/mp4"
511
+ print("uploading full video via Files API (native model sampling)...",
512
+ file=sys.stderr)
513
+ file_name = gemini_upload(base, key, path, mime)
514
+ if not file_name:
515
+ return None
516
+ print(f"upload ok: {file_name}, waiting for processing...", file=sys.stderr)
517
+ file_uri = gemini_wait_active(base, key, file_name)
518
+ if not file_uri:
519
+ return None
520
+ cuts = []
521
+ if cut_threshold is not None:
522
+ print("detecting hard cuts (ffmpeg scene detection)...",
523
+ file=sys.stderr)
524
+ cuts = detect_cuts(path, cut_threshold)
525
+ print(f" {len(cuts)} cuts detected", file=sys.stderr)
526
+ segments = []
527
+ if want_motion:
528
+ print("pass 1: optical flow looking for subtle motion...",
529
+ file=sys.stderr)
530
+ segments = detect_subtle_motion(path)
531
+ for s in segments:
532
+ print(f" subtle motion: {fmt_ts(s['start'])}-{fmt_ts(s['end'])} "
533
+ f"({s['region']}, mag {s['magnitude']})", file=sys.stderr)
534
+ if not segments:
535
+ print(" no subtle motion above noise floor", file=sys.stderr)
536
+ parts = [{"text": build_prompt(segments, prompt, cuts)},
537
+ {"file_data": {"file_uri": file_uri, "mime_type": mime}}]
538
+ return gemini_generate(base, key, model, parts)
539
+
540
+
541
+ def analyze_file_openai(base: str, key: str, model: str, path: str,
542
+ prompt: str, want_motion: bool,
543
+ keyframes: int,
544
+ cut_threshold: float | None) -> str | None:
545
+ info = validate_video(path)
546
+ print(f"validated: {info['video_codec']}, {info['duration']:.0f}s, "
547
+ f"audio={'yes' if info['has_audio'] else 'no'}", file=sys.stderr)
548
+ print(f"extracting {keyframes} keyframes...", file=sys.stderr)
549
+ kf_paths = extract_keyframes(path, keyframes, info["duration"])
550
+ if not kf_paths:
551
+ print("error: could not extract keyframes", file=sys.stderr)
552
+ return None
553
+ cuts = []
554
+ if cut_threshold is not None:
555
+ print("detecting hard cuts (ffmpeg scene detection)...",
556
+ file=sys.stderr)
557
+ cuts = detect_cuts(path, cut_threshold)
558
+ print(f" {len(cuts)} cuts detected", file=sys.stderr)
559
+ segments = []
560
+ if want_motion:
561
+ print("pass 1: optical flow looking for subtle motion...",
562
+ file=sys.stderr)
563
+ segments = detect_subtle_motion(path)
564
+ content = [{"type": "text", "text": build_prompt(segments, prompt, cuts)}]
565
+ try:
566
+ for i, kf in enumerate(kf_paths):
567
+ with open(kf, "rb") as f:
568
+ b64 = base64.b64encode(f.read()).decode("ascii")
569
+ content.append({
570
+ "type": "text",
571
+ "text": f"[frame {i + 1}/{len(kf_paths)}]",
572
+ })
573
+ content.append({
574
+ "type": "image_url",
575
+ "image_url": {"url": f"data:image/jpeg;base64,{b64}"},
576
+ })
577
+ return openai_chat(base, key, model,
578
+ [{"role": "user", "content": content}])
579
+ finally:
580
+ for kf in kf_paths:
581
+ try:
582
+ os.unlink(kf)
583
+ except OSError:
584
+ pass
585
+
586
+
587
+ # ---------------- auxiliary model (universal, provider-agnostic) ----------------
588
+
589
+ AUX_FAST_PREAMBLE = """\
590
+ You are analyzing a video through evenly spaced still frames (keyframes). \
591
+ Treat the frames as a temporal sequence: describe what CHANGES between them, \
592
+ verify the order of events, and call out motion explicitly. This is the \
593
+ fast analysis path; be concise but do not skip the temporal verification \
594
+ section.\
595
+ """
596
+
597
+
598
+ def analyze_aux_fast(aux: dict, path: str, prompt: str, want_motion: bool,
599
+ keyframes: int,
600
+ cut_threshold: float | None) -> str | None:
601
+ """Modo Rapido: whole analysis on the auxiliary model via keyframes.
602
+
603
+ No full upload, no native temporal sampling. The optical-flow pass
604
+ still runs so subtle motion gets flagged into the prompt. Works with
605
+ any OpenAI-compatible vision endpoint.
606
+ """
607
+ info = validate_video(path)
608
+ print(f"validated: {info['video_codec']}, {info['duration']:.0f}s, "
609
+ f"audio={'yes' if info['has_audio'] else 'no'}", file=sys.stderr)
610
+ print(f"Modo Rapido: {keyframes} keyframes -> aux model "
611
+ f"'{aux['model']}'...", file=sys.stderr)
612
+ kf_paths = extract_keyframes(path, keyframes, info["duration"])
613
+ if not kf_paths:
614
+ print("error: could not extract keyframes", file=sys.stderr)
615
+ return None
616
+ cuts = []
617
+ if cut_threshold is not None:
618
+ print("detecting hard cuts (ffmpeg scene detection)...",
619
+ file=sys.stderr)
620
+ cuts = detect_cuts(path, cut_threshold)
621
+ print(f" {len(cuts)} cuts detected", file=sys.stderr)
622
+ segments = []
623
+ if want_motion:
624
+ print("pass 1: optical flow looking for subtle motion...",
625
+ file=sys.stderr)
626
+ segments = detect_subtle_motion(path)
627
+ for s in segments:
628
+ print(f" subtle motion: {fmt_ts(s['start'])}-{fmt_ts(s['end'])} "
629
+ f"({s['region']}, mag {s['magnitude']})", file=sys.stderr)
630
+ full_prompt = AUX_FAST_PREAMBLE + build_prompt(segments, prompt, cuts)
631
+ content = [{"type": "text", "text": full_prompt}]
632
+ try:
633
+ for i, kf in enumerate(kf_paths):
634
+ with open(kf, "rb") as f:
635
+ b64 = base64.b64encode(f.read()).decode("ascii")
636
+ content.append({
637
+ "type": "text",
638
+ "text": f"[frame {i + 1}/{len(kf_paths)}]",
639
+ })
640
+ content.append({
641
+ "type": "image_url",
642
+ "image_url": {"url": f"data:image/jpeg;base64,{b64}"},
643
+ })
644
+ return openai_chat(aux["base_url"], aux["api_key"], aux["model"],
645
+ [{"role": "user", "content": content}])
646
+ finally:
647
+ for kf in kf_paths:
648
+ try:
649
+ os.unlink(kf)
650
+ except OSError:
651
+ pass
652
+
653
+
654
+ def analyze_aux_verify(aux: dict, path: str, primary_report: str,
655
+ keyframes: int) -> str | None:
656
+ """Second opinion: the aux model cross-checks the primary report.
657
+
658
+ Sends keyframes plus the primary report and asks for agreement /
659
+ disagreement per scene, focusing on temporal claims. Returns the
660
+ verdict text or None.
661
+ """
662
+ info = validate_video(path)
663
+ kf_paths = extract_keyframes(path, keyframes, info["duration"])
664
+ if not kf_paths:
665
+ return None
666
+ verify_prompt = (
667
+ "You are a second-opinion reviewer. Below is a video analysis report "
668
+ "produced by another model from evenly spaced keyframes of the same "
669
+ "video. Review each scene claim against the frames: say which claims "
670
+ "you AGREE with, which you DISAGREE with (and why), and flag any "
671
+ "temporal-order mistake (wrong event sequence). Be terse.\n\n"
672
+ "--- PRIMARY REPORT ---\n" + primary_report
673
+ )
674
+ content = [{"type": "text", "text": verify_prompt}]
675
+ try:
676
+ for i, kf in enumerate(kf_paths):
677
+ with open(kf, "rb") as f:
678
+ b64 = base64.b64encode(f.read()).decode("ascii")
679
+ content.append({"type": "text",
680
+ "text": f"[frame {i + 1}/{len(kf_paths)}]"})
681
+ content.append({
682
+ "type": "image_url",
683
+ "image_url": {"url": f"data:image/jpeg;base64,{b64}"},
684
+ })
685
+ verdict = openai_chat(aux["base_url"], aux["api_key"], aux["model"],
686
+ [{"role": "user", "content": content}])
687
+ if verdict:
688
+ return "## Second opinion (auxiliary model)\n\n" + verdict
689
+ return None
690
+ finally:
691
+ for kf in kf_paths:
692
+ try:
693
+ os.unlink(kf)
694
+ except OSError:
695
+ pass
696
+
697
+
698
+ # ---------------- main ----------------
699
+
700
+ def main() -> int:
701
+ p = argparse.ArgumentParser(description="Videolyzer: deep video analysis.")
702
+ p.add_argument("source", help="YouTube URL (gemini only) or local file path")
703
+ p.add_argument("--provider", default=DEFAULT_PROVIDER,
704
+ choices=["gemini", "openai"],
705
+ help="API provider (default: gemini)")
706
+ p.add_argument("--model", default=DEFAULT_MODEL,
707
+ help=f"Model name (default: {DEFAULT_MODEL})")
708
+ p.add_argument("--base-url", default=None,
709
+ help="Custom API base URL for OpenAI-compatible providers")
710
+ p.add_argument("--api-key", default=None, help="API key (or env var)")
711
+ p.add_argument("--aux-model", default=None,
712
+ help="Auxiliary multimodal model name (any OpenAI-compatible "
713
+ f"vision endpoint; or {AUX_ENV_MODEL})")
714
+ p.add_argument("--aux-base-url", default=None,
715
+ help="Aux model API base URL "
716
+ f"(or {AUX_ENV_BASE_URL}; default {OPENAI_API_BASE})")
717
+ p.add_argument("--aux-api-key", default=None,
718
+ help=f"Aux model API key (or {AUX_ENV_API_KEY})")
719
+ p.add_argument("--fast", action="store_true",
720
+ help="Modo Rapido: run the whole analysis on the auxiliary "
721
+ "model via keyframes (fast, no full upload). "
722
+ "Requires --aux-model.")
723
+ p.add_argument("--verify", action="store_true",
724
+ help="Second opinion: after the primary analysis, have the "
725
+ "auxiliary model cross-check the report. "
726
+ "Requires --aux-model.")
727
+ p.add_argument("--out", default=None, help="Output .md file (default: stdout)")
728
+ p.add_argument("--prompt", default=None,
729
+ help="Custom analysis prompt (overrides the default)")
730
+ p.add_argument("--no-motion", action="store_true",
731
+ help="Skip the optical-flow subtle-motion pass")
732
+ p.add_argument("--cut-threshold", type=float, default=0.4,
733
+ help="Scene-detection threshold for deterministic cut "
734
+ "detection (ffmpeg). Lower = more sensitive. "
735
+ "Default: 0.4")
736
+ p.add_argument("--no-cuts", action="store_true",
737
+ help="Skip deterministic cut detection")
738
+ p.add_argument("--keyframes", type=int, default=KEYFRAME_COUNT,
739
+ help="Keyframes for the openai provider / aux model (default: 8)")
740
+ args = p.parse_args()
741
+
742
+ key = get_api_key(args)
743
+ aux = get_aux_config(args)
744
+ prompt = args.prompt or ANALYZE_PROMPT
745
+ want_motion = not args.no_motion
746
+ cut_threshold = None if args.no_cuts else args.cut_threshold
747
+
748
+ if args.fast and not aux:
749
+ print("error: --fast (Modo Rapido) requires an auxiliary model. "
750
+ f"Set --aux-model (or {AUX_ENV_MODEL}) plus "
751
+ f"--aux-api-key (or {AUX_ENV_API_KEY}).", file=sys.stderr)
752
+ return 2
753
+ if args.verify and not aux:
754
+ print("error: --verify requires an auxiliary model. "
755
+ f"Set --aux-model (or {AUX_ENV_MODEL}).", file=sys.stderr)
756
+ return 2
757
+ if is_url(args.source) and (args.fast or args.provider == "openai"):
758
+ print("error: URL input is only supported with "
759
+ "--provider gemini (without --fast)", file=sys.stderr)
760
+ return 2
761
+
762
+ try:
763
+ if args.fast:
764
+ # Modo Rapido: everything on the aux model via keyframes.
765
+ if not os.path.isfile(args.source):
766
+ print(f"error: file not found: {args.source}", file=sys.stderr)
767
+ return 2
768
+ report = analyze_aux_fast(aux, args.source, prompt,
769
+ want_motion, args.keyframes,
770
+ cut_threshold)
771
+ elif args.provider == "gemini":
772
+ base = GEMINI_API_BASE
773
+ if is_url(args.source):
774
+ print("URL mode: sending straight to the model, no download...",
775
+ file=sys.stderr)
776
+ print("note: cut detection unavailable in URL mode "
777
+ "(requires the file)", file=sys.stderr)
778
+ report = analyze_url_gemini(base, key, args.model,
779
+ args.source, prompt)
780
+ else:
781
+ if not os.path.isfile(args.source):
782
+ print(f"error: file not found: {args.source}",
783
+ file=sys.stderr)
784
+ return 2
785
+ print("file mode: validation + native upload...",
786
+ file=sys.stderr)
787
+ report = analyze_file_gemini(base, key, args.model,
788
+ args.source, prompt, want_motion,
789
+ cut_threshold)
790
+ if not report and aux:
791
+ # Fallback: aux model with keyframes.
792
+ print("warn: primary analysis failed, falling back to "
793
+ "auxiliary model...", file=sys.stderr)
794
+ report = analyze_aux_fast(aux, args.source, prompt,
795
+ want_motion, args.keyframes,
796
+ cut_threshold)
797
+ else: # openai-compatible
798
+ if not os.path.isfile(args.source):
799
+ print(f"error: file not found: {args.source}", file=sys.stderr)
800
+ return 2
801
+ base = args.base_url or OPENAI_API_BASE
802
+ print(f"file mode (openai-compatible): {args.keyframes} keyframes...",
803
+ file=sys.stderr)
804
+ report = analyze_file_openai(base, key, args.model, args.source,
805
+ prompt, want_motion, args.keyframes,
806
+ cut_threshold)
807
+ if not report and aux:
808
+ print("warn: primary analysis failed, falling back to "
809
+ "auxiliary model...", file=sys.stderr)
810
+ report = analyze_aux_fast(aux, args.source, prompt,
811
+ want_motion, args.keyframes,
812
+ cut_threshold)
813
+ except Exception as exc: # noqa: BLE001
814
+ print(f"error: {exc}", file=sys.stderr)
815
+ return 4
816
+
817
+ if not report:
818
+ print("error: empty response from the model", file=sys.stderr)
819
+ return 5
820
+
821
+ # Second opinion (optional): aux model cross-checks the primary report.
822
+ if args.verify and not args.fast and not is_url(args.source):
823
+ print("second opinion: aux model reviewing the report...",
824
+ file=sys.stderr)
825
+ verdict = analyze_aux_verify(aux, args.source, report, args.keyframes)
826
+ if verdict:
827
+ report = report.rstrip() + "\n\n" + verdict + "\n"
828
+ else:
829
+ print("note: second opinion unavailable, keeping primary report",
830
+ file=sys.stderr)
831
+
832
+ if args.out:
833
+ with open(args.out, "w") as f:
834
+ f.write(report + "\n")
835
+ print(f"report saved: {args.out}", file=sys.stderr)
836
+ else:
837
+ print(report)
838
+ return 0
839
+
840
+
841
+ if __name__ == "__main__":
842
+ sys.exit(main())