from pathlib import Path
import torch
from transformers import AutoConfig, AutoModelForCausalLM, AutoProcessor


model_path = Path(__file__).parent.resolve()
print(f"Loading model from: {model_path}")

# 加载模型配置
config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
print(f"Model config: {config.model_type}")
print(f"Architecture: {config.architectures}")

# 加载处理器（tokenizer + image processor + ts processor）
print("\nLoading processor...")
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)

# 加载模型（使用 bfloat16 精度和自动设备映射）
print("\nLoading model...")
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    dtype=torch.bfloat16,
    device_map="auto",
    # attn_implementation="flash_attention_2",  #时序暂不支持flash_attn，load加这行会报错
    trust_remote_code=True
)

print(f"✓ Model loaded successfully!")
print(f"Model type: {type(model).__name__}")
print(f"Model device: {model.device}")

# ============================================================================
# 测试 3: 时序对话
# ============================================================================
print("\n" + "=" * 80)
print("测试 3: 时序对话")
print("=" * 80)

messages = [
    {
        "role": "user",
        "content": [
            {"type": "time_series", "data": "./0092638_seism.npy", "sampling_rate": 100},
            {"type": "text", "text": "Please determine whether an Earthquake event has occurred in the provided time-series data. If so, please specify the starting time point indices of the P-wave and S-wave in the event."},
        ],
    }
]

time_series_inputs = processor.time_series_preprocessor(messages)
multimodal_inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", enable_thinking=False, **time_series_inputs).to(model.device, dtype=torch.bfloat16)

print("\n生成时序回复...")
with torch.inference_mode():
    multimodal_generated_ids = model.generate(
        **multimodal_inputs,
        max_new_tokens=200,
        do_sample=False,
        temperature=1.0,
    )

# 提取生成的 token（去除输入部分）
multimodal_generated_ids_trimmed = [
    out_ids[len(in_ids):] for in_ids, out_ids in zip(multimodal_inputs.input_ids, multimodal_generated_ids)
]

# 解码为文本
multimodal_output = processor.batch_decode(
    multimodal_generated_ids_trimmed,
    skip_special_tokens=True,
    clean_up_tokenization_spaces=False
)

print("\n" + "-" * 80)
print("时序输出：")
print("-" * 80)
print(multimodal_output[0])
print("-" * 80)
print("\n✅ 时序功能测试完成！")