2Btainment commited on
Commit
36de25c
·
verified ·
1 Parent(s): db3e932

P2.4: per-file metadata, versions, streamed downloads

Browse files
Files changed (8) hide show
  1. app.js +5 -5
  2. avatar.js +1 -1
  3. index.html +2 -2
  4. master.js +1 -1
  5. real.js +3 -2
  6. server/main.py +114 -27
  7. style.css +1 -0
  8. workspace.js +11 -4
app.js CHANGED
@@ -1,10 +1,10 @@
1
  import * as THREE from './vendor/three.module.min.js';
2
  import { STUDIOS, stopLoops } from './widgets.js?v=50';
3
- import './real.js?v=60';
4
- import './avatar.js?v=60';
5
- import './master.js?v=60';
6
- import './workspace.js?v=60';
7
- import { icon } from './icons.js?v=60';
8
  import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
9
  import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
10
  import { RenderPass } from './vendor/addons/postprocessing/RenderPass.js';
 
1
  import * as THREE from './vendor/three.module.min.js';
2
  import { STUDIOS, stopLoops } from './widgets.js?v=50';
3
+ import './real.js?v=61';
4
+ import './avatar.js?v=61';
5
+ import './master.js?v=61';
6
+ import './workspace.js?v=61';
7
+ import { icon } from './icons.js?v=61';
8
  import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
9
  import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
10
  import { RenderPass } from './vendor/addons/postprocessing/RenderPass.js';
avatar.js CHANGED
@@ -1,7 +1,7 @@
1
  // Avatar / Persona studio (DoD): persistent avatars as workspace asset type `avatar`
2
  // avatars/<slug>/avatar.json + ref.webp + voice.wav · reused by Chat, Image (Kontext), agents.
3
  import { STUDIOS, onStop } from './widgets.js?v=50';
4
- import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, LS, FLUX, KONTEXT, TTS, CHAT, signedIn } from './real.js?v=60';
5
 
6
  const LANGS = ['German', 'English', 'French', 'Spanish', 'Auto'];
7
  const slug = (n) => (n || 'avatar').toLowerCase().normalize('NFKD').replace(/[^\w]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'avatar';
 
1
  // Avatar / Persona studio (DoD): persistent avatars as workspace asset type `avatar`
2
  // avatars/<slug>/avatar.json + ref.webp + voice.wav · reused by Chat, Image (Kontext), agents.
3
  import { STUDIOS, onStop } from './widgets.js?v=50';
4
+ import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, LS, FLUX, KONTEXT, TTS, CHAT, signedIn } from './real.js?v=61';
5
 
6
  const LANGS = ['German', 'English', 'French', 'Spanish', 'Auto'];
7
  const slug = (n) => (n || 'avatar').toLowerCase().normalize('NFKD').replace(/[^\w]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'avatar';
index.html CHANGED
@@ -8,7 +8,7 @@
8
  <title>STUDIUS · DAS Studio — Einswarm</title>
9
  <link rel="icon" href="assets/einswarm-mascot.webp">
10
  <link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
11
- <link rel="stylesheet" href="style.css?v=60">
12
  </head>
13
  <body>
14
  <canvas id="gl"></canvas>
@@ -49,6 +49,6 @@
49
 
50
  <a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
51
  <noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
52
- <script type="module" src="app.js?v=60"></script>
53
  </body>
54
  </html>
 
8
  <title>STUDIUS · DAS Studio — Einswarm</title>
9
  <link rel="icon" href="assets/einswarm-mascot.webp">
10
  <link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
11
+ <link rel="stylesheet" href="style.css?v=61">
12
  </head>
13
  <body>
14
  <canvas id="gl"></canvas>
 
49
 
50
  <a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
51
  <noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
52
+ <script type="module" src="app.js?v=61"></script>
53
  </body>
54
  </html>
master.js CHANGED
@@ -1,7 +1,7 @@
1
  // Mastering studio (DoD): client-side WebAudio chain EQ → compressor → limiter, loudness normalisation to target LUFS
2
  // (ITU-R BS.1770-4 K-weighting + gating, measured offline), live meter, A/B, WAV/MP3 export, save to workspace.
3
  import { STUDIOS, onStop, loop, cv } from './widgets.js?v=50';
4
- import { result, MODULES, esc, setS, keep } from './real.js?v=60';
5
 
6
  /* ---------- BS.1770 loudness ---------- */
7
  function biquad(x, b0, b1, b2, a0, a1, a2) { const y = new Float32Array(x.length); b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0; let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
 
1
  // Mastering studio (DoD): client-side WebAudio chain EQ → compressor → limiter, loudness normalisation to target LUFS
2
  // (ITU-R BS.1770-4 K-weighting + gating, measured offline), live meter, A/B, WAV/MP3 export, save to workspace.
3
  import { STUDIOS, onStop, loop, cv } from './widgets.js?v=50';
4
+ import { result, MODULES, esc, setS, keep } from './real.js?v=61';
5
 
6
  /* ---------- BS.1770 loudness ---------- */
7
  function biquad(x, b0, b1, b2, a0, a1, a2) { const y = new Float32Array(x.length); b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0; let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
real.js CHANGED
@@ -49,7 +49,8 @@ async function runUser(space, ep, data, { onStatus = () => {}, onData = () => {}
49
  window.__studiusLog.push({ space, ep, via: 'user', ms: Math.round(performance.now() - t0) }); return last;
50
  }
51
  export const signedIn = () => !!window.__ws?.me?.signedIn;
52
- export async function run(space, ep, data, opt = {}) {
 
53
  if (signedIn()) {
54
  try { const d = await runUser(space, ep, data, opt); opt.el && via(opt.el, 'user'); return d; }
55
  catch (e) { if (e.message === 'abgebrochen' || (opt.el && !opt.el.isConnected)) throw e; console.warn('user-quota run failed, trying anonymous:', e.message); opt.onStatus?.({ stage: 'pending', message: 'Deine Quota: ' + e.message + ' → anonym' }); }
@@ -71,7 +72,7 @@ async function dl(a, src, name) { // cross-origin download → blob URL
71
  function timer(el, sel) { const t0 = performance.now(); const s = el.querySelector(sel); return every(() => { if (s && s.dataset.base) s.textContent = s.dataset.base + ' · ' + ((performance.now() - t0) / 1000).toFixed(0) + ' s'; }, 1000); }
72
  const setS = (el, txt, err) => { const s = el.querySelector('.stat'); if (!s) return; s.dataset.base = txt; s.textContent = txt; s.classList.toggle('err', !!err); };
73
  /** typed asset bus: every studio result is announced; workspace.js adds 'Save to Workspace' + 'Send to…' */
74
- export const result = (el, asset) => { window.__lastAsset = asset; window.dispatchEvent(new CustomEvent('studius-result', { detail: { el, asset } })); };
75
  const S = (id) => STUDIOS.find(s => s.id === id);
76
  const keep = (el) => el.querySelectorAll('input,textarea').forEach(i => i.addEventListener('keydown', e => e.stopPropagation()));
77
 
 
49
  window.__studiusLog.push({ space, ep, via: 'user', ms: Math.round(performance.now() - t0) }); return last;
50
  }
51
  export const signedIn = () => !!window.__ws?.me?.signedIn;
52
+ let LASTM = '';
53
+ export async function run(space, ep, data, opt = {}) { LASTM = space;
54
  if (signedIn()) {
55
  try { const d = await runUser(space, ep, data, opt); opt.el && via(opt.el, 'user'); return d; }
56
  catch (e) { if (e.message === 'abgebrochen' || (opt.el && !opt.el.isConnected)) throw e; console.warn('user-quota run failed, trying anonymous:', e.message); opt.onStatus?.({ stage: 'pending', message: 'Deine Quota: ' + e.message + ' → anonym' }); }
 
72
  function timer(el, sel) { const t0 = performance.now(); const s = el.querySelector(sel); return every(() => { if (s && s.dataset.base) s.textContent = s.dataset.base + ' · ' + ((performance.now() - t0) / 1000).toFixed(0) + ' s'; }, 1000); }
73
  const setS = (el, txt, err) => { const s = el.querySelector('.stat'); if (!s) return; s.dataset.base = txt; s.textContent = txt; s.classList.toggle('err', !!err); };
74
  /** typed asset bus: every studio result is announced; workspace.js adds 'Save to Workspace' + 'Send to…' */
75
+ export const result = (el, asset) => { if (!asset.model && LASTM && /^(\/api\/tmp\/|https:)/.test(asset.url || '')) asset.model = LASTM; window.__lastAsset = asset; window.dispatchEvent(new CustomEvent('studius-result', { detail: { el, asset } })); };
76
  const S = (id) => STUDIOS.find(s => s.id === id);
77
  const keep = (el) => el.querySelectorAll('input,textarea').forEach(i => i.addEventListener('keydown', e => e.stopPropagation()));
78
 
server/main.py CHANGED
@@ -4,7 +4,7 @@ import os, io, json, time, secrets, base64, tempfile, mimetypes, urllib.parse, r
4
  from pathlib import Path
5
  import httpx
6
  from fastapi import FastAPI, Request, UploadFile, File, Form, HTTPException
7
- from fastapi.responses import RedirectResponse, JSONResponse, FileResponse, Response
8
  from fastapi.staticfiles import StaticFiles
9
  from huggingface_hub import HfApi
10
  from .infer import make_router, tmp_path
@@ -107,27 +107,70 @@ def ws_connect(req: Request, bucket: str = Form(...), create: bool = Form(False)
107
  return {"bucket": info.id, "private": info.private}
108
  except Exception as e: herr(e)
109
 
110
- def META(api, bucket):
 
 
 
 
 
111
  try:
112
  with tempfile.TemporaryDirectory() as d:
113
  api.download_bucket_files(bucket, [(".studius/assets.json", f"{d}/a.json")]); return json.loads(Path(f"{d}/a.json").read_text())
114
  except Exception: return {}
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  @app.get("/api/ws/list")
117
  def ws_list(req: Request, bucket: str, prefix: str = ""):
118
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s)
119
  try:
120
- meta = META(api, bucket); out = []
121
- for f in api.list_bucket_tree(bucket, prefix=prefix or None, recursive=True):
122
- if getattr(f, "type", "") != "file" or f.path.startswith(".studius/"): continue
123
- out.append({"path": f.path, "size": f.size, "mtime": f.mtime.isoformat() if f.mtime else None, "mime": mimetypes.guess_type(f.path)[0] or "application/octet-stream", **({"meta": meta[f.path]} if f.path in meta else {})})
 
 
 
 
124
  return {"bucket": bucket, "files": sorted(out, key=lambda x: x["mtime"] or "", reverse=True)}
125
  except Exception as e: herr(e)
126
 
127
  def put(api, bucket, data: bytes, path: str, meta: dict):
128
- m = META(api, bucket); m[path] = {**meta, "saved": int(time.time()), "v": m.get(path, {}).get("v", 0) + 1}
129
- api.batch_bucket_files(bucket, add=[(data, path), (json.dumps(m, indent=1).encode(), ".studius/assets.json")])
130
- return {"path": path, "size": len(data), "meta": m[path]}
 
 
131
 
132
  @app.post("/api/ws/upload")
133
  async def ws_upload(req: Request, bucket: str = Form(...), path: str = Form(""), studio: str = Form("upload"), file: UploadFile = File(...)):
@@ -135,54 +178,98 @@ async def ws_upload(req: Request, bucket: str = Form(...), path: str = Form(""),
135
  data = await file.read(MAX_UP + 1)
136
  if len(data) > MAX_UP: raise HTTPException(413, "max 200 MB")
137
  p = safe(path or f"uploads/{file.filename}")
138
- try: return put(api, bucket, data, p, {"studio": studio, "mime": file.content_type})
139
  except Exception as e: herr(e)
140
 
141
  @app.post("/api/ws/save-url")
142
- async def ws_save_url(req: Request, bucket: str = Form(...), url: str = Form(...), path: str = Form(...), studio: str = Form(""), prompt: str = Form("")):
143
- """Save a studio result (public *.hf.space file URL) into the workspace server-side."""
144
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s)
145
  if url.startswith("/api/tmp/"):
146
  lp = tmp_path(url)
147
  if not lp: raise HTTPException(410, "result expired")
148
- content = Path(lp).read_bytes()
149
  else:
150
  if not ALLOW_FETCH.match(url): raise HTTPException(400, "only *.hf.space result URLs")
151
  async with httpx.AsyncClient(timeout=60, follow_redirects=True) as c:
152
  r = await c.get(url)
153
  if r.status_code != 200 or len(r.content) > MAX_UP: raise HTTPException(502, "fetch failed")
154
- content = r.content
155
- try: return put(api, bucket, content, safe(path), {"studio": studio, "prompt": prompt[:500], "source": url.split("/gradio_api")[0].split("/file=")[0]})
156
  except Exception as e: herr(e)
157
 
158
- @app.get("/api/ws/file")
159
- def ws_file(req: Request, bucket: str, path: str, dl: int = 0):
 
 
 
 
 
 
160
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
161
  try:
162
- d = tempfile.mkdtemp(); out = f"{d}/f"; api.download_bucket_files(bucket, [(p, out)], raise_on_missing_files=True)
163
- data = Path(out).read_bytes(); os.remove(out); os.rmdir(d)
 
 
 
 
164
  except Exception as e: herr(e)
165
- mt = mimetypes.guess_type(p)[0] or "application/octet-stream"
166
- h = {"Cache-Control": "private, no-store"}
167
- if dl: h["Content-Disposition"] = f'attachment; filename="{Path(p).name}"'
168
- return Response(data, media_type=mt, headers=h)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  @app.post("/api/ws/delete")
171
  def ws_delete(req: Request, bucket: str = Form(...), path: str = Form(...), confirm: str = Form("")):
 
172
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
173
  if confirm != p: raise HTTPException(400, "confirm must equal path")
174
  try:
175
- m = META(api, bucket); m.pop(p, None)
176
- api.batch_bucket_files(bucket, delete=[p], add=[(json.dumps(m, indent=1).encode(), ".studius/assets.json")]); return {"deleted": p}
 
177
  except Exception as e: herr(e)
178
 
179
  @app.post("/api/ws/pin")
180
  def ws_pin(req: Request, bucket: str = Form(...), path: str = Form(...), studio: str = Form(...), on: bool = Form(True)):
181
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
182
  try:
183
- m = META(api, bucket); e = m.setdefault(p, {}); pins = set(e.get("pins", []))
184
  (pins.add if on else pins.discard)(studio); e["pins"] = sorted(pins)
185
- api.batch_bucket_files(bucket, add=[(json.dumps(m, indent=1).encode(), ".studius/assets.json")]); return {"path": p, "pins": e["pins"]}
186
  except Exception as e: herr(e)
187
 
188
  @app.middleware("http")
 
4
  from pathlib import Path
5
  import httpx
6
  from fastapi import FastAPI, Request, UploadFile, File, Form, HTTPException
7
+ from fastapi.responses import RedirectResponse, JSONResponse, FileResponse, Response, StreamingResponse
8
  from fastapi.staticfiles import StaticFiles
9
  from huggingface_hub import HfApi
10
  from .infer import make_router, tmp_path
 
107
  return {"bucket": info.id, "private": info.private}
108
  except Exception as e: herr(e)
109
 
110
+ # ---- per-file sidecar metadata (.studius/meta/<path>.json) + versions (.studius/versions/<path>/v<N>__<name>) ----
111
+ HUB = os.environ.get("HF_ENDPOINT", "https://huggingface.co")
112
+ MD = ".studius/meta/"; VD = ".studius/versions/"
113
+ def mpath(p): return f"{MD}{p}.json"
114
+
115
+ def legacy(api, bucket): # read-only fallback for Phase-1 single index (never written anymore)
116
  try:
117
  with tempfile.TemporaryDirectory() as d:
118
  api.download_bucket_files(bucket, [(".studius/assets.json", f"{d}/a.json")]); return json.loads(Path(f"{d}/a.json").read_text())
119
  except Exception: return {}
120
 
121
+ def metas(api, bucket, paths):
122
+ """Batch-download sidecars for paths -> {path: meta}."""
123
+ out = {}; paths = list(paths)
124
+ if not paths: return out
125
+ with tempfile.TemporaryDirectory() as d:
126
+ pairs = [(mpath(p), f"{d}/{i}.json") for i, p in enumerate(paths)]
127
+ try: api.download_bucket_files(bucket, pairs, raise_on_missing_files=False)
128
+ except TypeError: api.download_bucket_files(bucket, pairs)
129
+ except Exception: pass
130
+ for i, p in enumerate(paths):
131
+ f = Path(f"{d}/{i}.json")
132
+ if f.exists():
133
+ try: out[p] = json.loads(f.read_text())
134
+ except Exception: pass
135
+ return out
136
+
137
+ def getmeta(api, bucket, p):
138
+ m = metas(api, bucket, [p]).get(p)
139
+ return m if m is not None else legacy(api, bucket).get(p, {})
140
+
141
+ def info(api, bucket, p):
142
+ r = list(api.get_bucket_paths_info(bucket, [p])); return r[0] if r else None
143
+
144
+ def snapshot(api, bucket, p, m):
145
+ """Server-side copy (by xet hash) of the current file into versions/ before overwrite/delete."""
146
+ cur = info(api, bucket, p)
147
+ if not cur: return None
148
+ v = int(m.get("v", 1) or 1); dst = f"{VD}{p}/v{v}__{Path(p).name}"
149
+ api.batch_bucket_files(bucket, copy=[("bucket", bucket, cur.xet_hash, dst)],
150
+ add=[(json.dumps({**m, "path": p, "archived": int(time.time())}, indent=1).encode(), dst + ".json")])
151
+ return dst
152
+
153
  @app.get("/api/ws/list")
154
  def ws_list(req: Request, bucket: str, prefix: str = ""):
155
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s)
156
  try:
157
+ files = [f for f in api.list_bucket_tree(bucket, prefix=prefix or None, recursive=True) if getattr(f, "type", "") == "file" and not f.path.startswith(".studius/")]
158
+ side = {f.path for f in api.list_bucket_tree(bucket, prefix=MD.rstrip("/"), recursive=True) if getattr(f, "type", "") == "file"}
159
+ want = [f.path for f in files if mpath(f.path) in side]
160
+ meta = metas(api, bucket, want); old = legacy(api, bucket) if len(want) < len(files) else {}
161
+ out = []
162
+ for f in files:
163
+ m = meta.get(f.path) or old.get(f.path)
164
+ out.append({"path": f.path, "size": f.size, "mtime": f.mtime.isoformat() if f.mtime else None, "mime": mimetypes.guess_type(f.path)[0] or "application/octet-stream", **({"meta": m} if m else {})})
165
  return {"bucket": bucket, "files": sorted(out, key=lambda x: x["mtime"] or "", reverse=True)}
166
  except Exception as e: herr(e)
167
 
168
  def put(api, bucket, data: bytes, path: str, meta: dict):
169
+ old = getmeta(api, bucket, path); exists = info(api, bucket, path) is not None
170
+ if exists: snapshot(api, bucket, path, {**old, "v": old.get("v", 1)})
171
+ m = {**{k: v for k, v in old.items() if k in ("pins",)}, **meta, "saved": int(time.time()), "v": (old.get("v", 1) + 1) if exists else 1}
172
+ api.batch_bucket_files(bucket, add=[(data, path), (json.dumps(m, indent=1).encode(), mpath(path))])
173
+ return {"path": path, "size": len(data), "meta": m}
174
 
175
  @app.post("/api/ws/upload")
176
  async def ws_upload(req: Request, bucket: str = Form(...), path: str = Form(""), studio: str = Form("upload"), file: UploadFile = File(...)):
 
178
  data = await file.read(MAX_UP + 1)
179
  if len(data) > MAX_UP: raise HTTPException(413, "max 200 MB")
180
  p = safe(path or f"uploads/{file.filename}")
181
+ try: return put(api, bucket, data, p, {"studio": studio, "mime": file.content_type, "source": "upload", "filename": file.filename})
182
  except Exception as e: herr(e)
183
 
184
  @app.post("/api/ws/save-url")
185
+ async def ws_save_url(req: Request, bucket: str = Form(...), url: str = Form(...), path: str = Form(...), studio: str = Form(""), prompt: str = Form(""), model: str = Form("")):
186
+ """Save a studio result (server tmp result or public *.hf.space file URL) into the workspace server-side."""
187
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s)
188
  if url.startswith("/api/tmp/"):
189
  lp = tmp_path(url)
190
  if not lp: raise HTTPException(410, "result expired")
191
+ content = Path(lp).read_bytes(); src = "hf:" + (model or "user-quota")
192
  else:
193
  if not ALLOW_FETCH.match(url): raise HTTPException(400, "only *.hf.space result URLs")
194
  async with httpx.AsyncClient(timeout=60, follow_redirects=True) as c:
195
  r = await c.get(url)
196
  if r.status_code != 200 or len(r.content) > MAX_UP: raise HTTPException(502, "fetch failed")
197
+ content = r.content; src = url.split("/gradio_api")[0].split("/file=")[0]
198
+ try: return put(api, bucket, content, safe(path), {"studio": studio, "prompt": prompt[:500], "source": src, **({"model": model} if model else {})})
199
  except Exception as e: herr(e)
200
 
201
+ @app.get("/api/ws/meta")
202
+ def ws_meta(req: Request, bucket: str, path: str):
203
+ s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
204
+ try: return {"path": p, "meta": getmeta(api, bucket, p)}
205
+ except Exception as e: herr(e)
206
+
207
+ @app.get("/api/ws/versions")
208
+ def ws_versions(req: Request, bucket: str, path: str):
209
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
210
  try:
211
+ vs = []; nm = re.escape(Path(p).name)
212
+ for f in api.list_bucket_tree(bucket, prefix=f"{VD}{p}", recursive=True):
213
+ mm = re.fullmatch(rf"v(\d+)__{nm}", f.path.rsplit("/", 1)[-1])
214
+ if getattr(f, "type", "") == "file" and mm and f.path.startswith(f"{VD}{p}/"):
215
+ vs.append({"v": int(mm.group(1)), "vpath": f.path, "size": f.size, "mtime": f.mtime.isoformat() if f.mtime else None})
216
+ return {"path": p, "current": getmeta(api, bucket, p).get("v"), "versions": sorted(vs, key=lambda x: -x["v"])}
217
  except Exception as e: herr(e)
218
+
219
+ @app.post("/api/ws/restore")
220
+ def ws_restore(req: Request, bucket: str = Form(...), path: str = Form(...), v: int = Form(...)):
221
+ """Restore version v as a NEW current version (current one is archived first; nothing is lost)."""
222
+ s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
223
+ try:
224
+ src = f"{VD}{p}/v{v}__{Path(p).name}"; old = info(api, bucket, src)
225
+ if not old: raise HTTPException(404, "version not found")
226
+ m = getmeta(api, bucket, p); exists = info(api, bucket, p) is not None
227
+ if exists: snapshot(api, bucket, p, m)
228
+ nm = {**m, "v": (m.get("v", 1) + 1) if exists else v + 1, "saved": int(time.time()), "restored_from": v}
229
+ api.batch_bucket_files(bucket, copy=[("bucket", bucket, old.xet_hash, p)], add=[(json.dumps(nm, indent=1).encode(), mpath(p))])
230
+ return {"path": p, "meta": nm}
231
+ except HTTPException: raise
232
+ except Exception as e: herr(e)
233
+
234
+ @app.get("/api/ws/file")
235
+ async def ws_file(req: Request, bucket: str, path: str, dl: int = 0):
236
+ """Streamed proxy from the bucket resolve URL (supports HTTP Range for audio/video seeking)."""
237
+ s = need(req); bucket = bid(bucket, s); p = safe(path)
238
+ from urllib.parse import quote
239
+ h = {"Authorization": f"Bearer {s['token']}"}
240
+ if req.headers.get("range"): h["Range"] = req.headers["range"]
241
+ c = httpx.AsyncClient(timeout=httpx.Timeout(60, read=300), follow_redirects=True)
242
+ r = await c.send(c.build_request("GET", f"{HUB}/buckets/{bucket}/resolve/{quote(p, safe='')}", headers=h), stream=True)
243
+ if r.status_code not in (200, 206):
244
+ await r.aclose(); await c.aclose(); raise HTTPException(404 if r.status_code == 404 else 502, f"bucket file: HTTP {r.status_code}")
245
+ oh = {"Cache-Control": "private, no-store", "Accept-Ranges": "bytes"}
246
+ for k in ("content-length", "content-range"):
247
+ if r.headers.get(k): oh[k] = r.headers[k]
248
+ if dl: oh["Content-Disposition"] = f'attachment; filename="{Path(p).name}"'
249
+ async def body():
250
+ try:
251
+ async for chunk in r.aiter_bytes(256 * 1024): yield chunk
252
+ finally: await r.aclose(); await c.aclose()
253
+ return StreamingResponse(body(), status_code=r.status_code, media_type=mimetypes.guess_type(p)[0] or "application/octet-stream", headers=oh)
254
 
255
  @app.post("/api/ws/delete")
256
  def ws_delete(req: Request, bucket: str = Form(...), path: str = Form(...), confirm: str = Form("")):
257
+ """Delete from the workspace view; the last version is archived in .studius/versions/ first."""
258
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
259
  if confirm != p: raise HTTPException(400, "confirm must equal path")
260
  try:
261
+ m = getmeta(api, bucket, p); arch = snapshot(api, bucket, p, {**m, "v": m.get("v", 1)})
262
+ dels = [p] + ([mpath(p)] if info(api, bucket, mpath(p)) else [])
263
+ api.batch_bucket_files(bucket, delete=dels); return {"deleted": p, "archived": arch}
264
  except Exception as e: herr(e)
265
 
266
  @app.post("/api/ws/pin")
267
  def ws_pin(req: Request, bucket: str = Form(...), path: str = Form(...), studio: str = Form(...), on: bool = Form(True)):
268
  s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); p = safe(path)
269
  try:
270
+ e = getmeta(api, bucket, p); pins = set(e.get("pins", []))
271
  (pins.add if on else pins.discard)(studio); e["pins"] = sorted(pins)
272
+ api.batch_bucket_files(bucket, add=[(json.dumps(e, indent=1).encode(), mpath(p))]); return {"path": p, "pins": e["pins"]}
273
  except Exception as e: herr(e)
274
 
275
  @app.middleware("http")
style.css CHANGED
@@ -220,3 +220,4 @@ body:not(.live) #beebtn{display:none}
220
  #pop .grp{border:1px solid rgba(242,201,76,.18);padding:6px 8px 8px;margin:8px 0 0;border-radius:4px}#pop .grp legend{color:var(--gold);font-size:10px;letter-spacing:.12em;padding:0 4px}
221
  #pop .avref{width:96px;height:96px;object-fit:cover;border:1px solid var(--line2);border-radius:4px;margin-top:6px}#pop .avout{width:100%;margin-top:6px;border-radius:4px}
222
  #pop .speak{margin:2px 0 6px}#pop .chat audio{width:100%;height:32px}
 
 
220
  #pop .grp{border:1px solid rgba(242,201,76,.18);padding:6px 8px 8px;margin:8px 0 0;border-radius:4px}#pop .grp legend{color:var(--gold);font-size:10px;letter-spacing:.12em;padding:0 4px}
221
  #pop .avref{width:96px;height:96px;object-fit:cover;border:1px solid var(--line2);border-radius:4px;margin-top:6px}#pop .avout{width:100%;margin-top:6px;border-radius:4px}
222
  #pop .speak{margin:2px 0 6px}#pop .chat audio{width:100%;height:32px}
223
+ .vers{margin-top:8px;font-size:12px}.vers .vr{display:flex;gap:6px;align-items:center;padding:2px 0}.vers .vl b{display:block;margin:6px 0 2px}
workspace.js CHANGED
@@ -1,5 +1,5 @@
1
  // STUDIUS empire backbone (frontend): HF sign-in, Workspace (user's HF Bucket), asset bus hand-off, bee agent dock.
2
- import { MODULES } from './real.js?v=60';
3
  const $ = (s, r = document) => r.querySelector(s);
4
  const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
5
  const ST = () => window.__studius.STUDIOS;
@@ -39,7 +39,7 @@ async function renderWS() {
39
  $('#wsp .files').innerHTML = files.map((f, i) => { const k = kindOf(f.mime, f.path); const pins = f.meta?.pins || [];
40
  return `<li><button class="fn" data-i="${i}" title="Vorschau">${{ image: '🖼', audio: '🎵', video: '🎬', text: '📄' }[k] || '📦'} ${esc(f.path)}</button><small>${(f.size / 1024).toFixed(0)} KB${f.meta?.studio ? ' · ' + esc(f.meta.studio) : ''}${f.meta?.v > 1 ? ' · v' + f.meta.v : ''}${pins.length ? ' · 📌' + esc(pins.join(',')) : ''}</small><span><select data-send="${i}" aria-label="An Studio senden"><option value="">→ Studio…</option>${targets(k).map(s => `<option value="${s.id}">${esc(s.name)}</option>`).join('')}</select><a class="ib" href="/api/ws/file?dl=1&bucket=${encodeURIComponent(W.bucket)}&path=${encodeURIComponent(f.path)}" aria-label="Download">⬇</a><button class="ib" data-del="${i}" aria-label="Löschen">🗑</button></span></li>`; }).join('') || '<li class="mut">Leer – speichere Ergebnisse mit „In Workspace“.</li>';
41
  $('#wsp .files').onclick = async (e) => { const t = e.target.closest('button'); if (!t) return; const f = files[t.dataset.i ?? t.dataset.del];
42
- if (t.dataset.del != null) { if (!confirm(`„${f.path}“ endgültig aus ${W.bucket} löschen?`)) return; try { await api('/api/ws/delete', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, confirm: f.path }) }); renderWS(); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; } return; }
43
  preview(f); };
44
  $('#wsp .files').onchange = (e) => { const s = e.target.closest('select[data-send]'); if (!s?.value) return; const f = files[s.dataset.send]; sendTo(s.value, wsAsset(f)); api('/api/ws/pin', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, studio: s.value }) }).catch(() => {}); s.value = ''; };
45
  } catch (e) { $('#wsst').textContent = '⚠ ' + e.message; }
@@ -47,7 +47,14 @@ async function renderWS() {
47
  const fileUrl = (p) => '/api/ws/file?bucket=' + encodeURIComponent(W.bucket) + '&path=' + encodeURIComponent(p);
48
  const wsAsset = (f) => ({ kind: kindOf(f.mime, f.path), mime: f.mime, url: fileUrl(f.path), name: f.path.split('/').pop(), studio: f.meta?.studio || 'workspace' });
49
  async function preview(f) { const k = kindOf(f.mime, f.path), u = fileUrl(f.path), pv = $('#wsp .pv');
50
- pv.innerHTML = k === 'image' ? `<img alt="${esc(f.path)}" src="${u}">` : k === 'audio' ? `<audio controls src="${u}"></audio>` : k === 'video' ? `<video controls src="${u}"></video>` : k === 'text' ? `<pre>${esc((await (await fetch(u)).text()).slice(0, 4000))}</pre>` : '<p class="mut">Keine Vorschau</p>'; }
 
 
 
 
 
 
 
51
  async function connectUI(b) {
52
  const def = W.me.user.name + '/studius-workspace';
53
  b.innerHTML = `<p><b>Workspace verbinden.</b> STUDIUS speichert alle Assets in <i>deinem</i> Hugging-Face Storage Bucket (privat). Wähle einen bestehenden Bucket oder lege einen neuen an.</p><input id="bkt" aria-label="Bucket-ID" value="${esc(def)}"><div class="row"><button class="btn" id="bcreate">Erstellen & verbinden</button><button class="btn alt" id="bconn">Nur verbinden</button></div><div class="stat" id="bst"></div><ul class="files" id="blist"></ul>`;
@@ -62,7 +69,7 @@ export async function saveAsset(a) {
62
  if (!W.backend || !W.me?.signedIn) throw new Error('Bitte anmelden (Sign in with Hugging Face)');
63
  if (!W.bucket) throw new Error('Kein Workspace-Bucket verbunden (▤ Workspace)');
64
  const path = `${a.studio || 'misc'}/${a.name}`;
65
- if (a.url && (/^https:\/\/[a-z0-9-]+\.hf\.space\//.test(a.url) || a.url.startsWith('/api/tmp/'))) return api('/api/ws/save-url', { method: 'POST', body: form({ bucket: W.bucket, url: a.url, path, studio: a.studio || '', prompt: a.prompt || '' }) });
66
  const blob = a.blob || (a.text != null ? new Blob([a.text], { type: 'text/plain' }) : await (await fetch(a.url)).blob());
67
  return api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path, studio: a.studio || '', file: new File([blob], a.name) }) });
68
  }
 
1
  // STUDIUS empire backbone (frontend): HF sign-in, Workspace (user's HF Bucket), asset bus hand-off, bee agent dock.
2
+ import { MODULES } from './real.js?v=61';
3
  const $ = (s, r = document) => r.querySelector(s);
4
  const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
5
  const ST = () => window.__studius.STUDIOS;
 
39
  $('#wsp .files').innerHTML = files.map((f, i) => { const k = kindOf(f.mime, f.path); const pins = f.meta?.pins || [];
40
  return `<li><button class="fn" data-i="${i}" title="Vorschau">${{ image: '🖼', audio: '🎵', video: '🎬', text: '📄' }[k] || '📦'} ${esc(f.path)}</button><small>${(f.size / 1024).toFixed(0)} KB${f.meta?.studio ? ' · ' + esc(f.meta.studio) : ''}${f.meta?.v > 1 ? ' · v' + f.meta.v : ''}${pins.length ? ' · 📌' + esc(pins.join(',')) : ''}</small><span><select data-send="${i}" aria-label="An Studio senden"><option value="">→ Studio…</option>${targets(k).map(s => `<option value="${s.id}">${esc(s.name)}</option>`).join('')}</select><a class="ib" href="/api/ws/file?dl=1&bucket=${encodeURIComponent(W.bucket)}&path=${encodeURIComponent(f.path)}" aria-label="Download">⬇</a><button class="ib" data-del="${i}" aria-label="Löschen">🗑</button></span></li>`; }).join('') || '<li class="mut">Leer – speichere Ergebnisse mit „In Workspace“.</li>';
41
  $('#wsp .files').onclick = async (e) => { const t = e.target.closest('button'); if (!t) return; const f = files[t.dataset.i ?? t.dataset.del];
42
+ if (t.dataset.del != null) { if (!confirm(`„${f.path}“ aus ${W.bucket} löschen? (Letzte Version bleibt unter .studius/versions archiviert.)`)) return; try { await api('/api/ws/delete', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, confirm: f.path }) }); renderWS(); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; } return; }
43
  preview(f); };
44
  $('#wsp .files').onchange = (e) => { const s = e.target.closest('select[data-send]'); if (!s?.value) return; const f = files[s.dataset.send]; sendTo(s.value, wsAsset(f)); api('/api/ws/pin', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, studio: s.value }) }).catch(() => {}); s.value = ''; };
45
  } catch (e) { $('#wsst').textContent = '⚠ ' + e.message; }
 
47
  const fileUrl = (p) => '/api/ws/file?bucket=' + encodeURIComponent(W.bucket) + '&path=' + encodeURIComponent(p);
48
  const wsAsset = (f) => ({ kind: kindOf(f.mime, f.path), mime: f.mime, url: fileUrl(f.path), name: f.path.split('/').pop(), studio: f.meta?.studio || 'workspace' });
49
  async function preview(f) { const k = kindOf(f.mime, f.path), u = fileUrl(f.path), pv = $('#wsp .pv');
50
+ pv.innerHTML = k === 'image' ? `<img alt="${esc(f.path)}" src="${u}">` : k === 'audio' ? `<audio controls src="${u}"></audio>` : k === 'video' ? `<video controls src="${u}"></video>` : k === 'text' ? `<pre>${esc((await (await fetch(u)).text()).slice(0, 4000))}</pre>` : '<p class="mut">Keine Vorschau</p>';
51
+ const m = f.meta || {}; const box = document.createElement('div'); box.className = 'vers'; pv.append(box);
52
+ box.innerHTML = `<small class="mut">${m.v ? 'v' + m.v : ''}${m.studio ? ' · ' + esc(m.studio) : ''}${m.model ? ' · ' + esc(m.model) : m.source ? ' · ' + esc(m.source) : ''}${m.prompt ? ' · „' + esc(m.prompt.slice(0, 80)) + '“' : ''}</small><div class="vl mut">Versionen laden…</div>`;
53
+ try { const { versions } = await api('/api/ws/versions?bucket=' + encodeURIComponent(W.bucket) + '&path=' + encodeURIComponent(f.path)); window.__versions = versions;
54
+ box.querySelector('.vl').innerHTML = versions.length ? '<b>Frühere Versionen</b>' + versions.map(v => `<div class="vr">v${v.v} · ${(v.size / 1024).toFixed(0)} KB · ${new Date(v.mtime).toLocaleString('de-DE')} <a class="ib" href="${fileUrl(v.vpath)}&dl=1" aria-label="v${v.v} herunterladen">⬇</a><button class="ib" data-rv="${v.v}" aria-label="v${v.v} wiederherstellen">↺</button></div>`).join('') : 'Keine früheren Versionen.';
55
+ box.onclick = async (e) => { const b = e.target.closest('[data-rv]'); if (!b) return; if (!confirm(`v${b.dataset.rv} als neue aktuelle Version von „${f.path}“ wiederherstellen? (Die jetzige bleibt als Version erhalten.)`)) return;
56
+ try { const r = await api('/api/ws/restore', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, v: b.dataset.rv }) }); window.__restored = r; $('#wsst').textContent = `✔ v${b.dataset.rv} wiederhergestellt → v${r.meta.v}`; renderWS(); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; } };
57
+ } catch (e) { box.querySelector('.vl').textContent = ''; } }
58
  async function connectUI(b) {
59
  const def = W.me.user.name + '/studius-workspace';
60
  b.innerHTML = `<p><b>Workspace verbinden.</b> STUDIUS speichert alle Assets in <i>deinem</i> Hugging-Face Storage Bucket (privat). Wähle einen bestehenden Bucket oder lege einen neuen an.</p><input id="bkt" aria-label="Bucket-ID" value="${esc(def)}"><div class="row"><button class="btn" id="bcreate">Erstellen & verbinden</button><button class="btn alt" id="bconn">Nur verbinden</button></div><div class="stat" id="bst"></div><ul class="files" id="blist"></ul>`;
 
69
  if (!W.backend || !W.me?.signedIn) throw new Error('Bitte anmelden (Sign in with Hugging Face)');
70
  if (!W.bucket) throw new Error('Kein Workspace-Bucket verbunden (▤ Workspace)');
71
  const path = `${a.studio || 'misc'}/${a.name}`;
72
+ if (a.url && (/^https:\/\/[a-z0-9-]+\.hf\.space\//.test(a.url) || a.url.startsWith('/api/tmp/'))) return api('/api/ws/save-url', { method: 'POST', body: form({ bucket: W.bucket, url: a.url, path, studio: a.studio || '', prompt: a.prompt || '', model: a.model || '' }) });
73
  const blob = a.blob || (a.text != null ? new Blob([a.text], { type: 'text/plain' }) : await (await fetch(a.url)).blob());
74
  return api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path, studio: a.studio || '', file: new File([blob], a.name) }) });
75
  }