import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import json
import re
from tqdm import tqdm
import os


def generate_output(tokenizer, model, input_texts):
    device = next(model.parameters()).device
    inputs = tokenizer(
        input_texts,
        return_tensors="pt",
        padding=True,
    ).to(device)

    with torch.no_grad():
        outputs = model.generate(
            **inputs, 
            max_new_tokens=10000, 
            pad_token_id=tokenizer.eos_token_id, 
            do_sample=False
        )

    all_outputs = []
    all_lengths = []
    for i, out in enumerate(outputs):
        inp = inputs['input_ids'][i]
        output = out[len(inp):]
        result = tokenizer.decode(output, skip_special_tokens=True)
        length = len(tokenizer.encode(result, add_special_tokens=False))
        all_outputs.append(result)
        all_lengths.append(length)
    return all_outputs, all_lengths


model_path = "path/to/model/DeepSeek-R1-Distill-Qwen-14B"
print(f"正在加载模型: {model_path} ...")

tokenizer = AutoTokenizer.from_pretrained(
    model_path,
    padding_side='left'
)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    low_cpu_mem_usage=True,
    local_files_only=True
)

file_paths = [
    "nature-cn.json",
    # "social-cn.json",
    # "space-cn.json",
    # "space+nature-cn.json",
    # "time-cn.json",
]


batch_size = 4
for file in file_paths:
    print(file)
    with open(os.path.join("path/to/LongCoT/Knowlogic/finaldata", file), 'r', encoding='utf-8') as f:
        data = json.load(f)
    # with open(os.path.join("path/to/LongCoT/Knowlogic/results", file), 'r', encoding='utf-8') as f:
    #     results = json.load(f)
    # for d, r in zip(data, results):
    #     r['id'] = d['id']
    # with open(os.path.join("path/to/LongCoT/Knowlogic/results", file), 'w', encoding='utf-8') as f:
    #     json.dump(results, f, ensure_ascii=False, indent=4)
    # data = data[len(results):]
    # results = []
    input_format = "<｜User｜>{question}<｜Assistant｜><think>"

    # process data
    num_batches = len(data) // batch_size + (1 if len(data) % batch_size != 0 else 0)
    for batch_idx in tqdm(range(num_batches), desc="Processing batches"):
        start_idx = batch_idx * batch_size
        end_idx = min(start_idx + batch_size, len(data))
        batch_data = data[start_idx:end_idx]

        input_texts = []
        correct_answers = []
        for item in batch_data:
            input_text = input_format.format(question=item['question'])
            input_texts.append(input_text)
            correct_answers.append(item['answer'])

        output_strs, output_length = generate_output(tokenizer, model, input_texts)

        for i in range(len(batch_data)):
            result = {
                "id": batch_data[i]['id'],
                "question": input_texts[i],
                "correct_answer": correct_answers[i],
                "model_answer": output_strs[i],
                "model_answer_length": output_length[i],
            }
            results.append(result)

        with open(os.path.join("path/to/LongCoT/Knowlogic/results", file), 'w', encoding='utf-8') as f:
            json.dump(results, f, ensure_ascii=False, indent=4)
    