Spaces:
Sleeping
Sleeping
Alexandre Gazola
commited on
Commit
·
81c782d
1
Parent(s):
012177f
utils
Browse files
utils.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import cv2
|
3 |
+
from typing import List
|
4 |
+
from io import BytesIO
|
5 |
+
import numpy as np
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
def encode_frame_to_base64(frame: cv2.Mat) -> str:
|
9 |
+
"""
|
10 |
+
Convert a cv2.Mat frame to a base64-encoded string.
|
11 |
+
"""
|
12 |
+
_, buffer = cv2.imencode('.jpg', frame)
|
13 |
+
encoded_string = base64.b64encode(buffer).decode('utf-8')
|
14 |
+
return encoded_string
|
15 |
+
|
16 |
+
def decode_base64_to_frame(encoded_string: str) -> cv2.Mat:
|
17 |
+
"""
|
18 |
+
Convert a base64-encoded string back to a cv2.Mat frame.
|
19 |
+
"""
|
20 |
+
decoded_data = base64.b64decode(encoded_string)
|
21 |
+
np_array = np.frombuffer(decoded_data, dtype=np.uint8)
|
22 |
+
return cv2.imdecode(np_array, cv2.IMREAD_COLOR)
|
23 |
+
|
24 |
+
def get_bytes(image_path: str) -> bytes:
|
25 |
+
with open(image_path, "rb") as f:
|
26 |
+
return f.read()
|
27 |
+
|
28 |
+
def get_text_file_contents(file_path):
|
29 |
+
"""
|
30 |
+
Reads a text file from the specified path and returns its content as a string.
|
31 |
+
|
32 |
+
Args:
|
33 |
+
file_path (str): The path to the text file.
|
34 |
+
|
35 |
+
Returns:
|
36 |
+
str: The content of the file, or None if an error occurred.
|
37 |
+
"""
|
38 |
+
try:
|
39 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
40 |
+
content = file.read()
|
41 |
+
return content
|
42 |
+
except FileNotFoundError:
|
43 |
+
print(f"Error: File not found at path: {file_path}")
|
44 |
+
return None
|
45 |
+
except Exception as e:
|
46 |
+
print(f"An error occurred while reading the file: {e}")
|
47 |
+
return None
|
48 |
+
|
49 |
+
def clean_text(text: str) -> str:
|
50 |
+
return text.encode("ascii", errors="ignore").decode()
|
51 |
+
|
52 |
+
def get_base64(path: str) -> str:
|
53 |
+
with open(path, "rb") as f:
|
54 |
+
return base64.b64encode(f.read()).decode("utf-8")
|