from pathlib import Path
from tqdm import tqdm
from mutagen.mp3 import MP3
from mutagen import MutagenError
import pandas as pd

workspace_dir = Path(__file__).parent.parent.parent

def format_duration(seconds):
    """将秒数格式化为 时:分:秒 的格式"""
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    
    if hours > 0:
        return f"{hours}小时{minutes}分{secs}秒"
    elif minutes > 0:
        return f"{minutes}分{secs}秒"
    else:
        return f"{secs}秒"

def get_mp3_duration(file_path: Path):
    """获取单个MP3文件的时长（秒）"""
    try:
        audio = MP3(file_path)
        return audio.info.length
    except MutagenError as e:
        print(f"错误：无法读取文件 {file_path} - {e}")
        return None
    except Exception as e:
        print(f"错误：处理文件 {file_path} 时出错 - {e}")
        return None

def analyze_mp3_files(directory: Path, ):
    """分析目录中的所有MP3文件"""
    results = []
    total_duration = 0
    df = pd.read_csv(workspace_dir / '.data/ug/val_new.tsv', sep='\t')

    for _, row in tqdm(df.iterrows(), total=len(df), desc="anlayze audio"):
        mp3_file: Path = workspace_dir / '.data/ug/clips'  / row['path']
        duration = get_mp3_duration(mp3_file)
        
        if duration is not None:
            total_duration += duration
            duration_str = format_duration(duration)
            file_size = mp3_file.stat().st_size / (1024 * 1024)  # 转换为MB
            
            result_line = f"{mp3_file.name:<50} {duration_str:>20} ({file_size:.2f} MB)"
            results.append(result_line)
        else:
            error_line = f"{mp3_file.name:<50} {'读取失败':>20}"
            print(error_line)
            results.append(error_line)

    mp3_files: list[Path] = []
    for ext in ['*.mp3', '*.MP3']:
            mp3_files.extend(directory.rglob(ext))
    
    print(f"tsv 找到 {len(results)} 个MP3文件\n")
    print(f"找到 {len(mp3_files)} 个MP3文件\n")
    print(f"\n总时长: {format_duration(total_duration)}")
    print(f"总时长(秒): {total_duration:.2f} 秒")
    print(f"总时长(分钟): {total_duration/60:.2f} 分钟")
    print(f"总时长(小时): {total_duration/3600:.2f} 小时")
    print(f"文件总数: {len(mp3_files)}")


audio_directory = Path(workspace_dir / '.data/ug/clips')
analyze_mp3_files(directory=audio_directory)
