import os import uuid import shutil from fastapi import UploadFile from app.config import settings class FileService: """文件上传、存储、删除""" def __init__(self): os.makedirs(settings.UPLOAD_DIR, exist_ok=True) os.makedirs(os.path.join(settings.UPLOAD_DIR, "transcripts"), exist_ok=True) os.makedirs(os.path.join(settings.UPLOAD_DIR, "persons"), exist_ok=True) os.makedirs(settings.EXPORT_DIR, exist_ok=True) async def save_transcript(self, file: UploadFile) -> dict: """保存上传的文字稿""" file_id = str(uuid.uuid4()) ext = os.path.splitext(file.filename)[1] save_name = f"{file_id}{ext}" save_dir = os.path.join(settings.UPLOAD_DIR, "transcripts") save_path = os.path.join(save_dir, save_name) content = await file.read() with open(save_path, "wb") as f: f.write(content) return { "id": file_id, "filename": file.filename, "file_path": save_path, "file_size": len(content), } async def save_person(self, file: UploadFile) -> dict: """保存上传的讲述者信息""" file_id = str(uuid.uuid4()) ext = os.path.splitext(file.filename)[1] save_name = f"{file_id}{ext}" save_dir = os.path.join(settings.UPLOAD_DIR, "persons") save_path = os.path.join(save_dir, save_name) content = await file.read() with open(save_path, "wb") as f: f.write(content) return { "id": file_id, "filename": file.filename, "file_path": save_path, "file_size": len(content), } def delete_file(self, file_path: str) -> bool: """删除文件""" if os.path.exists(file_path): os.remove(file_path) return True return False file_service = FileService()