Spaces:
Sleeping
Sleeping
AlexCool2024
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,22 +1,37 @@
|
|
1 |
import streamlit as st
|
2 |
import numpy as np
|
3 |
import cv2
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
|
8 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
st.title("Video Frame to Image Description")
|
10 |
|
11 |
# Загрузка видеофайла
|
12 |
uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov"])
|
13 |
|
14 |
-
try:
|
15 |
-
response = requests.get("https://hf.space")
|
16 |
-
print(f"Status Code: {response.status_code}")
|
17 |
-
except requests.exceptions.SSLError as e:
|
18 |
-
print("SSL error occurred:", e)
|
19 |
-
|
20 |
cap = None # Инициализируем объект cap как None
|
21 |
|
22 |
if uploaded_file is not None:
|
@@ -35,31 +50,16 @@ if uploaded_file is not None:
|
|
35 |
ret, frame = cap.read()
|
36 |
|
37 |
if ret:
|
|
|
|
|
|
|
|
|
38 |
# Отображение выбранного кадра
|
39 |
-
st.image(
|
40 |
-
|
41 |
-
# Конвертация кадра в подходящий формат для отправки в модель
|
42 |
-
_, buf = cv2.imencode('.jpg', frame)
|
43 |
-
files = {'file': ('image.jpg', buf.tobytes(), 'image/jpeg')}
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
# Отправка изображения в модель
|
49 |
-
response = requests.post(
|
50 |
-
model_url,
|
51 |
-
headers=headers,
|
52 |
-
files=files,
|
53 |
-
verify=False
|
54 |
-
)
|
55 |
-
|
56 |
-
# Получение и отображение результата
|
57 |
-
if response.status_code == 200:
|
58 |
-
result = response.json()
|
59 |
-
description = result['data'][0]['generated_text']
|
60 |
-
st.success(f"Generated Description: {description}")
|
61 |
-
else:
|
62 |
-
st.error("Error: Could not get a response from the model.")
|
63 |
else:
|
64 |
st.error("Error: Could not read a frame from the video.")
|
65 |
else:
|
@@ -67,4 +67,4 @@ if uploaded_file is not None:
|
|
67 |
|
68 |
# Проверяем, был ли cap создан, и только тогда освобождаем ресурсы
|
69 |
if cap is not None:
|
70 |
-
cap.release()
|
|
|
1 |
import streamlit as st
|
2 |
import numpy as np
|
3 |
import cv2
|
4 |
+
import torch
|
5 |
+
from PIL import Image
|
6 |
+
from transformers import AutoTokenizer, ViTFeatureExtractor, VisionEncoderDecoderModel
|
7 |
|
8 |
+
# Инициализация модели
|
9 |
+
model_id = "nttdataspain/vit-gpt2-stablediffusion2-lora"
|
10 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_id)
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
12 |
+
feature_extractor = ViTFeatureExtractor.from_pretrained(model_id)
|
13 |
+
|
14 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
15 |
+
model.to(device)
|
16 |
+
|
17 |
+
# Функция для получения текста из изображения
|
18 |
+
def predict(image):
|
19 |
+
img = image.convert('RGB')
|
20 |
+
model.eval()
|
21 |
+
pixel_values = feature_extractor(images=[img], return_tensors="pt").pixel_values.to(device)
|
22 |
+
with torch.no_grad():
|
23 |
+
output_ids = model.generate(pixel_values, max_length=16, num_beams=4, return_dict_in_generate=True).sequences
|
24 |
+
|
25 |
+
preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
26 |
+
preds = [pred.strip() for pred in preds]
|
27 |
+
return preds[0]
|
28 |
+
|
29 |
+
# Streamlit интерфейс
|
30 |
st.title("Video Frame to Image Description")
|
31 |
|
32 |
# Загрузка видеофайла
|
33 |
uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov"])
|
34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
cap = None # Инициализируем объект cap как None
|
36 |
|
37 |
if uploaded_file is not None:
|
|
|
50 |
ret, frame = cap.read()
|
51 |
|
52 |
if ret:
|
53 |
+
# Конвертация кадра OpenCV в PIL Image
|
54 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
55 |
+
pil_image = Image.fromarray(frame_rgb)
|
56 |
+
|
57 |
# Отображение выбранного кадра
|
58 |
+
st.image(pil_image, caption=f"Random Frame {random_frame}")
|
|
|
|
|
|
|
|
|
59 |
|
60 |
+
# Получение текста из изображения
|
61 |
+
description = predict(pil_image)
|
62 |
+
st.success(f"Generated Description: {description}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
else:
|
64 |
st.error("Error: Could not read a frame from the video.")
|
65 |
else:
|
|
|
67 |
|
68 |
# Проверяем, был ли cap создан, и только тогда освобождаем ресурсы
|
69 |
if cap is not None:
|
70 |
+
cap.release()
|