AlexCool2024 commited on
Commit
cc8d245
·
verified ·
1 Parent(s): c3906ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -68
app.py CHANGED
@@ -1,71 +1,57 @@
1
- import streamlit as st
2
- import numpy as np
3
- import cv2
4
- import tempfile
5
- from gradio_client import Client
6
- from PIL import Image
7
-
8
- # Инициализация клиента для нового API
9
- client = Client("https://pragnakalp-ocr-image-to-text.hf.space/--replicas/lhzf3/")
10
- result = client.predict(
11
- PaddleOCR, # Literal[PaddleOCR, EasyOCR, KerasOCR] in 'Method' Radio component
12
- https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png, # filepath in 'img' Image component
13
- api_name="/predict"
14
- )
15
- print(result)
16
-
17
- # Заголовок приложения
18
- st.title("Video Frame to Image Description")
19
-
20
- # Загрузка видеофайла
21
- uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov"])
22
-
23
- cap = None # Инициализируем объект cap как None
24
-
25
- if uploaded_file is not None:
26
- # Создаем временный файл для хранения видео
27
- tfile = tempfile.NamedTemporaryFile(delete=False)
28
- tfile.write(uploaded_file.read())
29
 
30
- # Захват видео
31
- cap = cv2.VideoCapture(tfile.name)
32
- length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
33
 
34
- if length > 0:
35
- # Выбор случайного кадра
36
- random_frame = np.random.randint(length)
37
- cap.set(cv2.CAP_PROP_POS_FRAMES, random_frame)
38
- ret, frame = cap.read()
39
-
40
- if ret:
41
- # Конвертация кадра OpenCV в PIL Image
42
- frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
43
- pil_image = Image.fromarray(frame_rgb)
44
-
45
- # Отображение выбранного кадра
46
- st.image(pil_image, caption=f"Random Frame {random_frame}")
47
-
48
- # Сохранение изображения в байты
49
- buf = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False)
50
- pil_image.save(buf, format='JPEG')
51
- buf.close()
52
-
53
- # Отправка изображения в новый API
54
- try:
55
- result = client.predict(
56
- "PaddleOCR", # Метод для использования
57
- buf.name, # Путь к изображению
58
- api_name="/predict"
59
- )
60
- description = result['data']
61
- st.success(f"Generated Description: {description}")
62
- except Exception as e:
63
- st.error(f"Error: Could not get a response from the model. {str(e)}")
64
- else:
65
- st.error("Error: Could not read a frame from the video.")
66
- else:
67
- st.error("Error: Video file does not contain any frames.")
68
-
69
- # Проверяем, был ли cap создан, и только тогда освобождаем ресурсы
70
- if cap is not None:
71
  cap.release()
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import cv2
4
+ import tempfile
5
+ from gradio_client import Client
6
+ from PIL import Image
7
+
8
+ # Проверка доступности API
9
+ api_url = "https://pragnakalp-ocr-image-to-text.hf.space/--replicas/lhzf3/"
10
+ try:
11
+ client = Client(api_url)
12
+ except Exception as e:
13
+ st.error(f"Failed to initialize client: {str(e)}")
14
+ st.stop()
15
+
16
+ # Заголовок приложения
17
+ st.title("Video Frame to Image Description")
18
+
19
+ # Загрузка видеофайла
20
+ uploaded_file = st.file_uploader("Upload a video file", type=["mp4", "avi", "mov"])
21
+
22
+ cap = None # Инициализируем объект cap как None
23
+
24
+ if uploaded_file is not None:
25
+ tfile = tempfile.NamedTemporaryFile(delete=False)
26
+ tfile.write(uploaded_file.read())
 
 
27
 
28
+ cap = cv2.VideoCapture(tfile.name)
29
+ length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
 
30
 
31
+ if length > 0:
32
+ random_frame = np.random.randint(length)
33
+ cap.set(cv2.CAP_PROP_POS_FRAMES, random_frame)
34
+ ret, frame = cap.read()
35
+
36
+ if ret:
37
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
38
+ pil_image = Image.fromarray(frame_rgb)
39
+ st.image(pil_image, caption=f"Random Frame {random_frame}")
40
+
41
+ buf = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False)
42
+ pil_image.save(buf, format='JPEG')
43
+ buf.close()
44
+
45
+ try:
46
+ result = client.predict("PaddleOCR", buf.name, api_name="/predict")
47
+ description = result['data']
48
+ st.success(f"Generated Description: {description}")
49
+ except Exception as e:
50
+ st.error(f"Error: Could not get a response from the model. {str(e)}")
51
+ else:
52
+ st.error("Error: Could not read a frame from the video.")
53
+ else:
54
+ st.error("Error: Video file does not contain any frames.")
55
+
56
+ if cap is not None:
 
 
 
 
 
 
 
 
 
 
 
57
  cap.release()