chwellofficial/nt360Slides
0
1import os2from typing import BinaryIO3import uuid4 5from fastapi import UploadFile6 7 8def replace_file_name(filename: str, new_stem: str) -> str:9 _, ext = os.path.splitext(filename)10 return f"{new_stem}{ext}"11 12 13def get_file_name_with_random_uuid(file: str | UploadFile | BinaryIO) -> str:14 filename = None15 if getattr(file, "filename", None):16 filename = file.filename17 elif isinstance(file, str):18 filename = os.path.basename(file)19 else:20 filename = str(uuid.uuid4())21 22 return replace_file_name(23 filename, f"{os.path.splitext(filename)[0]}----{str(uuid.uuid4())}"24 )25 26 27def get_original_file_name(file_path: str) -> str:28 base_name = os.path.basename(file_path)29 name = base_name.split("----")[0]30 ext = get_file_ext_or_none(base_name)31 return f"{name}{ext}"32 33 34def get_file_ext_or_none(filename: str) -> str | None:35 splitted = os.path.splitext(filename)36 if len(splitted) > 1:37 return splitted[-1]38 return None39 40 41def set_file_ext(file_path: str, ext: str) -> str:42 if get_file_ext_or_none(file_path):43 return f"{os.path.splitext(file_path)[0]}{ext}"44 return f"{file_path}{ext}"45 