Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -8,6 +8,7 @@ import spaces
|
|
8 |
import cv2
|
9 |
from pathlib import Path
|
10 |
from PIL import Image
|
|
|
11 |
|
12 |
MODEL_ID = "Qwen/Qwen2.5-VL-7B-Instruct" # или "Qwen/Qwen2.5-VL-3B-Instruct"
|
13 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
@@ -17,27 +18,43 @@ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
|
17 |
torch_dtype=torch.bfloat16
|
18 |
).to("cuda").eval()
|
19 |
|
20 |
-
|
21 |
-
def extract_frames(video_path, interval=2.0):
|
22 |
"""
|
23 |
-
Извлекает
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
"""
|
25 |
cap = cv2.VideoCapture(video_path)
|
26 |
-
frames = []
|
27 |
fps = cap.get(cv2.CAP_PROP_FPS)
|
28 |
if fps == 0:
|
29 |
fps = 25 # запасное значение
|
30 |
-
|
31 |
-
frame_count = 0
|
32 |
-
while True:
|
33 |
-
ret, frame = cap.read()
|
34 |
-
if not ret:
|
35 |
-
break
|
36 |
-
if frame_count % frame_interval == 0:
|
37 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
38 |
-
frames.append(Image.fromarray(frame))
|
39 |
-
frame_count += 1
|
40 |
cap.release()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
return frames
|
42 |
|
43 |
@spaces.GPU
|
@@ -47,16 +64,15 @@ def model_inference(input_dict, history):
|
|
47 |
|
48 |
images = []
|
49 |
video_extensions = [".mp4", ".avi", ".mov", ".mkv"]
|
50 |
-
|
51 |
if files:
|
52 |
for file in files:
|
53 |
ext = Path(file).suffix.lower()
|
54 |
if ext in video_extensions:
|
55 |
try:
|
56 |
-
#
|
57 |
-
frames =
|
58 |
if frames:
|
59 |
-
# Можно передать все извлечённые кадры
|
60 |
images.extend(frames)
|
61 |
else:
|
62 |
gr.Error("Не удалось извлечь кадры из видео.")
|
@@ -123,7 +139,7 @@ examples = [
|
|
123 |
|
124 |
demo = gr.ChatInterface(
|
125 |
fn=model_inference,
|
126 |
-
description="# **Qwen2.5-VL-7B-Instruct**\nТеперь
|
127 |
examples=examples,
|
128 |
textbox=gr.MultimodalTextbox(label="Запрос (текст + изображение/видео)", file_types=["image", "video"], file_count="multiple"),
|
129 |
stop_btn="Остановить генерацию",
|
|
|
8 |
import cv2
|
9 |
from pathlib import Path
|
10 |
from PIL import Image
|
11 |
+
import concurrent.futures
|
12 |
|
13 |
MODEL_ID = "Qwen/Qwen2.5-VL-7B-Instruct" # или "Qwen/Qwen2.5-VL-3B-Instruct"
|
14 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
|
|
18 |
torch_dtype=torch.bfloat16
|
19 |
).to("cuda").eval()
|
20 |
|
21 |
+
def extract_frame_at(video_path, frame_index):
|
|
|
22 |
"""
|
23 |
+
Извлекает кадр по указанному индексу.
|
24 |
+
"""
|
25 |
+
cap = cv2.VideoCapture(video_path)
|
26 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_index)
|
27 |
+
ret, frame = cap.read()
|
28 |
+
cap.release()
|
29 |
+
if ret:
|
30 |
+
# Преобразуем BGR в RGB и возвращаем как PIL Image
|
31 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
32 |
+
return Image.fromarray(frame)
|
33 |
+
else:
|
34 |
+
return None
|
35 |
+
|
36 |
+
def extract_frames_parallel(video_path, interval=2.0):
|
37 |
+
"""
|
38 |
+
Извлекает кадры из видео с интервалом в секундах, выполняя запросы параллельно.
|
39 |
"""
|
40 |
cap = cv2.VideoCapture(video_path)
|
|
|
41 |
fps = cap.get(cv2.CAP_PROP_FPS)
|
42 |
if fps == 0:
|
43 |
fps = 25 # запасное значение
|
44 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
cap.release()
|
46 |
+
|
47 |
+
frame_interval = int(fps * interval)
|
48 |
+
# Вычисляем номера кадров для извлечения
|
49 |
+
frame_indices = list(range(0, total_frames, frame_interval))
|
50 |
+
|
51 |
+
frames = []
|
52 |
+
# Параллельное извлечение кадров
|
53 |
+
with concurrent.futures.ThreadPoolExecutor() as executor:
|
54 |
+
results = executor.map(lambda idx: extract_frame_at(video_path, idx), frame_indices)
|
55 |
+
for frame in results:
|
56 |
+
if frame is not None:
|
57 |
+
frames.append(frame)
|
58 |
return frames
|
59 |
|
60 |
@spaces.GPU
|
|
|
64 |
|
65 |
images = []
|
66 |
video_extensions = [".mp4", ".avi", ".mov", ".mkv"]
|
67 |
+
|
68 |
if files:
|
69 |
for file in files:
|
70 |
ext = Path(file).suffix.lower()
|
71 |
if ext in video_extensions:
|
72 |
try:
|
73 |
+
# Используем параллельное извлечение кадров с интервалом 2 секунды
|
74 |
+
frames = extract_frames_parallel(file, interval=2.0)
|
75 |
if frames:
|
|
|
76 |
images.extend(frames)
|
77 |
else:
|
78 |
gr.Error("Не удалось извлечь кадры из видео.")
|
|
|
139 |
|
140 |
demo = gr.ChatInterface(
|
141 |
fn=model_inference,
|
142 |
+
description="# **Qwen2.5-VL-7B-Instruct**\nТеперь видео обрабатываются параллельно для ускорения извлечения кадров.",
|
143 |
examples=examples,
|
144 |
textbox=gr.MultimodalTextbox(label="Запрос (текст + изображение/видео)", file_types=["image", "video"], file_count="multiple"),
|
145 |
stop_btn="Остановить генерацию",
|