cpuai's picture
Update app.py
cb0f157 verified
#!/usr/bin/env python3
"""
Gradio set_static_paths() English demo
Run: python app.py
Requires: pip install "gradio>=5.31.0"
"""
from pathlib import Path
import gradio as gr
# --------------------------------------------------------------------
# 1) Tell Gradio which directory should be exposed as a static folder.
# --------------------------------------------------------------------
BASE_DIR = Path(__file__).resolve().parent
STATIC_DIR = BASE_DIR / "static" # ./static
gr.set_static_paths([STATIC_DIR])
# --------------------------------------------------------------------
# 2) Build a minimal UI that references the static assets.
# --------------------------------------------------------------------
with gr.Blocks(title="Static Assets Demo") as demo:
gr.Markdown("## Static assets served via gr.set_static_paths()")
# Link to the static HTML page
gr.HTML(
'<a href="/gradio_api/file=static/index.html" target="_blank">'
"Open index.html"
"</a>"
)
# Display the static image
gr.HTML(
'<img src="/gradio_api/file=static/logo.png" style="max-width:200px;">'
)
# --------------------------------------------------------------------
# 3) Launch! allowed_paths keeps working even if you remove set_static_paths.
# --------------------------------------------------------------------
if __name__ == "__main__":
# 添加自定义JS抑制重复渲染
demo.load(
None,
None,
None,
js="""
() => {
// 标记已初始化,避免重复操作
if (!window.__gradio_initialized) {
window.__gradio_initialized = true;
// 这里放置仅需执行一次的代码
}
}
"""
)
demo.launch(
server_name="0.0.0.0",
server_port=7860,
allowed_paths=[STATIC_DIR], # optional but recommended
)