



# Copyright (c) 2019 Uber Technologies, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import csv
import json
import math
import time

import numpy as np
import torch
import torch.optim as optim
import torch.utils.data as data
from nltk.tokenize.treebank import TreebankWordDetokenizer
from pplm_classification_head import ClassificationHead
from torch import nn
from torchtext import data as torchtext_data
from torchtext import datasets
from tqdm import tqdm, trange

from transformers import GPTaLMHeadModel, GPTaTokenizer


torch.manual_seed(0)
np.random.seed(0)
__snake_case		:Optional[int] 						=	1E-10
__snake_case		:Optional[int] 						=	'''This is incredible! I love it, this is the best chicken I have ever had.'''
__snake_case		:int 						=	100

class        _A			(      nn.Module       ):



       def __init__(						self				:	Optional[int]	,						__SCREAMING_SNAKE_CASE				:	Any	,						__SCREAMING_SNAKE_CASE				:	Dict="gpt2-medium"	,						__SCREAMING_SNAKE_CASE				:	Dict=False	,						__SCREAMING_SNAKE_CASE				:	int="cpu"):


           '''simple docstring'''

           super().__init__()
           __a					=							GPTaTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE)
           __a					=							GPTaLMHeadModel.from_pretrained(__SCREAMING_SNAKE_CASE)
           __a					=							self.encoder.transformer.config.hidden_size
           __a					=							ClassificationHead(class_size=__SCREAMING_SNAKE_CASE	,						embed_size=self.embed_size)
           __a					=							cached_mode
           __a					=							device



       def 						_lowerCamelCase     (						self				:	str):


           '''simple docstring'''

           return self.classifier_head



       def 						_lowerCamelCase     (						self				:	Tuple):


           '''simple docstring'''

           for param in self.encoder.parameters():
               __a					=							False
           self.classifier_head.train()



       def 						_lowerCamelCase     (						self				:	str	,						__SCREAMING_SNAKE_CASE				:	Dict):


           '''simple docstring'''

           __a					=							x.ne(0).unsqueeze(2).repeat(1	,						1	,						self.embed_size).float().to(self.device).detach()
           __a					=							self.encoder.transformer(__SCREAMING_SNAKE_CASE)['''last_hidden_state''']
           __a					=							hidden * mask
           __a					=							torch.sum(__SCREAMING_SNAKE_CASE	,						dim=1) / (torch.sum(__SCREAMING_SNAKE_CASE	,						dim=1).detach() + EPSILON)
           return avg_hidden





       def 						_lowerCamelCase     (						self				:	Union[str, Any]	,						__SCREAMING_SNAKE_CASE				:	Tuple):


           '''simple docstring'''

           if self.cached_mode:
               __a					=							x.to(self.device)
           else:
               __a					=							self.avg_representation(x.to(self.device))

           __a					=							self.classifier_head(__SCREAMING_SNAKE_CASE)
           __a					=							nn.functional.log_softmax(__SCREAMING_SNAKE_CASE	,						dim=-1)

           return probs


class        _A			(      data.Dataset       ):



       def __init__(						self				:	Any	,						__SCREAMING_SNAKE_CASE				:	Optional[int]	,						__SCREAMING_SNAKE_CASE				:	Optional[Any]):


           '''simple docstring'''

           __a					=							X
           __a					=							y



       def __len__(						self				:	List[Any]):


           '''simple docstring'''

           return len(self.X)





       def __getitem__(						self				:	Optional[Any]	,						__SCREAMING_SNAKE_CASE				:	Optional[Any]):


           '''simple docstring'''

           __a					=							{}
           __a					=							self.X[index]
           __a					=							self.y[index]
           return data





def 	__snake_case      (     _UpperCAmelCase							):
    def pad_sequences(_UpperCAmelCase							):
        __a					=							[len(_UpperCAmelCase							) for seq in sequences]

        __a					=							torch.zeros(len(_UpperCAmelCase							)  ,					max(_UpperCAmelCase							)							).long()  # padding value = 0

        for i, seq in enumerate(_UpperCAmelCase							):
            __a					=							lengths[i]
            __a					=							seq[:end]

        return padded_sequences, lengths

    __a					=							{}
    for key in data[0].keys():
        __a					=							[d[key] for d in data]

    __a			,  __a					=							pad_sequences(item_info['''X''']							)
    __a					=							torch.tensor(item_info['''y''']  ,					dtype=torch.long							)

    return x_batch, y_batch





def 	__snake_case      (     _UpperCAmelCase							):
    __a					=							{}
    for key in data[0].keys():
        __a					=							[d[key] for d in data]

    __a					=							torch.cat(item_info['''X''']  ,					0							)
    __a					=							torch.tensor(item_info['''y''']  ,					dtype=torch.long							)

    return x_batch, y_batch





def 	__snake_case      (     _UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase=0  ,					_UpperCAmelCase=10  ,					_UpperCAmelCase="cpu"							):
    __a					=							0
    discriminator.train_custom()
    for batch_idx, (input_t, target_t) in enumerate(_UpperCAmelCase							):
        __a			,  __a					=							input_t.to(_UpperCAmelCase							), target_t.to(_UpperCAmelCase							)

        optimizer.zero_grad()

        __a					=							discriminator(_UpperCAmelCase							)
        __a					=							nn.functional.nll_loss(_UpperCAmelCase  ,					_UpperCAmelCase							)
        loss.backward(retain_graph=_UpperCAmelCase							)
        optimizer.step()

        samples_so_far += len(_UpperCAmelCase							)

        if batch_idx % log_interval == 0:
            print(
                '''Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'''.format(
                    epoch + 1  ,					_UpperCAmelCase  ,					len(data_loader.dataset							)  ,					100 * samples_so_far / len(data_loader.dataset							)  ,					loss.item()  ,					)							)





def 	__snake_case      (     _UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase="cpu"							):
    discriminator.eval()
    __a					=							0
    __a					=							0
    with torch.no_grad():
        for input_t, target_t in data_loader:
            __a			,  __a					=							input_t.to(_UpperCAmelCase							), target_t.to(_UpperCAmelCase							)
            __a					=							discriminator(_UpperCAmelCase							)
            # sum up batch loss
            test_loss += nn.functional.nll_loss(_UpperCAmelCase  ,					_UpperCAmelCase  ,					reduction='''sum'''							).item()
            # get the index of the max log-probability
            __a					=							output_t.argmax(dim=1  ,					keepdim=_UpperCAmelCase							)
            correct += pred_t.eq(target_t.view_as(_UpperCAmelCase							)							).sum().item()

    test_loss /= len(data_loader.dataset							)

    print(
        '''Performance on test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'''.format(
            _UpperCAmelCase  ,					_UpperCAmelCase  ,					len(data_loader.dataset							)  ,					1_00.0 * correct / len(data_loader.dataset							)							)							)





def 	__snake_case      (     _UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase=False  ,					_UpperCAmelCase="cpu"							):
    __a					=							model.tokenizer.encode(_UpperCAmelCase							)
    __a					=							torch.tensor([input_t]  ,					dtype=torch.long  ,					device=_UpperCAmelCase							)
    if cached:
        __a					=							model.avg_representation(_UpperCAmelCase							)

    __a					=							model(_UpperCAmelCase							).data.cpu().numpy().flatten().tolist()
    print('''Input sentence:'''  ,					_UpperCAmelCase							)
    print(
        '''Predictions:'''  ,					''', '''.join('''{}: {:.4f}'''.format(_UpperCAmelCase  ,					math.exp(_UpperCAmelCase							)							) for c, log_prob in zip(_UpperCAmelCase  ,					_UpperCAmelCase							)							)  ,					)





def 	__snake_case      (     _UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase=False  ,					_UpperCAmelCase="cpu"							):
    __a					=							torch.utils.data.DataLoader(dataset=_UpperCAmelCase  ,					batch_size=_UpperCAmelCase  ,					collate_fn=_UpperCAmelCase							)

    __a					=							[]
    __a					=							[]
    for batch_idx, (x, y) in enumerate(tqdm(_UpperCAmelCase  ,					ascii=_UpperCAmelCase							)							):
        with torch.no_grad():
            __a					=							x.to(_UpperCAmelCase							)
            __a					=							discriminator.avg_representation(_UpperCAmelCase							).cpu().detach()
            __a					=							torch.unbind(avg_rep.unsqueeze(1							)							)
            xs += avg_rep_list
            ys += y.cpu().numpy().tolist()

    __a					=							torch.utils.data.DataLoader(
        dataset=Dataset(_UpperCAmelCase  ,					_UpperCAmelCase							)  ,					batch_size=_UpperCAmelCase  ,					shuffle=_UpperCAmelCase  ,					collate_fn=_UpperCAmelCase							)

    return data_loader





def 	__snake_case      (     _UpperCAmelCase  ,					_UpperCAmelCase=None  ,					_UpperCAmelCase="gpt2-medium"  ,					_UpperCAmelCase=10  ,					_UpperCAmelCase=64  ,					_UpperCAmelCase=10  ,					_UpperCAmelCase=False  ,					_UpperCAmelCase=False  ,					_UpperCAmelCase=False  ,					):
    __a					=							'''cuda''' if torch.cuda.is_available() and not no_cuda else '''cpu'''

    print('''Preprocessing {} dataset...'''.format(_UpperCAmelCase							)							)
    __a					=							time.time()

    if dataset == "SST":
        __a					=							['''positive''', '''negative''', '''very positive''', '''very negative''', '''neutral''']
        __a					=							{c: i for i, c in enumerate(_UpperCAmelCase							)}

        __a					=							Discriminator(
            class_size=len(_UpperCAmelCase							)  ,					pretrained_model=_UpperCAmelCase  ,					cached_mode=_UpperCAmelCase  ,					device=_UpperCAmelCase							).to(_UpperCAmelCase							)

        __a					=							torchtext_data.Field()
        __a					=							torchtext_data.Field(sequential=_UpperCAmelCase							)
        __a			,  __a			,  __a					=							datasets.SST.splits(
            _UpperCAmelCase  ,					_UpperCAmelCase  ,					fine_grained=_UpperCAmelCase  ,					train_subtrees=_UpperCAmelCase  ,					)

        __a					=							[]
        __a					=							[]
        for i in trange(len(_UpperCAmelCase							)  ,					ascii=_UpperCAmelCase							):
            __a					=							TreebankWordDetokenizer().detokenize(vars(train_data[i]							)['''text''']							)
            __a					=							discriminator.tokenizer.encode(_UpperCAmelCase							)
            __a					=							torch.tensor([50256] + seq  ,					device=_UpperCAmelCase  ,					dtype=torch.long							)
            x.append(_UpperCAmelCase							)
            y.append(classaidx[vars(train_data[i]							)['''label''']]							)
        __a					=							Dataset(_UpperCAmelCase  ,					_UpperCAmelCase							)

        __a					=							[]
        __a					=							[]
        for i in trange(len(_UpperCAmelCase							)  ,					ascii=_UpperCAmelCase							):
            __a					=							TreebankWordDetokenizer().detokenize(vars(test_data[i]							)['''text''']							)
            __a					=							discriminator.tokenizer.encode(_UpperCAmelCase							)
            __a					=							torch.tensor([50256] + seq  ,					device=_UpperCAmelCase  ,					dtype=torch.long							)
            test_x.append(_UpperCAmelCase							)
            test_y.append(classaidx[vars(test_data[i]							)['''label''']]							)
        __a					=							Dataset(_UpperCAmelCase  ,					_UpperCAmelCase							)

        __a					=							{
            '''class_size''': len(_UpperCAmelCase							),
            '''embed_size''': discriminator.embed_size,
            '''pretrained_model''': pretrained_model,
            '''class_vocab''': classaidx,
            '''default_class''': 2,
        }

    elif dataset == "clickbait":
        __a					=							['''non_clickbait''', '''clickbait''']
        __a					=							{c: i for i, c in enumerate(_UpperCAmelCase							)}

        __a					=							Discriminator(
            class_size=len(_UpperCAmelCase							)  ,					pretrained_model=_UpperCAmelCase  ,					cached_mode=_UpperCAmelCase  ,					device=_UpperCAmelCase							).to(_UpperCAmelCase							)

        with open('''datasets/clickbait/clickbait_train_prefix.txt'''							) as f:
            __a					=							[]
            for i, line in enumerate(_UpperCAmelCase							):
                try:
                    data.append(eval(_UpperCAmelCase							)							)
                except Exception:
                    print('''Error evaluating line {}: {}'''.format(_UpperCAmelCase  ,					_UpperCAmelCase							)							)
                    continue
        __a					=							[]
        __a					=							[]
        with open('''datasets/clickbait/clickbait_train_prefix.txt'''							) as f:
            for i, line in enumerate(tqdm(_UpperCAmelCase  ,					ascii=_UpperCAmelCase							)							):
                try:
                    __a					=							eval(_UpperCAmelCase							)
                    __a					=							discriminator.tokenizer.encode(d['''text''']							)

                    if len(_UpperCAmelCase							) < max_length_seq:
                        __a					=							torch.tensor([50256] + seq  ,					device=_UpperCAmelCase  ,					dtype=torch.long							)
                    else:
                        print('''Line {} is longer than maximum length {}'''.format(_UpperCAmelCase  ,					_UpperCAmelCase							)							)
                        continue
                    x.append(_UpperCAmelCase							)
                    y.append(d['''label''']							)
                except Exception:
                    print('''Error evaluating / tokenizing line {}, skipping it'''.format(_UpperCAmelCase							)							)
                    pass

        __a					=							Dataset(_UpperCAmelCase  ,					_UpperCAmelCase							)
        __a					=							int(0.9 * len(_UpperCAmelCase							)							)
        __a					=							len(_UpperCAmelCase							) - train_size
        __a			,  __a					=							torch.utils.data.random_split(_UpperCAmelCase  ,					[train_size, test_size]							)

        __a					=							{
            '''class_size''': len(_UpperCAmelCase							),
            '''embed_size''': discriminator.embed_size,
            '''pretrained_model''': pretrained_model,
            '''class_vocab''': classaidx,
            '''default_class''': 1,
        }

    elif dataset == "toxic":
        __a					=							['''non_toxic''', '''toxic''']
        __a					=							{c: i for i, c in enumerate(_UpperCAmelCase							)}

        __a					=							Discriminator(
            class_size=len(_UpperCAmelCase							)  ,					pretrained_model=_UpperCAmelCase  ,					cached_mode=_UpperCAmelCase  ,					device=_UpperCAmelCase							).to(_UpperCAmelCase							)

        __a					=							[]
        __a					=							[]
        with open('''datasets/toxic/toxic_train.txt'''							) as f:
            for i, line in enumerate(tqdm(_UpperCAmelCase  ,					ascii=_UpperCAmelCase							)							):
                try:
                    __a					=							eval(_UpperCAmelCase							)
                    __a					=							discriminator.tokenizer.encode(d['''text''']							)

                    if len(_UpperCAmelCase							) < max_length_seq:
                        __a					=							torch.tensor([50256] + seq  ,					device=_UpperCAmelCase  ,					dtype=torch.long							)
                    else:
                        print('''Line {} is longer than maximum length {}'''.format(_UpperCAmelCase  ,					_UpperCAmelCase							)							)
                        continue
                    x.append(_UpperCAmelCase							)
                    y.append(int(np.sum(d['''label''']							) > 0							)							)
                except Exception:
                    print('''Error evaluating / tokenizing line {}, skipping it'''.format(_UpperCAmelCase							)							)
                    pass

        __a					=							Dataset(_UpperCAmelCase  ,					_UpperCAmelCase							)
        __a					=							int(0.9 * len(_UpperCAmelCase							)							)
        __a					=							len(_UpperCAmelCase							) - train_size
        __a			,  __a					=							torch.utils.data.random_split(_UpperCAmelCase  ,					[train_size, test_size]							)

        __a					=							{
            '''class_size''': len(_UpperCAmelCase							),
            '''embed_size''': discriminator.embed_size,
            '''pretrained_model''': pretrained_model,
            '''class_vocab''': classaidx,
            '''default_class''': 0,
        }

    else:  # if dataset == "generic":
        # This assumes the input dataset is a TSV with the following structure:
        # class \t text

        if dataset_fp is None:
            raise ValueError('''When generic dataset is selected, dataset_fp needs to be specified aswell.'''							)

        __a					=							set()
        with open(_UpperCAmelCase							) as f:
            __a					=							csv.reader(_UpperCAmelCase  ,					delimiter='''\t'''							)
            for row in tqdm(_UpperCAmelCase  ,					ascii=_UpperCAmelCase							):
                if row:
                    classes.add(row[0]							)

        __a					=							sorted(_UpperCAmelCase							)
        __a					=							{c: i for i, c in enumerate(_UpperCAmelCase							)}

        __a					=							Discriminator(
            class_size=len(_UpperCAmelCase							)  ,					pretrained_model=_UpperCAmelCase  ,					cached_mode=_UpperCAmelCase  ,					device=_UpperCAmelCase							).to(_UpperCAmelCase							)

        __a					=							[]
        __a					=							[]
        with open(_UpperCAmelCase							) as f:
            __a					=							csv.reader(_UpperCAmelCase  ,					delimiter='''\t'''							)
            for i, row in enumerate(tqdm(_UpperCAmelCase  ,					ascii=_UpperCAmelCase							)							):
                if row:
                    __a					=							row[0]
                    __a					=							row[1]

                    try:
                        __a					=							discriminator.tokenizer.encode(_UpperCAmelCase							)
                        if len(_UpperCAmelCase							) < max_length_seq:
                            __a					=							torch.tensor([50256] + seq  ,					device=_UpperCAmelCase  ,					dtype=torch.long							)

                        else:
                            print('''Line {} is longer than maximum length {}'''.format(_UpperCAmelCase  ,					_UpperCAmelCase							)							)
                            continue

                        x.append(_UpperCAmelCase							)
                        y.append(classaidx[label]							)

                    except Exception:
                        print('''Error tokenizing line {}, skipping it'''.format(_UpperCAmelCase							)							)
                        pass

        __a					=							Dataset(_UpperCAmelCase  ,					_UpperCAmelCase							)
        __a					=							int(0.9 * len(_UpperCAmelCase							)							)
        __a					=							len(_UpperCAmelCase							) - train_size
        __a			,  __a					=							torch.utils.data.random_split(_UpperCAmelCase  ,					[train_size, test_size]							)

        __a					=							{
            '''class_size''': len(_UpperCAmelCase							),
            '''embed_size''': discriminator.embed_size,
            '''pretrained_model''': pretrained_model,
            '''class_vocab''': classaidx,
            '''default_class''': 0,
        }

    __a					=							time.time()
    print('''Preprocessed {} data points'''.format(len(_UpperCAmelCase							) + len(_UpperCAmelCase							)							)							)
    print('''Data preprocessing took: {:.3f}s'''.format(end - start							)							)

    if cached:
        print('''Building representation cache...'''							)

        __a					=							time.time()

        __a					=							get_cached_data_loader(_UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase  ,					shuffle=_UpperCAmelCase  ,					device=_UpperCAmelCase							)

        __a					=							get_cached_data_loader(_UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase  ,					device=_UpperCAmelCase							)

        __a					=							time.time()
        print('''Building representation cache took: {:.3f}s'''.format(end - start							)							)

    else:
        __a					=							torch.utils.data.DataLoader(
            dataset=_UpperCAmelCase  ,					batch_size=_UpperCAmelCase  ,					shuffle=_UpperCAmelCase  ,					collate_fn=_UpperCAmelCase							)
        __a					=							torch.utils.data.DataLoader(dataset=_UpperCAmelCase  ,					batch_size=_UpperCAmelCase  ,					collate_fn=_UpperCAmelCase							)

    if save_model:
        with open('''{}_classifier_head_meta.json'''.format(_UpperCAmelCase							)  ,					'''w'''							) as meta_file:
            json.dump(_UpperCAmelCase  ,					_UpperCAmelCase							)

    __a					=							optim.Adam(discriminator.parameters()  ,					lr=0.00_01							)

    for epoch in range(_UpperCAmelCase							):
        __a					=							time.time()
        print('''\nEpoch'''  ,					epoch + 1							)

        train_epoch(
            discriminator=_UpperCAmelCase  ,					data_loader=_UpperCAmelCase  ,					optimizer=_UpperCAmelCase  ,					epoch=_UpperCAmelCase  ,					log_interval=_UpperCAmelCase  ,					device=_UpperCAmelCase  ,					)
        evaluate_performance(data_loader=_UpperCAmelCase  ,					discriminator=_UpperCAmelCase  ,					device=_UpperCAmelCase							)

        __a					=							time.time()
        print('''Epoch took: {:.3f}s'''.format(end - start							)							)

        print('''\nExample prediction'''							)
        predict(_UpperCAmelCase  ,					_UpperCAmelCase  ,					_UpperCAmelCase  ,					cached=_UpperCAmelCase  ,					device=_UpperCAmelCase							)

        if save_model:
            # torch.save(discriminator.state_dict(),
            #           "{}_discriminator_{}.pt".format(
            #               args.dataset, epoch + 1
            #               ))
            torch.save(
                discriminator.get_classifier().state_dict()  ,					'''{}_classifier_head_epoch_{}.pt'''.format(_UpperCAmelCase  ,					epoch + 1							)  ,					)


if __name__ == "__main__":
 __snake_case		:str 						=	argparse.ArgumentParser(description='''Train a discriminator on top of GPT-2 representations''')
 parser.add_argument(
     '''--dataset''',
     type=str,
     default='''SST''',
     choices=('''SST''', '''clickbait''', '''toxic''', '''generic'''),
     help=(
         '''dataset to train the discriminator on.'''
         '''In case of generic, the dataset is expected'''
         '''to be a TSBV file with structure: class \\t text'''
     ),
 )
 parser.add_argument(
     '''--dataset_fp''',
     type=str,
     default='''''',
     help='''File path of the dataset to use. Needed only in case of generic datadset''',
 )
 parser.add_argument(
     '''--pretrained_model''', type=str, default='''gpt2-medium''', help='''Pretrained model to use as encoder'''
 )
 parser.add_argument('''--epochs''', type=int, default=10, metavar='''N''', help='''Number of training epochs''')
 parser.add_argument(
     '''--batch_size''', type=int, default=64, metavar='''N''', help='''input batch size for training (default: 64)'''
 )
 parser.add_argument(
     '''--log_interval''',
     type=int,
     default=10,
     metavar='''N''',
     help='''how many batches to wait before logging training status''',
 )
 parser.add_argument('''--save_model''', action='''store_true''', help='''whether to save the model''')
 parser.add_argument('''--cached''', action='''store_true''', help='''whether to cache the input representations''')
 parser.add_argument('''--no_cuda''', action='''store_true''', help='''use to turn off cuda''')
 __snake_case		:Optional[int] 						=	parser.parse_args()

 train_discriminator(**(vars(args)))










from math import floor, sqrt





def 	__snake_case      (     _UpperCAmelCase							):
    __a					=							0.0
    __a					=							1.0
    __a					=							int(sqrt(_UpperCAmelCase							)							)
    __a					=							root
    __a					=							0
    while integer_part != 2 * root:
        __a					=							denominator * integer_part - numerator
        __a					=							(n - numerator**2) / denominator
        __a					=							int((root + numerator) / denominator							)
        period += 1
    return period





def 	__snake_case      (     _UpperCAmelCase = 10000							):
    __a					=							0
    for i in range(2  ,					n + 1							):
        __a					=							sqrt(_UpperCAmelCase							)
        if sr - floor(_UpperCAmelCase							) != 0 and continuous_fraction_period(_UpperCAmelCase							) % 2 == 1:
            count_odd_periods += 1
    return count_odd_periods


if __name__ == "__main__":
 print(f'{solution(int(input().strip()))}')





