File size: 1,920 Bytes
91705d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd36ee7
 
 
 
 
cb0f157
cd36ee7
 
 
 
 
 
 
 
 
91705d3
 
 
 
 
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
#!/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
    )