#!/opt/homebrew/bin/python3.11
"""
ASR三方案上下并列对比

展示三个方案在相同时间段的文字识别差异（上下并列格式）
"""

import json
from pathlib import Path
from difflib import SequenceMatcher

def load_segments(json_path):
    """加载segments"""
    with open(json_path) as f:
        data = json.load(f)
    return data['asr_output']['segments']

def align_segments_by_time(seg_a, seg_b, seg_d):
    """按时间对齐三个方案的segments"""
    aligned = []
    
    # 使用方案A作为基准
    for seg_a_item in seg_a:
        start_a = seg_a_item['start']
        
        # 找到方案B和D中时间相近的segment
        seg_b_match = None
        seg_d_match = None
        
        for seg_b_item in seg_b:
            if abs(seg_b_item['start'] - start_a) < 3.0:
                seg_b_match = seg_b_item
                break
        
        for seg_d_item in seg_d:
            if abs(seg_d_item['start'] - start_a) < 3.0:
                seg_d_match = seg_d_item
                break
        
        if seg_b_match and seg_d_match:
            text_a = seg_a_item['text']
            text_b = seg_b_match['text']
            text_d = seg_d_match['text']
            
            # 只显示有差异的
            if text_a != text_b or text_a != text_d or text_b != text_d:
                aligned.append({
                    'time': start_a,
                    'text_a': text_a,
                    'text_b': text_b,
                    'text_d': text_d,
                    'sim_ab': SequenceMatcher(None, text_a, text_b).ratio(),
                    'sim_ad': SequenceMatcher(None, text_a, text_d).ratio(),
                    'sim_bd': SequenceMatcher(None, text_b, text_d).ratio()
                })
    
    return aligned

def print_side_by_side(aligned, max_display=50):
    """上下并列打印"""
    print()
    print("="*80)
    print("三方案文字差异上下并列对比")
    print("="*80)
    print()
    
    print(f"共发现 {len(aligned)} 处差异")
    print()
    
    for i, item in enumerate(aligned[:max_display]):
        print(f"[{i+1}] 时间: {item['time']:.2f}秒")
        print(f"    方案A (faster-whisper): \"{item['text_a']}\"")
        print(f"    方案B (whisper small):  \"{item['text_b']}\"")
        print(f"    方案D (whisper medium): \"{item['text_d']}\"")
        
        # 显示相似度
        sim_ab = item['sim_ab']
        sim_ad = item['sim_ad']
        sim_bd = item['sim_bd']
        
        if sim_ab < 0.9:
            print(f"    ⚠️ A vs B: {sim_ab*100:.1f}%相似")
        if sim_ad < 0.9:
            print(f"    ⚠️ A vs D: {sim_ad*100:.1f}%相似")
        if sim_bd < 0.9:
            print(f"    ⚠️ B vs D: {sim_bd*100:.1f}%相似")
        
        print()
    
    if len(aligned) > max_display:
        print(f"... 还有 {len(aligned) - max_display} 处差异")

def generate_full_report(aligned, output_path):
    """生成完整报告文件"""
    lines = []
    
    lines.append("# ASR三方案文字差异上下并列对比报告")
    lines.append("")
    lines.append("## 测试方案")
    lines.append("")
    lines.append("| 方案 | 引擎 | 模型 | Segments |")
    lines.append("|------|------|------|---------|")
    lines.append("| **A** | faster-whisper | small (int8) | 77 |")
    lines.append("| **B** | OpenAI whisper | small | 78 |")
    lines.append("| **D** | OpenAI whisper | medium | 74 |")
    lines.append("")
    lines.append("---")
    lines.append("")
    lines.append("## 差异总览")
    lines.append("")
    lines.append(f"共发现 **{len(aligned)}** 处文字差异")
    lines.append("")
    lines.append("---")
    lines.append("")
    lines.append("## 详细对比（上下并列）")
    lines.append("")
    
    for i, item in enumerate(aligned):
        lines.append(f"### [{i+1}] 时间: {item['time']:.2f}秒")
        lines.append("")
        lines.append("| 方案 | 文字 | 相似度 |")
        lines.append("|------|------|--------|")
        lines.append(f"| **A** (faster-whisper) | \"{item['text_a']}\" | - |")
        lines.append(f"| **B** (whisper small) | \"{item['text_b']}\" | A vs B: {item['sim_ab']*100:.1f}% |")
        lines.append(f"| **D** (whisper medium) | \"{item['text_d']}\" | B vs D: {item['sim_bd']*100:.1f}% |")
        lines.append("")
        
        # 分析差异类型
        if item['text_a'] == item['text_b'] and item['text_a'] != item['text_d']:
            lines.append("**差异类型**: A和B一致，D不同")
        elif item['text_a'] == item['text_d'] and item['text_a'] != item['text_b']:
            lines.append("**差异类型**: A和D一致，B不同")
        elif item['text_b'] == item['text_d'] and item['text_b'] != item['text_a']:
            lines.append("**差异类型**: B和D一致，A不同")
        elif item['text_a'] != item['text_b'] and item['text_a'] != item['text_d'] and item['text_b'] != item['text_d']:
            lines.append("**差异类型**: 三方案完全不同")
        
        lines.append("")
        lines.append("---")
        lines.append("")
    
    lines.append("## 总结")
    lines.append("")
    lines.append(f"- 总差异处: {len(aligned)}")
    lines.append(f"- A vs B相似度低于90%: {sum(1 for i in aligned if i['sim_ab'] < 0.9)}")
    lines.append(f"- A vs D相似度低于90%: {sum(1 for i in aligned if i['sim_ad'] < 0.9)}")
    lines.append(f"- B vs D相似度低于90%: {sum(1 for i in aligned if i['sim_bd'] < 0.9)}")
    lines.append("")
    
    with open(output_path, 'w') as f:
        f.write('\n'.join(lines))
    
    print(f"\n完整报告已保存: {output_path}")

def main():
    output_dir = Path('/Users/accusys/momentry_core_0.1/output/benchmark')
    
    # 加载修正后的数据
    seg_a_path = output_dir / 'exasan_pcie/scheme_A_faster-whisper_small_cpu.json'
    seg_b_path = output_dir / 'exasan_pcie/scheme_B_whisper_small_cpu.json'
    seg_d_path = output_dir / 'exasan_pcie/scheme_D_whisper_medium_cpu.json'
    
    seg_a = load_segments(seg_a_path)
    seg_b = load_segments(seg_b_path)
    seg_d = load_segments(seg_d_path)
    
    print("="*80)
    print("ASR三方案数据加载")
    print("="*80)
    print()
    print(f"方案A: {len(seg_a)} segments")
    print(f"方案B: {len(seg_b)} segments")
    print(f"方案D: {len(seg_d)} segments")
    
    # 按时间对齐
    aligned = align_segments_by_time(seg_a, seg_b, seg_d)
    
    # 打印上下并列对比
    print_side_by_side(aligned, max_display=30)
    
    # 生成完整报告
    report_path = output_dir / 'ASR_SIDE_BY_SIDE_COMPARISON.md'
    generate_full_report(aligned, report_path)

if __name__ == '__main__':
    main()