dryymatt's picture
Upload server.py
cfe0b9c verified
"""
╔══════════════════════════════════════════════════════╗
║ OMNI-VIBE STUDIO — INSTANT WAKE Server ║
║ ║
║ PHASE 1 (<1ms): Bind 0.0.0.0:7860, serve 200 OK ║
║ health + loading HTML immediately. ║
║ PHASE 2 (bg): Lazy-import OmniVibeEngine, ║
║ PoseArchitect, PosePainter, ║
║ PoseAuditor, ReflectSelect. ║
║ ║
║ No import of core/ghost_deploy at module level. ║
║ First byte on wire within milliseconds of CMD. ║
╚══════════════════════════════════════════════════════╝
"""
import json, os, sys, asyncio, time
from pathlib import Path
from aiohttp import web
# ─── CONSTANTS (no heavy imports) ───
PORT = int(os.environ.get("WIZARD_PORT", 7860))
STATIC = Path(__file__).parent / "static"
CANONICAL_REPO = "dryymatt/Wizard-Vibe-Studio"
WIZARD_HAT_COLOR = "steady-gold"
# ─── Engine refs — lazy-loaded in Phase 2 ───
_engine = None
_ghost = None
_reflect = None
_engine_loaded = False
# ──────────────────────────────────────────────────────
# PHASE 1: Instant HTML — served before any imports
# ──────────────────────────────────────────────────────
LOADING_HTML = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Omni-Vibe Studio</title>
<style>
:root{
--glass-bg:rgba(255,255,255,.03);--glass-border:rgba(255,255,255,.06);
--purple:#8B5CF6;--cyan:#06B6D4;--green:#10B981;--gold:#F59E0B;
--text:#e0e0ff;--text2:#9090b0;--text3:#606080;
--bg1:#0a0a1a;--bg2:#1a0a2e;--radius:20px;--radius-sm:12px;
--font:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{
font-family:var(--font);
background:linear-gradient(135deg,var(--bg1),var(--bg2),#0a1a2e);
color:var(--text);min-height:100vh;display:flex;
align-items:center;justify-content:center;
-webkit-font-smoothing:antialiased;
}
::selection{background:rgba(139,92,246,.5);color:#fff}
.glass{
background:var(--glass-bg);backdrop-filter:blur(20px);
-webkit-backdrop-filter:blur(20px);
border:1px solid var(--glass-border);border-radius:var(--radius);
padding:3rem 4rem;text-align:center;
animation:fadeIn .6s ease-out;
}
@keyframes fadeIn{from{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}
.gradient-text{
background:linear-gradient(135deg,var(--purple),var(--cyan),var(--green));
-webkit-background-clip:text;-webkit-text-fill-color:transparent;
background-clip:text;
}
h1{font-size:clamp(2rem,6vw,4rem);font-weight:800;line-height:1.1}
p{color:var(--text2);margin-top:1rem;font-size:1.1rem}
.loading-bar{
width:240px;height:4px;background:var(--glass-bg);
border-radius:2px;margin:1.5rem auto 0;overflow:hidden;
}
.loading-bar::after{
content:'';display:block;width:40%;height:100%;
background:linear-gradient(90deg,var(--purple),var(--cyan),var(--green));
border-radius:2px;
animation:slide 1.2s ease-in-out infinite;
}
@keyframes slide{0%{transform:translateX(-100%)}100%{transform:translateX(350%)}}
.status-dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px}
.status-dot.gold{background:var(--gold);box-shadow:0 0 8px var(--gold)}
.pulse{animation:pulse 2s ease-in-out infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.3}}
.wizard-svg{filter:drop-shadow(0 0 20px rgba(139,92,246,.6));margin-bottom:1.5rem}
</style>
<script>
let pollTimer;
function checkReady(){
fetch('/api/health').then(r=>r.json()).then(d=>{
if(d.engine_loaded){
clearInterval(pollTimer);
location.reload();
}
}).catch(()=>{});
}
pollTimer=setInterval(checkReady,500);
document.addEventListener('DOMContentLoaded',()=>{
document.getElementById('status-text').textContent='Waking the Athanor…';
});
</script>
</head>
<body>
<div class="glass">
<svg class="wizard-svg" width="56" height="56" viewBox="0 0 64 64">
<defs><linearGradient id="hg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#8B5CF6"><animate attributeName="stop-color" values="#8B5CF6;#06B6D4;#10B981;#8B5CF6" dur="6s" repeatCount="indefinite"/></stop>
<stop offset="50%" style="stop-color:#06B6D4"><animate attributeName="stop-color" values="#06B6D4;#10B981;#8B5CF6;#06B6D4" dur="6s" repeatCount="indefinite"/></stop>
<stop offset="100%" style="stop-color:#10B981"><animate attributeName="stop-color" values="#10B981;#8B5CF6;#06B6D4;#10B981" dur="6s" repeatCount="indefinite"/></stop>
</linearGradient></defs>
<path d="M32 8 L8 48 L32 40 L56 48 Z" fill="url(#hg)" stroke="rgba(255,255,255,.3)" stroke-width="1.5">
<animateTransform attributeName="transform" type="rotate" values="0 32 28;2 32 28;-1 32 28;0 32 28" dur="6s" repeatCount="indefinite"/>
</path>
<ellipse cx="32" cy="48" rx="26" ry="7" fill="none" stroke="url(#hg)" stroke-width="2" opacity=".6">
<animate attributeName="rx" values="26;28;26" dur="3s" repeatCount="indefinite"/>
</ellipse>
</svg>
<h1 class="gradient-text">Omni-Vibe Studio</h1>
<p>Specialized Swarm — Pose Architect · Painter · Auditor</p>
<div class="loading-bar"></div>
<p style="font-size:.85rem;color:var(--text3);margin-top:1rem">
<span class="status-dot gold pulse"></span>
<span id="status-text">Initializing LiteRT engine…</span>
</p>
<p style="font-size:.7rem;color:var(--text3);margin-top:1.5rem">0.0.0.0:7860 · Steady Gold</p>
</div>
</body>
</html>"""
async def handle_root_get(req):
if _engine_loaded:
fp = STATIC / "index.html"
if fp.exists():
return web.Response(text=fp.read_text(), content_type="text/html")
return web.Response(text=LOADING_HTML, content_type="text/html")
async def handle_health(req):
return web.json_response({
"status": "alive",
"engine": "Omni-Vibe Studio — Specialized Swarm",
"engine_loaded": _engine_loaded,
"binding": "0.0.0.0:7860",
"port": PORT,
"hat": WIZARD_HAT_COLOR,
"hf_token": bool(os.environ.get("HF_TOKEN")),
})
async def handle_agent(req):
return web.json_response({
"name": "omni-vibe-studio",
"description": "Omni-Vibe Studio — Specialized AI Swarm. 0.0.0.0:7860. LiteRT engine.",
"url": "https://dryymatt-wizard-vibe-studio-v2.hf.space",
"provider": {"organization": "Omni-Vibe Studio — Litehat System",
"url": "https://huggingface.co/dryymatt"},
"version": "3.0.0",
"capabilities": {"streaming": True, "ghostDeploy": True, "liquidGlass": True},
})
async def handle_static(req):
path = req.match_info.get("path", "index.html")
fp = STATIC / path
if not fp.exists():
return web.Response(text="Not found", status=404)
ct = {".html": "text/html", ".css": "text/css", ".js": "application/javascript"}
return web.Response(text=fp.read_text(), content_type=ct.get(fp.suffix, "text/plain"))
def _get_engine():
global _engine, _ghost, _reflect, _engine_loaded
if _engine is None:
from core import state as st, sandbox_validate
from ghost_deploy import ghost as g
_engine = st.engine
_ghost = g
_reflect = st.reflect
_engine_loaded = True
print("⚡ Omni-Vibe Engine: LAZY-LOADED")
from core import state as st
return st, _ghost
def _sse(ev, d):
return f"event: {ev}\ndata: {json.dumps(d)}\n\n"
async def stream_gen(sid, prompt):
st, ghost = _get_engine()
session = st.sessions[sid]
session["status"] = "streaming"
st.sandbox[sid] = "building"
yield _sse("phase", {"phase": "pose", "hat": WIZARD_HAT_COLOR})
await asyncio.sleep(0.02)
pose_plan = st.engine.pose(prompt)
yield _sse("pose", {"architect": {"stack":pose_plan["architect"]["stack"],"features":pose_plan["architect"]["features"],"files":pose_plan["architect"]["files_needed"]},"painter":pose_plan["painter"],"auditor":pose_plan["auditor"]})
yield _sse("phase", {"phase": "generate"})
await asyncio.sleep(0.02)
t0 = time.time()
code, schema = st.engine.generate(prompt)
elapsed = (time.time()-t0)*1000
chunk_size = max(1, len(code)//30)
for i in range(0, len(code), chunk_size):
yield _sse("code", {"chunk": code[i:i+chunk_size], "partial": code[:i+chunk_size], "progress": min(100, int((i+chunk_size)/len(code)*100))})
await asyncio.sleep(0.01)
st.codes[sid] = code
st.sessions[sid]["schema"] = schema
yield _sse("generated", {"chars": len(code), "elapsed_ms": round(elapsed,1)})
yield _sse("phase", {"phase": "audit"})
await asyncio.sleep(0.02)
findings = st.engine.auditor.audit(code, schema)
yield _sse("audit", {"findings":len(findings),"errors":sum(1 for f in findings if f.severity=="ERROR"),"warnings":sum(1 for f in findings if f.severity=="WARN")})
yield _sse("phase", {"phase": "heal"})
code, auto_fixes = st.engine.auditor.heal_findings(code, findings)
st.codes[sid] = code
healed, found, fixed = st.reflect.heal(code)
for i in range(15):
from core import sandbox_validate
result = sandbox_validate(healed)
if result["success"]: break
healed, _, extra = st.reflect.heal(healed, result["errors"])
await asyncio.sleep(0.01)
yield _sse("phase", {"phase": "sandbox"})
from core import sandbox_validate
result = sandbox_validate(healed)
if result["success"]:
st.sandbox[sid] = "stable"; st.publish_ready[sid] = True
yield _sse("sandbox", {"status":"stable","hat":"steady-gold"})
else:
st.sandbox[sid] = "error"
yield _sse("sandbox", {"status":"error"})
session["status"] = "complete"
yield _sse("done", {"status":st.sandbox[sid]})
async def handle_stream(req):
_get_engine()
sid = __import__('uuid').uuid4().hex[:8]
d = await req.json(); prompt = d.get("prompt","")
st, _ = _get_engine()
st.sessions[sid] = {"id":sid,"prompt":prompt,"status":"init"}
st.sandbox[sid] = "building"; st.publish_ready[sid] = False
resp = web.StreamResponse(status=200, headers={"Content-Type":"text/event-stream","Cache-Control":"no-cache","Connection":"keep-alive","X-Accel-Buffering":"no"})
await resp.prepare(req)
try:
async for ev in stream_gen(sid, prompt): await resp.write(ev.encode())
await resp.write(b"event: close\ndata: {}\n\n")
except Exception as e:
await resp.write(f"event: error\ndata: {json.dumps({'error':str(e)})}\n\n".encode())
return resp
async def handle_publish(req):
st, ghost = _get_engine()
d = await req.json(); sid = d.get("session_id")
if not st.publish_ready.get(sid):
return web.json_response({"success":False,"error":"Sandbox not stable"}, status=400)
code = st.codes.get(sid,"")
if not code: return web.json_response({"success":False,"error":"No code"}, status=400)
description = d.get("description", st.sessions.get(sid,{}).get("prompt",""))
result = await ghost.publish(code, d.get("vibe_name",f"omni-vibe-{sid}"), description[:200] if description else "", port=PORT)
if result.get("success"):
st.sessions[sid]["published"] = True
st.sessions[sid]["deploy_url"] = result.get("space_url")
return web.json_response(result)
async def handle_status(req):
st, _ = _get_engine()
sid = req.query.get("session_id","")
if sid in st.sessions:
s = st.sessions[sid]
return web.json_response({"status":s["status"],"sandbox":st.sandbox.get(sid),"ready":st.publish_ready.get(sid),"deploy_url":s.get("deploy_url"),"hat":"steady-gold" if st.publish_ready.get(sid) else "cyan-blink"})
return web.json_response({"sessions":len(st.sessions),"engine":"omni-vibe","hat":WIZARD_HAT_COLOR})
async def handle_vibes(req):
_, ghost = _get_engine()
vibes = await ghost.list_vibes()
return web.json_response({"vibes":vibes,"count":len(vibes),"registry":CANONICAL_REPO})
async def handle_tunnel(req):
_, ghost = _get_engine()
try:
url = await ghost.tunnel.up(PORT, timeout=10.0)
return web.json_response({"success":bool(url),"url":url})
except Exception as e:
return web.json_response({"success":False,"error":str(e)}, status=500)
async def handle_schema(req):
st, _ = _get_engine()
sid = req.query.get("session_id","")
return web.json_response(st.sessions.get(sid,{}).get("schema",{}))
async def handle_preview(req):
st, _ = _get_engine()
sid = req.query.get("session_id","")
return web.Response(text=st.codes.get(sid,"<!-- Omni-Vibe -->"), content_type="text/html")
def create_app():
app = web.Application()
# Phase 1: no engine needed
app.router.add_get("/", handle_root_get)
app.router.add_get("/api/health", handle_health)
app.router.add_get("/.well-known/agent.json", handle_agent)
# Phase 2: lazy-load engine
app.router.add_post("/api/stream", handle_stream)
app.router.add_post("/api/publish", handle_publish)
app.router.add_get("/api/status", handle_status)
app.router.add_get("/api/preview", handle_preview)
app.router.add_get("/api/vibes", handle_vibes)
app.router.add_get("/api/tunnel", handle_tunnel)
app.router.add_get("/api/schema", handle_schema)
app.router.add_get("/{path:.*}", handle_static)
return app
def main():
import subprocess
try:
subprocess.run(["fuser","-k",f"{PORT}/tcp"], capture_output=True, timeout=5)
except Exception: pass
print(f"🧙‍♂️ Omni-Vibe Studio — INSTANT WAKE")
print(f" Binding : 0.0.0.0:{PORT}")
print(f" Health pulse : 200 OK in <1ms")
print(f" Loading HTML : served before engine import")
print(f" Registry : {CANONICAL_REPO}")
print(f" Hat : {WIZARD_HAT_COLOR}")
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def warm_start():
await asyncio.sleep(0.5)
print("⚡ Warm Start: loading OmniVibeEngine…")
try:
_get_engine()
print(f"⚡ Engine active — all Poses synchronized")
except Exception as e:
print(f"⚠ Engine load warning: {e}")
loop.create_task(warm_start())
web.run_app(create_app(), host="0.0.0.0", port=PORT, handle_signals=True)
if __name__ == "__main__":
main()