Skip to content
Merged

Dev #13

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion static/studio-storage.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* Shared browser storage for generated maps and selected video materials. */
window.StudioStorage = (() => {
let connection;
let clearing = false;
function open() {
if (!connection) {
connection = new Promise((resolve, reject) => {
Expand Down Expand Up @@ -43,7 +44,9 @@ window.StudioStorage = (() => {
}

async function setAsset(key, file, metadata = {}) {
if (clearing) return;
const db = await open();
if (clearing) return;
const record = {
blob: file, name: file?.name, type: file?.type,
lastModified: file?.lastModified, updatedAt: Date.now(),
Expand All @@ -62,7 +65,9 @@ window.StudioStorage = (() => {

/* Run a read/write history transaction, pruning entries older than 24 hours. */
async function historyTransaction(action) {
if (clearing) return [];
const db = await open();
if (clearing) return [];
return new Promise((resolve, reject) => {
const transaction = db.transaction('history', 'readwrite');
const store = transaction.objectStore('history');
Expand Down Expand Up @@ -98,10 +103,47 @@ window.StudioStorage = (() => {
});
}

return {getAsset, setAsset, HISTORY_RETENTION_MS,
async function clearAll() {
clearing = true;
try {
const db = await open();
await new Promise((resolve, reject) => {
const transaction = db.transaction(['assets', 'history'], 'readwrite');
transaction.objectStore('assets').clear();
transaction.objectStore('history').clear();
transaction.oncomplete = resolve;
transaction.onabort = () => reject(transaction.error || new Error('Could not clear browser data.'));
transaction.onerror = () => reject(transaction.error);
});
} catch (error) {
clearing = false;
throw error;
}
}

return {getAsset, setAsset, clearAll, HISTORY_RETENTION_MS,
getHistory: () => historyTransaction(),
pruneHistory: () => historyTransaction({prune: true}),
addHistory: entry => historyTransaction({entry}),
clearHistory: () => historyTransaction({clear: true}),
};
})();

/* Reset both studios together; cookies and server credentials are unaffected. */
async function clearAllUserData(button) {
if (!window.confirm('Clear all data? This removes saved API keys, topics, settings, run history, maps, and selected video/audio materials from this browser. This cannot be undone.')) return;
button.disabled = true;
try {
await StudioStorage.clearAll();
for (const storage of [localStorage, sessionStorage]) {
for (const key of Object.keys(storage)) {
if (/^automap[-_]/.test(key)) storage.removeItem(key);
}
}
// Navigate to a fresh document so inputs and in-memory previews reset too.
window.location.replace(window.location.pathname);
} catch (error) {
button.disabled = false;
window.alert('Could not clear all data. Please allow browser storage and try again.');
}
}
1 change: 1 addition & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ <h1 class="font-display font-bold text-lg tracking-tight bg-gradient-to-r from-w
<span>Video Studio</span>
<i class="fa-solid fa-arrow-right text-[10px] opacity-75 group-hover:translate-x-0.5 transition-transform"></i>
</a>
<button type="button" id="clearAllDataBtn" onclick="clearAllUserData(this)" class="px-3 py-2 rounded-xl bg-slate-900/90 hover:bg-rose-950 text-rose-300 border border-rose-500/30 text-xs font-semibold transition-all shrink-0">Clear all data</button>
{% if config.WEB_AUTH_ENABLED and session.get('web_identity') %}
<form method="post" action="{{ url_for('web_logout') }}">
<input type="hidden" name="csrf_token" value="{{ session.get('logout_csrf', '') }}">
Expand Down
1 change: 1 addition & 0 deletions templates/video.html
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ <h1 class="font-display font-bold text-lg tracking-tight text-white">AutoMap Vid
<span class="text-indigo-400 font-semibold">03 Frame &amp; Render</span>
</div>

<button type="button" id="clearAllDataBtn" onclick="clearAllUserData(this)" class="px-3 py-2 rounded-xl bg-slate-900/90 hover:bg-rose-950 text-rose-300 border border-rose-500/30 text-xs font-semibold transition-all shrink-0">Clear all data</button>
{% if config.WEB_AUTH_ENABLED and session.get('web_identity') %}
<form method="post" action="{{ url_for('web_logout') }}">
<input type="hidden" name="csrf_token" value="{{ session.get('logout_csrf', '') }}">
Expand Down
28 changes: 28 additions & 0 deletions tests/browser/test_video_studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,3 +666,31 @@ def test_new_stickers_exist_on_both_sides_and_preview_offline(studio):
page.wait_for_function("document.querySelector('#stageTopLeftSticker img')?.naturalWidth > 0")
page.wait_for_function("document.querySelector('#stageTopRightSticker img')?.naturalWidth > 0")
assert page.locator('#stageCompositeBox').evaluate("el => el.classList.contains('has-top-stickers')")


def test_clear_all_data_requires_confirmation_and_clears_both_studios(studio):
page, _ = studio
page.evaluate("""async () => {
localStorage.setItem('automap-gemini-api-key', 'private-key');
localStorage.setItem('automap-map-topic', 'saved topic');
localStorage.setItem('unrelated-setting', 'keep');
sessionStorage.setItem('automap-test', 'session value');
await StudioStorage.setAsset('latest-map', new File(['map'], 'map.png'));
await StudioStorage.addHistory({id: 'test', createdAt: Date.now(), state: {topic: 'saved topic'}});
}""")
page.once('dialog', lambda dialog: dialog.dismiss())
page.locator('#clearAllDataBtn').click()
assert page.evaluate("localStorage.getItem('automap-gemini-api-key')") == 'private-key'
assert page.evaluate("async () => (await StudioStorage.getHistory()).length") == 1
page.once('dialog', lambda dialog: dialog.accept())
with page.expect_navigation():
page.locator('#clearAllDataBtn').click()
assert page.evaluate("localStorage.getItem('automap-gemini-api-key')") is None
assert page.evaluate("localStorage.getItem('automap-map-topic')") is None
assert page.evaluate("sessionStorage.getItem('automap-test')") is None
assert page.evaluate("localStorage.getItem('unrelated-setting')") == 'keep'
assert page.evaluate("async () => await StudioStorage.getAsset('latest-map')") is None
assert page.evaluate("async () => await StudioStorage.getHistory()") == []
page.goto('http://automap.test/')
assert page.locator('#clearAllDataBtn').is_visible()
assert page.locator('#topicInput').input_value() == ''
30 changes: 20 additions & 10 deletions yt-dlp_serv.py
Original file line number Diff line number Diff line change
Expand Up @@ -813,18 +813,28 @@ def _veil_mask(t: float) -> np.ndarray:
try: # pragma: no cover
import automap_rs

def _to_rgba_bytes(arr: np.ndarray) -> bytes:
# Ensure 4-channel RGBA layout before passing raw bytes to Rust.
if arr.shape[2] == 3:
if not hasattr(automap_rs, "render_video_rs"):
raise ImportError("automap_rs native extension not built")

def _clip_to_rgba_bytes(clip_obj, sample_t: float = 0.0) -> bytes:
# MoviePy splits RGBA inputs into 3-channel clip.img + float clip.mask.
arr = np.asarray(clip_obj.img, dtype=np.uint8)
if arr.ndim == 3 and arr.shape[2] == 4:
return arr.tobytes()
if getattr(clip_obj, "mask", None) is not None:
mask_frame = np.asarray(clip_obj.mask.get_frame(sample_t))
alpha = np.clip(mask_frame * 255.0, 0, 255).astype(np.uint8)
if alpha.ndim == 2:
alpha = alpha[:, :, None]
else:
alpha = np.full((arr.shape[0], arr.shape[1], 1), 255, dtype=np.uint8)
arr = np.concatenate([arr, alpha], axis=2)
return arr.tobytes()
return np.concatenate([arr[:, :, :3], alpha], axis=2).tobytes()

static_rgba = None
dynamic_overlays = []
veil_duration = 0.0

# Skip clips[0] (background_video); Rust decodes it directly from bg_path.
# Skip clips[0] (background_video); Rust decodes it directly from prepared_bg_path.
for clip in clips[1:]:
if not hasattr(clip, "img"):
continue
Expand All @@ -833,7 +843,7 @@ def _to_rgba_bytes(arr: np.ndarray) -> bytes:
is_full_canvas = clip.img.shape[:2] == (canvas_h, canvas_w)

if not is_dynamic and is_full_canvas:
static_rgba = _to_rgba_bytes(clip.img)
static_rgba = _clip_to_rgba_bytes(clip, 0.0)
elif is_dynamic and is_full_canvas and clip.img.shape[2] == 3:
# Full-canvas 3-channel black clip represents the intro fade veil.
veil_duration = float(clip.duration or 0.0)
Expand All @@ -843,11 +853,11 @@ def _to_rgba_bytes(arr: np.ndarray) -> bytes:
h, w = clip.img.shape[:2]
x = (canvas_w - w) // 2 if pos[0] == "center" else int(pos[0])
y = (canvas_h - h) // 2 if pos[1] == "center" else int(pos[1])
dynamic_overlays.append((_to_rgba_bytes(clip.img), x, y, int(w), int(h), 0.0, 0.0))
dynamic_overlays.append((_clip_to_rgba_bytes(clip, float(bg_duration)), x, y, int(w), int(h), 0.0, 0.0))

if static_rgba is not None and bg_path:
if static_rgba is not None and prepared_bg_path:
automap_rs.render_video_rs(
bg_path,
prepared_bg_path,
static_rgba,
dynamic_overlays,
veil_duration,
Expand Down
Loading