suanan commited on
Commit
6edeb66
·
verified ·
1 Parent(s): 9894420

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +210 -0
  2. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import json
4
+ import torch
5
+ import requests
6
+ from PIL import Image
7
+ import soundfile as sf
8
+ import gradio as gr
9
+ from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
10
+
11
+ # -------------------------------
12
+ # 模型與處理器載入設定
13
+ # -------------------------------
14
+ model_path = "microsoft/Phi-4-multimodal-instruct"
15
+
16
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
17
+ model = AutoModelForCausalLM.from_pretrained(
18
+ model_path,
19
+ device_map="auto",
20
+ torch_dtype="auto",
21
+ trust_remote_code=True,
22
+ _attn_implementation="eager",
23
+ )
24
+
25
+ generation_config = GenerationConfig.from_pretrained(model_path)
26
+
27
+ # -------------------------------
28
+ # 根據任務模式組合 prompt 並調用模型生成結果
29
+ # -------------------------------
30
+ def process_task(mode, system_msg, user_msg, image_multi, audio, vs_images, vs_audio):
31
+ """
32
+ 根據不同任務模式組合 prompt,並使用 processor 與 model 進行生成
33
+ """
34
+ # -------------------------------
35
+ # 依據不同模式構建 prompt 與處理輸入資料
36
+ # -------------------------------
37
+ if mode == "Text Chat":
38
+ prompt = f"<|system|>{system_msg}<|end|><|user|>{user_msg}<|end|><|assistant|>"
39
+ inputs = processor(text=prompt, return_tensors='pt').to(model.device)
40
+
41
+ elif mode == "Tool-enabled Function Calling":
42
+ tools = [{
43
+ "name": "get_weather_updates",
44
+ "description": "Fetches weather updates for a given city using the RapidAPI Weather API.",
45
+ "parameters": {
46
+ "city": {
47
+ "description": "The name of the city for which to retrieve weather information.",
48
+ "type": "str",
49
+ "default": "London"
50
+ }
51
+ }
52
+ }]
53
+ tools_json = json.dumps(tools, ensure_ascii=False)
54
+ prompt = f"<|system|>{system_msg}<|tool|>{tools_json}<|/tool|><|end|><|user|>{user_msg}<|end|><|assistant|>"
55
+ inputs = processor(text=prompt, return_tensors='pt').to(model.device)
56
+
57
+ elif mode == "Vision-Language":
58
+ # 優先判斷單一圖片上傳;若無則檢查多圖上傳
59
+ if image_multi is not None and len(image_multi) > 0:
60
+ num = len(image_multi)
61
+ image_tags = ''.join([f"<|image_{i+1}|>" for i in range(num)])
62
+ prompt = f"<|user|>{image_tags}{user_msg}<|end|><|assistant|>"
63
+ images = []
64
+ for file in image_multi:
65
+ images.append(Image.open(file))
66
+ inputs = processor(text=prompt, images=images, return_tensors='pt').to(model.device)
67
+ else:
68
+ return "No image provided."
69
+
70
+ elif mode == "Speech-Language":
71
+ prompt = f"<|user|><|audio_1|>{user_msg}<|end|><|assistant|>"
72
+ if audio is None:
73
+ return "No audio provided."
74
+ # 若 audio 為 tuple,則直接取出取樣率與音訊資料
75
+ if isinstance(audio, tuple):
76
+ sample_rate, audio_data = audio
77
+ else:
78
+ audio_data, sample_rate = sf.read(audio)
79
+ inputs = processor(text=prompt, audios=[(audio_data, sample_rate)], return_tensors='pt').to(model.device)
80
+
81
+ elif mode == "Vision-Speech":
82
+ prompt = f"<|user|>"
83
+ images = []
84
+ if vs_images is not None and len(vs_images) > 0:
85
+ num = len(vs_images)
86
+ image_tags = ''.join([f"<|image_{i+1}|>" for i in range(num)])
87
+ prompt += image_tags
88
+ for file in vs_images:
89
+ images.append(Image.open(file))
90
+ if vs_audio is None:
91
+ return "No audio provided for vision-speech."
92
+ prompt += "<|audio_1|><|end|><|assistant|>"
93
+ audio_data, samplerate = sf.read(vs_audio)
94
+ inputs = processor(text=prompt, images=images, audios=[(audio_data, samplerate)], return_tensors='pt').to(model.device)
95
+
96
+ else:
97
+ return "Invalid mode."
98
+
99
+ # -------------------------------
100
+ # 調用模型生成回應
101
+ # -------------------------------
102
+ generate_ids = model.generate(
103
+ **inputs,
104
+ max_new_tokens=1000,
105
+ generation_config=generation_config,
106
+ )
107
+ # 裁剪掉輸入部分的 token
108
+ generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
109
+ response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
110
+ return response
111
+
112
+ # -------------------------------
113
+ # 更新介面元件顯示 (根據任務模式決定顯示哪些輸入區塊)
114
+ # -------------------------------
115
+ def update_visibility(mode):
116
+ if mode == "Text Chat":
117
+ return (gr.update(visible=True), # system_msg
118
+ gr.update(visible=True), # user_msg
119
+ gr.update(visible=False), # image_upload_multi (多圖)
120
+ gr.update(visible=False), # audio_upload
121
+ gr.update(visible=False), # vs_image_upload
122
+ gr.update(visible=False)) # vs_audio_upload
123
+ elif mode == "Tool-enabled Function Calling":
124
+ return (gr.update(visible=True),
125
+ gr.update(visible=True),
126
+ gr.update(visible=False),
127
+ gr.update(visible=False),
128
+ gr.update(visible=False),
129
+ gr.update(visible=False))
130
+ elif mode == "Vision-Language":
131
+ return (gr.update(visible=False),
132
+ gr.update(visible=True),
133
+ gr.update(visible=True),
134
+ gr.update(visible=False),
135
+ gr.update(visible=False),
136
+ gr.update(visible=False))
137
+ elif mode == "Speech-Language":
138
+ return (gr.update(visible=False),
139
+ gr.update(visible=True),
140
+ gr.update(visible=False),
141
+ gr.update(visible=True),
142
+ gr.update(visible=False),
143
+ gr.update(visible=False))
144
+ elif mode == "Vision-Speech":
145
+ return (gr.update(visible=False),
146
+ gr.update(visible=False),
147
+ gr.update(visible=False),
148
+ gr.update(visible=False),
149
+ gr.update(visible=True),
150
+ gr.update(visible=True))
151
+ else:
152
+ return (gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update())
153
+
154
+ # -------------------------------
155
+ # 建立 Gradio Blocks 介面
156
+ # -------------------------------
157
+ with gr.Blocks() as demo:
158
+ gr.Markdown("## Multi-Modal Prompt Builder & Model Inference")
159
+ # 任務模式選單
160
+ mode_radio = gr.Radio(
161
+ choices=["Text Chat", "Vision-Language", "Speech-Language", "Vision-Speech"], #, "Tool-enabled Function Calling"
162
+ label="Select Task Mode",
163
+ value="Text Chat"
164
+ )
165
+
166
+ # 文字輸入區塊 (Text Chat 與 Tool-enabled 都需要)
167
+ system_text = gr.Textbox(label="System Message", value="You are a helpful assistant.", visible=True)
168
+ user_text = gr.Textbox(label="User Message", visible=True)
169
+
170
+ # 圖片上傳區塊 (Vision-Language)
171
+ # image_upload = gr.Image(label="Upload Image (Single)", type="pil", visible=False)
172
+ image_upload_multi = gr.File(label="Upload Image(s) (Multiple)", file_count="multiple", visible=False)
173
+
174
+ # 音檔上傳區塊 (Speech-Language)
175
+ audio_upload = gr.Audio(label="Upload Audio (wav, mp3, flac)", visible=False)
176
+
177
+ # Vision-Speech 區塊:圖片上傳 (多張) 與音檔上傳
178
+ vs_image_upload = gr.File(label="Upload Image(s) for Vision-Speech", file_count="multiple", visible=False)
179
+ vs_audio_upload = gr.Audio(label="Upload Audio for Vision-Speech", visible=False)
180
+
181
+ # 送出按鈕與結果輸出區塊
182
+ submit_btn = gr.Button("Submit")
183
+ output_text = gr.Textbox(label="Result", lines=6)
184
+
185
+ # gr.Examples 區塊,提供部份任務的文字範例(其他任務請自行上傳圖片或音檔)
186
+ examples = gr.Examples(
187
+ examples=[
188
+ ["Text Chat", "hi who are you?"],
189
+ # ["Tool-enabled Function Calling", "You are a helpful assistant with some tools.", "What is the weather like in Paris today?"],
190
+ ["Vision-Language", "Describe the image in detail."],
191
+ ["Speech-Language", "Transcribe the audio to text."],
192
+ ["Vision-Speech", ""]
193
+ ],
194
+ inputs=[mode_radio, user_text],
195
+ label="Examples"
196
+ )
197
+
198
+ # 當任務模式改變時,更新介面各元件顯示狀態
199
+ mode_radio.change(fn=update_visibility,
200
+ inputs=mode_radio,
201
+ outputs=[system_text, user_text, image_upload_multi, audio_upload, vs_image_upload, vs_audio_upload])
202
+
203
+ # 點擊送出按鈕時根據選擇的模式與輸入內容生成 prompt 並調用模型生成回答
204
+ submit_btn.click(
205
+ fn=process_task,
206
+ inputs=[mode_radio, system_text, user_text, image_upload_multi, audio_upload, vs_image_upload, vs_audio_upload],
207
+ outputs=output_text
208
+ )
209
+
210
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ torchvision
3
+ scipy
4
+ peft
5
+ backoff
6
+ gradio
7
+ spaces
8
+ requests
9
+ torch
10
+ pillow
11
+ soundfile