Update app.py
Browse files
app.py
CHANGED
@@ -10,229 +10,132 @@ from transformers import AutoModel, AutoTokenizer
|
|
10 |
|
11 |
# Argparser
|
12 |
parser = argparse.ArgumentParser(description='demo')
|
13 |
-
parser.add_argument('--device', type=str, default='
|
|
|
14 |
args = parser.parse_args()
|
15 |
device = args.device
|
16 |
-
assert device in ['
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
# Load model
|
19 |
model_path = 'openbmb/MiniCPM-V-2'
|
20 |
-
|
21 |
-
if device == 'mps':
|
22 |
-
print('Error: running int4 model with bitsandbytes on Mac is not supported right now.')
|
23 |
-
exit()
|
24 |
-
model = AutoModel.from_pretrained(model_path, trust_remote_code=True)
|
25 |
-
else:
|
26 |
-
model = AutoModel.from_pretrained(model_path, trust_remote_code=True, torch_dtype=torch.float16, device_map=device)
|
27 |
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
28 |
-
model.eval()
|
29 |
-
|
30 |
|
|
|
|
|
31 |
|
32 |
ERROR_MSG = "Error, please retry"
|
33 |
-
model_name = 'MiniCPM-V 2'
|
34 |
|
|
|
35 |
form_radio = {
|
36 |
'choices': ['Beam Search', 'Sampling'],
|
37 |
-
#'value': 'Beam Search',
|
38 |
'value': 'Sampling',
|
39 |
'interactive': True,
|
40 |
'label': 'Decode Type'
|
41 |
}
|
42 |
-
# Beam Form
|
43 |
-
num_beams_slider = {
|
44 |
-
'minimum': 0,
|
45 |
-
'maximum': 5,
|
46 |
-
'value': 3,
|
47 |
-
'step': 1,
|
48 |
-
'interactive': True,
|
49 |
-
'label': 'Num Beams'
|
50 |
-
}
|
51 |
-
repetition_penalty_slider = {
|
52 |
-
'minimum': 0,
|
53 |
-
'maximum': 3,
|
54 |
-
'value': 1.2,
|
55 |
-
'step': 0.01,
|
56 |
-
'interactive': True,
|
57 |
-
'label': 'Repetition Penalty'
|
58 |
-
}
|
59 |
-
repetition_penalty_slider2 = {
|
60 |
-
'minimum': 0,
|
61 |
-
'maximum': 3,
|
62 |
-
'value': 1.05,
|
63 |
-
'step': 0.01,
|
64 |
-
'interactive': True,
|
65 |
-
'label': 'Repetition Penalty'
|
66 |
-
}
|
67 |
-
max_new_tokens_slider = {
|
68 |
-
'minimum': 1,
|
69 |
-
'maximum': 4096,
|
70 |
-
'value': 1024,
|
71 |
-
'step': 1,
|
72 |
-
'interactive': True,
|
73 |
-
'label': 'Max New Tokens'
|
74 |
-
}
|
75 |
-
|
76 |
-
top_p_slider = {
|
77 |
-
'minimum': 0,
|
78 |
-
'maximum': 1,
|
79 |
-
'value': 0.8,
|
80 |
-
'step': 0.05,
|
81 |
-
'interactive': True,
|
82 |
-
'label': 'Top P'
|
83 |
-
}
|
84 |
-
top_k_slider = {
|
85 |
-
'minimum': 0,
|
86 |
-
'maximum': 200,
|
87 |
-
'value': 100,
|
88 |
-
'step': 1,
|
89 |
-
'interactive': True,
|
90 |
-
'label': 'Top K'
|
91 |
-
}
|
92 |
-
temperature_slider = {
|
93 |
-
'minimum': 0,
|
94 |
-
'maximum': 2,
|
95 |
-
'value': 0.7,
|
96 |
-
'step': 0.05,
|
97 |
-
'interactive': True,
|
98 |
-
'label': 'Temperature'
|
99 |
-
}
|
100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
def create_component(params, comp='Slider'):
|
103 |
if comp == 'Slider':
|
104 |
-
return gr.Slider(
|
105 |
-
minimum=params['minimum'],
|
106 |
-
maximum=params['maximum'],
|
107 |
-
value=params['value'],
|
108 |
-
step=params['step'],
|
109 |
-
interactive=params['interactive'],
|
110 |
-
label=params['label']
|
111 |
-
)
|
112 |
elif comp == 'Radio':
|
113 |
-
return gr.Radio(
|
114 |
-
choices=params['choices'],
|
115 |
-
value=params['value'],
|
116 |
-
interactive=params['interactive'],
|
117 |
-
label=params['label']
|
118 |
-
)
|
119 |
elif comp == 'Button':
|
120 |
-
return gr.Button(
|
121 |
-
value=params['value'],
|
122 |
-
interactive=True
|
123 |
-
)
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
default_params = {"num_beams":3, "repetition_penalty": 1.2, "max_new_tokens": 1024}
|
128 |
if params is None:
|
129 |
params = default_params
|
130 |
if img is None:
|
131 |
return -1, "Error, invalid image, please upload a new image", None, None
|
132 |
try:
|
133 |
image = img.convert('RGB')
|
134 |
-
answer = model.chat(
|
135 |
-
|
136 |
-
|
137 |
-
tokenizer=tokenizer,
|
138 |
-
**params
|
139 |
-
)
|
140 |
-
res = re.sub(r'(<box>.*</box>)', '', answer)
|
141 |
-
res = res.replace('<ref>', '')
|
142 |
-
res = res.replace('</ref>', '')
|
143 |
-
res = res.replace('<box>', '')
|
144 |
-
answer = res.replace('</box>', '')
|
145 |
-
return 0, answer, None, None
|
146 |
except Exception as err:
|
147 |
print(err)
|
148 |
traceback.print_exc()
|
149 |
return -1, ERROR_MSG, None, None
|
150 |
|
151 |
-
|
152 |
def upload_img(image, _chatbot, _app_session):
|
153 |
image = Image.fromarray(image)
|
154 |
-
|
155 |
-
_app_session['
|
156 |
-
_app_session['
|
157 |
-
_app_session['img']=image
|
158 |
_chatbot.append(('', 'Image uploaded successfully, you can talk to me now'))
|
159 |
return _chatbot, _app_session
|
160 |
|
161 |
-
|
162 |
def respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
|
163 |
if _app_cfg.get('ctx', None) is None:
|
164 |
_chat_bot.append((_question, 'Please upload an image to start'))
|
165 |
return '', _chat_bot, _app_cfg
|
166 |
|
167 |
_context = _app_cfg['ctx'].copy()
|
168 |
-
|
169 |
-
_context.append({"role": "user", "content": _question})
|
170 |
-
else:
|
171 |
-
_context = [{"role": "user", "content": _question}]
|
172 |
-
print('<User>:', _question)
|
173 |
|
174 |
if params_form == 'Beam Search':
|
175 |
-
params = {
|
176 |
-
|
177 |
-
'num_beams': num_beams,
|
178 |
-
'repetition_penalty': repetition_penalty,
|
179 |
-
"max_new_tokens": 896
|
180 |
-
}
|
181 |
-
else:
|
182 |
params = {
|
183 |
'sampling': True,
|
184 |
'top_p': top_p,
|
185 |
'top_k': top_k,
|
186 |
'temperature': temperature,
|
187 |
'repetition_penalty': repetition_penalty_2,
|
188 |
-
"max_new_tokens": 896
|
189 |
}
|
|
|
190 |
code, _answer, _, sts = chat(_app_cfg['img'], _context, None, params)
|
191 |
-
|
192 |
-
|
193 |
_context.append({"role": "assistant", "content": _answer})
|
194 |
_chat_bot.append((_question, _answer))
|
195 |
if code == 0:
|
196 |
-
_app_cfg['ctx']=_context
|
197 |
-
_app_cfg['sts']=sts
|
198 |
return '', _chat_bot, _app_cfg
|
199 |
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
return '', _chat_bot, _app_cfg
|
205 |
-
elif _chat_bot[-1][0] == 'Regenerate':
|
206 |
-
return '', _chat_bot, _app_cfg
|
207 |
-
else:
|
208 |
-
_question = _chat_bot[-1][0]
|
209 |
-
_chat_bot = _chat_bot[:-1]
|
210 |
-
_app_cfg['ctx'] = _app_cfg['ctx'][:-2]
|
211 |
-
return respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature)
|
212 |
-
|
213 |
-
|
214 |
|
215 |
with gr.Blocks() as demo:
|
|
|
|
|
216 |
with gr.Row():
|
217 |
with gr.Column(scale=2, min_width=300):
|
218 |
-
app_session = gr.State({'sts':None,'ctx':None,'img':None})
|
219 |
bt_pic = gr.Image(label="Upload an image to start")
|
220 |
-
txt_message = gr.Textbox(label="
|
|
|
221 |
with gr.Column(scale=2, min_width=300):
|
222 |
-
chat_bot = gr.Chatbot(label=f"
|
223 |
-
|
224 |
-
regenerate.click(
|
225 |
-
regenerate_button_clicked,
|
226 |
-
[txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
|
227 |
-
[txt_message, chat_bot, app_session]
|
228 |
-
)
|
229 |
txt_message.submit(
|
230 |
respond,
|
231 |
-
[txt_message, chat_bot, app_session
|
232 |
[txt_message, chat_bot, app_session]
|
233 |
)
|
234 |
-
bt_pic.upload(lambda: None, None, chat_bot, queue=False).then(upload_img, inputs=[bt_pic,chat_bot,app_session], outputs=[chat_bot,app_session])
|
235 |
|
236 |
-
|
237 |
-
|
238 |
|
|
|
|
|
|
10 |
|
11 |
# Argparser
|
12 |
parser = argparse.ArgumentParser(description='demo')
|
13 |
+
parser.add_argument('--device', type=str, default='cpu', help='cpu')
|
14 |
+
parser.add_argument('--dtype', type=str, default='fp32', help='fp32')
|
15 |
args = parser.parse_args()
|
16 |
device = args.device
|
17 |
+
assert device in ['cpu']
|
18 |
+
|
19 |
+
# Set dtype
|
20 |
+
if args.dtype == 'fp32':
|
21 |
+
dtype = torch.float32
|
22 |
+
else:
|
23 |
+
dtype = torch.float16
|
24 |
|
25 |
# Load model
|
26 |
model_path = 'openbmb/MiniCPM-V-2'
|
27 |
+
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).to(dtype=dtype)
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
|
|
|
|
29 |
|
30 |
+
model = model.to(device=device)
|
31 |
+
model.eval()
|
32 |
|
33 |
ERROR_MSG = "Error, please retry"
|
34 |
+
model_name = 'MiniCPM-V 2.0'
|
35 |
|
36 |
+
# UI Components
|
37 |
form_radio = {
|
38 |
'choices': ['Beam Search', 'Sampling'],
|
|
|
39 |
'value': 'Sampling',
|
40 |
'interactive': True,
|
41 |
'label': 'Decode Type'
|
42 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
+
# Sliders and their settings
|
45 |
+
num_beams_slider = {'minimum': 0, 'maximum': 5, 'value': 3, 'step': 1, 'interactive': True, 'label': 'Num Beams'}
|
46 |
+
repetition_penalty_slider = {'minimum': 0, 'maximum': 3, 'value': 1.2, 'step': 0.01, 'interactive': True, 'label': 'Repetition Penalty'}
|
47 |
+
repetition_penalty_slider2 = {'minimum': 0, 'maximum': 3, 'value': 1.05, 'step': 0.01, 'interactive': True, 'label': 'Repetition Penalty'}
|
48 |
+
max_new_tokens_slider = {'minimum': 1, 'maximum': 4096, 'value': 1024, 'step': 1, 'interactive': True, 'label': 'Max New Tokens'}
|
49 |
+
top_p_slider = {'minimum': 0, 'maximum': 1, 'value': 0.8, 'step': 0.05, 'interactive': True, 'label': 'Top P'}
|
50 |
+
top_k_slider = {'minimum': 0, 'maximum': 200, 'value': 100, 'step': 1, 'interactive': True, 'label': 'Top K'}
|
51 |
+
temperature_slider = {'minimum': 0, 'maximum': 2, 'value': 0.7, 'step': 0.05, 'interactive': True, 'label': 'Temperature'}
|
52 |
|
53 |
def create_component(params, comp='Slider'):
|
54 |
if comp == 'Slider':
|
55 |
+
return gr.Slider(**params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
elif comp == 'Radio':
|
57 |
+
return gr.Radio(choices=params['choices'], value=params['value'], interactive=params['interactive'], label=params['label'])
|
|
|
|
|
|
|
|
|
|
|
58 |
elif comp == 'Button':
|
59 |
+
return gr.Button(value=params['value'], interactive=True)
|
|
|
|
|
|
|
60 |
|
61 |
+
def chat(img, msgs, ctx, params=None):
|
62 |
+
default_params = {"num_beams": 3, "repetition_penalty": 1.2, "max_new_tokens": 1024}
|
|
|
63 |
if params is None:
|
64 |
params = default_params
|
65 |
if img is None:
|
66 |
return -1, "Error, invalid image, please upload a new image", None, None
|
67 |
try:
|
68 |
image = img.convert('RGB')
|
69 |
+
answer, context, _ = model.chat(image=image, msgs=msgs, context=None, tokenizer=tokenizer, **params)
|
70 |
+
res = re.sub(r'(<box>.*</box>)', '', answer).replace('<ref>', '').replace('</ref>', '').replace('<box>', '').replace('</box>', '')
|
71 |
+
return 0, res, None, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
except Exception as err:
|
73 |
print(err)
|
74 |
traceback.print_exc()
|
75 |
return -1, ERROR_MSG, None, None
|
76 |
|
|
|
77 |
def upload_img(image, _chatbot, _app_session):
|
78 |
image = Image.fromarray(image)
|
79 |
+
_app_session['sts'] = None
|
80 |
+
_app_session['ctx'] = []
|
81 |
+
_app_session['img'] = image
|
|
|
82 |
_chatbot.append(('', 'Image uploaded successfully, you can talk to me now'))
|
83 |
return _chatbot, _app_session
|
84 |
|
|
|
85 |
def respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
|
86 |
if _app_cfg.get('ctx', None) is None:
|
87 |
_chat_bot.append((_question, 'Please upload an image to start'))
|
88 |
return '', _chat_bot, _app_cfg
|
89 |
|
90 |
_context = _app_cfg['ctx'].copy()
|
91 |
+
_context.append({"role": "user", "content": _question})
|
|
|
|
|
|
|
|
|
92 |
|
93 |
if params_form == 'Beam Search':
|
94 |
+
params = {'sampling': False, 'num_beams': num_beams, 'repetition_penalty': repetition_penalty, "max_new_tokens": 896}
|
95 |
+
else: # Ensure this block is executed for Sampling
|
|
|
|
|
|
|
|
|
|
|
96 |
params = {
|
97 |
'sampling': True,
|
98 |
'top_p': top_p,
|
99 |
'top_k': top_k,
|
100 |
'temperature': temperature,
|
101 |
'repetition_penalty': repetition_penalty_2,
|
102 |
+
"max_new_tokens": 896
|
103 |
}
|
104 |
+
|
105 |
code, _answer, _, sts = chat(_app_cfg['img'], _context, None, params)
|
106 |
+
|
|
|
107 |
_context.append({"role": "assistant", "content": _answer})
|
108 |
_chat_bot.append((_question, _answer))
|
109 |
if code == 0:
|
110 |
+
_app_cfg['ctx'] = _context
|
111 |
+
_app_cfg['sts'] = sts
|
112 |
return '', _chat_bot, _app_cfg
|
113 |
|
114 |
+
def clear(chat_bot, app_session):
|
115 |
+
app_session['img'] = None
|
116 |
+
chat_bot.clear()
|
117 |
+
return chat_bot
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
with gr.Blocks() as demo:
|
120 |
+
gr.Markdown("<h1 style='text-align: center;'>Medical Assistant</h1>")
|
121 |
+
|
122 |
with gr.Row():
|
123 |
with gr.Column(scale=2, min_width=300):
|
124 |
+
app_session = gr.State({'sts': None, 'ctx': None, 'img': None})
|
125 |
bt_pic = gr.Image(label="Upload an image to start")
|
126 |
+
txt_message = gr.Textbox(label="Ask your question...")
|
127 |
+
|
128 |
with gr.Column(scale=2, min_width=300):
|
129 |
+
chat_bot = gr.Chatbot(label=f"Chatbot")
|
130 |
+
clear_button = gr.Button(value='Clear')
|
|
|
|
|
|
|
|
|
|
|
131 |
txt_message.submit(
|
132 |
respond,
|
133 |
+
[txt_message, chat_bot, app_session],
|
134 |
[txt_message, chat_bot, app_session]
|
135 |
)
|
|
|
136 |
|
137 |
+
bt_pic.upload(lambda: None, None, chat_bot, queue=False).then(upload_img, inputs=[bt_pic, chat_bot, app_session], outputs=[chat_bot, app_session])
|
138 |
+
clear_button.click(clear, [chat_bot, app_session], chat_bot)
|
139 |
|
140 |
+
# Launch
|
141 |
+
demo.launch(share=True, debug=True, show_api=False)
|