VOIDER commited on
Commit
5855ef7
·
verified ·
1 Parent(s): 45c7b52

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -53
app.py CHANGED
@@ -4,7 +4,6 @@ from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor, Bits
4
  from qwen_vl_utils import process_vision_info
5
  from threading import Thread
6
  import re
7
- import random
8
  import spaces
9
 
10
  # Константы
@@ -20,26 +19,38 @@ PROMPT = (
20
  QUESTION_TEMPLATE_THINKING = "{Question} First output the thinking process in <think> </think> tags and then output the final answer with only one score in <answer> </answer> tags."
21
  QUESTION_TEMPLATE_NO_THINKING = "{Question} Please only output the final answer with only one score in <answer> </answer> tags."
22
 
23
- # Конфигурация 8-bit квантизации
24
- quantization_config = BitsAndBytesConfig(
25
- load_in_8bit=True,
26
- llm_int8_threshold=6.0,
27
- llm_int8_has_fp16_weight=False,
28
- )
29
 
30
- print("Loading model...")
31
- model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
32
- MODEL_PATH,
33
- quantization_config=quantization_config,
34
- device_map="auto",
35
- trust_remote_code=True,
36
- torch_dtype=torch.float16,
37
- )
38
- model.eval()
39
 
40
- processor = AutoProcessor.from_pretrained(MODEL_PATH, trust_remote_code=True)
41
- processor.tokenizer.padding_side = "left"
42
- print("Model loaded successfully!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
 
45
  def extract_score(text):
@@ -53,7 +64,7 @@ def extract_score(text):
53
  score_match = re.search(r'\d+(\.\d+)?', model_answer)
54
  if score_match:
55
  score = float(score_match.group())
56
- return min(max(score, 1.0), 5.0) # Ограничение от 1 до 5
57
  except Exception as e:
58
  print(f"Error extracting score: {e}")
59
  return None
@@ -67,9 +78,14 @@ def extract_thinking(text):
67
  return None
68
 
69
 
70
- @spaces.GPU(duration=120)
71
  def score_image_streaming(image, use_thinking=True):
72
  """Оценка качества изображения со стримингом"""
 
 
 
 
 
73
  if image is None:
74
  yield "❌ Please upload an image first.", "", ""
75
  return
@@ -134,7 +150,7 @@ def score_image_streaming(image, use_thinking=True):
134
  # Стриминг вывода
135
  generated_text = ""
136
  current_thinking = ""
137
- current_score = ""
138
 
139
  for new_text in streamer:
140
  generated_text += new_text
@@ -149,10 +165,7 @@ def score_image_streaming(image, use_thinking=True):
149
  if score is not None:
150
  current_score = f"⭐ **Quality Score: {score:.2f} / 5.00**"
151
 
152
- # Форматирование вывода
153
- display_text = generated_text
154
-
155
- yield display_text, current_thinking, current_score
156
 
157
  thread.join()
158
 
@@ -174,23 +187,6 @@ def create_interface():
174
  with gr.Blocks(
175
  title="VisualQuality-R1: Image Quality Assessment",
176
  theme=gr.themes.Soft(),
177
- css="""
178
- .score-box {
179
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
180
- border-radius: 10px;
181
- padding: 20px;
182
- color: white;
183
- text-align: center;
184
- font-size: 1.2em;
185
- }
186
- .thinking-box {
187
- background-color: #f0f4f8;
188
- border-left: 4px solid #667eea;
189
- padding: 15px;
190
- border-radius: 5px;
191
- font-style: italic;
192
- }
193
- """
194
  ) as demo:
195
 
196
  gr.Markdown("""
@@ -260,16 +256,6 @@ def create_interface():
260
  interactive=False
261
  )
262
 
263
- # Примеры
264
- gr.Markdown("### 📸 Example Images")
265
- gr.Examples(
266
- examples=[
267
- ["https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/PNG_transparency_demonstration_1.png/300px-PNG_transparency_demonstration_1.png"],
268
- ],
269
- inputs=[image_input],
270
- label="Click to try"
271
- )
272
-
273
  # Обработка события
274
  submit_btn.click(
275
  fn=score_image_streaming,
 
4
  from qwen_vl_utils import process_vision_info
5
  from threading import Thread
6
  import re
 
7
  import spaces
8
 
9
  # Константы
 
19
  QUESTION_TEMPLATE_THINKING = "{Question} First output the thinking process in <think> </think> tags and then output the final answer with only one score in <answer> </answer> tags."
20
  QUESTION_TEMPLATE_NO_THINKING = "{Question} Please only output the final answer with only one score in <answer> </answer> tags."
21
 
22
+ # Глобальные переменные для модели
23
+ model = None
24
+ processor = None
 
 
 
25
 
 
 
 
 
 
 
 
 
 
26
 
27
+ def load_model():
28
+ """Загрузка модели с 8-bit квантизацией"""
29
+ global model, processor
30
+
31
+ if model is not None:
32
+ return
33
+
34
+ print("Loading model...")
35
+
36
+ quantization_config = BitsAndBytesConfig(
37
+ load_in_8bit=True,
38
+ llm_int8_threshold=6.0,
39
+ )
40
+
41
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
42
+ MODEL_PATH,
43
+ quantization_config=quantization_config,
44
+ device_map="auto",
45
+ trust_remote_code=True,
46
+ torch_dtype=torch.float16,
47
+ )
48
+ model.eval()
49
+
50
+ processor = AutoProcessor.from_pretrained(MODEL_PATH, trust_remote_code=True)
51
+ processor.tokenizer.padding_side = "left"
52
+
53
+ print("Model loaded successfully!")
54
 
55
 
56
  def extract_score(text):
 
64
  score_match = re.search(r'\d+(\.\d+)?', model_answer)
65
  if score_match:
66
  score = float(score_match.group())
67
+ return min(max(score, 1.0), 5.0)
68
  except Exception as e:
69
  print(f"Error extracting score: {e}")
70
  return None
 
78
  return None
79
 
80
 
81
+ @spaces.GPU(duration=180)
82
  def score_image_streaming(image, use_thinking=True):
83
  """Оценка качества изображения со стримингом"""
84
+ global model, processor
85
+
86
+ # Загрузка модели при первом вызове
87
+ load_model()
88
+
89
  if image is None:
90
  yield "❌ Please upload an image first.", "", ""
91
  return
 
150
  # Стриминг вывода
151
  generated_text = ""
152
  current_thinking = ""
153
+ current_score = "*Analyzing...*"
154
 
155
  for new_text in streamer:
156
  generated_text += new_text
 
165
  if score is not None:
166
  current_score = f"⭐ **Quality Score: {score:.2f} / 5.00**"
167
 
168
+ yield generated_text, current_thinking, current_score
 
 
 
169
 
170
  thread.join()
171
 
 
187
  with gr.Blocks(
188
  title="VisualQuality-R1: Image Quality Assessment",
189
  theme=gr.themes.Soft(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  ) as demo:
191
 
192
  gr.Markdown("""
 
256
  interactive=False
257
  )
258
 
 
 
 
 
 
 
 
 
 
 
259
  # Обработка события
260
  submit_btn.click(
261
  fn=score_image_streaming,