Update app.py
Browse files1234567891034567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859111213616263646566676869707172737414151617181920212223242576777879802627282930828384858687888990919231323334353694959697983738394041424344454647484950511001011025253545556575810410510610710810911011111211359606111511611711811962636465661211226768697071727374757677787980818283848586125878889909192import osimport base64import jsonimport zlibimport importlib.machineryimport importlib.utilfrom pathlib import Pathfrom typing import Any, Dictimport gradio as gr
html_content = """<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Google Veo 3 Generator</title> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"> <meta http-equiv="Pragma" content="no-cache"> <meta http-equiv="Expires" content="0"> <style> footer { display: none !important; } .gradio-container { padding: 0 !important; margin: 0 !important; max-width: 100% !important; } html, body { margin: 0; padding: 0; width: 100%; height: 100vh; overflow: hidden; background-color: #ffffff; } #loading { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255, 255, 255, 0.9); display: flex; justify-content: center; align-items: center; font-size: 24px; font-family: sans-serif; z-index: 1000; } iframe { width: 100%; height: 100%; border: none; display: block; } </style></head><body> <div id="loading">Selecting optimal server...</div> <iframe id="streamlit-frame" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" allowfullscreen></iframe>
<script> const VERSION = "v1"; const SERVERS = [ "https://zenefil-veobatch.hf.space/", "https://zenefil-veobatch.hf.space/" ];# --- CONFIGURATION PROTOCOLS ---_CONFIG_MARKER = b"OMNICFG1"
async function checkServerSpeed(url) { const start = performance.now(); try { const response = await Promise.race([ fetch(url, { method: 'HEAD', mode: 'no-cors' }), new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 5000)) ]); const end = performance.now(); return end - start; } catch (error) { console.error(`Error checking ${url}:`, error); return Infinity; } }def _collect_config_values(namespace: Dict[str, Any]) -> Dict[str, Any]: data: Dict[str, Any] = {} for key, value in namespace.items(): if key.isupper() and key != "APP_RUNTIME_CONFIG": data[key] = value class_obj = namespace.get("APP_RUNTIME_CONFIG") if class_obj is not None: for key in dir(class_obj): if key.isupper() and key not in data: data[key] = getattr(class_obj, key) return data
async function chooseServer() { const speeds = await Promise.all(SERVERS.map(checkServerSpeed)); const fastestIndex = speeds.indexOf(Math.min(...speeds)); return SERVERS[fastestIndex]; }def _load_config_from_source(content: str) -> Dict[str, Any]: scope: Dict[str, Any] = {"__builtins__": __builtins__, "__name__": "omni_private_config"} exec(content, scope, scope) return _collect_config_values(scope)
async function loadStreamlit() { const loadingElement = document.getElementById('loading'); const iframe = document.getElementById('streamlit-frame'); const storageKey = `streamlitUrl_${VERSION}`; let chosenUrl = sessionStorage.getItem(storageKey); if (!chosenUrl) { chosenUrl = await chooseServer(); sessionStorage.setItem(storageKey, chosenUrl); }def _write_packed_private_config(path: Path, data: Dict[str, Any]) -> None: payload = json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8") packed = _CONFIG_MARKER + zlib.compress(payload, level=9) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(packed)
const cacheBuster = new Date().getTime(); const separator = chosenUrl.includes('?') ? '&' : '?'; const iframeSrc = `${chosenUrl}${separator}cb=${cacheBuster}`; iframe.src = iframeSrc;def _materialize_private_config_from_env() -> None: repo_dir = Path(__file__).resolve().parent pyc_target = repo_dir / "src" / "config.pyc" raw_b64 = (os.getenv("OMNI_PRIVATE_CONFIG_B64") or "").strip() raw_py = (os.getenv("OMNI_PRIVATE_CONFIG_PY") or "").strip() content = "" if raw_b64: try: content = base64.b64decode(raw_b64.encode("utf-8")).decode("utf-8") except Exception: return elif raw_py: content = raw_py
iframe.onload = () => { loadingElement.style.display = 'none'; }; if content: try: data = _load_config_from_source(content.rstrip() + "\n") _write_packed_private_config(pyc_target, data) except Exception: pass
iframe.onerror = async () => { console.warn('Iframe load failed, rechoosing server...'); sessionStorage.removeItem(storageKey); chosenUrl = await chooseServer(); sessionStorage.setItem(storageKey, chosenUrl); const newSeparator = chosenUrl.includes('?') ? '&' : '?'; iframe.src = `${chosenUrl}${newSeparator}cb=${new Date().getTime()}`; }; }# --- RUNTIME PREPARATION ---_materialize_private_config_from_env()
window.onload = loadStreamlit; </script></body></html>"""# --- IFRAME INTERFACE (Optimized for Free Tier) ---# Direct link to the source space to avoid "Refused to connect"SOURCE_SPACE_URL = "https://selfit-camera-omni-image-editor.hf.space"
def build_iframe_interface():with gr.Blocks(title="Veo 3 App", fill_height=True) as demo: gr.HTML(html_content) with gr.Blocks(fill_height=True) as demo: gr.HTML(f""" <iframe src="{SOURCE_SPACE_URL}" frameborder="0" width="100%" height="100%" style="min-height: 850px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen> </iframe> """) return demo
# --- MAIN EXECUTION ---if __name__ == "__main__": print("[startup] Initializing Omni-Image-Editor Bridge...") # Launch with settings optimized for Colab / API Access demo = build_iframe_interface() demo.launch() demo.launch( share=True, server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860")), inline=False )app.py+80-113