cppowboy commited on
Commit
514e45b
1 Parent(s): f507de7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -0
app.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # encoding: utf-8
3
+ import gradio as gr
4
+ from PIL import Image
5
+ import requests
6
+ import base64
7
+ from io import BytesIO
8
+ import traceback
9
+ import os
10
+
11
+
12
+ def upload_img(image,_chatbot,_app_session):
13
+ image = Image.fromarray(image)
14
+ _app_session['sts']=None
15
+ _app_session['ctx']=''
16
+ _app_session['img']=image
17
+ _chatbot.append(('图片解析成功,可以和我对话了', ''))
18
+ return _chatbot,_app_session
19
+
20
+
21
+ def respond( _question, _chat_bot,_app_cfg):
22
+ try:
23
+ img = _app_cfg['img']
24
+ buffered = BytesIO()
25
+ img.save(buffered, format="JPEG")
26
+ img_str = base64.b64encode(buffered.getvalue()).decode('utf-8')
27
+ url = os.environ['SERVICE_URL']
28
+ _answer = requests.post(url, headers={
29
+ "X-Model-Best-Model": "viscpm-chat-balance",
30
+ "X-Model-Best-Trace-ID": "test-trace",
31
+ }, json={
32
+ "image": img_str,
33
+ "question": _question,
34
+ }).json()
35
+ _answer = _answer['data']['response']
36
+ print(f'question: {_question}, answer: {_answer}')
37
+ except Exception as e:
38
+ print(traceback.format_exc())
39
+ _answer = "请求失败"
40
+ _chat_bot.append((_question, _answer))
41
+ _context = _app_cfg['ctx'] + '\n' + _question + '\n' + _answer + '\n'
42
+ sts = None
43
+ _app_cfg['ctx'] = _context
44
+ _app_cfg['sts'] = sts
45
+ return '', _chat_bot, _app_cfg
46
+
47
+
48
+ with gr.Blocks() as demo:
49
+ app_session = gr.State({'sts':None,'ctx':None,'img':None})
50
+ bt_pic = gr.Image(label="先上传一张图片")
51
+ chat_bot = gr.Chatbot(label="聊天对话")
52
+ txt_message = gr.Textbox(label="输入文字")
53
+
54
+ txt_message.submit(respond, [ txt_message, chat_bot,app_session], [txt_message,chat_bot,app_session])
55
+ 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])
56
+
57
+
58
+ demo.queue(concurrency_count=1, max_size=20).launch(share=False, debug=True, server_port=7890,
59
+ server_name="0.0.0.0")