Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,22 +2,20 @@ import os
|
|
| 2 |
import sys
|
| 3 |
import subprocess
|
| 4 |
|
| 5 |
-
# --- УСТАНОВКА
|
| 6 |
try:
|
| 7 |
-
import llama_cpp
|
| 8 |
from llama_cpp import Llama
|
| 9 |
-
|
|
|
|
| 10 |
except ImportError:
|
| 11 |
-
print("Установка llama-cpp-python...")
|
| 12 |
-
#
|
| 13 |
subprocess.check_call([
|
| 14 |
sys.executable, "-m", "pip", "install",
|
| 15 |
-
"llama-cpp-python",
|
| 16 |
-
"--upgrade",
|
| 17 |
"--extra-index-url", "https://abetlen.github.io/llama-cpp-python/whl/cpu"
|
| 18 |
])
|
| 19 |
-
print("Установка завершена!
|
| 20 |
-
import llama_cpp
|
| 21 |
from llama_cpp import Llama
|
| 22 |
|
| 23 |
import gradio as gr
|
|
@@ -25,6 +23,7 @@ from huggingface_hub import hf_hub_download
|
|
| 25 |
import base64
|
| 26 |
import io
|
| 27 |
import re
|
|
|
|
| 28 |
|
| 29 |
# Настройки модели
|
| 30 |
REPO_ID = "mradermacher/VisualQuality-R1-7B-GGUF"
|
|
@@ -42,45 +41,43 @@ def load_model():
|
|
| 42 |
filename=MODEL_FILENAME
|
| 43 |
)
|
| 44 |
|
| 45 |
-
#
|
| 46 |
-
chat_handler = None
|
| 47 |
-
try:
|
| 48 |
-
# Проверяем, есть ли встроенная поддержка Qwen2-VL в chat_format
|
| 49 |
-
from llama_cpp.llama_chat_format import Qwen2VLChatHandler
|
| 50 |
-
print("Используем Qwen2VLChatHandler")
|
| 51 |
-
chat_handler = Qwen2VLChatHandler()
|
| 52 |
-
except ImportError:
|
| 53 |
-
print("Специфичный Qwen2VLChatHandler не найден, используем стандартный режим.")
|
| 54 |
-
# В новых версиях llama.cpp поддержка может быть нативной без Python-хендлера,
|
| 55 |
-
# если не переопределять chat_format.
|
| 56 |
-
|
| 57 |
llm = Llama(
|
| 58 |
model_path=model_path,
|
| 59 |
-
n_ctx=
|
| 60 |
n_gpu_layers=0, # CPU
|
| 61 |
verbose=True,
|
| 62 |
-
|
| 63 |
-
# ВАЖНО: Убрали chat_format="chatml...", чтобы не ломать vision-логику
|
| 64 |
)
|
| 65 |
print("Модель успешно загружена!")
|
| 66 |
except Exception as e:
|
| 67 |
-
print(f"
|
| 68 |
raise e
|
| 69 |
return llm
|
| 70 |
|
| 71 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
buffered = io.BytesIO()
|
| 73 |
-
|
| 74 |
-
image =
|
| 75 |
-
image.save(buffered, format="JPEG", quality=95)
|
| 76 |
return base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 77 |
|
| 78 |
def evaluate_image(image, progress=gr.Progress()):
|
| 79 |
if image is None:
|
| 80 |
return "Пожалуйста, загрузите изображение.", ""
|
| 81 |
|
| 82 |
-
progress(0, desc="
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
system_prompt = "You are doing the image quality assessment task."
|
| 86 |
user_prompt_text = (
|
|
@@ -90,8 +87,8 @@ def evaluate_image(image, progress=gr.Progress()):
|
|
| 90 |
"Please only output the final answer with only one score in <answer> </answer> tags."
|
| 91 |
)
|
| 92 |
|
| 93 |
-
progress(0.
|
| 94 |
-
base64_image =
|
| 95 |
image_url = f"data:image/jpeg;base64,{base64_image}"
|
| 96 |
|
| 97 |
messages = [
|
|
@@ -106,12 +103,12 @@ def evaluate_image(image, progress=gr.Progress()):
|
|
| 106 |
]
|
| 107 |
|
| 108 |
full_response = ""
|
| 109 |
-
print("
|
| 110 |
|
| 111 |
try:
|
| 112 |
stream = model.create_chat_completion(
|
| 113 |
messages=messages,
|
| 114 |
-
max_tokens=
|
| 115 |
temperature=0.6,
|
| 116 |
stream=True
|
| 117 |
)
|
|
@@ -123,14 +120,20 @@ def evaluate_image(image, progress=gr.Progress()):
|
|
| 123 |
content = delta["content"]
|
| 124 |
full_response += content
|
| 125 |
yield full_response, "Вычисляется..."
|
|
|
|
| 126 |
except ValueError as e:
|
| 127 |
-
# Если
|
| 128 |
-
|
| 129 |
-
print(
|
| 130 |
-
yield
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
return
|
| 132 |
|
| 133 |
-
#
|
| 134 |
score_match = re.search(r'<answer>\s*([\d\.]+)\s*</answer>', full_response)
|
| 135 |
final_score = score_match.group(1) if score_match else "Не найдено"
|
| 136 |
|
|
@@ -138,16 +141,19 @@ def evaluate_image(image, progress=gr.Progress()):
|
|
| 138 |
|
| 139 |
with gr.Blocks(title="VisualQuality-R1 (Q8 GGUF)") as demo:
|
| 140 |
gr.Markdown("# 👁️ VisualQuality-R1 (7B Q8)")
|
| 141 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
with gr.Row():
|
| 144 |
with gr.Column():
|
| 145 |
-
input_img = gr.Image(type="pil", label="
|
| 146 |
-
run_btn = gr.Button("Оценить
|
| 147 |
|
| 148 |
with gr.Column():
|
| 149 |
-
output_score = gr.Label(label="
|
| 150 |
-
output_text = gr.Textbox(label="
|
| 151 |
|
| 152 |
run_btn.click(
|
| 153 |
fn=evaluate_image,
|
|
|
|
| 2 |
import sys
|
| 3 |
import subprocess
|
| 4 |
|
| 5 |
+
# --- УСТАНОВКА LLAMA-CPP-PYTHON (Runtime) ---
|
| 6 |
try:
|
|
|
|
| 7 |
from llama_cpp import Llama
|
| 8 |
+
from llama_cpp.llama_chat_format import Llava15ChatHandler
|
| 9 |
+
print("Библиотека llama-cpp-python проверена.")
|
| 10 |
except ImportError:
|
| 11 |
+
print("Установка llama-cpp-python с поддержкой CPU...")
|
| 12 |
+
# Устанавливаем версию с официального индекса разработчика
|
| 13 |
subprocess.check_call([
|
| 14 |
sys.executable, "-m", "pip", "install",
|
| 15 |
+
"llama-cpp-python>=0.3.2",
|
|
|
|
| 16 |
"--extra-index-url", "https://abetlen.github.io/llama-cpp-python/whl/cpu"
|
| 17 |
])
|
| 18 |
+
print("Установка завершена! Импортируем...")
|
|
|
|
| 19 |
from llama_cpp import Llama
|
| 20 |
|
| 21 |
import gradio as gr
|
|
|
|
| 23 |
import base64
|
| 24 |
import io
|
| 25 |
import re
|
| 26 |
+
from PIL import Image
|
| 27 |
|
| 28 |
# Настройки модели
|
| 29 |
REPO_ID = "mradermacher/VisualQuality-R1-7B-GGUF"
|
|
|
|
| 41 |
filename=MODEL_FILENAME
|
| 42 |
)
|
| 43 |
|
| 44 |
+
# ВАЖНО: chat_format="qwen2vl" включает встроенный хендлер для картинок
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
llm = Llama(
|
| 46 |
model_path=model_path,
|
| 47 |
+
n_ctx=12288, # 12k контекста (хватит для HD картинки)
|
| 48 |
n_gpu_layers=0, # CPU
|
| 49 |
verbose=True,
|
| 50 |
+
chat_format="qwen2vl" # Явно включаем режим Qwen2-VL
|
|
|
|
| 51 |
)
|
| 52 |
print("Модель успешно загружена!")
|
| 53 |
except Exception as e:
|
| 54 |
+
print(f"Критическая ошибка загрузки: {e}")
|
| 55 |
raise e
|
| 56 |
return llm
|
| 57 |
|
| 58 |
+
def process_image(image):
|
| 59 |
+
# Ресайз слишком больших изображений для экономии памяти и контекста
|
| 60 |
+
max_size = 1024
|
| 61 |
+
if max(image.size) > max_size:
|
| 62 |
+
ratio = max_size / max(image.size)
|
| 63 |
+
new_size = (int(image.size[0] * ratio), int(image.size[1] * ratio))
|
| 64 |
+
image = image.resize(new_size, Image.Resampling.LANCZOS)
|
| 65 |
+
|
| 66 |
+
# Конвертация в Base64
|
| 67 |
buffered = io.BytesIO()
|
| 68 |
+
image = image.convert("RGB")
|
| 69 |
+
image.save(buffered, format="JPEG", quality=90)
|
|
|
|
| 70 |
return base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 71 |
|
| 72 |
def evaluate_image(image, progress=gr.Progress()):
|
| 73 |
if image is None:
|
| 74 |
return "Пожалуйста, загрузите изображение.", ""
|
| 75 |
|
| 76 |
+
progress(0, desc="Инициализация...")
|
| 77 |
+
try:
|
| 78 |
+
model = load_model()
|
| 79 |
+
except Exception as e:
|
| 80 |
+
return f"Ошибка инициализации модели: {str(e)}", "Ошибка"
|
| 81 |
|
| 82 |
system_prompt = "You are doing the image quality assessment task."
|
| 83 |
user_prompt_text = (
|
|
|
|
| 87 |
"Please only output the final answer with only one score in <answer> </answer> tags."
|
| 88 |
)
|
| 89 |
|
| 90 |
+
progress(0.1, desc="Обработка изображения...")
|
| 91 |
+
base64_image = process_image(image)
|
| 92 |
image_url = f"data:image/jpeg;base64,{base64_image}"
|
| 93 |
|
| 94 |
messages = [
|
|
|
|
| 103 |
]
|
| 104 |
|
| 105 |
full_response = ""
|
| 106 |
+
print("Отправка запроса в модель...")
|
| 107 |
|
| 108 |
try:
|
| 109 |
stream = model.create_chat_completion(
|
| 110 |
messages=messages,
|
| 111 |
+
max_tokens=1500,
|
| 112 |
temperature=0.6,
|
| 113 |
stream=True
|
| 114 |
)
|
|
|
|
| 120 |
content = delta["content"]
|
| 121 |
full_response += content
|
| 122 |
yield full_response, "Вычисляется..."
|
| 123 |
+
|
| 124 |
except ValueError as e:
|
| 125 |
+
# Если формат чата не сработал
|
| 126 |
+
err = f"Ошибка формата: {e}. Попробуйте перезагрузить Space."
|
| 127 |
+
print(err)
|
| 128 |
+
yield err, "Error"
|
| 129 |
+
return
|
| 130 |
+
except Exception as e:
|
| 131 |
+
err = f"Внутренняя ошибка: {e}"
|
| 132 |
+
print(err)
|
| 133 |
+
yield err, "Error"
|
| 134 |
return
|
| 135 |
|
| 136 |
+
# Извлечение оценки
|
| 137 |
score_match = re.search(r'<answer>\s*([\d\.]+)\s*</answer>', full_response)
|
| 138 |
final_score = score_match.group(1) if score_match else "Не найдено"
|
| 139 |
|
|
|
|
| 141 |
|
| 142 |
with gr.Blocks(title="VisualQuality-R1 (Q8 GGUF)") as demo:
|
| 143 |
gr.Markdown("# 👁️ VisualQuality-R1 (7B Q8)")
|
| 144 |
+
gr.Markdown(
|
| 145 |
+
"Оценка качества (IQA) с CoT. Работает на CPU (медленно!).\n"
|
| 146 |
+
"Если видите ошибку 'context window', попробуйте картинку меньшего разрешения."
|
| 147 |
+
)
|
| 148 |
|
| 149 |
with gr.Row():
|
| 150 |
with gr.Column():
|
| 151 |
+
input_img = gr.Image(type="pil", label="Изображение")
|
| 152 |
+
run_btn = gr.Button("Оценить", variant="primary")
|
| 153 |
|
| 154 |
with gr.Column():
|
| 155 |
+
output_score = gr.Label(label="Оценка")
|
| 156 |
+
output_text = gr.Textbox(label="Рассуждения (CoT)", lines=15)
|
| 157 |
|
| 158 |
run_btn.click(
|
| 159 |
fn=evaluate_image,
|