feat(cloud): user-friendly job logs + transcription progress; hide auto profile id in header

- log_view.py: whitelist-based cloud log view — transcription percentage,
  clip counters, errors; no file paths, model names or pipeline internals.
  Self-host (BILLING off) and DEBUG_LOGS keep the full raw output.
- transcribe_backends: emit '🎙️ Transcribing… NN% (Xs)' at 25% steps from
  both parakeet and whisper paths.
- dashboard: profile selector shows connected networks instead of the
  auto-generated os_<hash> id.
This commit is contained in:
juancarlos.cavero 2026-07-18 02:20:31 +02:00
parent 913c461b9b
commit 8160fc6465
5 changed files with 189 additions and 20 deletions

20
app.py
View file

@ -560,26 +560,18 @@ def _visible_logs(logs):
"""Logs to surface to the client.
Self-host (BILLING off) shows the full pipeline output so people running
their own instance can debug. Cloud shows only the pipeline's own friendly
progress lines (emoji-prefixed, plus the worker's start/finish markers),
minus any ingest plumbing (proxy / downloader / cookies) — paying users
just want to see analysis and rendering progress.
their own instance can debug. Cloud shows a curated whitelist view
(log_view.friendly_logs): plain progress for normal users — transcription
percentage, clip counters — with no file paths, model names or pipeline
internals.
DEBUG_LOGS=true forces the full output even under billing — for local dev
where you run in paid mode but still want the raw logs.
"""
if not BILLING_ENABLED or DEBUG_LOGS:
return logs
visible = []
for ln in logs:
s = ln.lstrip()
if not s:
continue
if _SENSITIVE_LOG_RE.search(ln):
continue
if s.startswith(("Job started", "Process finished")) or ord(s[0]) > 0x2000:
visible.append(ln)
return visible
from log_view import friendly_logs
return friendly_logs(logs)
def enqueue_output(out, job_id):

View file

@ -67,12 +67,31 @@ const TikTokIcon = ({ size = 16, className = "" }) => (
</svg>
);
// Cloud accounts get an auto-generated opaque id (os_<hash>) as username —
// meaningless to the user, so the selector shows connected networks instead.
const isAutoProfileId = (username) => /^os_[0-9a-f]/i.test(username || "");
const ProfileNetworkIcons = ({ profile, size = 12 }) => (
<span className="flex items-center gap-1.5">
<span className={profile?.connected?.includes('tiktok') ? 'text-ink' : 'text-muted opacity-40'}>
<TikTokIcon size={size} />
</span>
<span className={profile?.connected?.includes('instagram') ? 'text-ink' : 'text-muted opacity-40'}>
<Instagram size={size} />
</span>
<span className={profile?.connected?.includes('youtube') ? 'text-ink' : 'text-muted opacity-40'}>
<Youtube size={size} />
</span>
</span>
);
const UserProfileSelector = ({ profiles, selectedUserId, onSelect }) => {
const [isOpen, setIsOpen] = useState(false);
if (!profiles || profiles.length === 0) return null;
const selectedProfile = profiles.find(p => p.username === selectedUserId) || profiles[0];
const autoId = isAutoProfileId(selectedProfile?.username);
return (
<div className="relative z-50">
@ -82,9 +101,13 @@ const UserProfileSelector = ({ profiles, selectedUserId, onSelect }) => {
>
<span className="flex items-center gap-2">
<div className="w-5 h-5 rounded-full bg-paper3 border border-rule flex items-center justify-center font-mono text-micro text-brass">
{selectedProfile?.username?.substring(0, 1).toUpperCase() || "U"}
{autoId ? "S" : (selectedProfile?.username?.substring(0, 1).toUpperCase() || "U")}
</div>
<span className="font-medium text-ink truncate max-w-[100px]">{selectedProfile?.username || "Select User"}</span>
{autoId ? (
<ProfileNetworkIcons profile={selectedProfile} size={13} />
) : (
<span className="font-medium text-ink truncate max-w-[100px]">{selectedProfile?.username || "Select User"}</span>
)}
</span>
<ChevronDown size={14} className={`text-muted transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</button>
@ -103,11 +126,13 @@ const UserProfileSelector = ({ profiles, selectedUserId, onSelect }) => {
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-paper3 flex items-center justify-center font-mono text-micro text-ink border border-rule shrink-0">
{profile.username.substring(0, 2).toUpperCase()}
{isAutoProfileId(profile.username) ? "S" : profile.username.substring(0, 2).toUpperCase()}
</div>
<div className="min-w-0">
<div className="text-sm font-medium text-ink2 group-hover:text-ink transition-colors truncate">
{profile.username}
{isAutoProfileId(profile.username)
? `Social profile ${profiles.indexOf(profile) + 1}`
: profile.username}
</div>
<div className="flex gap-2 mt-0.5">
{/* Status indicators */}

54
log_view.py Normal file
View file

@ -0,0 +1,54 @@
"""Cloud-facing job log view.
Self-hosted instances see the raw pipeline output (useful for debugging).
Cloud/paying users get a curated, whitelist-based view: friendly progress
lines only — no file paths, model names, encoder details or pipeline
internals. Anything not matched by a rule is hidden.
"""
import re
# Strips any slashy path token (output/…/clip.mp4, /app/uploads/x.mp4, …).
_PATH_RE = re.compile(r'(?:/?[\w.\-]+/)+[\w.\-]+')
def _strip_paths(line):
return _PATH_RE.sub('', line).rstrip(' :')
# Ordered rules; first match wins. Replacement is a template using the
# match's groups, or None to keep the (path-stripped) line verbatim.
_RULES = [
# Worker/job lifecycle + errors: keep, minus any paths.
(re.compile(r'^(Job started|Process finished|Process failed|'
r'Execution error|No metadata|❌)'), None),
# Live transcription progress emitted by transcribe_backends.
(re.compile(r'^🎙️ Transcribing… \d+%'), None),
(re.compile(r'Transcribing (video|audio)'), '🎙️ Transcribing audio…'),
(re.compile(r'Found (\d+) viral clips'), '🔥 Found {0} viral clips!'),
(re.compile(r'Processing Clip (\d+)'), '🎬 Creating clip {0}…'),
(re.compile(r'Clip (\d+) ready'), '✅ Clip {0} ready'),
]
def friendly_log_line(line):
"""Map one raw log line to its cloud-visible form, or None to hide it."""
stripped = line.strip()
if not stripped:
return None
for pattern, template in _RULES:
match = pattern.search(stripped)
if match:
if template is None:
return _strip_paths(stripped)
return template.format(*match.groups())
return None
def friendly_logs(logs):
"""Curated log list for cloud users, consecutive duplicates collapsed."""
out = []
for line in logs:
friendly = friendly_log_line(line)
if friendly and (not out or out[-1] != friendly):
out.append(friendly)
return out

61
tests/test_log_view.py Normal file
View file

@ -0,0 +1,61 @@
from log_view import friendly_log_line, friendly_logs
# Raw lines captured from a real production job.
RAW_JOB = [
"Job started by worker.",
"🎙️ Transcribing video...",
"🎙️ Transcribing… 25% (3s)",
"🎙️ Transcribing… 100% (7s)",
"🎙️ [ASR] parakeet ok: lang=es segments=43",
"🔥 Found 2 viral clips!",
"🎬 Processing Clip 1: 0.004s - 35.336s",
"🎞️ [Encoder] video encoder: h264_nvenc (FFMPEG_ENCODER=auto)",
"🎬 Processing clip: output/e7f00666/temp_e7f00666_agente-ia_clip_1.mp4",
"✅ Found 2 scenes.",
"🧠 Step 2: Preparing Active Tracking...",
"🤖 Step 3: Analyzing Scenes for Strategy (Single vs Group)...",
"✂️ Step 4: Processing video frames...",
"🔊 Step 5: Extracting audio...",
"✨ Step 6: Merging...",
"✅ Clip saved to output/e7f00666/e7f00666_agente-ia_clip_1.mp4",
"✅ Clip 1 ready: output/e7f00666/e7f00666_agente-ia_clip_1.mp4",
"Process finished successfully.",
]
def test_real_job_produces_clean_user_view():
assert friendly_logs(RAW_JOB) == [
"Job started by worker.",
"🎙️ Transcribing audio…",
"🎙️ Transcribing… 25% (3s)",
"🎙️ Transcribing… 100% (7s)",
"🔥 Found 2 viral clips!",
"🎬 Creating clip 1…",
"✅ Clip 1 ready",
"Process finished successfully.",
]
def test_no_paths_ever_leak():
for line in friendly_logs(RAW_JOB):
assert "output/" not in line
assert ".mp4" not in line
def test_technical_lines_are_hidden():
assert friendly_log_line("🎙️ [ASR] parakeet ok: lang=es segments=43") is None
assert friendly_log_line("🎞️ [Encoder] video encoder: h264_nvenc") is None
assert friendly_log_line("🧠 Step 2: Preparing Active Tracking...") is None
assert friendly_log_line("yt-dlp downloading format 137") is None
def test_errors_kept_without_paths():
assert friendly_log_line("Process failed with exit code 1") == \
"Process failed with exit code 1"
out = friendly_log_line("❌ Could not read output/abc/clip.mp4")
assert out is not None and "output/" not in out
def test_consecutive_duplicates_collapse():
logs = ["🎙️ Transcribing video...", "🎙️ Transcribing audio from: x.mp4"]
assert friendly_logs(logs) == ["🎙️ Transcribing audio…"]

View file

@ -27,6 +27,7 @@ import os
import subprocess
import tempfile
import threading
import time
from subtitles import (
get_whisper_config,
@ -59,6 +60,28 @@ class _NullGate:
_NULL_GATE = _NullGate()
class _TranscribeProgress:
"""Emits '🎙️ Transcribing… NN% (Xs)' lines at 25% steps.
These are the only transcription lines cloud users see (log_view keeps
them), so they must stay free of technical detail.
"""
def __init__(self, total_seconds):
self.total = max(float(total_seconds or 0), 0.0)
self.started = time.time()
self.next_pct = 25
def update(self, position_seconds):
if self.total <= 0:
return
pct = min(int(position_seconds / self.total * 100), 100)
while pct >= self.next_pct and self.next_pct <= 100:
elapsed = int(time.time() - self.started)
print(f"🎙️ Transcribing… {self.next_pct}% ({elapsed}s)", flush=True)
self.next_pct += 25
# --- whisper singleton ------------------------------------------------------
_whisper_model = None
@ -94,7 +117,12 @@ def run_whisper_transcription(media_path, **params):
gate = _ASR_GATE if device != "cpu" else _NULL_GATE
with gate:
segments, info = model.transcribe(media_path, **params)
return list(segments), info
progress = _TranscribeProgress(getattr(info, "duration", 0))
materialized = []
for segment in segments:
materialized.append(segment)
progress.update(segment.end)
return materialized, info
def _transcribe_with_whisper(media_path):
@ -194,8 +222,17 @@ def _transcribe_with_parakeet(media_path):
model = _get_parakeet_model()
wav_path = _extract_wav(media_path)
try:
# 16kHz mono s16le wav -> 32000 bytes per second of audio.
try:
duration = os.path.getsize(wav_path) / 32000.0
except OSError:
duration = 0.0
with _ASR_GATE:
results = list(model.recognize(wav_path))
progress = _TranscribeProgress(duration)
results = []
for seg in model.recognize(wav_path):
results.append(seg)
progress.update(float(seg.end))
finally:
try:
os.remove(wav_path)