-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
424 lines (368 loc) · 13.4 KB
/
cli.py
File metadata and controls
424 lines (368 loc) · 13.4 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
from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import uuid
from dataclasses import replace
from pathlib import Path
from time import monotonic
import click
import httpx
import uvicorn
from core_config import Config
from service_media import extract_frames_ffmpeg, prepare_source
from service_summarize import SummarizationEngine
from video_rss_aggregator.bootstrap import AppRuntime, build_runtime
from video_rss_aggregator.domain.outcomes import Failure
log = logging.getLogger(__name__)
def _setup_logging() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
)
def _digest_file(path: Path) -> str:
digest = hashlib.sha1()
with path.open("rb") as handle:
while True:
chunk = handle.read(1 << 16)
if not chunk:
break
digest.update(chunk)
return digest.hexdigest()
def _frame_metrics(paths: list[Path]) -> dict[str, float | int]:
seen: set[str] = set()
for path in paths:
if not path.exists():
continue
try:
seen.add(_digest_file(path))
except OSError:
continue
frame_count = len(paths)
unique_frames = len(seen)
duplicates = max(frame_count - unique_frames, 0)
unique_ratio = round(unique_frames / frame_count, 3) if frame_count else 0.0
return {
"frame_count": frame_count,
"unique_frames": unique_frames,
"duplicate_frames": duplicates,
"unique_ratio": unique_ratio,
}
def _as_int(value: object) -> int:
if isinstance(value, int):
return value
if isinstance(value, float):
return int(value)
if isinstance(value, str):
try:
return int(value)
except ValueError:
return 0
return 0
def _as_float(value: object) -> float:
if isinstance(value, (int, float)):
return float(value)
if isinstance(value, str):
try:
return float(value)
except ValueError:
return 0.0
return 0.0
async def _close_runtime(runtime: AppRuntime) -> None:
close_result = runtime.close()
if close_result is not None:
await close_result
@click.group()
def cli() -> None:
"""Video RSS Aggregator powered by Qwen3.5 vision models."""
_setup_logging()
@cli.command()
def bootstrap() -> None:
"""Validate Ollama connectivity and pull configured models."""
config = Config.from_env()
async def _run() -> None:
runtime = await build_runtime(config)
try:
report = await runtime.use_cases.bootstrap_runtime.execute()
models_prepared = report.get("models_prepared")
if models_prepared is None:
models_prepared = report["models"]
runtime_payload = report.get("runtime")
if isinstance(runtime_payload, dict):
runtime_response = runtime_payload
else:
runtime_response = await runtime.use_cases.get_runtime_status.execute()
print(
json.dumps(
{
"models_prepared": models_prepared,
"runtime": runtime_response,
},
indent=2,
)
)
finally:
await _close_runtime(runtime)
try:
asyncio.run(_run())
except Exception as exc:
raise click.ClickException(str(exc)) from exc
@cli.command()
@click.option("--bind", default=None, help="host:port override")
def serve(bind: str | None) -> None:
"""Start the FastAPI server."""
config = Config.from_env()
host, port = config.bind_host, config.bind_port
if bind:
host_part, sep, port_part = bind.rpartition(":")
if sep and host_part:
host = host_part
try:
port = int(port_part)
except ValueError:
pass
async def _run() -> None:
from adapter_api import create_app
app = create_app(config=config)
uv_cfg = uvicorn.Config(app, host=host, port=port, log_level="info")
server = uvicorn.Server(uv_cfg)
await server.serve()
try:
asyncio.run(_run())
except Exception as exc:
raise click.ClickException(str(exc)) from exc
@cli.command()
def status() -> None:
"""Print runtime status including VRAM usage."""
config = Config.from_env()
async def _run() -> None:
runtime = await build_runtime(config)
try:
status_payload = await runtime.use_cases.get_runtime_status.execute()
print(json.dumps(status_payload, indent=2))
finally:
await _close_runtime(runtime)
try:
asyncio.run(_run())
except Exception as exc:
raise click.ClickException(str(exc)) from exc
@cli.command()
@click.option("--source", envvar="VRA_VERIFY_SOURCE", required=True, help="URL or file")
@click.option("--title", envvar="VRA_VERIFY_TITLE", default=None)
def verify(source: str, title: str | None) -> None:
"""Run one end-to-end processing job and print metrics."""
config = Config.from_env()
async def _run() -> None:
runtime = await build_runtime(config)
try:
t0 = monotonic()
outcome = await runtime.use_cases.process_source.execute(source, title)
if isinstance(outcome, Failure):
raise click.ClickException(outcome.reason)
total_ms = int((monotonic() - t0) * 1000)
print(
json.dumps(
{
"source_url": outcome.media.source_url,
"title": outcome.media.title,
"transcript_chars": outcome.summary.transcript_chars,
"frame_count": outcome.summary.frame_count,
"model_used": outcome.summary.model_used,
"vram_mb": outcome.summary.vram_mb,
"error": outcome.summary.error,
"summary_chars": len(outcome.summary.summary),
"key_points": len(outcome.summary.key_points),
"total_ms": total_ms,
},
indent=2,
)
)
finally:
await _close_runtime(runtime)
try:
asyncio.run(_run())
except Exception as exc:
raise click.ClickException(str(exc)) from exc
@cli.command()
@click.option("--source", envvar="VRA_BENCH_SOURCE", required=True, help="URL or file")
@click.option("--title", envvar="VRA_BENCH_TITLE", default=None)
@click.option(
"--max-frames",
type=int,
default=None,
help="Optional override for frame count during benchmark",
)
@click.option(
"--with-summary/--no-summary",
default=True,
show_default=True,
help="Run model summarization for both extraction strategies",
)
def benchmark(
source: str,
title: str | None,
max_frames: int | None,
with_summary: bool,
) -> None:
"""Compare scene-aware and uniform frame extraction on one source."""
config = Config.from_env()
if max_frames is not None:
config = replace(config, max_frames=max(max_frames, 1))
async def _run_mode(
*,
mode: str,
source_url: str,
media_path: Path,
resolved_title: str | None,
transcript: str,
scene_detection: bool,
summarizer: SummarizationEngine | None,
frame_output_dir: Path,
cfg: Config,
) -> dict[str, object]:
started = monotonic()
try:
frames = await extract_frames_ffmpeg(
input_path=media_path,
output_dir=frame_output_dir,
file_id=uuid.uuid4(),
max_frames=cfg.max_frames,
scene_detection=scene_detection,
scene_threshold=cfg.frame_scene_threshold,
min_scene_frames=cfg.frame_scene_min_frames,
)
except Exception as exc:
return {
"mode": mode,
"error": str(exc),
"extraction_ms": int((monotonic() - started) * 1000),
}
result: dict[str, object] = {
"mode": mode,
"extraction_ms": int((monotonic() - started) * 1000),
"frames": [str(path) for path in frames],
"scene_frame_count": sum(1 for path in frames if "_scene_" in path.name),
"uniform_frame_count": sum(
1 for path in frames if "_uniform_" in path.name
),
**_frame_metrics(frames),
}
if summarizer is None:
return result
summary_started = monotonic()
summary = await summarizer.summarize(
source_url=source_url,
title=resolved_title,
transcript=transcript,
frame_paths=frames,
)
result["summary"] = {
"latency_ms": int((monotonic() - summary_started) * 1000),
"summary_chars": len(summary.summary),
"key_points": len(summary.key_points),
"visual_highlights": len(summary.visual_highlights),
"model_used": summary.model_used,
"vram_mb": summary.vram_mb,
"error": summary.error,
}
return result
async def _run() -> None:
client = httpx.AsyncClient(
timeout=httpx.Timeout(connect=15.0, read=300.0, write=300.0, pool=60.0),
follow_redirects=True,
limits=httpx.Limits(max_keepalive_connections=20, max_connections=50),
)
summarizer: SummarizationEngine | None = None
try:
prepared = await prepare_source(
client=client,
source=source,
storage_dir=config.storage_dir,
max_transcript_chars=config.max_transcript_chars,
)
resolved_title = title or prepared.title
if with_summary:
summarizer = SummarizationEngine(config)
await summarizer.prepare_models()
frame_dir = Path(config.storage_dir) / "frames"
scene_aware = await _run_mode(
mode="scene_aware",
source_url=source,
media_path=prepared.media_path,
resolved_title=resolved_title,
transcript=prepared.transcript,
scene_detection=True,
summarizer=summarizer,
frame_output_dir=frame_dir,
cfg=config,
)
uniform_only = await _run_mode(
mode="uniform_only",
source_url=source,
media_path=prepared.media_path,
resolved_title=resolved_title,
transcript=prepared.transcript,
scene_detection=False,
summarizer=summarizer,
frame_output_dir=frame_dir,
cfg=config,
)
comparison: dict[str, object] = {
"extraction_delta_ms": int(
_as_int(scene_aware.get("extraction_ms", 0))
- _as_int(uniform_only.get("extraction_ms", 0))
),
"unique_ratio_delta": round(
_as_float(scene_aware.get("unique_ratio", 0.0))
- _as_float(uniform_only.get("unique_ratio", 0.0)),
3,
),
}
scene_summary = scene_aware.get("summary")
uniform_summary = uniform_only.get("summary")
if isinstance(scene_summary, dict) and isinstance(uniform_summary, dict):
comparison.update(
{
"summary_latency_delta_ms": int(
scene_summary.get("latency_ms", 0)
- uniform_summary.get("latency_ms", 0)
),
"summary_chars_delta": int(
scene_summary.get("summary_chars", 0)
- uniform_summary.get("summary_chars", 0)
),
"key_points_delta": int(
scene_summary.get("key_points", 0)
- uniform_summary.get("key_points", 0)
),
"visual_highlights_delta": int(
scene_summary.get("visual_highlights", 0)
- uniform_summary.get("visual_highlights", 0)
),
}
)
print(
json.dumps(
{
"source_url": source,
"title": resolved_title,
"transcript_chars": len(prepared.transcript),
"max_frames": config.max_frames,
"scene_threshold": config.frame_scene_threshold,
"scene_min_frames": config.frame_scene_min_frames,
"scene_aware": scene_aware,
"uniform_only": uniform_only,
"comparison": comparison,
},
indent=2,
)
)
finally:
await client.aclose()
if summarizer is not None:
await summarizer.close()
try:
asyncio.run(_run())
except Exception as exc:
raise click.ClickException(str(exc)) from exc