WhateverBlue commited on
Commit
0c9dd7c
·
verified ·
1 Parent(s): 278661f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +176 -62
app.py CHANGED
@@ -1,70 +1,184 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
3
 
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
-
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
4
+ from qwen_vl_utils import process_vision_info
5
+ import os
6
 
7
+ # Model path configuration - can be loaded from environment variable or default path
8
+ MODEL_PATH = os.getenv("MODEL_PATH", "Jiaqi-hkust/Robust-R1")
9
 
10
+ # Global variables to store model and processor
11
+ model = None
12
+ processor = None
 
 
 
 
 
 
 
 
 
 
13
 
14
+ def load_model():
15
+ """Load model and processor"""
16
+ global model, processor
17
+
18
+ if model is None or processor is None:
19
+ print(f"Loading model: {MODEL_PATH}")
20
+
21
+ # Load model
22
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
23
+ MODEL_PATH,
24
+ torch_dtype=torch.bfloat16,
25
+ device_map="auto",
26
+ )
27
+
28
+ # Load processor
29
+ processor = AutoProcessor.from_pretrained(MODEL_PATH)
30
+
31
+ print("Model loaded successfully!")
32
+
33
+ return model, processor
34
 
35
+ def inference(image, question, max_new_tokens=1024, temperature=0.7):
36
+ """Perform inference"""
37
+ try:
38
+ # Ensure model is loaded
39
+ model, processor = load_model()
40
+
41
+ # Validate multimodal inputs
42
+ if image is None:
43
+ return "⚠️ Error: Please upload an image. This is a multimodal model that requires both an image and text input."
44
+
45
+ if not question or question.strip() == "":
46
+ return "⚠️ Error: Please enter your question. This is a multimodal model that requires both an image and text input."
47
+
48
+ # Build multimodal messages (image + text)
49
+ messages = [
50
+ {
51
+ "role": "user",
52
+ "content": [
53
+ {
54
+ "type": "image",
55
+ "image": image, # Image input
56
+ },
57
+ {"type": "text", "text": question}, # Text input
58
+ ],
59
+ }
60
+ ]
61
+
62
+ # Prepare inputs
63
+ text = processor.apply_chat_template(
64
+ messages, tokenize=False, add_generation_prompt=True
65
+ )
66
+ image_inputs, video_inputs = process_vision_info(messages)
67
+ inputs = processor(
68
+ text=[text],
69
+ images=image_inputs,
70
+ videos=video_inputs,
71
+ padding=True,
72
+ return_tensors="pt",
73
+ )
74
+
75
+ # Move inputs to the device where the model is located
76
+ device = next(model.parameters()).device
77
+ inputs = inputs.to(device)
78
+
79
+ # Generate response
80
+ generated_ids = model.generate(
81
+ **inputs,
82
+ max_new_tokens=max_new_tokens,
83
+ temperature=temperature,
84
+ do_sample=True if temperature > 0 else False,
85
+ )
86
+
87
+ # Decode output
88
+ generated_ids_trimmed = [
89
+ out_ids[len(in_ids):]
90
+ for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
91
+ ]
92
+ output_text = processor.batch_decode(
93
+ generated_ids_trimmed,
94
+ skip_special_tokens=True,
95
+ clean_up_tokenization_spaces=False
96
+ )
97
+
98
+ return output_text[0]
99
+
100
+ except Exception as e:
101
+ return f"An error occurred: {str(e)}"
102
 
103
+ # Create Gradio interface
104
+ with gr.Blocks(title="Robust-R1: Visual Understanding Demo", theme=gr.themes.Soft()) as demo:
105
+ gr.Markdown(
106
+ """
107
+ ## Citation
108
+ The following is a BibTeX reference:
109
+
110
+ """
111
+ )
112
+
113
+ with gr.Row():
114
+ with gr.Column(scale=1):
115
+ image_input = gr.Image(
116
+ type="pil",
117
+ label="📸 Upload Image (Required)",
118
+ height=400,
119
+ info="Upload an image that you want to ask questions about"
120
+ )
121
+ question_input = gr.Textbox(
122
+ label="💬 Your Question (Required)",
123
+ placeholder="e.g., Describe the content of this image",
124
+ lines=3,
125
+ info="Enter your question about the uploaded image"
126
+ )
127
+
128
+ with gr.Row():
129
+ max_tokens = gr.Slider(
130
+ minimum=64,
131
+ maximum=2048,
132
+ value=512,
133
+ step=64,
134
+ label="Max Generation Length"
135
+ )
136
+ temperature = gr.Slider(
137
+ minimum=0.1,
138
+ maximum=1.0,
139
+ value=0.7,
140
+ step=0.1,
141
+ label="Temperature"
142
+ )
143
+
144
+ submit_btn = gr.Button("Submit", variant="primary", size="lg")
145
+ clear_btn = gr.Button("Clear", variant="secondary")
146
+
147
+ with gr.Column(scale=1):
148
+ output = gr.Textbox(
149
+ label="Model Response",
150
+ lines=15,
151
+ interactive=False
152
+ )
153
+
154
+ # Examples
155
+ gr.Examples(
156
+ examples=[
157
+ ["Describe this image", "What does this image show?"],
158
+ ],
159
+ inputs=[question_input],
160
+ label="Example Questions"
161
+ )
162
+
163
+ # Bind events
164
+ submit_btn.click(
165
+ fn=inference,
166
+ inputs=[image_input, question_input, max_tokens, temperature],
167
+ outputs=output
168
+ )
169
+
170
+ clear_btn.click(
171
+ fn=lambda: (None, "", 512, 0.7, ""),
172
+ outputs=[image_input, question_input, max_tokens, temperature, output]
173
+ )
174
+
175
+ # Show message when page loads
176
+ demo.load(
177
+ fn=lambda: "Model is loading, please wait...",
178
+ outputs=output
179
+ )
180
 
181
  if __name__ == "__main__":
182
+ # When running in Space, Gradio will automatically handle the port
183
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
184
+