"""Initialize Gradio in English before rendering any built-in controls."""
from pathlib import Path
import json
import re
import gradio
from starlette.middleware import Middleware
class EnglishStartupMiddleware:
"""Bootstrap the pinned Gradio frontend with an explicit English locale.
Starting i18n before the application mounts also covers upload prompts,
toolbar labels, and validation controls on non-English browsers.
API responses, static files, and model inference pass through unchanged.
"""
def __init__(self, app):
self.app = app
assets = Path(gradio.__file__).parent / "templates/frontend/assets"
self.core = next(assets.glob("core-*.js")).name
async def __call__(self, scope, receive, send):
if (
scope["type"] != "http"
or scope.get("method") != "GET"
or scope.get("path", "")
not in ("", "/", scope.get("root_path", "").rstrip("/") + "/")
):
return await self.app(scope, receive, send)
start = None
chunks = []
is_html = False
async def english_response(message):
nonlocal start, is_html
if message["type"] == "http.response.start":
is_html = any(
key.lower() == b"content-type" and b"text/html" in value
for key, value in message.get("headers", [])
)
if not is_html:
await send(message)
return
start = message
elif message["type"] == "http.response.body" and is_html:
chunks.append(message.get("body", b""))
if message.get("more_body"):
return
body = b"".join(chunks).decode("utf-8")
pattern = r''
def bootstrap(match):
entry = match.group(1)
core = entry.rsplit("/", 1)[0] + "/" + self.core
return (
'"
)
body, count = re.subn(pattern, bootstrap, body, count=1)
if count != 1:
raise RuntimeError("Gradio frontend entry point was not found.")
encoded = body.encode("utf-8")
headers = [
(key, value)
for key, value in start.get("headers", [])
if key.lower() not in (b"content-length", b"content-language")
]
headers += [
(b"content-length", str(len(encoded)).encode()),
(b"content-language", b"en"),
]
await send(dict(start, headers=headers))
await send(
{"type": "http.response.body", "body": encoded, "more_body": False}
)
else:
await send(message)
await self.app(scope, receive, english_response)
def english_app_kwargs():
return {"middleware": [Middleware(EnglishStartupMiddleware)]}