Spaces:
Sleeping
Sleeping
| import base64 | |
| import mimetypes | |
| import os | |
| from urllib.parse import unquote, urlparse | |
| import requests | |
| from file_util import File_Util | |
| class Image_Util: | |
| """ | |
| Manipulação de imagens | |
| """ | |
| def encode_image_to_base64(image_path: str) -> str: | |
| """Codifica um arquivo de imagem (frame) para base64.""" | |
| try: | |
| with open(image_path, "rb") as image_file: | |
| return base64.b64encode(image_file.read()).decode('utf-8') | |
| except FileNotFoundError: | |
| print(f"Erro: Arquivo não encontrado em {image_path}") | |
| return None | |
| except Exception as e: | |
| print(f"Erro ao codificar imagem {image_path} para base64: {e}") | |
| return None | |
| def get_image_extension_from_url(url: str) -> str: | |
| """ | |
| Retorna a extensão do arquivo de imagem com base na URL informada. | |
| Args: | |
| url: URL da imagem (pode conter parâmetros). | |
| Returns: | |
| Extensão do arquivo (ex: 'jpg', 'png') ou None se não for possível identificar. | |
| """ | |
| path = unquote(urlparse(url).path) # decodifica e extrai o caminho da URL | |
| filename = os.path.basename(path) | |
| # Tenta extrair extensão diretamente | |
| _, ext = os.path.splitext(filename) | |
| ext = ext.lower().lstrip('.') # remove o ponto | |
| # Verifica se a extensão é de imagem conhecida | |
| if ext in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff']: | |
| return ext | |
| # Caso não haja extensão, tenta deduzir pelo tipo MIME | |
| mime_type, _ = mimetypes.guess_type(url) | |
| if mime_type and mime_type.startswith("image/"): | |
| return mime_type.split("/")[1] # ex: 'image/png' → 'png' | |
| return None | |
| def download_image_from_url(url: str, output_path: str, image_file_name: str) -> str: | |
| """ | |
| Baixa uma imagem a partir de uma URL. | |
| Args: | |
| url: url da imagem | |
| output_path: local esperado para gravação da imagem | |
| image_file_name: nome do arquivo que deve ser utilizado para download | |
| """ | |
| File_Util.create_or_clear_output_directory(output_path) | |
| image_path = f'{output_path}/{image_file_name}.{Image_Util.get_image_extension_from_url(url)}' | |
| response = requests.get(url, stream=True) | |
| if response.status_code == 200: | |
| if save_path is None: | |
| save_path = os.path.basename(url.split("?")[0]) # remove query params, se houver | |
| with open(save_path, 'wb') as f: | |
| for chunk in response.iter_content(1024): | |
| f.write(chunk) | |
| return save_path | |
| else: | |
| raise Exception(f"Erro ao baixar imagem: {response.status_code} - {response.reason}") | |
| return image_path |