File size: 6,886 Bytes
4689c2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
"""Runtime monkey patch that injects a Gradio background-scheduler fix into templates."""

from __future__ import annotations

import sys
from pathlib import Path
from typing import Callable

ENABLE_GRADIO_FOCUS_QUEUE_MONKEYPATCH = True
GRADIO_FOCUS_QUEUE_MONKEYPATCH_VERBOSE = False

_PATCH_SENTINEL = "window.__gradioFocusQueuePatch"
_TARGET_TEMPLATES = {"frontend/index.html", "frontend/share.html"}
_PROJECT_ROOT = Path(__file__).resolve().parents[2]


def get_javascript() -> str:
    if not ENABLE_GRADIO_FOCUS_QUEUE_MONKEYPATCH:
        return ""
    verbose = "true" if GRADIO_FOCUS_QUEUE_MONKEYPATCH_VERBOSE else "false"
    return f"""

(function () {{

  if (typeof window === "undefined" || window.__gradioFocusQueuePatch) {{

    return;

  }}



  const nativeRequestAnimationFrame = window.requestAnimationFrame.bind(window);

  const nativeCancelAnimationFrame = window.cancelAnimationFrame.bind(window);

  const channel = typeof MessageChannel === "function" ? new MessageChannel() : null;



  function isElementVisible(element) {{

    if (!element) {{

      return false;

    }}

    const rect = element.getBoundingClientRect();

    const style = window.getComputedStyle(element);

    return style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0;

  }}



  function getVideoGenTab() {{

    return Array.from(document.querySelectorAll('[role="tab"]')).find((element) => element.textContent.trim() === "Video Generator") || null;

  }}



  function getVideoGenPanel() {{

    const tab = getVideoGenTab();

    const panelId = tab?.getAttribute("aria-controls");

    const panel = panelId ? document.getElementById(panelId) : null;

    return isElementVisible(panel) ? panel : null;

  }}



  function isVideoGenActive() {{

    return getVideoGenPanel() !== null;

  }}



  const patch = {{

    enabled: true,

    forceBackground: false,

    verbose: {verbose},

    nextId: 1,

    pending: new Map(),

    queue: [],

    nativeRequestAnimationFrame,

    nativeCancelAnimationFrame,

    isBackground() {{

      if (this.forceBackground) {{

        return true;

      }}

      try {{

        return document.visibilityState !== "visible" || !document.hasFocus();

      }} catch (_error) {{

        return false;

      }}

    }},

    shouldPatch() {{

      return this.enabled && this.isBackground() && isVideoGenActive();

    }},

    shouldPatchAnimationFrame(stack, callback) {{

      if (!this.shouldPatch()) {{

        return false;

      }}

      const stackText = String(stack || "");

      const source = String(callback || "");

      const isBlocksDispatch = stackText.includes("/assets/Blocks-") && source.includes("Jt(");

      const isCoreFlush = stackText.includes("/assets/index-") && source.includes("l.update(") && source.includes("ge.length") && source.includes("f.props[v.prop]=j");

      return isBlocksDispatch || isCoreFlush;

    }}

  }};



  function cancelSynthetic(id) {{

    const job = patch.pending.get(id);

    if (!job) {{

      return false;

    }}

    job.canceled = true;

    patch.pending.delete(id);

    return true;

  }}



  function dispatchSynthetic(job) {{

    if (!job || job.canceled) {{

      return;

    }}

    patch.pending.delete(job.id);

    try {{

      if (job.kind === "raf") {{

        job.callback(window.performance.now());

      }}

    }} catch (error) {{

      window.setTimeout(() => {{

        throw error;

      }}, 0);

    }}

  }}



  function flushOne() {{

    const job = patch.queue.shift();

    dispatchSynthetic(job);

  }}



  function scheduleSyntheticAnimationFrame(callback) {{

    if (!channel) {{

      return nativeRequestAnimationFrame(callback);

    }}

    const id = -patch.nextId++;

    const job = {{ id, kind: "raf", callback, args: null, canceled: false }};

    patch.pending.set(id, job);

    patch.queue.push(job);

    channel.port2.postMessage(id);

    if (patch.verbose) {{

      console.debug("[Gradio] focus queue synthetic animation frame", id);

    }}

    return id;

  }}



  if (channel) {{

    channel.port1.onmessage = flushOne;

  }}



  window.__gradioFocusQueuePatch = patch;



  window.requestAnimationFrame = function (callback) {{

    if (typeof callback !== "function") {{

      return nativeRequestAnimationFrame(callback);

    }}

    if (!patch.shouldPatch()) {{

      return nativeRequestAnimationFrame(callback);

    }}

    const stack = new Error().stack || "";

    if (!patch.shouldPatchAnimationFrame(stack, callback)) {{

      return nativeRequestAnimationFrame(callback);

    }}

    return scheduleSyntheticAnimationFrame(callback);

  }};



  window.cancelAnimationFrame = function (id) {{

    if (cancelSynthetic(id)) {{

      return;

    }}

    return nativeCancelAnimationFrame(id);

  }};



  console.info("[Gradio] focus queue patch installed");

}})();

"""


def _inject_script(template_source: str) -> str:
    if _PATCH_SENTINEL in template_source:
        return template_source
    script_tag = f"\n\t\t<script>\n{get_javascript()}\n\t\t</script>\n"
    module_tag = '<script type="module"'
    insert_at = template_source.find(module_tag)
    if insert_at != -1:
        return template_source[:insert_at] + script_tag + template_source[insert_at:]
    head_close = template_source.find("</head>")
    if head_close != -1:
        return template_source[:head_close] + script_tag + template_source[head_close:]
    return template_source + script_tag


def install() -> bool:
    if not ENABLE_GRADIO_FOCUS_QUEUE_MONKEYPATCH:
        return False
    argv0 = Path(sys.argv[0]).name.lower() if sys.argv and sys.argv[0] else ""
    cwd = Path.cwd().resolve()
    if cwd != _PROJECT_ROOT and _PROJECT_ROOT not in cwd.parents and argv0 != "wgp.py":
        return False
    import gradio.routes as gradio_routes

    templates = getattr(gradio_routes, "templates", None)
    loader = getattr(getattr(templates, "env", None), "loader", None)
    if loader is None:
        return False
    if getattr(loader, "_focus_queue_patch_installed", False):
        return True

    original_get_source: Callable = loader.get_source

    def patched_get_source(environment, template):
        source, filename, uptodate = original_get_source(environment, template)
        if template in _TARGET_TEMPLATES:
            source = _inject_script(source)
        return source, filename, uptodate

    loader.get_source = patched_get_source
    loader._focus_queue_patch_installed = True
    loader._focus_queue_patch_original_get_source = original_get_source
    templates.env.cache.clear()
    return True


__all__ = [
    "ENABLE_GRADIO_FOCUS_QUEUE_MONKEYPATCH",
    "GRADIO_FOCUS_QUEUE_MONKEYPATCH_VERBOSE",
    "get_javascript",
    "install",
]