import re
from urllib.parse import urlencode
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import RedirectResponse, Response
THEME_QUERY_PARAM = "__theme"
LIGHT_THEME = "light"
FOOTER_LINKS_WITHOUT_API = ["gradio", "settings"]
CRAWLER_USER_AGENT = re.compile(
r"bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|vkshare",
re.IGNORECASE,
)
GRADIO_SOCIAL_META = re.compile(
r'\s*',
re.IGNORECASE,
)
DOCUMENT_TITLE = re.compile(r"
.*?\s*", re.IGNORECASE | re.DOTALL)
HEAD_OPEN = re.compile(r"]*>", re.IGNORECASE)
def is_crawler(request):
return bool(CRAWLER_USER_AGENT.search(request.headers.get("user-agent", "")))
async def force_light_theme(request, call_next):
wants_html = "text/html" in request.headers.get("accept", "")
if (
request.url.path == "/"
and request.query_params.get(THEME_QUERY_PARAM) != LIGHT_THEME
and wants_html
and not is_crawler(request)
):
params = dict(request.query_params)
params[THEME_QUERY_PARAM] = LIGHT_THEME
return RedirectResponse(f"/?{urlencode(params)}")
return await call_next(request)
def with_document_head(html, title, head):
stripped = DOCUMENT_TITLE.sub("", GRADIO_SOCIAL_META.sub("", html))
opening = HEAD_OPEN.search(stripped)
if not opening:
return html
tags = f"{title}\n{head}\n"
return stripped[: opening.end()] + tags + stripped[opening.end():]
def document_head_middleware(title, head):
async def serve_document_head(request, call_next):
response = await call_next(request)
if request.url.path != "/" or "text/html" not in response.headers.get("content-type", ""):
return response
body = b"".join([chunk async for chunk in response.body_iterator])
html = with_document_head(body.decode("utf-8"), title, head)
headers = {k: v for k, v in response.headers.items() if k.lower() != "content-length"}
return Response(html, status_code=response.status_code, headers=headers)
return serve_document_head
def build_launch_kwargs(theme, css, js, head, title=""):
middleware = [Middleware(BaseHTTPMiddleware, dispatch=force_light_theme)]
if title:
middleware.append(
Middleware(BaseHTTPMiddleware, dispatch=document_head_middleware(title, head))
)
return {
"theme": theme,
"css": css,
"js": js,
"head": "" if title else head,
"footer_links": list(FOOTER_LINKS_WITHOUT_API),
"ssr_mode": False,
"app_kwargs": {"middleware": middleware},
}