28 lines
842 B
Python
28 lines
842 B
Python
import base64
|
|||
|
|
import random
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
|
||
|
|
def image_to_base64(file_path: Path) -> str | None:
|
||
|
|
"""图片转 base64,文件不存在时返回 None"""
|
||
|
|
if not file_path.is_file():
|
||
|
|
return None
|
||
|
|
with open(file_path, "rb") as f:
|
||
|
|
return "base64://" + base64.b64encode(f.read()).decode()
|
||
|
|
|
||
|
|
|
||
|
|
def audio_to_base64(file_path: Path) -> str:
|
||
|
|
"""音频转 base64"""
|
||
|
|
with open(file_path, "rb") as f:
|
||
|
|
return "base64://" + base64.b64encode(f.read()).decode()
|
||
|
|
|
||
|
|
|
||
|
|
def random_audio(dir_path: Path) -> str | None:
|
||
|
|
"""随机取目录下的一个语音文件并转 base64,目录不存在或为空时返回 None"""
|
||
|
|
if not dir_path.is_dir():
|
||
|
|
return None
|
||
|
|
files = [p for p in dir_path.iterdir() if p.is_file()]
|
||
|
|
if not files:
|
||
|
|
return None
|
||
|
|
return audio_to_base64(random.choice(files))
|