Saravutw commited on
Commit
f4170ee
·
verified ·
1 Parent(s): 41a2ba7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -113
app.py CHANGED
@@ -1,125 +1,92 @@
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
 
3
- html_content = """
4
- <!DOCTYPE html>
5
- <html lang="en">
6
- <head>
7
- <meta charset="UTF-8">
8
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
9
- <title>Google Veo 3 Generator</title>
10
-
11
- <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
12
- <meta http-equiv="Pragma" content="no-cache">
13
- <meta http-equiv="Expires" content="0">
14
-
15
- <style>
16
- footer { display: none !important; }
17
- .gradio-container { padding: 0 !important; margin: 0 !important; max-width: 100% !important; }
18
-
19
- html, body {
20
- margin: 0;
21
- padding: 0;
22
- width: 100%;
23
- height: 100vh;
24
- overflow: hidden;
25
- background-color: #ffffff;
26
- }
27
- #loading {
28
- position: fixed;
29
- top: 0;
30
- left: 0;
31
- width: 100%;
32
- height: 100%;
33
- background: rgba(255, 255, 255, 0.9);
34
- display: flex;
35
- justify-content: center;
36
- align-items: center;
37
- font-size: 24px;
38
- font-family: sans-serif;
39
- z-index: 1000;
40
- }
41
- iframe {
42
- width: 100%;
43
- height: 100%;
44
- border: none;
45
- display: block;
46
- }
47
- </style>
48
- </head>
49
- <body>
50
- <div id="loading">Selecting optimal server...</div>
51
- <iframe id="streamlit-frame" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" allowfullscreen></iframe>
52
-
53
- <script>
54
- const VERSION = "v1";
55
-
56
- const SERVERS = [
57
- "https://zenefil-veobatch.hf.space/",
58
- "https://zenefil-veobatch.hf.space/"
59
- ];
60
 
61
- async function checkServerSpeed(url) {
62
- const start = performance.now();
63
- try {
64
- const response = await Promise.race([
65
- fetch(url, { method: 'HEAD', mode: 'no-cors' }),
66
- new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 5000))
67
- ]);
68
- const end = performance.now();
69
- return end - start;
70
- } catch (error) {
71
- console.error(`Error checking ${url}:`, error);
72
- return Infinity;
73
- }
74
- }
75
 
76
- async function chooseServer() {
77
- const speeds = await Promise.all(SERVERS.map(checkServerSpeed));
78
- const fastestIndex = speeds.indexOf(Math.min(...speeds));
79
- return SERVERS[fastestIndex];
80
- }
81
 
82
- async function loadStreamlit() {
83
- const loadingElement = document.getElementById('loading');
84
- const iframe = document.getElementById('streamlit-frame');
85
-
86
- const storageKey = `streamlitUrl_${VERSION}`;
87
- let chosenUrl = sessionStorage.getItem(storageKey);
88
-
89
- if (!chosenUrl) {
90
- chosenUrl = await chooseServer();
91
- sessionStorage.setItem(storageKey, chosenUrl);
92
- }
93
 
94
- const cacheBuster = new Date().getTime();
95
- const separator = chosenUrl.includes('?') ? '&' : '?';
96
- const iframeSrc = `${chosenUrl}${separator}cb=${cacheBuster}`;
97
-
98
- iframe.src = iframeSrc;
 
 
 
 
 
 
 
 
 
99
 
100
- iframe.onload = () => {
101
- loadingElement.style.display = 'none';
102
- };
 
 
 
103
 
104
- iframe.onerror = async () => {
105
- console.warn('Iframe load failed, rechoosing server...');
106
- sessionStorage.removeItem(storageKey);
107
- chosenUrl = await chooseServer();
108
- sessionStorage.setItem(storageKey, chosenUrl);
109
-
110
- const newSeparator = chosenUrl.includes('?') ? '&' : '?';
111
- iframe.src = `${chosenUrl}${newSeparator}cb=${new Date().getTime()}`;
112
- };
113
- }
114
 
115
- window.onload = loadStreamlit;
116
- </script>
117
- </body>
118
- </html>
119
- """
120
 
121
- with gr.Blocks(title="Veo 3 App", fill_height=True) as demo:
122
- gr.HTML(html_content)
 
 
 
 
 
 
 
 
 
 
 
 
123
 
 
124
  if __name__ == "__main__":
125
- demo.launch()
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import base64
3
+ import json
4
+ import zlib
5
+ import importlib.machinery
6
+ import importlib.util
7
+ from pathlib import Path
8
+ from typing import Any, Dict
9
  import gradio as gr
10
 
11
+ # --- CONFIGURATION PROTOCOLS ---
12
+ _CONFIG_MARKER = b"OMNICFG1"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ def _collect_config_values(namespace: Dict[str, Any]) -> Dict[str, Any]:
15
+ data: Dict[str, Any] = {}
16
+ for key, value in namespace.items():
17
+ if key.isupper() and key != "APP_RUNTIME_CONFIG":
18
+ data[key] = value
19
+ class_obj = namespace.get("APP_RUNTIME_CONFIG")
20
+ if class_obj is not None:
21
+ for key in dir(class_obj):
22
+ if key.isupper() and key not in data:
23
+ data[key] = getattr(class_obj, key)
24
+ return data
 
 
 
25
 
26
+ def _load_config_from_source(content: str) -> Dict[str, Any]:
27
+ scope: Dict[str, Any] = {"__builtins__": __builtins__, "__name__": "omni_private_config"}
28
+ exec(content, scope, scope)
29
+ return _collect_config_values(scope)
 
30
 
31
+ def _write_packed_private_config(path: Path, data: Dict[str, Any]) -> None:
32
+ payload = json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
33
+ packed = _CONFIG_MARKER + zlib.compress(payload, level=9)
34
+ path.parent.mkdir(parents=True, exist_ok=True)
35
+ path.write_bytes(packed)
 
 
 
 
 
 
36
 
37
+ def _materialize_private_config_from_env() -> None:
38
+ repo_dir = Path(__file__).resolve().parent
39
+ pyc_target = repo_dir / "src" / "config.pyc"
40
+ raw_b64 = (os.getenv("OMNI_PRIVATE_CONFIG_B64") or "").strip()
41
+ raw_py = (os.getenv("OMNI_PRIVATE_CONFIG_PY") or "").strip()
42
+ content = ""
43
+
44
+ if raw_b64:
45
+ try:
46
+ content = base64.b64decode(raw_b64.encode("utf-8")).decode("utf-8")
47
+ except Exception:
48
+ return
49
+ elif raw_py:
50
+ content = raw_py
51
 
52
+ if content:
53
+ try:
54
+ data = _load_config_from_source(content.rstrip() + "\n")
55
+ _write_packed_private_config(pyc_target, data)
56
+ except Exception:
57
+ pass
58
 
59
+ # --- RUNTIME PREPARATION ---
60
+ _materialize_private_config_from_env()
 
 
 
 
 
 
 
 
61
 
62
+ # --- IFRAME INTERFACE (Optimized for Free Tier) ---
63
+ # Direct link to the source space to avoid "Refused to connect"
64
+ SOURCE_SPACE_URL = "https://selfit-camera-omni-image-editor.hf.space"
 
 
65
 
66
+ def build_iframe_interface():
67
+ with gr.Blocks(fill_height=True) as demo:
68
+ gr.HTML(f"""
69
+ <iframe
70
+ src="{SOURCE_SPACE_URL}"
71
+ frameborder="0"
72
+ width="100%"
73
+ height="100%"
74
+ style="min-height: 850px; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"
75
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
76
+ allowfullscreen>
77
+ </iframe>
78
+ """)
79
+ return demo
80
 
81
+ # --- MAIN EXECUTION ---
82
  if __name__ == "__main__":
83
+ print("[startup] Initializing Omni-Image-Editor Bridge...")
84
+
85
+ # Launch with settings optimized for Colab / API Access
86
+ demo = build_iframe_interface()
87
+ demo.launch(
88
+ share=True,
89
+ server_name="0.0.0.0",
90
+ server_port=int(os.getenv("PORT", "7860")),
91
+ inline=False
92
+ )