-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
543 lines (475 loc) · 24.3 KB
/
cli.py
File metadata and controls
543 lines (475 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
# cli.py
from __future__ import annotations
import json
import time
import shutil
from pathlib import Path
from typing import List, Optional, Tuple
import typer
from stockflow.config import Config
from stockflow.qc.probe import probe_video, VideoProbe
from stockflow.qc.specs import load_specs
from stockflow.qc.validate import validate_against_specs, qc_all as qc_all_helper
from stockflow.qc.preflight import preflight_check
from stockflow.qc.gate import (
default_report_path,
save_report,
load_report,
build_pass_index,
summarize_console,
check_all_files_pass,
)
from stockflow.decide.richness import decide_container
from stockflow.metadata.embed import embed_in_dir
from stockflow.transform.transcode import transcode_mp4, transcode_prores
from stockflow.metadata.generate import generate_texts
# add alongside your other imports
from stockflow.metadata.csv.shutterstock import row_for as sstk_row_for
from stockflow.metadata.csv.pond5 import row_for as pond5_row_for
from stockflow.metadata.csv.adobe import row_for as adobe_row_for
from stockflow.metadata.csv.common import write_rows # used for the master CSV
from stockflow.metadata.csv.pond5 import Pond5Row, write_csv as write_pond5_csv
from stockflow.metadata.csv.shutterstock import ShutterstockRow, write_csv as write_sstk_csv
from stockflow.metadata.csv.adobe import AdobeRow, write_csv as write_adobe_csv
from pathlib import Path
from stockflow.metadata.csv import master, shutterstock, adobe, pond5
from stockflow.portals import open_portals
from stockflow.manifest import ManifestEntry, manifest_path_for, append_entries, build_output_pass_index
app = typer.Typer(add_completion=False, help="stockflow – automate QC, transform, metadata & upload for stock footage")
MEDIA_EXTS: Tuple[str, ...] = (".avi", ".mp4", ".mov")
def iter_media_files(root: Path, recursive: bool = True) -> List[Path]:
pattern = "**/*" if recursive else "*"
return sorted(p for p in root.glob(pattern) if p.is_file() and p.suffix.lower() in MEDIA_EXTS)
def _union_allowed_fps(specs: dict, sites=("adobe","shutterstock","pond5")) -> List[float]:
vals: List[float] = []
for s in sites:
arr = specs["specs"].get(s, {}).get("fps_allowed", [])
vals.extend([float(x) for x in arr])
# remove dupes while preserving order
seen = set()
out: List[float] = []
for v in vals:
if v not in seen:
seen.add(v); out.append(v)
return out
import re
def _output_stem(stem: str) -> str:
# Historically we appended "_cleared" to indicate band-hide. We now rely on
# stage directories (passed/failed) and do not alter the stem.
# Also normalize any historical multiple "_cleared" suffixes away if present.
return re.sub(r"(?:_cleared)+$", "", stem)
# -------------------------------------------------------------------
# Stage 1 – init-qc (pre-flight)
# -------------------------------------------------------------------
@app.command("init-qc")
def init_qc(
input_dir: Optional[str] = typer.Option(None, "--input-dir", "-i", help="Defaults to paths.in_root from YAML"),
out_dir: Optional[str] = typer.Option(None, "--out-dir", "-o", help="Defaults to paths.out_root from YAML"),
move: bool = typer.Option(True, "--move/--copy", help="Move files instead of copying to stage folders"),
recursive: bool = typer.Option(True, help="Recurse into subfolders"),
):
cfg = Config.load()
specs = load_specs(cfg.specs_path)
in_dir = Path(input_dir or cfg.paths.in_root)
root = Path(out_dir or cfg.paths.out_root)
stage_root = root / "init_qc"
passed_dir = stage_root / "passed"
failed_dir = stage_root / "failed"
passed_dir.mkdir(parents=True, exist_ok=True)
failed_dir.mkdir(parents=True, exist_ok=True)
files = iter_media_files(in_dir, recursive=recursive)
if not files:
typer.secho("No media files found.", fg=typer.colors.YELLOW)
raise typer.Exit(code=1)
report: List[dict] = []
n_pass = n_fail = 0
N = len(files)
typer.secho(f"init_qc: Started with {N} files", fg=typer.colors.GREEN)
#get allowed FPS set to annotate normalization plan
allowed_fps = _union_allowed_fps(specs)
eps = cfg.encode.fps_epsilon
for i, src in enumerate(files):
pr = probe_video(src, cfg.encode.ffprobe)
res = preflight_check(pr, cfg, specs)
# --- NEW: annotate FPS plan (never rejects in init-qc)
fps_info = {}
if pr.fps:
nearest = min(allowed_fps, key=lambda a: abs(pr.fps - float(a)))
needs_norm = abs(pr.fps - nearest) > eps
fps_info = {
"actual": pr.fps,
"nearest_allowed": float(nearest),
"needs_normalization": bool(needs_norm),
}
record = {
"file": str(src),
"preflight": {"ok": res.ok, "reasons": res.reasons},
"fps": fps_info, # <-- NEW
}
report.append(record)
dst = passed_dir / src.name if res.ok else failed_dir / src.name
op = shutil.move if move else shutil.copy2
op(str(src), str(dst))
prefix = f"[{i+1}/{N}] "
if res.ok:
n_pass += 1
extra = ""
if fps_info.get("needs_normalization"):
extra = f" (will normalize to {fps_info['nearest_allowed']:g} fps)"
typer.secho(prefix + f"{src.name}: init_qc PASSED{extra}", fg=typer.colors.GREEN)
else:
n_fail += 1
typer.secho(prefix + f"{src.name}: init_qc FAILED (see {stage_root/'init_report.json'})", fg=typer.colors.RED)
report_path = stage_root / "init_report.json"
report_path.write_text(json.dumps(report, indent=2))
typer.secho(f"init_qc: {n_pass} passed, {n_fail} failed. Report: {report_path}", fg=typer.colors.GREEN if n_fail == 0 else typer.colors.YELLOW)
typer.secho("init_qc: Complete", fg=typer.colors.GREEN)
# -------------------------------------------------------------------
# Stage 2 – hideband-transcode (delivery QC + optional FPS normalization)
# -------------------------------------------------------------------
# --- paste to replace the entire hideband_transcode() in cli.py ---
@app.command("hideband-transcode")
def hideband_transcode(
out_dir: Optional[str] = typer.Option(None, "--out-dir", "-o", help="Pipeline output root (default paths.out_root)"),
no_hide_band: bool = typer.Option(False, "--no-hide-band", help="Disable bottom band hide filter"),
overwrite: bool = typer.Option(True, help="Overwrite outputs if they already exist"),
):
cfg = Config.load()
specs = load_specs(cfg.specs_path)
root = Path(out_dir or cfg.paths.out_root)
src_dir = root / "init_qc" / "passed"
if not src_dir.exists():
typer.secho(f"Missing input folder: {src_dir}. Run init-qc first.", fg=typer.colors.RED)
raise typer.Exit(code=2)
stage_root = root / "hideband_transcode"
passed_dir = stage_root / "passed"
failed_dir = stage_root / "failed"
passed_dir.mkdir(parents=True, exist_ok=True)
failed_dir.mkdir(parents=True, exist_ok=True)
files = [p for p in src_dir.glob("*") if p.is_file() and p.suffix.lower() in (".avi", ".mp4", ".mov")]
if not files:
typer.secho("No files found in init_qc/passed.", fg=typer.colors.YELLOW)
raise typer.Exit(code=1)
allowed_fps = _union_allowed_fps(specs)
eps = Config.load().encode.fps_epsilon
def _is_allowed(fps: Optional[float]) -> bool:
return fps is not None and any(abs(float(fps) - float(a)) <= eps for a in allowed_fps)
def _nearest(fps: float) -> float:
return float(min(allowed_fps, key=lambda a: abs(float(fps) - float(a))))
report: List[dict] = []
n_pass = n_fail = 0
N = len(files)
typer.secho(f"hideband_transcode: Started with {N} files", fg=typer.colors.GREEN)
for i, src in enumerate(files):
prefix = f"[{i+1}/{N}] "
try:
pr = probe_video(src, cfg.encode.ffprobe)
# Decide container & output name up front (no unbound locals)
decision = decide_container(pr, cfg)
suffix = ".mp4" if decision.target == "mp4" else ".mov"
tmp_out = stage_root / f"{_output_stem(src.stem)}{suffix}"
if tmp_out.exists() and not overwrite:
typer.secho(prefix + f"Skip (exists): {tmp_out.name}", fg=typer.colors.YELLOW)
continue
# 1st attempt: normalize if input FPS is known & off-spec
target_fps: Optional[float] = None
if cfg.encode.normalize_fps and pr.fps is not None and not _is_allowed(pr.fps):
target_fps = _nearest(pr.fps)
typer.secho(prefix + f"Normalizing FPS {pr.fps:.3f} → {target_fps:g}", fg=typer.colors.MAGENTA)
# Transcode (CFR enforced by transcode_* when target_fps is set)
if decision.target == "mp4":
transcode_mp4(pr, src, tmp_out, cfg, hide_band=(not no_hide_band), target_fps=target_fps)
else:
transcode_prores(pr, src, tmp_out, cfg, hide_band=(not no_hide_band), target_fps=target_fps)
# Probe output and print its FPS
pr_out = probe_video(tmp_out, cfg.encode.ffprobe)
typer.echo(prefix + f"Output FPS: {pr_out.fps:.3f}" if pr_out.fps is not None else prefix + "Output FPS: <unknown>")
# Fallback: if still off-spec (or unknown), retry once with nearest allowed CFR
if cfg.encode.normalize_fps and not _is_allowed(pr_out.fps):
if pr_out.fps is not None:
fix_target = _nearest(pr_out.fps)
else:
# worst case: choose a sensible default that’s widely accepted
fix_target = 30.0
typer.secho(prefix + f"Retrying with CFR normalization to {fix_target:g} fps", fg=typer.colors.MAGENTA)
if decision.target == "mp4":
transcode_mp4(pr, src, tmp_out, cfg, hide_band=(not no_hide_band), target_fps=fix_target)
else:
transcode_prores(pr, src, tmp_out, cfg, hide_band=(not no_hide_band), target_fps=fix_target)
pr_out = probe_video(tmp_out, cfg.encode.ffprobe)
typer.echo(prefix + f"Output FPS (retry): {pr_out.fps:.3f}" if pr_out.fps is not None else prefix + "Output FPS (retry): <unknown>")
# Delivery QC on final output
delivery = validate_against_specs(pr_out, specs, sites=["adobe", "shutterstock", "pond5"])
ok = delivery.overall_ok
dst = (passed_dir if ok else failed_dir) / tmp_out.name
if tmp_out != dst:
shutil.move(str(tmp_out), str(dst))
report.append({
"source": str(src),
"output": str(dst),
"overall_ok": ok,
"qc": {k: {"ok": v.ok, "reasons": v.reasons, "suggestions": v.suggestions} for k, v in delivery.by_site.items()},
})
if ok:
n_pass += 1
typer.secho(prefix + f"{src.name} → {dst.name}: delivery PASSED", fg=typer.colors.GREEN)
else:
n_fail += 1
typer.secho(prefix + f"{src.name} → {dst.name}: delivery FAILED (see {stage_root/'delivery_report.json'})", fg=typer.colors.RED)
except Exception as e:
n_fail += 1
report.append({"source": str(src), "output": None, "overall_ok": False, "error": repr(e)})
typer.secho(prefix + f"{src.name}: transcode ERROR → failed (see {stage_root/'delivery_report.json'})", fg=typer.colors.RED)
rep_path = stage_root / "delivery_report.json"
rep_path.write_text(json.dumps(report, indent=2))
man_path = root / "_stockflow_manifest.json"
entries = [
ManifestEntry(source=r.get("source",""), output=r["output"], qc_passed=bool(r.get("overall_ok", False)), ts=time.time())
for r in report if r.get("output")
]
if entries:
append_entries(man_path, entries)
typer.secho(
f"hideband_transcode: {n_pass} passed, {n_fail} failed. Report: {rep_path}",
fg=typer.colors.GREEN if n_fail == 0 else typer.colors.YELLOW
)
typer.secho("hideband_transcode: Complete", fg=typer.colors.GREEN)
@app.command("embed-meta")
def embed_meta(
input_dir: Optional[str] = typer.Option(None, "--input-dir", "-i", help="Defaults to paths.out_root/hideband_transcode/passed"),
recursive: bool = typer.Option(False, help="Recurse into subfolders"),
use_llm: bool = typer.Option(False, "--use-llm/--no-use-llm", help="Use LLM for cache misses before embedding"),
):
cfg = Config.load()
default_dir = Path(cfg.paths.out_root) / "hideband_transcode" / "passed"
in_dir = Path(input_dir or default_dir)
if not in_dir.exists():
typer.secho(f"Missing folder: {in_dir}", fg=typer.colors.RED)
raise typer.Exit(code=2)
from stockflow.metadata.embed import embed_in_dir
files = embed_in_dir(in_dir, cfg, recursive=recursive, use_llm=use_llm)
if files:
typer.secho(f"Embedded metadata in {len(files)} file(s).", fg=typer.colors.GREEN)
else:
typer.secho("No media files found to embed.", fg=typer.colors.YELLOW)
# --------------------
# Existing consolidated commands also get defaults + progress
# --------------------
@app.command()
def qc(
input_dir: Optional[str] = typer.Option(None, "--input-dir", "-i", help="Defaults to paths.in_root"),
site: str = typer.Option("all", help="adobe|shutterstock|pond5|all"),
json_out: Optional[Path] = typer.Option(None, "--json-out", "-o", help="Defaults to <in>/qc_report.json"),
recursive: bool = typer.Option(True, help="Recurse into subfolders"),
):
cfg = Config.load()
specs = load_specs(cfg.specs_path)
sites = None if site == "all" else [site]
in_dir = Path(input_dir or cfg.paths.in_root)
report_path = Path(json_out) if json_out else default_report_path(in_dir)
results = qc_all_helper(in_dir, cfg.encode.ffprobe, specs, sites=sites, recursive=recursive)
save_report(results, report_path)
summarize_console(results, report_path)
typer.secho(f"Wrote QC report: {report_path}", fg=typer.colors.GREEN)
@app.command()
def process(
input_dir: Optional[str] = typer.Option(None, "--input-dir", "-i", help="Defaults to paths.in_root"),
out_dir: Optional[str] = typer.Option(None, "--out-dir", "-o", help="Defaults to paths.out_root"),
no_hide_band: bool = typer.Option(False, "--no-hide-band", help="Disable bottom band hide filter"),
overwrite: bool = typer.Option(True, help="Overwrite outputs if they already exist"),
recursive: bool = typer.Option(True, help="Recurse into subfolders"),
require_qc: bool = typer.Option(True, "--require-qc/--no-require-qc", help="Refuse unless QC says OK"),
qc_report: Optional[Path] = typer.Option(None, "--qc-report", help="Defaults to <in>/qc_report.json"),
):
cfg = Config.load()
in_dir = Path(input_dir or cfg.paths.in_root)
out_root = Path(out_dir or cfg.paths.out_root)
out_root.mkdir(parents=True, exist_ok=True)
files = iter_media_files(in_dir, recursive=recursive)
if not files:
typer.secho("No media files found.", fg=typer.colors.YELLOW)
raise typer.Exit(code=1)
if require_qc:
report_path = qc_report or default_report_path(in_dir)
if not Path(report_path).exists():
typer.secho(f"Missing QC report: {report_path}. Run: python cli.py qc -i {in_dir} --site all", fg=typer.colors.RED)
raise typer.Exit(code=2)
report = load_report(report_path)
pass_idx = build_pass_index(report)
ok, bad = check_all_files_pass(files, pass_idx)
if not ok:
typer.secho("Some files failed QC or weren’t in the report:", fg=typer.colors.RED)
for b in bad: typer.echo(f" - {b}")
typer.secho(f"See report: {report_path}", fg=typer.colors.RED)
raise typer.Exit(code=2)
processed_entries: List[ManifestEntry] = []
N = len(files)
for i, src in enumerate(files):
prefix = f"[{i+1}/{N}] "
probe = probe_video(src, cfg.encode.ffprobe)
decision = decide_container(probe, cfg)
suffix = ".mp4" if decision.target == "mp4" else ".mov"
dst = out_root / f"{_output_stem(src.stem)}{suffix}"
if dst.exists() and not overwrite:
typer.secho(prefix + f"Skip (exists): {dst}", fg=typer.colors.YELLOW)
continue
typer.secho(prefix + f"Processing: {src.name} → {dst.name} [{decision.reason}]", fg=typer.colors.CYAN)
if decision.target == "mp4":
transcode_mp4(probe, src, dst, cfg, hide_band=(not no_hide_band))
else:
transcode_prores(probe, src, dst, cfg, hide_band=(not no_hide_band))
processed_entries.append(ManifestEntry(source=str(src.resolve()), output=str(dst.resolve()), qc_passed=True, ts=time.time()))
man_path = manifest_path_for(out_root)
append_entries(man_path, processed_entries)
typer.secho(f"Updated manifest: {man_path}", fg=typer.colors.GREEN)
typer.secho("Process complete.", fg=typer.colors.GREEN)
@app.command("make-csv")
def make_csv(
site: str = typer.Option("all", help="adobe|shutterstock|pond5|all"),
input_dir: Optional[str] = typer.Option(None, "--input-dir", "-i", help="Defaults to out/hideband_transcode/passed"),
recursive: bool = typer.Option(True, help="Recurse into subfolders"),
use_llm: bool = typer.Option(False, "--use-llm/--no-use-llm", help="Use LLM for cache misses before writing CSVs"),
):
cfg = Config.load()
csv_root = Path(cfg.paths.csv_root)
csv_root.mkdir(parents=True, exist_ok=True)
default_in = Path(cfg.paths.out_root) / "hideband_transcode" / "passed"
in_dir = Path(input_dir or default_in)
files = iter_media_files(in_dir, recursive=recursive)
if not files:
typer.secho("No media files found.", fg=typer.colors.YELLOW)
raise typer.Exit(code=1)
from stockflow.metadata.cache import load_master
from stockflow.metadata.llm import generate_texts_for_path, make_tracker
from stockflow.metadata.generate import ClipText
cache = load_master(cfg) # filename -> ClipText‑like
tracker = make_tracker(cfg)
rows_master = []
rows_sstk = []
rows_pond5 = []
rows_adobe = []
N = len(files)
for i, p in enumerate(files, 1):
prefix = f"[{i}/{N}] "
# cache or LLM
if p.name in cache:
c = cache[p.name]
texts = ClipText(c.title, c.description, list(c.keywords))
typer.secho(prefix + f"Using cached metadata for {p.name}", fg=typer.colors.CYAN)
else:
texts = generate_texts_for_path(p, cfg, use_llm=use_llm, cost=tracker)
typer.secho(prefix + f"Generated metadata for {p.name}", fg=typer.colors.MAGENTA)
# Build rows right here (no second pass and no extra LLM call)
rows_master.append(master.row_for(p, texts)) # (fn,title,desc,keywords) with ranking/stop‑words
rows_sstk.append(shutterstock.row_for(p, texts)) # uses clean_and_rank_keywords under the hood
rows_pond5.append(pond5.row_for(p, texts)) # now also uses clean_and_rank_keywords
rows_adobe.append(adobe.row_for(p, texts)) # uses clean_and_rank_keywords
# Write CSVs
master.write(csv_root / "master.csv", rows_master)
if site in ("all", "shutterstock"):
shutterstock.write(csv_root / "shutterstock.csv", rows_sstk)
if site in ("all", "pond5"):
pond5.write(csv_root / "pond5.csv", rows_pond5)
if site in ("all", "adobe"):
adobe.write(csv_root / "adobe.csv", rows_adobe)
# Cost summary if we used the LLM
if use_llm:
typer.secho(tracker.summary_str(), fg=typer.colors.GREEN)
tracker.append_run_log(cfg)
@app.command()
def upload(
site: str = typer.Argument(..., help="pond5 | shutterstock | adobe"),
src_dir: Optional[str] = typer.Option(
None, "--src-dir", "-s",
help="Defaults to <paths.out_root>/hideband_transcode/passed"
),
username: Optional[str] = typer.Option(None, "--user", help="Override username (else Keychain)"),
password: Optional[str] = typer.Option(None, "--password", help="Override password (else Keychain)"),
require_qc: bool = typer.Option(True, "--require-qc/--no-require-qc", help="Refuse unless outputs are in manifest as qc_passed"),
manifest: Optional[Path] = typer.Option(
None, "--manifest",
help="Defaults to <paths.out_root>/_stockflow_manifest.json"
),
):
cfg = Config.load()
default_src = Path(cfg.paths.out_root) / "hideband_transcode" / "passed"
src_dir = Path(src_dir) if src_dir else default_src
# Announce which site we're about to upload to
site_norm = site.lower()
site_label = site_norm.capitalize()
typer.secho(f"Starting upload to {site_label} from {src_dir}", fg=typer.colors.CYAN)
if require_qc:
# --- IMPORTANT: point at the manifest in the OUT ROOT
man_path = manifest or (Path(cfg.paths.out_root) / "_stockflow_manifest.json")
idx = build_output_pass_index(man_path)
files = [p for p in src_dir.glob("*") if p.is_file() and p.suffix.lower() in (".mp4", ".mov")]
bad = [p for p in files if idx.get(str(p.resolve())) is not True]
if bad:
typer.secho("Some outputs are missing from manifest or not qc_passed; refusing upload:", fg=typer.colors.RED)
for b in bad:
typer.echo(f" - {b}")
typer.secho(f"Manifest: {man_path}", fg=typer.colors.RED)
raise typer.Exit(code=2)
from stockflow.upload import pond5_ftp, shutterstock_ftps, adobe_sftp
results = []
if site_norm == "pond5":
results = pond5_ftp.upload_files(cfg, src_dir, username=username, password=password)
elif site_norm == "shutterstock":
results = shutterstock_ftps.upload_files(cfg, src_dir, username=username, password=password)
elif site_norm == "adobe":
results = adobe_sftp.upload_files(cfg, src_dir, username=username, password=password)
else:
typer.secho("Site must be one of: pond5 | shutterstock | adobe", fg=typer.colors.RED)
raise typer.Exit(code=2)
# Per-site completion announcement
typer.secho(f"{site_label} upload complete.", fg=typer.colors.GREEN)
# Write per-site report to ready-for-upload/auto-uploaded
try:
out_root = Path(Config.load().paths.out_root)
ready_dir = out_root / "ready-for-upload"
auto_dir = ready_dir / "auto-uploaded"
auto_dir.mkdir(parents=True, exist_ok=True)
report_path = auto_dir / f"{site_norm}_report.json"
report = {
"site": site_norm,
"timestamp": time.time(),
"src_dir": str(src_dir),
"results": results,
}
report_path.write_text(json.dumps(report, indent=2))
typer.secho(f"Wrote upload report: {report_path}", fg=typer.colors.GREEN)
except Exception as e:
typer.secho(f"Warning: failed to write upload report for {site_label}: {e}", fg=typer.colors.YELLOW)
@app.command()
def portals(
adobe: bool = typer.Option(True, help="Open Adobe portal"),
shutterstock: bool = typer.Option(True, help="Open Shutterstock portal"),
pond5: bool = typer.Option(True, help="Open Pond5 portal"),
):
cfg = Config.load()
which = []
if adobe: which.append("adobe")
if shutterstock: which.append("shutterstock")
if pond5: which.append("pond5")
open_portals(cfg, which=tuple(which))
if __name__ == "__main__":
app()
@app.command("debug-ftplist")
def debug_ftplist(site: str = typer.Argument(..., help="shutterstock | pond5"),
username: Optional[str] = typer.Option(None, "--user"),
password: Optional[str] = typer.Option(None, "--password")):
"""
Quick remote LIST to confirm files hit the provider's ingest server.
"""
cfg = Config.load()
if site.lower() == "shutterstock":
from stockflow.upload import shutterstock_ftps
entries = shutterstock_ftps.list_remote(cfg, cfg.sites.shutterstock, username=username, password=password)
typer.echo("\n".join(entries) if entries else "(no listing)")
elif site.lower() == "pond5":
from stockflow.upload import pond5_ftp
entries = pond5_ftp.list_remote(cfg, cfg.sites.pond5, username=username, password=password)
typer.echo("\n".join(entries) if entries else "(no listing)")
else:
typer.secho("Site must be one of: shutterstock | pond5", fg=typer.colors.RED)
raise typer.Exit(code=2)