video_screen / app.py
AlexCool2024's picture
Update app.py
84a4a41 verified
raw
history blame
2.71 kB
import streamlit as st
import numpy as np
import cv2
import requests
import tempfile
import os
# Заголовок приложения
st.title("Video Frame to Image Description")
# Загрузка видеофайла
uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov"])
try:
response = requests.get("https://hf.space")
print(f"Status Code: {response.status_code}")
except requests.exceptions.SSLError as e:
print("SSL error occurred:", e)
cap = None # Инициализируем объект cap как None
if uploaded_file is not None:
# Создаем временный файл для хранения видео
tfile = tempfile.NamedTemporaryFile(delete=False)
tfile.write(uploaded_file.read())
# Захват видео
cap = cv2.VideoCapture(tfile.name)
length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if length > 0:
# Выбор случайного кадра
random_frame = np.random.randint(length)
cap.set(cv2.CAP_PROP_POS_FRAMES, random_frame)
ret, frame = cap.read()
if ret:
# Отображение выбранного кадра
st.image(frame, channels="BGR", caption=f"Random Frame {random_frame}")
# Конвертация кадра в подходящий формат для отправки в модель
_, buf = cv2.imencode('.jpg', frame)
files = {'file': ('image.jpg', buf.tobytes(), 'image/jpeg')}
model_url = "https://hf.space/embed/nttdataspain/Image-To-Text-Lora-ViT/run/predict"
headers = {"Authorization": f"Bearer {os.getenv('HUGGINGFACE_TOKEN_READ')}"}
# Отправка изображения в модель
response = requests.post(
model_url,
headers=headers,
files=files,
verify=False
)
# Получение и отображение результата
if response.status_code == 200:
result = response.json()
description = result['data'][0]['generated_text']
st.success(f"Generated Description: {description}")
else:
st.error("Error: Could not get a response from the model.")
else:
st.error("Error: Could not read a frame from the video.")
else:
st.error("Error: Video file does not contain any frames.")
# Проверяем, был ли cap создан, и только тогда освобождаем ресурсы
if cap is not None:
cap.release()