import os

os.environ["WANDB_MODE"] = "offline"
# os.environ["WANDB_DISABLED"] = "true"

import json
import math
import random
import shutil
import sys
import threading
import time
import traceback
from datetime import datetime
from pathlib import Path

import gradio as gr
import torch
import transformers
from datasets import Dataset, load_dataset
from peft import (
    LoraConfig,
    get_peft_model,
    prepare_model_for_int8_training,
    set_peft_model_state_dict
)
from peft.utils.other import \
    TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING as model_to_lora_modules
from transformers.models.auto.modeling_auto import (
    MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
)

from modules import shared, ui, utils
from modules.evaluate import (
    calculate_perplexity,
    generate_markdown_table,
    save_past_evaluations
)
from modules.logging_colors import logger
from modules.models import reload_model
from modules.utils import natural_keys

MODEL_CLASSES = {v[1]: v[0] for v in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.items()}
PARAMETERS = ["lora_name", "always_override", "save_steps", "micro_batch_size", "batch_size", "epochs", "learning_rate", "lr_scheduler_type", "lora_rank", "lora_alpha", "lora_dropout", "cutoff_len", "dataset", "eval_dataset", "format", "eval_steps", "raw_text_file", "overlap_len", "newline_favor_len", "higher_rank_limit", "warmup_steps", "optimizer", "hard_cut_string", "train_only_after", "stop_at_loss", "add_eos_token", "min_chars", "report_to"]
WANT_INTERRUPT = False

train_log = {}
train_template = {}

def create_ui():
    with gr.Tab("Training", elem_id="training-tab"):
        with gr.Tab('Train LoRA', elem_id='lora-train-tab'):
            tmp = gr.State('')
            with gr.Row():
                with gr.Column():
                    gr.Markdown("[Tutorial](https://github.com/oobabooga/text-generation-webui/blob/main/docs/Training-LoRAs.md)")

                    with gr.Row():
                        copy_from = gr.Dropdown(label='Copy parameters from', value='None', choices=utils.get_available_loras(), elem_classes=['slim-dropdown'])
                        ui.create_refresh_button(copy_from, lambda: None, lambda: {'choices': utils.get_available_loras()}, 'refresh-button')

                    with gr.Row():
                        with gr.Column(scale=5):
                            lora_name = gr.Textbox(label='Name', info='The name of your new LoRA file')
                        with gr.Column():
                            always_override = gr.Checkbox(label='Override Existing Files', value=False, info='If the name is the same, checking will replace the existing file, and unchecking will load and continue from it (the rank must be the same).')

                    with gr.Row():
                        with gr.Column():
                            lora_rank = gr.Slider(label='LoRA Rank', value=32, minimum=0, maximum=1024, step=4, info='Also called dimension count. Higher values = larger file, more content control. Smaller values = smaller file, less control. Use 4 or 8 for style, 128 or 256 to teach, 1024+ for fine-detail on big data. More VRAM is needed for higher ranks.')
                            lora_alpha = gr.Slider(label='LoRA Alpha', value=64, minimum=0, maximum=2048, step=4, info='This divided by the rank becomes the scaling of the LoRA. Higher means stronger. A good standard value is twice your Rank.')
                            batch_size = gr.Slider(label='Batch Size', value=128, minimum=0, maximum=1024, step=4, info='Global batch size. The two batch sizes together determine gradient accumulation (gradientAccum = batch / microBatch). Higher gradient accum values lead to better quality training.')
                            micro_batch_size = gr.Slider(label='Micro Batch Size', value=4, minimum=1, maximum=128, step=1, info='Per-device batch size (NOTE: multiple devices not yet implemented). Increasing this will increase VRAM usage.')
                            cutoff_len = gr.Slider(label='Cutoff Length', minimum=0, maximum=2048, value=256, step=32, info='Cutoff length for text input. Essentially, how long of a line of text to feed in at a time. Higher values require drastically more VRAM.')

                        with gr.Column():
                            save_steps = gr.Number(label='Save every n steps', value=0, info='If above 0, a checkpoint of the LoRA will be saved every time this many steps pass.')

                            epochs = gr.Number(label='Epochs', value=3, info='Number of times every entry in the dataset should be fed into training. So 1 means feed each item in once, 5 means feed it in five times, etc.')
                            learning_rate = gr.Textbox(label='Learning Rate', value='3e-4', info='In scientific notation. 3e-4 is a good starting base point. 1e-2 is extremely high, 1e-6 is extremely low.')
                            lr_scheduler_type = gr.Dropdown(label='LR Scheduler', value='linear', choices=['linear', 'constant', 'constant_with_warmup', 'cosine', 'cosine_with_restarts', 'polynomial', 'inverse_sqrt'], info='Learning rate scheduler - defines how the learning rate changes over time. "Constant" means never change, "linear" means to go in a straight line from the learning rate down to 0, cosine follows a curve, etc.', elem_classes=['slim-dropdown'])

                    with gr.Accordion(label='Advanced Options', open=False):
                        with gr.Row():
                            with gr.Column():
                                lora_dropout = gr.Slider(label='LoRA Dropout', minimum=0.0, maximum=1.0, step=0.025, value=0.05, info='Percentage probability for dropout of LoRA layers. This can help reduce overfitting. Most users should leave at default.')
                                stop_at_loss = gr.Slider(label='Stop at loss', minimum=0.0, maximum=3.0, step=0.1, value=0.00, info='The process will automatically stop once the desired loss value is reached. (reasonable numbers are 1.5-1.8)')
                                optimizer = gr.Dropdown(label='Optimizer', value='adamw_torch', choices=['adamw_hf', 'adamw_torch', 'adamw_torch_fused', 'adamw_torch_xla', 'adamw_apex_fused', 'adafactor', 'adamw_bnb_8bit', 'adamw_anyprecision', 'sgd', 'adagrad'], info='Different optimizer implementation options, for advanced users. Effects of different options are not well documented yet.', elem_classes=['slim-dropdown'])

                            with gr.Column():
                                warmup_steps = gr.Number(label='Warmup Steps', value=100, info='For this many steps at the start, the learning rate will be lower than normal. This helps the trainer prepare the model and precompute statistics to improve the quality of training after the start.')
                                train_only_after = gr.Textbox(label='Train Only After', value='', info='Only consider text *after* this string in any given chunk for training. For Alpaca datasets, use "### Response:" to only train the response and ignore the input.')

                                add_eos_token = gr.Checkbox(label='Add EOS token', value=False, info="Adds EOS token for each dataset item. In case of raw text, the EOS will be added at the Hard Cut")

                                higher_rank_limit = gr.Checkbox(label='Enable higher ranks', value=False, info='If checked, changes Rank/Alpha slider above to go much higher. This will not work without a datacenter-class GPU.')
                                report_to = gr.Radio(label="Save detailed logs with", value="None", choices=["None", "wandb", "tensorboard"], interactive=True)

                with gr.Column():
                    with gr.Tab(label='Formatted Dataset'):
                        with gr.Row():
                            format = gr.Dropdown(choices=utils.get_datasets('training/formats', 'json'), value='None', label='Data Format', info='The format file used to decide how to format the dataset input.', elem_classes=['slim-dropdown'])
                            ui.create_refresh_button(format, lambda: None, lambda: {'choices': utils.get_datasets('training/formats', 'json')}, 'refresh-button')

                        with gr.Row():
                            dataset = gr.Dropdown(choices=utils.get_datasets('training/datasets', 'json'), value='None', label='Dataset', info='The dataset file to use for training.', elem_classes=['slim-dropdown'])
                            ui.create_refresh_button(dataset, lambda: None, lambda: {'choices': utils.get_datasets('training/datasets', 'json')}, 'refresh-button')

                        with gr.Row():
                            eval_dataset = gr.Dropdown(choices=utils.get_datasets('training/datasets', 'json'), value='None', label='Evaluation Dataset', info='The (optional) dataset file used to evaluate the model after training.', elem_classes=['slim-dropdown'])
                            ui.create_refresh_button(eval_dataset, lambda: None, lambda: {'choices': utils.get_datasets('training/datasets', 'json')}, 'refresh-button')

                        eval_steps = gr.Number(label='Evaluate every n steps', value=100, info='If an evaluation dataset is given, test it every time this many steps pass.')

                    with gr.Tab(label="Raw text file"):
                        with gr.Row():
                            raw_text_file = gr.Dropdown(choices=utils.get_datasets('training/datasets', 'txt'), value='None', label='Text file', info='The raw text file to use for training.', elem_classes=['slim-dropdown'])
                            ui.create_refresh_button(raw_text_file, lambda: None, lambda: {'choices': utils.get_datasets('training/datasets', 'txt')}, 'refresh-button')

                        with gr.Row():
                            with gr.Column():
                                overlap_len = gr.Slider(label='Overlap Length', minimum=0, maximum=512, value=128, step=16, info='How many tokens from the prior chunk of text to include into the next chunk. (The chunks themselves will be of a size determined by Cutoff Length). Setting overlap to exactly half the cutoff length may be ideal.')
                                newline_favor_len = gr.Slider(label='Prefer Newline Cut Length', minimum=0, maximum=512, value=128, step=16, info='Length (in characters, not tokens) of the maximum distance to shift an overlap cut by to ensure chunks cut at newlines. If too low, cuts may occur in the middle of lines.')

                            with gr.Column():
                                hard_cut_string = gr.Textbox(label='Hard Cut String', value='\\n\\n\\n', info='String that indicates a hard cut between text parts. Helps prevent unwanted overlap.')
                                min_chars = gr.Number(label='Ignore small blocks', value=0, info='Ignore Hard Cut blocks that have less or equal characters than this number')

                    with gr.Row():
                        start_button = gr.Button("Start LoRA Training", variant='primary')
                        stop_button = gr.Button("Interrupt")

                    output = gr.Markdown(value="Ready")

        with gr.Tab('Perplexity evaluation', elem_id='evaluate-tab'):
            with gr.Row():
                with gr.Column():
                    models = gr.Dropdown(utils.get_available_models(), label='Models', multiselect=True)
                    evaluate_text_file = gr.Dropdown(choices=['wikitext', 'ptb', 'ptb_new'] + utils.get_datasets('training/datasets', 'txt')[1:], value='wikitext', label='Input dataset', info='The raw text file on which the model will be evaluated. The first options are automatically downloaded: wikitext, ptb, and ptb_new. The next options are your local text files under training/datasets.')
                    with gr.Row():
                        with gr.Column():
                            stride_length = gr.Slider(label='Stride', minimum=1, maximum=2048, value=512, step=1, info='Used to make the evaluation faster at the cost of accuracy. 1 = slowest but most accurate. 512 is a common value.')

                        with gr.Column():
                            max_length = gr.Slider(label='max_length', minimum=0, maximum=8096, value=0, step=1, info='The context for each evaluation. If set to 0, the maximum context length for the model will be used.')

                    with gr.Row():
                        start_current_evaluation = gr.Button("Evaluate loaded model")
                        start_evaluation = gr.Button("Evaluate selected models")
                        stop_evaluation = gr.Button("Interrupt")

                with gr.Column():
                    evaluation_log = gr.Markdown(value='')

            evaluation_table = gr.Dataframe(value=generate_markdown_table(), interactive=True)
            with gr.Row():
                save_comments = gr.Button('Save comments', elem_classes="small-button")
                refresh_table = gr.Button('Refresh the table', elem_classes="small-button")

    # Training events
    all_params = [lora_name, always_override, save_steps, micro_batch_size, batch_size, epochs, learning_rate, lr_scheduler_type, lora_rank, lora_alpha, lora_dropout, cutoff_len, dataset, eval_dataset, format, eval_steps, raw_text_file, overlap_len, newline_favor_len, higher_rank_limit, warmup_steps, optimizer, hard_cut_string, train_only_after, stop_at_loss, add_eos_token, min_chars, report_to]

    copy_from.change(do_copy_params, [copy_from] + all_params, all_params)
    start_button.click(do_train, all_params, output)
    stop_button.click(do_interrupt, None, None, queue=False)
    higher_rank_limit.change(change_rank_limit, [higher_rank_limit], [lora_rank, lora_alpha])

    # Evaluation events. For some reason, the interrupt event
    # doesn't work with the .then() syntax, so I write them one
    # by one in this ugly but functional way.
    ev = start_evaluation.click(calculate_perplexity, [models, evaluate_text_file, stride_length, max_length], evaluation_log, show_progress=False)
    start_evaluation.click(generate_markdown_table, None, evaluation_table, show_progress=False)

    start_current_evaluation.click(lambda: ['current model'], None, tmp)
    ev_cur = start_current_evaluation.click(calculate_perplexity, [tmp, evaluate_text_file, stride_length, max_length], evaluation_log, show_progress=False)
    start_current_evaluation.click(generate_markdown_table, None, evaluation_table, show_progress=False)

    stop_evaluation.click(None, None, None, cancels=[ev, ev_cur], queue=False)
    refresh_table.click(generate_markdown_table, None, evaluation_table, show_progress=True)
    save_comments.click(
        save_past_evaluations, evaluation_table, None).then(
        lambda: "Comments saved.", None, evaluation_log, show_progress=False)

def do_interrupt():
    global WANT_INTERRUPT
    WANT_INTERRUPT = True

def do_copy_params(lora_name: str, *args):
    f_name = f"{shared.args.lora_dir}/{clean_path(None, lora_name)}/training_parameters.json"
    if Path(f_name).is_file():
        with open(f_name, 'r', encoding='utf-8') as format_file:
            params: dict[str, str] = json.load(format_file)
    else:
        params = {}

    result = list()
    for i in range(0, len(PARAMETERS)):
        key = PARAMETERS[i]
        if key in params:
            result.append(params[key])
        else:
            result.append(args[i])

    return result

def change_rank_limit(use_higher_ranks: bool):
    mult = 2 if use_higher_ranks else 1
    return {"maximum": 1024 * mult, "__type__": "update"}, {"maximum": 2048 * mult, "__type__": "update"}

def clean_path(base_path: str, path: str):
    """Strips unusual symbols and forcibly builds a path as relative to the intended directory."""
    path = path.replace('\\', '/').replace('..', '_')
    if base_path is None:
        return path

    return f'{Path(base_path).absolute()}/{path}'

def backup_adapter(input_folder):
    # Get the creation date of the file adapter_model.bin
    try:
        adapter_file = Path(f"{input_folder}/adapter_model.bin")
        if adapter_file.is_file():

            logger.info("Backing up existing LoRA adapter...")
            creation_date = datetime.fromtimestamp(adapter_file.stat().st_ctime)
            creation_date_str = creation_date.strftime("Backup-%Y-%m-%d")

            # Create the new subfolder
            subfolder_path = Path(f"{input_folder}/{creation_date_str}")
            subfolder_path.mkdir(parents=True, exist_ok=True)

            # Check if the file already exists in the subfolder
            backup_adapter_file = Path(f"{input_folder}/{creation_date_str}/adapter_model.bin")
            if backup_adapter_file.is_file():
                print(" - Backup already exists. Skipping backup process.")
                return

            # Copy existing files to the new subfolder
            existing_files = Path(input_folder).iterdir()
            for file in existing_files:
                if file.is_file():
                    shutil.copy2(file, subfolder_path)
    except Exception as e:
        print("An error occurred in backup_adapter:", str(e))

def calc_trainable_parameters(model):
    trainable_params = 0
    all_param = 0
    for _, param in model.named_parameters():
        num_params = param.numel()
        # if using DS Zero 3 and the weights are initialized empty
        if num_params == 0 and hasattr(param, "ds_numel"):
            num_params = param.ds_numel

        all_param += num_params
        if param.requires_grad:
            trainable_params += num_params

    return trainable_params, all_param

def do_train(lora_name: str, always_override: bool, save_steps: int, micro_batch_size: int, batch_size: int, epochs: int, learning_rate: str, lr_scheduler_type: str, lora_rank: int, lora_alpha: int, lora_dropout: float, cutoff_len: int, dataset: str, eval_dataset: str, format: str, eval_steps: int, raw_text_file: str, overlap_len: int, newline_favor_len: int, higher_rank_limit: bool, warmup_steps: int, optimizer: str, hard_cut_string: str, train_only_after: str, stop_at_loss: float, add_eos_token: bool, min_chars: int, report_to: str):

    if shared.args.monkey_patch:
        from monkeypatch.peft_tuners_lora_monkey_patch import (
            replace_peft_model_with_gptq_lora_model
        )
        replace_peft_model_with_gptq_lora_model()

    global WANT_INTERRUPT
    WANT_INTERRUPT = False

    # == Input validation / processing ==
    yield "Preparing the input..."
    lora_file_path = clean_path(None, lora_name)
    if lora_file_path.strip() == '':
        yield "Missing or invalid LoRA file name input."
        return

    lora_file_path = f"{Path(shared.args.lora_dir)}/{lora_file_path}"
    actual_lr = float(learning_rate)
    model_type = type(shared.model).__name__

    if model_type in MODEL_CLASSES:
        model_id = MODEL_CLASSES[model_type]
    else:
        model_id = "llama"
        if model_type == "PeftModelForCausalLM":
            if len(shared.lora_names) > 0:
                yield "You are trying to train a LoRA while you already have another LoRA loaded. This will work, but may have unexpected effects. *(Will continue anyway in 5 seconds, press `Interrupt` to stop.)*"
                logger.warning("Training LoRA over top of another LoRA. May have unexpected effects.")
            else:
                yield "Model ID not matched due to LoRA loading. Consider reloading base model. *(Will continue anyway in 5 seconds, press `Interrupt` to stop.)*"
                logger.warning("Model ID not matched due to LoRA loading. Consider reloading base model.")
        else:
            yield "LoRA training has only currently been validated for LLaMA, OPT, GPT-J, and GPT-NeoX models. Unexpected errors may follow. *(Will continue anyway in 5 seconds, press `Interrupt` to stop.)*"
            logger.warning(f"LoRA training has only currently been validated for LLaMA, OPT, GPT-J, and GPT-NeoX models. (Found model type: {model_type})")

        time.sleep(5)

    if shared.args.wbits > 0 and not shared.args.monkey_patch:
        yield "LoRA training with GPTQ models requires loading with `--monkey-patch`"
        return

    elif not (shared.args.load_in_8bit or shared.args.load_in_4bit) and shared.args.wbits <= 0:
        yield "It is highly recommended you use `--load-in-8bit` for LoRA training. *(Will continue anyway in 2 seconds, press `Interrupt` to stop.)*"
        logger.warning("It is highly recommended you use `--load-in-8bit` for LoRA training.")
        time.sleep(2)  # Give it a moment for the message to show in UI before continuing

    if cutoff_len <= 0 or micro_batch_size <= 0 or batch_size <= 0 or actual_lr <= 0 or lora_rank <= 0 or lora_alpha <= 0:
        yield "Cannot input zeroes."
        return

    gradient_accumulation_steps = batch_size // micro_batch_size
    shared.tokenizer.pad_token_id = 0
    shared.tokenizer.padding_side = "left"

    def encode(text, add_bos_token):
        result = shared.tokenizer.encode(text, truncation=True, max_length=cutoff_len)
        # Check if the first two tokens are BOS
        if len(result) >= 2 and result[:2] == [shared.tokenizer.bos_token_id, shared.tokenizer.bos_token_id]:
            result = result[1:]

        if not add_bos_token and result[0] == shared.tokenizer.bos_token_id:
            result = result[1:]
        return result

    def tokenize(prompt, append_eos_token=False):

        if train_only_after == '' or train_only_after not in prompt:
            input_ids = encode(prompt, True)

            if append_eos_token and input_ids[-1] != shared.tokenizer.eos_token_id and len(input_ids) < cutoff_len:
                input_ids.append(shared.tokenizer.eos_token_id)

            input_ids = [shared.tokenizer.pad_token_id] * (cutoff_len - len(input_ids)) + input_ids
            labels = [1] * len(input_ids)

        else:
            ind = prompt.index(train_only_after) + len(train_only_after)
            before_tokens = encode(prompt[:ind], True)
            after_tokens = encode(prompt[ind:], False)

            if append_eos_token and after_tokens[-1] != shared.tokenizer.eos_token_id:
                after_tokens.append(shared.tokenizer.eos_token_id)

            full_length = len(after_tokens) + len(before_tokens)
            if full_length > cutoff_len:
                after_tokens = after_tokens[:cutoff_len - len(before_tokens)]
            else:
                before_tokens = [shared.tokenizer.pad_token_id] * (cutoff_len - full_length) + before_tokens

            input_ids = before_tokens + after_tokens
            labels = [-100] * len(before_tokens) + [1] * len(after_tokens)

        input_ids = torch.tensor(input_ids)
        return {
            "input_ids": input_ids,
            "labels": labels,
            "attention_mask": input_ids.ne(shared.tokenizer.pad_token_id),
        }

    train_template.clear()

    # == Prep the dataset, format, etc ==
    if raw_text_file not in ['None', '']:
        train_template["template_type"] = "raw_text"
        logger.info("Loading raw text file dataset...")
        fullpath = clean_path('training/datasets', f'{raw_text_file}')
        fullpath = Path(fullpath)
        if fullpath.is_dir():
            logger.info('Training path directory {}'.format(raw_text_file))
            raw_text = ""
            file_paths = sorted(fullpath.glob('*.txt'), key=lambda path: natural_keys(path.name))
            for file_path in file_paths:
                if file_path.is_file():
                    with file_path.open('r', encoding='utf-8') as file:
                        raw_text += file.read().replace('\r', '')

                    logger.info(f"Loaded training file: {file_path.name}")
        else:
            with open(clean_path('training/datasets', f'{raw_text_file}.txt'), 'r', encoding='utf-8') as file:
                raw_text = file.read().replace('\r', '')

        cut_string = hard_cut_string.replace('\\n', '\n')
        eos_added = 0
        out_tokens = []
        for text_part in raw_text.split(cut_string):
            if len(text_part.strip()) <= min_chars:
                continue

            tokens = shared.tokenizer.encode(text_part)
            if add_eos_token:
                tokens.append(shared.tokenizer.eos_token_id)
                eos_added += 1

            step = cutoff_len - overlap_len
            if step <= 0:
                yield f"Error: overlap_len ({overlap_len}) cannot be greater than or equal to cutoff_len ({cutoff_len})"
                return

            out_tokens.extend(split_chunks(tokens, cutoff_len, step))

        if eos_added > 0:
            print(f"EOS added to {eos_added} text blocks")

        del raw_text  # Note: could be a gig for a large dataset, so delete redundant data as we go to be safe on RAM
        text_chunks = [shared.tokenizer.decode(x) for x in out_tokens]
        del out_tokens
        if newline_favor_len > 0:
            text_chunks = [cut_chunk_for_newline(x, newline_favor_len) for x in text_chunks]

        train_data = Dataset.from_list([tokenize(x) for x in text_chunks])
        del text_chunks
        eval_data = None
    else:
        if dataset in ['None', '']:
            yield "Missing dataset choice input, cannot continue."
            return

        if format in ['None', '']:
            yield "Missing format choice input, cannot continue."
            return

        train_template["template_type"] = "dataset"

        with open(clean_path('training/formats', f'{format}.json'), 'r', encoding='utf-8-sig') as formatFile:
            format_data: dict[str, str] = json.load(formatFile)

        # == store training prompt ==
        for _, value in format_data.items():
            prompt_key = f"template_{len(train_template)}"
            train_template[prompt_key] = value

        def generate_prompt(data_point: dict[str, str]):
            for options, data in format_data.items():
                if set(options.split(',')) == set(x[0] for x in data_point.items() if (type(x[1]) is str and len(x[1].strip()) > 0)):
                    for key, val in data_point.items():
                        if type(val) is str:
                            data = data.replace(f'%{key}%', val)
                    return data
            raise RuntimeError(f'Data-point "{data_point}" has no keyset match within format "{list(format_data.keys())}"')

        def generate_and_tokenize_prompt(data_point):
            prompt = generate_prompt(data_point)
            return tokenize(prompt, add_eos_token)

        logger.info("Loading JSON datasets...")
        data = load_dataset("json", data_files=clean_path('training/datasets', f'{dataset}.json'))
        train_data = data['train'].map(generate_and_tokenize_prompt, new_fingerprint='%030x' % random.randrange(16**30))

        if eval_dataset == 'None':
            eval_data = None
        else:
            eval_data = load_dataset("json", data_files=clean_path('training/datasets', f'{eval_dataset}.json'))
            eval_data = eval_data['train'].map(generate_and_tokenize_prompt, new_fingerprint='%030x' % random.randrange(16**30))

    # == We MUST reload model if it went through any previous training, even failed one ==
    if shared.model_dirty_from_training:
        selected_model = shared.model_name
        if selected_model:
            print("\033[1;31;1m(Model has been modified by previous training, it needs to be reloaded...)\033[0;37;0m")
            try:
                yield f"Reloading {selected_model}..."
                reload_model()
                if shared.model is not None:
                    print("Model reloaded OK, continue with training.")
                else:
                    return f"Failed to load {selected_model}."
            except:
                exc = traceback.format_exc()
                logger.error('Failed to reload the model.')
                print(exc)
                return exc.replace('\n', '\n\n')

    # == Start prepping the model itself ==
    if not hasattr(shared.model, 'lm_head') or hasattr(shared.model.lm_head, 'weight'):
        logger.info("Getting model ready...")
        prepare_model_for_int8_training(shared.model)

    # base model is now frozen and should not be reused for any other LoRA training than this one
    shared.model_dirty_from_training = True

    logger.info("Preparing for training...")
    config = LoraConfig(
        r=lora_rank,
        lora_alpha=lora_alpha,
        target_modules=model_to_lora_modules[model_id],
        lora_dropout=lora_dropout,
        bias="none",
        task_type="CAUSAL_LM"
    )

    # == Backup the existing adapter ==
    if not always_override:
        backup_adapter(lora_file_path)

    # == get model trainable params
    model_trainable_params, model_all_params = calc_trainable_parameters(shared.model)

    try:
        logger.info("Creating LoRA model...")
        lora_model = get_peft_model(shared.model, config)
        if not always_override and Path(f"{lora_file_path}/adapter_model.bin").is_file():
            logger.info("Loading existing LoRA data...")
            state_dict_peft = torch.load(f"{lora_file_path}/adapter_model.bin")
            set_peft_model_state_dict(lora_model, state_dict_peft)
    except:
        yield traceback.format_exc().replace('\n', '\n\n')
        return

    if shared.args.monkey_patch:
        for n, m in lora_model.named_modules():
            if '4bit' in str(type(m)):
                if m.is_v1_model:
                    m.zeros = m.zeros.half()

                m.scales = m.scales.half()

    class Tracked():
        def __init__(self):
            self.current_steps = 0
            self.max_steps = 0
            self.did_save = False

    tracked = Tracked()
    actual_save_steps = math.ceil(save_steps / gradient_accumulation_steps)

    class Callbacks(transformers.TrainerCallback):
        def on_step_begin(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
            tracked.current_steps = state.global_step * gradient_accumulation_steps
            tracked.max_steps = state.max_steps * gradient_accumulation_steps
            if WANT_INTERRUPT:
                control.should_epoch_stop = True
                control.should_training_stop = True
            elif state.global_step > 0 and actual_save_steps > 0 and state.global_step % actual_save_steps == 0:
                lora_model.save_pretrained(f"{lora_file_path}/checkpoint-{tracked.current_steps}/")
                # Save log
                with open(f"{lora_file_path}/checkpoint-{tracked.current_steps}/training_log.json", 'w', encoding='utf-8') as file:
                    json.dump(train_log, file, indent=2)
                # == Save training prompt ==
                with open(f"{lora_file_path}/checkpoint-{tracked.current_steps}/training_prompt.json", 'w', encoding='utf-8') as file:
                    json.dump(train_template, file, indent=2)

        def on_substep_end(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, **kwargs):
            tracked.current_steps += 1
            if WANT_INTERRUPT:
                control.should_epoch_stop = True
                control.should_training_stop = True

        def on_log(self, args: transformers.TrainingArguments, state: transformers.TrainerState, control: transformers.TrainerControl, logs, **kwargs):
            train_log.update(logs)
            train_log.update({"current_steps": tracked.current_steps})
            if WANT_INTERRUPT:
                print("\033[1;31;1mInterrupted by user\033[0;37;0m")

            print(f"\033[1;30;40mStep: {tracked.current_steps} \033[0;37;0m", end='')
            if 'loss' in logs:
                loss = float(logs['loss'])
                if loss <= stop_at_loss:
                    control.should_epoch_stop = True
                    control.should_training_stop = True
                    print(f"\033[1;31;1mStop Loss {stop_at_loss} reached.\033[0;37;0m")

    trainer = transformers.Trainer(
        model=lora_model,
        train_dataset=train_data,
        eval_dataset=eval_data,
        args=transformers.TrainingArguments(
            report_to=report_to if report_to != "None" else None,
            per_device_train_batch_size=micro_batch_size,
            gradient_accumulation_steps=gradient_accumulation_steps,
            warmup_steps=math.ceil(warmup_steps / gradient_accumulation_steps),
            num_train_epochs=epochs,
            learning_rate=actual_lr,
            fp16=False if shared.args.cpu else True,
            optim=optimizer,
            logging_steps=2 if stop_at_loss > 0 else 5,
            evaluation_strategy="steps" if eval_data is not None else "no",
            eval_steps=math.ceil(eval_steps / gradient_accumulation_steps) if eval_data is not None else None,
            save_strategy="steps" if eval_data is not None else "no",
            output_dir=lora_file_path,
            lr_scheduler_type=lr_scheduler_type,
            load_best_model_at_end=eval_data is not None,
            # TODO: Enable multi-device support
            ddp_find_unused_parameters=None,
            no_cuda=shared.args.cpu,
        ),
        data_collator=transformers.DataCollatorForLanguageModeling(shared.tokenizer, mlm=False),
        callbacks=list([Callbacks()])
    )

    lora_model.config.use_cache = False

    if torch.__version__ >= "2" and sys.platform != "win32":
        lora_model = torch.compile(lora_model)

    # == Save parameters for reuse ==
    with open(f"{lora_file_path}/training_parameters.json", 'w', encoding='utf-8') as file:
        vars = locals()
        json.dump({x: vars[x] for x in PARAMETERS}, file, indent=2)

    # == Save training prompt ==
    with open(f"{lora_file_path}/training_prompt.json", 'w', encoding='utf-8') as file:
        json.dump(train_template, file, indent=2)

    # == Main run and monitor loop ==
    logger.info("Starting training...")
    yield "Starting..."

    lora_trainable_param, lora_all_param = calc_trainable_parameters(lora_model)

    projections_string = ", ".join([projection.replace("_proj", "") for projection in model_to_lora_modules[model_id]])

    print(f"Training '{model_id}' model using ({projections_string}) projections")

    if lora_all_param > 0:
        print(f"Trainable params: {lora_trainable_param:,d} ({100 * lora_trainable_param / lora_all_param:.4f} %), All params: {lora_all_param:,d} (Model: {model_all_params:,d})")

    train_log.update({"base_model_name": shared.model_name})
    train_log.update({"base_model_class": shared.model.__class__.__name__})
    train_log.update({"base_loaded_in_4bit": getattr(lora_model, "is_loaded_in_4bit", False)})
    train_log.update({"base_loaded_in_8bit": getattr(lora_model, "is_loaded_in_8bit", False)})
    train_log.update({"projections": projections_string})

    if stop_at_loss > 0:
        print(f"Monitoring loss \033[1;31;1m(Auto-Stop at: {stop_at_loss})\033[0;37;0m")

    if WANT_INTERRUPT:
        yield "Interrupted before start."
        return

    def log_train_dataset(trainer):
        decoded_entries = []
        # Try to decode the entries and write the log file
        try:
            # Iterate over the first 10 elements in the dataset (or fewer if there are less than 10)
            for i in range(min(10, len(trainer.train_dataset))):
                decoded_text = shared.tokenizer.decode(trainer.train_dataset[i]['input_ids'])
                decoded_entries.append({"value": decoded_text})

            # Write the log file
            Path('logs').mkdir(exist_ok=True)
            with open(Path('logs/train_dataset_sample.json'), 'w') as json_file:
                json.dump(decoded_entries, json_file, indent=4)

            logger.info("Log file 'train_dataset_sample.json' created in the 'logs' directory.")
        except Exception as e:
            logger.error(f"Failed to create log file due to error: {e}")

    def threaded_run():
        log_train_dataset(trainer)
        trainer.train()
        # Note: save in the thread in case the gradio thread breaks (eg browser closed)
        lora_model.save_pretrained(lora_file_path)
        logger.info("LoRA training run is completed and saved.")
        # Save log
        with open(f"{lora_file_path}/training_log.json", 'w', encoding='utf-8') as file:
            json.dump(train_log, file, indent=2)

    thread = threading.Thread(target=threaded_run)
    thread.start()
    last_step = 0
    start_time = time.perf_counter()

    while thread.is_alive():
        time.sleep(0.5)
        if WANT_INTERRUPT:
            yield "Interrupting, please wait... *(Run will stop after the current training step completes.)*"

        elif tracked.current_steps != last_step:
            last_step = tracked.current_steps
            time_elapsed = time.perf_counter() - start_time
            if time_elapsed <= 0:
                timer_info = ""
                total_time_estimate = 999
            else:
                its = tracked.current_steps / time_elapsed
                if its > 1:
                    timer_info = f"`{its:.2f}` it/s"
                else:
                    timer_info = f"`{1.0/its:.2f}` s/it"

                total_time_estimate = (1.0 / its) * (tracked.max_steps)

            yield f"Running... **{tracked.current_steps}** / **{tracked.max_steps}** ... {timer_info}, {format_time(time_elapsed)} / {format_time(total_time_estimate)} ... {format_time(total_time_estimate - time_elapsed)} remaining"

    # Saving in the train thread might fail if an error occurs, so save here if so.
    if not tracked.did_save:
        logger.info("Training complete, saving...")
        lora_model.save_pretrained(lora_file_path)

    if WANT_INTERRUPT:
        logger.info("Training interrupted.")
        yield f"Interrupted. Incomplete LoRA saved to `{lora_file_path}`."
    else:
        logger.info("Training complete!")
        yield f"Done! LoRA saved to `{lora_file_path}`.\n\nBefore testing your new LoRA, make sure to first reload the model, as it is currently dirty from training."

def split_chunks(arr, size, step):
    for i in range(0, len(arr), step):
        yield arr[i:i + size]

def cut_chunk_for_newline(chunk: str, max_length: int):
    if '\n' not in chunk:
        return chunk

    first_newline = chunk.index('\n')
    if first_newline < max_length:
        chunk = chunk[first_newline + 1:]

    if '\n' not in chunk:
        return chunk

    last_newline = chunk.rindex('\n')
    if len(chunk) - last_newline < max_length:
        chunk = chunk[:last_newline]

    return chunk

def format_time(seconds: float):
    if seconds < 120:
        return f"`{seconds:.0f}` seconds"

    minutes = seconds / 60
    if minutes < 120:
        return f"`{minutes:.0f}` minutes"

    hours = minutes / 60
    return f"`{hours:.0f}` hours"


"""Insteon base entity."""
import logging

# import string

from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.const import CONF_VERIFY_SSL

# from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN, PACKAGE_NAME, _LOGGER, DEVICE_TYPE_BINARY_SENSOR, CONF_IGNORE_PLATFORM
from .vimarlink.vimarlink import VimarLink, VimarProject
from .vimar_coordinator import VimarDataUpdateCoordinator

class VimarEntity(CoordinatorEntity):
    """Vimar abstract base entity."""

    _logger = _LOGGER
    _logger_is_debug = False
    _device = []
    _device_id = 0
    _vimarconnection: VimarLink = None
    _vimarproject: VimarProject = None
    _coordinator: VimarDataUpdateCoordinator = None
    _attributes = {}

    ICON = "mdi:checkbox-marked"

    def __init__(self, coordinator: VimarDataUpdateCoordinator, device_id: int):
        """Initialize the base entity."""
        super().__init__(coordinator)
        self._coordinator = coordinator
        self._device_id = device_id
        self._vimarconnection = coordinator.vimarconnection
        self._vimarproject = coordinator.vimarproject
        self._reset_status()

        if self._device_id in self._vimarproject.devices:
            self._device = self._vimarproject.devices[self._device_id]
            self._logger = logging.getLogger(PACKAGE_NAME + "." + self.entity_platform)
            self._logger_is_debug = self._logger.isEnabledFor(logging.DEBUG)
        else:
            self._logger.warning("Cannot find device #%s", self._device_id)

        # self.entity_id = self._platform + "." + self.name.lower().replace(" ", "_") + "_" + self._device_id

    @property
    def device_name(self):
        """Return the name of the device."""
        name = self._device["device_friendly_name"]
        if name is None:
            name = self._device["object_name"]
        return name

    @property
    def name(self):
        """Return the name of the device."""
        return self.device_name

    @property
    def extra_state_attributes(self):
        """Return device specific state attributes."""
        # see: https://developers.home-assistant.io/docs/dev_101_states/
        # mostro gli attributi importati da vimar
        if self._device is not None:
            for key in self._device:
                value = self._device[key]
                if self._logger_is_debug is False and (
                    key == "status" or key == "device_class" or key == "device_friendly_name" or key == "vimar_icon"
                ):
                    # for status_name in value:
                    #    deviceItem["state_" + status_name.replace("/", "_").replace(" ", "_")] = value[status_name]["status_value"]
                    continue
                self._attributes["vimar_" + key] = value
        return self._attributes

    def request_statemachine_update(self):
        """Update the hass status."""
        # with polling, we need to schedule another poll request
        self.async_schedule_update_ha_state()
        # if not self.should_poll:
        #     # with the central update coordinator, we do this
        #     self._coordinator.async_request_refresh()

    # def change_state(self, state: str, value: str,  *args):
    def change_state(self, *args, **kwargs):
        """Change state on bus system and the local device state."""
        state_changed = False
        if "status" in self._device and self._device["status"]:

            if args and len(args) > 0:
                iter_args = iter(args)
                for state, value in zip(iter_args, iter_args):
                    if state in self._device["status"]:
                        state_changed = True
                        optionals = self._vimarconnection.get_optionals_param(state)
                        self.hass.async_add_executor_job(
                            self._vimarconnection.set_device_status,
                            self._device["status"][state]["status_id"],
                            str(value),
                            optionals,
                        )
                        self._device["status"][state]["status_value"] = str(value)
                    else:
                        self._logger.warning(
                            "Could not find state %s in device %s - %s - could not change value to: %s",
                            state,
                            self.name,
                            self._device_id,
                            value,
                        )

            if kwargs and len(kwargs) > 0:
                for state, value in kwargs.items():
                    if state in self._device["status"]:
                        state_changed = True
                        optionals = self._vimarconnection.get_optionals_param(state)
                        self.hass.async_add_executor_job(
                            self._vimarconnection.set_device_status,
                            self._device["status"][state]["status_id"],
                            str(value),
                            optionals,
                        )
                        self._device["status"][state]["status_value"] = str(value)
                    else:
                        self._logger.warning(
                            "Could not find state %s in device %s - %s - could not change value to: %s",
                            state,
                            self.name,
                            self._device_id,
                            value,
                        )

            if state_changed:
                self.request_statemachine_update()

        # TODO - call async_add_executor_job with asyncio.gather maybe?

    def get_state(self, state):
        """Get state of the local device state."""
        if self.has_state(state):
            return self._device["status"][state]["status_value"]
        else:
            self._logger.warning(
                "Could not find state %s in device %s - %s - could not get value", state, self.name, self._device_id
            )
        return None

    def has_state(self, state):
        """Return true if local device has a given state."""
        if "status" in self._device and self._device["status"] and state in self._device["status"]:
            return True
        else:
            return False

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        if isinstance(self._device["icon"], str):
            return self._device["icon"]
        elif isinstance(self._device["icon"], list):
            return (self._device["icon"][1], self._device["icon"][0])[self.is_default_state]

        return self.ICON

    @property
    def device_class(self):
        """Return the class of this device, from component DEVICE_CLASSES."""
        return self._device["device_class"]

    @property
    def unique_id(self):
        """Return the ID of this device."""
        # self._logger.debug("Unique Id: " + DOMAIN + '_' + self._platform + '_' + self._device_id + " - " + self.name)
        prefix = self._coordinator.entity_unique_id_prefix or ""
        if len(prefix) > 0:
            prefix += "_"
        return DOMAIN + "_" + prefix + self.entity_platform + "_" + self._device_id

    def _reset_status(self):
        """Set status from _device to class variables."""

    @property
    def is_default_state(self):
        """Return True of in default state - resulting in default icon."""
        return False

    @property
    def device_info(self):
        room_name = None
        if self._device.get("room_friendly_name") and self._device["room_friendly_name"] != "":
            room_name = self._device["room_friendly_name"]
        return {
            "identifiers": {(DOMAIN, self._coordinator.entity_unique_id_prefix or "", self._device_id)},
            "name": self.device_name,
            "model": self._device.get("object_type"),
            "manufacturer": "Vimar",
            "suggested_area": room_name,
        }

    @property
    def entity_platform(self):
        """Return device_type (platform overrrided in sensor class)"""
        return self._device["device_type"]

    def get_entity_list(self) -> list:
        """return entity as list for async_add_devices, method to override if has multiple attribute, as sensor"""
        return [self]

class VimarStatusSensor(BinarySensorEntity):
    """Representation of a Sensor."""

    _coordinator: VimarDataUpdateCoordinator = None

    def __init__(self, coordinator: VimarDataUpdateCoordinator):
        """Initialize the sensor."""
        self._coordinator = coordinator
        vimarconfig = coordinator.vimarconfig
        self._name = (
            "Vimar Connection to "
            + str(coordinator.vimarconnection._host)
            + ":"
            + str(coordinator.vimarconnection._port)
        )
        self._type = "connectivity"
        self._attributes = {
            "Host": coordinator.vimarconnection._host,
            "Port": coordinator.vimarconnection._port,
            "Secure": coordinator.vimarconnection._schema == "https",
            "Verify SSL": coordinator.vimarconnection._schema == "https" and vimarconfig.get(CONF_VERIFY_SSL),
            "Vimar Url": "%s://%s:%s"
            % (
                coordinator.vimarconnection._schema,
                coordinator.vimarconnection._host,
                coordinator.vimarconnection._port,
            ),
            "Certificate": coordinator.vimarconnection._certificate,
            "Username": coordinator.vimarconnection._username,
            "SessionID": coordinator.vimarconnection._session_id,
        }
        self._data = self._attributes
        self._state = False

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return self._type

    @property
    def should_poll(self):
        """Polling needed for a demo binary sensor."""
        return True

    @property
    def name(self):
        """Return the name of the binary sensor."""
        return self._name

    @property
    def unique_id(self):
        """Return the ID of this device."""
        # self._logger.debug("Unique Id: " + DOMAIN + '_' + self._platform + '_' + self._device_id + " - " + self.name)
        prefix = self._coordinator.entity_unique_id_prefix or ""
        if len(prefix) > 0:
            prefix += "_"
        return DOMAIN + "_" + prefix + "status"

    @property
    def device_state_attributes(self):
        """Return the state attributes of the sensor."""
        if self._data:
            return self._data
        else:
            return None

    @property
    def extra_state_attributes(self):
        """Return device specific state attributes."""
        return self._attributes

    @property
    def device_info(self):
        return {
            "identifiers": {(DOMAIN, self._coordinator.entity_unique_id_prefix or "", "status")},
            "name": "Vimar WebServer",
            "model": "Vimar WebServer",
            "manufacturer": "Vimar",
        }

    @property
    def is_on(self):
        """Return true if the binary sensor is on."""
        return self._state

    def update(self):
        """Fetch new state data for the sensor.
        This is the only method that should fetch new data for Home Assistant.
        """
        # self._data = self._fetch(self._host)
        logged = self._coordinator.vimarconnection.is_logged()
        if logged:
            self._state = True
        else:
            self._state = False

def vimar_setup_entry(vimar_entity_class: VimarEntity, platform, hass: HomeAssistantType, entry, async_add_devices):
    """Generic method for add entities of specified platform to HASS"""
    logger = logging.getLogger(PACKAGE_NAME + "." + platform)
    coordinator: VimarDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
    ignored_platforms = coordinator.vimarconfig.get(CONF_IGNORE_PLATFORM) or []
    platform_ignored = platform in ignored_platforms
    vimarproject = coordinator.vimarproject

    entities = []
    entities_to_add = []

    if platform == DEVICE_TYPE_BINARY_SENSOR:
        status_sensor = VimarStatusSensor(coordinator)
        async_add_devices([status_sensor], True)
        entities += [status_sensor]

    if not platform_ignored:
        logger.debug("Vimar %s started!", platform)
        devices = vimarproject.get_by_device_type(platform)
        if len(devices) != 0:
            for device_id, device in devices.items():
                if device.get("ignored", False):
                    continue
                entity: VimarEntity = vimar_entity_class(coordinator, device_id)
                entity_list = entity.get_entity_list()
                entities_to_add += entity_list

    if len(entities_to_add) != 0:
        logger.info("Adding %d %s", len(entities_to_add), platform)
    # need to call async_add_devices everytime for each registered platform (even if it's empty)! if not called, entry reload not work.
    async_add_devices(entities_to_add)
    entities += entities_to_add

    coordinator.devices_for_platform[platform] = entities

    if not platform_ignored:
        logger.debug("Vimar %s complete!", platform)


# -*- coding: utf-8 -*-

import numpy as np
import tensorflow as tf
from tensorflow.python.ops import array_ops
from tensorflow.contrib.rnn.python.ops import core_rnn_cell
from tensorflow.python.util import nest
from tensorflow.python.ops import variable_scope as vs
from sklearn.base import BaseEstimator, ClassifierMixin
import time
from type import DiversityQuery

def select_by_index(value, index, zero_base=True):
    select_dim = tf.shape(value)[1]
    mask = tf.equal(tf.range(select_dim), tf.expand_dims(index, axis=-1) - (0 if zero_base else 1))
    return tf.boolean_mask(value, mask)

def tensormul(tensor, arrs):
    dims = [d.value for d in tensor.get_shape()]
    batch = tf.shape(arrs[0])[0]
    ultimate = [batch] + dims
    tensor = tf.reshape(tf.tile(tensor, [batch] + [1] * (len(dims) - 1)), ultimate)
    arrs = [tf.reshape(tf.tile(tf.reshape(arrs[i], [batch, dims[i], 1]),
                               [1, int(np.product(dims[:i])), int(np.product(dims[i+1:]))]),
                       ultimate) for i in range(len(arrs))]
    for arr in arrs:
        tensor *= arr
    return tf.reduce_sum(tensor, list(range(1, len(ultimate))))

def interaction_op(emb1, emb2, var_name, op='general', attn=False):
    s1 = emb1.get_shape()[1].value
    s2 = emb2.get_shape()[1].value
    if op == 'general':
        variable = vs.get_variable(var_name, [s1, s2])
        return tensormul(variable, [emb1, emb2])
    elif op == 'dot':
        return tf.reduce_sum(emb1 * emb2, reduction_indices=1) * (-1 if attn else 1)

class RNNCellBase(core_rnn_cell.RNNCell):
    def zero_state_np(self, batch_size, dtype):
        states = np.zeros((batch_size, self.state_size), dtype=dtype)
        return states

class DSSACell(RNNCellBase):
    '''
    DSSA cell: combination of traditional RNN and pooling
    '''
    VALID_OP = {'general', 'dot'}
    VALID_POOL = {'max', 'min'}

    def __init__(self, cell, n_doc_emb, n_rel_feat, n_query_emb, most_n_subquery,
                 lambdaa=0.5, op='general', pool='max', state_is_tuple=False):
        if not isinstance(cell, core_rnn_cell.RNNCell):
            raise TypeError('cell should be instance of RNNCell')
        if op not in DSSACell.VALID_OP:
            raise ValueError('op not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSACell.VALID_OP))))
        if pool not in DSSACell.VALID_POOL:
            raise ValueError('pool not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSACell.VALID_POOL))))
        if nest.is_sequence(cell.state_size) != state_is_tuple:
            raise ValueError('base cell state_is_tuple is not consistent with the current. '
                             'base state size is: {}'.format(cell.state_size))
        self.cell = cell
        self.n_doc_emb = n_doc_emb
        self.n_rel_feat = n_rel_feat
        self.n_query_emb = n_query_emb
        self.most_n_subquery = most_n_subquery
        self.lambdaa = lambdaa
        self.op = op
        self.pool = pool
        self.state_is_tuple = state_is_tuple

    @property
    def state_size(self):
        ss = (self.cell.state_size, self.most_n_subquery, self.most_n_subquery)
        if self.state_is_tuple:
            return ss
        return sum(ss)

    @property
    def output_size(self):
        return 1

    def __call__(self, inputs, state, scope=None):
        with vs.variable_scope(scope or type(self).__name__):
            with vs.variable_scope('Transformation'):
                batch_size = tf.shape(inputs)[0]
                input_dim = tf.shape(inputs)[1]
                # the samples in the same batch must have same number of subtopics
                to_attn_len = tf.to_int32(tf.reduce_max(array_ops.slice(inputs, [0, input_dim - 1], [-1, -1]))) - 1
                to_attn_len = tf.maximum(to_attn_len, 0) # avoid bug for paddings
                query_rel = array_ops.slice(inputs, [0, 0], [-1, self.n_rel_feat])
                subquery_rel = tf.reshape(array_ops.slice(inputs, [0, self.n_rel_feat],
                                                          [-1, self.n_rel_feat * to_attn_len]),
                                          [batch_size, to_attn_len, self.n_rel_feat])
                doc_emb = array_ops.slice(inputs, [0, self.n_rel_feat * self.most_n_subquery], [-1, self.n_doc_emb])
                query_emb = array_ops.slice(inputs,
                                            [0, self.n_rel_feat * self.most_n_subquery + self.n_doc_emb],
                                            [-1, self.n_query_emb])
                to_attn = tf.reshape(array_ops.slice(
                    inputs,
                    [0, self.n_rel_feat * self.most_n_subquery + self.n_doc_emb + self.n_query_emb + 1],
                    [-1, (self.n_query_emb + 1) * to_attn_len]), [batch_size, to_attn_len, self.n_query_emb + 1])
                initial_weight = to_attn[:, :, self.n_query_emb]
                subquery_emb = to_attn[:, :, :self.n_query_emb]
                last_state = state[:, :self.cell.state_size]
                last_attn_rnn = array_ops.slice(state, [0, self.cell.state_size], [-1, to_attn_len])
                last_attn_pool = array_ops.slice(state,
                                                 [0, self.cell.state_size + self.most_n_subquery],
                                                 [-1, to_attn_len])
                last_attn = last_attn_rnn + last_attn_pool
                last_attn = tf.nn.softmax(last_attn + tf.log(initial_weight))
            with vs.variable_scope('DocumentSequenceRepresentation'):
                cur_output, cur_state = self.cell(doc_emb, last_state)
            with vs.variable_scope('Scoring'):
                lambda_factor = vs.get_variable('Lambda', [1],
                                                initializer=tf.constant_initializer(self.lambdaa, dtype=tf.float32),
                                                trainable=False)
                # diversity score
                div_score = tf.zeros([batch_size])
                relw = vs.get_variable('RelW', [self.n_rel_feat, 1])
                sub_rel = tf.reduce_sum(subquery_rel * tf.reshape(relw, [self.n_rel_feat]), reduction_indices=2)
                div_score += tf.reduce_sum(sub_rel * last_attn, reduction_indices=1)
                div_score += interaction_op(doc_emb,
                                            tf.reduce_sum(tf.expand_dims(last_attn, -1) * subquery_emb,
                                                          reduction_indices=1),
                                            'OutW', op=self.op)
                # relevance score
                rel_score = tf.zeros([batch_size])
                rel_score += tf.reshape(tf.matmul(query_rel, relw), [batch_size])
                vs.get_variable_scope().reuse_variables()
                rel_score += interaction_op(doc_emb, query_emb, 'OutW', op=self.op)
                score = lambda_factor * div_score + (1.0 - lambda_factor) * rel_score
            with vs.variable_scope('SubtopicAttention'):
                # rnn attention part
                attn_rnn = tf.reshape(interaction_op(
                    tf.reshape(tf.tile(cur_output, [1, to_attn_len]), [-1, self.cell.output_size]),
                    tf.reshape(subquery_emb, [-1, self.n_query_emb]), 'AttnW', op=self.op, attn=True),
                    [batch_size, to_attn_len])
                # pooling attention part
                attn_relw = vs.get_variable('AttnRelW', [self.n_rel_feat, 1])
                attn_sub_rel = tf.reduce_sum(subquery_rel * tf.reshape(attn_relw, [self.n_rel_feat]),
                                             reduction_indices=2)
                if self.pool == 'max':
                    attn_pool = tf.reduce_max(tf.stack([attn_sub_rel, last_attn_pool], axis=2),
                                              reduction_indices=2)
                elif self.pool == 'min':
                    attn_pool = tf.reduce_min(tf.stack([attn_sub_rel, last_attn_pool], axis=2),
                                              reduction_indices=2)
            score = tf.reshape(score, [batch_size, 1])
            next_state = (cur_state,
                          tf.concat([attn_rnn,
                                     tf.zeros((batch_size, self.most_n_subquery - to_attn_len))], axis=1),
                          tf.concat([attn_pool,
                                     tf.zeros((batch_size, self.most_n_subquery - to_attn_len))], axis=1))
            if self.state_is_tuple:
                return score, next_state
            return score, tf.concat(list(next_state), axis=1)

    def zero_state_np(self, batch_size, dtype):
        if self.pool == 'max':
            v = np.finfo(np.float32).min
        elif self.pool == 'min':
            v = np.finfo(np.float32).max
        if self.state_is_tuple:
            state_base = tuple(np.zeros([batch_size, d]) for d in self.cell.state_size)
        else:
            state_base = np.zeros([batch_size, self.cell.state_size])
        state_rnn = np.zeros((batch_size, self.most_n_subquery), dtype=dtype)
        state_pool = np.ones((batch_size, self.most_n_subquery), dtype=dtype) * v
        if self.state_is_tuple:
            return (state_base, state_rnn, state_pool)
        return np.concatenate([state_base, state_rnn, state_pool], axis=1)

    def zero_state(self, batch_size, dtype):
        if self.pool == 'max':
            v = tf.float32.min
        elif self.pool == 'min':
            v = tf.float32.max
        state_base = self.cell.zero_state(batch_size, dtype)
        state_rnn = array_ops.zeros([batch_size, self.most_n_subquery], dtype=dtype)
        state_pool = tf.fill([batch_size, self.most_n_subquery], v)
        if self.state_is_tuple:
            return (state_base, state_rnn, state_pool)
        return tf.concat([state_base, state_rnn, state_pool], axis=1)

class DSSA(BaseEstimator, ClassifierMixin):
    '''
    DSSA model
    '''
    VALID_INTERACTION = {'general', 'dot'}
    VALID_CELL_TYPE = {'vanilla', 'LSTM', 'GRU'}
    VALID_OPTIMIZATION = {'listpair'}

    def __init__(self,
                 n_rel_feat=10,
                 n_doc_emb=10,
                 n_query_emb=10,
                 hidden_size=10,
                 interaction='general',
                 cell_type='vanilla',
                 lambdaa=0.5,
                 most_n_subquery=10,
                 most_n_pair=10,
                 most_n_doc=10,
                 doc_emb=np.ones((10, 110)),
                 query_emb=np.ones((10, 11)),
                 learning_rate=.1,
                 n_epochs=10,
                 batch_size=10,
                 optimization='listpair',
                 save_epochs=None,
                 verbose=True,
                 random_seed=0,
                 reuse_model=None,
                 save_model=None):
        self.n_rel_feat = n_rel_feat
        self.n_doc_emb = n_doc_emb
        self.n_query_emb = n_query_emb
        self.hidden_size = hidden_size
        self.interaction = interaction
        self.cell_type = cell_type
        self.lambdaa = lambdaa
        self.most_n_subquery = most_n_subquery
        self.most_n_pair = most_n_pair
        self.most_n_doc = most_n_doc
        self.doc_emb = doc_emb
        self.query_emb = query_emb
        self.learning_rate = learning_rate
        self.n_epochs = n_epochs
        self.batch_size = batch_size
        self.optimization = optimization
        self.save_epochs = save_epochs
        self.verbose = verbose
        self.random_seed = random_seed
        self.reuse_model = reuse_model
        self.save_model = save_model

    def check_params(self):
        if self.interaction not in DSSA.VALID_INTERACTION:
            raise ValueError('interaction not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSA.VALID_INTERACTION))))
        if self.cell_type not in DSSA.VALID_CELL_TYPE:
            raise ValueError('cell_type not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSA.VALID_CELL_TYPE))))
        if not isinstance(self.doc_emb, np.ndarray) or not isinstance(self.query_emb, np.ndarray):
            raise ValueError('both doc_emb and query_emb should by instance of numpy.ndarray')
        self.doc_emb_actual_size = self.n_rel_feat * self.most_n_subquery + self.n_doc_emb
        if self.doc_emb.shape[1] != self.doc_emb_actual_size:
            raise ValueError('doc_emb shape[1] is unexpected. {} is desired while we got {}'
                             .format(self.doc_emb_actual_size, self.doc_emb.shape[1]))
        self.query_emb_actual_size = self.n_query_emb + 1
        if self.query_emb.shape[1] != self.query_emb_actual_size:
            raise ValueError('query_emb shape[1] is unexpected. {} is desired while we got {}'
                             .format(self.query_emb_actual_size, self.query_emb.shape[1]))
        if self.optimization not in DSSA.VALID_OPTIMIZATION:
            raise ValueError('optimization not valid, it should be one of {}'
                             .format(', '.join(map(lambda x: '"' + x + '"', DSSA.VALID_OPTIMIZATION))))
        self.input_dim = 1 + self.most_n_subquery
        self.expand_input_dim = \
            self.n_rel_feat * self.most_n_subquery + self.n_doc_emb + (self.n_query_emb + 1) * self.most_n_subquery
        if self.reuse_model and not hasattr(self, 'session_'): # read model from file
            self.graph_ = tf.Graph()
            with self.graph_.as_default():
                tf.set_random_seed(self.random_seed)
                with vs.variable_scope('DSSA', initializer=
                tf.uniform_unit_scaling_initializer(seed=self.random_seed)) as scope:
                    self.build_graph()
                    scope.reuse_variables()
                    self.build_graph_test()
            self.session_ = tf.Session(graph=self.graph_)
            print('load model from "{}"'.format(self.reuse_model))
            self.saver.restore(self.session_, self.reuse_model)

    @staticmethod
    def get_cell(cell_type, hidden_size):
        if cell_type == 'vanilla':
            return core_rnn_cell.BasicRNNCell(num_units=hidden_size)
        elif cell_type == 'GRU':
            return core_rnn_cell.GRUCell(num_units=hidden_size)
        elif cell_type == 'LSTM':
            return core_rnn_cell.LSTMCell(num_units=hidden_size, state_is_tuple=False)

    @property
    def weights(self):
        if not hasattr(self, 'session_'):
            raise AttributeError('need fit or fit_iterable to be called before getting weights')
        return [(v.name, v.eval(self.session_))
                for v in self.graph_.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='DSSA')]

    def batcher(self, X, y=None):
        for q in X:
            n_sample = q['train_x'].shape[0]
            if n_sample <= 0:
                continue
            for i in range(0, n_sample, self.batch_size):
                yield q['train_x'][i:i + self.batch_size], None

    def batch_to_feeddict(self, X, y):
        if self.optimization == 'listpair':
            return self.batch_to_feeddict_listpair(X, y)

    def batch_to_feeddict_listpair(self, X, y):
        batch_num = X.shape[0]
        actual_dim = self.most_n_doc * (self.input_dim + 1) + \
                     self.most_n_pair * (2 * (self.input_dim + 1) + 1 + 1) + \
                     1 + 1
        if X.shape[1] != actual_dim:
            raise ValueError('input X\'s dimension is unexpected. '
                             '{} is desired while we got {}'.format(actual_dim, X.shape[1]))
        # assemble feed_dict
        feed_dict = {}
        feed_dict[self.context_input] = \
            X[:, :self.most_n_doc * (self.input_dim + 1)].reshape(batch_num, self.most_n_doc, self.input_dim + 1)
        feed_dict[self.context_input_len] = X[:, -2]
        feed_dict[self.pair_input_len] = X[:, -1]
        pair = X[:, self.most_n_doc * (self.input_dim + 1):-2].reshape(batch_num, self.most_n_pair, -1)
        feed_dict[self.pair_input] = pair[:, :, :-2].reshape(batch_num, self.most_n_pair, 2, self.input_dim + 1)
        feed_dict[self.pair_target] = pair[:, :, -2].astype(np.int32)
        feed_dict[self.pair_weight] = pair[:, :, -1]
        return feed_dict

    def build_graph_test(self):
        if not hasattr(self, 'cell'):
            raise AttributeError('need build train graph before build test graph')
        with vs.variable_scope('TestInput'):
            self.test_input = tf.placeholder(tf.float32, shape=[None, None, self.input_dim + 1], name='test_input')
            self.test_input_len = tf.placeholder(tf.int32, shape=[None], name='test_input_len')
            self.test_initial_state = tf.placeholder(tf.float32,
                                                     shape=[None, self.cell.state_size],
                                                     name='test_initial_state')
            dim = tf.shape(self.test_input)
            batch_num = dim[0]
            doc_num = dim[1]
        with vs.variable_scope('EmbeddingLookup'):
            tid = tf.nn.embedding_lookup(self.doc_emb_W,
                                         tf.to_int32(self.test_input[:, :, :1]))
            tiq = tf.nn.embedding_lookup(self.query_emb_W,
                                         tf.to_int32(self.test_input[:, :, 1:1 + self.most_n_subquery]))
            test_input_expand = tf.concat([tf.reshape(tid, [batch_num, doc_num, -1]),
                                           tf.reshape(tiq, [batch_num, doc_num, -1]),
                                           self.test_input[:, :, self.input_dim:]], axis=2)
            test_input_expand.set_shape([None, None, self.expand_input_dim + 1])
        with vs.variable_scope('DSSA-RNNMP'):
            outputs, self.states = tf.nn.dynamic_rnn(
                initial_state=self.test_initial_state,
                cell=self.cell,
                dtype=tf.float32,
                sequence_length=self.test_input_len,
                inputs=test_input_expand)
            self.outputs_test = tf.reshape(select_by_index(outputs, self.test_input_len, zero_base=False),
                                           [batch_num])

    def build_graph(self):
        if self.optimization == 'listpair':
            self.build_graph_listpair()

    def build_graph_listpair(self):
        with vs.variable_scope('TrainInput'):
            self.context_input = tf.placeholder(tf.float32, shape=[None, self.most_n_doc, self.input_dim + 1],
                                                name='context_input')
            self.context_input_len = tf.placeholder(tf.int32, shape=[None], name='context_input_len')
            self.pair_input = tf.placeholder(tf.float32, shape=[None, self.most_n_pair, 2, self.input_dim + 1],
                                             name='pair_input_raw')
            self.pair_weight = tf.placeholder(tf.float32, shape=[None, self.most_n_pair], name='pair_weight_raw')
            self.pair_target = tf.placeholder(tf.int32, shape=[None, self.most_n_pair], name='pair_target_raw')
            self.pair_input_len = tf.placeholder(tf.int32, shape=[None], name='pair_input_len')
        with vs.variable_scope('TrainInputShape'):
            batch_num = tf.shape(self.context_input)[0]
        with vs.variable_scope('EmbeddingLookup'):
            self.doc_emb_W = tf.get_variable('doc_emb_W',self.doc_emb.shape,
                                             initializer=tf.constant_initializer(self.doc_emb),
                                             trainable=False)
            #self.doc_emb_W = tf.constant(self.doc_emb, dtype=tf.float32, name='doc_emb_W')
            self.query_emb_W = tf.get_variable('query_emb_W',self.query_emb.shape,
                                               initializer=tf.constant_initializer(self.query_emb),
                                               trainable=False)
            #self.query_emb_W = tf.constant(self.query_emb, dtype=tf.float32, name='query_emb_W')
            # look up context_input doc & query embedding
            cid = tf.nn.embedding_lookup(self.doc_emb_W,
                                         tf.to_int32(self.context_input[:, :, :1]))
            ciq = tf.nn.embedding_lookup(self.query_emb_W,
                                         tf.to_int32(self.context_input[:, :, 1:1 + self.most_n_subquery]))
            context_input_expand = tf.concat([tf.reshape(cid, [batch_num, self.most_n_doc, -1]),
                                              tf.reshape(ciq, [batch_num, self.most_n_doc, -1]),
                                              self.context_input[:, :, self.input_dim:]], axis=2)
            context_input_expand.set_shape([None, self.most_n_doc, self.expand_input_dim + 1])
            # look up pair_input doc & query embedding
            pid = tf.nn.embedding_lookup(self.doc_emb_W,
                                         tf.to_int32(self.pair_input[:, :, :, :1]))
            piq = tf.nn.embedding_lookup(self.query_emb_W,
                                         tf.to_int32(self.pair_input[:, :, :, 1:1 + self.most_n_subquery]))
            pair_input_expand = tf.concat([tf.reshape(pid, [batch_num, self.most_n_pair, 2, -1]),
                                           tf.reshape(piq, [batch_num, self.most_n_pair, 2, -1]),
                                           self.pair_input[:, :, :, self.input_dim:]], axis=3)
            pair_input_expand.set_shape([None, self.most_n_pair, 2, self.expand_input_dim + 1])
        with vs.variable_scope('DSSA-RNNMP'):
            cell = DSSA.get_cell(self.cell_type, self.hidden_size)
            self.cell = DSSACell(cell=cell, n_doc_emb=self.n_doc_emb, n_rel_feat=self.n_rel_feat,
                                 n_query_emb=self.n_query_emb, most_n_subquery=self.most_n_subquery,
                                 lambdaa=self.lambdaa, op=self.interaction, pool='max', state_is_tuple=False)
            outputs, context_states = tf.nn.dynamic_rnn(
                cell=self.cell,
                dtype=tf.float32,
                sequence_length=self.context_input_len,
                inputs=context_input_expand
            )
            with vs.variable_scope('ContextPairTransformation'):
                context_states = tf.reshape(tf.tile(context_states, [1, self.most_n_pair * 2]),
                                            [batch_num, self.most_n_pair, 2, self.cell.state_size])
                pair_mask = tf.range(self.most_n_pair) < tf.expand_dims(self.pair_input_len, -1)
                pair_weight_selected = tf.boolean_mask(self.pair_weight, pair_mask, name='pair_weight_select')
                pair_target_selected = tf.boolean_mask(self.pair_target, pair_mask, name='pair_target_select')
                pair_input_selected = tf.boolean_mask(pair_input_expand, pair_mask, name='pair_input_select')
                self.pair_input_selected = tf.reshape(pair_input_selected, [-1, 1, self.expand_input_dim + 1])
                context_states_selected = tf.boolean_mask(context_states, pair_mask, name='pair_states_select')
                self.context_states_selected = tf.reshape(context_states_selected, [-1, self.cell.state_size])
                actual_batch_num = tf.shape(pair_weight_selected)[0]
            vs.get_variable_scope().reuse_variables()
            outputs, second_states = tf.nn.dynamic_rnn(
                initial_state=self.context_states_selected,
                cell=self.cell,
                dtype=tf.float32,
                sequence_length=tf.fill([actual_batch_num * 2], 1),
                inputs=self.pair_input_selected
            )
        with vs.variable_scope('Loss'):
            self.outputs = tf.reshape(outputs, [actual_batch_num, 2])
            self.prob = tf.nn.softmax(self.outputs, name='pair_prob')
            target = tf.reshape(select_by_index(self.prob, pair_target_selected, zero_base=True),
                                [actual_batch_num])
            self.accuracy = tf.reduce_sum(tf.cast(target > 0.5, tf.float32)) /\
                            tf.cast(tf.reduce_prod(tf.shape(target)), tf.float32)
            self.log_loss = -tf.reduce_sum(pair_weight_selected * tf.log(target), name='log_loss')
            self.trainer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.log_loss)
        self.init_all_vars = tf.global_variables_initializer()
        self.saver = tf.train.Saver()

    def fit_iterable(self, X, y=None):
        # check params
        self.check_params()
        # init graph and session
        if not hasattr(self, 'session_'):
            self.graph_ = tf.Graph()
            with self.graph_.as_default():
                tf.set_random_seed(self.random_seed)
                with vs.variable_scope('DSSA', initializer=
                tf.uniform_unit_scaling_initializer(seed=self.random_seed)) as scope:
                    self.build_graph()
                    scope.reuse_variables()
                    self.build_graph_test()
            self.session_ = tf.Session(graph=self.graph_)
            self.session_.run(self.init_all_vars)
        # iteration
        for epoch in range(self.n_epochs):
            epoch += 1
            start = time.time()
            perm = np.random.permutation(len(X))
            loss_list, accuracy_list = [], []
            for i, (bX, by) in enumerate(self.batcher(X[perm], y[perm] if isinstance(y, np.ndarray) else None)):
                fd = self.batch_to_feeddict(bX, by)
                if self.optimization == 'listpair':
                    log_loss, accuracy, _ = \
                        self.session_.run([self.log_loss, self.accuracy, self.trainer], feed_dict=fd)
                    accuracy_list.append(accuracy)
                    loss_list.append(log_loss)
            if self.verbose: # output epoch stat
                print('{:<10}\t{:>7}:{:>5.3f}:{:>7.3f}'
                      .format('EPO[{}_{:>3.1f}]'.format(epoch, (time.time() - start)/60),
                              'train', np.mean(accuracy_list), np.mean(loss_list)), end='')
            if self.save_epochs and epoch % self.save_epochs == 0: # save the model
                if self.save_model:
                    self.saver.save(self.session_, self.save_model)
                yield
            # save the final model
            elif epoch == self.n_epochs and self.save_epochs and self.n_epochs % self.save_epochs != 0:
                if self.save_model:
                    self.saver.save(self.session_, self.save_model)
                yield
            if self.verbose:
                print('')

    def fit(self, X, y=None):
        list(self.fit_iterable(X, y))
        return self

    def decision_function(self, X):
        self.check_params()
        if not hasattr(self, 'session_'):
            raise AttributeError('need fit or fit_iterable to be called before prediction')
        ranks = []
        for q in X:
            select = []
            raw_data = q['test_x']
            n_doc = raw_data.shape[0]
            for r in range(n_doc):
                remain_ind = [i for i in range(n_doc) if i not in select]
                batch_input = np.array([[raw_data[i]] for i in remain_ind])
                out, states = self.session_.run([self.outputs_test, self.states], feed_dict={
                    self.test_input: batch_input,
                    self.test_input_len: np.ones((len(remain_ind))),
                    self.test_initial_state:
                        np.tile(last_states, [len(remain_ind)]).reshape(len(remain_ind), self.cell.state_size)
                        if r > 0 else self.cell.zero_state_np(len(remain_ind), np.float32)
                })
                next = np.argmax(out)
                select.append(remain_ind[next])
                last_states = states[next]
            ranks.append(select)
        return ranks

    def predict(self, X):
        return self.decision_function(X)

    def score(self, X, y, sample_weight=None):
        ranks = self.predict(X)
        metrics = []
        for i in range(len(X)):
            dq = y[i]
            ndq = DiversityQuery(dq.query, dq.qid, dq.subtopics, dq.docs[ranks[i]])
            metrics.append(ndq.get_metric('alpha_nDCG'))
        return np.mean(metrics)

    def __del__(self):
        if hasattr(self, 'session_'):
            self.session_.close()


#from __future__ import print_function
from pycocoevalcap.bleu.bleu import Bleu
from pycocoevalcap.rouge.rouge import Rouge
from pycocoevalcap.cider.cider import Cider
from pycocoevalcap.meteor.meteor import Meteor
from pycocoevalcap.spice.spice import Spice

import sys
import pickle

def score_func(ref, hypo, idx=None):
    """
    ref, dictionary of reference sentences (id, sentence)
    hypo, dictionary of hypothesis sentences (id, sentence)
    score, dictionary of scores
    """
    scorers = [
        (Spice(), "SPICE"),
        (Bleu(4), ["Bleu_1", "Bleu_2", "Bleu_3", "Bleu_4"]),
        (Rouge(), "ROUGE_L"),
        (Cider(), "CIDEr"),
        (Meteor(),"METEOR")
    ]
    final_scores = {}
    if idx is not None:
        scorers = [scorers[idx]]
    for scorer, method in scorers:
        score, scores = scorer.compute_score(ref, hypo)
        print('score', method, score)
        if type(score) == list:
            for m, s in zip(method, score):
                final_scores[m] = s
        else:
            final_scores[method] = score
    return final_scores

if __name__ == '__main__':
    ref_file = sys.argv[1]
    hyp_file = sys.argv[2]
    print(ref_file)
    print(hyp_file)

    refs = pickle.load(open(ref_file, 'rb'))[3]
    print('len(refs)', len(refs))

    hyps = {}
    for line in open(hyp_file, 'r'):
        key, hyp = line.strip().split('\t')
        if key not in hyps:
            hyps[key] = [hyp.strip()]
    print('len(hyps)', len(hyps))
    print('keys', set(hyps.keys()) == set(refs.keys()))

    scores = score_func(refs, hyps)
    print(scores)


from lib.components.abstract.container import Container
from lib.components.datastructs.dataset import Dataset
from lib.components.datastructs.trackout import Trackout
from lib.components.datastructs.loopkit import Loopkit
from lib.components.datastructs.loop import Track
import numpy as np
import logging
logger = logging.getLogger('my_logger')

class Mixer(Container):

    def __init__(self, name='section_as_a_track'):
        super().__init__(name)

    def sequence_loopkit(self, loopkit, loop_rep, info):
        loopseq = Trackout()
        loopseq.set_name(loopkit.get_name())
        loops = loopkit.get_items()
        loopseq.fill(loopkit=loops, loop_rep = loop_rep,
                        structure=info[loopkit.get_name()]['structure'],
                        tune_scheme=info[loopkit.get_name()]['tune_scheme'])
        return loopseq

    def fill(self, dataset: Dataset, loop_rep, info):
        self.ctrl_track = np.zeros([dataset.bar_length*loop_rep])
        for item in dataset.get_items():
            sequence = self.sequence_loopkit(item, loop_rep, info)
            self.add_item(sequence)

    def render_section(self):
        trackouts = Loopkit()
        beat = self.ctrl_track * 0

        for i, item in enumerate(self.get_items()):
            trackout = item.render_sequence()
            trackouts.add_item(trackout)
            beat = np.add(beat, trackout)
            track = Track(id=i, name=i, data=beat, sr=0, path=None, scale=None, st_shift=0)
        return track, trackouts


# -*- coding: utf-8 -*-
import os, sys
from importlib import import_module
from django.conf import settings
from django.contrib import messages
from django.utils import timezone
from django.utils.translation import gettext, gettext_lazy as _

def ac_expand_component_layout(modeladmin, request, queryset):
    """
        1. Ejecutar la función definida en cada registro
    """

    for obj in queryset:
        # import pdb; pdb.set_trace()
        if not obj.locked:
            obj.expand_component_layout()
            message = "Función %s realizada" % obj.alias
            modeladmin.message_user(request, message, level=messages.SUCCESS)
        else:
            message = _("el id:%s, %s no se carga porque está bloqueado") % (obj.id, obj.name)
            modeladmin.message_user(request, message, level=messages.warning)
    return
ac_expand_component_layout.short_description = "Expandir Layout con sus Componentes"

def ac_create_i18n(modeladmin, request, queryset):
    """
        1. Ejecutar la función definida en cada registro
    """

    for obj in queryset:
        # import pdb; pdb.set_trace()
        if not obj.locked:
            obj.create_i18n()
            message = "Función %s realizada" % obj.alias
        else:
            message = _("el id:%s, %s no se carga porque está bloqueado") % (obj.id, obj.name)
        modeladmin.message_user(request, message, level=messages.SUCCESS)
    return
ac_create_i18n.short_description = "Generar Traducciones"


import random
import collections
import termcolor
import pyfiglet

length = 4
random_string = [random.choice("ABCDEF") for rand_str in range(length)]
# print(*random_string)
count = collections.Counter(random_string)

def rule():
    print(termcolor.colored(pyfiglet.figlet_format("MASTERMIND"), color="red"))
    print("-----------------------------------------")
    print("\t\tMenu")
    print("-----------------------------------------")
    print("Enter code using characters.")
    print("you should constant of 4 characters from A to F ")
    print("EXAMPLE : ABCD")
    print("If you don't know how to play the game, read the file README\n")
    print("You have 8 attempts")

def create_game():
    guess = input('Your guess ?: ').upper()
    guess_count = collections.Counter(guess)
    wrong_position = sum(min(count[key], guess_count[key]) for key in count)
    right_position = sum(a==b for a,b in zip(random_string, guess))
    wrong_position -= right_position
    print(f'Right Position is : {right_position} Wrong Position is : {wrong_position}')
    return right_position != length

def result():
    for attempts in range(8):
        if not create_game():
            print('You Win !')
            break
        else:
            print('Your remaining attempts is :', 8 - 1- attempts)
    else:
        print('You Lost . The secret was {}.'.format(''.join(random_string)))

rule()
print("-----------------------------------------")
create_game()
result()


""" Utility functions related to mesh processing """
import numpy as np
import vsi.utils.io_utils as io_utils
import vtk
import glob
import os.path

def write_grid_vtk(image_stack_glob, output_filename, origin=(0,0,0), vox_len=1.0):
  """ write out an image stack to a VTK "Structured Points" format """
  image_fnames = glob.glob(image_stack_glob)
  image_fnames.sort()
  nk = len(image_fnames)
  if nk == 0:
    raise Exception('No images matching ' + image_stack_glob)

  # read first image to get x,y dimensions
  img0 = io_utils.imread(image_fnames[0])

  ni = img0.shape[1]
  nj = img0.shape[0]

  fd = open(output_filename, 'w')
  fd.write('# vtk DataFile Version 3.1\n')
  fd.write('a voxel grid\n')
  fd.write('ASCII\n')
  fd.write('DATASET STRUCTURED_POINTS\n')
  fd.write('DIMENSIONS %d %d %d\n' % (ni,nj,nk))
  fd.write('ORIGIN %f %f %f\n' % (origin[0], origin[1], origin[2]))
  fd.write('SPACING %f %f %f\n' % (vox_len, vox_len, vox_len))
  fd.write('POINT_DATA %d\n' % (ni*nj*nk))
  fd.write('SCALARS values float 1\n')
  fd.write('LOOKUP_TABLE default\n')
  for k in range(nk):
    img = io_utils.imread(image_fnames[k])
    for j in range(nj):
      for i in range(ni):
        fd.write('%f\n' % (float(img[j,i]) / 255.0))
  fd.write('\n')
  fd.close()

def marching_cubes(grid_fname_vtk, mesh_filename_ply, value=0.5):
  """ read in a grid in vtk format, run marching cubes, save the result as ply mesh """
  reader = vtk.vtkStructuredPointsReader()
  reader.SetFileName(grid_fname_vtk)
  reader.Update()
  points = reader.GetOutput()

  mcubes = vtk.vtkMarchingCubes()
  mcubes.SetInput(points)
  mcubes.SetValue(0, value)
  mcubes.Update()
  mesh = mcubes.GetOutput()

  writer = vtk.vtkPLYWriter()
  writer.SetInput(mesh)
  writer.SetFileName(mesh_filename_ply)
  writer.Update()
  writer.Write()

def colorize_verts_ply(ply_in_filename, ply_out_filename, image, camera):
  """ add per-vertex color information based on projections into images """
  # read in PLY file
  reader = vtk.vtkPLYReader()
  reader.SetFileName(ply_in_filename)
  reader.Update()
  data = reader.GetOutput()

  # create Color data
  colors = vtk.vtkUnsignedCharArray()
  colors.SetNumberOfComponents(3)
  colors.SetName("Colors")

  num_pts = data.GetNumberOfPoints()
  for n in range(num_pts):
    pt3d = data.GetPoint(n)
    pt2d = camera.project_point(pt3d).astype(np.int)
    img_size = np.array((image.shape[1], image.shape[0]))
    if np.any(pt2d < 0) or np.any(pt2d >= img_size):
      color = (128, 128, 128)
    else:
      color = image[pt2d[1], pt2d[0], :]
    # convert gray to RGB
    if len(color) == 1:
      color = (color, color, color)
    colors.InsertNextTuple3(color[0], color[1], color[2])

  data.GetPointData().SetScalars(colors)
  data.Update()

  # write new PLY
  writer = vtk.vtkPLYWriter()
  writer.SetFileName(ply_out_filename)
  writer.SetInput(data)
  writer.SetArrayName("Colors")
  writer.Update()
  writer.Write()

def get_mesh_vertices(mesh_filename):
  """ read a ply file, return vertices in form of 3xN numpy array """
  # read in PLY file
  mesh_ext = os.path.splitext(mesh_filename)[1].lower()
  if mesh_ext == '.ply':
    reader = vtk.vtkPLYReader()
  elif mesh_ext == '.obj':
    reader = vtk.vtkOBJReader()
  else:
    raise Exception('Unsupported filename extension ' + mesh_ext)
  reader.SetFileName(mesh_filename)
  reader.Update()
  data = reader.GetOutput()

  num_pts = data.GetNumberOfPoints()
  vert_matrix = np.zeros((3,num_pts))
  for n in range(num_pts):
    pt3d = data.GetPoint(n)
    vert_matrix[:,n] = pt3d

  return vert_matrix


# encoding:utf-8
import socket
import json
from utils.convert import *
def udp_receive_message(ip_addr,port):
    """使用udp连接方式循环接收数据，输入IP地址(字符串类型)和端口（数值类型）"""
    ip_addr_str = str(ip_addr)  # 转换成字符串类型
    # 1.创建套接字
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    # 2.绑定本地信息
    addr = (ip_addr_str,port)
    udp_socket.bind(addr)
    # 3.创建存储发动机转速数据的结构
    latitude_deg_data=[]
    longitude_deg_data=[]
    # 3接受数据
    while True:
        rec_data = udp_socket.recvfrom(1024)
        rec_msg = rec_data[0].decode()
        str_recmsg = "{"+rec_msg[:-1]+"}"
        dict_recmsg = json.loads(str_recmsg)
        latitude_deg_data.append(dict_recmsg.get("latitude-deg"))
        longitude_deg_data.append(dict_recmsg.get("longitude-deg"))
        #savedata2xlsx(latitude_deg_data)
        longitude_deg_data = [str(i) for i in latitude_deg_data]
        latitude_deg_data = [str(i) for i in latitude_deg_data]
        location=[longitude_deg_data,latitude_deg_data]
        xw_toexcel(location,'E:\\test_data\\test.xlsx')
        #send_addr = rec_data[1] 主机地址信息
        # 打印收到的数据
        # print(rec_data)
        #coordinate=zip(longitude_deg_data,latitude_deg_data)
        #print(dict(coordinate))
        #print(rec_data)  #数据来源
        #print(type(data))
        # print("%s:%s" % (str(send_addr), rec_msg.decode("gb18030")))
    # 关闭套接字
    udp_socket.close()


import requests
from bs4 import BeautifulSoup
import json

def fetch(url, params):
    headers = params['headers']
    body = params['body']
    if params['method'] == 'GET':
        return requests.get(url, headers=headers)
    if params['method'] == 'POST':
        return requests.post(url, headers=headers, data=body)

card = fetch("https://basket-05.wb.ru/vol735/part73512/73512949/info/ru/card.json", {
    "headers": {},
    "referrerPolicy": "no-referrer-when-downgrade",
    "body": None,
    "method": "GET"
});

print(card.status_code)
print(card.json().keys())

article = card.json()['nm_id']
print(article)

brand = card.json()['selling']['brand_name']
print(brand)

article_name = card.json()['imt_name']
print(article_name)


import urllib.request
import os
import zipfile

def download(data_path):
    url = "https://bai-scieval.duiopen.com/bai-scieval.zip"
    save_path = data_path + "/bai-scieval.zip"
    unzip_path = data_path

    if not os.path.isdir(unzip_path):
        os.mkdir(unzip_path)

    try:
        urllib.request.urlretrieve(url, save_path)
    except:
        print("download failed!")
        return False

    #开始解压
    #判断是否是压缩文件
    if zipfile.is_zipfile(save_path):
    #读取压缩文件
        fz = zipfile.ZipFile(save_path, 'r')
    #提取文件到解压目录
        for file in fz.namelist():
            fz.extract(file, unzip_path)
    else:
    #否则返回失败
        return False
    return True