umyuu commited on
Commit
0977623
·
1 Parent(s): 12980d5

Gradioのautoreloadに対応

Browse files

https://www.gradio.app/guides/developing-faster-with-reload-mode

Files changed (3) hide show
  1. app.py +153 -9
  2. run_hot_reload.bat +7 -0
  3. src/myapp.py +0 -154
app.py CHANGED
@@ -3,18 +3,26 @@
3
  SaliencyMapDemo
4
  """
5
  from argparse import ArgumentParser, BooleanOptionalAction
 
 
 
 
 
 
6
 
7
  from src import PROGRAM_NAME, get_package_version
 
 
 
8
 
9
  __version__ = get_package_version()
 
 
10
 
11
 
12
- def main():
13
- from src.myapp import run_app
14
  """
15
- エントリーポイント
16
- 1, コマンドライン引数の解析を行います
17
- 2, アプリを起動します。
18
  """
19
  parser = ArgumentParser(prog=PROGRAM_NAME, description=PROGRAM_NAME)
20
  parser.add_argument('--inbrowser',
@@ -25,11 +33,147 @@ def main():
25
  type=int, default=7860, help="Gradio server port")
26
  parser.add_argument('--max_file_size',
27
  type=str, default="20MB", help="Gradio max file size")
28
- parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- args = parser.parse_args()
31
- run_app(args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
 
34
  if __name__ == "__main__":
35
- main()
 
 
 
 
 
 
 
 
 
 
 
3
  SaliencyMapDemo
4
  """
5
  from argparse import ArgumentParser, BooleanOptionalAction
6
+ #from datetime import datetime
7
+ import sys
8
+ from typing import Literal
9
+
10
+ import gradio as gr
11
+ import numpy as np
12
 
13
  from src import PROGRAM_NAME, get_package_version
14
+ from src.reporter import log
15
+ from src.saliency import SaliencyMap, convert_colormap
16
+ from src.utils import Stopwatch
17
 
18
  __version__ = get_package_version()
19
+ log.info("#アプリ起動中")
20
+ watch = Stopwatch.start_new()
21
 
22
 
23
+ def parse_args():
 
24
  """
25
+ コマンドライン引数の解析を行います
 
 
26
  """
27
  parser = ArgumentParser(prog=PROGRAM_NAME, description=PROGRAM_NAME)
28
  parser.add_argument('--inbrowser',
 
33
  type=int, default=7860, help="Gradio server port")
34
  parser.add_argument('--max_file_size',
35
  type=str, default="20MB", help="Gradio max file size")
36
+ parser.add_argument('--version',
37
+ action='version', version=f'%(prog)s {__version__}')
38
+
39
+ return parser.parse_args()
40
+
41
+
42
+ def jet_tab_selected(image: np.ndarray):
43
+ """
44
+ JETタブを選択時
45
+ """
46
+ sw = Stopwatch.start_new()
47
+ log.info(f"#jet_tab_selected({sw.elapsed:.3f}s)")
48
+ saliency = SaliencyMap("SpectralResidual")
49
+ success, saliency_map = saliency.compute(image)
50
+ if not success:
51
+ return image # エラーが発生した場合は入力画像を返します。
52
+ retval = convert_colormap(image, saliency_map, "jet")
53
+ log.info(f"#jet_tab_selected({sw.elapsed:.3f}s)")
54
+ return retval
55
+
56
+
57
+ def hot_tab_selected(image: np.ndarray):
58
+ """
59
+ HOTタブを選択時
60
+ """
61
+ sw = Stopwatch.start_new()
62
+ log.info(f"#hot_tab_selected({sw.elapsed:.3f}s)")
63
+ saliency = SaliencyMap("SpectralResidual")
64
+ success, saliency_map = saliency.compute(image)
65
+ if not success:
66
+ return image # エラーが発生した場合は入力画像を返します。
67
+ retval = convert_colormap(image, saliency_map, "turbo")
68
+ log.info(f"#hot_tab_selected({sw.elapsed:.3f}s)")
69
+ return retval
70
+
71
+
72
+ def submit_clicked(image: np.ndarray, algorithm: Literal["SpectralResidual", "FineGrained"]):
73
+ """
74
+ 入力画像を元に顕著マップを計算します。
75
+
76
+ Parameters:
77
+ image: 入力画像
78
+ str: 顕著性マップのアルゴリズム
79
+ Returns:
80
+ np.ndarray: JET画像
81
+ np.ndarray: HOT画像
82
+ """
83
+ sw = Stopwatch.start_new()
84
+ log.info(f"#submit_clicked({sw.elapsed:.3f}s)")
85
+ #
86
+ saliency = SaliencyMap(algorithm)
87
+ log.info(f"#SaliencyMap({sw.elapsed:.3f}s)")
88
+ success, saliency_map = saliency.compute(image)
89
+ log.info(f"#compute({sw.elapsed:.3f}s)")
90
+
91
+ if not success:
92
+ return image, image # エラーが発生した場合は入力画像を返します。
93
+
94
+ log.info(f"#jet({sw.elapsed:.3f}s)")
95
+ jet = convert_colormap(image, saliency_map, "jet")
96
+ # jet = None
97
+ log.info(f"#hot({sw.elapsed:.3f}s)")
98
+ hot = convert_colormap(image, saliency_map, "hot")
99
+ saliency = None
100
+ log.info(f"#submit_clicked({sw.elapsed:.3f}s)")
101
+ return jet, hot
102
 
103
+
104
+ args = parse_args()
105
+ """
106
+ アプリの画面を作成し、Gradioサービスを起動します。
107
+ analytics_enabled=False
108
+ https://github.com/gradio-app/gradio/issues/4226
109
+ ホットリロード対応として、topレベルのインデントに。
110
+ https://www.gradio.app/guides/developing-faster-with-reload-mode
111
+ """
112
+ with gr.Blocks(
113
+ analytics_enabled=False,
114
+ title=f"{PROGRAM_NAME} {get_package_version()}",
115
+ head="""
116
+ <meta name="format-detection" content="telephone=no">
117
+ <meta name="robots" content="noindex, nofollow, noarchive">
118
+ <meta name="referrer" content="no-referrer" />
119
+ """
120
+ ) as demo:
121
+ gr.Markdown("""
122
+ # Saliency Map demo.
123
+ """)
124
+ with gr.Accordion("取り扱い説明書", open=False):
125
+ gr.Markdown("""
126
+ 1. inputタブで画像を選択します。
127
+ 2. Submitボタンを押します。
128
+ 3. 結果は、JETタブとHOTタブに表示します。
129
+ """)
130
+ algorithm_type = gr.Radio(
131
+ ["SpectralResidual", "FineGrained"],
132
+ label="Saliency",
133
+ value="SpectralResidual",
134
+ interactive=True
135
+ )
136
+
137
+ submit_button = gr.Button("submit", variant="primary")
138
+
139
+ with gr.Row():
140
+ with gr.Tab("input", id="input"):
141
+ image_input = gr.Image(sources=["upload", "clipboard"], interactive=True)
142
+ with gr.Tab("overlay(JET)"):
143
+ image_overlay_jet = gr.Image(interactive=False)
144
+ # tab_jet.select(jet_tab_selected,
145
+ # inputs=[image_input],
146
+ # outputs=image_overlay_jet)
147
+ with gr.Tab("overlay(HOT)"):
148
+ image_overlay_hot = gr.Image(interactive=False)
149
+ # tab_hot.select(hot_tab_selected,
150
+ # inputs=[image_input],
151
+ # outputs=image_overlay_hot, api_name=False)
152
+ #
153
+ submit_button.click(
154
+ submit_clicked,
155
+ inputs=[image_input, algorithm_type],
156
+ outputs=[image_overlay_jet, image_overlay_hot]
157
+ )
158
+ gr.Markdown(f"""
159
+ Python {sys.version}
160
+ App {get_package_version()}
161
+ """)
162
+
163
+ demo.queue(default_concurrency_limit=1)
164
+
165
+ log.info(f"#アプリ起動完了({watch.elapsed:.3f}s)アプリを終了するにはCtrl+Cキーを入力してください。")
166
 
167
 
168
  if __name__ == "__main__":
169
+ log.info(f"#launch({watch.elapsed:.3f}s)")
170
+ # アプリを起動します。
171
+ # https://www.gradio.app/docs/gradio/blocks#blocks-launch
172
+ demo.launch(
173
+ inbrowser=args.inbrowser,
174
+ share=args.share,
175
+ server_port=args.server_port,
176
+ max_file_size=args.max_file_size,
177
+ )
178
+
179
+ log.info(f"#Hot Reload完了({watch.elapsed:.3f}s)")
run_hot_reload.bat ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ @echo on
2
+
3
+ cd %~dp0
4
+ call venv\Scripts\activate
5
+ gradio app.py
6
+
7
+ TIMEOUT /T 10
src/myapp.py DELETED
@@ -1,154 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """myapp Widget"""
3
- import argparse
4
- #from datetime import datetime
5
- import sys
6
- from typing import Literal
7
-
8
- import gradio as gr
9
- import numpy as np
10
-
11
- from . import PROGRAM_NAME
12
- from src.reporter import log
13
- from src.saliency import SaliencyMap, convert_colormap
14
- from src.utils import Stopwatch, get_package_version
15
-
16
- log.info("#アプリ起動中")
17
- watch = Stopwatch.start_new()
18
-
19
-
20
- def jet_tab_selected(image: np.ndarray):
21
- """
22
- JETタブを選択時
23
- """
24
- #print(f"{datetime.now()}#jet")
25
- saliency = SaliencyMap("SpectralResidual")
26
- success, saliency_map = saliency.compute(image)
27
- if not success:
28
- return image # エラーが発生した場合は入力画像を返します。
29
- retval = convert_colormap(image, saliency_map, "jet")
30
- #print(f"{datetime.now()}#jet")
31
- return retval
32
-
33
-
34
- def hot_tab_selected(image: np.ndarray):
35
- """
36
- HOTタブを選択時
37
- """
38
- #print(f"{datetime.now()}#hot")
39
- saliency = SaliencyMap("SpectralResidual")
40
- success, saliency_map = saliency.compute(image)
41
- if not success:
42
- return image # エラーが発生した場合は入力画像を返します。
43
- retval = convert_colormap(image, saliency_map, "turbo")
44
- #print(f"{datetime.now()}#hot")
45
- return retval
46
-
47
-
48
- def submit_clicked(image: np.ndarray, algorithm: Literal["SpectralResidual", "FineGrained"]):
49
- """
50
- 入力画像を元に顕著マップを計算します。
51
-
52
- Parameters:
53
- image: 入力画像
54
- str: 顕著性マップのアルゴリズム
55
- Returns:
56
- np.ndarray: JET画像
57
- np.ndarray: HOT画像
58
- """
59
- sw = Stopwatch.start_new()
60
- log.info(f"#submit_clicked({sw.elapsed:.3f}s)")
61
- #
62
- saliency = SaliencyMap(algorithm)
63
- log.info(f"#SaliencyMap({sw.elapsed:.3f}s)")
64
- success, saliency_map = saliency.compute(image)
65
- log.info(f"#compute({sw.elapsed:.3f}s)")
66
-
67
- if not success:
68
- return image, image # エラーが発生した場合は入力画像を返します。
69
-
70
- log.info(f"#jet({sw.elapsed:.3f}s)")
71
- jet = convert_colormap(image, saliency_map, "jet")
72
- # jet = None
73
- log.info(f"#hot({sw.elapsed:.3f}s)")
74
- hot = convert_colormap(image, saliency_map, "hot")
75
- saliency = None
76
- log.info(f"#submit_clicked({sw.elapsed:.3f}s)")
77
- return jet, hot
78
-
79
-
80
- def run_app(args: argparse.Namespace) -> None:
81
- """
82
- アプリの画面を作成し、Gradioサービスを起動します。
83
-
84
- Parameters:
85
- args: コマンドライン引数
86
- watch: 起動したスタート時間
87
- """
88
- # analytics_enabled=False
89
- # https://github.com/gradio-app/gradio/issues/4226
90
- with gr.Blocks(
91
- analytics_enabled=False,
92
- title=f"{PROGRAM_NAME} {get_package_version()}",
93
- head="""
94
- <meta name="format-detection" content="telephone=no">
95
- <meta name="robots" content="noindex, nofollow, noarchive">
96
- <meta name="referrer" content="no-referrer" />
97
- """
98
- ) as demo:
99
-
100
- gr.Markdown("""
101
- # Saliency Map demo.
102
- """)
103
- with gr.Accordion("取り扱い説明書", open=False):
104
- gr.Markdown("""
105
- 1. inputタブで画像を選択します。
106
- 2. Submitボタンを押します。
107
- 3. 結果は、JETタブとHOTタブに表示します。
108
- """)
109
- algorithm_type = gr.Radio(
110
- ["SpectralResidual", "FineGrained"],
111
- label="Saliency",
112
- value="SpectralResidual",
113
- interactive=True
114
- )
115
-
116
- submit_button = gr.Button("submit", variant="primary")
117
-
118
- with gr.Row():
119
- with gr.Tab("input", id="input"):
120
- image_input = gr.Image(sources=["upload", "clipboard"],
121
- interactive=True)
122
- with gr.Tab("overlay(JET)"):
123
- image_overlay_jet = gr.Image(interactive=False)
124
- # tab_jet.select(jet_tab_selected,
125
- # inputs=[image_input],
126
- # outputs=image_overlay_jet)
127
- with gr.Tab("overlay(HOT)"):
128
- image_overlay_hot = gr.Image(interactive=False)
129
- # tab_hot.select(hot_tab_selected,
130
- # inputs=[image_input],
131
- # outputs=image_overlay_hot, api_name=False)
132
- #
133
- submit_button.click(
134
- submit_clicked,
135
- inputs=[image_input, algorithm_type],
136
- outputs=[image_overlay_jet,
137
- image_overlay_hot]
138
- )
139
-
140
- gr.Markdown(f"""
141
- Python {sys.version}
142
- App {get_package_version()}
143
- """)
144
-
145
- demo.queue(default_concurrency_limit=5)
146
-
147
- log.info(f"#アプリ起動完了({watch.stop():.3f}s)")
148
- # https://www.gradio.app/docs/gradio/blocks#blocks-launch
149
- demo.launch(
150
- inbrowser=args.inbrowser,
151
- share=args.share,
152
- server_port=args.server_port,
153
- max_file_size=args.max_file_size,
154
- )