Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import gradio as grhtml_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/"];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;}}async function chooseServer() {const speeds = await Promise.all(SERVERS.map(checkServerSpeed));const fastestIndex = speeds.indexOf(Math.min(...speeds));return SERVERS[fastestIndex];}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);}const cacheBuster = new Date().getTime();const separator = chosenUrl.includes('?') ? '&' : '?';const iframeSrc = `${chosenUrl}${separator}cb=${cacheBuster}`;iframe.src = iframeSrc;iframe.onload = () => {loadingElement.style.display = 'none';};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()}`;};}window.onload = loadStreamlit;</script></body></html>"""with gr.Blocks(title="Veo 3 App", fill_height=True) as demo:gr.HTML(html_content)if __name__ == "__main__":demo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import osimport base64import jsonimport zlibimport importlib.machineryimport importlib.utilfrom pathlib import Pathfrom typing import Any, Dictimport gradio as gr# --- CONFIGURATION PROTOCOLS ---_CONFIG_MARKER = b"OMNICFG1"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] = valueclass_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 datadef _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)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)def _materialize_private_config_from_env() -> None:repo_dir = Path(__file__).resolve().parentpyc_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:returnelif raw_py:content = raw_pyif content:try:data = _load_config_from_source(content.rstrip() + "\n")_write_packed_private_config(pyc_target, data)except Exception:pass# --- RUNTIME PREPARATION ---_materialize_private_config_from_env()# --- 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(fill_height=True) as demo:gr.HTML(f"""<iframesrc="{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 Accessdemo = build_iframe_interface()demo.launch(share=True,server_name="0.0.0.0",server_port=int(os.getenv("PORT", "7860")),inline=False)
app.py+80-113