repo_id
stringlengths
6
101
size
int64
367
5.14M
file_path
stringlengths
2
269
content
stringlengths
367
5.14M
274056675/springboot-openai-chatgpt
1,146
mng_web/src/mock/user.js
import Mock from 'mockjs' export default ({ mock }) => { if (!mock) return; // 用户登录 Mock.mock('/user/login', 'post', { data: new Date().getTime() + '' }); //用户退出 Mock.mock('/user/logout', 'get', { data: true, }); //刷新token Mock.mock('/user/refesh', 'post', { data: new Date().getTime() + '' }); //获取表格数据 Mock.mock('/user/getTable', 'get', () => { let list = [] for (let i = 0; i < 5; i++) { list.push(Mock.mock({ id: '@increment', name: Mock.mock('@cname'), username: Mock.mock('@last'), type: [0, 2], checkbox: [0, 1], 'number|0-100': 0, datetime: 1532932422071, 'sex|0-1': 0, moreselect: [0, 1], "grade": 0, address: Mock.mock('@cparagraph(1, 3)'), check: [1, 3, 4] })) } return { data: { total: 11, pageSize: 10, tableData: list } } }) }
274056675/springboot-openai-chatgpt
2,842
mng_web/src/styles/media.scss
.avue-left, .avue-header, .avue-top, .avue-logo, .avue-layout .login-logo, .avue-main { transition: all .3s; } .avue-contail { width: 100%; height: 100%; background: #f0f2f5; background-size: 100%; background-repeat: no-repeat; } .avue-left { position: fixed; left: 0; top: 0; width: 240px; height: 100%; z-index: 1025; } .avue--collapse { .avue-left, .avue-logo { width: 60px; } .avue-header { padding-left: 60px; } .avue-main { width: calc(100% - 60px); left: 60px; } } .avue-header { padding-left: 240px; width: 100%; background-color: #fff; box-sizing: border-box; } .avue-main { position: absolute; left: 240px; padding: 0; padding-bottom: 20px; width: calc(100% - 240px); height: calc(100% - 70px); box-sizing: border-box; overflow: hidden; } .avue-view { padding-bottom: 22px; width: 100%; box-sizing: border-box; } .avue-footer { margin: 0 auto; padding: 0 22px; width: 1300px; display: flex; align-items: center; justify-content: space-between; .logo { margin-left: -50px; } .copyright { color: #666; line-height: 1.5; font-size: 12px; } } .avue-shade { position: fixed; display: none; width: 100%; height: 100%; left: 0; right: 0; top: 0; bottom: 0; background-color: rgba(0, 0, 0, .3); z-index: 1024; &--show { display: block; } } @media screen and (max-width: 992px) { $width: 240px; // ele的自适应 .el-dialog, .el-message-box { width: 98% !important; } //登录页面 .login-left { display: none !important; } .login-logo { padding-top: 30px !important; margin-left: -30px; } .login-weaper{ margin: 0 auto; width: 96% !important; } .login-border { border-radius: 5px; padding: 40px; margin: 0 auto; float: none !important; width: 100% !important; } .login-main { width: 100% !important; } //主框架 .avue-tags { display: none; } .avue-left, .avue-logo { left: -$width; } .avue-main { left: 0; width: 100%; } .avue-header { margin-bottom: 15px; padding-left: 15px; } .top-bar__item { display: none; } .avue--collapse { .avue-left, .avue-logo { width: $width; left: 0; } .avue-main { left: $width; width: 100%; } .avue-header { padding: 0; transform: translate3d(230px, 0, 0); } .avue-shade { display: block; } } }
233zzh/TitanDataOperationSystem
14,580
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/js/task-init.js
$(function() { /** * Created by Zura on 4/5/2016. */ $(function() { Lobibox.notify.DEFAULTS = $.extend({}, Lobibox.notify.DEFAULTS, { size: 'mini', // delay: false, position: 'right top' }); //Basic example $('#todo-lists-basic-demo').lobiList({ lists: [{ id: 'todo', title: 'Todo', defaultStyle: 'lobilist-danger', items: [{ title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' }, { title: 'Periods pride', description: 'Accepted was mollis', done: true }, { title: 'Flags better burns pigeon', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank treacherously darkling.' }, { title: 'Accepted was mollis', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank treacherously darkling.', dueDate: '2015-02-02' } ] }, { id: 'doing', title: 'Doing', defaultStyle: 'lobilist-primary', items: [{ title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage celerities gales beams.' }, { title: 'Chic leafy' }, { title: 'Guessed interdum armies chirp writhes most', description: 'Came champlain live leopards twilight whenever warm read wish squirrel rock.', dueDate: '2015-02-04', done: true } ] }, { id: 'Done', title: 'Done', defaultStyle: 'lobilist-success', items: [{ title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage celerities gales beams.' }, { title: 'Chic leafy' }, { title: 'Guessed interdum armies chirp writhes most', description: 'Came champlain live leopards twilight whenever warm read wish squirrel rock.', dueDate: '2015-02-04', done: true } ] } ] }); //Custom datepicker $('#todo-lists-demo-datepicker').lobiList({ lists: [{ title: 'Todo', defaultStyle: 'lobilist-info', items: [{ title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' }] }], afterListAdd: function(lobilist, list) { var $dueDateInput = list.$el.find('form [name=dueDate]'); $dueDateInput.datepicker(); } }); // Event handling (function() { var list; $('#todo-lists-initialize-btn').click(function() { list = $('#todo-lists-demo-events') .lobiList({ init: function() { Lobibox.notify('default', { msg: 'init' }); }, beforeDestroy: function() { Lobibox.notify('default', { msg: 'beforeDestroy' }); }, afterDestroy: function() { Lobibox.notify('default', { msg: 'afterDestroy' }); }, beforeListAdd: function() { Lobibox.notify('default', { msg: 'beforeListAdd' }); }, afterListAdd: function() { Lobibox.notify('default', { msg: 'afterListAdd' }); }, beforeListRemove: function() { Lobibox.notify('default', { msg: 'beforeListRemove' }); }, afterListRemove: function() { Lobibox.notify('default', { msg: 'afterListRemove' }); }, beforeItemAdd: function() { Lobibox.notify('default', { msg: 'beforeItemAdd' }); }, afterItemAdd: function() { console.log(arguments); Lobibox.notify('default', { msg: 'afterItemAdd' }); }, beforeItemUpdate: function() { Lobibox.notify('default', { msg: 'beforeItemUpdate' }); }, afterItemUpdate: function() { console.log(arguments); Lobibox.notify('default', { msg: 'afterItemUpdate' }); }, beforeItemDelete: function() { Lobibox.notify('default', { msg: 'beforeItemDelete' }); }, afterItemDelete: function() { Lobibox.notify('default', { msg: 'afterItemDelete' }); }, beforeListDrop: function() { Lobibox.notify('default', { msg: 'beforeListDrop' }); }, afterListReorder: function() { Lobibox.notify('default', { msg: 'afterListReorder' }); }, beforeItemDrop: function() { Lobibox.notify('default', { msg: 'beforeItemDrop' }); }, afterItemReorder: function() { Lobibox.notify('default', { msg: 'afterItemReorder' }); }, afterMarkAsDone: function() { Lobibox.notify('default', { msg: 'afterMarkAsDone' }); }, afterMarkAsUndone: function() { Lobibox.notify('default', { msg: 'afterMarkAsUndone' }); }, styleChange: function(list, oldStyle, newStyle) { console.log(arguments); Lobibox.notify('default', { msg: 'styleChange: Old style - "' + oldStyle + '". New style - "' + newStyle + '"' }); }, titleChange: function(list, oldTitle, newTitle) { console.log(arguments); Lobibox.notify('default', { msg: 'titleChange: Old title - "' + oldTitle + '". New title - "' + newTitle + '"' }); }, lists: [{ title: 'Todo', defaultStyle: 'lobilist-info', items: [{ title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' }, { title: 'Periods pride', description: 'Accepted was mollis', done: true }, { title: 'Flags better burns pigeon', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank ' + 'treacherously darkling.' }, { title: 'Accepted was mollis', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank ' + 'treacherously darkling.', dueDate: '2015-02-02' } ] }] }) .data('lobiList'); }); $('#todo-lists-destroy-btn').click(function() { list.destroy(); }); })(); // Custom controls $('#todo-lists-demo-controls').lobiList({ lists: [{ title: 'Todo', defaultStyle: 'lobilist-info', controls: ['edit', 'styleChange'], items: [{ title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' }] }, { title: 'Disabled checkboxes', defaultStyle: 'lobilist-danger', controls: ['edit', 'add', 'remove'], useLobicheck: false, items: [{ title: 'Periods pride', description: 'Accepted was mollis', done: true }] }, { title: 'Controls disabled', controls: false, items: [{ title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. ' + 'Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage ' + 'celerities gales beams.' }] }, { title: 'No edit/remove', enableTodoRemove: false, enableTodoEdit: false, items: [{ title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. ' + 'Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage ' + 'celerities gales beams.' }] } ] }); // Disabled drag & drop $('#todo-lists-demo-sorting').lobiList({ sortable: false, lists: [{ title: 'Todo', defaultStyle: 'lobilist-info', controls: ['edit', 'styleChange'], items: [{ title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' }] }, { title: 'Controls disabled', controls: false, items: [{ title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage celerities gales beams.' }] } ] }); $('#actions-by-ajax').lobiList({ actions: { load: '../example1/load.json', insert: '../example1/insert.php', delete: '../example1/delete.php', update: '../example1/update.php' }, afterItemAdd: function() { console.log(arguments); } }); $('.datepicker').datepicker({ autoclose: true, todayHighlight: true }); $('.lobilist').perfectScrollbar(); }); });
274056675/springboot-openai-chatgpt
1,757
mng_web/src/styles/mixin.scss
@mixin clearfix { &:after { content: ""; display: table; clear: both; } } @mixin scrollBar { ::-webkit-scrollbar-track-piece { background-color: transparent; } ::-webkit-scrollbar { width: 7px; height: 7px; background-color: transparent; } ::-webkit-scrollbar-thumb { border-radius: 5px; background-color: hsla(220, 4%, 58%, .3); } } @mixin radius($width, $size, $color) { width: $width; height: $width; line-height: $width; border-radius: $width; text-align: center; border-width: $size; border-style: solid; border-color: $color; } @mixin relative { position: relative; width: 100%; height: 100%; } @mixin pct($pct) { width: #{$pct}; position: relative; margin: 0 auto; } @mixin triangle($width, $height, $color, $direction) { $width: $width/2; $color-border-style: $height solid $color; $transparent-border-style: $width solid transparent; height: 0; width: 0; @if $direction==up { border-bottom: $color-border-style; border-left: $transparent-border-style; border-right: $transparent-border-style; } @else if $direction==right { border-left: $color-border-style; border-top: $transparent-border-style; border-bottom: $transparent-border-style; } @else if $direction==down { border-top: $color-border-style; border-left: $transparent-border-style; border-right: $transparent-border-style; } @else if $direction==left { border-right: $color-border-style; border-top: $transparent-border-style; border-bottom: $transparent-border-style; } }
274056675/springboot-openai-chatgpt
3,051
mng_web/src/styles/login.scss
.login-container { display: flex; align-items: center; position: relative; width: 100%; height: 100%; margin: 0 auto; background-image: url("/img/bg/bg.jpeg"); background-size: 100% 100%; } .login-weaper { margin: 0 auto; width: 500px; box-shadow: -4px 5px 10px rgba(0, 0, 0, 0.4); .el-input-group__append { border: none; } } .login-left, .login-border { position: relative; min-height: 500px; align-items: center; display: flex; } .login-left { position: relative; border-top-left-radius: 5px; border-bottom-left-radius: 5px; justify-content: center; flex-direction: column; // background-color: #8b9aac; color: #fff; background-color: #fff; float: left; width: 50%; position: relative; border-right: 1px solid #f1f1f1; } .login-left .img { position: absolute; left: 0; top: 0; width: 100%; border-top-left-radius: 5px; border-bottom-left-radius: 5px; } .login-time { position: absolute; left: 25px; top: 25px; width: 100%; color: #fff; font-weight: 200; opacity: 0.9; font-size: 18px; overflow: hidden; } .login-left .title { text-align: center; color: #fff; font-weight: bold; font-size: 30px; letter-spacing: 2px; } .login-border { border-left: none; border-top-right-radius: 5px; border-bottom-right-radius: 5px; color: #fff; background-color: #fff; width: 100%; float: left; box-sizing: border-box; } .login-main { margin: 0 auto; width: 65%; box-sizing: border-box; } .login-main > h3 { margin-bottom: 20px; } .login-main > p { color: #76838f; } .login-title { color: #333; margin-bottom: 40px; font-weight: 500; font-size: 22px; text-align: center; letter-spacing: 4px; } .login-menu { margin-top: 40px; width: 100%; text-align: center; a { color: #999; font-size: 12px; margin: 0px 8px; } } .login-submit { width: 100%; height: 45px; border: 1px solid #409EFF; background: none; font-size: 18px; letter-spacing: 2px; font-weight: 300; color: #409EFF; cursor: pointer; margin-top: 30px; font-family: "neo"; transition: 0.25s; } .login-form { margin: 10px 0; i { color: #333; } .el-form-item__content { width: 100%; } .el-form-item { margin-bottom: 12px; } .el-input { input { padding-bottom: 10px; text-indent: 5px; background: transparent; border: none; border-radius: 0; color: #333; border-bottom: 1px solid rgb(235, 237, 242); } .el-input__prefix { i { padding: 0 5px; font-size: 16px !important; } } } } .login-code { display: flex; align-items: center; justify-content: space-around; margin: 0 0 0 10px; } .login-code-img { margin-top: 2px; width: 100px; height: 38px; background-color: #fdfdfd; border: 1px solid #f0f0f0; color: #333; font-size: 14px; font-weight: bold; letter-spacing: 5px; line-height: 38px; text-indent: 5px; text-align: center; cursor:pointer!important; }
27182812/ChatGLM-LLaMA-chinese-insturct
14,734
src/transformers/audio_utils.py
# coding=utf-8 # Copyright 2023 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. """ Audio processing functions to extract feature from a raw audio. Should all be in numpy to support all frameworks, and remmove unecessary dependencies. """ import math import warnings from typing import Optional import numpy as np from numpy.fft import fft def hertz_to_mel(freq: float, mel_scale: str = "htk") -> float: """Convert Hertz to Mels. Args: freqs (`float`): Frequencies in Hertz mel_scale (`str`, *optional*, defaults to `"htk"`): Scale to use, `htk` or `slaney`. Returns: mels (`float`): Frequency in Mels """ if mel_scale not in ["slaney", "htk"]: raise ValueError('mel_scale should be one of "htk" or "slaney".') if mel_scale == "htk": return 2595.0 * math.log10(1.0 + (freq / 700.0)) # Fill in the linear part frequency_min = 0.0 f_sp = 200.0 / 3 mels = (freq - frequency_min) / f_sp # Fill in the log-scale part min_log_hertz = 1000.0 min_log_mel = (min_log_hertz - frequency_min) / f_sp logstep = math.log(6.4) / 27.0 if freq >= min_log_hertz: mels = min_log_mel + math.log(freq / min_log_hertz) / logstep return mels def mel_to_hertz(mels: np.array, mel_scale: str = "htk") -> np.array: """Convert mel bin numbers to frequencies. Args: mels (`np.array`): Mel frequencies mel_scale (`str`, *optional*, `"htk"`): Scale to use: `htk` or `slaney`. Returns: freqs (`np.array`): Mels converted to Hertz """ if mel_scale not in ["slaney", "htk"]: raise ValueError('mel_scale should be one of "htk" or "slaney".') if mel_scale == "htk": return 700.0 * (10.0 ** (mels / 2595.0) - 1.0) # Fill in the linear scale frequency_min = 0.0 f_sp = 200.0 / 3 freqs = frequency_min + f_sp * mels # And now the nonlinear scale min_log_hertz = 1000.0 min_log_mel = (min_log_hertz - frequency_min) / f_sp logstep = math.log(6.4) / 27.0 log_t = mels >= min_log_mel freqs[log_t] = min_log_hertz * np.exp(logstep * (mels[log_t] - min_log_mel)) return freqs def _create_triangular_filterbank( all_freqs: np.array, f_pts: np.array, ) -> np.array: """Create a triangular filter bank. Args: all_freqs (`np.array` of shape (`nb_frequency_bins`, )): Discrete frequencies used when the STFT was computed. f_pts (`np.array`, of shape (`nb_mel_filters`, )): Coordinates of the middle points of the triangular filters to create. Returns: fb (np.array): The filter bank of size (`nb_frequency_bins`, `nb_mel_filters`). """ # Adapted from Librosa # calculate the difference between each filter mid point and each stft freq point in hertz f_diff = f_pts[1:] - f_pts[:-1] # (n_filter + 1) slopes = np.expand_dims(f_pts, 0) - np.expand_dims(all_freqs, 1) # (nb_frequency_bins, n_filter + 2) # create overlapping triangles zero = np.zeros(1) down_slopes = (-1.0 * slopes[:, :-2]) / f_diff[:-1] # (nb_frequency_bins, n_filter) up_slopes = slopes[:, 2:] / f_diff[1:] # (nb_frequency_bins, n_filter) fb = np.maximum(zero, np.minimum(down_slopes, up_slopes)) return fb def get_mel_filter_banks( nb_frequency_bins: int, nb_mel_filters: int, frequency_min: float, frequency_max: float, sample_rate: int, norm: Optional[str] = None, mel_scale: str = "htk", ) -> np.array: """ Create a frequency bin conversion matrix used to obtain the Mel Spectrogram. This is called a *mel filter bank*, and various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency. This code is heavily inspired from the *torchaudio* implementation, see [here](https://pytorch.org/audio/stable/transforms.html) for more details. Tips: - Different banks of Mel filters were introduced in the litterature. The following variation are supported: - MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHertz and a speech bandwidth of `[0, 4600]` Hertz - MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a speech bandwidth `[0, 8000]` Hertz (sampling rate ≥ 16 kHertz). - MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate of 16 kHertz, and speech bandwidth [133, 6854] Hertz. This version also includes an area normalization. - HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes sampling rate of 12.5 kHertz and speech bandwidth [0, 6250] Hertz - The default parameters of `torchaudio`'s mel filterbanks implement the `"htk"` filers while `torchlibrosa` uses the `"slaney"` implementation. Args: nb_frequency_bins (`int`): Number of frequencies used to compute the spectrogram (should be the same as in `stft`). nb_mel_filters (`int`): Number of Mel filers to generate. frequency_min (`float`): Minimum frequency of interest(Hertz). frequency_max (`float`): Maximum frequency of interest(Hertz). sample_rate (`int`): Sample rate of the audio waveform. norm (`str`, *optional*): If "slaney", divide the triangular Mel weights by the width of the mel band (area normalization). mel_scale (`str`, *optional*, defaults to `"htk"`): Scale to use: `"htk"` or `"slaney"`. Returns: `np.ndarray`: Triangular filter banks (fb matrix) of shape (`nb_frequency_bins`, `nb_mel_filters`). This matrix is a projection matrix to go from a spectrogram to a Mel Spectrogram. """ if norm is not None and norm != "slaney": raise ValueError('norm must be one of None or "slaney"') # freqency bins all_freqs = np.linspace(0, sample_rate // 2, nb_frequency_bins) # Compute mim and max frequencies in mel scale m_min = hertz_to_mel(frequency_min, mel_scale=mel_scale) m_max = hertz_to_mel(frequency_max, mel_scale=mel_scale) # create the centers of the triangular mel filters. m_pts = np.linspace(m_min, m_max, nb_mel_filters + 2) f_pts = mel_to_hertz(m_pts, mel_scale=mel_scale) # create the filterbank filterbank = _create_triangular_filterbank(all_freqs, f_pts) if norm is not None and norm == "slaney": # Slaney-style mel is scaled to be approx constant energy per channel enorm = 2.0 / (f_pts[2 : nb_mel_filters + 2] - f_pts[:nb_mel_filters]) filterbank *= np.expand_dims(enorm, 0) if (filterbank.max(axis=0) == 0.0).any(): warnings.warn( "At least one mel filterbank has all zero values. " f"The value for `nb_mel_filters` ({nb_mel_filters}) may be set too high. " f"Or, the value for `nb_frequency_bins` ({nb_frequency_bins}) may be set too low." ) return filterbank def power_to_db(mel_spectrogram, top_db=None, a_min=1e-10, ref=1.0): """ Convert a mel spectrogram from power to db scale, this function is the numpy implementation of librosa.power_to_lb. It computes `10 * log10(mel_spectrogram / ref)`, using basic log properties for stability. Tips: - The motivation behind applying the log function on the mel spectrogram is that humans do not hear loudness on a linear scale. Generally to double the percieved volume of a sound we need to put 8 times as much energy into it. - This means that large variations in energy may not sound all that different if the sound is loud to begin with. This compression operation makes the mel features match more closely what humans actually hear. Args: mel_spectrogram (`np.array`): Input mel spectrogram. top_db (`int`, *optional*): The maximum decibel value. a_min (`int`, *optional*, default to 1e-10): Minimum value to use when cliping the mel spectrogram. ref (`float`, *optional*, default to 1.0): Maximum reference value used to scale the mel_spectrogram. """ log_spec = 10 * np.log10(np.clip(mel_spectrogram, a_min=a_min, a_max=None)) log_spec -= 10.0 * np.log10(np.maximum(a_min, ref)) if top_db is not None: if top_db < 0: raise ValueError("top_db must be non-negative") log_spec = np.clip(log_spec, min=np.maximum(log_spec) - top_db, max=np.inf) return log_spec # TODO @ArthurZucker: This method does not support batching yet as we are mainly focus on inference. def fram_wave(waveform: np.array, hop_length: int = 160, fft_window_size: int = 400, center: bool = True): """ In order to compute the short time fourier transform, the waveform needs to be split in overlapping windowed segments called `frames`. The window length (window_length) defines how much of the signal is contained in each frame, while the hop length defines the step between the beginning of each new frame. Args: waveform (`np.array` of shape `(sample_length,)`): The raw waveform which will be split into smaller chunks. hop_length (`int`, *optional*, defaults to 160): Step between each window of the waveform. fft_window_size (`int`, *optional*, defaults to 400): Defines the size of the window. center (`bool`, defaults to `True`): Whether or not to center each frame around the middle of the frame. Centering is done by reflecting the waveform on the left and on the right. Return: framed_waveform (`np.array` of shape `(waveform.shape // hop_length , fft_window_size)`): The framed waveforms that can be fed to `np.fft`. """ frames = [] for i in range(0, waveform.shape[0] + 1, hop_length): if center: half_window = (fft_window_size - 1) // 2 + 1 start = i - half_window if i > half_window else 0 end = i + half_window if i < waveform.shape[0] - half_window else waveform.shape[0] frame = waveform[start:end] if start == 0: padd_width = (-i + half_window, 0) frame = np.pad(frame, pad_width=padd_width, mode="reflect") elif end == waveform.shape[0]: padd_width = (0, (i - waveform.shape[0] + half_window)) frame = np.pad(frame, pad_width=padd_width, mode="reflect") else: frame = waveform[i : i + fft_window_size] frame_width = frame.shape[0] if frame_width < waveform.shape[0]: frame = np.lib.pad( frame, pad_width=(0, fft_window_size - frame_width), mode="constant", constant_values=0 ) frames.append(frame) frames = np.stack(frames, 0) return frames # TODO @ArthurZucker: This method does not support batching yet as we are mainly focus on inference. def stft(frames: np.array, windowing_function: np.array, fft_window_size: int = None): """ Calculates the complex Short-Time Fourier Transform (STFT) of the given framed signal. Should give the same results as `torch.stft`. Args: frames (`np.array` of dimension `(num_frames, fft_window_size)`): A framed audio signal obtained using `audio_utils.fram_wav`. windowing_function (`np.array` of dimension `(nb_frequency_bins, nb_mel_filters)`: A array reprensenting the function that will be used to reduces the amplitude of the discontinuities at the boundaries of each frame when computing the STFT. Each frame will be multiplied by the windowing_function. For more information on the discontinuities, called *Spectral leakage*, refer to [this tutorial]https://download.ni.com/evaluation/pxi/Understanding%20FFTs%20and%20Windowing.pdf fft_window_size (`int`, *optional*): Size of the window om which the Fourier transform is applied. This controls the frequency resolution of the spectrogram. 400 means that the fourrier transform is computed on windows of 400 samples. The number of frequency bins (`nb_frequency_bins`) used to divide the window into equal strips is equal to `(1+fft_window_size)//2`. An increase of the fft_window_size slows the calculus time proportionnally. Example: ```python >>> from transformers.audio_utils import stft, fram_wave >>> import numpy as np >>> audio = np.random.rand(50) >>> fft_window_size = 10 >>> hop_length = 2 >>> framed_audio = fram_wave(audio, hop_length, fft_window_size) >>> spectrogram = stft(framed_audio, np.hanning(fft_window_size + 1)) ``` Returns: spectrogram (`np.ndarray`): A spectrogram of shape `(num_frames, nb_frequency_bins)` obtained using the STFT algorithm """ frame_size = frames.shape[1] if fft_window_size is None: fft_window_size = frame_size if fft_window_size < frame_size: raise ValueError("FFT size must greater or equal the frame size") # number of FFT bins to store nb_frequency_bins = (fft_window_size >> 1) + 1 spectrogram = np.empty((len(frames), nb_frequency_bins), dtype=np.complex64) fft_signal = np.zeros(fft_window_size) for f, frame in enumerate(frames): if windowing_function is not None: np.multiply(frame, windowing_function, out=fft_signal[:frame_size]) else: fft_signal[:frame_size] = frame spectrogram[f] = fft(fft_signal, axis=0)[:nb_frequency_bins] return spectrogram.T
27182812/ChatGLM-LLaMA-chinese-insturct
26,395
src/transformers/feature_extraction_utils.py
# coding=utf-8 # Copyright 2021 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. """ Feature extraction saving/loading class for common feature extractors. """ import copy import json import os from collections import UserDict from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union import numpy as np from .dynamic_module_utils import custom_object_save from .utils import ( FEATURE_EXTRACTOR_NAME, PushToHubMixin, TensorType, cached_file, copy_func, download_url, is_flax_available, is_jax_tensor, is_numpy_array, is_offline_mode, is_remote_url, is_tf_available, is_torch_available, is_torch_device, is_torch_dtype, logging, requires_backends, ) if TYPE_CHECKING: if is_torch_available(): import torch # noqa logger = logging.get_logger(__name__) PreTrainedFeatureExtractor = Union["SequenceFeatureExtractor"] # noqa: F821 class BatchFeature(UserDict): r""" Holds the output of the [`~SequenceFeatureExtractor.pad`] and feature extractor specific `__call__` methods. This class is derived from a python dictionary and can be used as a dictionary. Args: data (`dict`): Dictionary of lists/arrays/tensors returned by the __call__/pad methods ('input_values', 'attention_mask', etc.). tensor_type (`Union[None, str, TensorType]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at initialization. """ def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None): super().__init__(data) self.convert_to_tensors(tensor_type=tensor_type) def __getitem__(self, item: str) -> Union[Any]: """ If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask', etc.). """ if isinstance(item, str): return self.data[item] else: raise KeyError("Indexing with integers is not available when using Python based feature extractors") def __getattr__(self, item: str): try: return self.data[item] except KeyError: raise AttributeError def __getstate__(self): return {"data": self.data} def __setstate__(self, state): if "data" in state: self.data = state["data"] # Copied from transformers.tokenization_utils_base.BatchEncoding.keys def keys(self): return self.data.keys() # Copied from transformers.tokenization_utils_base.BatchEncoding.values def values(self): return self.data.values() # Copied from transformers.tokenization_utils_base.BatchEncoding.items def items(self): return self.data.items() def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None): """ Convert the inner content to tensors. Args: tensor_type (`str` or [`~utils.TensorType`], *optional*): The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If `None`, no modification is done. """ if tensor_type is None: return self # Convert to TensorType if not isinstance(tensor_type, TensorType): tensor_type = TensorType(tensor_type) # Get a function reference for the correct framework if tensor_type == TensorType.TENSORFLOW: if not is_tf_available(): raise ImportError( "Unable to convert output to TensorFlow tensors format, TensorFlow is not installed." ) import tensorflow as tf as_tensor = tf.constant is_tensor = tf.is_tensor elif tensor_type == TensorType.PYTORCH: if not is_torch_available(): raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.") import torch # noqa def as_tensor(value): if isinstance(value, (list, tuple)) and len(value) > 0 and isinstance(value[0], np.ndarray): value = np.array(value) return torch.tensor(value) is_tensor = torch.is_tensor elif tensor_type == TensorType.JAX: if not is_flax_available(): raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed.") import jax.numpy as jnp # noqa: F811 as_tensor = jnp.array is_tensor = is_jax_tensor else: as_tensor = np.asarray is_tensor = is_numpy_array # Do the tensor conversion in batch for key, value in self.items(): try: if not is_tensor(value): tensor = as_tensor(value) self[key] = tensor except: # noqa E722 if key == "overflowing_values": raise ValueError("Unable to create tensor returning overflowing values of different lengths. ") raise ValueError( "Unable to create tensor, you should probably activate padding " "with 'padding=True' to have batched tensors with the same length." ) return self def to(self, *args, **kwargs) -> "BatchFeature": """ Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in different `dtypes` and sending the `BatchFeature` to a different `device`. Args: args (`Tuple`): Will be passed to the `to(...)` function of the tensors. kwargs (`Dict`, *optional*): Will be passed to the `to(...)` function of the tensors. Returns: [`BatchFeature`]: The same instance after modification. """ requires_backends(self, ["torch"]) import torch # noqa new_data = {} device = kwargs.get("device") # Check if the args are a device or a dtype if device is None and len(args) > 0: # device should be always the first argument arg = args[0] if is_torch_dtype(arg): # The first argument is a dtype pass elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int): device = arg else: # it's something else raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.") # We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor` for k, v in self.items(): # check if v is a floating point if torch.is_floating_point(v): # cast and send to device new_data[k] = v.to(*args, **kwargs) elif device is not None: new_data[k] = v.to(device=device) else: new_data[k] = v self.data = new_data return self class FeatureExtractionMixin(PushToHubMixin): """ This is a feature extraction mixin used to provide saving/loading functionality for sequential and image feature extractors. """ _auto_class = None def __init__(self, **kwargs): """Set elements of `kwargs` as attributes.""" # Pop "processor_class" as it should be saved as private attribute self._processor_class = kwargs.pop("processor_class", None) # Additional attributes without default values for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err def _set_processor_class(self, processor_class: str): """Sets processor class as an attribute.""" self._processor_class = processor_class @classmethod def from_pretrained( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> PreTrainedFeatureExtractor: r""" Instantiate a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a feature extractor, *e.g.* a derived class of [`SequenceFeatureExtractor`]. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a feature extractor file saved using the [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved feature extractor JSON *file*, e.g., `./my_model_directory/preprocessor_config.json`. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model feature extractor should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the feature extractor files and override the cached versions if they exist. resume_download (`bool`, *optional*, defaults to `False`): Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. use_auth_token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". </Tip> return_unused_kwargs (`bool`, *optional*, defaults to `False`): If `False`, then this function returns just the final feature extractor object. If `True`, then this functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored. kwargs (`Dict[str, Any]`, *optional*): The values in kwargs of any keys which are feature extractor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is controlled by the `return_unused_kwargs` keyword parameter. Returns: A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]. Examples: ```python # We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a # derived class: *Wav2Vec2FeatureExtractor* feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base-960h" ) # Download feature_extraction_config from huggingface.co and cache. feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "./test/saved_model/" ) # E.g. feature_extractor (or model) was saved using *save_pretrained('./test/saved_model/')* feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("./test/saved_model/preprocessor_config.json") feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False ) assert feature_extractor.return_attention_mask is False feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True ) assert feature_extractor.return_attention_mask is False assert unused_kwargs == {"foo": False} ```""" feature_extractor_dict, kwargs = cls.get_feature_extractor_dict(pretrained_model_name_or_path, **kwargs) return cls.from_dict(feature_extractor_dict, **kwargs) def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): """ Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method. Args: save_directory (`str` or `os.PathLike`): Directory where the feature extractor JSON file will be saved (will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs: Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = self._create_repo(repo_id, **kwargs) files_timestamps = self._get_files_timestamps(save_directory) # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self) # If we save using the predefined names, we can load using `from_pretrained` output_feature_extractor_file = os.path.join(save_directory, FEATURE_EXTRACTOR_NAME) self.to_json_file(output_feature_extractor_file) logger.info(f"Feature extractor saved in {output_feature_extractor_file}") if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("use_auth_token"), ) return [output_feature_extractor_file] @classmethod def get_feature_extractor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] using `from_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): The identifier of the pre-trained checkpoint from which we want the dictionary of parameters. Returns: `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the feature extractor object. """ cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) resume_download = kwargs.pop("resume_download", False) proxies = kwargs.pop("proxies", None) use_auth_token = kwargs.pop("use_auth_token", None) local_files_only = kwargs.pop("local_files_only", False) revision = kwargs.pop("revision", None) from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) user_agent = {"file_type": "feature extractor", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isdir(pretrained_model_name_or_path): feature_extractor_file = os.path.join(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME) if os.path.isfile(pretrained_model_name_or_path): resolved_feature_extractor_file = pretrained_model_name_or_path is_local = True elif is_remote_url(pretrained_model_name_or_path): feature_extractor_file = pretrained_model_name_or_path resolved_feature_extractor_file = download_url(pretrained_model_name_or_path) else: feature_extractor_file = FEATURE_EXTRACTOR_NAME try: # Load from local folder or from cache or download from model Hub and cache resolved_feature_extractor_file = cached_file( pretrained_model_name_or_path, feature_extractor_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, local_files_only=local_files_only, use_auth_token=use_auth_token, user_agent=user_agent, revision=revision, ) except EnvironmentError: # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to # the original exception. raise except Exception: # For any other exception, we throw a generic error. raise EnvironmentError( f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load" " it from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {FEATURE_EXTRACTOR_NAME} file" ) try: # Load feature_extractor dict with open(resolved_feature_extractor_file, "r", encoding="utf-8") as reader: text = reader.read() feature_extractor_dict = json.loads(text) except json.JSONDecodeError: raise EnvironmentError( f"It looks like the config file at '{resolved_feature_extractor_file}' is not a valid JSON file." ) if is_local: logger.info(f"loading configuration file {resolved_feature_extractor_file}") else: logger.info( f"loading configuration file {feature_extractor_file} from cache at {resolved_feature_extractor_file}" ) return feature_extractor_dict, kwargs @classmethod def from_dict(cls, feature_extractor_dict: Dict[str, Any], **kwargs) -> PreTrainedFeatureExtractor: """ Instantiates a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a Python dictionary of parameters. Args: feature_extractor_dict (`Dict[str, Any]`): Dictionary that will be used to instantiate the feature extractor object. Such a dictionary can be retrieved from a pretrained checkpoint by leveraging the [`~feature_extraction_utils.FeatureExtractionMixin.to_dict`] method. kwargs (`Dict[str, Any]`): Additional parameters from which to initialize the feature extractor object. Returns: [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature extractor object instantiated from those parameters. """ return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) feature_extractor = cls(**feature_extractor_dict) # Update feature_extractor with kwargs if needed to_remove = [] for key, value in kwargs.items(): if hasattr(feature_extractor, key): setattr(feature_extractor, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) logger.info(f"Feature extractor {feature_extractor}") if return_unused_kwargs: return feature_extractor, kwargs else: return feature_extractor def to_dict(self) -> Dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this feature extractor instance. """ output = copy.deepcopy(self.__dict__) output["feature_extractor_type"] = self.__class__.__name__ return output @classmethod def from_json_file(cls, json_file: Union[str, os.PathLike]) -> PreTrainedFeatureExtractor: """ Instantiates a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] from the path to a JSON file of parameters. Args: json_file (`str` or `os.PathLike`): Path to the JSON file containing the parameters. Returns: A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature_extractor object instantiated from that JSON file. """ with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() feature_extractor_dict = json.loads(text) return cls(**feature_extractor_dict) def to_json_string(self) -> str: """ Serializes this instance to a JSON string. Returns: `str`: String containing all the attributes that make up this feature_extractor instance in JSON format. """ dictionary = self.to_dict() for key, value in dictionary.items(): if isinstance(value, np.ndarray): dictionary[key] = value.tolist() # make sure private name "_processor_class" is correctly # saved as "processor_class" _processor_class = dictionary.pop("_processor_class", None) if _processor_class is not None: dictionary["processor_class"] = _processor_class return json.dumps(dictionary, indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path: Union[str, os.PathLike]): """ Save this instance to a JSON file. Args: json_file_path (`str` or `os.PathLike`): Path to the JSON file in which this feature_extractor instance's parameters will be saved. """ with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) def __repr__(self): return f"{self.__class__.__name__} {self.to_json_string()}" @classmethod def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"): """ Register this class with a given auto class. This should only be used for custom feature extractors as the ones in the library are already mapped with `AutoFeatureExtractor`. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. </Tip> Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoFeatureExtractor"`): The auto class to register this new feature extractor with. """ if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f"{auto_class} is not a valid auto class.") cls._auto_class = auto_class FeatureExtractionMixin.push_to_hub = copy_func(FeatureExtractionMixin.push_to_hub) if FeatureExtractionMixin.push_to_hub.__doc__ is not None: FeatureExtractionMixin.push_to_hub.__doc__ = FeatureExtractionMixin.push_to_hub.__doc__.format( object="feature extractor", object_class="AutoFeatureExtractor", object_files="feature extractor file" )
274056675/springboot-openai-chatgpt
1,758
mng_web/src/styles/top.scss
.avue-top { padding: 0 20px; position: relative; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15); color: rgba(0, 0, 0, .65); font-size: 28px; height: 64px; box-sizing: border-box; white-space: nowrap; .el-menu-item{ i,span{ font-size: 13px; } } } .avue-breadcrumb { height: 100%; i{ font-size: 30px !important; } &--active { transform:rotate(90deg); } } .top-menu { box-sizing: border-box; .el-menu-item { padding: 0 10px; border:none !important; } } .top-search { line-height: 64px; position: absolute !important; left: 20px; top:0; width: 400px !important; .el-input__inner { font-size: 13px; border: none; background-color: transparent; } } .top-bar__img { margin: 0 8px 0 5px; padding: 2px; width: 30px; height: 30px; border-radius: 100%; box-sizing: border-box; border: 1px solid #eee; vertical-align: middle; } .top-bar__left, .top-bar__right { height: 64px; position: absolute; top: 0; i{ line-height: 64px; } } .top-bar__left { left: 20px; } .top-bar__right { right: 20px; display: flex; align-items: center; } .top-bar__item { position: relative; display: inline-block; height: 64px; margin:0 10px; font-size: 16px; &--show { display: inline-block !important; } .el-badge__content.is-fixed{ top:12px; right: 5px; } } .top-bar__title { height: 100%; padding:0 40px; box-sizing: border-box; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: inherit; font-weight: 400; }
274056675/springboot-openai-chatgpt
1,425
mng_web/src/styles/element-ui.scss
.el-dropdown-menu__item { font-size: 12px !important; line-height: 28px !important; } .el-card.is-always-shadow { box-shadow: none; border: none !important; } .el-scrollbar__view { height: 100%; } .el-menu--horizontal { border-bottom: none !important; } .el-menu { border-right: none !important; } .el-menu--display, .el-menu--display+.el-submenu__icon-arrow { display: none; } .el-message__icon, .el-message__content { display: inline-block; } .el-date-editor .el-range-input, .el-date-editor .el-range-separator { height: auto; overflow: hidden; } .el-dialog__wrapper { z-index: 2048; } .el-scrollbar__wrap { overflow-x: hidden; } .el-col { margin-bottom: 8px; } .el-main { padding: 0 !important; } .el-dropdown-menu__item--divided:before, .el-menu, .el-menu--horizontal>.el-menu-item:not(.is-disabled):focus, .el-menu--horizontal>.el-menu-item:not(.is-disabled):hover, .el-menu--horizontal>.el-submenu .el-submenu__title:hover { background-color:transparent; } .el-dropdown-menu__item--divided:before, .el-menu, .el-menu--horizontal>.el-menu-item:not(.is-disabled):focus, .el-menu--horizontal>.el-menu-item:not(.is-disabled):hover, .el-menu--horizontal>.el-submenu .el-submenu__title:hover{ background-color: transparent !important; } .el-card__header { padding: 6px 18px !important; } .el-card__body { //padding: 16px !important; }
274056675/springboot-openai-chatgpt
2,346
mng_web/src/styles/tags.scss
.avue-tags { user-select: none; position: relative; padding: 0 10px; margin-bottom: 10px; box-sizing: border-box; overflow: hidden; border-top: 1px solid #f6f6f6; background-color: #fff; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, .05); .el-tabs--card>.el-tabs__header { margin: 0; } .el-tabs--card>.el-tabs__header .el-tabs__nav, .el-tabs--card>.el-tabs__header .el-tabs__item, .el-tabs--card>.el-tabs__header { border: none; } .el-tabs--card>.el-tabs__header .el-tabs__item:first-child { border-left-width: 1px } .el-tabs--card>.el-tabs__header .el-tabs__item { margin: 0 3px; height: 40px; line-height:40px; font-size: 13px; font-weight: normal; color: #ccc; &.is-active { color: #409EFF; border-bottom: 3px solid #409EFF; } } .el-tabs__nav-prev, .el-tabs__nav-next { width: 20px; line-height: 34px; font-size: 18x; text-align: center; } &__box { position: relative; box-sizing: border-box; padding-right: 106px; width: 100%; &--close { .el-tabs__item { &:first-child { padding: 0 20px !important; .el-icon-close { display: none; } } } } } &__contentmenu{ position: fixed; width:120px; background-color: #fff; z-index:1024; border-radius: 5px; box-shadow: 1px 2px 10px #ccc; .item{ cursor: pointer; font-size: 14px; padding: 8px 20px 8px 15px; color: #606266; &:first-child{ border-top-left-radius: 5px; border-top-right-radius: 5px; } &:last-child{ border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } &:hover{ background-color: #409EFF; color:#fff; } } } &__menu { position: absolute !important; top: 3px; right: 0; padding: 1px 0 0 15px; box-sizing: border-box; } }
2833844911/gurs
5,655
cBezier.py
''' author: cbb 这个库基于贝塞尔曲线实现模拟人手动滑动的轨迹 可以用于selenium轨迹的模拟,或者生成轨迹数组用于js加密通过网站服务器后端分控检测 QQ群 134064772 里面的人说话好听,个个都是人才 ''' import numpy as np import math import random class bezierTrajectory: def _bztsg(self, dataTrajectory): lengthOfdata = len(dataTrajectory) def staer(x): t = ((x - dataTrajectory[0][0]) / (dataTrajectory[-1][0] - dataTrajectory[0][0])) y = np.array([0, 0], dtype=np.float64) for s in range(len(dataTrajectory)): y += dataTrajectory[s] * ((math.factorial(lengthOfdata - 1) / ( math.factorial(s) * math.factorial(lengthOfdata - 1 - s))) * math.pow(t, s) * math.pow( (1 - t), lengthOfdata - 1 - s)) return y[1] return staer def _type(self, type, x, numberList): numberListre = [] pin = (x[1] - x[0]) / numberList if type == 0: for i in range(numberList): numberListre.append(i * pin) if pin >= 0: numberListre = numberListre[::-1] elif type == 1: for i in range(numberList): numberListre.append(1 * ((i * pin) ** 2)) numberListre = numberListre[::-1] elif type == 2: for i in range(numberList): numberListre.append(1 * ((i * pin - x[1]) ** 2)) elif type == 3: dataTrajectory = [np.array([0,0]), np.array([(x[1]-x[0])*0.8, (x[1]-x[0])*0.6]), np.array([x[1]-x[0], 0])] fun = self._bztsg(dataTrajectory) numberListre = [0] for i in range(1,numberList): numberListre.append(fun(i * pin) + numberListre[-1]) if pin >= 0: numberListre = numberListre[::-1] numberListre = np.abs(np.array(numberListre) - max(numberListre)) biaoNumberList = ((numberListre - numberListre[numberListre.argmin()]) / ( numberListre[numberListre.argmax()] - numberListre[numberListre.argmin()])) * (x[1] - x[0]) + x[0] biaoNumberList[0] = x[0] biaoNumberList[-1] = x[1] return biaoNumberList def getFun(self, s): ''' :param s: 传入P点 :return: 返回公式 ''' dataTrajectory = [] for i in s: dataTrajectory.append(np.array(i)) return self._bztsg(dataTrajectory) def simulation(self, start, end, le=1, deviation=0, bias=0.5): ''' :param start:开始点的坐标 如 start = [0, 0] :param end:结束点的坐标 如 end = [100, 100] :param le:几阶贝塞尔曲线,越大越复杂 如 le = 4 :param deviation:轨迹上下波动的范围 如 deviation = 10 :param bias:波动范围的分布位置 如 bias = 0.5 :return:返回一个字典equation对应该曲线的方程,P对应贝塞尔曲线的影响点 ''' start = np.array(start) end = np.array(end) cbb = [] if le != 1: e = (1 - bias) / (le - 1) cbb = [[bias + e * i, bias + e * (i + 1)] for i in range(le - 1)] dataTrajectoryList = [start] t = random.choice([-1, 1]) w = 0 for i in cbb: px1 = start[0] + (end[0] - start[0]) * (random.random() * (i[1] - i[0]) + (i[0])) p = np.array([px1, self._bztsg([start, end])(px1) + t * deviation]) dataTrajectoryList.append(p) w += 1 if w >= 2: w = 0 t = -1 * t dataTrajectoryList.append(end) return {"equation": self._bztsg(dataTrajectoryList), "P": np.array(dataTrajectoryList)} def trackArray(self, start, end, numberList, le=1, deviation=0, bias=0.5, type=0, cbb=0, yhh=10): ''' :param start:开始点的坐标 如 start = [0, 0] :param end:结束点的坐标 如 end = [100, 100] :param numberList:返回的数组的轨迹点的数量 numberList = 150 :param le:几阶贝塞尔曲线,越大越复杂 如 le = 4 :param deviation:轨迹上下波动的范围 如 deviation = 10 :param bias:波动范围的分布位置 如 bias = 0.5 :param type:0表示均速滑动,1表示先慢后快,2表示先快后慢,3表示先慢中间快后慢 如 type = 1 :param cbb:在终点来回摆动的次数 :param yhh:在终点来回摆动的范围 :return:返回一个字典trackArray对应轨迹数组,P对应贝塞尔曲线的影响点 ''' s = [] fun = self.simulation(start, end, le, deviation, bias) w = fun['P'] fun = fun["equation"] if cbb != 0: numberListOfcbb = round(numberList*0.2/(cbb+1)) numberList -= (numberListOfcbb*(cbb+1)) xTrackArray = self._type(type, [start[0], end[0]], numberList) for i in xTrackArray: s.append([i, fun(i)]) dq = yhh/cbb kg = 0 ends = np.copy(end) for i in range(cbb): if kg == 0: d = np.array([end[0] + (yhh-dq*i), ((end[1]-start[1])/(end[0]-start[0]))*(end[0]+(yhh-dq*i)) +(end[1]-((end[1]-start[1])/(end[0]-start[0]))*end[0]) ]) kg = 1 else: d = np.array([end[0] - (yhh - dq * i), ((end[1]-start[1])/(end[0]-start[0]))*(end[0]-(yhh-dq*i)) +(end[1]-((end[1]-start[1])/(end[0]-start[0]))*end[0]) ]) kg = 0 print(d) y = self.trackArray(ends, d, numberListOfcbb, le=2, deviation=0, bias=0.5, type=0, cbb=0, yhh=10) s += list(y['trackArray']) ends = d y = self.trackArray(ends, end, numberListOfcbb, le=2, deviation=0, bias=0.5, type=0, cbb=0, yhh=10) s += list(y['trackArray']) else: xTrackArray = self._type(type, [start[0], end[0]], numberList) for i in xTrackArray: s.append([i, fun(i)]) return {"trackArray": np.array(s), "P": w}
233zzh/TitanDataOperationSystem
16,966
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/js/lobilist.min.js
$(function(){var LIST_COUNTER=0,List=function($lobiList,options){this.$lobiList=$lobiList,this.$options=options,this.$globalOptions=$lobiList.$options,this.$items={},this._init()};List.prototype={$lobiList:null,$el:null,$elWrapper:null,$options:{},$items:{},$globalOptions:{},$ul:null,$header:null,$title:null,$form:null,$footer:null,$body:null,eventsSuppressed:!1,_init:function(){var me=this;me.suppressEvents(),me.$options.id||(me.$options.id="lobilist-list-"+LIST_COUNTER++);var $wrapper=$('<div class="lobilist-wrapper"></div>'),$div=$('<div id="'+me.$options.id+'" class="lobilist"></div>').appendTo($wrapper);me.$options.defaultStyle&&$div.addClass(me.$options.defaultStyle),me.$el=$div,me.$elWrapper=$wrapper,me.$header=me._createHeader(),me.$title=me._createTitle(),me.$body=me._createBody(),me.$ul=me._createList(),me.$options.items&&me._createItems(me.$options.items),me.$form=me._createForm(),me.$body.append(me.$ul,me.$form),me.$footer=me._createFooter(),me.$globalOptions.sortable&&me._enableSorting(),me.resumeEvents()},addItem:function(item,errorCallback){var me=this;return me._triggerEvent("beforeItemAdd",[me,item])===!1?me:(item=me._processItemData(item),me.$globalOptions.actions.insert?$.ajax(me.$globalOptions.actions.insert,{data:item,method:"POST"}).done(function(res){res.success?(item.id=res.id,me._addItemToList(item)):errorCallback&&"function"==typeof errorCallback&&errorCallback(res)}):(item.id=me.$lobiList.getNextId(),me._addItemToList(item)),me)},updateItem:function(item,errorCallback){var me=this;return me._triggerEvent("beforeItemUpdate",[me,item])===!1?me:(me.$globalOptions.actions.update?$.ajax(me.$globalOptions.actions.update,{data:item,method:"POST"}).done(function(res){res.success?me._updateItemInList(item):errorCallback&&"function"==typeof errorCallback&&errorCallback(res)}):me._updateItemInList(item),me)},deleteItem:function(item,errorCallback){var me=this;return me._triggerEvent("beforeItemDelete",[me,item])===!1?me:me.$globalOptions.actions["delete"]?me._sendAjax(me.$globalOptions.actions["delete"],{data:item,method:"POST"}).done(function(res){res.success?me._removeItemFromList(item):errorCallback&&"function"==typeof errorCallback&&errorCallback(res)}):(me._removeItemFromList(item),me)},saveOrUpdateItem:function(item,errorCallback){var me=this;return item.id?me.updateItem(item,errorCallback):me.addItem(item,errorCallback),me},startTitleEditing:function(){var me=this,input=me._createInput();return me.$title.attr("data-old-title",me.$title.html()),input.val(me.$title.html()),input.insertAfter(me.$title),me.$title.addClass("hide"),me.$header.addClass("title-editing"),input[0].focus(),input[0].select(),me},finishTitleEditing:function(){var me=this,$input=me.$header.find("input"),oldTitle=me.$title.attr("data-old-title");return me.$title.html($input.val()).removeClass("hide").removeAttr("data-old-title"),$input.remove(),me.$header.removeClass("title-editing"),console.log(oldTitle,$input.val()),me._triggerEvent("titleChange",[me,oldTitle,$input.val()]),me},cancelTitleEditing:function(){var me=this,$input=me.$header.find("input");return 0===$input.length?me:(me.$title.html(me.$title.attr("data-old-title")).removeClass("hide"),$input.remove(),me.$header.removeClass("title-editing"),me)},remove:function(){var me=this;return me.$lobiList.$lists.splice(me.$el.index(),1),me.$elWrapper.remove(),me},editItem:function(id){var me=this,$item=me.$lobiList.$el.find("li[data-id="+id+"]"),$form=$item.closest(".lobilist").find(".lobilist-add-todo-form"),$footer=$item.closest(".lobilist").find(".lobilist-footer");return $form.removeClass("hide"),$footer.addClass("hide"),$form[0].id.value=$item.attr("data-id"),$form[0].title.value=$item.find(".lobilist-item-title").html(),$form[0].description.value=$item.find(".lobilist-item-description").html()||"",$form[0].dueDate.value=$item.find(".lobilist-item-duedate").html()||"",me},suppressEvents:function(){return this.eventsSuppressed=!0,this},resumeEvents:function(){return this.eventsSuppressed=!1,this},_processItemData:function(item){var me=this;return $.extend({},me.$globalOptions.itemOptions,item)},_createHeader:function(){var me=this,$header=$("<div>",{"class":"lobilist-header"}),$actions=$("<div>",{"class":"lobilist-actions"}).appendTo($header);return me.$options.controls&&me.$options.controls.length>0&&(me.$options.controls.indexOf("styleChange")>-1&&$actions.append(me._createDropdownForStyleChange()),me.$options.controls.indexOf("edit")>-1&&($actions.append(me._createEditTitleButton()),$actions.append(me._createFinishTitleEditing()),$actions.append(me._createCancelTitleEditing())),me.$options.controls.indexOf("add")>-1&&$actions.append(me._createAddNewButton()),me.$options.controls.indexOf("remove")>-1&&$actions.append(me._createCloseButton())),me.$el.append($header),$header},_createTitle:function(){var me=this,$title=$("<div>",{"class":"lobilist-title",html:me.$options.title}).appendTo(me.$header);return me.$options.controls&&me.$options.controls.indexOf("edit")>-1&&$title.on("dblclick",function(){me.startTitleEditing()}),$title},_createBody:function(){var me=this;return $("<div>",{"class":"lobilist-body"}).appendTo(me.$el)},_createForm:function(){var me=this,$form=$("<form>",{"class":"lobilist-add-todo-form hide"});$('<input type="hidden" name="id">').appendTo($form),$('<div class="form-group">').append($("<input>",{type:"text",name:"title","class":"form-control",placeholder:"TODO title"})).appendTo($form),$('<div class="form-group">').append($("<textarea>",{rows:"2",name:"description","class":"form-control",placeholder:"TODO description"})).appendTo($form),$('<div class="form-group">').append($("<input>",{type:"text",name:"dueDate","class":"form-control",placeholder:"Due Date"})).appendTo($form);var $ft=$('<div class="lobilist-form-footer">');return $("<button>",{"class":"btn btn-primary btn-sm btn-add-todo",html:"Add"}).appendTo($ft),$("<button>",{type:"button","class":"btn btn-default btn-sm btn-discard-todo",html:'<i class="glyphicon glyphicon-remove-circle"></i>'}).click(function(){$form.addClass("hide"),me.$footer.removeClass("hide")}).appendTo($ft),$ft.appendTo($form),me._formHandler($form),me.$el.append($form),$form},_formHandler:function($form){var me=this;$form.on("submit",function(ev){ev.preventDefault(),me._submitForm()})},_submitForm:function(){var me=this;return me.$form[0].title.value?(me.saveOrUpdateItem({id:me.$form[0].id.value,title:me.$form[0].title.value,description:me.$form[0].description.value,dueDate:me.$form[0].dueDate.value}),me.$form.addClass("hide"),void me.$footer.removeClass("hide")):void me._showFormError("title","Title can not be empty")},_createFooter:function(){var me=this,$footer=$("<div>",{"class":"lobilist-footer"});return $("<button>",{type:"button","class":"btn-link btn-show-form",html:"Add new"}).click(function(){me._resetForm(),me.$form.removeClass("hide"),$footer.addClass("hide")}).appendTo($footer),me.$el.append($footer),$footer},_createList:function(){var me=this,$list=$("<ul>",{"class":"lobilist-items"});return me.$el.append($list),$list},_createItems:function(items){for(var me=this,i=0;i<items.length;i++)me._addItem(items[i])},_addItem:function(item){var me=this;item.id||(item.id=me.$lobiList.getNextId()),me._triggerEvent("beforeItemAdd",[me,item])!==!1&&(item=me._processItemData(item),me._addItemToList(item))},_createCheckbox:function(){var me=this,$item=$("<input>",{type:"checkbox"});return $item.change(function(){me._onCheckboxChange(this)}),$("<label>",{"class":"checkbox-inline lobilist-check"}).append($item)},_onCheckboxChange:function(checkbox){var me=this,$this=$(checkbox);$this.prop("checked")?me._triggerEvent("afterMarkAsDone",[me,$this]):me._triggerEvent("afterMarkAsUndone",[me,$this]),$this.closest(".lobilist-item").toggleClass("item-done")},_createDropdownForStyleChange:function(){for(var me=this,$dropdown=$("<div>",{"class":"dropdown"}).append($("<button>",{type:"button","data-toggle":"dropdown","class":"btn btn-default btn-xs",html:'<i class="glyphicon glyphicon-th"></i>'})),$menu=$("<div>",{"class":"dropdown-menu dropdown-menu-right"}).appendTo($dropdown),i=0;i<me.$globalOptions.listStyles.length;i++){var st=me.$globalOptions.listStyles[i];$('<div class="'+st+'"></div>').on("mousedown",function(ev){ev.stopPropagation()}).click(function(){for(var classes=me.$el[0].className.split(" "),oldClass=null,i=0;i<classes.length;i++)me.$globalOptions.listStyles.indexOf(classes[i])>-1&&(oldClass=classes[i]);me.$el.removeClass(me.$globalOptions.listStyles.join(" ")).addClass(this.className),me._triggerEvent("styleChange",[me,oldClass,this.className])}).appendTo($menu)}return $dropdown},_createEditTitleButton:function(){var me=this,$btn=$("<button>",{"class":"btn btn-default btn-xs",html:'<i class="glyphicon glyphicon-edit"></i>'});return $btn.click(function(){me.startTitleEditing()}),$btn},_createAddNewButton:function(){var me=this,$btn=$("<button>",{"class":"btn btn-default btn-xs",html:'<i class="glyphicon glyphicon-plus"></i>'});return $btn.click(function(){var list=me.$lobiList.addList();list.startTitleEditing()}),$btn},_createCloseButton:function(){var me=this,$btn=$("<button>",{"class":"btn btn-default btn-xs",html:'<i class="glyphicon glyphicon-remove"></i>'});return $btn.click(me._onRemoveListClick),$btn},_onRemoveListClick:function(){var me=this;return me._triggerEvent("beforeListRemove",[me]),me.remove(),me._triggerEvent("afterListRemove",[me]),me},_createFinishTitleEditing:function(){var me=this,$btn=$("<button>",{"class":"btn btn-default btn-xs btn-finish-title-editing",html:'<i class="glyphicon glyphicon-ok-circle"></i>'});return $btn.click(function(){me.finishTitleEditing()}),$btn},_createCancelTitleEditing:function(){var me=this,$btn=$("<button>",{"class":"btn btn-default btn-xs btn-cancel-title-editing",html:'<i class="glyphicon glyphicon-remove-circle"></i>'});return $btn.click(function(){me.cancelTitleEditing()}),$btn},_createInput:function(){var me=this,input=$('<input type="text" class="form-control">');return input.on("keyup",function(ev){13===ev.which&&me.finishTitleEditing()}),input},_showFormError:function(field,error){var $fGroup=this.$form.find('[name="'+field+'"]').closest(".form-group").addClass("has-error");$fGroup.find(".help-block").remove(),$fGroup.append($('<span class="help-block">'+error+"</span>"))},_resetForm:function(){var me=this;me.$form[0].reset(),me.$form[0].id.value="",me.$form.find(".form-group").removeClass("has-error").find(".help-block").remove()},_enableSorting:function(){var me=this;me.$el.find(".lobilist-items").sortable({connectWith:".lobilist .lobilist-items",items:".lobilist-item",handle:".drag-handler",cursor:"move",placeholder:"lobilist-item-placeholder",forcePlaceholderSize:!0,opacity:.9,revert:70,update:function(event,ui){me._triggerEvent("afterItemReorder",[me,ui.item])}})},_addItemToList:function(item){var me=this,$li=$("<li>",{"data-id":item.id,"class":"lobilist-item"});return $li.append($("<div>",{"class":"lobilist-item-title",html:item.title})),item.description&&$li.append($("<div>",{"class":"lobilist-item-description",html:item.description})),item.dueDate&&$li.append($("<div>",{"class":"lobilist-item-duedate",html:item.dueDate})),$li=me._addItemControls($li),item.done&&($li.find("input[type=checkbox]").prop("checked",!0),$li.addClass("item-done")),$li.data("lobiListItem",item),me.$ul.append($li),me.$items[item.id]=item,me._triggerEvent("afterItemAdd",[me,item]),$li},_addItemControls:function($li){var me=this;me.$options.useCheckboxes&&$li.append(me._createCheckbox());var $itemControlsDiv=$("<div>",{"class":"todo-actions"}).appendTo($li);return me.$options.enableTodoEdit&&$itemControlsDiv.append($("<div>",{"class":"edit-todo todo-action",html:'<i class="glyphicon glyphicon-pencil"></i>'}).click(function(){me.editItem($(this).closest("li").data("id"))})),me.$options.enableTodoRemove&&$itemControlsDiv.append($("<div>",{"class":"delete-todo todo-action",html:'<i class="glyphicon glyphicon-remove"></i>'}).click(function(){me._onDeleteItemClick($(this).closest("li").data("lobiListItem"))})),$li.append($("<div>",{"class":"drag-handler"})),$li},_onDeleteItemClick:function(item){this.deleteItem(item)},_updateItemInList:function(item){var me=this,$li=me.$lobiList.$el.find('li[data-id="'+item.id+'"]');$li.find("input[type=checkbox]").prop("checked",item.done),$li.find(".lobilist-item-title").html(item.title),$li.find(".lobilist-item-description").remove(),$li.find(".lobilist-item-duedate").remove(),item.description&&$li.append('<div class="lobilist-item-description">'+item.description+"</div>"),item.dueDate&&$li.append('<div class="lobilist-item-duedate">'+item.dueDate+"</div>"),$li.data("lobiListItem",item),$.extend(me.$items[item.id],item),me._triggerEvent("afterItemUpdate",[me,item])},_triggerEvent:function(type,data){var me=this;if(!me.eventsSuppressed)return me.$options[type]&&"function"==typeof me.$options[type]?me.$options[type].apply(me,data):me.$el.trigger(type,data)},_removeItemFromList:function(item){var me=this;me.$lobiList.$el.find("li[data-id="+item.id+"]").remove(),me._triggerEvent("afterItemDelete",[me,item])},_sendAjax:function(url,params){var me=this;return $.ajax(url,me._beforeAjaxSent(params))},_beforeAjaxSent:function(params){var me=this,eventParams=me._triggerEvent("beforeAjaxSent",[me,params]);return $.extend({},params,eventParams||{})}};var LobiList=function($el,options){this.$el=$el,this.init(options)};LobiList.prototype={$el:null,$lists:[],$options:{},_nextId:1,eventsSuppressed:!1,init:function(options){var me=this;me.suppressEvents(),me.$options=this._processInput(options),me.$el.addClass("lobilists"),me.$options.onSingleLine&&me.$el.addClass("single-line"),me._createLists(),me._handleSortable(),me._triggerEvent("init",[me]),me.resumeEvents()},_processInput:function(options){return options=$.extend({},$.fn.lobiList.DEFAULT_OPTIONS,options),options.actions.load&&$.ajax(options.actions.load,{async:!1}).done(function(res){options.lists=res.lists}),options},_createLists:function(){for(var me=this,i=0;i<me.$options.lists.length;i++)me.addList(me.$options.lists[i]);return me},_handleSortable:function(){var me=this;return me.$options.sortable?me.$el.sortable({items:".lobilist-wrapper",handle:".lobilist-header",cursor:"move",placeholder:"lobilist-placeholder",forcePlaceholderSize:!0,opacity:.9,revert:70,update:function(event,ui){me._triggerEvent("afterListReorder",[me,ui.item.find(".lobilist").data("lobiList")])}}):me.$el.addClass("no-sortable"),me},addList:function(list){var me=this;return list instanceof List||(list=new List(me,me._processListOptions(list))),me._triggerEvent("beforeListAdd",[me,list])!==!1&&(me.$lists.push(list),me.$el.append(list.$elWrapper),list.$el.data("lobiList",list),me._triggerEvent("afterListAdd",[me,list])),list},destroy:function(){var me=this;if(me._triggerEvent("beforeDestroy",[me])!==!1){for(var i=0;i<me.$lists.length;i++)me.$lists[i].remove();me.$options.sortable&&me.$el.sortable("destroy"),me.$el.removeClass("lobilists"),me.$options.onSingleLine&&me.$el.removeClass("single-line"),me.$el.removeData("lobiList"),me._triggerEvent("afterDestroy",[me])}return me},getNextId:function(){return this._nextId++},_processListOptions:function(listOptions){var me=this;listOptions=$.extend({},me.$options.listsOptions,listOptions);for(var i in me.$options)me.$options.hasOwnProperty(i)&&void 0===listOptions[i]&&(listOptions[i]=me.$options[i]);return listOptions},suppressEvents:function(){return this.eventsSuppressed=!0,this},resumeEvents:function(){return this.eventsSuppressed=!1,this},_triggerEvent:function(type,data){var me=this;if(!me.eventsSuppressed)return me.$options[type]&&"function"==typeof me.$options[type]?me.$options[type].apply(me,data):me.$el.trigger(type,data)}},$.fn.lobiList=function(option){var ret,args=arguments;return this.each(function(){var $this=$(this),data=$this.data("lobiList"),options="object"==typeof option&&option;data||$this.data("lobiList",data=new LobiList($this,options)),"string"==typeof option&&(args=Array.prototype.slice.call(args,1),ret=data[option].apply(data,args))})},$.fn.lobiList.DEFAULT_OPTIONS={listStyles:["lobilist-default","lobilist-danger","lobilist-success","lobilist-warning","lobilist-info","lobilist-primary"],listsOptions:{id:!1,title:"",items:[]},itemOptions:{id:!1,title:"",description:"",dueDate:"",done:!1},lists:[],actions:{load:"",update:"",insert:"","delete":""},useCheckboxes:!0,enableTodoRemove:!0,enableTodoEdit:!0,sortable:!0,controls:["edit","add","remove","styleChange"],defaultStyle:"lobilist-default",onSingleLine:!0,init:null,beforeDestroy:null,afterDestroy:null,beforeListAdd:null,afterListAdd:null,beforeListRemove:null,afterListRemove:null,beforeItemAdd:null,afterItemAdd:null,beforeItemUpdate:null,afterItemUpdate:null,beforeItemDelete:null,afterItemDelete:null,afterListReorder:null,afterItemReorder:null,afterMarkAsDone:null,afterMarkAsUndone:null,beforeAjaxSent:null,styleChange:null,titleChange:null}});
27182812/ChatGLM-LLaMA-chinese-insturct
16,554
src/transformers/optimization_tf.py
# Copyright 2019 The TensorFlow Authors, The Hugging Face 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. # ============================================================================== """Functions and classes related to optimization (weight updates).""" import re from typing import Callable, List, Optional, Union import tensorflow as tf try: from tensorflow.keras.optimizers.legacy import Adam except ImportError: from tensorflow.keras.optimizers import Adam class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule): """ Applies a warmup schedule on a given learning rate decay schedule. Args: initial_learning_rate (`float`): The initial learning rate for the schedule after the warmup (so this will be the learning rate at the end of the warmup). decay_schedule_fn (`Callable`): The schedule function to apply after the warmup for the rest of training. warmup_steps (`int`): The number of steps for the warmup part of training. power (`float`, *optional*, defaults to 1): The power to use for the polynomial warmup (defaults is a linear warmup). name (`str`, *optional*): Optional name prefix for the returned tensors during the schedule. """ def __init__( self, initial_learning_rate: float, decay_schedule_fn: Callable, warmup_steps: int, power: float = 1.0, name: str = None, ): super().__init__() self.initial_learning_rate = initial_learning_rate self.warmup_steps = warmup_steps self.power = power self.decay_schedule_fn = decay_schedule_fn self.name = name def __call__(self, step): with tf.name_scope(self.name or "WarmUp") as name: # Implements polynomial warmup. i.e., if global_step < warmup_steps, the # learning rate will be `global_step/num_warmup_steps * init_lr`. global_step_float = tf.cast(step, tf.float32) warmup_steps_float = tf.cast(self.warmup_steps, tf.float32) warmup_percent_done = global_step_float / warmup_steps_float warmup_learning_rate = self.initial_learning_rate * tf.math.pow(warmup_percent_done, self.power) return tf.cond( global_step_float < warmup_steps_float, lambda: warmup_learning_rate, lambda: self.decay_schedule_fn(step - self.warmup_steps), name=name, ) def get_config(self): return { "initial_learning_rate": self.initial_learning_rate, "decay_schedule_fn": self.decay_schedule_fn, "warmup_steps": self.warmup_steps, "power": self.power, "name": self.name, } def create_optimizer( init_lr: float, num_train_steps: int, num_warmup_steps: int, min_lr_ratio: float = 0.0, adam_beta1: float = 0.9, adam_beta2: float = 0.999, adam_epsilon: float = 1e-8, adam_clipnorm: Optional[float] = None, adam_global_clipnorm: Optional[float] = None, weight_decay_rate: float = 0.0, power: float = 1.0, include_in_weight_decay: Optional[List[str]] = None, ): """ Creates an optimizer with a learning rate schedule using a warmup phase followed by a linear decay. Args: init_lr (`float`): The desired learning rate at the end of the warmup phase. num_train_steps (`int`): The total number of training steps. num_warmup_steps (`int`): The number of warmup steps. min_lr_ratio (`float`, *optional*, defaults to 0): The final learning rate at the end of the linear decay will be `init_lr * min_lr_ratio`. adam_beta1 (`float`, *optional*, defaults to 0.9): The beta1 to use in Adam. adam_beta2 (`float`, *optional*, defaults to 0.999): The beta2 to use in Adam. adam_epsilon (`float`, *optional*, defaults to 1e-8): The epsilon to use in Adam. adam_clipnorm: (`float`, *optional*, defaults to `None`): If not `None`, clip the gradient norm for each weight tensor to this value. adam_global_clipnorm: (`float`, *optional*, defaults to `None`) If not `None`, clip gradient norm to this value. When using this argument, the norm is computed over all weight tensors, as if they were concatenated into a single vector. weight_decay_rate (`float`, *optional*, defaults to 0): The weight decay to use. power (`float`, *optional*, defaults to 1.0): The power to use for PolynomialDecay. include_in_weight_decay (`List[str]`, *optional*): List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is applied to all parameters except bias and layer norm parameters. """ # Implements linear decay of the learning rate. lr_schedule = tf.keras.optimizers.schedules.PolynomialDecay( initial_learning_rate=init_lr, decay_steps=num_train_steps - num_warmup_steps, end_learning_rate=init_lr * min_lr_ratio, power=power, ) if num_warmup_steps: lr_schedule = WarmUp( initial_learning_rate=init_lr, decay_schedule_fn=lr_schedule, warmup_steps=num_warmup_steps, ) if weight_decay_rate > 0.0: optimizer = AdamWeightDecay( learning_rate=lr_schedule, weight_decay_rate=weight_decay_rate, beta_1=adam_beta1, beta_2=adam_beta2, epsilon=adam_epsilon, clipnorm=adam_clipnorm, global_clipnorm=adam_global_clipnorm, exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"], include_in_weight_decay=include_in_weight_decay, ) else: optimizer = tf.keras.optimizers.Adam( learning_rate=lr_schedule, beta_1=adam_beta1, beta_2=adam_beta2, epsilon=adam_epsilon, clipnorm=adam_clipnorm, global_clipnorm=adam_global_clipnorm, ) # We return the optimizer and the LR scheduler in order to better track the # evolution of the LR independently of the optimizer. return optimizer, lr_schedule class AdamWeightDecay(Adam): """ Adam enables L2 weight decay and clip_by_global_norm on gradients. Just adding the square of the weights to the loss function is *not* the correct way of using L2 regularization/weight decay with Adam, since that will interact with the m and v parameters in strange ways as shown in [Decoupled Weight Decay Regularization](https://arxiv.org/abs/1711.05101). Instead we want to decay the weights in a manner that doesn't interact with the m/v parameters. This is equivalent to adding the square of the weights to the loss with plain (non-momentum) SGD. Args: learning_rate (`Union[float, tf.keras.optimizers.schedules.LearningRateSchedule]`, *optional*, defaults to 1e-3): The learning rate to use or a schedule. beta_1 (`float`, *optional*, defaults to 0.9): The beta1 parameter in Adam, which is the exponential decay rate for the 1st momentum estimates. beta_2 (`float`, *optional*, defaults to 0.999): The beta2 parameter in Adam, which is the exponential decay rate for the 2nd momentum estimates. epsilon (`float`, *optional*, defaults to 1e-7): The epsilon parameter in Adam, which is a small constant for numerical stability. amsgrad (`bool`, *optional*, default to `False`): Whether to apply AMSGrad variant of this algorithm or not, see [On the Convergence of Adam and Beyond](https://arxiv.org/abs/1904.09237). weight_decay_rate (`float`, *optional*, defaults to 0): The weight decay to apply. include_in_weight_decay (`List[str]`, *optional*): List of the parameter names (or re patterns) to apply weight decay to. If none is passed, weight decay is applied to all parameters by default (unless they are in `exclude_from_weight_decay`). exclude_from_weight_decay (`List[str]`, *optional*): List of the parameter names (or re patterns) to exclude from applying weight decay to. If a `include_in_weight_decay` is passed, the names in it will supersede this list. name (`str`, *optional*, defaults to 'AdamWeightDecay'): Optional name for the operations created when applying gradients. kwargs: Keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip gradients by value, `decay` is included for backward compatibility to allow time inverse decay of learning rate. `lr` is included for backward compatibility, recommended to use `learning_rate` instead. """ def __init__( self, learning_rate: Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001, beta_1: float = 0.9, beta_2: float = 0.999, epsilon: float = 1e-7, amsgrad: bool = False, weight_decay_rate: float = 0.0, include_in_weight_decay: Optional[List[str]] = None, exclude_from_weight_decay: Optional[List[str]] = None, name: str = "AdamWeightDecay", **kwargs, ): super().__init__(learning_rate, beta_1, beta_2, epsilon, amsgrad, name, **kwargs) self.weight_decay_rate = weight_decay_rate self._include_in_weight_decay = include_in_weight_decay self._exclude_from_weight_decay = exclude_from_weight_decay @classmethod def from_config(cls, config): """Creates an optimizer from its config with WarmUp custom object.""" custom_objects = {"WarmUp": WarmUp} return super(AdamWeightDecay, cls).from_config(config, custom_objects=custom_objects) def _prepare_local(self, var_device, var_dtype, apply_state): super(AdamWeightDecay, self)._prepare_local(var_device, var_dtype, apply_state) apply_state[(var_device, var_dtype)]["weight_decay_rate"] = tf.constant( self.weight_decay_rate, name="adam_weight_decay_rate" ) def _decay_weights_op(self, var, learning_rate, apply_state): do_decay = self._do_use_weight_decay(var.name) if do_decay: return var.assign_sub( learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["weight_decay_rate"], use_locking=self._use_locking, ) return tf.no_op() def apply_gradients(self, grads_and_vars, name=None, **kwargs): grads, tvars = list(zip(*grads_and_vars)) return super(AdamWeightDecay, self).apply_gradients(zip(grads, tvars), name=name, **kwargs) def _get_lr(self, var_device, var_dtype, apply_state): """Retrieves the learning rate with the given state.""" if apply_state is None: return self._decayed_lr_t[var_dtype], {} apply_state = apply_state or {} coefficients = apply_state.get((var_device, var_dtype)) if coefficients is None: coefficients = self._fallback_apply_state(var_device, var_dtype) apply_state[(var_device, var_dtype)] = coefficients return coefficients["lr_t"], {"apply_state": apply_state} def _resource_apply_dense(self, grad, var, apply_state=None): lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state) decay = self._decay_weights_op(var, lr_t, apply_state) with tf.control_dependencies([decay]): return super(AdamWeightDecay, self)._resource_apply_dense(grad, var, **kwargs) def _resource_apply_sparse(self, grad, var, indices, apply_state=None): lr_t, kwargs = self._get_lr(var.device, var.dtype.base_dtype, apply_state) decay = self._decay_weights_op(var, lr_t, apply_state) with tf.control_dependencies([decay]): return super(AdamWeightDecay, self)._resource_apply_sparse(grad, var, indices, **kwargs) def get_config(self): config = super().get_config() config.update({"weight_decay_rate": self.weight_decay_rate}) return config def _do_use_weight_decay(self, param_name): """Whether to use L2 weight decay for `param_name`.""" if self.weight_decay_rate == 0: return False if self._include_in_weight_decay: for r in self._include_in_weight_decay: if re.search(r, param_name) is not None: return True if self._exclude_from_weight_decay: for r in self._exclude_from_weight_decay: if re.search(r, param_name) is not None: return False return True # Extracted from https://github.com/OpenNMT/OpenNMT-tf/blob/master/opennmt/optimizers/utils.py class GradientAccumulator(object): """ Gradient accumulation utility. When used with a distribution strategy, the accumulator should be called in a replica context. Gradients will be accumulated locally on each replica and without synchronization. Users should then call `.gradients`, scale the gradients if required, and pass the result to `apply_gradients`. """ # We use the ON_READ synchronization policy so that no synchronization is # performed on assignment. To get the value, we call .value() which returns the # value on the current replica without synchronization. def __init__(self): """Initializes the accumulator.""" self._gradients = [] self._accum_steps = None @property def step(self): """Number of accumulated steps.""" if self._accum_steps is None: self._accum_steps = tf.Variable( tf.constant(0, dtype=tf.int64), trainable=False, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA, ) return self._accum_steps.value() @property def gradients(self): """The accumulated gradients on the current replica.""" if not self._gradients: raise ValueError("The accumulator should be called first to initialize the gradients") return [gradient.value() if gradient is not None else gradient for gradient in self._gradients] def __call__(self, gradients): """Accumulates `gradients` on the current replica.""" if not self._gradients: _ = self.step # Create the step variable. self._gradients.extend( [ tf.Variable( tf.zeros_like(gradient), trainable=False, synchronization=tf.VariableSynchronization.ON_READ, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA, ) if gradient is not None else gradient for gradient in gradients ] ) if len(gradients) != len(self._gradients): raise ValueError(f"Expected {len(self._gradients)} gradients, but got {len(gradients)}") for accum_gradient, gradient in zip(self._gradients, gradients): if accum_gradient is not None and gradient is not None: accum_gradient.assign_add(gradient) self._accum_steps.assign_add(1) def reset(self): """Resets the accumulated gradients on the current replica.""" if not self._gradients: return self._accum_steps.assign(0) for gradient in self._gradients: if gradient is not None: gradient.assign(tf.zeros_like(gradient))
274056675/springboot-openai-chatgpt
1,973
mng_web/src/styles/sidebar.scss
.el-menu--popup{ .el-menu-item{ background-color: #20222a; i{ margin-right: 5px; } i,span{ color:hsla(0,0%,100%,.7); } &:hover{ i,span{ color:#fff; } } &.is-active { background-color: rgba(0,0,0,.8); &:before { content: ''; top: 0; left: 0; bottom: 0; width: 4px; background: #409eff; position: absolute; } i,span{ color:#fff; } } } } .avue-sidebar { user-select: none; position: relative; padding-top: 60px; height: 100%; position: relative; background-color: #20222a; transition: width .2s; box-sizing: border-box; box-shadow: 2px 0 6px rgba(0,21,41,.35); &--tip{ width:90%; height: 140px; display: flex; align-items: center; justify-content: center; border-radius: 5px; position: absolute; top:5px; left:5%; color:#ccc; z-index: 2; text-align: center; font-size: 14px; background-color: rgba(0,0,0,.4); } .el-menu-item,.el-submenu__title{ i{ margin-right: 5px; } i,span{ color:hsla(0,0%,100%,.7); } &:hover{ background: transparent; i,span{ color:#fff; } } &.is-active { &:before { content: ''; top: 0; left: 0; bottom: 0; width: 4px; background: #409eff; position: absolute; } background-color: rgba(0,0,0,.8); i,span{ color:#fff; } } } }
274056675/springboot-openai-chatgpt
9,915
mng_web/src/styles/normalize.scss
/*! normalize.css v2.1.2 | MIT License | git.io/normalize */ /* /*! 我就是自己看看,然后翻译下下,让大家看看 */ /* ========================================================================== HTML5 display definitions HTML5 新增元素定义 ========================================================================== */ /** * Correct `block` display not defined in IE 8/9. * * 修正IE 8/9 中未定义的块级元素。 */ article, aside, details, figcaption, figure, footer, header, hgroup, main, nav, section, summary { display: block; } /** * Correct `inline-block` display not defined in IE 8/9. * * 修正在 IE 8/9 中未定义的 'inline-block' 元素。 */ audio, canvas, video { display: inline-block; } /** * Prevent modern browsers from displaying `audio` without controls. * Remove excess height in iOS 5 devices. * * 阻止现在浏览器显示未定义 control 播放控件的 'audio' 声音元素。 * 删除 IOS 5 设备中显示的多余的高度。 */ audio:not([controls]) { display: none; height: 0; } /** * Address styling not present in IE 8/9. * * 处理 IE 8/9 中不存在的样式。 */ [hidden] { display: none; } /* ========================================================================== Base 基本设置 ========================================================================== */ /** * 1. Set default font family to sans-serif. * 2. Prevent iOS text size adjust after orientation change, without disabling * user zoom. * * 1. 设置默认字体类型为 sans-serif. * 2. 当用户放大或缩小页面时不改变字体大小。 */ html { font-family: sans-serif; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ } /** * Remove default margin. * * 删除默认边距。 */ body { margin: 0; } /* ========================================================================== Links 链接 ========================================================================== */ /** * Address `outline` inconsistency between Chrome and other browsers. * * 处理 Chrome 与其它浏览器中关于 'outline' 的不一致性。 */ a:focus { outline: thin dotted; } /** * Improve readability when focused and also mouse hovered in all browsers. * * 为所有浏览器改善当激活或悬停在元素上时元素内容的可读性。 */ a:active, a:hover { outline: 0; } /* ========================================================================== Typography 排版 ========================================================================== */ /** * Address variable `h1` font-size and margin within `section` and `article` * contexts in Firefox 4+, Safari 5, and Chrome. * * 处理多变的 'h1' 字体大小及其在 Firefox 4+, Safari 5, 及 Chrome时浏览器中的 * 'section' 与 'article' 元素中的边距。 */ h1 { font-size: 2em; margin: 0.67em 0; } /** * Address styling not present in IE 8/9, Safari 5, and Chrome. * * 处理在 IE 8/9, Safari 5, 及 Chrome 没有的样式。 */ abbr[title] { border-bottom: 1px dotted; } /** * Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome. * * 处理 Firefox 4+, Safari 5, 及 Chrome 中默认的 'bolder' 样式为 'bold'. */ b, strong { font-weight: bold; } /** * Address styling not present in Safari 5 and Chrome. * * 处理在 Safari 5 和 Chrome 没有的样式。 */ dfn { font-style: italic; } /** * Address differences between Firefox and other browsers. * * 处理 Firefox 与其它浏览器的差异。 */ hr { -moz-box-sizing: content-box; box-sizing: content-box; height: 0; } /** * Address styling not present in IE 8/9. * * 处理在 IE 8/9 中没有的样式。 */ mark { background: #ff0; color: #000; } /** * Correct font family set oddly in Safari 5 and Chrome. * * 修正确 Safari 5 和 Chrome 中古怪的默认字体。 */ code, kbd, pre, samp { font-family: monospace, serif; font-size: 1em; } /** * Improve readability of pre-formatted text in all browsers. * * 为所有浏览器改善预格式化文本的可读性。 */ pre { white-space: pre-wrap; } /** * Set consistent quote types. * * 设置一致的引用格式。 */ q { quotes: "\201C" "\201D" "\2018" "\2019"; } /** * Address inconsistent and variable font size in all browsers. * * 处理所有浏览器中字体大小的不一致性[译者注:原文直译为:处理所有 * 浏览器中的不一致和多变的字体大小]。 */ small { font-size: 80%; } /** * Prevent `sub` and `sup` affecting `line-height` in all browsers. * * 阻止所有浏览器中 'sub' 和 'sup' 元素影响 'line-height'. * [译者注:就是不让上标与下标影响行高。] */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* ========================================================================== Embedded content 嵌入的内容 ========================================================================== */ /** * Remove border when inside `a` element in IE 8/9. * * 删除 IE 8/9 中当内容位于 'a' 中出现的边框。 */ img { border: 0; } /** * Correct overflow displayed oddly in IE 9. * * 修正 IE 9 中显示古怪的溢出内容。 */ svg:not(:root) { overflow: hidden; } /* ========================================================================== Figures Figure 图像/图表/代码等 ========================================================================== */ /** * Address margin not present in IE 8/9 and Safari 5. * * 处理在 IE 8/9 和 Safari 5 没有的边距。 */ figure { margin: 0; } /* ========================================================================== Forms ========================================================================== */ /** * Define consistent border, margin, and padding. * * 定义一致的边框、外边距及内边距。 */ fieldset { border: 1px solid #c0c0c0; margin: 0 2px; padding: 0.35em 0.625em 0.75em; } /** * 1. Correct `color` not being inherited in IE 8/9. * 2. Remove padding so people aren't caught out if they zero out fieldsets. * 1. 修正在 IE 8/9 中没有继承的 'color'. * * [译者注:说是修正颜色嘛,可下面没有关于颜色的呀,这也行?求大神解释!] * 2. 去掉内边距,避免当用户清空表单组时认为出错了。 */ legend { border: 0; /* 1 */ padding: 0; /* 2 */ } /** * 1. Correct font family not being inherited in all browsers. * 2. Correct font size not being inherited in all browsers. * 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome. * * 1. 修正所有浏览器中未被继承的字体类型。 * 2. 修正所有浏览器中未被继承的字体大小。 * 3. 处理 Firefox 4+, Safari 5, 及 Chrome 中默认设置不同的外边距。 */ button, input, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 2 */ margin: 0; /* 3 */ } /** * Address Firefox 4+ setting `line-height` on `input` using `!important` in * the UA stylesheet. * * 处理 Firefox 4+ 中的客户端样式表里使用 '!important' 设置的 'line-height'. */ button, input { line-height: normal; } /** * Address inconsistent `text-transform` inheritance for `button` and `select`. * All other form control elements do not inherit `text-transform` values. * Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+. * Correct `select` style inheritance in Firefox 4+ and Opera. * * 处理 'button' 和 'select' 的 'text-transform' 继承的不一致性。 * 所有其它表单控件元素不继承 'text-transform' 的值。 * 修正 Chrome, Safari 5+, 及 IE 8+ 中 'button' 的继承样式。 * 修正 Firefox 4+ 和 Opera 中 'select' 的继承样式。 */ button, select { text-transform: none; } /** * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` * and `video` controls. * 2. Correct inability to style clickable `input` types in iOS. * 3. Improve usability and consistency of cursor style between image-type * `input` and others. * * 1. 避免 Android 4.0.* 中 WebKit 的一个bug, 防止 'audio' 与 'video' 的播放控件失效。 * 2. 修正 iOS 中不可点击的 'input' 样式。 * 3. 改善图片类型的 'input' 等光标样式的可用性与一致性。 */ button, html input[type="button"], /* 1 */ input[type="reset"], input[type="submit"] { -webkit-appearance: button; /* 2 */ cursor: pointer; /* 3 */ } /** * Re-set default cursor for disabled elements. * * 重置不可用元素的默认光标样式。 */ button[disabled], html input[disabled] { cursor: default; } /** * 1. Address box sizing set to `content-box` in IE 8/9. * 2. Remove excess padding in IE 8/9. * * 1. 处理 IE 8/9 中设置为 'content-box' 的盒子模型。 * 2. 删除 IE 8/9 中多余的内边距。 */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* 1 */ padding: 0; /* 2 */ } /** * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome. * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome * (include `-moz` to future-proof). * * 1. 处理 Safari 5 和 Chrome 中默认设置为 'appearance' 的 'searchfield'. * 2. 处理 Safari 5 和 Chrome 中默认设置为 'box-sizing' 的 'border-box' * (包括不会过时的 '-moz'). */ input[type="search"] { -webkit-appearance: textfield; /* 1 */ -moz-box-sizing: content-box; -webkit-box-sizing: content-box; /* 2 */ box-sizing: content-box; } /** * Remove inner padding and search cancel button in Safari 5 and Chrome * on OS X. * * 删除 Safari 5 和 OS X 上的 Chrome 中的输入框上的内边距和搜索取消按钮。 */ input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; } /** * Remove inner padding and border in Firefox 4+. * * 删除 Firefox 4+ button 与 input 上的内边距。 */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /** * 1. Remove default vertical scrollbar in IE 8/9. * 2. Improve readability and alignment in all browsers. * * 1. 删除 IE8/9 中默认的垂直滚动条。 * 2. 改善所有浏览器中的可读性并使文本垂直对齐。 */ textarea { overflow: auto; /* 1 */ vertical-align: top; /* 2 */ } /* ========================================================================== Tables 表格 ========================================================================== */ /** * Remove most spacing between table cells. * * 删除表格里单元格间的间距。 */ table { border-collapse: collapse; border-spacing: 0; }
27182812/ChatGLM-LLaMA-chinese-insturct
3,019
src/transformers/dependency_versions_table.py
# THIS FILE HAS BEEN AUTOGENERATED. To update: # 1. modify the `_deps` dict in setup.py # 2. run `make deps_table_update`` deps = { "Pillow": "Pillow", "accelerate": "accelerate>=0.10.0", "av": "av==9.2.0", "beautifulsoup4": "beautifulsoup4", "black": "black~=23.1", "codecarbon": "codecarbon==1.2.0", "cookiecutter": "cookiecutter==1.7.3", "dataclasses": "dataclasses", "datasets": "datasets!=2.5.0", "decord": "decord==0.6.0", "deepspeed": "deepspeed>=0.6.5", "dill": "dill<0.3.5", "evaluate": "evaluate>=0.2.0", "fairscale": "fairscale>0.3", "faiss-cpu": "faiss-cpu", "fastapi": "fastapi", "filelock": "filelock", "flax": "flax>=0.4.1", "ftfy": "ftfy", "fugashi": "fugashi>=1.0", "GitPython": "GitPython<3.1.19", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.11.0,<1.0", "importlib_metadata": "importlib_metadata", "ipadic": "ipadic>=1.0.0,<2.0", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2,<=0.3.6", "jaxlib": "jaxlib>=0.1.65,<=0.3.6", "jieba": "jieba", "kenlm": "kenlm", "keras-nlp": "keras-nlp>=0.3.1", "librosa": "librosa", "nltk": "nltk", "natten": "natten>=0.14.4", "numpy": "numpy>=1.17", "onnxconverter-common": "onnxconverter-common", "onnxruntime-tools": "onnxruntime-tools>=1.4.2", "onnxruntime": "onnxruntime>=1.4.0", "optuna": "optuna", "optax": "optax>=0.0.8", "packaging": "packaging>=20.0", "parameterized": "parameterized", "phonemizer": "phonemizer", "protobuf": "protobuf<=3.20.2", "psutil": "psutil", "pyyaml": "pyyaml>=5.1", "pydantic": "pydantic", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "python": "python>=3.7.0", "ray[tune]": "ray[tune]", "regex": "regex!=2019.12.17", "requests": "requests", "rhoknp": "rhoknp>=1.1.0", "rjieba": "rjieba", "rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1", "ruff": "ruff>=0.0.241", "sacrebleu": "sacrebleu>=1.4.12,<2.0.0", "sacremoses": "sacremoses", "safetensors": "safetensors>=0.2.1", "sagemaker": "sagemaker>=2.31.0", "scikit-learn": "scikit-learn", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "sigopt": "sigopt", "starlette": "starlette", "sudachipy": "sudachipy>=0.6.6", "sudachidict_core": "sudachidict_core>=20220729", "tensorflow-cpu": "tensorflow-cpu>=2.4,<2.12", "tensorflow": "tensorflow>=2.4,<2.12", "tensorflow-text": "tensorflow-text", "tf2onnx": "tf2onnx", "timeout-decorator": "timeout-decorator", "timm": "timm", "tokenizers": "tokenizers>=0.11.1,!=0.11.3,<0.14", "torch": "torch>=1.7,!=1.12.0", "torchaudio": "torchaudio", "torchvision": "torchvision", "pyctcdecode": "pyctcdecode>=0.4.0", "tqdm": "tqdm>=4.27", "unidic": "unidic>=1.0.2", "unidic_lite": "unidic_lite>=1.0.7", "uvicorn": "uvicorn", }
27182812/ChatGLM-LLaMA-chinese-insturct
1,756
src/transformers/dependency_versions_check.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. import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers pkgs_to_check_at_runtime = "python tqdm regex requests packaging filelock numpy tokenizers".split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append("dataclasses") if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append("importlib_metadata") for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py") def dep_version_check(pkg, hint=None): require_version(deps[pkg], hint)
27182812/ChatGLM-LLaMA-chinese-insturct
54,504
src/transformers/modeling_tf_outputs.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 dataclasses import dataclass from typing import List, Optional, Tuple import tensorflow as tf from .utils import ModelOutput @dataclass class TFBaseModelOutput(ModelOutput): """ Base class for model's outputs, with potential hidden states and 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.FloatTensor)`, *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. """ last_hidden_state: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFBaseModelOutputWithNoAttention(ModelOutput): """ Base class for model's outputs, with potential hidden states. Args: last_hidden_state (`tf.Tensor` shape `(batch_size, num_channels, height, width)`): 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 `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, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. """ last_hidden_state: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor, ...]] = None @dataclass class TFBaseModelOutputWithPooling(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. 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. pooler_output (`tf.Tensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining. This output is usually *not* a good summary of the semantic content of the input, you're often better with averaging or pooling the sequence of hidden-states for the whole input sequence. 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. """ last_hidden_state: tf.Tensor = None pooler_output: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFBaseModelOutputWithPoolingAndNoAttention(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`tf.Tensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state after a pooling operation on the spatial dimensions. 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, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, num_channels, height, width)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. """ last_hidden_state: tf.Tensor = None pooler_output: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor, ...]] = None @dataclass class TFBaseModelOutputWithPoolingAndCrossAttentions(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. 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. pooler_output (`tf.Tensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining. This output is usually *not* a good summary of the semantic content of the input, you're often better with averaging or pooling the sequence of hidden-states for the whole input sequence. 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) that can be used (see `past_key_values` input) to speed up sequential decoding. 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. 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. """ last_hidden_state: tf.Tensor = None pooler_output: tf.Tensor = None past_key_values: Optional[List[tf.Tensor]] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None cross_attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFBaseModelOutputWithPast(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to 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 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) that can be used (see `past_key_values` input) to speed up sequential decoding. 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. """ last_hidden_state: tf.Tensor = None past_key_values: Optional[List[tf.Tensor]] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFBaseModelOutputWithCrossAttentions(ModelOutput): """ Base class for model's outputs, with potential hidden states and 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.FloatTensor)`, *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. 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. """ last_hidden_state: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None cross_attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFBaseModelOutputWithPastAndCrossAttentions(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to 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 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) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(tf.FloatTensor)`, *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. 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. """ last_hidden_state: tf.Tensor = None past_key_values: Optional[List[tf.Tensor]] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None cross_attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFSeq2SeqModelOutput(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. """ 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 @dataclass class TFCausalLMOutput(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Language modeling loss (for next-token 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). 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 logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFCausalLMOutputWithPast(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Language modeling loss (for next-token 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). 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) that can be used (see `past_key_values` input) to speed up sequential decoding. 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 logits: tf.Tensor = None past_key_values: Optional[List[tf.Tensor]] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFCausalLMOutputWithCrossAttentions(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Language modeling loss (for next-token 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). 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. 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. 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) that can be used (see `past_key_values` input) to speed up sequential decoding. """ loss: Optional[tf.Tensor] = None logits: tf.Tensor = None past_key_values: Optional[List[tf.Tensor]] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None cross_attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFMaskedLMOutput(ModelOutput): """ Base class for masked language models outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Masked language modeling (MLM) 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). 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 logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFSeq2SeqLMOutput(ModelOutput): """ Base class for sequence-to-sequence language models outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, 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. """ 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 @dataclass class TFNextSentencePredictorOutput(ModelOutput): """ Base class for outputs of models predicting if two sentences are consecutive or not. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `next_sentence_label` is provided): Next sentence prediction loss. 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 logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFSequenceClassifierOutput(ModelOutput): """ Base class for outputs of sentence classification models. Args: loss (`tf.Tensor` of shape `(batch_size, )`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (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 logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFSeq2SeqSequenceClassifierOutput(ModelOutput): """ Base class for outputs of sequence-to-sequence sentence classification models. Args: loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `label` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (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)` 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. """ 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 @dataclass class TFSemanticSegmenterOutput(ModelOutput): """ Base class for outputs of semantic segmentation models. Args: loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels, logits_height, logits_width)`): Classification scores for each pixel. <Tip warning={true}> The logits returned do not necessarily have the same size as the `pixel_values` passed as inputs. This is to avoid doing two interpolations and lose some quality when a user needs to resize the logits to the original image size as post-processing. You should always check your logits shape and resize as needed. </Tip> 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, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, patch_size, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional 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, patch_size, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[tf.Tensor] = None logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFSemanticSegmenterOutputWithNoAttention(ModelOutput): """ Base class for outputs of semantic segmentation models that do not output attention scores. Args: loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels, logits_height, logits_width)`): Classification scores for each pixel. <Tip warning={true}> The logits returned do not necessarily have the same size as the `pixel_values` passed as inputs. This is to avoid doing two interpolations and lose some quality when a user needs to resize the logits to the original image size as post-processing. You should always check your logits shape and resize as needed. </Tip> 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, if the model has an embedding layer, + one for the output of each layer) of shape `(batch_size, patch_size, hidden_size)`. Hidden-states of the model at the output of each layer plus the optional initial embedding outputs. """ loss: Optional[tf.Tensor] = None logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None @dataclass class TFImageClassifierOutput(ModelOutput): """ Base class for outputs of image classification models. Args: loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (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, if the model has an embedding layer, + one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states (also called feature maps) of the model at the output of each stage. 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, patch_size, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[tf.Tensor] = None logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFMultipleChoiceModelOutput(ModelOutput): """ Base class for outputs of multiple choice models. Args: loss (`tf.Tensor` of shape *(batch_size, )*, *optional*, returned when `labels` is provided): Classification loss. logits (`tf.Tensor` of shape `(batch_size, num_choices)`): *num_choices* is the second dimension of the input tensors. (see *input_ids* above). Classification scores (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 logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFTokenClassifierOutput(ModelOutput): """ Base class for outputs of token classification models. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of unmasked labels, returned when `labels` is provided) : Classification loss. logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.num_labels)`): Classification scores (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 logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFQuestionAnsweringModelOutput(ModelOutput): """ Base class for outputs of question answering models. Args: loss (`tf.Tensor` of shape `(batch_size, )`, *optional*, returned when `start_positions` and `end_positions` are provided): Total span extraction loss is the sum of a Cross-Entropy for the start and end positions. start_logits (`tf.Tensor` of shape `(batch_size, sequence_length)`): Span-start scores (before SoftMax). end_logits (`tf.Tensor` of shape `(batch_size, sequence_length)`): Span-end scores (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 start_logits: tf.Tensor = None end_logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFSeq2SeqQuestionAnsweringModelOutput(ModelOutput): """ Base class for outputs of sequence-to-sequence question answering models. Args: loss (`tf.Tensor` 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 (`tf.Tensor` of shape `(batch_size, sequence_length)`): Span-start scores (before SoftMax). end_logits (`tf.Tensor` of shape `(batch_size, sequence_length)`): Span-end scores (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. 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. """ loss: Optional[tf.Tensor] = None start_logits: tf.Tensor = None end_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 encoder_last_hidden_state: Optional[tf.Tensor] = None encoder_hidden_states: Optional[Tuple[tf.Tensor]] = None encoder_attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFSequenceClassifierOutputWithPast(ModelOutput): """ Base class for outputs of sentence classification models. Args: loss (`tf.Tensor` of shape `(batch_size, )`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (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) that can be used (see `past_key_values` input) to speed up sequential decoding. 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 logits: tf.Tensor = None past_key_values: Optional[List[tf.Tensor]] = None hidden_states: Optional[Tuple[tf.Tensor]] = None attentions: Optional[Tuple[tf.Tensor]] = None @dataclass class TFImageClassifierOutputWithNoAttention(ModelOutput): """ Base class for outputs of image classification models. Args: loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (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, if the model has an embedding layer, + one for the output of each stage) of shape `(batch_size, num_channels, height, width)`. Hidden-states (also called feature maps) of the model at the output of each stage. """ loss: Optional[tf.Tensor] = None logits: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor, ...]] = None
274056675/springboot-openai-chatgpt
1,224
mng_web/src/store/modules/logs.js
import { setStore, getStore } from '@/util/store' import { dateFormat } from '@/util/date' import { sendLogs } from '@/api/user' const logs = { state: { logsList: getStore({ name: 'logsList' }) || [], }, actions: { //发送错误日志 SendLogs({ state, commit }) { return new Promise((resolve, reject) => { sendLogs(state.logsList).then(() => { commit('CLEAR_LOGS'); resolve(); }).catch(error => { reject(error) }) }) }, }, mutations: { ADD_LOGS: (state, { type, message, stack, info }) => { state.logsList.push(Object.assign({ url: window.location.href, time: dateFormat(new Date()) }, { type, message, stack, info: info.toString() })) setStore({ name: 'logsList', content: state.logsList }) }, CLEAR_LOGS: (state) => { state.logsList = []; setStore({ name: 'logsList', content: state.logsList }) } } }; export default logs;
274056675/springboot-openai-chatgpt
2,296
mng_web/src/store/modules/common.js
import { setStore, getStore, removeStore } from '@/util/store' import website from '@/config/website' const common = { state: { language: getStore({name: 'language'}) || 'zh', isCollapse: false, isFullScren: false, isMenu: true, isShade: false, screen: -1, isLock: getStore({name: 'isLock'}) || false, showTag: true, showDebug: true, showCollapse: true, showSearch: true, showLock: true, showFullScren: true, showTheme: true, showMenu: true, showColor: true, colorName: getStore({name: 'colorName'}) || '#409EFF', themeName: getStore({name: 'themeName'}) || 'theme-default', lockPasswd: getStore({name: 'lockPasswd'}) || '', website: website, }, mutations: { SET_LANGUAGE: (state, language) => { state.language = language setStore({ name: 'language', content: state.language }) }, SET_SHADE: (state, active) => { state.isShade = active; }, SET_COLLAPSE: (state) => { state.isCollapse = !state.isCollapse; }, SET_FULLSCREN: (state) => { state.isFullScren = !state.isFullScren; }, SET_IS_MENU: (state, menu) => { state.isMenu = menu; }, SET_LOCK: (state) => { state.isLock = true; setStore({ name: 'isLock', content: state.isLock, type: 'session' }) }, SET_SCREEN: (state, screen) => { state.screen = screen; }, SET_COLOR_NAME: (state, colorName) => { state.colorName = colorName; setStore({ name: 'colorName', content: state.colorName, }) }, SET_THEME_NAME: (state, themeName) => { state.themeName = themeName; setStore({ name: 'themeName', content: state.themeName, }) }, SET_LOCK_PASSWD: (state, lockPasswd) => { state.lockPasswd = lockPasswd; setStore({ name: 'lockPasswd', content: state.lockPasswd, type: 'session' }) }, CLEAR_LOCK: (state) => { state.isLock = false; state.lockPasswd = ''; removeStore({ name: 'lockPasswd', type: 'session' }); removeStore({ name: 'isLock', type: 'session' }); }, } } export default common
274056675/springboot-openai-chatgpt
2,233
mng_web/src/store/modules/tags.js
import { setStore, getStore } from '@/util/store' import { diff } from '@/util/util' import website from '@/config/website' const isFirstPage = website.isFirstPage; const tagWel = website.fistPage; const tagObj = { label: '', //标题名称 value: '', //标题的路径 params: '', //标题的路径参数 query: '', //标题的参数 meta: {},//额外参数 group: [], //分组 } //处理首个标签 function setFistTag(list) { if (list.length == 1) { list[0].close = false; } else { list.forEach(ele => { if (ele.value === tagWel.value && isFirstPage === false) { ele.close = false } else { ele.close = true } }) } } const navs = { state: { tagList: getStore({ name: 'tagList' }) || [], tag: getStore({ name: 'tag' }) || tagObj, tagWel: tagWel }, actions: { }, mutations: { ADD_TAG: (state, action) => { state.tag = action; setStore({ name: 'tag', content: state.tag, type: 'session' }) if (state.tagList.some(ele => diff(ele, action))) return state.tagList.push(action) setFistTag(state.tagList); setStore({ name: 'tagList', content: state.tagList, type: 'session' }) }, DEL_TAG: (state, action) => { state.tagList = state.tagList.filter(item => { return !diff(item, action); }) setFistTag(state.tagList); setStore({ name: 'tagList', content: state.tagList, type: 'session' }) }, DEL_ALL_TAG: (state) => { state.tagList = [state.tagWel]; setStore({ name: 'tagList', content: state.tagList, type: 'session' }) }, DEL_TAG_OTHER: (state) => { state.tagList = state.tagList.filter(item => { if (item.value === state.tag.value) { return true; } else if (!website.isFirstPage && item.value === website.fistPage.value) { return true; } }) setFistTag(state.tagList); setStore({ name: 'tagList', content: state.tagList, type: 'session' }) }, } } export default navs
233zzh/TitanDataOperationSystem
12,866
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/js/demo.js
/** * Created by Zura on 4/5/2016. */ $(function () { Lobibox.notify.DEFAULTS = $.extend({}, Lobibox.notify.DEFAULTS, { size: 'mini', // delay: false, position: 'right top' }); //Basic example $('#todo-lists-basic-demo').lobiList({ lists: [ { id: 'todo', title: 'TODO', defaultStyle: 'lobilist-info', items: [ { title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' }, { title: 'Periods pride', description: 'Accepted was mollis', done: true }, { title: 'Flags better burns pigeon', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank treacherously darkling.' }, { title: 'Accepted was mollis', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank treacherously darkling.', dueDate: '2015-02-02' } ] }, { title: 'DOING', items: [ { title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage celerities gales beams.' }, { title: 'Chic leafy' }, { title: 'Guessed interdum armies chirp writhes most', description: 'Came champlain live leopards twilight whenever warm read wish squirrel rock.', dueDate: '2015-02-04', done: true } ] } ] }); //Custom datepicker $('#todo-lists-demo-datepicker').lobiList({ lists: [ { title: 'TODO', defaultStyle: 'lobilist-info', items: [ { title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' } ] } ], afterListAdd: function(lobilist, list){ var $dueDateInput = list.$el.find('form [name=dueDate]'); $dueDateInput.datepicker(); } }); // Event handling (function () { var list; $('#todo-lists-initialize-btn').click(function () { list = $('#todo-lists-demo-events') .lobiList({ init: function () { Lobibox.notify('default', { msg: 'init' }); }, beforeDestroy: function () { Lobibox.notify('default', { msg: 'beforeDestroy' }); }, afterDestroy: function () { Lobibox.notify('default', { msg: 'afterDestroy' }); }, beforeListAdd: function () { Lobibox.notify('default', { msg: 'beforeListAdd' }); }, afterListAdd: function () { Lobibox.notify('default', { msg: 'afterListAdd' }); }, beforeListRemove: function () { Lobibox.notify('default', { msg: 'beforeListRemove' }); }, afterListRemove: function () { Lobibox.notify('default', { msg: 'afterListRemove' }); }, beforeItemAdd: function () { Lobibox.notify('default', { msg: 'beforeItemAdd' }); }, afterItemAdd: function () { console.log(arguments); Lobibox.notify('default', { msg: 'afterItemAdd' }); }, beforeItemUpdate: function () { Lobibox.notify('default', { msg: 'beforeItemUpdate' }); }, afterItemUpdate: function () { console.log(arguments); Lobibox.notify('default', { msg: 'afterItemUpdate' }); }, beforeItemDelete: function () { Lobibox.notify('default', { msg: 'beforeItemDelete' }); }, afterItemDelete: function () { Lobibox.notify('default', { msg: 'afterItemDelete' }); }, beforeListDrop: function () { Lobibox.notify('default', { msg: 'beforeListDrop' }); }, afterListReorder: function () { Lobibox.notify('default', { msg: 'afterListReorder' }); }, beforeItemDrop: function () { Lobibox.notify('default', { msg: 'beforeItemDrop' }); }, afterItemReorder: function () { Lobibox.notify('default', { msg: 'afterItemReorder' }); }, afterMarkAsDone: function () { Lobibox.notify('default', { msg: 'afterMarkAsDone' }); }, afterMarkAsUndone: function () { Lobibox.notify('default', { msg: 'afterMarkAsUndone' }); }, styleChange: function(list, oldStyle, newStyle){ console.log(arguments); Lobibox.notify('default', { msg: 'styleChange: Old style - "'+oldStyle+'". New style - "'+ newStyle +'"' }); }, titleChange: function(list, oldTitle, newTitle){ console.log(arguments); Lobibox.notify('default', { msg: 'titleChange: Old title - "'+oldTitle+'". New title - "'+ newTitle + '"' }); }, lists: [ { title: 'TODO', defaultStyle: 'lobilist-info', items: [ { title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' }, { title: 'Periods pride', description: 'Accepted was mollis', done: true }, { title: 'Flags better burns pigeon', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank ' + 'treacherously darkling.' }, { title: 'Accepted was mollis', description: 'Rowed cloven frolic thereby, vivamus pining gown intruding strangers prank ' + 'treacherously darkling.', dueDate: '2015-02-02' } ] } ] }) .data('lobiList'); }); $('#todo-lists-destroy-btn').click(function () { list.destroy(); }); })(); // Custom controls $('#todo-lists-demo-controls').lobiList({ lists: [ { title: 'TODO', defaultStyle: 'lobilist-info', controls: ['edit', 'styleChange'], items: [ { title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' } ] }, { title: 'Disabled custom checkboxes', defaultStyle: 'lobilist-danger', controls: ['edit', 'add', 'remove'], useLobicheck: false, items: [ { title: 'Periods pride', description: 'Accepted was mollis', done: true } ] }, { title: 'Controls disabled', controls: false, items: [ { title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. ' + 'Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage ' + 'celerities gales beams.' } ] }, { title: 'Disabled todo edit/remove', enableTodoRemove: false, enableTodoEdit: false, items: [ { title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. ' + 'Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage ' + 'celerities gales beams.' } ] } ] }); // Disabled drag & drop $('#todo-lists-demo-sorting').lobiList({ sortable: false, lists: [ { title: 'TODO', defaultStyle: 'lobilist-info', controls: ['edit', 'styleChange'], items: [ { title: 'Floor cool cinders', description: 'Thunder fulfilled travellers folly, wading, lake.', dueDate: '2015-01-31' } ] }, { title: 'Controls disabled', controls: false, items: [ { title: 'Composed trays', description: 'Hoary rattle exulting suspendisse elit paradises craft wistful. Bayonets allures prefer traits wrongs flushed. Tent wily matched bold polite slab coinage celerities gales beams.' } ] } ] }); $('#actions-by-ajax').lobiList({ actions: { load: 'demo/example1/load.json', insert: 'demo/example1/insert.php', delete: 'demo/example1/delete.php', update: 'demo/example1/update.php' }, afterItemAdd: function(){ console.log(arguments); } }); });
27182812/ChatGLM-LLaMA-chinese-insturct
2,639
src/transformers/tf_utils.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 List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging logger = logging.get_logger(__name__) def shape_list(tensor: Union[tf.Tensor, np.ndarray]) -> List[int]: """ Deal with dynamic shape in tensorflow cleanly. Args: tensor (`tf.Tensor` or `np.ndarray`): The tensor we want the shape of. Returns: `List[int]`: The shape of the tensor as a list. """ if isinstance(tensor, np.ndarray): return list(tensor.shape) dynamic = tf.shape(tensor) if tensor.shape == tf.TensorShape(None): return dynamic static = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(static)] def stable_softmax(logits: tf.Tensor, axis: Optional[int] = None, name: Optional[str] = None) -> tf.Tensor: """ Stable wrapper that returns the same output as `tf.nn.softmax`, but that works reliably with XLA on CPU. It is meant as a workaround for the [following issue](https://github.com/tensorflow/tensorflow/issues/55682), and will be removed after it gets fixed. The arguments and outputs are the same as `tf.nn.softmax`, and relies on the fact that `softmax(x) = softmax(x + c)` (see https://ogunlao.github.io/2020/04/26/you_dont_really_know_softmax.html). Args: logits (`tf.Tensor`): Must be one of the following types: half, float32, float64. axis (`int`, *optional*): The dimension softmax would be performed on. The default is -1 which indicates the last dimension. name (`str`, *optional*): A name for the operation. Returns: `tf.Tensor`: A Tensor. Has the same type and shape as logits. """ # TODO: When the issue linked above gets sorted, add a check on TF version here and use the original function if # it has the fix. After we drop the support for unfixed versions, remove this function. return tf.nn.softmax(logits=logits + 1e-9, axis=axis, name=name)
274056675/springboot-openai-chatgpt
8,739
mng_web/src/store/modules/user.js
import { setToken, setRefreshToken, removeToken, removeRefreshToken, } from "@/util/auth"; import { setStore, getStore } from "@/util/store"; import { isURL, validatenull } from "@/util/validate"; import { deepClone } from "@/util/util"; import website from "@/config/website"; import { Message } from "element-ui"; import { loginByUsername, loginBySocial, getUserInfo, getMenu, getTopMenu, logout, refreshToken, getButtons, } from "@/api/user"; function addPath(ele, first) { const menu = website.menu; const propsConfig = menu.props; const propsDefault = { label: propsConfig.label || "name", path: propsConfig.path || "path", icon: propsConfig.icon || "icon", children: propsConfig.children || "children", }; const icon = ele[propsDefault.icon]; ele[propsDefault.icon] = validatenull(icon) ? menu.iconDefault : icon; const isChild = ele[propsDefault.children] && ele[propsDefault.children].length !== 0; if (!isChild) ele[propsDefault.children] = []; if (!isChild && first && !isURL(ele[propsDefault.path])) { ele[propsDefault.path] = ele[propsDefault.path] + "/index"; } else { ele[propsDefault.children].forEach((child) => { addPath(child); }); } } const user = { state: { userInfo: getStore({ name: "userInfo" }) || [], permission: getStore({ name: "permission" }) || {}, roles: [], menu: getStore({ name: "menu" }) || [], menuAll: [], token: getStore({ name: "token" }) || "", refreshToken: getStore({ name: "refreshToken" }) || "", }, actions: { //根据用户名登录 LoginByUsername({ commit }, userInfo) { return new Promise((resolve, reject) => { loginByUsername( userInfo.tenantId, userInfo.username, userInfo.password, userInfo.type, userInfo.key, userInfo.code ) .then((res) => { const data = res.data; commit("SET_TOKEN", data.data.accessToken); commit("SET_REFRESH_TOKEN", data.data.refreshToken); commit("SET_USER_INFO", data.data); commit("DEL_ALL_TAG"); commit("CLEAR_LOCK"); resolve(); }) .catch((error) => { reject(error); }); }); }, //根据第三方信息登录 LoginBySocial({ commit }, userInfo) { return new Promise((resolve) => { loginBySocial( userInfo.tenantId, userInfo.source, userInfo.code, userInfo.state ).then((res) => { const data = res.data; if (data.success) { commit("SET_TOKEN", data.data.accessToken); commit("SET_REFRESH_TOKEN", data.data.refreshToken); commit("SET_USER_INFO", data.data); commit("DEL_ALL_TAG"); commit("CLEAR_LOCK"); } else { Message({ message: data.msg, type: "error", }); } resolve(); }); }); }, //根据手机号登录 LoginByPhone({ commit }, userInfo) { return new Promise((resolve) => { loginByUsername(userInfo.phone, userInfo.code).then((res) => { const data = res.data.data; commit("SET_TOKEN", data); commit("DEL_ALL_TAG"); commit("CLEAR_LOCK"); resolve(); }); }); }, GetUserInfo({ commit }) { return new Promise((resolve, reject) => { getUserInfo() .then((res) => { const data = res.data.data; commit("SET_ROLES", data.roles); resolve(data); }) .catch((err) => { reject(err); }); }); }, //刷新token RefreshToken({ state, commit }) { return new Promise((resolve, reject) => { refreshToken(state.refreshToken) .then((res) => { const data = res.data; commit("SET_TOKEN", data.data.accessToken); commit("SET_REFRESH_TOKEN", data.data.refreshToken); commit("SET_USER_INFO", data.data); resolve(data); }) .catch((error) => { reject(error); }); }); }, // // 登出 // LogOut({commit}) { // return new Promise((resolve, reject) => { // logout().then(() => { // commit('SET_TOKEN', ''); // commit('SET_REFRESH_TOKEN', ''); // commit('SET_MENU', []) // commit('SET_MENU_ALL', []); // commit('SET_ROLES', []); // commit('DEL_ALL_TAG'); // commit('CLEAR_LOCK'); // removeToken() // removeRefreshToken() // resolve() // }).catch(error => { // reject(error) // }) // }) // }, // 登出 LogOut({ commit }) { return new Promise((resolve, reject) => { try { commit("SET_TOKEN", ""); commit("SET_REFRESH_TOKEN", ""); commit("SET_MENU", []); commit("SET_MENU_ALL", []); commit("SET_ROLES", []); commit("DEL_ALL_TAG"); commit("CLEAR_LOCK"); removeToken(); removeRefreshToken(); resolve(); } catch (error) { reject(error); } }); }, //注销session FedLogOut({ commit }) { return new Promise((resolve) => { commit("SET_TOKEN", ""); commit("SET_REFRESH_TOKEN", ""); commit("SET_MENU", []); commit("SET_MENU_ALL", []); commit("SET_ROLES", []); commit("DEL_ALL_TAG"); commit("CLEAR_LOCK"); removeToken(); removeRefreshToken(); resolve(); }); }, GetTopMenu() { return new Promise((resolve) => { getTopMenu().then((res) => { const data = res.data.data || []; resolve(data); }); }); }, //获取系统菜单 GetMenu({ commit, dispatch }, parentId) { return new Promise((resolve) => { getMenu(parentId).then((res) => { const data = res.data.data; let menu = deepClone(data); menu.forEach((ele) => { addPath(ele, true); }); commit("SET_MENU", menu); commit("SET_MENU_ALL", menu); dispatch("GetButtons"); resolve(menu); }); }); }, GetButtons({ commit }) { return new Promise((resolve) => { getButtons().then((res) => { const data = res.data.data; commit("SET_PERMISSION", data); resolve(); }); }); }, }, mutations: { SET_TOKEN: (state, token) => { setToken(token); state.token = token; setStore({ name: "token", content: state.token, type: "session" }); }, SET_REFRESH_TOKEN: (state, refreshToken) => { setRefreshToken(refreshToken); state.refreshToken = refreshToken; setStore({ name: "refreshToken", content: state.refreshToken }); }, SET_USER_INFO: (state, userInfo) => { state.userInfo = userInfo; setStore({ name: "userInfo", content: state.userInfo }); }, SET_MENU_ALL: (state, menuAll) => { state.menuAll = menuAll; setStore({ name: "menuAll", content: state.menuAll, type: "session" }); }, SET_MENU: (state, menu) => { state.menu = menu; setStore({ name: "menu", content: state.menu, type: "session" }); if (validatenull(menu)) return; //合并动态路由去重 let menuAll = state.menuAll; menuAll = menuAll.concat(menu).reverse(); let newMenu = []; for (let item1 of menuAll) { let flag = true; for (let item2 of newMenu) { if (item1.name === item2.name || item1.path === item2.path) { flag = false; } } if (flag) newMenu.push(item1); } state.menuAll = newMenu; setStore({ name: "menuAll", content: state.menuAll, type: "session" }); }, SET_ROLES: (state, roles) => { state.roles = roles; }, SET_PERMISSION: (state, permission) => { let result = []; function getCode(list) { list.forEach((ele) => { if (typeof ele === "object") { const chiildren = ele.children; const code = ele.code; if (chiildren) { getCode(chiildren); } else { result.push(code); } } }); } getCode(permission); state.permission = {}; result.forEach((ele) => { state.permission[ele] = true; }); setStore({ name: "permission", content: state.permission, type: "session", }); }, }, }; export default user;
274056675/springboot-openai-chatgpt
1,361
mng_web/src/const/user/info.js
export default { tabs: true, tabsActive: 1, group: [ { label: '个人信息', prop: 'info', column: [{ label: '头像', type: 'upload', listType: 'picture-img', propsHttp: { res: 'data', url: 'link', }, canvasOption: { text: 'blade', ratio: 0.1 }, action: '/api/blade-resource/oss/endpoint/put-file', tip: '只能上传jpg/png用户头像,且不超过500kb', span: 12, row: true, prop: 'avatar' }, { label: '姓名', span: 12, row: true, prop: 'name' }, { label: '用户名', span: 12, row: true, prop: 'realName' }, { label: '手机号', span: 12, row: true, prop: 'phone' }, { label: '邮箱', prop: 'email', span: 12, row: true, }] }, { label: '修改密码', prop: 'password', column: [{ label: '原密码', span: 12, row: true, type: 'password', prop: 'oldPassword' }, { label: '新密码', span: 12, row: true, type: 'password', prop: 'newPassword' }, { label: '确认密码', span: 12, row: true, type: 'password', prop: 'newPassword1' }] } ], }
274056675/springboot-openai-chatgpt
2,846
mng_web/src/components/iframe/main.vue
<template> <basic-container> <iframe :src="src" class="iframe" ref="iframe"></iframe> </basic-container> </template> <script> import { mapGetters } from "vuex"; import NProgress from "nprogress"; // progress bar import "nprogress/nprogress.css"; // progress bar style export default { name: "AvueIframe", data() { return { urlPath: this.getUrlPath() //iframe src 路径 }; }, created() { NProgress.configure({ showSpinner: false }); }, mounted() { this.load(); this.resize(); }, props: ["routerPath"], watch: { $route: function() { this.load(); }, routerPath: function() { // 监听routerPath变化,改变src路径 this.urlPath = this.getUrlPath(); } }, computed: { ...mapGetters(["screen"]), src() { return this.$route.query.src ? this.$route.query.src.replace("$", "#") : this.urlPath; } }, methods: { // 显示等待框 show() { NProgress.start(); }, // 隐藏等待狂 hide() { NProgress.done(); }, // 加载浏览器窗口变化自适应 resize() { window.onresize = () => { this.iframeInit(); }; }, // 加载组件 load() { this.show(); var flag = true; //URL是否包含问号 if (this.$route.query.src.indexOf("?") == -1) { flag = false; } var list = []; for (var key in this.$route.query) { if (key != "src" && key != "name" && key != "i18n") { list.push(`${key}= this.$route.query[key]`); } } list = list.join("&").toString(); if (flag) { this.$route.query.src = `${this.$route.query.src}${ list.length > 0 ? `&list` : "" }`; } else { this.$route.query.src = `${this.$route.query.src}${ list.length > 0 ? `?list` : "" }`; } //超时3s自动隐藏等待狂,加强用户体验 let time = 3; const timeFunc = setInterval(() => { time--; if (time == 0) { this.hide(); clearInterval(timeFunc); } }, 1000); this.iframeInit(); }, //iframe窗口初始化 iframeInit() { const iframe = this.$refs.iframe; const clientHeight = document.documentElement.clientHeight - (screen > 1 ? 200 : 130); if (!iframe) return; iframe.style.height = `${clientHeight}px`; if (iframe.attachEvent) { iframe.attachEvent("onload", () => { this.hide(); }); } else { iframe.onload = () => { this.hide(); }; } }, getUrlPath: function() { //获取 iframe src 路径 let url = window.location.href; url = url.replace("/myiframe", ""); return url; } } }; </script> <style lang="scss"> .iframe { width: 100%; height: 100%; border: 0; overflow: hidden; box-sizing: border-box; } </style>
27182812/ChatGLM-LLaMA-chinese-insturct
256,497
src/transformers/__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. # When adding a new object to this init, remember to add it twice: once inside the `_import_structure` dictionary and # once inside the `if TYPE_CHECKING` branch. The `TYPE_CHECKING` should have import statements as usual, but they are # only there for type checking. The `_import_structure` is a dictionary submodule to list of object names, and is used # to defer the actual importing for when the objects are requested. This way `import transformers` provides the names # in the namespace without actually importing anything (and especially none of the backends). __version__ = "4.27.0.dev0" from typing import TYPE_CHECKING # Check the dependencies satisfy the minimal versions required. from . import dependency_versions_check from .utils import ( OptionalDependencyNotAvailable, _LazyModule, is_bitsandbytes_available, is_flax_available, is_keras_nlp_available, is_sentencepiece_available, is_speech_available, is_tensorflow_text_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torchvision_available, is_vision_available, logging, ) logger = logging.get_logger(__name__) # pylint: disable=invalid-name # Base objects, independent of any specific backend _import_structure = { "audio_utils": [], "benchmark": [], "commands": [], "configuration_utils": ["PretrainedConfig"], "convert_graph_to_onnx": [], "convert_slow_tokenizers_checkpoints_to_fast": [], "convert_tf_hub_seq_to_seq_bert_to_pytorch": [], "data": [ "DataProcessor", "InputExample", "InputFeatures", "SingleSentenceClassificationProcessor", "SquadExample", "SquadFeatures", "SquadV1Processor", "SquadV2Processor", "glue_compute_metrics", "glue_convert_examples_to_features", "glue_output_modes", "glue_processors", "glue_tasks_num_labels", "squad_convert_examples_to_features", "xnli_compute_metrics", "xnli_output_modes", "xnli_processors", "xnli_tasks_num_labels", ], "data.data_collator": [ "DataCollator", "DataCollatorForLanguageModeling", "DataCollatorForPermutationLanguageModeling", "DataCollatorForSeq2Seq", "DataCollatorForSOP", "DataCollatorForTokenClassification", "DataCollatorForWholeWordMask", "DataCollatorWithPadding", "DefaultDataCollator", "default_data_collator", ], "data.metrics": [], "data.processors": [], "debug_utils": [], "dependency_versions_check": [], "dependency_versions_table": [], "dynamic_module_utils": [], "feature_extraction_sequence_utils": ["SequenceFeatureExtractor"], "feature_extraction_utils": ["BatchFeature", "FeatureExtractionMixin"], "file_utils": [], "generation": ["GenerationConfig"], "hf_argparser": ["HfArgumentParser"], "image_transforms": [], "integrations": [ "is_clearml_available", "is_comet_available", "is_neptune_available", "is_optuna_available", "is_ray_available", "is_ray_tune_available", "is_sigopt_available", "is_tensorboard_available", "is_wandb_available", ], "modelcard": ["ModelCard"], "modeling_tf_pytorch_utils": [ "convert_tf_weight_name_to_pt_weight_name", "load_pytorch_checkpoint_in_tf2_model", "load_pytorch_model_in_tf2_model", "load_pytorch_weights_in_tf2_model", "load_tf2_checkpoint_in_pytorch_model", "load_tf2_model_in_pytorch_model", "load_tf2_weights_in_pytorch_model", ], "models": [], # Models "models.albert": ["ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlbertConfig"], "models.align": [ "ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlignConfig", "AlignProcessor", "AlignTextConfig", "AlignVisionConfig", ], "models.altclip": [ "ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "AltCLIPConfig", "AltCLIPProcessor", "AltCLIPTextConfig", "AltCLIPVisionConfig", ], "models.audio_spectrogram_transformer": [ "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ASTConfig", ], "models.auto": [ "ALL_PRETRAINED_CONFIG_ARCHIVE_MAP", "CONFIG_MAPPING", "FEATURE_EXTRACTOR_MAPPING", "IMAGE_PROCESSOR_MAPPING", "MODEL_NAMES_MAPPING", "PROCESSOR_MAPPING", "TOKENIZER_MAPPING", "AutoConfig", "AutoFeatureExtractor", "AutoImageProcessor", "AutoProcessor", "AutoTokenizer", ], "models.bart": ["BartConfig", "BartTokenizer"], "models.barthez": [], "models.bartpho": [], "models.beit": ["BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BeitConfig"], "models.bert": [ "BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BasicTokenizer", "BertConfig", "BertTokenizer", "WordpieceTokenizer", ], "models.bert_generation": ["BertGenerationConfig"], "models.bert_japanese": ["BertJapaneseTokenizer", "CharacterTokenizer", "MecabTokenizer"], "models.bertweet": ["BertweetTokenizer"], "models.big_bird": ["BIG_BIRD_PRETRAINED_CONFIG_ARCHIVE_MAP", "BigBirdConfig"], "models.bigbird_pegasus": [ "BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP", "BigBirdPegasusConfig", ], "models.biogpt": ["BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BioGptConfig", "BioGptTokenizer"], "models.bit": ["BIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BitConfig"], "models.blenderbot": ["BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotTokenizer"], "models.blenderbot_small": [ "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotSmallConfig", "BlenderbotSmallTokenizer", ], "models.blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipProcessor", "BlipTextConfig", "BlipVisionConfig", ], "models.blip_2": [ "BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Blip2Config", "Blip2Processor", "Blip2QFormerConfig", "Blip2VisionConfig", ], "models.bloom": ["BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP", "BloomConfig"], "models.bort": [], "models.bridgetower": [ "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP", "BridgeTowerConfig", "BridgeTowerProcessor", "BridgeTowerTextConfig", "BridgeTowerVisionConfig", ], "models.byt5": ["ByT5Tokenizer"], "models.camembert": ["CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CamembertConfig"], "models.canine": ["CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP", "CanineConfig", "CanineTokenizer"], "models.chinese_clip": [ "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "ChineseCLIPConfig", "ChineseCLIPProcessor", "ChineseCLIPTextConfig", "ChineseCLIPVisionConfig", ], "models.clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapProcessor", "ClapTextConfig", ], "models.clip": [ "CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPConfig", "CLIPProcessor", "CLIPTextConfig", "CLIPTokenizer", "CLIPVisionConfig", ], "models.clipseg": [ "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPSegConfig", "CLIPSegProcessor", "CLIPSegTextConfig", "CLIPSegVisionConfig", ], "models.codegen": ["CODEGEN_PRETRAINED_CONFIG_ARCHIVE_MAP", "CodeGenConfig", "CodeGenTokenizer"], "models.conditional_detr": ["CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig"], "models.convbert": ["CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvBertConfig", "ConvBertTokenizer"], "models.convnext": ["CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvNextConfig"], "models.cpm": [], "models.ctrl": ["CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP", "CTRLConfig", "CTRLTokenizer"], "models.cvt": ["CVT_PRETRAINED_CONFIG_ARCHIVE_MAP", "CvtConfig"], "models.data2vec": [ "DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP", "Data2VecAudioConfig", "Data2VecTextConfig", "Data2VecVisionConfig", ], "models.deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaTokenizer"], "models.deberta_v2": ["DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaV2Config"], "models.decision_transformer": ["DECISION_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "DecisionTransformerConfig"], "models.deformable_detr": ["DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeformableDetrConfig"], "models.deit": ["DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DeiTConfig"], "models.deta": ["DETA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DetaConfig"], "models.detr": ["DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DetrConfig"], "models.dialogpt": [], "models.dinat": ["DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DinatConfig"], "models.distilbert": ["DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DistilBertConfig", "DistilBertTokenizer"], "models.dit": [], "models.donut": ["DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP", "DonutProcessor", "DonutSwinConfig"], "models.dpr": [ "DPR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPRConfig", "DPRContextEncoderTokenizer", "DPRQuestionEncoderTokenizer", "DPRReaderOutput", "DPRReaderTokenizer", ], "models.dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"], "models.efficientformer": ["EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig"], "models.efficientnet": ["EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientNetConfig"], "models.electra": ["ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP", "ElectraConfig", "ElectraTokenizer"], "models.encoder_decoder": ["EncoderDecoderConfig"], "models.ernie": [ "ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", ], "models.ernie_m": ["ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieMConfig"], "models.esm": ["ESM_PRETRAINED_CONFIG_ARCHIVE_MAP", "EsmConfig", "EsmTokenizer"], "models.flaubert": ["FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "FlaubertConfig", "FlaubertTokenizer"], "models.flava": [ "FLAVA_PRETRAINED_CONFIG_ARCHIVE_MAP", "FlavaConfig", "FlavaImageCodebookConfig", "FlavaImageConfig", "FlavaMultimodalConfig", "FlavaTextConfig", ], "models.fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"], "models.fsmt": ["FSMT_PRETRAINED_CONFIG_ARCHIVE_MAP", "FSMTConfig", "FSMTTokenizer"], "models.funnel": ["FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP", "FunnelConfig", "FunnelTokenizer"], "models.git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitProcessor", "GitVisionConfig"], "models.glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"], "models.gpt2": ["GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPT2Config", "GPT2Tokenizer"], "models.gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig"], "models.gpt_neox": ["GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXConfig"], "models.gpt_neox_japanese": ["GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoXJapaneseConfig"], "models.gpt_sw3": [], "models.gptj": ["GPTJ_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTJConfig"], "models.gptsan_japanese": [ "GPTSAN_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTSanJapaneseConfig", "GPTSanJapaneseTokenizer", ], "models.graphormer": ["GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "GraphormerConfig"], "models.groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], "models.herbert": ["HerbertTokenizer"], "models.hubert": ["HUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "HubertConfig"], "models.ibert": ["IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "IBertConfig"], "models.imagegpt": ["IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ImageGPTConfig"], "models.jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxTokenizer", "JukeboxVQVAEConfig", ], "models.layoutlm": ["LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMConfig", "LayoutLMTokenizer"], "models.layoutlmv2": [ "LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv2Config", "LayoutLMv2FeatureExtractor", "LayoutLMv2ImageProcessor", "LayoutLMv2Processor", "LayoutLMv2Tokenizer", ], "models.layoutlmv3": [ "LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv3Config", "LayoutLMv3FeatureExtractor", "LayoutLMv3ImageProcessor", "LayoutLMv3Processor", "LayoutLMv3Tokenizer", ], "models.layoutxlm": ["LayoutXLMProcessor"], "models.led": ["LED_PRETRAINED_CONFIG_ARCHIVE_MAP", "LEDConfig", "LEDTokenizer"], "models.levit": ["LEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LevitConfig"], "models.lilt": ["LILT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LiltConfig"], "models.llama": ["LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP", "LlamaConfig"], "models.longformer": ["LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongformerConfig", "LongformerTokenizer"], "models.longt5": ["LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongT5Config"], "models.luke": ["LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP", "LukeConfig", "LukeTokenizer"], "models.lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig", "LxmertTokenizer"], "models.m2m_100": ["M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP", "M2M100Config"], "models.marian": ["MarianConfig"], "models.markuplm": [ "MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "MarkupLMConfig", "MarkupLMFeatureExtractor", "MarkupLMProcessor", "MarkupLMTokenizer", ], "models.mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], "models.maskformer": ["MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "MaskFormerConfig", "MaskFormerSwinConfig"], "models.mbart": ["MBartConfig"], "models.mbart50": [], "models.mctct": ["MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MCTCTConfig", "MCTCTProcessor"], "models.megatron_bert": ["MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegatronBertConfig"], "models.megatron_gpt2": [], "models.mluke": [], "models.mmbt": ["MMBTConfig"], "models.mobilebert": ["MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileBertConfig", "MobileBertTokenizer"], "models.mobilenet_v1": ["MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV1Config"], "models.mobilenet_v2": ["MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileNetV2Config"], "models.mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig"], "models.mpnet": ["MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "MPNetConfig", "MPNetTokenizer"], "models.mt5": ["MT5Config"], "models.mvp": ["MvpConfig", "MvpTokenizer"], "models.nat": ["NAT_PRETRAINED_CONFIG_ARCHIVE_MAP", "NatConfig"], "models.nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"], "models.nllb": [], "models.nystromformer": [ "NYSTROMFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "NystromformerConfig", ], "models.oneformer": ["ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "OneFormerConfig", "OneFormerProcessor"], "models.openai": ["OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OpenAIGPTConfig", "OpenAIGPTTokenizer"], "models.opt": ["OPTConfig"], "models.owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTProcessor", "OwlViTTextConfig", "OwlViTVisionConfig", ], "models.pegasus": ["PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP", "PegasusConfig", "PegasusTokenizer"], "models.pegasus_x": ["PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP", "PegasusXConfig"], "models.perceiver": ["PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP", "PerceiverConfig", "PerceiverTokenizer"], "models.phobert": ["PhobertTokenizer"], "models.plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"], "models.poolformer": ["POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "PoolFormerConfig"], "models.prophetnet": ["PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ProphetNetConfig", "ProphetNetTokenizer"], "models.qdqbert": ["QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "QDQBertConfig"], "models.rag": ["RagConfig", "RagRetriever", "RagTokenizer"], "models.realm": ["REALM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RealmConfig", "RealmTokenizer"], "models.reformer": ["REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ReformerConfig"], "models.regnet": ["REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "RegNetConfig"], "models.rembert": ["REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RemBertConfig"], "models.resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig"], "models.retribert": ["RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RetriBertConfig", "RetriBertTokenizer"], "models.roberta": ["ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaConfig", "RobertaTokenizer"], "models.roberta_prelayernorm": ["ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP", "RobertaPreLayerNormConfig"], "models.roc_bert": ["ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoCBertConfig", "RoCBertTokenizer"], "models.roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerTokenizer"], "models.segformer": ["SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SegformerConfig"], "models.sew": ["SEW_PRETRAINED_CONFIG_ARCHIVE_MAP", "SEWConfig"], "models.sew_d": ["SEW_D_PRETRAINED_CONFIG_ARCHIVE_MAP", "SEWDConfig"], "models.speech_encoder_decoder": ["SpeechEncoderDecoderConfig"], "models.speech_to_text": [ "SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig", "Speech2TextProcessor", ], "models.speech_to_text_2": [ "SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2Text2Config", "Speech2Text2Processor", "Speech2Text2Tokenizer", ], "models.speecht5": [ "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP", "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP", "SpeechT5Config", "SpeechT5HifiGanConfig", "SpeechT5Processor", ], "models.splinter": ["SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP", "SplinterConfig", "SplinterTokenizer"], "models.squeezebert": ["SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "SqueezeBertConfig", "SqueezeBertTokenizer"], "models.swin": ["SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP", "SwinConfig"], "models.swin2sr": ["SWIN2SR_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swin2SRConfig"], "models.swinv2": ["SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swinv2Config"], "models.switch_transformers": ["SWITCH_TRANSFORMERS_PRETRAINED_CONFIG_ARCHIVE_MAP", "SwitchTransformersConfig"], "models.t5": ["T5_PRETRAINED_CONFIG_ARCHIVE_MAP", "T5Config"], "models.table_transformer": ["TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TableTransformerConfig"], "models.tapas": ["TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP", "TapasConfig", "TapasTokenizer"], "models.tapex": ["TapexTokenizer"], "models.time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], "models.timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"], "models.trajectory_transformer": [ "TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrajectoryTransformerConfig", ], "models.transfo_xl": [ "TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "TransfoXLConfig", "TransfoXLCorpus", "TransfoXLTokenizer", ], "models.trocr": [ "TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig", "TrOCRProcessor", ], "models.tvlt": [ "TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP", "TvltConfig", "TvltProcessor", ], "models.unispeech": [ "UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechConfig", ], "models.unispeech_sat": [ "UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP", "UniSpeechSatConfig", ], "models.upernet": ["UperNetConfig"], "models.van": ["VAN_PRETRAINED_CONFIG_ARCHIVE_MAP", "VanConfig"], "models.videomae": ["VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "VideoMAEConfig"], "models.vilt": [ "VILT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViltConfig", "ViltFeatureExtractor", "ViltImageProcessor", "ViltProcessor", ], "models.vision_encoder_decoder": ["VisionEncoderDecoderConfig"], "models.vision_text_dual_encoder": ["VisionTextDualEncoderConfig", "VisionTextDualEncoderProcessor"], "models.visual_bert": ["VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "VisualBertConfig"], "models.vit": ["VIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTConfig"], "models.vit_hybrid": ["VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTHybridConfig"], "models.vit_mae": ["VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMAEConfig"], "models.vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"], "models.wav2vec2": [ "WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2Config", "Wav2Vec2CTCTokenizer", "Wav2Vec2FeatureExtractor", "Wav2Vec2Processor", "Wav2Vec2Tokenizer", ], "models.wav2vec2_conformer": [ "WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Wav2Vec2ConformerConfig", ], "models.wav2vec2_phoneme": ["Wav2Vec2PhonemeCTCTokenizer"], "models.wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"], "models.wavlm": [ "WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig", ], "models.whisper": [ "WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP", "WhisperConfig", "WhisperFeatureExtractor", "WhisperProcessor", "WhisperTokenizer", ], "models.x_clip": [ "XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "XCLIPConfig", "XCLIPProcessor", "XCLIPTextConfig", "XCLIPVisionConfig", ], "models.xglm": ["XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XGLMConfig"], "models.xlm": ["XLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMConfig", "XLMTokenizer"], "models.xlm_prophetnet": ["XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMProphetNetConfig"], "models.xlm_roberta": ["XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaConfig"], "models.xlm_roberta_xl": ["XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMRobertaXLConfig"], "models.xlnet": ["XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLNetConfig"], "models.xmod": ["XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP", "XmodConfig"], "models.yolos": ["YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP", "YolosConfig"], "models.yoso": ["YOSO_PRETRAINED_CONFIG_ARCHIVE_MAP", "YosoConfig"], "onnx": [], "pipelines": [ "AudioClassificationPipeline", "AutomaticSpeechRecognitionPipeline", "Conversation", "ConversationalPipeline", "CsvPipelineDataFormat", "DepthEstimationPipeline", "DocumentQuestionAnsweringPipeline", "FeatureExtractionPipeline", "FillMaskPipeline", "ImageClassificationPipeline", "ImageSegmentationPipeline", "ImageToTextPipeline", "JsonPipelineDataFormat", "NerPipeline", "ObjectDetectionPipeline", "PipedPipelineDataFormat", "Pipeline", "PipelineDataFormat", "QuestionAnsweringPipeline", "SummarizationPipeline", "TableQuestionAnsweringPipeline", "Text2TextGenerationPipeline", "TextClassificationPipeline", "TextGenerationPipeline", "TokenClassificationPipeline", "TranslationPipeline", "VideoClassificationPipeline", "VisualQuestionAnsweringPipeline", "ZeroShotAudioClassificationPipeline", "ZeroShotClassificationPipeline", "ZeroShotImageClassificationPipeline", "ZeroShotObjectDetectionPipeline", "pipeline", ], "processing_utils": ["ProcessorMixin"], "testing_utils": [], "tokenization_utils": ["PreTrainedTokenizer"], "tokenization_utils_base": [ "AddedToken", "BatchEncoding", "CharSpan", "PreTrainedTokenizerBase", "SpecialTokensMixin", "TokenSpan", ], "trainer_callback": [ "DefaultFlowCallback", "EarlyStoppingCallback", "PrinterCallback", "ProgressCallback", "TrainerCallback", "TrainerControl", "TrainerState", ], "trainer_utils": ["EvalPrediction", "IntervalStrategy", "SchedulerType", "enable_full_determinism", "set_seed"], "training_args": ["TrainingArguments"], "training_args_seq2seq": ["Seq2SeqTrainingArguments"], "training_args_tf": ["TFTrainingArguments"], "utils": [ "CONFIG_NAME", "MODEL_CARD_NAME", "PYTORCH_PRETRAINED_BERT_CACHE", "PYTORCH_TRANSFORMERS_CACHE", "SPIECE_UNDERLINE", "TF2_WEIGHTS_NAME", "TF_WEIGHTS_NAME", "TRANSFORMERS_CACHE", "WEIGHTS_NAME", "TensorType", "add_end_docstrings", "add_start_docstrings", "is_apex_available", "is_bitsandbytes_available", "is_datasets_available", "is_decord_available", "is_faiss_available", "is_flax_available", "is_keras_nlp_available", "is_phonemizer_available", "is_psutil_available", "is_py3nvml_available", "is_pyctcdecode_available", "is_safetensors_available", "is_scipy_available", "is_sentencepiece_available", "is_sklearn_available", "is_speech_available", "is_tensorflow_text_available", "is_tf_available", "is_timm_available", "is_tokenizers_available", "is_torch_available", "is_torch_neuroncore_available", "is_torch_tpu_available", "is_torchvision_available", "is_vision_available", "logging", ], "utils.bitsandbytes": [], "utils.quantization_config": ["BitsAndBytesConfig"], } # sentencepiece-backed objects try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_sentencepiece_objects _import_structure["utils.dummy_sentencepiece_objects"] = [ name for name in dir(dummy_sentencepiece_objects) if not name.startswith("_") ] else: _import_structure["models.albert"].append("AlbertTokenizer") _import_structure["models.barthez"].append("BarthezTokenizer") _import_structure["models.bartpho"].append("BartphoTokenizer") _import_structure["models.bert_generation"].append("BertGenerationTokenizer") _import_structure["models.big_bird"].append("BigBirdTokenizer") _import_structure["models.camembert"].append("CamembertTokenizer") _import_structure["models.cpm"].append("CpmTokenizer") _import_structure["models.deberta_v2"].append("DebertaV2Tokenizer") _import_structure["models.ernie_m"].append("ErnieMTokenizer") _import_structure["models.fnet"].append("FNetTokenizer") _import_structure["models.gpt_sw3"].append("GPTSw3Tokenizer") _import_structure["models.layoutxlm"].append("LayoutXLMTokenizer") _import_structure["models.llama"].append("LlamaTokenizer") _import_structure["models.m2m_100"].append("M2M100Tokenizer") _import_structure["models.marian"].append("MarianTokenizer") _import_structure["models.mbart"].append("MBartTokenizer") _import_structure["models.mbart50"].append("MBart50Tokenizer") _import_structure["models.mluke"].append("MLukeTokenizer") _import_structure["models.mt5"].append("MT5Tokenizer") _import_structure["models.nllb"].append("NllbTokenizer") _import_structure["models.pegasus"].append("PegasusTokenizer") _import_structure["models.plbart"].append("PLBartTokenizer") _import_structure["models.reformer"].append("ReformerTokenizer") _import_structure["models.rembert"].append("RemBertTokenizer") _import_structure["models.speech_to_text"].append("Speech2TextTokenizer") _import_structure["models.speecht5"].append("SpeechT5Tokenizer") _import_structure["models.t5"].append("T5Tokenizer") _import_structure["models.xglm"].append("XGLMTokenizer") _import_structure["models.xlm_prophetnet"].append("XLMProphetNetTokenizer") _import_structure["models.xlm_roberta"].append("XLMRobertaTokenizer") _import_structure["models.xlnet"].append("XLNetTokenizer") # tokenizers-backed objects try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_tokenizers_objects _import_structure["utils.dummy_tokenizers_objects"] = [ name for name in dir(dummy_tokenizers_objects) if not name.startswith("_") ] else: # Fast tokenizers structure _import_structure["models.albert"].append("AlbertTokenizerFast") _import_structure["models.bart"].append("BartTokenizerFast") _import_structure["models.barthez"].append("BarthezTokenizerFast") _import_structure["models.bert"].append("BertTokenizerFast") _import_structure["models.big_bird"].append("BigBirdTokenizerFast") _import_structure["models.blenderbot"].append("BlenderbotTokenizerFast") _import_structure["models.blenderbot_small"].append("BlenderbotSmallTokenizerFast") _import_structure["models.bloom"].append("BloomTokenizerFast") _import_structure["models.camembert"].append("CamembertTokenizerFast") _import_structure["models.clip"].append("CLIPTokenizerFast") _import_structure["models.codegen"].append("CodeGenTokenizerFast") _import_structure["models.convbert"].append("ConvBertTokenizerFast") _import_structure["models.cpm"].append("CpmTokenizerFast") _import_structure["models.deberta"].append("DebertaTokenizerFast") _import_structure["models.deberta_v2"].append("DebertaV2TokenizerFast") _import_structure["models.distilbert"].append("DistilBertTokenizerFast") _import_structure["models.dpr"].extend( ["DPRContextEncoderTokenizerFast", "DPRQuestionEncoderTokenizerFast", "DPRReaderTokenizerFast"] ) _import_structure["models.electra"].append("ElectraTokenizerFast") _import_structure["models.fnet"].append("FNetTokenizerFast") _import_structure["models.funnel"].append("FunnelTokenizerFast") _import_structure["models.gpt2"].append("GPT2TokenizerFast") _import_structure["models.gpt_neox"].append("GPTNeoXTokenizerFast") _import_structure["models.gpt_neox_japanese"].append("GPTNeoXJapaneseTokenizer") _import_structure["models.herbert"].append("HerbertTokenizerFast") _import_structure["models.layoutlm"].append("LayoutLMTokenizerFast") _import_structure["models.layoutlmv2"].append("LayoutLMv2TokenizerFast") _import_structure["models.layoutlmv3"].append("LayoutLMv3TokenizerFast") _import_structure["models.layoutxlm"].append("LayoutXLMTokenizerFast") _import_structure["models.led"].append("LEDTokenizerFast") _import_structure["models.longformer"].append("LongformerTokenizerFast") _import_structure["models.lxmert"].append("LxmertTokenizerFast") _import_structure["models.markuplm"].append("MarkupLMTokenizerFast") _import_structure["models.mbart"].append("MBartTokenizerFast") _import_structure["models.mbart50"].append("MBart50TokenizerFast") _import_structure["models.mobilebert"].append("MobileBertTokenizerFast") _import_structure["models.mpnet"].append("MPNetTokenizerFast") _import_structure["models.mt5"].append("MT5TokenizerFast") _import_structure["models.mvp"].append("MvpTokenizerFast") _import_structure["models.nllb"].append("NllbTokenizerFast") _import_structure["models.openai"].append("OpenAIGPTTokenizerFast") _import_structure["models.pegasus"].append("PegasusTokenizerFast") _import_structure["models.realm"].append("RealmTokenizerFast") _import_structure["models.reformer"].append("ReformerTokenizerFast") _import_structure["models.rembert"].append("RemBertTokenizerFast") _import_structure["models.retribert"].append("RetriBertTokenizerFast") _import_structure["models.roberta"].append("RobertaTokenizerFast") _import_structure["models.roformer"].append("RoFormerTokenizerFast") _import_structure["models.splinter"].append("SplinterTokenizerFast") _import_structure["models.squeezebert"].append("SqueezeBertTokenizerFast") _import_structure["models.t5"].append("T5TokenizerFast") _import_structure["models.whisper"].append("WhisperTokenizerFast") _import_structure["models.xglm"].append("XGLMTokenizerFast") _import_structure["models.xlm_roberta"].append("XLMRobertaTokenizerFast") _import_structure["models.xlnet"].append("XLNetTokenizerFast") _import_structure["tokenization_utils_fast"] = ["PreTrainedTokenizerFast"] try: if not (is_sentencepiece_available() and is_tokenizers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_sentencepiece_and_tokenizers_objects _import_structure["utils.dummy_sentencepiece_and_tokenizers_objects"] = [ name for name in dir(dummy_sentencepiece_and_tokenizers_objects) if not name.startswith("_") ] else: _import_structure["convert_slow_tokenizer"] = ["SLOW_TO_FAST_CONVERTERS", "convert_slow_tokenizer"] # Speech-specific objects try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_speech_objects _import_structure["utils.dummy_speech_objects"] = [ name for name in dir(dummy_speech_objects) if not name.startswith("_") ] else: _import_structure["models.audio_spectrogram_transformer"].append("ASTFeatureExtractor") _import_structure["models.mctct"].append("MCTCTFeatureExtractor") _import_structure["models.speech_to_text"].append("Speech2TextFeatureExtractor") _import_structure["models.speecht5"].append("SpeechT5FeatureExtractor") _import_structure["models.tvlt"].append("TvltFeatureExtractor") # Tensorflow-text-specific objects try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_tensorflow_text_objects _import_structure["utils.dummy_tensorflow_text_objects"] = [ name for name in dir(dummy_tensorflow_text_objects) if not name.startswith("_") ] else: _import_structure["models.bert"].append("TFBertTokenizer") # keras-nlp-specific objects try: if not is_keras_nlp_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_keras_nlp_objects _import_structure["utils.dummy_keras_nlp_objects"] = [ name for name in dir(dummy_keras_nlp_objects) if not name.startswith("_") ] else: _import_structure["models.gpt2"].append("TFGPT2Tokenizer") # Vision-specific objects try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_vision_objects _import_structure["utils.dummy_vision_objects"] = [ name for name in dir(dummy_vision_objects) if not name.startswith("_") ] else: _import_structure["image_processing_utils"] = ["ImageProcessingMixin"] _import_structure["image_utils"] = ["ImageFeatureExtractionMixin"] _import_structure["models.beit"].extend(["BeitFeatureExtractor", "BeitImageProcessor"]) _import_structure["models.bit"].extend(["BitImageProcessor"]) _import_structure["models.blip"].extend(["BlipImageProcessor"]) _import_structure["models.bridgetower"].append("BridgeTowerImageProcessor") _import_structure["models.chinese_clip"].extend(["ChineseCLIPFeatureExtractor", "ChineseCLIPImageProcessor"]) _import_structure["models.clip"].extend(["CLIPFeatureExtractor", "CLIPImageProcessor"]) _import_structure["models.conditional_detr"].extend( ["ConditionalDetrFeatureExtractor", "ConditionalDetrImageProcessor"] ) _import_structure["models.convnext"].extend(["ConvNextFeatureExtractor", "ConvNextImageProcessor"]) _import_structure["models.deformable_detr"].extend( ["DeformableDetrFeatureExtractor", "DeformableDetrImageProcessor"] ) _import_structure["models.deit"].extend(["DeiTFeatureExtractor", "DeiTImageProcessor"]) _import_structure["models.deta"].append("DetaImageProcessor") _import_structure["models.detr"].extend(["DetrFeatureExtractor", "DetrImageProcessor"]) _import_structure["models.donut"].extend(["DonutFeatureExtractor", "DonutImageProcessor"]) _import_structure["models.dpt"].extend(["DPTFeatureExtractor", "DPTImageProcessor"]) _import_structure["models.efficientformer"].append("EfficientFormerImageProcessor") _import_structure["models.efficientnet"].append("EfficientNetImageProcessor") _import_structure["models.flava"].extend(["FlavaFeatureExtractor", "FlavaImageProcessor", "FlavaProcessor"]) _import_structure["models.glpn"].extend(["GLPNFeatureExtractor", "GLPNImageProcessor"]) _import_structure["models.imagegpt"].extend(["ImageGPTFeatureExtractor", "ImageGPTImageProcessor"]) _import_structure["models.layoutlmv2"].extend(["LayoutLMv2FeatureExtractor", "LayoutLMv2ImageProcessor"]) _import_structure["models.layoutlmv3"].extend(["LayoutLMv3FeatureExtractor", "LayoutLMv3ImageProcessor"]) _import_structure["models.levit"].extend(["LevitFeatureExtractor", "LevitImageProcessor"]) _import_structure["models.mask2former"].append("Mask2FormerImageProcessor") _import_structure["models.maskformer"].extend(["MaskFormerFeatureExtractor", "MaskFormerImageProcessor"]) _import_structure["models.mobilenet_v1"].extend(["MobileNetV1FeatureExtractor", "MobileNetV1ImageProcessor"]) _import_structure["models.mobilenet_v2"].extend(["MobileNetV2FeatureExtractor", "MobileNetV2ImageProcessor"]) _import_structure["models.mobilevit"].extend(["MobileViTFeatureExtractor", "MobileViTImageProcessor"]) _import_structure["models.oneformer"].extend(["OneFormerImageProcessor"]) _import_structure["models.owlvit"].extend(["OwlViTFeatureExtractor", "OwlViTImageProcessor"]) _import_structure["models.perceiver"].extend(["PerceiverFeatureExtractor", "PerceiverImageProcessor"]) _import_structure["models.poolformer"].extend(["PoolFormerFeatureExtractor", "PoolFormerImageProcessor"]) _import_structure["models.segformer"].extend(["SegformerFeatureExtractor", "SegformerImageProcessor"]) _import_structure["models.swin2sr"].append("Swin2SRImageProcessor") _import_structure["models.tvlt"].append("TvltImageProcessor") _import_structure["models.videomae"].extend(["VideoMAEFeatureExtractor", "VideoMAEImageProcessor"]) _import_structure["models.vilt"].extend(["ViltFeatureExtractor", "ViltImageProcessor", "ViltProcessor"]) _import_structure["models.vit"].extend(["ViTFeatureExtractor", "ViTImageProcessor"]) _import_structure["models.vit_hybrid"].extend(["ViTHybridImageProcessor"]) _import_structure["models.yolos"].extend(["YolosFeatureExtractor", "YolosImageProcessor"]) # Timm-backed objects try: if not (is_timm_available() and is_vision_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_timm_and_vision_objects _import_structure["utils.dummy_timm_and_vision_objects"] = [ name for name in dir(dummy_timm_and_vision_objects) if not name.startswith("_") ] else: _import_structure["models.deformable_detr"].extend( [ "DEFORMABLE_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "DeformableDetrForObjectDetection", "DeformableDetrModel", "DeformableDetrPreTrainedModel", ] ) _import_structure["models.detr"].extend( [ "DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "DetrForObjectDetection", "DetrForSegmentation", "DetrModel", "DetrPreTrainedModel", ] ) _import_structure["models.table_transformer"].extend( [ "TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TableTransformerForObjectDetection", "TableTransformerModel", "TableTransformerPreTrainedModel", ] ) _import_structure["models.conditional_detr"].extend( [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] ) # PyTorch-backed objects try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_pt_objects _import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")] else: _import_structure["activations"] = [] _import_structure["benchmark.benchmark"] = ["PyTorchBenchmark"] _import_structure["benchmark.benchmark_args"] = ["PyTorchBenchmarkArguments"] _import_structure["data.datasets"] = [ "GlueDataset", "GlueDataTrainingArguments", "LineByLineTextDataset", "LineByLineWithRefDataset", "LineByLineWithSOPTextDataset", "SquadDataset", "SquadDataTrainingArguments", "TextDataset", "TextDatasetForNextSentencePrediction", ] _import_structure["deepspeed"] = [] _import_structure["generation"].extend( [ "BeamScorer", "BeamSearchScorer", "ConstrainedBeamSearchScorer", "Constraint", "ConstraintListState", "DisjunctiveConstraint", "ForcedBOSTokenLogitsProcessor", "ForcedEOSTokenLogitsProcessor", "GenerationMixin", "HammingDiversityLogitsProcessor", "InfNanRemoveLogitsProcessor", "LogitsProcessor", "LogitsProcessorList", "LogitsWarper", "MaxLengthCriteria", "MaxTimeCriteria", "MinLengthLogitsProcessor", "MinNewTokensLengthLogitsProcessor", "NoBadWordsLogitsProcessor", "NoRepeatNGramLogitsProcessor", "PhrasalConstraint", "PrefixConstrainedLogitsProcessor", "RepetitionPenaltyLogitsProcessor", "StoppingCriteria", "StoppingCriteriaList", "TemperatureLogitsWarper", "TopKLogitsWarper", "TopPLogitsWarper", "TypicalLogitsWarper", "top_k_top_p_filtering", ] ) _import_structure["generation_utils"] = [] _import_structure["modeling_outputs"] = [] _import_structure["modeling_utils"] = ["PreTrainedModel"] # PyTorch models structure _import_structure["models.albert"].extend( [ "ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "AlbertForMaskedLM", "AlbertForMultipleChoice", "AlbertForPreTraining", "AlbertForQuestionAnswering", "AlbertForSequenceClassification", "AlbertForTokenClassification", "AlbertModel", "AlbertPreTrainedModel", "load_tf_weights_in_albert", ] ) _import_structure["models.align"].extend( [ "ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST", "AlignModel", "AlignPreTrainedModel", "AlignTextModel", "AlignVisionModel", ] ) _import_structure["models.altclip"].extend( [ "ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "AltCLIPModel", "AltCLIPPreTrainedModel", "AltCLIPTextModel", "AltCLIPVisionModel", ] ) _import_structure["models.audio_spectrogram_transformer"].extend( [ "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ASTForAudioClassification", "ASTModel", "ASTPreTrainedModel", ] ) _import_structure["models.auto"].extend( [ "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING", "MODEL_FOR_AUDIO_XVECTOR_MAPPING", "MODEL_FOR_BACKBONE_MAPPING", "MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING", "MODEL_FOR_CAUSAL_LM_MAPPING", "MODEL_FOR_CTC_MAPPING", "MODEL_FOR_DEPTH_ESTIMATION_MAPPING", "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING", "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING", "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING", "MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING", "MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING", "MODEL_FOR_MASKED_LM_MAPPING", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING", "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", "MODEL_FOR_OBJECT_DETECTION_MAPPING", "MODEL_FOR_PRETRAINING_MAPPING", "MODEL_FOR_QUESTION_ANSWERING_MAPPING", "MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING", "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", "MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING", "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING", "MODEL_FOR_VISION_2_SEQ_MAPPING", "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING", "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING", "MODEL_MAPPING", "MODEL_WITH_LM_HEAD_MAPPING", "AutoBackbone", "AutoModel", "AutoModelForAudioClassification", "AutoModelForAudioFrameClassification", "AutoModelForAudioXVector", "AutoModelForCausalLM", "AutoModelForCTC", "AutoModelForDepthEstimation", "AutoModelForDocumentQuestionAnswering", "AutoModelForImageClassification", "AutoModelForImageSegmentation", "AutoModelForInstanceSegmentation", "AutoModelForMaskedImageModeling", "AutoModelForMaskedLM", "AutoModelForMultipleChoice", "AutoModelForNextSentencePrediction", "AutoModelForObjectDetection", "AutoModelForPreTraining", "AutoModelForQuestionAnswering", "AutoModelForSemanticSegmentation", "AutoModelForSeq2SeqLM", "AutoModelForSequenceClassification", "AutoModelForSpeechSeq2Seq", "AutoModelForTableQuestionAnswering", "AutoModelForTokenClassification", "AutoModelForUniversalSegmentation", "AutoModelForVideoClassification", "AutoModelForVision2Seq", "AutoModelForVisualQuestionAnswering", "AutoModelForZeroShotObjectDetection", "AutoModelWithLMHead", ] ) _import_structure["models.bart"].extend( [ "BART_PRETRAINED_MODEL_ARCHIVE_LIST", "BartForCausalLM", "BartForConditionalGeneration", "BartForQuestionAnswering", "BartForSequenceClassification", "BartModel", "BartPretrainedModel", "PretrainedBartModel", ] ) _import_structure["models.beit"].extend( [ "BEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "BeitForImageClassification", "BeitForMaskedImageModeling", "BeitForSemanticSegmentation", "BeitModel", "BeitPreTrainedModel", ] ) _import_structure["models.bert"].extend( [ "BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "BertForMaskedLM", "BertForMultipleChoice", "BertForNextSentencePrediction", "BertForPreTraining", "BertForQuestionAnswering", "BertForSequenceClassification", "BertForTokenClassification", "BertLayer", "BertLMHeadModel", "BertModel", "BertPreTrainedModel", "load_tf_weights_in_bert", ] ) _import_structure["models.bert_generation"].extend( [ "BertGenerationDecoder", "BertGenerationEncoder", "BertGenerationPreTrainedModel", "load_tf_weights_in_bert_generation", ] ) _import_structure["models.big_bird"].extend( [ "BIG_BIRD_PRETRAINED_MODEL_ARCHIVE_LIST", "BigBirdForCausalLM", "BigBirdForMaskedLM", "BigBirdForMultipleChoice", "BigBirdForPreTraining", "BigBirdForQuestionAnswering", "BigBirdForSequenceClassification", "BigBirdForTokenClassification", "BigBirdLayer", "BigBirdModel", "BigBirdPreTrainedModel", "load_tf_weights_in_big_bird", ] ) _import_structure["models.bigbird_pegasus"].extend( [ "BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST", "BigBirdPegasusForCausalLM", "BigBirdPegasusForConditionalGeneration", "BigBirdPegasusForQuestionAnswering", "BigBirdPegasusForSequenceClassification", "BigBirdPegasusModel", "BigBirdPegasusPreTrainedModel", ] ) _import_structure["models.biogpt"].extend( [ "BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST", "BioGptForCausalLM", "BioGptModel", "BioGptPreTrainedModel", ] ) _import_structure["models.bit"].extend( [ "BIT_PRETRAINED_MODEL_ARCHIVE_LIST", "BitBackbone", "BitForImageClassification", "BitModel", "BitPreTrainedModel", ] ) _import_structure["models.blenderbot"].extend( [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] ) _import_structure["models.blenderbot_small"].extend( [ "BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotSmallForCausalLM", "BlenderbotSmallForConditionalGeneration", "BlenderbotSmallModel", "BlenderbotSmallPreTrainedModel", ] ) _import_structure["models.blip"].extend( [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipForConditionalGeneration", "BlipForImageTextRetrieval", "BlipForQuestionAnswering", "BlipModel", "BlipPreTrainedModel", "BlipTextModel", "BlipVisionModel", ] ) _import_structure["models.blip_2"].extend( [ "BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Blip2ForConditionalGeneration", "Blip2Model", "Blip2PreTrainedModel", "Blip2QFormerModel", "Blip2VisionModel", ] ) _import_structure["models.bloom"].extend( [ "BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST", "BloomForCausalLM", "BloomForQuestionAnswering", "BloomForSequenceClassification", "BloomForTokenClassification", "BloomModel", "BloomPreTrainedModel", ] ) _import_structure["models.bridgetower"].extend( [ "BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST", "BridgeTowerForImageAndTextRetrieval", "BridgeTowerForMaskedLM", "BridgeTowerModel", "BridgeTowerPreTrainedModel", ] ) _import_structure["models.camembert"].extend( [ "CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "CamembertForCausalLM", "CamembertForMaskedLM", "CamembertForMultipleChoice", "CamembertForQuestionAnswering", "CamembertForSequenceClassification", "CamembertForTokenClassification", "CamembertModel", "CamembertPreTrainedModel", ] ) _import_structure["models.canine"].extend( [ "CANINE_PRETRAINED_MODEL_ARCHIVE_LIST", "CanineForMultipleChoice", "CanineForQuestionAnswering", "CanineForSequenceClassification", "CanineForTokenClassification", "CanineLayer", "CanineModel", "CaninePreTrainedModel", "load_tf_weights_in_canine", ] ) _import_structure["models.chinese_clip"].extend( [ "CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "ChineseCLIPModel", "ChineseCLIPPreTrainedModel", "ChineseCLIPTextModel", "ChineseCLIPVisionModel", ] ) _import_structure["models.clap"].extend( [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioModel", "ClapAudioModelWithProjection", "ClapFeatureExtractor", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", ] ) _import_structure["models.clip"].extend( [ "CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPModel", "CLIPPreTrainedModel", "CLIPTextModel", "CLIPTextModelWithProjection", "CLIPVisionModel", "CLIPVisionModelWithProjection", ] ) _import_structure["models.clipseg"].extend( [ "CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPSegForImageSegmentation", "CLIPSegModel", "CLIPSegPreTrainedModel", "CLIPSegTextModel", "CLIPSegVisionModel", ] ) _import_structure["models.codegen"].extend( [ "CODEGEN_PRETRAINED_MODEL_ARCHIVE_LIST", "CodeGenForCausalLM", "CodeGenModel", "CodeGenPreTrainedModel", ] ) _import_structure["models.convbert"].extend( [ "CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvBertForMaskedLM", "ConvBertForMultipleChoice", "ConvBertForQuestionAnswering", "ConvBertForSequenceClassification", "ConvBertForTokenClassification", "ConvBertLayer", "ConvBertModel", "ConvBertPreTrainedModel", "load_tf_weights_in_convbert", ] ) _import_structure["models.convnext"].extend( [ "CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvNextBackbone", "ConvNextForImageClassification", "ConvNextModel", "ConvNextPreTrainedModel", ] ) _import_structure["models.ctrl"].extend( [ "CTRL_PRETRAINED_MODEL_ARCHIVE_LIST", "CTRLForSequenceClassification", "CTRLLMHeadModel", "CTRLModel", "CTRLPreTrainedModel", ] ) _import_structure["models.cvt"].extend( [ "CVT_PRETRAINED_MODEL_ARCHIVE_LIST", "CvtForImageClassification", "CvtModel", "CvtPreTrainedModel", ] ) _import_structure["models.data2vec"].extend( [ "DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST", "DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST", "Data2VecAudioForAudioFrameClassification", "Data2VecAudioForCTC", "Data2VecAudioForSequenceClassification", "Data2VecAudioForXVector", "Data2VecAudioModel", "Data2VecAudioPreTrainedModel", "Data2VecTextForCausalLM", "Data2VecTextForMaskedLM", "Data2VecTextForMultipleChoice", "Data2VecTextForQuestionAnswering", "Data2VecTextForSequenceClassification", "Data2VecTextForTokenClassification", "Data2VecTextModel", "Data2VecTextPreTrainedModel", "Data2VecVisionForImageClassification", "Data2VecVisionForSemanticSegmentation", "Data2VecVisionModel", "Data2VecVisionPreTrainedModel", ] ) _import_structure["models.deberta"].extend( [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] ) _import_structure["models.deberta_v2"].extend( [ "DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaV2ForMaskedLM", "DebertaV2ForMultipleChoice", "DebertaV2ForQuestionAnswering", "DebertaV2ForSequenceClassification", "DebertaV2ForTokenClassification", "DebertaV2Model", "DebertaV2PreTrainedModel", ] ) _import_structure["models.decision_transformer"].extend( [ "DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "DecisionTransformerGPT2Model", "DecisionTransformerGPT2PreTrainedModel", "DecisionTransformerModel", "DecisionTransformerPreTrainedModel", ] ) _import_structure["models.deit"].extend( [ "DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "DeiTForImageClassification", "DeiTForImageClassificationWithTeacher", "DeiTForMaskedImageModeling", "DeiTModel", "DeiTPreTrainedModel", ] ) _import_structure["models.deta"].extend( [ "DETA_PRETRAINED_MODEL_ARCHIVE_LIST", "DetaForObjectDetection", "DetaModel", "DetaPreTrainedModel", ] ) _import_structure["models.dinat"].extend( [ "DINAT_PRETRAINED_MODEL_ARCHIVE_LIST", "DinatBackbone", "DinatForImageClassification", "DinatModel", "DinatPreTrainedModel", ] ) _import_structure["models.distilbert"].extend( [ "DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "DistilBertForMaskedLM", "DistilBertForMultipleChoice", "DistilBertForQuestionAnswering", "DistilBertForSequenceClassification", "DistilBertForTokenClassification", "DistilBertModel", "DistilBertPreTrainedModel", ] ) _import_structure["models.donut"].extend( [ "DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST", "DonutSwinModel", "DonutSwinPreTrainedModel", ] ) _import_structure["models.dpr"].extend( [ "DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST", "DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST", "DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST", "DPRContextEncoder", "DPRPretrainedContextEncoder", "DPRPreTrainedModel", "DPRPretrainedQuestionEncoder", "DPRPretrainedReader", "DPRQuestionEncoder", "DPRReader", ] ) _import_structure["models.dpt"].extend( [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] ) _import_structure["models.efficientformer"].extend( [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] ) _import_structure["models.efficientnet"].extend( [ "EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientNetForImageClassification", "EfficientNetModel", "EfficientNetPreTrainedModel", ] ) _import_structure["models.electra"].extend( [ "ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST", "ElectraForCausalLM", "ElectraForMaskedLM", "ElectraForMultipleChoice", "ElectraForPreTraining", "ElectraForQuestionAnswering", "ElectraForSequenceClassification", "ElectraForTokenClassification", "ElectraModel", "ElectraPreTrainedModel", "load_tf_weights_in_electra", ] ) _import_structure["models.encoder_decoder"].append("EncoderDecoderModel") _import_structure["models.ernie"].extend( [ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] ) _import_structure["models.ernie_m"].extend( [ "ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieMForInformationExtraction", "ErnieMForMultipleChoice", "ErnieMForQuestionAnswering", "ErnieMForSequenceClassification", "ErnieMForTokenClassification", "ErnieMModel", "ErnieMPreTrainedModel", ] ) _import_structure["models.esm"].extend( [ "ESM_PRETRAINED_MODEL_ARCHIVE_LIST", "EsmFoldPreTrainedModel", "EsmForMaskedLM", "EsmForProteinFolding", "EsmForSequenceClassification", "EsmForTokenClassification", "EsmModel", "EsmPreTrainedModel", ] ) _import_structure["models.flaubert"].extend( [ "FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaubertForMultipleChoice", "FlaubertForQuestionAnswering", "FlaubertForQuestionAnsweringSimple", "FlaubertForSequenceClassification", "FlaubertForTokenClassification", "FlaubertModel", "FlaubertPreTrainedModel", "FlaubertWithLMHeadModel", ] ) _import_structure["models.flava"].extend( [ "FLAVA_PRETRAINED_MODEL_ARCHIVE_LIST", "FlavaForPreTraining", "FlavaImageCodebook", "FlavaImageModel", "FlavaModel", "FlavaMultimodalModel", "FlavaPreTrainedModel", "FlavaTextModel", ] ) _import_structure["models.fnet"].extend( [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] ) _import_structure["models.fsmt"].extend(["FSMTForConditionalGeneration", "FSMTModel", "PretrainedFSMTModel"]) _import_structure["models.funnel"].extend( [ "FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "FunnelBaseModel", "FunnelForMaskedLM", "FunnelForMultipleChoice", "FunnelForPreTraining", "FunnelForQuestionAnswering", "FunnelForSequenceClassification", "FunnelForTokenClassification", "FunnelModel", "FunnelPreTrainedModel", "load_tf_weights_in_funnel", ] ) _import_structure["models.git"].extend( [ "GIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GitForCausalLM", "GitModel", "GitPreTrainedModel", "GitVisionModel", ] ) _import_structure["models.glpn"].extend( [ "GLPN_PRETRAINED_MODEL_ARCHIVE_LIST", "GLPNForDepthEstimation", "GLPNModel", "GLPNPreTrainedModel", ] ) _import_structure["models.gpt2"].extend( [ "GPT2_PRETRAINED_MODEL_ARCHIVE_LIST", "GPT2DoubleHeadsModel", "GPT2ForSequenceClassification", "GPT2ForTokenClassification", "GPT2LMHeadModel", "GPT2Model", "GPT2PreTrainedModel", "load_tf_weights_in_gpt2", ] ) _import_structure["models.gpt_neo"].extend( [ "GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoForCausalLM", "GPTNeoForSequenceClassification", "GPTNeoModel", "GPTNeoPreTrainedModel", "load_tf_weights_in_gpt_neo", ] ) _import_structure["models.gpt_neox"].extend( [ "GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXForCausalLM", "GPTNeoXLayer", "GPTNeoXModel", "GPTNeoXPreTrainedModel", ] ) _import_structure["models.gpt_neox_japanese"].extend( [ "GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoXJapaneseForCausalLM", "GPTNeoXJapaneseLayer", "GPTNeoXJapaneseModel", "GPTNeoXJapanesePreTrainedModel", ] ) _import_structure["models.gptj"].extend( [ "GPTJ_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTJForCausalLM", "GPTJForQuestionAnswering", "GPTJForSequenceClassification", "GPTJModel", "GPTJPreTrainedModel", ] ) _import_structure["models.gptsan_japanese"].extend( [ "GPTSAN_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTSanJapaneseForConditionalGeneration", "GPTSanJapaneseModel", "GPTSanJapanesePreTrainedModel", ] ) _import_structure["models.graphormer"].extend( [ "GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "GraphormerForGraphClassification", "GraphormerModel", "GraphormerPreTrainedModel", ] ) _import_structure["models.groupvit"].extend( [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] ) _import_structure["models.hubert"].extend( [ "HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "HubertForCTC", "HubertForSequenceClassification", "HubertModel", "HubertPreTrainedModel", ] ) _import_structure["models.ibert"].extend( [ "IBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "IBertForMaskedLM", "IBertForMultipleChoice", "IBertForQuestionAnswering", "IBertForSequenceClassification", "IBertForTokenClassification", "IBertModel", "IBertPreTrainedModel", ] ) _import_structure["models.imagegpt"].extend( [ "IMAGEGPT_PRETRAINED_MODEL_ARCHIVE_LIST", "ImageGPTForCausalImageModeling", "ImageGPTForImageClassification", "ImageGPTModel", "ImageGPTPreTrainedModel", "load_tf_weights_in_imagegpt", ] ) _import_structure["models.jukebox"].extend( [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxPrior", "JukeboxVQVAE", ] ) _import_structure["models.layoutlm"].extend( [ "LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMForMaskedLM", "LayoutLMForQuestionAnswering", "LayoutLMForSequenceClassification", "LayoutLMForTokenClassification", "LayoutLMModel", "LayoutLMPreTrainedModel", ] ) _import_structure["models.layoutlmv2"].extend( [ "LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv2ForQuestionAnswering", "LayoutLMv2ForSequenceClassification", "LayoutLMv2ForTokenClassification", "LayoutLMv2Model", "LayoutLMv2PreTrainedModel", ] ) _import_structure["models.layoutlmv3"].extend( [ "LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv3ForQuestionAnswering", "LayoutLMv3ForSequenceClassification", "LayoutLMv3ForTokenClassification", "LayoutLMv3Model", "LayoutLMv3PreTrainedModel", ] ) _import_structure["models.led"].extend( [ "LED_PRETRAINED_MODEL_ARCHIVE_LIST", "LEDForConditionalGeneration", "LEDForQuestionAnswering", "LEDForSequenceClassification", "LEDModel", "LEDPreTrainedModel", ] ) _import_structure["models.levit"].extend( [ "LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "LevitForImageClassification", "LevitForImageClassificationWithTeacher", "LevitModel", "LevitPreTrainedModel", ] ) _import_structure["models.lilt"].extend( [ "LILT_PRETRAINED_MODEL_ARCHIVE_LIST", "LiltForQuestionAnswering", "LiltForSequenceClassification", "LiltForTokenClassification", "LiltModel", "LiltPreTrainedModel", ] ) _import_structure["models.llama"].extend( [ "LlamaForCausalLM", "LlamaModel", "LlamaPreTrainedModel", ] ) _import_structure["models.longformer"].extend( [ "LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "LongformerForMaskedLM", "LongformerForMultipleChoice", "LongformerForQuestionAnswering", "LongformerForSequenceClassification", "LongformerForTokenClassification", "LongformerModel", "LongformerPreTrainedModel", "LongformerSelfAttention", ] ) _import_structure["models.longt5"].extend( [ "LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST", "LongT5EncoderModel", "LongT5ForConditionalGeneration", "LongT5Model", "LongT5PreTrainedModel", ] ) _import_structure["models.luke"].extend( [ "LUKE_PRETRAINED_MODEL_ARCHIVE_LIST", "LukeForEntityClassification", "LukeForEntityPairClassification", "LukeForEntitySpanClassification", "LukeForMaskedLM", "LukeForMultipleChoice", "LukeForQuestionAnswering", "LukeForSequenceClassification", "LukeForTokenClassification", "LukeModel", "LukePreTrainedModel", ] ) _import_structure["models.lxmert"].extend( [ "LxmertEncoder", "LxmertForPreTraining", "LxmertForQuestionAnswering", "LxmertModel", "LxmertPreTrainedModel", "LxmertVisualFeatureEncoder", "LxmertXLayer", ] ) _import_structure["models.m2m_100"].extend( [ "M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST", "M2M100ForConditionalGeneration", "M2M100Model", "M2M100PreTrainedModel", ] ) _import_structure["models.marian"].extend(["MarianForCausalLM", "MarianModel", "MarianMTModel"]) _import_structure["models.markuplm"].extend( [ "MARKUPLM_PRETRAINED_MODEL_ARCHIVE_LIST", "MarkupLMForQuestionAnswering", "MarkupLMForSequenceClassification", "MarkupLMForTokenClassification", "MarkupLMModel", "MarkupLMPreTrainedModel", ] ) _import_structure["models.mask2former"].extend( [ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] ) _import_structure["models.maskformer"].extend( [ "MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "MaskFormerForInstanceSegmentation", "MaskFormerModel", "MaskFormerPreTrainedModel", "MaskFormerSwinBackbone", ] ) _import_structure["models.mbart"].extend( [ "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] ) _import_structure["models.mctct"].extend( [ "MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST", "MCTCTForCTC", "MCTCTModel", "MCTCTPreTrainedModel", ] ) _import_structure["models.megatron_bert"].extend( [ "MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "MegatronBertForCausalLM", "MegatronBertForMaskedLM", "MegatronBertForMultipleChoice", "MegatronBertForNextSentencePrediction", "MegatronBertForPreTraining", "MegatronBertForQuestionAnswering", "MegatronBertForSequenceClassification", "MegatronBertForTokenClassification", "MegatronBertModel", "MegatronBertPreTrainedModel", ] ) _import_structure["models.mmbt"].extend(["MMBTForClassification", "MMBTModel", "ModalEmbeddings"]) _import_structure["models.mobilebert"].extend( [ "MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileBertForMaskedLM", "MobileBertForMultipleChoice", "MobileBertForNextSentencePrediction", "MobileBertForPreTraining", "MobileBertForQuestionAnswering", "MobileBertForSequenceClassification", "MobileBertForTokenClassification", "MobileBertLayer", "MobileBertModel", "MobileBertPreTrainedModel", "load_tf_weights_in_mobilebert", ] ) _import_structure["models.mobilenet_v1"].extend( [ "MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV1ForImageClassification", "MobileNetV1Model", "MobileNetV1PreTrainedModel", "load_tf_weights_in_mobilenet_v1", ] ) _import_structure["models.mobilenet_v2"].extend( [ "MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileNetV2ForImageClassification", "MobileNetV2ForSemanticSegmentation", "MobileNetV2Model", "MobileNetV2PreTrainedModel", "load_tf_weights_in_mobilenet_v2", ] ) _import_structure["models.mobilevit"].extend( [ "MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileViTForImageClassification", "MobileViTForSemanticSegmentation", "MobileViTModel", "MobileViTPreTrainedModel", ] ) _import_structure["models.mpnet"].extend( [ "MPNET_PRETRAINED_MODEL_ARCHIVE_LIST", "MPNetForMaskedLM", "MPNetForMultipleChoice", "MPNetForQuestionAnswering", "MPNetForSequenceClassification", "MPNetForTokenClassification", "MPNetLayer", "MPNetModel", "MPNetPreTrainedModel", ] ) _import_structure["models.mt5"].extend( ["MT5EncoderModel", "MT5ForConditionalGeneration", "MT5Model", "MT5PreTrainedModel"] ) _import_structure["models.mvp"].extend( [ "MVP_PRETRAINED_MODEL_ARCHIVE_LIST", "MvpForCausalLM", "MvpForConditionalGeneration", "MvpForQuestionAnswering", "MvpForSequenceClassification", "MvpModel", "MvpPreTrainedModel", ] ) _import_structure["models.nat"].extend( [ "NAT_PRETRAINED_MODEL_ARCHIVE_LIST", "NatBackbone", "NatForImageClassification", "NatModel", "NatPreTrainedModel", ] ) _import_structure["models.nezha"].extend( [ "NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST", "NezhaForMaskedLM", "NezhaForMultipleChoice", "NezhaForNextSentencePrediction", "NezhaForPreTraining", "NezhaForQuestionAnswering", "NezhaForSequenceClassification", "NezhaForTokenClassification", "NezhaModel", "NezhaPreTrainedModel", ] ) _import_structure["models.nystromformer"].extend( [ "NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "NystromformerForMaskedLM", "NystromformerForMultipleChoice", "NystromformerForQuestionAnswering", "NystromformerForSequenceClassification", "NystromformerForTokenClassification", "NystromformerLayer", "NystromformerModel", "NystromformerPreTrainedModel", ] ) _import_structure["models.oneformer"].extend( [ "ONEFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "OneFormerForUniversalSegmentation", "OneFormerModel", "OneFormerPreTrainedModel", ] ) _import_structure["models.openai"].extend( [ "OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST", "OpenAIGPTDoubleHeadsModel", "OpenAIGPTForSequenceClassification", "OpenAIGPTLMHeadModel", "OpenAIGPTModel", "OpenAIGPTPreTrainedModel", "load_tf_weights_in_openai_gpt", ] ) _import_structure["models.opt"].extend( [ "OPT_PRETRAINED_MODEL_ARCHIVE_LIST", "OPTForCausalLM", "OPTForQuestionAnswering", "OPTForSequenceClassification", "OPTModel", "OPTPreTrainedModel", ] ) _import_structure["models.owlvit"].extend( [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTForObjectDetection", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", ] ) _import_structure["models.pegasus"].extend( ["PegasusForCausalLM", "PegasusForConditionalGeneration", "PegasusModel", "PegasusPreTrainedModel"] ) _import_structure["models.pegasus_x"].extend( [ "PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST", "PegasusXForConditionalGeneration", "PegasusXModel", "PegasusXPreTrainedModel", ] ) _import_structure["models.perceiver"].extend( [ "PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST", "PerceiverForImageClassificationConvProcessing", "PerceiverForImageClassificationFourier", "PerceiverForImageClassificationLearned", "PerceiverForMaskedLM", "PerceiverForMultimodalAutoencoding", "PerceiverForOpticalFlow", "PerceiverForSequenceClassification", "PerceiverLayer", "PerceiverModel", "PerceiverPreTrainedModel", ] ) _import_structure["models.plbart"].extend( [ "PLBART_PRETRAINED_MODEL_ARCHIVE_LIST", "PLBartForCausalLM", "PLBartForConditionalGeneration", "PLBartForSequenceClassification", "PLBartModel", "PLBartPreTrainedModel", ] ) _import_structure["models.poolformer"].extend( [ "POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "PoolFormerForImageClassification", "PoolFormerModel", "PoolFormerPreTrainedModel", ] ) _import_structure["models.prophetnet"].extend( [ "PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ProphetNetDecoder", "ProphetNetEncoder", "ProphetNetForCausalLM", "ProphetNetForConditionalGeneration", "ProphetNetModel", "ProphetNetPreTrainedModel", ] ) _import_structure["models.qdqbert"].extend( [ "QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "QDQBertForMaskedLM", "QDQBertForMultipleChoice", "QDQBertForNextSentencePrediction", "QDQBertForQuestionAnswering", "QDQBertForSequenceClassification", "QDQBertForTokenClassification", "QDQBertLayer", "QDQBertLMHeadModel", "QDQBertModel", "QDQBertPreTrainedModel", "load_tf_weights_in_qdqbert", ] ) _import_structure["models.rag"].extend( ["RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration"] ) _import_structure["models.realm"].extend( [ "REALM_PRETRAINED_MODEL_ARCHIVE_LIST", "RealmEmbedder", "RealmForOpenQA", "RealmKnowledgeAugEncoder", "RealmPreTrainedModel", "RealmReader", "RealmRetriever", "RealmScorer", "load_tf_weights_in_realm", ] ) _import_structure["models.reformer"].extend( [ "REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ReformerAttention", "ReformerForMaskedLM", "ReformerForQuestionAnswering", "ReformerForSequenceClassification", "ReformerLayer", "ReformerModel", "ReformerModelWithLMHead", "ReformerPreTrainedModel", ] ) _import_structure["models.regnet"].extend( [ "REGNET_PRETRAINED_MODEL_ARCHIVE_LIST", "RegNetForImageClassification", "RegNetModel", "RegNetPreTrainedModel", ] ) _import_structure["models.rembert"].extend( [ "REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RemBertForCausalLM", "RemBertForMaskedLM", "RemBertForMultipleChoice", "RemBertForQuestionAnswering", "RemBertForSequenceClassification", "RemBertForTokenClassification", "RemBertLayer", "RemBertModel", "RemBertPreTrainedModel", "load_tf_weights_in_rembert", ] ) _import_structure["models.resnet"].extend( [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetBackbone", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", ] ) _import_structure["models.retribert"].extend( ["RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RetriBertModel", "RetriBertPreTrainedModel"] ) _import_structure["models.roberta"].extend( [ "ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaForCausalLM", "RobertaForMaskedLM", "RobertaForMultipleChoice", "RobertaForQuestionAnswering", "RobertaForSequenceClassification", "RobertaForTokenClassification", "RobertaModel", "RobertaPreTrainedModel", ] ) _import_structure["models.roberta_prelayernorm"].extend( [ "ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "RobertaPreLayerNormForCausalLM", "RobertaPreLayerNormForMaskedLM", "RobertaPreLayerNormForMultipleChoice", "RobertaPreLayerNormForQuestionAnswering", "RobertaPreLayerNormForSequenceClassification", "RobertaPreLayerNormForTokenClassification", "RobertaPreLayerNormModel", "RobertaPreLayerNormPreTrainedModel", ] ) _import_structure["models.roc_bert"].extend( [ "ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RoCBertForCausalLM", "RoCBertForMaskedLM", "RoCBertForMultipleChoice", "RoCBertForPreTraining", "RoCBertForQuestionAnswering", "RoCBertForSequenceClassification", "RoCBertForTokenClassification", "RoCBertLayer", "RoCBertModel", "RoCBertPreTrainedModel", "load_tf_weights_in_roc_bert", ] ) _import_structure["models.roformer"].extend( [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] ) _import_structure["models.segformer"].extend( [ "SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "SegformerDecodeHead", "SegformerForImageClassification", "SegformerForSemanticSegmentation", "SegformerLayer", "SegformerModel", "SegformerPreTrainedModel", ] ) _import_structure["models.sew"].extend( [ "SEW_PRETRAINED_MODEL_ARCHIVE_LIST", "SEWForCTC", "SEWForSequenceClassification", "SEWModel", "SEWPreTrainedModel", ] ) _import_structure["models.sew_d"].extend( [ "SEW_D_PRETRAINED_MODEL_ARCHIVE_LIST", "SEWDForCTC", "SEWDForSequenceClassification", "SEWDModel", "SEWDPreTrainedModel", ] ) _import_structure["models.speech_encoder_decoder"].extend(["SpeechEncoderDecoderModel"]) _import_structure["models.speech_to_text"].extend( [ "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Speech2TextForConditionalGeneration", "Speech2TextModel", "Speech2TextPreTrainedModel", ] ) _import_structure["models.speech_to_text_2"].extend(["Speech2Text2ForCausalLM", "Speech2Text2PreTrainedModel"]) _import_structure["models.speecht5"].extend( [ "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST", "SpeechT5ForSpeechToSpeech", "SpeechT5ForSpeechToText", "SpeechT5ForTextToSpeech", "SpeechT5HifiGan", "SpeechT5Model", "SpeechT5PreTrainedModel", ] ) _import_structure["models.splinter"].extend( [ "SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST", "SplinterForPreTraining", "SplinterForQuestionAnswering", "SplinterLayer", "SplinterModel", "SplinterPreTrainedModel", ] ) _import_structure["models.squeezebert"].extend( [ "SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "SqueezeBertForMaskedLM", "SqueezeBertForMultipleChoice", "SqueezeBertForQuestionAnswering", "SqueezeBertForSequenceClassification", "SqueezeBertForTokenClassification", "SqueezeBertModel", "SqueezeBertModule", "SqueezeBertPreTrainedModel", ] ) _import_structure["models.swin"].extend( [ "SWIN_PRETRAINED_MODEL_ARCHIVE_LIST", "SwinBackbone", "SwinForImageClassification", "SwinForMaskedImageModeling", "SwinModel", "SwinPreTrainedModel", ] ) _import_structure["models.swin2sr"].extend( [ "SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST", "Swin2SRForImageSuperResolution", "Swin2SRModel", "Swin2SRPreTrainedModel", ] ) _import_structure["models.swinv2"].extend( [ "SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST", "Swinv2ForImageClassification", "Swinv2ForMaskedImageModeling", "Swinv2Model", "Swinv2PreTrainedModel", ] ) _import_structure["models.switch_transformers"].extend( [ "SWITCH_TRANSFORMERS_PRETRAINED_MODEL_ARCHIVE_LIST", "SwitchTransformersEncoderModel", "SwitchTransformersForConditionalGeneration", "SwitchTransformersModel", "SwitchTransformersPreTrainedModel", "SwitchTransformersSparseMLP", "SwitchTransformersTop1Router", ] ) _import_structure["models.t5"].extend( [ "T5_PRETRAINED_MODEL_ARCHIVE_LIST", "T5EncoderModel", "T5ForConditionalGeneration", "T5Model", "T5PreTrainedModel", "load_tf_weights_in_t5", ] ) _import_structure["models.tapas"].extend( [ "TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST", "TapasForMaskedLM", "TapasForQuestionAnswering", "TapasForSequenceClassification", "TapasModel", "TapasPreTrainedModel", "load_tf_weights_in_tapas", ] ) _import_structure["models.time_series_transformer"].extend( [ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] ) _import_structure["models.timesformer"].extend( [ "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimesformerForVideoClassification", "TimesformerModel", "TimesformerPreTrainedModel", ] ) _import_structure["models.trajectory_transformer"].extend( [ "TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TrajectoryTransformerModel", "TrajectoryTransformerPreTrainedModel", ] ) _import_structure["models.transfo_xl"].extend( [ "TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "AdaptiveEmbedding", "TransfoXLForSequenceClassification", "TransfoXLLMHeadModel", "TransfoXLModel", "TransfoXLPreTrainedModel", "load_tf_weights_in_transfo_xl", ] ) _import_structure["models.trocr"].extend( ["TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel"] ) _import_structure["models.tvlt"].extend( [ "TVLT_PRETRAINED_MODEL_ARCHIVE_LIST", "TvltForAudioVisualClassification", "TvltForPreTraining", "TvltModel", "TvltPreTrainedModel", ] ) _import_structure["models.unispeech"].extend( [ "UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechForCTC", "UniSpeechForPreTraining", "UniSpeechForSequenceClassification", "UniSpeechModel", "UniSpeechPreTrainedModel", ] ) _import_structure["models.unispeech_sat"].extend( [ "UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST", "UniSpeechSatForAudioFrameClassification", "UniSpeechSatForCTC", "UniSpeechSatForPreTraining", "UniSpeechSatForSequenceClassification", "UniSpeechSatForXVector", "UniSpeechSatModel", "UniSpeechSatPreTrainedModel", ] ) _import_structure["models.upernet"].extend( [ "UperNetForSemanticSegmentation", "UperNetPreTrainedModel", ] ) _import_structure["models.van"].extend( [ "VAN_PRETRAINED_MODEL_ARCHIVE_LIST", "VanForImageClassification", "VanModel", "VanPreTrainedModel", ] ) _import_structure["models.videomae"].extend( [ "VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST", "VideoMAEForPreTraining", "VideoMAEForVideoClassification", "VideoMAEModel", "VideoMAEPreTrainedModel", ] ) _import_structure["models.vilt"].extend( [ "VILT_PRETRAINED_MODEL_ARCHIVE_LIST", "ViltForImageAndTextRetrieval", "ViltForImagesAndTextClassification", "ViltForMaskedLM", "ViltForQuestionAnswering", "ViltForTokenClassification", "ViltLayer", "ViltModel", "ViltPreTrainedModel", ] ) _import_structure["models.vision_encoder_decoder"].extend(["VisionEncoderDecoderModel"]) _import_structure["models.vision_text_dual_encoder"].extend(["VisionTextDualEncoderModel"]) _import_structure["models.visual_bert"].extend( [ "VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "VisualBertForMultipleChoice", "VisualBertForPreTraining", "VisualBertForQuestionAnswering", "VisualBertForRegionToPhraseAlignment", "VisualBertForVisualReasoning", "VisualBertLayer", "VisualBertModel", "VisualBertPreTrainedModel", ] ) _import_structure["models.vit"].extend( [ "VIT_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTForImageClassification", "ViTForMaskedImageModeling", "ViTModel", "ViTPreTrainedModel", ] ) _import_structure["models.vit_hybrid"].extend( [ "VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTHybridForImageClassification", "ViTHybridModel", "ViTHybridPreTrainedModel", ] ) _import_structure["models.vit_mae"].extend( [ "VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMAEForPreTraining", "ViTMAELayer", "ViTMAEModel", "ViTMAEPreTrainedModel", ] ) _import_structure["models.vit_msn"].extend( [ "VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMSNForImageClassification", "ViTMSNModel", "ViTMSNPreTrainedModel", ] ) _import_structure["models.wav2vec2"].extend( [ "WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ForAudioFrameClassification", "Wav2Vec2ForCTC", "Wav2Vec2ForMaskedLM", "Wav2Vec2ForPreTraining", "Wav2Vec2ForSequenceClassification", "Wav2Vec2ForXVector", "Wav2Vec2Model", "Wav2Vec2PreTrainedModel", ] ) _import_structure["models.wav2vec2_conformer"].extend( [ "WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Wav2Vec2ConformerForAudioFrameClassification", "Wav2Vec2ConformerForCTC", "Wav2Vec2ConformerForPreTraining", "Wav2Vec2ConformerForSequenceClassification", "Wav2Vec2ConformerForXVector", "Wav2Vec2ConformerModel", "Wav2Vec2ConformerPreTrainedModel", ] ) _import_structure["models.wavlm"].extend( [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] ) _import_structure["models.whisper"].extend( [ "WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST", "WhisperForConditionalGeneration", "WhisperModel", "WhisperPreTrainedModel", ] ) _import_structure["models.x_clip"].extend( [ "XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "XCLIPModel", "XCLIPPreTrainedModel", "XCLIPTextModel", "XCLIPVisionModel", ] ) _import_structure["models.xglm"].extend( [ "XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel", ] ) _import_structure["models.xlm"].extend( [ "XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMForMultipleChoice", "XLMForQuestionAnswering", "XLMForQuestionAnsweringSimple", "XLMForSequenceClassification", "XLMForTokenClassification", "XLMModel", "XLMPreTrainedModel", "XLMWithLMHeadModel", ] ) _import_structure["models.xlm_prophetnet"].extend( [ "XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMProphetNetDecoder", "XLMProphetNetEncoder", "XLMProphetNetForCausalLM", "XLMProphetNetForConditionalGeneration", "XLMProphetNetModel", "XLMProphetNetPreTrainedModel", ] ) _import_structure["models.xlm_roberta"].extend( [ "XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMRobertaForCausalLM", "XLMRobertaForMaskedLM", "XLMRobertaForMultipleChoice", "XLMRobertaForQuestionAnswering", "XLMRobertaForSequenceClassification", "XLMRobertaForTokenClassification", "XLMRobertaModel", "XLMRobertaPreTrainedModel", ] ) _import_structure["models.xlm_roberta_xl"].extend( [ "XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "XLMRobertaXLForCausalLM", "XLMRobertaXLForMaskedLM", "XLMRobertaXLForMultipleChoice", "XLMRobertaXLForQuestionAnswering", "XLMRobertaXLForSequenceClassification", "XLMRobertaXLForTokenClassification", "XLMRobertaXLModel", "XLMRobertaXLPreTrainedModel", ] ) _import_structure["models.xlnet"].extend( [ "XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "XLNetForMultipleChoice", "XLNetForQuestionAnswering", "XLNetForQuestionAnsweringSimple", "XLNetForSequenceClassification", "XLNetForTokenClassification", "XLNetLMHeadModel", "XLNetModel", "XLNetPreTrainedModel", "load_tf_weights_in_xlnet", ] ) _import_structure["models.xmod"].extend( [ "XMOD_PRETRAINED_MODEL_ARCHIVE_LIST", "XmodForCausalLM", "XmodForMaskedLM", "XmodForMultipleChoice", "XmodForQuestionAnswering", "XmodForSequenceClassification", "XmodForTokenClassification", "XmodModel", "XmodPreTrainedModel", ] ) _import_structure["models.yolos"].extend( [ "YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST", "YolosForObjectDetection", "YolosModel", "YolosPreTrainedModel", ] ) _import_structure["models.yoso"].extend( [ "YOSO_PRETRAINED_MODEL_ARCHIVE_LIST", "YosoForMaskedLM", "YosoForMultipleChoice", "YosoForQuestionAnswering", "YosoForSequenceClassification", "YosoForTokenClassification", "YosoLayer", "YosoModel", "YosoPreTrainedModel", ] ) _import_structure["optimization"] = [ "Adafactor", "AdamW", "get_constant_schedule", "get_constant_schedule_with_warmup", "get_cosine_schedule_with_warmup", "get_cosine_with_hard_restarts_schedule_with_warmup", "get_inverse_sqrt_schedule", "get_linear_schedule_with_warmup", "get_polynomial_decay_schedule_with_warmup", "get_scheduler", ] _import_structure["pytorch_utils"] = ["Conv1D", "apply_chunking_to_forward", "prune_layer"] _import_structure["sagemaker"] = [] _import_structure["trainer"] = ["Trainer"] _import_structure["trainer_pt_utils"] = ["torch_distributed_zero_first"] _import_structure["trainer_seq2seq"] = ["Seq2SeqTrainer"] # TensorFlow-backed objects try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_tf_objects _import_structure["utils.dummy_tf_objects"] = [name for name in dir(dummy_tf_objects) if not name.startswith("_")] else: _import_structure["activations_tf"] = [] _import_structure["benchmark.benchmark_args_tf"] = ["TensorFlowBenchmarkArguments"] _import_structure["benchmark.benchmark_tf"] = ["TensorFlowBenchmark"] _import_structure["generation"].extend( [ "TFForcedBOSTokenLogitsProcessor", "TFForcedEOSTokenLogitsProcessor", "TFGenerationMixin", "TFLogitsProcessor", "TFLogitsProcessorList", "TFLogitsWarper", "TFMinLengthLogitsProcessor", "TFNoBadWordsLogitsProcessor", "TFNoRepeatNGramLogitsProcessor", "TFRepetitionPenaltyLogitsProcessor", "TFTemperatureLogitsWarper", "TFTopKLogitsWarper", "TFTopPLogitsWarper", "tf_top_k_top_p_filtering", ] ) _import_structure["generation_tf_utils"] = [] _import_structure["keras_callbacks"] = ["KerasMetricCallback", "PushToHubCallback"] _import_structure["modeling_tf_outputs"] = [] _import_structure["modeling_tf_utils"] = [ "TFPreTrainedModel", "TFSequenceSummary", "TFSharedEmbeddings", "shape_list", ] # TensorFlow models structure _import_structure["models.albert"].extend( [ "TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFAlbertForMaskedLM", "TFAlbertForMultipleChoice", "TFAlbertForPreTraining", "TFAlbertForQuestionAnswering", "TFAlbertForSequenceClassification", "TFAlbertForTokenClassification", "TFAlbertMainLayer", "TFAlbertModel", "TFAlbertPreTrainedModel", ] ) _import_structure["models.auto"].extend( [ "TF_MODEL_FOR_CAUSAL_LM_MAPPING", "TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING", "TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING", "TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING", "TF_MODEL_FOR_MASKED_LM_MAPPING", "TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING", "TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", "TF_MODEL_FOR_PRETRAINING_MAPPING", "TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING", "TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING", "TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", "TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", "TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING", "TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING", "TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", "TF_MODEL_FOR_VISION_2_SEQ_MAPPING", "TF_MODEL_MAPPING", "TF_MODEL_WITH_LM_HEAD_MAPPING", "TFAutoModel", "TFAutoModelForCausalLM", "TFAutoModelForDocumentQuestionAnswering", "TFAutoModelForImageClassification", "TFAutoModelForMaskedLM", "TFAutoModelForMultipleChoice", "TFAutoModelForNextSentencePrediction", "TFAutoModelForPreTraining", "TFAutoModelForQuestionAnswering", "TFAutoModelForSemanticSegmentation", "TFAutoModelForSeq2SeqLM", "TFAutoModelForSequenceClassification", "TFAutoModelForSpeechSeq2Seq", "TFAutoModelForTableQuestionAnswering", "TFAutoModelForTokenClassification", "TFAutoModelForVision2Seq", "TFAutoModelWithLMHead", ] ) _import_structure["models.bart"].extend( ["TFBartForConditionalGeneration", "TFBartForSequenceClassification", "TFBartModel", "TFBartPretrainedModel"] ) _import_structure["models.bert"].extend( [ "TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBertEmbeddings", "TFBertForMaskedLM", "TFBertForMultipleChoice", "TFBertForNextSentencePrediction", "TFBertForPreTraining", "TFBertForQuestionAnswering", "TFBertForSequenceClassification", "TFBertForTokenClassification", "TFBertLMHeadModel", "TFBertMainLayer", "TFBertModel", "TFBertPreTrainedModel", ] ) _import_structure["models.blenderbot"].extend( ["TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel"] ) _import_structure["models.blenderbot_small"].extend( ["TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel", "TFBlenderbotSmallPreTrainedModel"] ) _import_structure["models.camembert"].extend( [ "TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCamembertForCausalLM", "TFCamembertForMaskedLM", "TFCamembertForMultipleChoice", "TFCamembertForQuestionAnswering", "TFCamembertForSequenceClassification", "TFCamembertForTokenClassification", "TFCamembertModel", "TFCamembertPreTrainedModel", ] ) _import_structure["models.clip"].extend( [ "TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCLIPModel", "TFCLIPPreTrainedModel", "TFCLIPTextModel", "TFCLIPVisionModel", ] ) _import_structure["models.convbert"].extend( [ "TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFConvBertForMaskedLM", "TFConvBertForMultipleChoice", "TFConvBertForQuestionAnswering", "TFConvBertForSequenceClassification", "TFConvBertForTokenClassification", "TFConvBertLayer", "TFConvBertModel", "TFConvBertPreTrainedModel", ] ) _import_structure["models.convnext"].extend( [ "TFConvNextForImageClassification", "TFConvNextModel", "TFConvNextPreTrainedModel", ] ) _import_structure["models.ctrl"].extend( [ "TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCTRLForSequenceClassification", "TFCTRLLMHeadModel", "TFCTRLModel", "TFCTRLPreTrainedModel", ] ) _import_structure["models.cvt"].extend( [ "TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFCvtForImageClassification", "TFCvtModel", "TFCvtPreTrainedModel", ] ) _import_structure["models.data2vec"].extend( [ "TFData2VecVisionForImageClassification", "TFData2VecVisionForSemanticSegmentation", "TFData2VecVisionModel", "TFData2VecVisionPreTrainedModel", ] ) _import_structure["models.deberta"].extend( [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] ) _import_structure["models.deberta_v2"].extend( [ "TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaV2ForMaskedLM", "TFDebertaV2ForQuestionAnswering", "TFDebertaV2ForSequenceClassification", "TFDebertaV2ForTokenClassification", "TFDebertaV2Model", "TFDebertaV2PreTrainedModel", ] ) _import_structure["models.deit"].extend( [ "TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDeiTForImageClassification", "TFDeiTForImageClassificationWithTeacher", "TFDeiTForMaskedImageModeling", "TFDeiTModel", "TFDeiTPreTrainedModel", ] ) _import_structure["models.distilbert"].extend( [ "TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDistilBertForMaskedLM", "TFDistilBertForMultipleChoice", "TFDistilBertForQuestionAnswering", "TFDistilBertForSequenceClassification", "TFDistilBertForTokenClassification", "TFDistilBertMainLayer", "TFDistilBertModel", "TFDistilBertPreTrainedModel", ] ) _import_structure["models.dpr"].extend( [ "TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST", "TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST", "TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDPRContextEncoder", "TFDPRPretrainedContextEncoder", "TFDPRPretrainedQuestionEncoder", "TFDPRPretrainedReader", "TFDPRQuestionEncoder", "TFDPRReader", ] ) _import_structure["models.electra"].extend( [ "TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFElectraForMaskedLM", "TFElectraForMultipleChoice", "TFElectraForPreTraining", "TFElectraForQuestionAnswering", "TFElectraForSequenceClassification", "TFElectraForTokenClassification", "TFElectraModel", "TFElectraPreTrainedModel", ] ) _import_structure["models.encoder_decoder"].append("TFEncoderDecoderModel") _import_structure["models.esm"].extend( [ "ESM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEsmForMaskedLM", "TFEsmForSequenceClassification", "TFEsmForTokenClassification", "TFEsmModel", "TFEsmPreTrainedModel", ] ) _import_structure["models.flaubert"].extend( [ "TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFlaubertForMultipleChoice", "TFFlaubertForQuestionAnsweringSimple", "TFFlaubertForSequenceClassification", "TFFlaubertForTokenClassification", "TFFlaubertModel", "TFFlaubertPreTrainedModel", "TFFlaubertWithLMHeadModel", ] ) _import_structure["models.funnel"].extend( [ "TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFFunnelBaseModel", "TFFunnelForMaskedLM", "TFFunnelForMultipleChoice", "TFFunnelForPreTraining", "TFFunnelForQuestionAnswering", "TFFunnelForSequenceClassification", "TFFunnelForTokenClassification", "TFFunnelModel", "TFFunnelPreTrainedModel", ] ) _import_structure["models.gpt2"].extend( [ "TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGPT2DoubleHeadsModel", "TFGPT2ForSequenceClassification", "TFGPT2LMHeadModel", "TFGPT2MainLayer", "TFGPT2Model", "TFGPT2PreTrainedModel", ] ) _import_structure["models.gptj"].extend( [ "TFGPTJForCausalLM", "TFGPTJForQuestionAnswering", "TFGPTJForSequenceClassification", "TFGPTJModel", "TFGPTJPreTrainedModel", ] ) _import_structure["models.groupvit"].extend( [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] ) _import_structure["models.hubert"].extend( [ "TF_HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFHubertForCTC", "TFHubertModel", "TFHubertPreTrainedModel", ] ) _import_structure["models.layoutlm"].extend( [ "TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLayoutLMForMaskedLM", "TFLayoutLMForQuestionAnswering", "TFLayoutLMForSequenceClassification", "TFLayoutLMForTokenClassification", "TFLayoutLMMainLayer", "TFLayoutLMModel", "TFLayoutLMPreTrainedModel", ] ) _import_structure["models.layoutlmv3"].extend( [ "TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLayoutLMv3ForQuestionAnswering", "TFLayoutLMv3ForSequenceClassification", "TFLayoutLMv3ForTokenClassification", "TFLayoutLMv3Model", "TFLayoutLMv3PreTrainedModel", ] ) _import_structure["models.led"].extend(["TFLEDForConditionalGeneration", "TFLEDModel", "TFLEDPreTrainedModel"]) _import_structure["models.longformer"].extend( [ "TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLongformerForMaskedLM", "TFLongformerForMultipleChoice", "TFLongformerForQuestionAnswering", "TFLongformerForSequenceClassification", "TFLongformerForTokenClassification", "TFLongformerModel", "TFLongformerPreTrainedModel", "TFLongformerSelfAttention", ] ) _import_structure["models.lxmert"].extend( [ "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLxmertForPreTraining", "TFLxmertMainLayer", "TFLxmertModel", "TFLxmertPreTrainedModel", "TFLxmertVisualFeatureEncoder", ] ) _import_structure["models.marian"].extend(["TFMarianModel", "TFMarianMTModel", "TFMarianPreTrainedModel"]) _import_structure["models.mbart"].extend( ["TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel"] ) _import_structure["models.mobilebert"].extend( [ "TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileBertForMaskedLM", "TFMobileBertForMultipleChoice", "TFMobileBertForNextSentencePrediction", "TFMobileBertForPreTraining", "TFMobileBertForQuestionAnswering", "TFMobileBertForSequenceClassification", "TFMobileBertForTokenClassification", "TFMobileBertMainLayer", "TFMobileBertModel", "TFMobileBertPreTrainedModel", ] ) _import_structure["models.mobilevit"].extend( [ "TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileViTForImageClassification", "TFMobileViTForSemanticSegmentation", "TFMobileViTModel", "TFMobileViTPreTrainedModel", ] ) _import_structure["models.mpnet"].extend( [ "TF_MPNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMPNetForMaskedLM", "TFMPNetForMultipleChoice", "TFMPNetForQuestionAnswering", "TFMPNetForSequenceClassification", "TFMPNetForTokenClassification", "TFMPNetMainLayer", "TFMPNetModel", "TFMPNetPreTrainedModel", ] ) _import_structure["models.mt5"].extend(["TFMT5EncoderModel", "TFMT5ForConditionalGeneration", "TFMT5Model"]) _import_structure["models.openai"].extend( [ "TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFOpenAIGPTDoubleHeadsModel", "TFOpenAIGPTForSequenceClassification", "TFOpenAIGPTLMHeadModel", "TFOpenAIGPTMainLayer", "TFOpenAIGPTModel", "TFOpenAIGPTPreTrainedModel", ] ) _import_structure["models.opt"].extend( [ "TFOPTForCausalLM", "TFOPTModel", "TFOPTPreTrainedModel", ] ) _import_structure["models.pegasus"].extend( ["TFPegasusForConditionalGeneration", "TFPegasusModel", "TFPegasusPreTrainedModel"] ) _import_structure["models.rag"].extend( [ "TFRagModel", "TFRagPreTrainedModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration", ] ) _import_structure["models.regnet"].extend( [ "TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRegNetForImageClassification", "TFRegNetModel", "TFRegNetPreTrainedModel", ] ) _import_structure["models.rembert"].extend( [ "TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRemBertForCausalLM", "TFRemBertForMaskedLM", "TFRemBertForMultipleChoice", "TFRemBertForQuestionAnswering", "TFRemBertForSequenceClassification", "TFRemBertForTokenClassification", "TFRemBertLayer", "TFRemBertModel", "TFRemBertPreTrainedModel", ] ) _import_structure["models.resnet"].extend( [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] ) _import_structure["models.roberta"].extend( [ "TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaForCausalLM", "TFRobertaForMaskedLM", "TFRobertaForMultipleChoice", "TFRobertaForQuestionAnswering", "TFRobertaForSequenceClassification", "TFRobertaForTokenClassification", "TFRobertaMainLayer", "TFRobertaModel", "TFRobertaPreTrainedModel", ] ) _import_structure["models.roberta_prelayernorm"].extend( [ "TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRobertaPreLayerNormForCausalLM", "TFRobertaPreLayerNormForMaskedLM", "TFRobertaPreLayerNormForMultipleChoice", "TFRobertaPreLayerNormForQuestionAnswering", "TFRobertaPreLayerNormForSequenceClassification", "TFRobertaPreLayerNormForTokenClassification", "TFRobertaPreLayerNormMainLayer", "TFRobertaPreLayerNormModel", "TFRobertaPreLayerNormPreTrainedModel", ] ) _import_structure["models.roformer"].extend( [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] ) _import_structure["models.segformer"].extend( [ "TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSegformerDecodeHead", "TFSegformerForImageClassification", "TFSegformerForSemanticSegmentation", "TFSegformerModel", "TFSegformerPreTrainedModel", ] ) _import_structure["models.speech_to_text"].extend( [ "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel", ] ) _import_structure["models.swin"].extend( [ "TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSwinForImageClassification", "TFSwinForMaskedImageModeling", "TFSwinModel", "TFSwinPreTrainedModel", ] ) _import_structure["models.t5"].extend( [ "TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST", "TFT5EncoderModel", "TFT5ForConditionalGeneration", "TFT5Model", "TFT5PreTrainedModel", ] ) _import_structure["models.tapas"].extend( [ "TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST", "TFTapasForMaskedLM", "TFTapasForQuestionAnswering", "TFTapasForSequenceClassification", "TFTapasModel", "TFTapasPreTrainedModel", ] ) _import_structure["models.transfo_xl"].extend( [ "TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST", "TFAdaptiveEmbedding", "TFTransfoXLForSequenceClassification", "TFTransfoXLLMHeadModel", "TFTransfoXLMainLayer", "TFTransfoXLModel", "TFTransfoXLPreTrainedModel", ] ) _import_structure["models.vision_encoder_decoder"].extend(["TFVisionEncoderDecoderModel"]) _import_structure["models.vision_text_dual_encoder"].extend(["TFVisionTextDualEncoderModel"]) _import_structure["models.vit"].extend( [ "TFViTForImageClassification", "TFViTModel", "TFViTPreTrainedModel", ] ) _import_structure["models.vit_mae"].extend( [ "TFViTMAEForPreTraining", "TFViTMAEModel", "TFViTMAEPreTrainedModel", ] ) _import_structure["models.wav2vec2"].extend( [ "TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWav2Vec2ForCTC", "TFWav2Vec2Model", "TFWav2Vec2PreTrainedModel", ] ) _import_structure["models.whisper"].extend( [ "TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFWhisperForConditionalGeneration", "TFWhisperModel", "TFWhisperPreTrainedModel", ] ) _import_structure["models.xglm"].extend( [ "TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel", ] ) _import_structure["models.xlm"].extend( [ "TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLMForMultipleChoice", "TFXLMForQuestionAnsweringSimple", "TFXLMForSequenceClassification", "TFXLMForTokenClassification", "TFXLMMainLayer", "TFXLMModel", "TFXLMPreTrainedModel", "TFXLMWithLMHeadModel", ] ) _import_structure["models.xlm_roberta"].extend( [ "TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLMRobertaForCausalLM", "TFXLMRobertaForMaskedLM", "TFXLMRobertaForMultipleChoice", "TFXLMRobertaForQuestionAnswering", "TFXLMRobertaForSequenceClassification", "TFXLMRobertaForTokenClassification", "TFXLMRobertaModel", "TFXLMRobertaPreTrainedModel", ] ) _import_structure["models.xlnet"].extend( [ "TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLNetForMultipleChoice", "TFXLNetForQuestionAnsweringSimple", "TFXLNetForSequenceClassification", "TFXLNetForTokenClassification", "TFXLNetLMHeadModel", "TFXLNetMainLayer", "TFXLNetModel", "TFXLNetPreTrainedModel", ] ) _import_structure["optimization_tf"] = ["AdamWeightDecay", "GradientAccumulator", "WarmUp", "create_optimizer"] _import_structure["tf_utils"] = [] _import_structure["trainer_tf"] = ["TFTrainer"] # FLAX-backed objects try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils import dummy_flax_objects _import_structure["utils.dummy_flax_objects"] = [ name for name in dir(dummy_flax_objects) if not name.startswith("_") ] else: _import_structure["generation"].extend( [ "FlaxForcedBOSTokenLogitsProcessor", "FlaxForcedEOSTokenLogitsProcessor", "FlaxGenerationMixin", "FlaxLogitsProcessor", "FlaxLogitsProcessorList", "FlaxLogitsWarper", "FlaxMinLengthLogitsProcessor", "FlaxTemperatureLogitsWarper", "FlaxTopKLogitsWarper", "FlaxTopPLogitsWarper", ] ) _import_structure["generation_flax_utils"] = [] _import_structure["modeling_flax_outputs"] = [] _import_structure["modeling_flax_utils"] = ["FlaxPreTrainedModel"] _import_structure["models.albert"].extend( [ "FlaxAlbertForMaskedLM", "FlaxAlbertForMultipleChoice", "FlaxAlbertForPreTraining", "FlaxAlbertForQuestionAnswering", "FlaxAlbertForSequenceClassification", "FlaxAlbertForTokenClassification", "FlaxAlbertModel", "FlaxAlbertPreTrainedModel", ] ) _import_structure["models.auto"].extend( [ "FLAX_MODEL_FOR_CAUSAL_LM_MAPPING", "FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING", "FLAX_MODEL_FOR_MASKED_LM_MAPPING", "FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING", "FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING", "FLAX_MODEL_FOR_PRETRAINING_MAPPING", "FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING", "FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING", "FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING", "FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING", "FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING", "FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING", "FLAX_MODEL_MAPPING", "FlaxAutoModel", "FlaxAutoModelForCausalLM", "FlaxAutoModelForImageClassification", "FlaxAutoModelForMaskedLM", "FlaxAutoModelForMultipleChoice", "FlaxAutoModelForNextSentencePrediction", "FlaxAutoModelForPreTraining", "FlaxAutoModelForQuestionAnswering", "FlaxAutoModelForSeq2SeqLM", "FlaxAutoModelForSequenceClassification", "FlaxAutoModelForSpeechSeq2Seq", "FlaxAutoModelForTokenClassification", "FlaxAutoModelForVision2Seq", ] ) # Flax models structure _import_structure["models.bart"].extend( [ "FlaxBartDecoderPreTrainedModel", "FlaxBartForCausalLM", "FlaxBartForConditionalGeneration", "FlaxBartForQuestionAnswering", "FlaxBartForSequenceClassification", "FlaxBartModel", "FlaxBartPreTrainedModel", ] ) _import_structure["models.beit"].extend( [ "FlaxBeitForImageClassification", "FlaxBeitForMaskedImageModeling", "FlaxBeitModel", "FlaxBeitPreTrainedModel", ] ) _import_structure["models.bert"].extend( [ "FlaxBertForCausalLM", "FlaxBertForMaskedLM", "FlaxBertForMultipleChoice", "FlaxBertForNextSentencePrediction", "FlaxBertForPreTraining", "FlaxBertForQuestionAnswering", "FlaxBertForSequenceClassification", "FlaxBertForTokenClassification", "FlaxBertModel", "FlaxBertPreTrainedModel", ] ) _import_structure["models.big_bird"].extend( [ "FlaxBigBirdForCausalLM", "FlaxBigBirdForMaskedLM", "FlaxBigBirdForMultipleChoice", "FlaxBigBirdForPreTraining", "FlaxBigBirdForQuestionAnswering", "FlaxBigBirdForSequenceClassification", "FlaxBigBirdForTokenClassification", "FlaxBigBirdModel", "FlaxBigBirdPreTrainedModel", ] ) _import_structure["models.blenderbot"].extend( ["FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel"] ) _import_structure["models.blenderbot_small"].extend( [ "FlaxBlenderbotSmallForConditionalGeneration", "FlaxBlenderbotSmallModel", "FlaxBlenderbotSmallPreTrainedModel", ] ) _import_structure["models.clip"].extend( [ "FlaxCLIPModel", "FlaxCLIPPreTrainedModel", "FlaxCLIPTextModel", "FlaxCLIPTextPreTrainedModel", "FlaxCLIPVisionModel", "FlaxCLIPVisionPreTrainedModel", ] ) _import_structure["models.distilbert"].extend( [ "FlaxDistilBertForMaskedLM", "FlaxDistilBertForMultipleChoice", "FlaxDistilBertForQuestionAnswering", "FlaxDistilBertForSequenceClassification", "FlaxDistilBertForTokenClassification", "FlaxDistilBertModel", "FlaxDistilBertPreTrainedModel", ] ) _import_structure["models.electra"].extend( [ "FlaxElectraForCausalLM", "FlaxElectraForMaskedLM", "FlaxElectraForMultipleChoice", "FlaxElectraForPreTraining", "FlaxElectraForQuestionAnswering", "FlaxElectraForSequenceClassification", "FlaxElectraForTokenClassification", "FlaxElectraModel", "FlaxElectraPreTrainedModel", ] ) _import_structure["models.encoder_decoder"].append("FlaxEncoderDecoderModel") _import_structure["models.gpt2"].extend(["FlaxGPT2LMHeadModel", "FlaxGPT2Model", "FlaxGPT2PreTrainedModel"]) _import_structure["models.gpt_neo"].extend( ["FlaxGPTNeoForCausalLM", "FlaxGPTNeoModel", "FlaxGPTNeoPreTrainedModel"] ) _import_structure["models.gptj"].extend(["FlaxGPTJForCausalLM", "FlaxGPTJModel", "FlaxGPTJPreTrainedModel"]) _import_structure["models.longt5"].extend( ["FlaxLongT5ForConditionalGeneration", "FlaxLongT5Model", "FlaxLongT5PreTrainedModel"] ) _import_structure["models.marian"].extend( [ "FlaxMarianModel", "FlaxMarianMTModel", "FlaxMarianPreTrainedModel", ] ) _import_structure["models.mbart"].extend( [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] ) _import_structure["models.mt5"].extend(["FlaxMT5EncoderModel", "FlaxMT5ForConditionalGeneration", "FlaxMT5Model"]) _import_structure["models.opt"].extend( [ "FlaxOPTForCausalLM", "FlaxOPTModel", "FlaxOPTPreTrainedModel", ] ) _import_structure["models.pegasus"].extend( [ "FlaxPegasusForConditionalGeneration", "FlaxPegasusModel", "FlaxPegasusPreTrainedModel", ] ) _import_structure["models.roberta"].extend( [ "FlaxRobertaForCausalLM", "FlaxRobertaForMaskedLM", "FlaxRobertaForMultipleChoice", "FlaxRobertaForQuestionAnswering", "FlaxRobertaForSequenceClassification", "FlaxRobertaForTokenClassification", "FlaxRobertaModel", "FlaxRobertaPreTrainedModel", ] ) _import_structure["models.roberta_prelayernorm"].extend( [ "FlaxRobertaPreLayerNormForCausalLM", "FlaxRobertaPreLayerNormForMaskedLM", "FlaxRobertaPreLayerNormForMultipleChoice", "FlaxRobertaPreLayerNormForQuestionAnswering", "FlaxRobertaPreLayerNormForSequenceClassification", "FlaxRobertaPreLayerNormForTokenClassification", "FlaxRobertaPreLayerNormModel", "FlaxRobertaPreLayerNormPreTrainedModel", ] ) _import_structure["models.roformer"].extend( [ "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] ) _import_structure["models.speech_encoder_decoder"].append("FlaxSpeechEncoderDecoderModel") _import_structure["models.t5"].extend( ["FlaxT5EncoderModel", "FlaxT5ForConditionalGeneration", "FlaxT5Model", "FlaxT5PreTrainedModel"] ) _import_structure["models.vision_encoder_decoder"].append("FlaxVisionEncoderDecoderModel") _import_structure["models.vision_text_dual_encoder"].extend(["FlaxVisionTextDualEncoderModel"]) _import_structure["models.vit"].extend(["FlaxViTForImageClassification", "FlaxViTModel", "FlaxViTPreTrainedModel"]) _import_structure["models.wav2vec2"].extend( ["FlaxWav2Vec2ForCTC", "FlaxWav2Vec2ForPreTraining", "FlaxWav2Vec2Model", "FlaxWav2Vec2PreTrainedModel"] ) _import_structure["models.whisper"].extend( [ "FlaxWhisperForConditionalGeneration", "FlaxWhisperModel", "FlaxWhisperPreTrainedModel", ] ) _import_structure["models.xglm"].extend( [ "FlaxXGLMForCausalLM", "FlaxXGLMModel", "FlaxXGLMPreTrainedModel", ] ) _import_structure["models.xlm_roberta"].extend( [ "FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxXLMRobertaForMaskedLM", "FlaxXLMRobertaForMultipleChoice", "FlaxXLMRobertaForQuestionAnswering", "FlaxXLMRobertaForSequenceClassification", "FlaxXLMRobertaForTokenClassification", "FlaxXLMRobertaModel", "FlaxXLMRobertaForCausalLM", "FlaxXLMRobertaPreTrainedModel", ] ) # Direct imports for type-checking if TYPE_CHECKING: # Configuration from .configuration_utils import PretrainedConfig # Data from .data import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadV1Processor, SquadV2Processor, glue_compute_metrics, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_compute_metrics, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, ) from .data.data_collator import ( DataCollator, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeq2Seq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .feature_extraction_sequence_utils import SequenceFeatureExtractor # Feature Extractor from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin # Generation from .generation import GenerationConfig from .hf_argparser import HfArgumentParser # Integrations from .integrations import ( is_clearml_available, is_comet_available, is_neptune_available, is_optuna_available, is_ray_available, is_ray_tune_available, is_sigopt_available, is_tensorboard_available, is_wandb_available, ) # Model Cards from .modelcard import ModelCard # TF 2.0 <=> PyTorch conversion utilities from .modeling_tf_pytorch_utils import ( convert_tf_weight_name_to_pt_weight_name, load_pytorch_checkpoint_in_tf2_model, load_pytorch_model_in_tf2_model, load_pytorch_weights_in_tf2_model, load_tf2_checkpoint_in_pytorch_model, load_tf2_model_in_pytorch_model, load_tf2_weights_in_pytorch_model, ) from .models.albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig from .models.align import ( ALIGN_PRETRAINED_CONFIG_ARCHIVE_MAP, AlignConfig, AlignProcessor, AlignTextConfig, AlignVisionConfig, ) from .models.altclip import ( ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, AltCLIPConfig, AltCLIPProcessor, AltCLIPTextConfig, AltCLIPVisionConfig, ) from .models.audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) from .models.auto import ( ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_NAMES_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer, ) from .models.bart import BartConfig, BartTokenizer from .models.beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig from .models.bert import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BasicTokenizer, BertConfig, BertTokenizer, WordpieceTokenizer, ) from .models.bert_generation import BertGenerationConfig from .models.bert_japanese import BertJapaneseTokenizer, CharacterTokenizer, MecabTokenizer from .models.bertweet import BertweetTokenizer from .models.big_bird import BIG_BIRD_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdConfig from .models.bigbird_pegasus import BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig from .models.biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig, BioGptTokenizer from .models.bit import BIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BitConfig from .models.blenderbot import BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotTokenizer from .models.blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallTokenizer, ) from .models.blip import ( BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipProcessor, BlipTextConfig, BlipVisionConfig, ) from .models.blip_2 import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, Blip2Config, Blip2Processor, Blip2QFormerConfig, Blip2VisionConfig, ) from .models.bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig from .models.bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerProcessor, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .models.byt5 import ByT5Tokenizer from .models.camembert import CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CamembertConfig from .models.canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig, CanineTokenizer from .models.chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPProcessor, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .models.clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapProcessor, ClapTextConfig, ) from .models.clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPProcessor, CLIPTextConfig, CLIPTokenizer, CLIPVisionConfig, ) from .models.clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegProcessor, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .models.codegen import CODEGEN_PRETRAINED_CONFIG_ARCHIVE_MAP, CodeGenConfig, CodeGenTokenizer from .models.conditional_detr import CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig from .models.convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertTokenizer from .models.convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig from .models.ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig, CTRLTokenizer from .models.cvt import CVT_PRETRAINED_CONFIG_ARCHIVE_MAP, CvtConfig from .models.data2vec import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, Data2VecAudioConfig, Data2VecTextConfig, Data2VecVisionConfig, ) from .models.deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaTokenizer from .models.deberta_v2 import DEBERTA_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaV2Config from .models.decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, DecisionTransformerConfig, ) from .models.deformable_detr import DEFORMABLE_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DeformableDetrConfig from .models.deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig from .models.deta import DETA_PRETRAINED_CONFIG_ARCHIVE_MAP, DetaConfig from .models.detr import DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, DetrConfig from .models.dinat import DINAT_PRETRAINED_CONFIG_ARCHIVE_MAP, DinatConfig from .models.distilbert import DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertTokenizer from .models.donut import DONUT_SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, DonutProcessor, DonutSwinConfig from .models.dpr import ( DPR_PRETRAINED_CONFIG_ARCHIVE_MAP, DPRConfig, DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderOutput, DPRReaderTokenizer, ) from .models.dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig from .models.efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig from .models.efficientnet import EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientNetConfig from .models.electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraTokenizer from .models.encoder_decoder import EncoderDecoderConfig from .models.ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig from .models.ernie_m import ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieMConfig from .models.esm import ESM_PRETRAINED_CONFIG_ARCHIVE_MAP, EsmConfig, EsmTokenizer from .models.flaubert import FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, FlaubertConfig, FlaubertTokenizer from .models.flava import ( FLAVA_PRETRAINED_CONFIG_ARCHIVE_MAP, FlavaConfig, FlavaImageCodebookConfig, FlavaImageConfig, FlavaMultimodalConfig, FlavaTextConfig, ) from .models.fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig from .models.fsmt import FSMT_PRETRAINED_CONFIG_ARCHIVE_MAP, FSMTConfig, FSMTTokenizer from .models.funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig, FunnelTokenizer from .models.git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitProcessor, GitVisionConfig from .models.glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig from .models.gpt2 import GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2Config, GPT2Tokenizer from .models.gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig from .models.gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig from .models.gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .models.gptj import GPTJ_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTJConfig from .models.gptsan_japanese import ( GPTSAN_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTSanJapaneseConfig, GPTSanJapaneseTokenizer, ) from .models.graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig from .models.groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTTextConfig, GroupViTVisionConfig, ) from .models.herbert import HerbertTokenizer from .models.hubert import HUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, HubertConfig from .models.ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig from .models.imagegpt import IMAGEGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ImageGPTConfig from .models.jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxTokenizer, JukeboxVQVAEConfig, ) from .models.layoutlm import LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMConfig, LayoutLMTokenizer from .models.layoutlmv2 import ( LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMv2Config, LayoutLMv2FeatureExtractor, LayoutLMv2ImageProcessor, LayoutLMv2Processor, LayoutLMv2Tokenizer, ) from .models.layoutlmv3 import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMv3Config, LayoutLMv3FeatureExtractor, LayoutLMv3ImageProcessor, LayoutLMv3Processor, LayoutLMv3Tokenizer, ) from .models.layoutxlm import LayoutXLMProcessor from .models.led import LED_PRETRAINED_CONFIG_ARCHIVE_MAP, LEDConfig, LEDTokenizer from .models.levit import LEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, LevitConfig from .models.lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig from .models.llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig from .models.longformer import LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerTokenizer from .models.longt5 import LONGT5_PRETRAINED_CONFIG_ARCHIVE_MAP, LongT5Config from .models.luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig, LukeTokenizer from .models.lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig, LxmertTokenizer from .models.m2m_100 import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, M2M100Config from .models.marian import MarianConfig from .models.markuplm import ( MARKUPLM_PRETRAINED_CONFIG_ARCHIVE_MAP, MarkupLMConfig, MarkupLMFeatureExtractor, MarkupLMProcessor, MarkupLMTokenizer, ) from .models.mask2former import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, Mask2FormerConfig from .models.maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig, MaskFormerSwinConfig from .models.mbart import MBartConfig from .models.mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig, MCTCTProcessor from .models.megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig from .models.mmbt import MMBTConfig from .models.mobilebert import MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertTokenizer from .models.mobilenet_v1 import MOBILENET_V1_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetV1Config from .models.mobilenet_v2 import MOBILENET_V2_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileNetV2Config from .models.mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig from .models.mpnet import MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP, MPNetConfig, MPNetTokenizer from .models.mt5 import MT5Config from .models.mvp import MvpConfig, MvpTokenizer from .models.nat import NAT_PRETRAINED_CONFIG_ARCHIVE_MAP, NatConfig from .models.nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig from .models.nystromformer import NYSTROMFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, NystromformerConfig from .models.oneformer import ONEFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, OneFormerConfig, OneFormerProcessor from .models.openai import OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OpenAIGPTConfig, OpenAIGPTTokenizer from .models.opt import OPTConfig from .models.owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTProcessor, OwlViTTextConfig, OwlViTVisionConfig, ) from .models.pegasus import PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusConfig, PegasusTokenizer from .models.pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig from .models.perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverTokenizer from .models.phobert import PhobertTokenizer from .models.plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig from .models.poolformer import POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig from .models.prophetnet import PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ProphetNetConfig, ProphetNetTokenizer from .models.qdqbert import QDQBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, QDQBertConfig from .models.rag import RagConfig, RagRetriever, RagTokenizer from .models.realm import REALM_PRETRAINED_CONFIG_ARCHIVE_MAP, RealmConfig, RealmTokenizer from .models.reformer import REFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ReformerConfig from .models.regnet import REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP, RegNetConfig from .models.rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig from .models.resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig from .models.retribert import RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RetriBertConfig, RetriBertTokenizer from .models.roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaTokenizer from .models.roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaPreLayerNormConfig, ) from .models.roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig, RoCBertTokenizer from .models.roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerTokenizer from .models.segformer import SEGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SegformerConfig from .models.sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig from .models.sew_d import SEW_D_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWDConfig from .models.speech_encoder_decoder import SpeechEncoderDecoderConfig from .models.speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, Speech2TextConfig, Speech2TextProcessor, ) from .models.speech_to_text_2 import ( SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP, Speech2Text2Config, Speech2Text2Processor, Speech2Text2Tokenizer, ) from .models.speecht5 import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechT5Config, SpeechT5HifiGanConfig, SpeechT5Processor, ) from .models.splinter import SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP, SplinterConfig, SplinterTokenizer from .models.squeezebert import SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertTokenizer from .models.swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig from .models.swin2sr import SWIN2SR_PRETRAINED_CONFIG_ARCHIVE_MAP, Swin2SRConfig from .models.swinv2 import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, Swinv2Config from .models.switch_transformers import SWITCH_TRANSFORMERS_PRETRAINED_CONFIG_ARCHIVE_MAP, SwitchTransformersConfig from .models.t5 import T5_PRETRAINED_CONFIG_ARCHIVE_MAP, T5Config from .models.table_transformer import TABLE_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TableTransformerConfig from .models.tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig, TapasTokenizer from .models.tapex import TapexTokenizer from .models.time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) from .models.timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig from .models.trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TrajectoryTransformerConfig, ) from .models.transfo_xl import ( TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig, TransfoXLCorpus, TransfoXLTokenizer, ) from .models.trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig, TrOCRProcessor from .models.tvlt import TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP, TvltConfig, TvltProcessor from .models.unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig from .models.unispeech_sat import UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechSatConfig from .models.upernet import UperNetConfig from .models.van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig from .models.videomae import VIDEOMAE_PRETRAINED_CONFIG_ARCHIVE_MAP, VideoMAEConfig from .models.vilt import ( VILT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViltConfig, ViltFeatureExtractor, ViltImageProcessor, ViltProcessor, ) from .models.vision_encoder_decoder import VisionEncoderDecoderConfig from .models.vision_text_dual_encoder import VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor from .models.visual_bert import VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, VisualBertConfig from .models.vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig from .models.vit_hybrid import VIT_HYBRID_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTHybridConfig from .models.vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig from .models.vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig from .models.wav2vec2 import ( WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, Wav2Vec2Config, Wav2Vec2CTCTokenizer, Wav2Vec2FeatureExtractor, Wav2Vec2Processor, Wav2Vec2Tokenizer, ) from .models.wav2vec2_conformer import WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, Wav2Vec2ConformerConfig from .models.wav2vec2_phoneme import Wav2Vec2PhonemeCTCTokenizer from .models.wav2vec2_with_lm import Wav2Vec2ProcessorWithLM from .models.wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig from .models.whisper import ( WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperFeatureExtractor, WhisperProcessor, WhisperTokenizer, ) from .models.x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPProcessor, XCLIPTextConfig, XCLIPVisionConfig, ) from .models.xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig from .models.xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMTokenizer from .models.xlm_prophetnet import XLM_PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMProphetNetConfig from .models.xlm_roberta import XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig from .models.xlm_roberta_xl import XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig from .models.xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig from .models.xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig from .models.yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig from .models.yoso import YOSO_PRETRAINED_CONFIG_ARCHIVE_MAP, YosoConfig # Pipelines from .pipelines import ( AudioClassificationPipeline, AutomaticSpeechRecognitionPipeline, Conversation, ConversationalPipeline, CsvPipelineDataFormat, DepthEstimationPipeline, DocumentQuestionAnsweringPipeline, FeatureExtractionPipeline, FillMaskPipeline, ImageClassificationPipeline, ImageSegmentationPipeline, ImageToTextPipeline, JsonPipelineDataFormat, NerPipeline, ObjectDetectionPipeline, PipedPipelineDataFormat, Pipeline, PipelineDataFormat, QuestionAnsweringPipeline, SummarizationPipeline, TableQuestionAnsweringPipeline, Text2TextGenerationPipeline, TextClassificationPipeline, TextGenerationPipeline, TokenClassificationPipeline, TranslationPipeline, VideoClassificationPipeline, VisualQuestionAnsweringPipeline, ZeroShotAudioClassificationPipeline, ZeroShotClassificationPipeline, ZeroShotImageClassificationPipeline, ZeroShotObjectDetectionPipeline, pipeline, ) from .processing_utils import ProcessorMixin # Tokenization from .tokenization_utils import PreTrainedTokenizer from .tokenization_utils_base import ( AddedToken, BatchEncoding, CharSpan, PreTrainedTokenizerBase, SpecialTokensMixin, TokenSpan, ) # Trainer from .trainer_callback import ( DefaultFlowCallback, EarlyStoppingCallback, PrinterCallback, ProgressCallback, TrainerCallback, TrainerControl, TrainerState, ) from .trainer_utils import EvalPrediction, IntervalStrategy, SchedulerType, enable_full_determinism, set_seed from .training_args import TrainingArguments from .training_args_seq2seq import Seq2SeqTrainingArguments from .training_args_tf import TFTrainingArguments # Files and general utilities from .utils import ( CONFIG_NAME, MODEL_CARD_NAME, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, TensorType, add_end_docstrings, add_start_docstrings, is_apex_available, is_bitsandbytes_available, is_datasets_available, is_decord_available, is_faiss_available, is_flax_available, is_keras_nlp_available, is_phonemizer_available, is_psutil_available, is_py3nvml_available, is_pyctcdecode_available, is_safetensors_available, is_scipy_available, is_sentencepiece_available, is_sklearn_available, is_speech_available, is_tensorflow_text_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_neuroncore_available, is_torch_tpu_available, is_torchvision_available, is_vision_available, logging, ) # bitsandbytes config from .utils.quantization_config import BitsAndBytesConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_sentencepiece_objects import * else: from .models.albert import AlbertTokenizer from .models.barthez import BarthezTokenizer from .models.bartpho import BartphoTokenizer from .models.bert_generation import BertGenerationTokenizer from .models.big_bird import BigBirdTokenizer from .models.camembert import CamembertTokenizer from .models.cpm import CpmTokenizer from .models.deberta_v2 import DebertaV2Tokenizer from .models.ernie_m import ErnieMTokenizer from .models.fnet import FNetTokenizer from .models.gpt_sw3 import GPTSw3Tokenizer from .models.layoutxlm import LayoutXLMTokenizer from .models.llama import LlamaTokenizer from .models.m2m_100 import M2M100Tokenizer from .models.marian import MarianTokenizer from .models.mbart import MBart50Tokenizer, MBartTokenizer from .models.mluke import MLukeTokenizer from .models.mt5 import MT5Tokenizer from .models.nllb import NllbTokenizer from .models.pegasus import PegasusTokenizer from .models.plbart import PLBartTokenizer from .models.reformer import ReformerTokenizer from .models.rembert import RemBertTokenizer from .models.speech_to_text import Speech2TextTokenizer from .models.speecht5 import SpeechT5Tokenizer from .models.t5 import T5Tokenizer from .models.xglm import XGLMTokenizer from .models.xlm_prophetnet import XLMProphetNetTokenizer from .models.xlm_roberta import XLMRobertaTokenizer from .models.xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_tokenizers_objects import * else: # Fast tokenizers imports from .models.albert import AlbertTokenizerFast from .models.bart import BartTokenizerFast from .models.barthez import BarthezTokenizerFast from .models.bert import BertTokenizerFast from .models.big_bird import BigBirdTokenizerFast from .models.blenderbot import BlenderbotTokenizerFast from .models.blenderbot_small import BlenderbotSmallTokenizerFast from .models.bloom import BloomTokenizerFast from .models.camembert import CamembertTokenizerFast from .models.clip import CLIPTokenizerFast from .models.codegen import CodeGenTokenizerFast from .models.convbert import ConvBertTokenizerFast from .models.cpm import CpmTokenizerFast from .models.deberta import DebertaTokenizerFast from .models.deberta_v2 import DebertaV2TokenizerFast from .models.distilbert import DistilBertTokenizerFast from .models.dpr import DPRContextEncoderTokenizerFast, DPRQuestionEncoderTokenizerFast, DPRReaderTokenizerFast from .models.electra import ElectraTokenizerFast from .models.fnet import FNetTokenizerFast from .models.funnel import FunnelTokenizerFast from .models.gpt2 import GPT2TokenizerFast from .models.gpt_neox import GPTNeoXTokenizerFast from .models.gpt_neox_japanese import GPTNeoXJapaneseTokenizer from .models.herbert import HerbertTokenizerFast from .models.layoutlm import LayoutLMTokenizerFast from .models.layoutlmv2 import LayoutLMv2TokenizerFast from .models.layoutlmv3 import LayoutLMv3TokenizerFast from .models.layoutxlm import LayoutXLMTokenizerFast from .models.led import LEDTokenizerFast from .models.longformer import LongformerTokenizerFast from .models.lxmert import LxmertTokenizerFast from .models.markuplm import MarkupLMTokenizerFast from .models.mbart import MBartTokenizerFast from .models.mbart50 import MBart50TokenizerFast from .models.mobilebert import MobileBertTokenizerFast from .models.mpnet import MPNetTokenizerFast from .models.mt5 import MT5TokenizerFast from .models.mvp import MvpTokenizerFast from .models.nllb import NllbTokenizerFast from .models.openai import OpenAIGPTTokenizerFast from .models.pegasus import PegasusTokenizerFast from .models.realm import RealmTokenizerFast from .models.reformer import ReformerTokenizerFast from .models.rembert import RemBertTokenizerFast from .models.retribert import RetriBertTokenizerFast from .models.roberta import RobertaTokenizerFast from .models.roformer import RoFormerTokenizerFast from .models.splinter import SplinterTokenizerFast from .models.squeezebert import SqueezeBertTokenizerFast from .models.t5 import T5TokenizerFast from .models.whisper import WhisperTokenizerFast from .models.xglm import XGLMTokenizerFast from .models.xlm_roberta import XLMRobertaTokenizerFast from .models.xlnet import XLNetTokenizerFast from .tokenization_utils_fast import PreTrainedTokenizerFast try: if not (is_sentencepiece_available() and is_tokenizers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummies_sentencepiece_and_tokenizers_objects import * else: from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS, convert_slow_tokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_speech_objects import * else: from .models.audio_spectrogram_transformer import ASTFeatureExtractor from .models.mctct import MCTCTFeatureExtractor from .models.speech_to_text import Speech2TextFeatureExtractor from .models.speecht5 import SpeechT5FeatureExtractor from .models.tvlt import TvltFeatureExtractor try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_tensorflow_text_objects import * else: from .models.bert import TFBertTokenizer try: if not is_keras_nlp_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_keras_nlp_objects import * else: from .models.gpt2 import TFGPT2Tokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_vision_objects import * else: from .image_processing_utils import ImageProcessingMixin from .image_utils import ImageFeatureExtractionMixin from .models.beit import BeitFeatureExtractor, BeitImageProcessor from .models.bit import BitImageProcessor from .models.blip import BlipImageProcessor from .models.bridgetower import BridgeTowerImageProcessor from .models.chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor from .models.clip import CLIPFeatureExtractor, CLIPImageProcessor from .models.conditional_detr import ConditionalDetrFeatureExtractor, ConditionalDetrImageProcessor from .models.convnext import ConvNextFeatureExtractor, ConvNextImageProcessor from .models.deformable_detr import DeformableDetrFeatureExtractor, DeformableDetrImageProcessor from .models.deit import DeiTFeatureExtractor, DeiTImageProcessor from .models.deta import DetaImageProcessor from .models.detr import DetrFeatureExtractor, DetrImageProcessor from .models.donut import DonutFeatureExtractor, DonutImageProcessor from .models.dpt import DPTFeatureExtractor, DPTImageProcessor from .models.efficientformer import EfficientFormerImageProcessor from .models.efficientnet import EfficientNetImageProcessor from .models.flava import FlavaFeatureExtractor, FlavaImageProcessor, FlavaProcessor from .models.glpn import GLPNFeatureExtractor, GLPNImageProcessor from .models.imagegpt import ImageGPTFeatureExtractor, ImageGPTImageProcessor from .models.layoutlmv2 import LayoutLMv2FeatureExtractor, LayoutLMv2ImageProcessor from .models.layoutlmv3 import LayoutLMv3FeatureExtractor, LayoutLMv3ImageProcessor from .models.levit import LevitFeatureExtractor, LevitImageProcessor from .models.mask2former import Mask2FormerImageProcessor from .models.maskformer import MaskFormerFeatureExtractor, MaskFormerImageProcessor from .models.mobilenet_v1 import MobileNetV1FeatureExtractor, MobileNetV1ImageProcessor from .models.mobilenet_v2 import MobileNetV2FeatureExtractor, MobileNetV2ImageProcessor from .models.mobilevit import MobileViTFeatureExtractor, MobileViTImageProcessor from .models.oneformer import OneFormerImageProcessor from .models.owlvit import OwlViTFeatureExtractor, OwlViTImageProcessor from .models.perceiver import PerceiverFeatureExtractor, PerceiverImageProcessor from .models.poolformer import PoolFormerFeatureExtractor, PoolFormerImageProcessor from .models.segformer import SegformerFeatureExtractor, SegformerImageProcessor from .models.swin2sr import Swin2SRImageProcessor from .models.tvlt import TvltImageProcessor from .models.videomae import VideoMAEFeatureExtractor, VideoMAEImageProcessor from .models.vilt import ViltFeatureExtractor, ViltImageProcessor, ViltProcessor from .models.vit import ViTFeatureExtractor, ViTImageProcessor from .models.vit_hybrid import ViTHybridImageProcessor from .models.yolos import YolosFeatureExtractor, YolosImageProcessor # Modeling try: if not (is_timm_available() and is_vision_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_timm_and_vision_objects import * else: from .models.conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) from .models.deformable_detr import ( DEFORMABLE_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, DeformableDetrForObjectDetection, DeformableDetrModel, DeformableDetrPreTrainedModel, ) from .models.detr import ( DETR_PRETRAINED_MODEL_ARCHIVE_LIST, DetrForObjectDetection, DetrForSegmentation, DetrModel, DetrPreTrainedModel, ) from .models.table_transformer import ( TABLE_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TableTransformerForObjectDetection, TableTransformerModel, TableTransformerPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * else: # Benchmarks from .benchmark.benchmark import PyTorchBenchmark from .benchmark.benchmark_args import PyTorchBenchmarkArguments from .data.datasets import ( GlueDataset, GlueDataTrainingArguments, LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, SquadDataset, SquadDataTrainingArguments, TextDataset, TextDatasetForNextSentencePrediction, ) from .generation import ( BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer, Constraint, ConstraintListState, DisjunctiveConstraint, ForcedBOSTokenLogitsProcessor, ForcedEOSTokenLogitsProcessor, GenerationMixin, HammingDiversityLogitsProcessor, InfNanRemoveLogitsProcessor, LogitsProcessor, LogitsProcessorList, LogitsWarper, MaxLengthCriteria, MaxTimeCriteria, MinLengthLogitsProcessor, MinNewTokensLengthLogitsProcessor, NoBadWordsLogitsProcessor, NoRepeatNGramLogitsProcessor, PhrasalConstraint, PrefixConstrainedLogitsProcessor, RepetitionPenaltyLogitsProcessor, StoppingCriteria, StoppingCriteriaList, TemperatureLogitsWarper, TopKLogitsWarper, TopPLogitsWarper, TypicalLogitsWarper, top_k_top_p_filtering, ) from .modeling_utils import PreTrainedModel from .models.albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) from .models.align import ( ALIGN_PRETRAINED_MODEL_ARCHIVE_LIST, AlignModel, AlignPreTrainedModel, AlignTextModel, AlignVisionModel, ) from .models.altclip import ( ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, AltCLIPModel, AltCLIPPreTrainedModel, AltCLIPTextModel, AltCLIPVisionModel, ) from .models.audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) from .models.auto import ( MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, MODEL_FOR_AUDIO_XVECTOR_MAPPING, MODEL_FOR_BACKBONE_MAPPING, MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING, MODEL_FOR_CAUSAL_LM_MAPPING, MODEL_FOR_CTC_MAPPING, MODEL_FOR_DEPTH_ESTIMATION_MAPPING, MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING, MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_PRETRAINING_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING, MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, MODEL_FOR_VISION_2_SEQ_MAPPING, MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, MODEL_MAPPING, MODEL_WITH_LM_HEAD_MAPPING, AutoBackbone, AutoModel, AutoModelForAudioClassification, AutoModelForAudioFrameClassification, AutoModelForAudioXVector, AutoModelForCausalLM, AutoModelForCTC, AutoModelForDepthEstimation, AutoModelForDocumentQuestionAnswering, AutoModelForImageClassification, AutoModelForImageSegmentation, AutoModelForInstanceSegmentation, AutoModelForMaskedImageModeling, AutoModelForMaskedLM, AutoModelForMultipleChoice, AutoModelForNextSentencePrediction, AutoModelForObjectDetection, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSemanticSegmentation, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification, AutoModelForSpeechSeq2Seq, AutoModelForTableQuestionAnswering, AutoModelForTokenClassification, AutoModelForUniversalSegmentation, AutoModelForVideoClassification, AutoModelForVision2Seq, AutoModelForVisualQuestionAnswering, AutoModelForZeroShotObjectDetection, AutoModelWithLMHead, ) from .models.bart import ( BART_PRETRAINED_MODEL_ARCHIVE_LIST, BartForCausalLM, BartForConditionalGeneration, BartForQuestionAnswering, BartForSequenceClassification, BartModel, BartPretrainedModel, PretrainedBartModel, ) from .models.beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) from .models.bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) from .models.bert_generation import ( BertGenerationDecoder, BertGenerationEncoder, BertGenerationPreTrainedModel, load_tf_weights_in_bert_generation, ) from .models.big_bird import ( BIG_BIRD_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdForCausalLM, BigBirdForMaskedLM, BigBirdForMultipleChoice, BigBirdForPreTraining, BigBirdForQuestionAnswering, BigBirdForSequenceClassification, BigBirdForTokenClassification, BigBirdLayer, BigBirdModel, BigBirdPreTrainedModel, load_tf_weights_in_big_bird, ) from .models.bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) from .models.biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptModel, BioGptPreTrainedModel, ) from .models.bit import ( BIT_PRETRAINED_MODEL_ARCHIVE_LIST, BitBackbone, BitForImageClassification, BitModel, BitPreTrainedModel, ) from .models.blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) from .models.blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) from .models.blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) from .models.blip_2 import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, Blip2ForConditionalGeneration, Blip2Model, Blip2PreTrainedModel, Blip2QFormerModel, Blip2VisionModel, ) from .models.bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) from .models.bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) from .models.camembert import ( CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, CamembertForCausalLM, CamembertForMaskedLM, CamembertForMultipleChoice, CamembertForQuestionAnswering, CamembertForSequenceClassification, CamembertForTokenClassification, CamembertModel, CamembertPreTrainedModel, ) from .models.canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) from .models.chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) from .models.clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapFeatureExtractor, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) from .models.clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) from .models.clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) from .models.codegen import ( CODEGEN_PRETRAINED_MODEL_ARCHIVE_LIST, CodeGenForCausalLM, CodeGenModel, CodeGenPreTrainedModel, ) from .models.convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) from .models.convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) from .models.ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) from .models.cvt import ( CVT_PRETRAINED_MODEL_ARCHIVE_LIST, CvtForImageClassification, CvtModel, CvtPreTrainedModel, ) from .models.data2vec import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, Data2VecAudioForAudioFrameClassification, Data2VecAudioForCTC, Data2VecAudioForSequenceClassification, Data2VecAudioForXVector, Data2VecAudioModel, Data2VecAudioPreTrainedModel, Data2VecTextForCausalLM, Data2VecTextForMaskedLM, Data2VecTextForMultipleChoice, Data2VecTextForQuestionAnswering, Data2VecTextForSequenceClassification, Data2VecTextForTokenClassification, Data2VecTextModel, Data2VecTextPreTrainedModel, Data2VecVisionForImageClassification, Data2VecVisionForSemanticSegmentation, Data2VecVisionModel, Data2VecVisionPreTrainedModel, ) from .models.deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) from .models.deberta_v2 import ( DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaV2ForMaskedLM, DebertaV2ForMultipleChoice, DebertaV2ForQuestionAnswering, DebertaV2ForSequenceClassification, DebertaV2ForTokenClassification, DebertaV2Model, DebertaV2PreTrainedModel, ) from .models.decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, DecisionTransformerGPT2Model, DecisionTransformerGPT2PreTrainedModel, DecisionTransformerModel, DecisionTransformerPreTrainedModel, ) from .models.deit import ( DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, DeiTPreTrainedModel, ) from .models.deta import ( DETA_PRETRAINED_MODEL_ARCHIVE_LIST, DetaForObjectDetection, DetaModel, DetaPreTrainedModel, ) from .models.dinat import ( DINAT_PRETRAINED_MODEL_ARCHIVE_LIST, DinatBackbone, DinatForImageClassification, DinatModel, DinatPreTrainedModel, ) from .models.distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) from .models.donut import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, DonutSwinModel, DonutSwinPreTrainedModel from .models.dpr import ( DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, DPRContextEncoder, DPRPretrainedContextEncoder, DPRPreTrainedModel, DPRPretrainedQuestionEncoder, DPRPretrainedReader, DPRQuestionEncoder, DPRReader, ) from .models.dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) from .models.efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) from .models.efficientnet import ( EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientNetForImageClassification, EfficientNetModel, EfficientNetPreTrainedModel, ) from .models.electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) from .models.encoder_decoder import EncoderDecoderModel from .models.ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) from .models.ernie_m import ( ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieMForInformationExtraction, ErnieMForMultipleChoice, ErnieMForQuestionAnswering, ErnieMForSequenceClassification, ErnieMForTokenClassification, ErnieMModel, ErnieMPreTrainedModel, ) from .models.esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, EsmFoldPreTrainedModel, EsmForMaskedLM, EsmForProteinFolding, EsmForSequenceClassification, EsmForTokenClassification, EsmModel, EsmPreTrainedModel, ) from .models.flaubert import ( FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertPreTrainedModel, FlaubertWithLMHeadModel, ) from .models.flava import ( FLAVA_PRETRAINED_MODEL_ARCHIVE_LIST, FlavaForPreTraining, FlavaImageCodebook, FlavaImageModel, FlavaModel, FlavaMultimodalModel, FlavaPreTrainedModel, FlavaTextModel, ) from .models.fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) from .models.fsmt import FSMTForConditionalGeneration, FSMTModel, PretrainedFSMTModel from .models.funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) from .models.git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) from .models.glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNModel, GLPNPreTrainedModel, ) from .models.gpt2 import ( GPT2_PRETRAINED_MODEL_ARCHIVE_LIST, GPT2DoubleHeadsModel, GPT2ForSequenceClassification, GPT2ForTokenClassification, GPT2LMHeadModel, GPT2Model, GPT2PreTrainedModel, load_tf_weights_in_gpt2, ) from .models.gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForSequenceClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) from .models.gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) from .models.gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) from .models.gptj import ( GPTJ_PRETRAINED_MODEL_ARCHIVE_LIST, GPTJForCausalLM, GPTJForQuestionAnswering, GPTJForSequenceClassification, GPTJModel, GPTJPreTrainedModel, ) from .models.gptsan_japanese import ( GPTSAN_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTSanJapaneseForConditionalGeneration, GPTSanJapaneseModel, GPTSanJapanesePreTrainedModel, ) from .models.graphormer import ( GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST, GraphormerForGraphClassification, GraphormerModel, GraphormerPreTrainedModel, ) from .models.groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) from .models.hubert import ( HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, HubertForCTC, HubertForSequenceClassification, HubertModel, HubertPreTrainedModel, ) from .models.ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) from .models.imagegpt import ( IMAGEGPT_PRETRAINED_MODEL_ARCHIVE_LIST, ImageGPTForCausalImageModeling, ImageGPTForImageClassification, ImageGPTModel, ImageGPTPreTrainedModel, load_tf_weights_in_imagegpt, ) from .models.jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) from .models.layoutlm import ( LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMForMaskedLM, LayoutLMForQuestionAnswering, LayoutLMForSequenceClassification, LayoutLMForTokenClassification, LayoutLMModel, LayoutLMPreTrainedModel, ) from .models.layoutlmv2 import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMv2ForQuestionAnswering, LayoutLMv2ForSequenceClassification, LayoutLMv2ForTokenClassification, LayoutLMv2Model, LayoutLMv2PreTrainedModel, ) from .models.layoutlmv3 import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMv3ForQuestionAnswering, LayoutLMv3ForSequenceClassification, LayoutLMv3ForTokenClassification, LayoutLMv3Model, LayoutLMv3PreTrainedModel, ) from .models.led import ( LED_PRETRAINED_MODEL_ARCHIVE_LIST, LEDForConditionalGeneration, LEDForQuestionAnswering, LEDForSequenceClassification, LEDModel, LEDPreTrainedModel, ) from .models.levit import ( LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, LevitForImageClassification, LevitForImageClassificationWithTeacher, LevitModel, LevitPreTrainedModel, ) from .models.lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) from .models.llama import ( LlamaForCausalLM, LlamaModel, LlamaPreTrainedModel, ) from .models.longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) from .models.longt5 import ( LONGT5_PRETRAINED_MODEL_ARCHIVE_LIST, LongT5EncoderModel, LongT5ForConditionalGeneration, LongT5Model, LongT5PreTrainedModel, ) from .models.luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) from .models.lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) from .models.m2m_100 import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, M2M100ForConditionalGeneration, M2M100Model, M2M100PreTrainedModel, ) from .models.marian import MarianForCausalLM, MarianModel, MarianMTModel from .models.markuplm import ( MARKUPLM_PRETRAINED_MODEL_ARCHIVE_LIST, MarkupLMForQuestionAnswering, MarkupLMForSequenceClassification, MarkupLMForTokenClassification, MarkupLMModel, MarkupLMPreTrainedModel, ) from .models.mask2former import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, Mask2FormerForUniversalSegmentation, Mask2FormerModel, Mask2FormerPreTrainedModel, ) from .models.maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, MaskFormerSwinBackbone, ) from .models.mbart import ( MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) from .models.mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel from .models.megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) from .models.mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings from .models.mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) from .models.mobilenet_v1 import ( MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetV1ForImageClassification, MobileNetV1Model, MobileNetV1PreTrainedModel, load_tf_weights_in_mobilenet_v1, ) from .models.mobilenet_v2 import ( MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST, MobileNetV2ForImageClassification, MobileNetV2ForSemanticSegmentation, MobileNetV2Model, MobileNetV2PreTrainedModel, load_tf_weights_in_mobilenet_v2, ) from .models.mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) from .models.mpnet import ( MPNET_PRETRAINED_MODEL_ARCHIVE_LIST, MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetLayer, MPNetModel, MPNetPreTrainedModel, ) from .models.mt5 import MT5EncoderModel, MT5ForConditionalGeneration, MT5Model, MT5PreTrainedModel from .models.mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) from .models.nat import ( NAT_PRETRAINED_MODEL_ARCHIVE_LIST, NatBackbone, NatForImageClassification, NatModel, NatPreTrainedModel, ) from .models.nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) from .models.nystromformer import ( NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerLayer, NystromformerModel, NystromformerPreTrainedModel, ) from .models.oneformer import ( ONEFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, OneFormerForUniversalSegmentation, OneFormerModel, OneFormerPreTrainedModel, ) from .models.openai import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, OpenAIGPTPreTrainedModel, load_tf_weights_in_openai_gpt, ) from .models.opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) from .models.owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) from .models.pegasus import ( PegasusForCausalLM, PegasusForConditionalGeneration, PegasusModel, PegasusPreTrainedModel, ) from .models.pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) from .models.perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) from .models.plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) from .models.poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) from .models.prophetnet import ( PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST, ProphetNetDecoder, ProphetNetEncoder, ProphetNetForCausalLM, ProphetNetForConditionalGeneration, ProphetNetModel, ProphetNetPreTrainedModel, ) from .models.qdqbert import ( QDQBERT_PRETRAINED_MODEL_ARCHIVE_LIST, QDQBertForMaskedLM, QDQBertForMultipleChoice, QDQBertForNextSentencePrediction, QDQBertForQuestionAnswering, QDQBertForSequenceClassification, QDQBertForTokenClassification, QDQBertLayer, QDQBertLMHeadModel, QDQBertModel, QDQBertPreTrainedModel, load_tf_weights_in_qdqbert, ) from .models.rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration from .models.realm import ( REALM_PRETRAINED_MODEL_ARCHIVE_LIST, RealmEmbedder, RealmForOpenQA, RealmKnowledgeAugEncoder, RealmPreTrainedModel, RealmReader, RealmRetriever, RealmScorer, load_tf_weights_in_realm, ) from .models.reformer import ( REFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ReformerAttention, ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerLayer, ReformerModel, ReformerModelWithLMHead, ReformerPreTrainedModel, ) from .models.regnet import ( REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, RegNetForImageClassification, RegNetModel, RegNetPreTrainedModel, ) from .models.rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) from .models.resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) from .models.retribert import RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RetriBertModel, RetriBertPreTrainedModel from .models.roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) from .models.roberta_prelayernorm import ( ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaPreLayerNormForCausalLM, RobertaPreLayerNormForMaskedLM, RobertaPreLayerNormForMultipleChoice, RobertaPreLayerNormForQuestionAnswering, RobertaPreLayerNormForSequenceClassification, RobertaPreLayerNormForTokenClassification, RobertaPreLayerNormModel, RobertaPreLayerNormPreTrainedModel, ) from .models.roc_bert import ( ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, RoCBertForCausalLM, RoCBertForMaskedLM, RoCBertForMultipleChoice, RoCBertForPreTraining, RoCBertForQuestionAnswering, RoCBertForSequenceClassification, RoCBertForTokenClassification, RoCBertLayer, RoCBertModel, RoCBertPreTrainedModel, load_tf_weights_in_roc_bert, ) from .models.roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) from .models.segformer import ( SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SegformerDecodeHead, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerLayer, SegformerModel, SegformerPreTrainedModel, ) from .models.sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) from .models.sew_d import ( SEW_D_PRETRAINED_MODEL_ARCHIVE_LIST, SEWDForCTC, SEWDForSequenceClassification, SEWDModel, SEWDPreTrainedModel, ) from .models.speech_encoder_decoder import SpeechEncoderDecoderModel from .models.speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, Speech2TextForConditionalGeneration, Speech2TextModel, Speech2TextPreTrainedModel, ) from .models.speech_to_text_2 import Speech2Text2ForCausalLM, Speech2Text2PreTrainedModel from .models.speecht5 import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechT5ForSpeechToSpeech, SpeechT5ForSpeechToText, SpeechT5ForTextToSpeech, SpeechT5HifiGan, SpeechT5Model, SpeechT5PreTrainedModel, ) from .models.splinter import ( SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST, SplinterForPreTraining, SplinterForQuestionAnswering, SplinterLayer, SplinterModel, SplinterPreTrainedModel, ) from .models.squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) from .models.swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) from .models.swin2sr import ( SWIN2SR_PRETRAINED_MODEL_ARCHIVE_LIST, Swin2SRForImageSuperResolution, Swin2SRModel, Swin2SRPreTrainedModel, ) from .models.swinv2 import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, Swinv2ForImageClassification, Swinv2ForMaskedImageModeling, Swinv2Model, Swinv2PreTrainedModel, ) from .models.switch_transformers import ( SWITCH_TRANSFORMERS_PRETRAINED_MODEL_ARCHIVE_LIST, SwitchTransformersEncoderModel, SwitchTransformersForConditionalGeneration, SwitchTransformersModel, SwitchTransformersPreTrainedModel, SwitchTransformersSparseMLP, SwitchTransformersTop1Router, ) from .models.t5 import ( T5_PRETRAINED_MODEL_ARCHIVE_LIST, T5EncoderModel, T5ForConditionalGeneration, T5Model, T5PreTrainedModel, load_tf_weights_in_t5, ) from .models.tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) from .models.time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) from .models.timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) from .models.trajectory_transformer import ( TRAJECTORY_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TrajectoryTransformerModel, TrajectoryTransformerPreTrainedModel, ) from .models.transfo_xl import ( TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, AdaptiveEmbedding, TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel, TransfoXLPreTrainedModel, load_tf_weights_in_transfo_xl, ) from .models.trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel from .models.tvlt import ( TVLT_PRETRAINED_MODEL_ARCHIVE_LIST, TvltForAudioVisualClassification, TvltForPreTraining, TvltModel, TvltPreTrainedModel, ) from .models.unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) from .models.unispeech_sat import ( UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechSatForAudioFrameClassification, UniSpeechSatForCTC, UniSpeechSatForPreTraining, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, UniSpeechSatModel, UniSpeechSatPreTrainedModel, ) from .models.upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel from .models.van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) from .models.videomae import ( VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, VideoMAEPreTrainedModel, ) from .models.vilt import ( VILT_PRETRAINED_MODEL_ARCHIVE_LIST, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltForTokenClassification, ViltLayer, ViltModel, ViltPreTrainedModel, ) from .models.vision_encoder_decoder import VisionEncoderDecoderModel from .models.vision_text_dual_encoder import VisionTextDualEncoderModel from .models.visual_bert import ( VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForRegionToPhraseAlignment, VisualBertForVisualReasoning, VisualBertLayer, VisualBertModel, VisualBertPreTrainedModel, ) from .models.vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) from .models.vit_hybrid import ( VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST, ViTHybridForImageClassification, ViTHybridModel, ViTHybridPreTrainedModel, ) from .models.vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) from .models.vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) from .models.wav2vec2 import ( WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, Wav2Vec2ForAudioFrameClassification, Wav2Vec2ForCTC, Wav2Vec2ForMaskedLM, Wav2Vec2ForPreTraining, Wav2Vec2ForSequenceClassification, Wav2Vec2ForXVector, Wav2Vec2Model, Wav2Vec2PreTrainedModel, ) from .models.wav2vec2_conformer import ( WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, Wav2Vec2ConformerForAudioFrameClassification, Wav2Vec2ConformerForCTC, Wav2Vec2ConformerForPreTraining, Wav2Vec2ConformerForSequenceClassification, Wav2Vec2ConformerForXVector, Wav2Vec2ConformerModel, Wav2Vec2ConformerPreTrainedModel, ) from .models.wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) from .models.whisper import ( WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, WhisperForConditionalGeneration, WhisperModel, WhisperPreTrainedModel, ) from .models.x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) from .models.xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel from .models.xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) from .models.xlm_prophetnet import ( XLM_PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLMProphetNetDecoder, XLMProphetNetEncoder, XLMProphetNetForCausalLM, XLMProphetNetForConditionalGeneration, XLMProphetNetModel, XLMProphetNetPreTrainedModel, ) from .models.xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) from .models.xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) from .models.xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) from .models.xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) from .models.yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) from .models.yoso import ( YOSO_PRETRAINED_MODEL_ARCHIVE_LIST, YosoForMaskedLM, YosoForMultipleChoice, YosoForQuestionAnswering, YosoForSequenceClassification, YosoForTokenClassification, YosoLayer, YosoModel, YosoPreTrainedModel, ) # Optimization from .optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pytorch_utils import Conv1D, apply_chunking_to_forward, prune_layer # Trainer from .trainer import Trainer from .trainer_pt_utils import torch_distributed_zero_first from .trainer_seq2seq import Seq2SeqTrainer # TensorFlow try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: # Import the same objects as dummies to get them in the namespace. # They will raise an import error if the user tries to instantiate / use them. from .utils.dummy_tf_objects import * else: from .benchmark.benchmark_args_tf import TensorFlowBenchmarkArguments # Benchmarks from .benchmark.benchmark_tf import TensorFlowBenchmark from .generation import ( TFForcedBOSTokenLogitsProcessor, TFForcedEOSTokenLogitsProcessor, TFGenerationMixin, TFLogitsProcessor, TFLogitsProcessorList, TFLogitsWarper, TFMinLengthLogitsProcessor, TFNoBadWordsLogitsProcessor, TFNoRepeatNGramLogitsProcessor, TFRepetitionPenaltyLogitsProcessor, TFTemperatureLogitsWarper, TFTopKLogitsWarper, TFTopPLogitsWarper, tf_top_k_top_p_filtering, ) from .keras_callbacks import KerasMetricCallback, PushToHubCallback from .modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMMainLayer, TFLayoutLMModel, TFLayoutLMPreTrainedModel, ) from .modeling_tf_utils import TFPreTrainedModel, TFSequenceSummary, TFSharedEmbeddings, shape_list # TensorFlow model imports from .models.albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) from .models.auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForDocumentQuestionAnswering, TFAutoModelForImageClassification, TFAutoModelForMaskedLM, TFAutoModelForMultipleChoice, TFAutoModelForNextSentencePrediction, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSemanticSegmentation, TFAutoModelForSeq2SeqLM, TFAutoModelForSequenceClassification, TFAutoModelForSpeechSeq2Seq, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelForVision2Seq, TFAutoModelWithLMHead, ) from .models.bart import ( TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBartModel, TFBartPretrainedModel, ) from .models.bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) from .models.blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) from .models.blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) from .models.camembert import ( TF_CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFCamembertForCausalLM, TFCamembertForMaskedLM, TFCamembertForMultipleChoice, TFCamembertForQuestionAnswering, TFCamembertForSequenceClassification, TFCamembertForTokenClassification, TFCamembertModel, TFCamembertPreTrainedModel, ) from .models.clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) from .models.convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) from .models.convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel from .models.ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) from .models.cvt import ( TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST, TFCvtForImageClassification, TFCvtModel, TFCvtPreTrainedModel, ) from .models.data2vec import ( TFData2VecVisionForImageClassification, TFData2VecVisionForSemanticSegmentation, TFData2VecVisionModel, TFData2VecVisionPreTrainedModel, ) from .models.deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) from .models.deberta_v2 import ( TF_DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaV2ForMaskedLM, TFDebertaV2ForQuestionAnswering, TFDebertaV2ForSequenceClassification, TFDebertaV2ForTokenClassification, TFDebertaV2Model, TFDebertaV2PreTrainedModel, ) from .models.deit import ( TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, TFDeiTPreTrainedModel, ) from .models.distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) from .models.dpr import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, TFDPRContextEncoder, TFDPRPretrainedContextEncoder, TFDPRPretrainedQuestionEncoder, TFDPRPretrainedReader, TFDPRQuestionEncoder, TFDPRReader, ) from .models.electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) from .models.encoder_decoder import TFEncoderDecoderModel from .models.esm import ( ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, TFEsmPreTrainedModel, ) from .models.flaubert import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertPreTrainedModel, TFFlaubertWithLMHeadModel, ) from .models.funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) from .models.gpt2 import ( TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST, TFGPT2DoubleHeadsModel, TFGPT2ForSequenceClassification, TFGPT2LMHeadModel, TFGPT2MainLayer, TFGPT2Model, TFGPT2PreTrainedModel, ) from .models.gptj import ( TFGPTJForCausalLM, TFGPTJForQuestionAnswering, TFGPTJForSequenceClassification, TFGPTJModel, TFGPTJPreTrainedModel, ) from .models.groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) from .models.hubert import ( TF_HUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFHubertForCTC, TFHubertModel, TFHubertPreTrainedModel, ) from .models.layoutlmv3 import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMv3ForQuestionAnswering, TFLayoutLMv3ForSequenceClassification, TFLayoutLMv3ForTokenClassification, TFLayoutLMv3Model, TFLayoutLMv3PreTrainedModel, ) from .models.led import TFLEDForConditionalGeneration, TFLEDModel, TFLEDPreTrainedModel from .models.longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) from .models.lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) from .models.marian import TFMarianModel, TFMarianMTModel, TFMarianPreTrainedModel from .models.mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel from .models.mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) from .models.mpnet import ( TF_MPNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFMPNetForMaskedLM, TFMPNetForMultipleChoice, TFMPNetForQuestionAnswering, TFMPNetForSequenceClassification, TFMPNetForTokenClassification, TFMPNetMainLayer, TFMPNetModel, TFMPNetPreTrainedModel, ) from .models.mt5 import TFMT5EncoderModel, TFMT5ForConditionalGeneration, TFMT5Model from .models.openai import ( TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification, TFOpenAIGPTLMHeadModel, TFOpenAIGPTMainLayer, TFOpenAIGPTModel, TFOpenAIGPTPreTrainedModel, ) from .models.opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel from .models.pegasus import TFPegasusForConditionalGeneration, TFPegasusModel, TFPegasusPreTrainedModel from .models.rag import TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration from .models.regnet import ( TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel, TFRegNetPreTrainedModel, ) from .models.rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) from .models.resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) from .models.roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) from .models.roberta_prelayernorm import ( TF_ROBERTA_PRELAYERNORM_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaPreLayerNormForCausalLM, TFRobertaPreLayerNormForMaskedLM, TFRobertaPreLayerNormForMultipleChoice, TFRobertaPreLayerNormForQuestionAnswering, TFRobertaPreLayerNormForSequenceClassification, TFRobertaPreLayerNormForTokenClassification, TFRobertaPreLayerNormMainLayer, TFRobertaPreLayerNormModel, TFRobertaPreLayerNormPreTrainedModel, ) from .models.roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) from .models.segformer import ( TF_SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFSegformerDecodeHead, TFSegformerForImageClassification, TFSegformerForSemanticSegmentation, TFSegformerModel, TFSegformerPreTrainedModel, ) from .models.speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeech2TextForConditionalGeneration, TFSpeech2TextModel, TFSpeech2TextPreTrainedModel, ) from .models.swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) from .models.t5 import ( TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST, TFT5EncoderModel, TFT5ForConditionalGeneration, TFT5Model, TFT5PreTrainedModel, ) from .models.tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) from .models.transfo_xl import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFAdaptiveEmbedding, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLMainLayer, TFTransfoXLModel, TFTransfoXLPreTrainedModel, ) from .models.vision_encoder_decoder import TFVisionEncoderDecoderModel from .models.vision_text_dual_encoder import TFVisionTextDualEncoderModel from .models.vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel from .models.vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel from .models.wav2vec2 import ( TF_WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, TFWav2Vec2ForCTC, TFWav2Vec2Model, TFWav2Vec2PreTrainedModel, ) from .models.whisper import ( TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST, TFWhisperForConditionalGeneration, TFWhisperModel, TFWhisperPreTrainedModel, ) from .models.xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) from .models.xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) from .models.xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) from .models.xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) # Optimization from .optimization_tf import AdamWeightDecay, GradientAccumulator, WarmUp, create_optimizer # Trainer from .trainer_tf import TFTrainer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: # Import the same objects as dummies to get them in the namespace. # They will raise an import error if the user tries to instantiate / use them. from .utils.dummy_flax_objects import * else: from .generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxGenerationMixin, FlaxLogitsProcessor, FlaxLogitsProcessorList, FlaxLogitsWarper, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) from .modeling_flax_utils import FlaxPreTrainedModel # Flax model imports from .models.albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) from .models.auto import ( FLAX_MODEL_FOR_CAUSAL_LM_MAPPING, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, FLAX_MODEL_FOR_MASKED_LM_MAPPING, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, FLAX_MODEL_FOR_PRETRAINING_MAPPING, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING, FLAX_MODEL_MAPPING, FlaxAutoModel, FlaxAutoModelForCausalLM, FlaxAutoModelForImageClassification, FlaxAutoModelForMaskedLM, FlaxAutoModelForMultipleChoice, FlaxAutoModelForNextSentencePrediction, FlaxAutoModelForPreTraining, FlaxAutoModelForQuestionAnswering, FlaxAutoModelForSeq2SeqLM, FlaxAutoModelForSequenceClassification, FlaxAutoModelForSpeechSeq2Seq, FlaxAutoModelForTokenClassification, FlaxAutoModelForVision2Seq, ) from .models.bart import ( FlaxBartDecoderPreTrainedModel, FlaxBartForCausalLM, FlaxBartForConditionalGeneration, FlaxBartForQuestionAnswering, FlaxBartForSequenceClassification, FlaxBartModel, FlaxBartPreTrainedModel, ) from .models.beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) from .models.bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) from .models.big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, FlaxBigBirdPreTrainedModel, ) from .models.blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) from .models.blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) from .models.clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) from .models.distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) from .models.electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) from .models.encoder_decoder import FlaxEncoderDecoderModel from .models.gpt2 import FlaxGPT2LMHeadModel, FlaxGPT2Model, FlaxGPT2PreTrainedModel from .models.gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel from .models.gptj import FlaxGPTJForCausalLM, FlaxGPTJModel, FlaxGPTJPreTrainedModel from .models.longt5 import FlaxLongT5ForConditionalGeneration, FlaxLongT5Model, FlaxLongT5PreTrainedModel from .models.marian import FlaxMarianModel, FlaxMarianMTModel, FlaxMarianPreTrainedModel from .models.mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) from .models.mt5 import FlaxMT5EncoderModel, FlaxMT5ForConditionalGeneration, FlaxMT5Model from .models.opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel from .models.pegasus import FlaxPegasusForConditionalGeneration, FlaxPegasusModel, FlaxPegasusPreTrainedModel from .models.roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) from .models.roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormPreTrainedModel, ) from .models.roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) from .models.speech_encoder_decoder import FlaxSpeechEncoderDecoderModel from .models.t5 import FlaxT5EncoderModel, FlaxT5ForConditionalGeneration, FlaxT5Model, FlaxT5PreTrainedModel from .models.vision_encoder_decoder import FlaxVisionEncoderDecoderModel from .models.vision_text_dual_encoder import FlaxVisionTextDualEncoderModel from .models.vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel from .models.wav2vec2 import ( FlaxWav2Vec2ForCTC, FlaxWav2Vec2ForPreTraining, FlaxWav2Vec2Model, FlaxWav2Vec2PreTrainedModel, ) from .models.whisper import FlaxWhisperForConditionalGeneration, FlaxWhisperModel, FlaxWhisperPreTrainedModel from .models.xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel from .models.xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys sys.modules[__name__] = _LazyModule( __name__, globals()["__file__"], _import_structure, module_spec=__spec__, extra_objects={"__version__": __version__}, ) if not is_tf_available() and not is_torch_available() and not is_flax_available(): logger.warning( "None of PyTorch, TensorFlow >= 2.0, or Flax have been found. " "Models won't be available and only tokenizers, configuration " "and file/data utilities can be used." )
27182812/ChatGLM-LLaMA-chinese-insturct
4,982
src/transformers/convert_slow_tokenizers_checkpoints_to_fast.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 slow tokenizers checkpoints in fast (serialization format of the `tokenizers` library)""" import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() logger = logging.get_logger(__name__) TOKENIZER_CLASSES = {name: getattr(transformers, name + "Fast") for name in SLOW_TO_FAST_CONVERTERS} def convert_slow_checkpoint_to_fast(tokenizer_name, checkpoint_name, dump_path, force_download): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f"Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys())}.") if tokenizer_name is None: tokenizer_names = TOKENIZER_CLASSES else: tokenizer_names = {tokenizer_name: getattr(transformers, tokenizer_name + "Fast")} logger.info(f"Loading tokenizer classes: {tokenizer_names}") for tokenizer_name in tokenizer_names: tokenizer_class = TOKENIZER_CLASSES[tokenizer_name] add_prefix = True if checkpoint_name is None: checkpoint_names = list(tokenizer_class.max_model_input_sizes.keys()) else: checkpoint_names = [checkpoint_name] logger.info(f"For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}") for checkpoint in checkpoint_names: logger.info(f"Loading {tokenizer_class.__class__.__name__} {checkpoint}") # Load tokenizer tokenizer = tokenizer_class.from_pretrained(checkpoint, force_download=force_download) # Save fast tokenizer logger.info(f"Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}") # For organization names we create sub-directories if "/" in checkpoint: checkpoint_directory, checkpoint_prefix_name = checkpoint.split("/") dump_path_full = os.path.join(dump_path, checkpoint_directory) elif add_prefix: checkpoint_prefix_name = checkpoint dump_path_full = dump_path else: checkpoint_prefix_name = None dump_path_full = dump_path logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}") if checkpoint in list(tokenizer.pretrained_vocab_files_map.values())[0]: file_path = list(tokenizer.pretrained_vocab_files_map.values())[0][checkpoint] next_char = file_path.split(checkpoint)[-1][0] if next_char == "/": dump_path_full = os.path.join(dump_path_full, checkpoint_prefix_name) checkpoint_prefix_name = None logger.info(f"=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}") file_names = tokenizer.save_pretrained( dump_path_full, legacy_format=False, filename_prefix=checkpoint_prefix_name ) logger.info(f"=> File names {file_names}") for file_name in file_names: if not file_name.endswith("tokenizer.json"): os.remove(file_name) logger.info(f"=> removing {file_name}") if __name__ == "__main__": parser = argparse.ArgumentParser() # Required parameters parser.add_argument( "--dump_path", default=None, type=str, required=True, help="Path to output generated fast tokenizer files." ) parser.add_argument( "--tokenizer_name", default=None, type=str, help=( f"Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will " "download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--checkpoint_name", default=None, type=str, help="Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.", ) parser.add_argument( "--force_download", action="store_true", help="Re-download checkpoints.", ) args = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
233zzh/TitanDataOperationSystem
253,669
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/js/jquery-ui.min.js
/*! jQuery UI - v1.12.1 - 2016-09-14 * http://jqueryui.com * Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js * Copyright jQuery Foundation and other contributors; Licensed MIT */ (function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,o)}function o(){t.datepicker._isDisabledDatepicker(m.inline?m.dpDiv.parent()[0]:m.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function a(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;a>o;o++)for(i in n[o])s=n[o][i],n[o].hasOwnProperty(i)&&void 0!==s&&(e[i]=t.isPlainObject(s)?t.isPlainObject(e[i])?t.widget.extend({},e[i],s):t.widget.extend({},s):s);return e},t.widget.bridge=function(e,i){var s=i.prototype.widgetFullName||e;t.fn[e]=function(n){var o="string"==typeof n,a=l.call(arguments,1),r=this;return o?this.length||"instance"!==n?this.each(function(){var i,o=t.data(this,s);return"instance"===n?(r=o,!1):o?t.isFunction(o[n])&&"_"!==n.charAt(0)?(i=o[n].apply(o,a),i!==o&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+n+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+n+"'")}):r=void 0:(a.length&&(n=t.widget.extend.apply(null,[n].concat(a))),this.each(function(){var e=t.data(this,s);e?(e.option(n||{}),e._init&&e._init()):t.data(this,s,new i(n,this))})),r}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{classes:{},disabled:!1,create:null},_createWidget:function(e,i){i=t(i||this.defaultElement||this)[0],this.element=t(i),this.uuid=h++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},i!==this&&(t.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===i&&this.destroy()}}),this.document=t(i.style?i.ownerDocument:i.document||i),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),e),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),this._on(e.element,{remove:"_untrackClassesElement"}),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_untrackClassesElement:function(e){var i=this;t.each(i.classesElementLookup,function(s,n){-1!==t.inArray(e.target,n)&&(i.classesElementLookup[s]=t(n.not(e.target).get()))})},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+o.eventNamespace,c=h[2];c?n.on(l,c,r):i.on(l,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,function(){function e(t,e,i){return[parseFloat(t[0])*(u.test(t[0])?e/100:1),parseFloat(t[1])*(u.test(t[1])?i/100:1)]}function i(e,i){return parseInt(t.css(e,i),10)||0}function s(e){var i=e[0];return 9===i.nodeType?{width:e.width(),height:e.height(),offset:{top:0,left:0}}:t.isWindow(i)?{width:e.width(),height:e.height(),offset:{top:e.scrollTop(),left:e.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:e.outerWidth(),height:e.outerHeight(),offset:e.offset()}}var n,o=Math.max,a=Math.abs,r=/left|center|right/,h=/top|center|bottom/,l=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,u=/%$/,d=t.fn.position;t.position={scrollbarWidth:function(){if(void 0!==n)return n;var e,i,s=t("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return t("body").append(s),e=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,e===i&&(i=s[0].clientWidth),s.remove(),n=e-i},getScrollInfo:function(e){var i=e.isWindow||e.isDocument?"":e.element.css("overflow-x"),s=e.isWindow||e.isDocument?"":e.element.css("overflow-y"),n="scroll"===i||"auto"===i&&e.width<e.element[0].scrollWidth,o="scroll"===s||"auto"===s&&e.height<e.element[0].scrollHeight;return{width:o?t.position.scrollbarWidth():0,height:n?t.position.scrollbarWidth():0}},getWithinInfo:function(e){var i=t(e||window),s=t.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType,o=!s&&!n;return{element:i,isWindow:s,isDocument:n,offset:o?t(e).offset():{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:i.outerWidth(),height:i.outerHeight()}}},t.fn.position=function(n){if(!n||!n.of)return d.apply(this,arguments);n=t.extend({},n);var u,p,f,g,m,_,v=t(n.of),b=t.position.getWithinInfo(n.within),y=t.position.getScrollInfo(b),w=(n.collision||"flip").split(" "),k={};return _=s(v),v[0].preventDefault&&(n.at="left top"),p=_.width,f=_.height,g=_.offset,m=t.extend({},g),t.each(["my","at"],function(){var t,e,i=(n[this]||"").split(" ");1===i.length&&(i=r.test(i[0])?i.concat(["center"]):h.test(i[0])?["center"].concat(i):["center","center"]),i[0]=r.test(i[0])?i[0]:"center",i[1]=h.test(i[1])?i[1]:"center",t=l.exec(i[0]),e=l.exec(i[1]),k[this]=[t?t[0]:0,e?e[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===w.length&&(w[1]=w[0]),"right"===n.at[0]?m.left+=p:"center"===n.at[0]&&(m.left+=p/2),"bottom"===n.at[1]?m.top+=f:"center"===n.at[1]&&(m.top+=f/2),u=e(k.at,p,f),m.left+=u[0],m.top+=u[1],this.each(function(){var s,r,h=t(this),l=h.outerWidth(),c=h.outerHeight(),d=i(this,"marginLeft"),_=i(this,"marginTop"),x=l+d+i(this,"marginRight")+y.width,C=c+_+i(this,"marginBottom")+y.height,D=t.extend({},m),I=e(k.my,h.outerWidth(),h.outerHeight());"right"===n.my[0]?D.left-=l:"center"===n.my[0]&&(D.left-=l/2),"bottom"===n.my[1]?D.top-=c:"center"===n.my[1]&&(D.top-=c/2),D.left+=I[0],D.top+=I[1],s={marginLeft:d,marginTop:_},t.each(["left","top"],function(e,i){t.ui.position[w[e]]&&t.ui.position[w[e]][i](D,{targetWidth:p,targetHeight:f,elemWidth:l,elemHeight:c,collisionPosition:s,collisionWidth:x,collisionHeight:C,offset:[u[0]+I[0],u[1]+I[1]],my:n.my,at:n.at,within:b,elem:h})}),n.using&&(r=function(t){var e=g.left-D.left,i=e+p-l,s=g.top-D.top,r=s+f-c,u={target:{element:v,left:g.left,top:g.top,width:p,height:f},element:{element:h,left:D.left,top:D.top,width:l,height:c},horizontal:0>i?"left":e>0?"right":"center",vertical:0>r?"top":s>0?"bottom":"middle"};l>p&&p>a(e+i)&&(u.horizontal="center"),c>f&&f>a(s+r)&&(u.vertical="middle"),u.important=o(a(e),a(i))>o(a(s),a(r))?"horizontal":"vertical",n.using.call(this,t,u)}),h.offset(t.extend(D,{using:r}))})},t.ui.position={fit:{left:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=t.left-e.collisionPosition.marginLeft,h=n-r,l=r+e.collisionWidth-a-n;e.collisionWidth>a?h>0&&0>=l?(i=t.left+h+e.collisionWidth-a-n,t.left+=h-i):t.left=l>0&&0>=h?n:h>l?n+a-e.collisionWidth:n:h>0?t.left+=h:l>0?t.left-=l:t.left=o(t.left-r,t.left)},top:function(t,e){var i,s=e.within,n=s.isWindow?s.scrollTop:s.offset.top,a=e.within.height,r=t.top-e.collisionPosition.marginTop,h=n-r,l=r+e.collisionHeight-a-n;e.collisionHeight>a?h>0&&0>=l?(i=t.top+h+e.collisionHeight-a-n,t.top+=h-i):t.top=l>0&&0>=h?n:h>l?n+a-e.collisionHeight:n:h>0?t.top+=h:l>0?t.top-=l:t.top=o(t.top-r,t.top)}},flip:{left:function(t,e){var i,s,n=e.within,o=n.offset.left+n.scrollLeft,r=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=t.left-e.collisionPosition.marginLeft,c=l-h,u=l+e.collisionWidth-r-h,d="left"===e.my[0]?-e.elemWidth:"right"===e.my[0]?e.elemWidth:0,p="left"===e.at[0]?e.targetWidth:"right"===e.at[0]?-e.targetWidth:0,f=-2*e.offset[0];0>c?(i=t.left+d+p+f+e.collisionWidth-r-o,(0>i||a(c)>i)&&(t.left+=d+p+f)):u>0&&(s=t.left-e.collisionPosition.marginLeft+d+p+f-h,(s>0||u>a(s))&&(t.left+=d+p+f))},top:function(t,e){var i,s,n=e.within,o=n.offset.top+n.scrollTop,r=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=t.top-e.collisionPosition.marginTop,c=l-h,u=l+e.collisionHeight-r-h,d="top"===e.my[1],p=d?-e.elemHeight:"bottom"===e.my[1]?e.elemHeight:0,f="top"===e.at[1]?e.targetHeight:"bottom"===e.at[1]?-e.targetHeight:0,g=-2*e.offset[1];0>c?(s=t.top+p+f+g+e.collisionHeight-r-o,(0>s||a(c)>s)&&(t.top+=p+f+g)):u>0&&(i=t.top-e.collisionPosition.marginTop+p+f+g-h,(i>0||u>a(i))&&(t.top+=p+f+g))}},flipfit:{left:function(){t.ui.position.flip.left.apply(this,arguments),t.ui.position.fit.left.apply(this,arguments)},top:function(){t.ui.position.flip.top.apply(this,arguments),t.ui.position.fit.top.apply(this,arguments)}}}}(),t.ui.position,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}});var c="ui-effects-",u="ui-effects-style",d="ui-effects-animated",p=t;t.effects={effect:{}},function(t,e){function i(t,e,i){var s=u[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:0>t?0:t>s.max?s.max:t)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(t,o){var a,r=o.re.exec(i),h=r&&o.parse(r),l=o.space||"rgba";return h?(a=s[l](h),s[c[l].cache]=a[c[l].cache],n=s._rgba=a._rgba,!1):e}),n.length?("0,0,0,0"===n.join()&&t.extend(n,o.transparent),s):o[i]}function n(t,e,i){return i=(i+1)%1,1>6*i?t+6*(e-t)*i:1>2*i?e:2>3*i?t+6*(e-t)*(2/3-i):t}var o,a="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[t[1],t[2],t[3],t[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(t){return[2.55*t[1],2.55*t[2],2.55*t[3],t[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(t){return[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(t){return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(t){return[t[1],t[2]/100,t[3]/100,t[4]]}}],l=t.Color=function(e,i,s,n){return new t.Color.fn.parse(e,i,s,n)},c={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},u={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},d=l.support={},p=t("<p>")[0],f=t.each;p.style.cssText="background-color:rgba(1,1,1,.5)",d.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(c,function(t,e){e.cache="_"+t,e.props.alpha={idx:3,type:"percent",def:1}}),l.fn=t.extend(l.prototype,{parse:function(n,a,r,h){if(n===e)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=t(n).css(a),a=e);var u=this,d=t.type(n),p=this._rgba=[];return a!==e&&(n=[n,a,r,h],d="array"),"string"===d?this.parse(s(n)||o._default):"array"===d?(f(c.rgba.props,function(t,e){p[e.idx]=i(n[e.idx],e)}),this):"object"===d?(n instanceof l?f(c,function(t,e){n[e.cache]&&(u[e.cache]=n[e.cache].slice())}):f(c,function(e,s){var o=s.cache;f(s.props,function(t,e){if(!u[o]&&s.to){if("alpha"===t||null==n[t])return;u[o]=s.to(u._rgba)}u[o][e.idx]=i(n[t],e,!0)}),u[o]&&0>t.inArray(null,u[o].slice(0,3))&&(u[o][3]=1,s.from&&(u._rgba=s.from(u[o])))}),this):e},is:function(t){var i=l(t),s=!0,n=this;return f(c,function(t,o){var a,r=i[o.cache];return r&&(a=n[o.cache]||o.to&&o.to(n._rgba)||[],f(o.props,function(t,i){return null!=r[i.idx]?s=r[i.idx]===a[i.idx]:e})),s}),s},_space:function(){var t=[],e=this;return f(c,function(i,s){e[s.cache]&&t.push(i)}),t.pop()},transition:function(t,e){var s=l(t),n=s._space(),o=c[n],a=0===this.alpha()?l("transparent"):this,r=a[o.cache]||o.to(a._rgba),h=r.slice();return s=s[o.cache],f(o.props,function(t,n){var o=n.idx,a=r[o],l=s[o],c=u[n.type]||{};null!==l&&(null===a?h[o]=l:(c.mod&&(l-a>c.mod/2?a+=c.mod:a-l>c.mod/2&&(a-=c.mod)),h[o]=i((l-a)*e+a,n)))}),this[n](h)},blend:function(e){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(e)._rgba;return l(t.map(i,function(t,e){return(1-s)*n[e]+s*t}))},toRgbaString:function(){var e="rgba(",i=t.map(this._rgba,function(t,e){return null==t?e>2?1:0:t});return 1===i[3]&&(i.pop(),e="rgb("),e+i.join()+")"},toHslaString:function(){var e="hsla(",i=t.map(this.hsla(),function(t,e){return null==t&&(t=e>2?1:0),e&&3>e&&(t=Math.round(100*t)+"%"),t});return 1===i[3]&&(i.pop(),e="hsl("),e+i.join()+")"},toHexString:function(e){var i=this._rgba.slice(),s=i.pop();return e&&i.push(~~(255*s)),"#"+t.map(i,function(t){return t=(t||0).toString(16),1===t.length?"0"+t:t}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,c.hsla.to=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e,i,s=t[0]/255,n=t[1]/255,o=t[2]/255,a=t[3],r=Math.max(s,n,o),h=Math.min(s,n,o),l=r-h,c=r+h,u=.5*c;return e=h===r?0:s===r?60*(n-o)/l+360:n===r?60*(o-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=u?l/c:l/(2-c),[Math.round(e)%360,i,u,null==a?1:a]},c.hsla.from=function(t){if(null==t[0]||null==t[1]||null==t[2])return[null,null,null,t[3]];var e=t[0]/360,i=t[1],s=t[2],o=t[3],a=.5>=s?s*(1+i):s+i-s*i,r=2*s-a;return[Math.round(255*n(r,a,e+1/3)),Math.round(255*n(r,a,e)),Math.round(255*n(r,a,e-1/3)),o]},f(c,function(s,n){var o=n.props,a=n.cache,h=n.to,c=n.from;l.fn[s]=function(s){if(h&&!this[a]&&(this[a]=h(this._rgba)),s===e)return this[a].slice();var n,r=t.type(s),u="array"===r||"object"===r?s:arguments,d=this[a].slice();return f(o,function(t,e){var s=u["object"===r?t:e.idx];null==s&&(s=d[e.idx]),d[e.idx]=i(s,e)}),c?(n=l(c(d)),n[a]=d,n):l(d)},f(o,function(e,i){l.fn[e]||(l.fn[e]=function(n){var o,a=t.type(n),h="alpha"===e?this._hsla?"hsla":"rgba":s,l=this[h](),c=l[i.idx];return"undefined"===a?c:("function"===a&&(n=n.call(this,c),a=t.type(n)),null==n&&i.empty?this:("string"===a&&(o=r.exec(n),o&&(n=c+parseFloat(o[2])*("+"===o[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(e){var i=e.split(" ");f(i,function(e,i){t.cssHooks[i]={set:function(e,n){var o,a,r="";if("transparent"!==n&&("string"!==t.type(n)||(o=s(n)))){if(n=l(o||n),!d.rgba&&1!==n._rgba[3]){for(a="backgroundColor"===i?e.parentNode:e;(""===r||"transparent"===r)&&a&&a.style;)try{r=t.css(a,"backgroundColor"),a=a.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{e.style[i]=n}catch(h){}}},t.fx.step[i]=function(e){e.colorInit||(e.start=l(e.elem,i),e.end=l(e.end),e.colorInit=!0),t.cssHooks[i].set(e.elem,e.start.transition(e.end,e.pos))}})},l.hook(a),t.cssHooks.borderColor={expand:function(t){var e={};return f(["Top","Right","Bottom","Left"],function(i,s){e["border"+s+"Color"]=t}),e}},o=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(p),function(){function e(e){var i,s,n=e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,null):e.currentStyle,o={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(o[t.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(o[i]=n[i]);return o}function i(e,i){var s,o,a={};for(s in i)o=i[s],e[s]!==o&&(n[s]||(t.fx.step[s]||!isNaN(parseFloat(o)))&&(a[s]=o));return a}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};t.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(e,i){t.fx.step[i]=function(t){("none"!==t.end&&!t.setAttr||1===t.pos&&!t.setAttr)&&(p.style(t.elem,i,t.end),t.setAttr=!0)}}),t.fn.addBack||(t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.effects.animateClass=function(n,o,a,r){var h=t.speed(o,a,r);return this.queue(function(){var o,a=t(this),r=a.attr("class")||"",l=h.children?a.find("*").addBack():a;l=l.map(function(){var i=t(this);return{el:i,start:e(this)}}),o=function(){t.each(s,function(t,e){n[e]&&a[e+"Class"](n[e])})},o(),l=l.map(function(){return this.end=e(this.el[0]),this.diff=i(this.start,this.end),this}),a.attr("class",r),l=l.map(function(){var e=this,i=t.Deferred(),s=t.extend({},h,{queue:!1,complete:function(){i.resolve(e)}});return this.el.animate(this.diff,s),i.promise()}),t.when.apply(t,l.get()).done(function(){o(),t.each(arguments,function(){var e=this.el;t.each(this.diff,function(t){e.css(t,"")})}),h.complete.call(a[0])})})},t.fn.extend({addClass:function(e){return function(i,s,n,o){return s?t.effects.animateClass.call(this,{add:i},s,n,o):e.apply(this,arguments)}}(t.fn.addClass),removeClass:function(e){return function(i,s,n,o){return arguments.length>1?t.effects.animateClass.call(this,{remove:i},s,n,o):e.apply(this,arguments)}}(t.fn.removeClass),toggleClass:function(e){return function(i,s,n,o,a){return"boolean"==typeof s||void 0===s?n?t.effects.animateClass.call(this,s?{add:i}:{remove:i},n,o,a):e.apply(this,arguments):t.effects.animateClass.call(this,{toggle:i},s,n,o)}}(t.fn.toggleClass),switchClass:function(e,i,s,n,o){return t.effects.animateClass.call(this,{add:i,remove:e},s,n,o)}})}(),function(){function e(e,i,s,n){return t.isPlainObject(e)&&(i=e,e=e.effect),e={effect:e},null==i&&(i={}),t.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||t.fx.speeds[i])&&(n=s,s=i,i={}),t.isFunction(s)&&(n=s,s=null),i&&t.extend(e,i),s=s||i.duration,e.duration=t.fx.off?0:"number"==typeof s?s:s in t.fx.speeds?t.fx.speeds[s]:t.fx.speeds._default,e.complete=n||i.complete,e}function i(e){return!e||"number"==typeof e||t.fx.speeds[e]?!0:"string"!=typeof e||t.effects.effect[e]?t.isFunction(e)?!0:"object"!=typeof e||e.effect?!1:!0:!0}function s(t,e){var i=e.outerWidth(),s=e.outerHeight(),n=/^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,o=n.exec(t)||["",0,i,s,0];return{top:parseFloat(o[1])||0,right:"auto"===o[2]?i:parseFloat(o[2]),bottom:"auto"===o[3]?s:parseFloat(o[3]),left:parseFloat(o[4])||0}}t.expr&&t.expr.filters&&t.expr.filters.animated&&(t.expr.filters.animated=function(e){return function(i){return!!t(i).data(d)||e(i)}}(t.expr.filters.animated)),t.uiBackCompat!==!1&&t.extend(t.effects,{save:function(t,e){for(var i=0,s=e.length;s>i;i++)null!==e[i]&&t.data(c+e[i],t[0].style[e[i]])},restore:function(t,e){for(var i,s=0,n=e.length;n>s;s++)null!==e[s]&&(i=t.data(c+e[s]),t.css(e[s],i))},setMode:function(t,e){return"toggle"===e&&(e=t.is(":hidden")?"show":"hide"),e},createWrapper:function(e){if(e.parent().is(".ui-effects-wrapper"))return e.parent();var i={width:e.outerWidth(!0),height:e.outerHeight(!0),"float":e.css("float")},s=t("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:e.width(),height:e.height()},o=document.activeElement;try{o.id}catch(a){o=document.body}return e.wrap(s),(e[0]===o||t.contains(e[0],o))&&t(o).trigger("focus"),s=e.parent(),"static"===e.css("position")?(s.css({position:"relative"}),e.css({position:"relative"})):(t.extend(i,{position:e.css("position"),zIndex:e.css("z-index")}),t.each(["top","left","bottom","right"],function(t,s){i[s]=e.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),e.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),e.css(n),s.css(i).show()},removeWrapper:function(e){var i=document.activeElement;return e.parent().is(".ui-effects-wrapper")&&(e.parent().replaceWith(e),(e[0]===i||t.contains(e[0],i))&&t(i).trigger("focus")),e}}),t.extend(t.effects,{version:"1.12.1",define:function(e,i,s){return s||(s=i,i="effect"),t.effects.effect[e]=s,t.effects.effect[e].mode=i,s},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,n="vertical"!==i?(e||100)/100:1;return{height:t.height()*n,width:t.width()*s,outerHeight:t.outerHeight()*n,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();e>1&&s.splice.apply(s,[1,0].concat(s.splice(e,i))),t.dequeue()},saveStyle:function(t){t.data(u,t[0].style.cssText)},restoreStyle:function(t){t[0].style.cssText=t.data(u)||"",t.removeData(u)},mode:function(t,e){var i=t.is(":hidden");return"toggle"===e&&(e=i?"show":"hide"),(i?"hide"===e:"show"===e)&&(e="none"),e},getBaseline:function(t,e){var i,s;switch(t[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=t[0]/e.height}switch(t[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=t[1]/e.width}return{x:s,y:i}},createPlaceholder:function(e){var i,s=e.css("position"),n=e.position();return e.css({marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()),/^(static|relative)/.test(s)&&(s="absolute",i=t("<"+e[0].nodeName+">").insertAfter(e).css({display:/^(inline|ruby)/.test(e.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:e.css("marginTop"),marginBottom:e.css("marginBottom"),marginLeft:e.css("marginLeft"),marginRight:e.css("marginRight"),"float":e.css("float")}).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).addClass("ui-effects-placeholder"),e.data(c+"placeholder",i)),e.css({position:s,left:n.left,top:n.top}),i},removePlaceholder:function(t){var e=c+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(e){t.effects.restoreStyle(e),t.effects.removePlaceholder(e)},setTransition:function(e,i,s,n){return n=n||{},t.each(i,function(t,i){var o=e.cssUnit(i);o[0]>0&&(n[i]=o[0]*s+o[1])}),n}}),t.fn.extend({effect:function(){function i(e){function i(){r.removeData(d),t.effects.cleanUp(r),"hide"===s.mode&&r.hide(),a()}function a(){t.isFunction(h)&&h.call(r[0]),t.isFunction(e)&&e()}var r=t(this);s.mode=c.shift(),t.uiBackCompat===!1||o?"none"===s.mode?(r[l](),a()):n.call(r[0],s,i):(r.is(":hidden")?"hide"===l:"show"===l)?(r[l](),a()):n.call(r[0],s,a)}var s=e.apply(this,arguments),n=t.effects.effect[s.effect],o=n.mode,a=s.queue,r=a||"fx",h=s.complete,l=s.mode,c=[],u=function(e){var i=t(this),s=t.effects.mode(i,l)||o;i.data(d,!0),c.push(s),o&&("show"===s||s===o&&"hide"===s)&&i.show(),o&&"none"===s||t.effects.saveStyle(i),t.isFunction(e)&&e()};return t.fx.off||!n?l?this[l](s.duration,h):this.each(function(){h&&h.call(this)}):a===!1?this.each(u).each(i):this.queue(r,u).queue(r,i)},show:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="show",this.effect.call(this,n) }}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):s(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),t.isFunction(i)&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=s(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}();var f=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},h=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),h&&h.css(t.effects.clipToBox(r)),r.clip=a),h&&h.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,h="hide"===r,l="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(l||h?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),l&&(n={opacity:1},n[m]=o,a.css("opacity",0).css(m,_?2*-u:2*u).animate(n,f,g)),h&&(u/=Math.pow(2,d-1)),n={},n[m]=o;d>v;v++)s={},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=h?2*u:u/2;h&&(s={opacity:0},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,h=r||"horizontal"===a,l=r||"vertical"===a;s=o.cssClip(),n.clip={top:l?(s.bottom-s.top)/2:s.top,right:h?(s.right-s.left)/2:s.right,bottom:l?(s.bottom-s.top)/2:s.bottom,left:h?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a="show"===o,r=e.direction||"left",h="up"===r||"down"===r?"top":"left",l="up"===r||"left"===r?"-=":"+=",c="+="===l?"-=":"+=",u={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,u[h]=l+s,a&&(n.css(u),u[h]=c+s,u.opacity=1),n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=e.mode,g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacity:g?1:0},e.duration||500,e.easing,s)}),t.effects.define("fade","toggle",function(e,i){var s="show"===e.mode;t(this).css("opacity",s?0:1).animate({opacity:s?1:0},{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("fold","hide",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=e.size||15,h=/([0-9]+)%/.exec(r),l=!!e.horizFirst,c=l?["right","bottom"]:["bottom","right"],u=e.duration/2,d=t.effects.createPlaceholder(s),p=s.cssClip(),f={clip:t.extend({},p)},g={clip:t.extend({},p)},m=[p[c[0]],p[c[1]]],_=s.queue().length;h&&(r=parseInt(h[1],10)/100*m[a?0:1]),f.clip[c[0]]=r,g.clip[c[0]]=r,g.clip[c[1]]=0,o&&(s.cssClip(g.clip),d&&d.css(t.effects.clipToBox(g)),g.clip=p),s.queue(function(i){d&&d.animate(t.effects.clipToBox(f),u,e.easing).animate(t.effects.clipToBox(g),u,e.easing),i()}).animate(f,u,e.easing).animate(g,u,e.easing).queue(i),t.effects.unshift(s,_,4)}),t.effects.define("highlight","show",function(e,i){var s=t(this),n={backgroundColor:s.css("backgroundColor")};"hide"===e.mode&&(n.opacity=0),t.effects.saveStyle(s),s.css({backgroundImage:"none",backgroundColor:e.color||"#ffff99"}).animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("size",function(e,i){var s,n,o,a=t(this),r=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],l=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],c=e.mode,u="effect"!==c,d=e.scale||"both",p=e.origin||["middle","center"],f=a.css("position"),g=a.position(),m=t.effects.scaledDimensions(a),_=e.from||m,v=e.to||t.effects.scaledDimensions(a,0);t.effects.createPlaceholder(a),"show"===c&&(o=_,_=v,v=o),n={from:{y:_.height/m.height,x:_.width/m.width},to:{y:v.height/m.height,x:v.width/m.width}},("box"===d||"both"===d)&&(n.from.y!==n.to.y&&(_=t.effects.setTransition(a,h,n.from.y,_),v=t.effects.setTransition(a,h,n.to.y,v)),n.from.x!==n.to.x&&(_=t.effects.setTransition(a,l,n.from.x,_),v=t.effects.setTransition(a,l,n.to.x,v))),("content"===d||"both"===d)&&n.from.y!==n.to.y&&(_=t.effects.setTransition(a,r,n.from.y,_),v=t.effects.setTransition(a,r,n.to.y,v)),p&&(s=t.effects.getBaseline(p,m),_.top=(m.outerHeight-_.outerHeight)*s.y+g.top,_.left=(m.outerWidth-_.outerWidth)*s.x+g.left,v.top=(m.outerHeight-v.outerHeight)*s.y+g.top,v.left=(m.outerWidth-v.outerWidth)*s.x+g.left),a.css(_),("content"===d||"both"===d)&&(h=h.concat(["marginTop","marginBottom"]).concat(r),l=l.concat(["marginLeft","marginRight"]),a.find("*[width]").each(function(){var i=t(this),s=t.effects.scaledDimensions(i),o={height:s.height*n.from.y,width:s.width*n.from.x,outerHeight:s.outerHeight*n.from.y,outerWidth:s.outerWidth*n.from.x},a={height:s.height*n.to.y,width:s.width*n.to.x,outerHeight:s.height*n.to.y,outerWidth:s.width*n.to.x};n.from.y!==n.to.y&&(o=t.effects.setTransition(i,h,n.from.y,o),a=t.effects.setTransition(i,h,n.to.y,a)),n.from.x!==n.to.x&&(o=t.effects.setTransition(i,l,n.from.x,o),a=t.effects.setTransition(i,l,n.to.x,a)),u&&t.effects.saveStyle(i),i.css(o),i.animate(a,e.duration,e.easing,function(){u&&t.effects.restoreStyle(i)})})),a.animate(v,{queue:!1,duration:e.duration,easing:e.easing,complete:function(){var e=a.offset();0===v.opacity&&a.css("opacity",_.opacity),u||(a.css("position","static"===f?"relative":f).offset(e),t.effects.saveStyle(a)),i()}})}),t.effects.define("scale",function(e,i){var s=t(this),n=e.mode,o=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"effect"!==n?0:100),a=t.extend(!0,{from:t.effects.scaledDimensions(s),to:t.effects.scaledDimensions(s,o,e.direction||"both"),origin:e.origin||["middle","center"]},e);e.fade&&(a.from.opacity=1,a.to.opacity=0),t.effects.effect.size.call(this,a,i)}),t.effects.define("puff","hide",function(e,i){var s=t.extend(!0,{},e,{fade:!0,percent:parseInt(e.percent,10)||150});t.effects.effect.scale.call(this,s,i)}),t.effects.define("pulsate","show",function(e,i){var s=t(this),n=e.mode,o="show"===n,a="hide"===n,r=o||a,h=2*(e.times||5)+(r?1:0),l=e.duration/h,c=0,u=1,d=s.queue().length;for((o||!s.is(":visible"))&&(s.css("opacity",0).show(),c=1);h>u;u++)s.animate({opacity:c},l,e.easing),c=1-c;s.animate({opacity:c},l,e.easing),s.queue(i),t.effects.unshift(s,d,h+1)}),t.effects.define("shake",function(e,i){var s=1,n=t(this),o=e.direction||"left",a=e.distance||20,r=e.times||3,h=2*r+1,l=Math.round(e.duration/h),c="up"===o||"down"===o?"top":"left",u="up"===o||"left"===o,d={},p={},f={},g=n.queue().length;for(t.effects.createPlaceholder(n),d[c]=(u?"-=":"+=")+a,p[c]=(u?"+=":"-=")+2*a,f[c]=(u?"-=":"+=")+2*a,n.animate(d,l,e.easing);r>s;s++)n.animate(p,l,e.easing).animate(f,l,e.easing);n.animate(p,l,e.easing).animate(d,l/2,e.easing).queue(i),t.effects.unshift(n,g,h+1)}),t.effects.define("slide","show",function(e,i){var s,n,o=t(this),a={up:["bottom","top"],down:["top","bottom"],left:["right","left"],right:["left","right"]},r=e.mode,h=e.direction||"left",l="up"===h||"down"===h?"top":"left",c="up"===h||"left"===h,u=e.distance||o["top"===l?"outerHeight":"outerWidth"](!0),d={};t.effects.createPlaceholder(o),s=o.cssClip(),n=o.position()[l],d[l]=(c?-1:1)*u+n,d.clip=o.cssClip(),d.clip[a[h][1]]=d.clip[a[h][0]],"show"===r&&(o.cssClip(d.clip),o.css(l,d[l]),d.clip=s,d[l]=n),o.animate(d,{queue:!1,duration:e.duration,easing:e.easing,complete:i})});var f;t.uiBackCompat!==!1&&(f=t.effects.define("transfer",function(e,i){t(this).transfer(e,i)})),t.ui.focusable=function(i,s){var n,o,a,r,h,l=i.nodeName.toLowerCase();return"area"===l?(n=i.parentNode,o=n.name,i.href&&o&&"map"===n.nodeName.toLowerCase()?(a=t("img[usemap='#"+o+"']"),a.length>0&&a.is(":visible")):!1):(/^(input|select|textarea|button|object)$/.test(l)?(r=!i.disabled,r&&(h=t(i).closest("fieldset")[0],h&&(r=!h.disabled))):r="a"===l?i.href||s:s,r&&t(i).is(":visible")&&e(t(i)))},t.extend(t.expr[":"],{focusable:function(e){return t.ui.focusable(e,null!=t.attr(e,"tabindex"))}}),t.ui.focusable,t.fn.form=function(){return"string"==typeof this[0].form?this.closest("form"):t(this[0].form)},t.ui.formResetMixin={_formResetHandler:function(){var e=t(this);setTimeout(function(){var i=e.data("ui-form-reset-instances");t.each(i,function(){this.refresh()})})},_bindFormResetHandler:function(){if(this.form=this.element.form(),this.form.length){var t=this.form.data("ui-form-reset-instances")||[];t.length||this.form.on("reset.ui-form-reset",this._formResetHandler),t.push(this),this.form.data("ui-form-reset-instances",t)}},_unbindFormResetHandler:function(){if(this.form.length){var e=this.form.data("ui-form-reset-instances");e.splice(t.inArray(this,e),1),e.length?this.form.data("ui-form-reset-instances",e):this.form.removeData("ui-form-reset-instances").off("reset.ui-form-reset")}}},"1.7"===t.fn.jquery.substring(0,3)&&(t.each(["Width","Height"],function(e,i){function s(e,i,s,o){return t.each(n,function(){i-=parseFloat(t.css(e,"padding"+this))||0,s&&(i-=parseFloat(t.css(e,"border"+this+"Width"))||0),o&&(i-=parseFloat(t.css(e,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],o=i.toLowerCase(),a={innerWidth:t.fn.innerWidth,innerHeight:t.fn.innerHeight,outerWidth:t.fn.outerWidth,outerHeight:t.fn.outerHeight};t.fn["inner"+i]=function(e){return void 0===e?a["inner"+i].call(this):this.each(function(){t(this).css(o,s(this,e)+"px")})},t.fn["outer"+i]=function(e,n){return"number"!=typeof e?a["outer"+i].call(this,e):this.each(function(){t(this).css(o,s(this,e,!0,n)+"px")})}}),t.fn.addBack=function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}),t.ui.keyCode={BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38},t.ui.escapeSelector=function(){var t=/([!"#$%&'()*+,.\/:;<=>?@[\]^`{|}~])/g;return function(e){return e.replace(t,"\\$1")}}(),t.fn.labels=function(){var e,i,s,n,o;return this[0].labels&&this[0].labels.length?this.pushStack(this[0].labels):(n=this.eq(0).parents("label"),s=this.attr("id"),s&&(e=this.eq(0).parents().last(),o=e.add(e.length?e.siblings():this.siblings()),i="label[for='"+t.ui.escapeSelector(s)+"']",n=n.add(o.find(i).addBack(i))),this.pushStack(n))},t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.extend(t.expr[":"],{tabbable:function(e){var i=t.attr(e,"tabindex"),s=null!=i;return(!s||i>=0)&&t.ui.focusable(e,s)}}),t.fn.extend({uniqueId:function(){var t=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++t)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&t(this).removeAttr("id")})}}),t.widget("ui.accordion",{version:"1.12.1",options:{active:0,animate:{},classes:{"ui-accordion-header":"ui-corner-top","ui-accordion-header-collapsed":"ui-corner-all","ui-accordion-content":"ui-corner-bottom"},collapsible:!1,event:"click",header:"> li > :first-child, > :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var e=this.options;this.prevShow=this.prevHide=t(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),e.collapsible||e.active!==!1&&null!=e.active||(e.active=0),this._processPanels(),0>e.active&&(e.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():t()}},_createIcons:function(){var e,i,s=this.options.icons;s&&(e=t("<span>"),this._addClass(e,"ui-accordion-header-icon","ui-icon "+s.header),e.prependTo(this.headers),i=this.active.children(".ui-accordion-header-icon"),this._removeClass(i,s.header)._addClass(i,null,s.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||this.options.active!==!1||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons()),void 0)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(e){if(!e.altKey&&!e.ctrlKey){var i=t.ui.keyCode,s=this.headers.length,n=this.headers.index(e.target),o=!1;switch(e.keyCode){case i.RIGHT:case i.DOWN:o=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:o=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(e);break;case i.HOME:o=this.headers[0];break;case i.END:o=this.headers[s-1]}o&&(t(e.target).attr("tabIndex",-1),t(o).attr("tabIndex",0),t(o).trigger("focus"),e.preventDefault())}},_panelKeyDown:function(e){e.keyCode===t.ui.keyCode.UP&&e.ctrlKey&&t(e.currentTarget).prev().trigger("focus")},refresh:function(){var e=this.options;this._processPanels(),e.active===!1&&e.collapsible===!0||!this.headers.length?(e.active=!1,this.active=t()):e.active===!1?this._activate(0):this.active.length&&!t.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(e.active=!1,this.active=t()):this._activate(Math.max(0,e.active-1)):e.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var e,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var e=t(this),i=e.uniqueId().attr("id"),s=e.next(),n=s.uniqueId().attr("id");e.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(e=n.height(),this.element.siblings(":visible").each(function(){var i=t(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(e-=i.outerHeight(!0))}),this.headers.each(function(){e-=t(this).outerHeight(!0)}),this.headers.next().each(function(){t(this).height(Math.max(0,e-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===s&&(e=0,this.headers.next().each(function(){var i=t(this).is(":visible");i||t(this).show(),e=Math.max(e,t(this).css("height","").height()),i||t(this).hide()}).height(e))},_activate:function(e){var i=this._findActive(e)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return"number"==typeof e?this.headers.eq(e):t()},_setupEvents:function(e){var i={keydown:"_keydown"};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(e){var i,s,n=this.options,o=this.active,a=t(e.currentTarget),r=a[0]===o[0],h=r&&n.collapsible,l=h?t():a.next(),c=o.next(),u={oldHeader:o,oldPanel:c,newHeader:h?t():a,newPanel:l};e.preventDefault(),r&&!n.collapsible||this._trigger("beforeActivate",e,u)===!1||(n.active=h?!1:this.headers.index(a),this.active=r?t():a,this._toggle(u),this._removeClass(o,"ui-accordion-header-active","ui-state-active"),n.icons&&(i=o.children(".ui-accordion-header-icon"),this._removeClass(i,null,n.icons.activeHeader)._addClass(i,null,n.icons.header)),r||(this._removeClass(a,"ui-accordion-header-collapsed")._addClass(a,"ui-accordion-header-active","ui-state-active"),n.icons&&(s=a.children(".ui-accordion-header-icon"),this._removeClass(s,null,n.icons.header)._addClass(s,null,n.icons.activeHeader)),this._addClass(a.next(),"ui-accordion-content-active")))},_toggle:function(e){var i=e.newPanel,s=this.prevShow.length?this.prevShow:e.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,e):(s.hide(),i.show(),this._toggleComplete(e)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(t(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,e,i){var s,n,o,a=this,r=0,h=t.css("box-sizing"),l=t.length&&(!e.length||t.index()<e.index()),c=this.options.animate||{},u=l&&c.down||c,d=function(){a._toggleComplete(i)};return"number"==typeof u&&(o=u),"string"==typeof u&&(n=u),n=n||u.easing||c.easing,o=o||u.duration||c.duration,e.length?t.length?(s=t.show().outerHeight(),e.animate(this.hideProps,{duration:o,easing:n,step:function(t,e){e.now=Math.round(t)}}),t.hide().animate(this.showProps,{duration:o,easing:n,complete:d,step:function(t,i){i.now=Math.round(t),"height"!==i.prop?"content-box"===h&&(r+=i.now):"content"!==a.options.heightStyle&&(i.now=Math.round(s-e.outerHeight()-r),r=0)}}),void 0):e.animate(this.hideProps,o,n,d):t.animate(this.showProps,o,n,d)},_toggleComplete:function(t){var e=t.oldPanel,i=e.prev();this._removeClass(e,"ui-accordion-content-active"),this._removeClass(i,"ui-accordion-header-active")._addClass(i,"ui-accordion-header-collapsed"),e.length&&(e.parent()[0].className=e.parent()[0].className),this._trigger("activate",null,t)}}),t.ui.safeActiveElement=function(t){var e;try{e=t.activeElement}catch(i){e=t.body}return e||(e=t.body),e.nodeName||(e=t.body),e},t.widget("ui.menu",{version:"1.12.1",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault()},"click .ui-menu-item":function(e){var i=t(e.target),s=t(t.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(e),e.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(e):!this.element.is(":focus")&&s.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(e){if(!this.previousFilter){var i=t(e.target).closest(".ui-menu-item"),s=t(e.currentTarget);i[0]===s[0]&&(this._removeClass(s.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(e,s))}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this.element.find(this.options.items).eq(0);e||this.focus(t,i)},blur:function(e){this._delay(function(){var i=!t.contains(this.element[0],t.ui.safeActiveElement(this.document[0]));i&&this.collapseAll(e)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t),this.mouseHandled=!1}})},_destroy:function(){var e=this.element.find(".ui-menu-item").removeAttr("role aria-disabled"),i=e.children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),i.children().each(function(){var e=t(this);e.data("ui-menu-submenu-caret")&&e.remove()})},_keydown:function(e){var i,s,n,o,a=!0;switch(e.keyCode){case t.ui.keyCode.PAGE_UP:this.previousPage(e);break;case t.ui.keyCode.PAGE_DOWN:this.nextPage(e);break;case t.ui.keyCode.HOME:this._move("first","first",e);break;case t.ui.keyCode.END:this._move("last","last",e);break;case t.ui.keyCode.UP:this.previous(e);break;case t.ui.keyCode.DOWN:this.next(e);break;case t.ui.keyCode.LEFT:this.collapse(e);break;case t.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(e);break;case t.ui.keyCode.ENTER:case t.ui.keyCode.SPACE:this._activate(e);break;case t.ui.keyCode.ESCAPE:this.collapse(e);break;default:a=!1,s=this.previousFilter||"",o=!1,n=e.keyCode>=96&&105>=e.keyCode?""+(e.keyCode-96):String.fromCharCode(e.keyCode),clearTimeout(this.filterTimer),n===s?o=!0:n=s+n,i=this._filterMenuItems(n),i=o&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(e.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(e,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}a&&e.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var e,i,s,n,o,a=this,r=this.options.icons.submenu,h=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),s=h.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var e=t(this),i=e.prev(),s=t("<span>").data("ui-menu-submenu-caret",!0);a._addClass(s,"ui-menu-icon","ui-icon "+r),i.attr("aria-haspopup","true").prepend(s),e.attr("aria-labelledby",i.attr("id"))}),this._addClass(s,"ui-menu","ui-widget ui-widget-content ui-front"),e=h.add(this.element),i=e.find(this.options.items),i.not(".ui-menu-item").each(function(){var e=t(this);a._isDivider(e)&&a._addClass(e,"ui-menu-divider","ui-widget-content")}),n=i.not(".ui-menu-item, .ui-menu-divider"),o=n.children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(n,"ui-menu-item")._addClass(o,"ui-menu-item-wrapper"),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!t.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){if("icons"===t){var i=this.element.find(".ui-menu-icon");this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)}this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t+""),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i,s,n;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),s=this.active.children(".ui-menu-item-wrapper"),this._addClass(s,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),n=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(n,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=e.children(".ui-menu"),i.length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(e){var i,s,n,o,a,r;this._hasScroll()&&(i=parseFloat(t.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(t.css(this.activeMenu[0],"paddingTop"))||0,n=e.offset().top-this.activeMenu.offset().top-i-s,o=this.activeMenu.scrollTop(),a=this.activeMenu.height(),r=e.outerHeight(),0>n?this.activeMenu.scrollTop(o+n):n+r>a&&this.activeMenu.scrollTop(o+n-a+r))},blur:function(t,e){e||clearTimeout(this.timer),this.active&&(this._removeClass(this.active.children(".ui-menu-item-wrapper"),null,"ui-state-active"),this._trigger("blur",t,{item:this.active}),this.active=null)},_startOpening:function(t){clearTimeout(this.timer),"true"===t.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(t)},this.delay))},_open:function(e){var i=t.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(e.parents(".ui-menu")).hide().attr("aria-hidden","true"),e.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(e,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:t(e&&e.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(e),this._removeClass(s.find(".ui-state-active"),null,"ui-state-active"),this.activeMenu=s},this.delay)},_close:function(t){t||(t=this.active?this.active.parent():this.element),t.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false")},_closeOnDocumentClick:function(e){return!t(e.target).closest(".ui-menu").length},_isDivider:function(t){return!/[^\-\u2014\u2013\s]/.test(t.text())},collapse:function(t){var e=this.active&&this.active.parent().closest(".ui-menu-item",this.element);e&&e.length&&(this._close(),this.focus(t,e))},expand:function(t){var e=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();e&&e.length&&(this._open(e.parent()),this._delay(function(){this.focus(t,e)}))},next:function(t){this._move("next","first",t)},previous:function(t){this._move("prev","last",t)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(t,e,i){var s;this.active&&(s="first"===t||"last"===t?this.active["first"===t?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[t+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[e]()),this.focus(i,s)},nextPage:function(e){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=t(this),0>i.offset().top-s-n}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(e),void 0)},previousPage:function(e){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=t(this),i.offset().top-s+n>0}),this.focus(e,i)):this.focus(e,this.activeMenu.find(this.options.items).first())),void 0):(this.next(e),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(e){this.active=this.active||t(e.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(e,!0),this._trigger("select",e,i)},_filterMenuItems:function(e){var i=e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(t.trim(t(this).children(".ui-menu-item-wrapper").text()))})}}),t.widget("ui.autocomplete",{version:"1.12.1",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var e,i,s,n=this.element[0].nodeName.toLowerCase(),o="textarea"===n,a="input"===n; this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,this.element[0]!==t.ui.safeActiveElement(this.document[0])&&this.element.trigger("focus")})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,i){var s=i.item.data("ui-autocomplete-item"),n=this.previous;this.element[0]!==t.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=n,this._delay(function(){this.previous=n,this.selectedItem=s})),!1!==this._trigger("select",e,{item:s})&&this._value(s.value),this.term=this._value(),this.close(e),this.selectedItem=s}}),this.liveRegion=t("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pending--,this.pending||this._removeClass("ui-autocomplete-loading")},this)},__response:function(t){t&&(t=this._normalize(t)),this._trigger("response",null,{content:t}),!this.options.disabled&&t&&t.length&&!this.cancelSearch?(this._suggest(t),this._trigger("open")):this._close()},close:function(t){this.cancelSearch=!0,this._close(t)},_close:function(t){this._off(this.document,"mousedown"),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",t))},_change:function(t){this.previous!==this._value()&&this._trigger("change",t,{item:this.selectedItem})},_normalize:function(e){return e.length&&e[0].label&&e[0].value?e:t.map(e,function(e){return"string"==typeof e?{label:e,value:e}:t.extend({},e,{label:e.label||e.value,value:e.value||e.label})})},_suggest:function(e){var i=this.menu.element.empty();this._renderMenu(i,e),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(t.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(),this._on(this.document,{mousedown:"_closeOnClickOutside"})},_resizeMenu:function(){var t=this.menu.element;t.outerWidth(Math.max(t.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(e,i){var s=this;t.each(i,function(t,i){s._renderItemData(e,i)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-autocomplete-item",e)},_renderItem:function(e,i){return t("<li>").append(t("<div>").text(i.label)).appendTo(e)},_move:function(t,e){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(t)||this.menu.isLastItem()&&/^next/.test(t)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[t](e),void 0):(this.search(null,e),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(t,e){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(t,e),e.preventDefault())},_isContentEditable:function(t){if(!t.length)return!1;var e=t.prop("contentEditable");return"inherit"===e?this._isContentEditable(t.parent()):"true"===e}}),t.extend(t.ui.autocomplete,{escapeRegex:function(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(e,i){var s=RegExp(t.ui.autocomplete.escapeRegex(i),"i");return t.grep(e,function(t){return s.test(t.label||t.value||t)})}}),t.widget("ui.autocomplete",t.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(t){return t+(t>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=e&&e.length?this.options.messages.results(e.length):this.options.messages.noResults,this.liveRegion.children().hide(),t("<div>").text(i).appendTo(this.liveRegion))}}),t.ui.autocomplete;var g=/ui-corner-([a-z]){2,6}/g;t.widget("ui.controlgroup",{version:"1.12.1",defaultElement:"<div>",options:{direction:"horizontal",disabled:null,onlyVisible:!0,items:{button:"input[type=button], input[type=submit], input[type=reset], button, a",controlgroupLabel:".ui-controlgroup-label",checkboxradio:"input[type='checkbox'], input[type='radio']",selectmenu:"select",spinner:".ui-spinner-input"}},_create:function(){this._enhance()},_enhance:function(){this.element.attr("role","toolbar"),this.refresh()},_destroy:function(){this._callChildMethod("destroy"),this.childWidgets.removeData("ui-controlgroup-data"),this.element.removeAttr("role"),this.options.items.controlgroupLabel&&this.element.find(this.options.items.controlgroupLabel).find(".ui-controlgroup-label-contents").contents().unwrap()},_initWidgets:function(){var e=this,i=[];t.each(this.options.items,function(s,n){var o,a={};return n?"controlgroupLabel"===s?(o=e.element.find(n),o.each(function(){var e=t(this);e.children(".ui-controlgroup-label-contents").length||e.contents().wrapAll("<span class='ui-controlgroup-label-contents'></span>")}),e._addClass(o,null,"ui-widget ui-widget-content ui-state-default"),i=i.concat(o.get()),void 0):(t.fn[s]&&(a=e["_"+s+"Options"]?e["_"+s+"Options"]("middle"):{classes:{}},e.element.find(n).each(function(){var n=t(this),o=n[s]("instance"),r=t.widget.extend({},a);if("button"!==s||!n.parent(".ui-spinner").length){o||(o=n[s]()[s]("instance")),o&&(r.classes=e._resolveClassesValues(r.classes,o)),n[s](r);var h=n[s]("widget");t.data(h[0],"ui-controlgroup-data",o?o:n[s]("instance")),i.push(h[0])}})),void 0):void 0}),this.childWidgets=t(t.unique(i)),this._addClass(this.childWidgets,"ui-controlgroup-item")},_callChildMethod:function(e){this.childWidgets.each(function(){var i=t(this),s=i.data("ui-controlgroup-data");s&&s[e]&&s[e]()})},_updateCornerClass:function(t,e){var i="ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all",s=this._buildSimpleOptions(e,"label").classes.label;this._removeClass(t,null,i),this._addClass(t,null,s)},_buildSimpleOptions:function(t,e){var i="vertical"===this.options.direction,s={classes:{}};return s.classes[e]={middle:"",first:"ui-corner-"+(i?"top":"left"),last:"ui-corner-"+(i?"bottom":"right"),only:"ui-corner-all"}[t],s},_spinnerOptions:function(t){var e=this._buildSimpleOptions(t,"ui-spinner");return e.classes["ui-spinner-up"]="",e.classes["ui-spinner-down"]="",e},_buttonOptions:function(t){return this._buildSimpleOptions(t,"ui-button")},_checkboxradioOptions:function(t){return this._buildSimpleOptions(t,"ui-checkboxradio-label")},_selectmenuOptions:function(t){var e="vertical"===this.options.direction;return{width:e?"auto":!1,classes:{middle:{"ui-selectmenu-button-open":"","ui-selectmenu-button-closed":""},first:{"ui-selectmenu-button-open":"ui-corner-"+(e?"top":"tl"),"ui-selectmenu-button-closed":"ui-corner-"+(e?"top":"left")},last:{"ui-selectmenu-button-open":e?"":"ui-corner-tr","ui-selectmenu-button-closed":"ui-corner-"+(e?"bottom":"right")},only:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"}}[t]}},_resolveClassesValues:function(e,i){var s={};return t.each(e,function(n){var o=i.options.classes[n]||"";o=t.trim(o.replace(g,"")),s[n]=(o+" "+e[n]).replace(/\s+/g," ")}),s},_setOption:function(t,e){return"direction"===t&&this._removeClass("ui-controlgroup-"+this.options.direction),this._super(t,e),"disabled"===t?(this._callChildMethod(e?"disable":"enable"),void 0):(this.refresh(),void 0)},refresh:function(){var e,i=this;this._addClass("ui-controlgroup ui-controlgroup-"+this.options.direction),"horizontal"===this.options.direction&&this._addClass(null,"ui-helper-clearfix"),this._initWidgets(),e=this.childWidgets,this.options.onlyVisible&&(e=e.filter(":visible")),e.length&&(t.each(["first","last"],function(t,s){var n=e[s]().data("ui-controlgroup-data");if(n&&i["_"+n.widgetName+"Options"]){var o=i["_"+n.widgetName+"Options"](1===e.length?"only":s);o.classes=i._resolveClassesValues(o.classes,n),n.element[n.widgetName](o)}else i._updateCornerClass(e[s](),s)}),this._callChildMethod("refresh"))}}),t.widget("ui.checkboxradio",[t.ui.formResetMixin,{version:"1.12.1",options:{disabled:null,label:null,icon:!0,classes:{"ui-checkboxradio-label":"ui-corner-all","ui-checkboxradio-icon":"ui-corner-all"}},_getCreateOptions:function(){var e,i,s=this,n=this._super()||{};return this._readType(),i=this.element.labels(),this.label=t(i[i.length-1]),this.label.length||t.error("No label found for checkboxradio widget"),this.originalLabel="",this.label.contents().not(this.element[0]).each(function(){s.originalLabel+=3===this.nodeType?t(this).text():this.outerHTML}),this.originalLabel&&(n.label=this.originalLabel),e=this.element[0].disabled,null!=e&&(n.disabled=e),n},_create:function(){var t=this.element[0].checked;this._bindFormResetHandler(),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled),this._setOption("disabled",this.options.disabled),this._addClass("ui-checkboxradio","ui-helper-hidden-accessible"),this._addClass(this.label,"ui-checkboxradio-label","ui-button ui-widget"),"radio"===this.type&&this._addClass(this.label,"ui-checkboxradio-radio-label"),this.options.label&&this.options.label!==this.originalLabel?this._updateLabel():this.originalLabel&&(this.options.label=this.originalLabel),this._enhance(),t&&(this._addClass(this.label,"ui-checkboxradio-checked","ui-state-active"),this.icon&&this._addClass(this.icon,null,"ui-state-hover")),this._on({change:"_toggleClasses",focus:function(){this._addClass(this.label,null,"ui-state-focus ui-visual-focus")},blur:function(){this._removeClass(this.label,null,"ui-state-focus ui-visual-focus")}})},_readType:function(){var e=this.element[0].nodeName.toLowerCase();this.type=this.element[0].type,"input"===e&&/radio|checkbox/.test(this.type)||t.error("Can't create checkboxradio on element.nodeName="+e+" and element.type="+this.type)},_enhance:function(){this._updateIcon(this.element[0].checked)},widget:function(){return this.label},_getRadioGroup:function(){var e,i=this.element[0].name,s="input[name='"+t.ui.escapeSelector(i)+"']";return i?(e=this.form.length?t(this.form[0].elements).filter(s):t(s).filter(function(){return 0===t(this).form().length}),e.not(this.element)):t([])},_toggleClasses:function(){var e=this.element[0].checked;this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",e),this.options.icon&&"checkbox"===this.type&&this._toggleClass(this.icon,null,"ui-icon-check ui-state-checked",e)._toggleClass(this.icon,null,"ui-icon-blank",!e),"radio"===this.type&&this._getRadioGroup().each(function(){var e=t(this).checkboxradio("instance");e&&e._removeClass(e.label,"ui-checkboxradio-checked","ui-state-active")})},_destroy:function(){this._unbindFormResetHandler(),this.icon&&(this.icon.remove(),this.iconSpace.remove())},_setOption:function(t,e){return"label"!==t||e?(this._super(t,e),"disabled"===t?(this._toggleClass(this.label,null,"ui-state-disabled",e),this.element[0].disabled=e,void 0):(this.refresh(),void 0)):void 0},_updateIcon:function(e){var i="ui-icon ui-icon-background ";this.options.icon?(this.icon||(this.icon=t("<span>"),this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-checkboxradio-icon-space")),"checkbox"===this.type?(i+=e?"ui-icon-check ui-state-checked":"ui-icon-blank",this._removeClass(this.icon,null,e?"ui-icon-blank":"ui-icon-check")):i+="ui-icon-blank",this._addClass(this.icon,"ui-checkboxradio-icon",i),e||this._removeClass(this.icon,null,"ui-icon-check ui-state-checked"),this.icon.prependTo(this.label).after(this.iconSpace)):void 0!==this.icon&&(this.icon.remove(),this.iconSpace.remove(),delete this.icon)},_updateLabel:function(){var t=this.label.contents().not(this.element[0]);this.icon&&(t=t.not(this.icon[0])),this.iconSpace&&(t=t.not(this.iconSpace[0])),t.remove(),this.label.append(this.options.label)},refresh:function(){var t=this.element[0].checked,e=this.element[0].disabled;this._updateIcon(t),this._toggleClass(this.label,"ui-checkboxradio-checked","ui-state-active",t),null!==this.options.label&&this._updateLabel(),e!==this.options.disabled&&this._setOptions({disabled:e})}}]),t.ui.checkboxradio,t.widget("ui.button",{version:"1.12.1",defaultElement:"<button>",options:{classes:{"ui-button":"ui-corner-all"},disabled:null,icon:null,iconPosition:"beginning",label:null,showLabel:!0},_getCreateOptions:function(){var t,e=this._super()||{};return this.isInput=this.element.is("input"),t=this.element[0].disabled,null!=t&&(e.disabled=t),this.originalLabel=this.isInput?this.element.val():this.element.html(),this.originalLabel&&(e.label=this.originalLabel),e},_create:function(){!this.option.showLabel&!this.options.icon&&(this.options.showLabel=!0),null==this.options.disabled&&(this.options.disabled=this.element[0].disabled||!1),this.hasTitle=!!this.element.attr("title"),this.options.label&&this.options.label!==this.originalLabel&&(this.isInput?this.element.val(this.options.label):this.element.html(this.options.label)),this._addClass("ui-button","ui-widget"),this._setOption("disabled",this.options.disabled),this._enhance(),this.element.is("a")&&this._on({keyup:function(e){e.keyCode===t.ui.keyCode.SPACE&&(e.preventDefault(),this.element[0].click?this.element[0].click():this.element.trigger("click"))}})},_enhance:function(){this.element.is("button")||this.element.attr("role","button"),this.options.icon&&(this._updateIcon("icon",this.options.icon),this._updateTooltip())},_updateTooltip:function(){this.title=this.element.attr("title"),this.options.showLabel||this.title||this.element.attr("title",this.options.label)},_updateIcon:function(e,i){var s="iconPosition"!==e,n=s?this.options.iconPosition:i,o="top"===n||"bottom"===n;this.icon?s&&this._removeClass(this.icon,null,this.options.icon):(this.icon=t("<span>"),this._addClass(this.icon,"ui-button-icon","ui-icon"),this.options.showLabel||this._addClass("ui-button-icon-only")),s&&this._addClass(this.icon,null,i),this._attachIcon(n),o?(this._addClass(this.icon,null,"ui-widget-icon-block"),this.iconSpace&&this.iconSpace.remove()):(this.iconSpace||(this.iconSpace=t("<span> </span>"),this._addClass(this.iconSpace,"ui-button-icon-space")),this._removeClass(this.icon,null,"ui-wiget-icon-block"),this._attachIconSpace(n))},_destroy:function(){this.element.removeAttr("role"),this.icon&&this.icon.remove(),this.iconSpace&&this.iconSpace.remove(),this.hasTitle||this.element.removeAttr("title")},_attachIconSpace:function(t){this.icon[/^(?:end|bottom)/.test(t)?"before":"after"](this.iconSpace)},_attachIcon:function(t){this.element[/^(?:end|bottom)/.test(t)?"append":"prepend"](this.icon)},_setOptions:function(t){var e=void 0===t.showLabel?this.options.showLabel:t.showLabel,i=void 0===t.icon?this.options.icon:t.icon;e||i||(t.showLabel=!0),this._super(t)},_setOption:function(t,e){"icon"===t&&(e?this._updateIcon(t,e):this.icon&&(this.icon.remove(),this.iconSpace&&this.iconSpace.remove())),"iconPosition"===t&&this._updateIcon(t,e),"showLabel"===t&&(this._toggleClass("ui-button-icon-only",null,!e),this._updateTooltip()),"label"===t&&(this.isInput?this.element.val(e):(this.element.html(e),this.icon&&(this._attachIcon(this.options.iconPosition),this._attachIconSpace(this.options.iconPosition)))),this._super(t,e),"disabled"===t&&(this._toggleClass(null,"ui-state-disabled",e),this.element[0].disabled=e,e&&this.element.blur())},refresh:function(){var t=this.element.is("input, button")?this.element[0].disabled:this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOptions({disabled:t}),this._updateTooltip()}}),t.uiBackCompat!==!1&&(t.widget("ui.button",t.ui.button,{options:{text:!0,icons:{primary:null,secondary:null}},_create:function(){this.options.showLabel&&!this.options.text&&(this.options.showLabel=this.options.text),!this.options.showLabel&&this.options.text&&(this.options.text=this.options.showLabel),this.options.icon||!this.options.icons.primary&&!this.options.icons.secondary?this.options.icon&&(this.options.icons.primary=this.options.icon):this.options.icons.primary?this.options.icon=this.options.icons.primary:(this.options.icon=this.options.icons.secondary,this.options.iconPosition="end"),this._super()},_setOption:function(t,e){return"text"===t?(this._super("showLabel",e),void 0):("showLabel"===t&&(this.options.text=e),"icon"===t&&(this.options.icons.primary=e),"icons"===t&&(e.primary?(this._super("icon",e.primary),this._super("iconPosition","beginning")):e.secondary&&(this._super("icon",e.secondary),this._super("iconPosition","end"))),this._superApply(arguments),void 0)}}),t.fn.button=function(e){return function(){return!this.length||this.length&&"INPUT"!==this[0].tagName||this.length&&"INPUT"===this[0].tagName&&"checkbox"!==this.attr("type")&&"radio"!==this.attr("type")?e.apply(this,arguments):(t.ui.checkboxradio||t.error("Checkboxradio widget missing"),0===arguments.length?this.checkboxradio({icon:!1}):this.checkboxradio.apply(this,arguments))}}(t.fn.button),t.fn.buttonset=function(){return t.ui.controlgroup||t.error("Controlgroup widget missing"),"option"===arguments[0]&&"items"===arguments[1]&&arguments[2]?this.controlgroup.apply(this,[arguments[0],"items.button",arguments[2]]):"option"===arguments[0]&&"items"===arguments[1]?this.controlgroup.apply(this,[arguments[0],"items.button"]):("object"==typeof arguments[0]&&arguments[0].items&&(arguments[0].items={button:arguments[0].items}),this.controlgroup.apply(this,arguments))}),t.ui.button,t.extend(t.ui,{datepicker:{version:"1.12.1"}});var m;t.extend(s.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(t){return a(this._defaults,t||{}),this},_attachDatepicker:function(e,i){var s,n,o;s=e.nodeName.toLowerCase(),n="div"===s||"span"===s,e.id||(this.uuid+=1,e.id="dp"+this.uuid),o=this._newInst(t(e),n),o.settings=t.extend({},i||{}),"input"===s?this._connectDatepicker(e,o):n&&this._inlineDatepicker(e,o)},_newInst:function(e,i){var s=e[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?n(t("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(e,i){var s=t(e);i.append=t([]),i.trigger=t([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).on("keydown",this._doKeyDown).on("keypress",this._doKeyPress).on("keyup",this._doKeyUp),this._autoSize(i),t.data(e,"datepicker",i),i.settings.disabled&&this._disableDatepicker(e))},_attachments:function(e,i){var s,n,o,a=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),a&&(i.append=t("<span class='"+this._appendClass+"'>"+a+"</span>"),e[r?"before":"after"](i.append)),e.off("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&e.on("focus",this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),o=this._get(i,"buttonImage"),i.trigger=t(this._get(i,"buttonImageOnly")?t("<img/>").addClass(this._triggerClass).attr({src:o,alt:n,title:n}):t("<button type='button'></button>").addClass(this._triggerClass).html(o?t("<img/>").attr({src:o,alt:n,title:n}):n)),e[r?"before":"after"](i.trigger),i.trigger.on("click",function(){return t.datepicker._datepickerShowing&&t.datepicker._lastInput===e[0]?t.datepicker._hideDatepicker():t.datepicker._datepickerShowing&&t.datepicker._lastInput!==e[0]?(t.datepicker._hideDatepicker(),t.datepicker._showDatepicker(e[0])):t.datepicker._showDatepicker(e[0]),!1}))},_autoSize:function(t){if(this._get(t,"autoSize")&&!t.inline){var e,i,s,n,o=new Date(2009,11,20),a=this._get(t,"dateFormat");a.match(/[DM]/)&&(e=function(t){for(i=0,s=0,n=0;t.length>n;n++)t[n].length>i&&(i=t[n].length,s=n);return s},o.setMonth(e(this._get(t,a.match(/MM/)?"monthNames":"monthNamesShort"))),o.setDate(e(this._get(t,a.match(/DD/)?"dayNames":"dayNamesShort"))+20-o.getDay())),t.input.attr("size",this._formatDate(t,o).length)}},_inlineDatepicker:function(e,i){var s=t(e);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),t.data(e,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(e),i.dpDiv.css("display","block"))},_dialogDatepicker:function(e,i,s,n,o){var r,h,l,c,u,d=this._dialogInst;return d||(this.uuid+=1,r="dp"+this.uuid,this._dialogInput=t("<input type='text' id='"+r+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.on("keydown",this._doKeyDown),t("body").append(this._dialogInput),d=this._dialogInst=this._newInst(this._dialogInput,!1),d.settings={},t.data(this._dialogInput[0],"datepicker",d)),a(d.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(d,i):i,this._dialogInput.val(i),this._pos=o?o.length?o:[o.pageX,o.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,c=document.documentElement.scrollLeft||document.body.scrollLeft,u=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+c,l/2-150+u]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),d.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),t.blockUI&&t.blockUI(this.dpDiv),t.data(this._dialogInput[0],"datepicker",d),this},_destroyDatepicker:function(e){var i,s=t(e),n=t.data(e,"datepicker");s.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),t.removeData(e,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).off("focus",this._showDatepicker).off("keydown",this._doKeyDown).off("keypress",this._doKeyPress).off("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),m===n&&(m=null))},_enableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!1,o.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}))},_disableDatepicker:function(e){var i,s,n=t(e),o=t.data(e,"datepicker");n.hasClass(this.markerClassName)&&(i=e.nodeName.toLowerCase(),"input"===i?(e.disabled=!0,o.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=t.map(this._disabledInputs,function(t){return t===e?null:t}),this._disabledInputs[this._disabledInputs.length]=e)},_isDisabledDatepicker:function(t){if(!t)return!1;for(var e=0;this._disabledInputs.length>e;e++)if(this._disabledInputs[e]===t)return!0;return!1},_getInst:function(e){try{return t.data(e,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,i,s){var n,o,r,h,l=this._getInst(e);return 2===arguments.length&&"string"==typeof i?"defaults"===i?t.extend({},t.datepicker._defaults):l?"all"===i?t.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),o=this._getDateDatepicker(e,!0),r=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),a(l.settings,n),null!==r&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,r)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(e):this._enableDatepicker(e)),this._attachments(t(e),l),this._autoSize(l),this._setDate(l,o),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(t,e,i){this._optionDatepicker(t,e,i)},_refreshDatepicker:function(t){var e=this._getInst(t);e&&this._updateDatepicker(e)},_setDateDatepicker:function(t,e){var i=this._getInst(t);i&&(this._setDate(i,e),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(t,e){var i=this._getInst(t);return i&&!i.inline&&this._setDateFromField(i,e),i?this._getDate(i):null},_doKeyDown:function(e){var i,s,n,o=t.datepicker._getInst(e.target),a=!0,r=o.dpDiv.is(".ui-datepicker-rtl");if(o._keyEvent=!0,t.datepicker._datepickerShowing)switch(e.keyCode){case 9:t.datepicker._hideDatepicker(),a=!1;break;case 13:return n=t("td."+t.datepicker._dayOverClass+":not(."+t.datepicker._currentClass+")",o.dpDiv),n[0]&&t.datepicker._selectDay(e.target,o.selectedMonth,o.selectedYear,n[0]),i=t.datepicker._get(o,"onSelect"),i?(s=t.datepicker._formatDate(o),i.apply(o.input?o.input[0]:null,[s,o])):t.datepicker._hideDatepicker(),!1;case 27:t.datepicker._hideDatepicker();break;case 33:t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 34:t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&t.datepicker._clearDate(e.target),a=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&t.datepicker._gotoToday(e.target),a=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?1:-1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?-t.datepicker._get(o,"stepBigMonths"):-t.datepicker._get(o,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,-7,"D"),a=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,r?-1:1,"D"),a=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&t.datepicker._adjustDate(e.target,e.ctrlKey?+t.datepicker._get(o,"stepBigMonths"):+t.datepicker._get(o,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&t.datepicker._adjustDate(e.target,7,"D"),a=e.ctrlKey||e.metaKey;break;default:a=!1}else 36===e.keyCode&&e.ctrlKey?t.datepicker._showDatepicker(this):a=!1;a&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var i,s,n=t.datepicker._getInst(e.target);return t.datepicker._get(n,"constrainInput")?(i=t.datepicker._possibleChars(t.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),e.ctrlKey||e.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(e){var i,s=t.datepicker._getInst(e.target);if(s.input.val()!==s.lastVal)try{i=t.datepicker.parseDate(t.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,t.datepicker._getFormatConfig(s)),i&&(t.datepicker._setDateFromField(s),t.datepicker._updateAlternate(s),t.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(e){if(e=e.target||e,"input"!==e.nodeName.toLowerCase()&&(e=t("input",e.parentNode)[0]),!t.datepicker._isDisabledDatepicker(e)&&t.datepicker._lastInput!==e){var s,n,o,r,h,l,c;s=t.datepicker._getInst(e),t.datepicker._curInst&&t.datepicker._curInst!==s&&(t.datepicker._curInst.dpDiv.stop(!0,!0),s&&t.datepicker._datepickerShowing&&t.datepicker._hideDatepicker(t.datepicker._curInst.input[0])),n=t.datepicker._get(s,"beforeShow"),o=n?n.apply(e,[e,s]):{},o!==!1&&(a(s.settings,o),s.lastVal=null,t.datepicker._lastInput=e,t.datepicker._setDateFromField(s),t.datepicker._inDialog&&(e.value=""),t.datepicker._pos||(t.datepicker._pos=t.datepicker._findPos(e),t.datepicker._pos[1]+=e.offsetHeight),r=!1,t(e).parents().each(function(){return r|="fixed"===t(this).css("position"),!r}),h={left:t.datepicker._pos[0],top:t.datepicker._pos[1]},t.datepicker._pos=null,s.dpDiv.empty(),s.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),t.datepicker._updateDatepicker(s),h=t.datepicker._checkOffset(s,h,r),s.dpDiv.css({position:t.datepicker._inDialog&&t.blockUI?"static":r?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),s.inline||(l=t.datepicker._get(s,"showAnim"),c=t.datepicker._get(s,"duration"),s.dpDiv.css("z-index",i(t(e))+1),t.datepicker._datepickerShowing=!0,t.effects&&t.effects.effect[l]?s.dpDiv.show(l,t.datepicker._get(s,"showOptions"),c):s.dpDiv[l||"show"](l?c:null),t.datepicker._shouldFocusInput(s)&&s.input.trigger("focus"),t.datepicker._curInst=s)) }},_updateDatepicker:function(e){this.maxRows=4,m=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],a=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;!a||e&&a!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&(t.effects.effect[i]||t.effects[i])?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(a,"onClose"),o&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),e=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((e-i)/864e5)/7)+1},parseDate:function(e,i,s){if(null==e||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,o,a,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,c="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),u=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,d=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,g=-1,m=-1,_=-1,v=-1,b=!1,y=function(t){var i=e.length>n+1&&e.charAt(n+1)===t;return i&&n++,i},w=function(t){var e=y(t),s="@"===t?14:"!"===t?20:"y"===t&&e?4:"o"===t?3:2,n="y"===t?s:1,o=RegExp("^\\d{"+n+","+s+"}"),a=i.substring(h).match(o);if(!a)throw"Missing number at position "+h;return h+=a[0].length,parseInt(a[0],10)},k=function(e,s,n){var o=-1,a=t.map(y(e)?n:s,function(t,e){return[[e,t]]}).sort(function(t,e){return-(t[1].length-e[1].length)});if(t.each(a,function(t,e){var s=e[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(o=e[0],h+=s.length,!1):void 0}),-1!==o)return o+1;throw"Unknown name at position "+h},x=function(){if(i.charAt(h)!==e.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;e.length>n;n++)if(b)"'"!==e.charAt(n)||y("'")?x():b=!1;else switch(e.charAt(n)){case"d":_=w("d");break;case"D":k("D",u,d);break;case"o":v=w("o");break;case"m":m=w("m");break;case"M":m=k("M",p,f);break;case"y":g=w("y");break;case"@":r=new Date(w("@")),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"!":r=new Date((w("!")-this._ticksTo1970)/1e4),g=r.getFullYear(),m=r.getMonth()+1,_=r.getDate();break;case"'":y("'")?x():b=!0;break;default:x()}if(i.length>h&&(a=i.substr(h),!/^\s+/.test(a)))throw"Extra/unparsed characters found in date: "+a;if(-1===g?g=(new Date).getFullYear():100>g&&(g+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c>=g?0:-100)),v>-1)for(m=1,_=v;;){if(o=this._getDaysInMonth(g,m-1),o>=_)break;m++,_-=o}if(r=this._daylightSavingAdjust(new Date(g,m-1,_)),r.getFullYear()!==g||r.getMonth()+1!==m||r.getDate()!==_)throw"Invalid date";return r},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(t,e,i){if(!e)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,o=(i?i.dayNames:null)||this._defaults.dayNames,a=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(e){var i=t.length>s+1&&t.charAt(s+1)===e;return i&&s++,i},l=function(t,e,i){var s=""+e;if(h(t))for(;i>s.length;)s="0"+s;return s},c=function(t,e,i,s){return h(t)?s[e]:i[e]},u="",d=!1;if(e)for(s=0;t.length>s;s++)if(d)"'"!==t.charAt(s)||h("'")?u+=t.charAt(s):d=!1;else switch(t.charAt(s)){case"d":u+=l("d",e.getDate(),2);break;case"D":u+=c("D",e.getDay(),n,o);break;case"o":u+=l("o",Math.round((new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()-new Date(e.getFullYear(),0,0).getTime())/864e5),3);break;case"m":u+=l("m",e.getMonth()+1,2);break;case"M":u+=c("M",e.getMonth(),a,r);break;case"y":u+=h("y")?e.getFullYear():(10>e.getFullYear()%100?"0":"")+e.getFullYear()%100;break;case"@":u+=e.getTime();break;case"!":u+=1e4*e.getTime()+this._ticksTo1970;break;case"'":h("'")?u+="'":d=!0;break;default:u+=t.charAt(s)}return u},_possibleChars:function(t){var e,i="",s=!1,n=function(i){var s=t.length>e+1&&t.charAt(e+1)===i;return s&&e++,s};for(e=0;t.length>e;e++)if(s)"'"!==t.charAt(e)||n("'")?i+=t.charAt(e):s=!1;else switch(t.charAt(e)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=t.charAt(e)}return i},_get:function(t,e){return void 0!==t.settings[e]?t.settings[e]:this._defaults[e]},_setDateFromField:function(t,e){if(t.input.val()!==t.lastVal){var i=this._get(t,"dateFormat"),s=t.lastVal=t.input?t.input.val():null,n=this._getDefaultDate(t),o=n,a=this._getFormatConfig(t);try{o=this.parseDate(i,s,a)||n}catch(r){s=e?"":s}t.selectedDay=o.getDate(),t.drawMonth=t.selectedMonth=o.getMonth(),t.drawYear=t.selectedYear=o.getFullYear(),t.currentDay=s?o.getDate():0,t.currentMonth=s?o.getMonth():0,t.currentYear=s?o.getFullYear():0,this._adjustInstDate(t)}},_getDefaultDate:function(t){return this._restrictMinMax(t,this._determineDate(t,this._get(t,"defaultDate"),new Date))},_determineDate:function(e,i,s){var n=function(t){var e=new Date;return e.setDate(e.getDate()+t),e},o=function(i){try{return t.datepicker.parseDate(t.datepicker._get(e,"dateFormat"),i,t.datepicker._getFormatConfig(e))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?t.datepicker._getDate(e):null)||new Date,o=n.getFullYear(),a=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":a+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a));break;case"y":case"Y":o+=parseInt(l[1],10),r=Math.min(r,t.datepicker._getDaysInMonth(o,a))}l=h.exec(i)}return new Date(o,a,r)},a=null==i||""===i?s:"string"==typeof i?o(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return a=a&&"Invalid Date"==""+a?s:a,a&&(a.setHours(0),a.setMinutes(0),a.setSeconds(0),a.setMilliseconds(0)),this._daylightSavingAdjust(a)},_daylightSavingAdjust:function(t){return t?(t.setHours(t.getHours()>12?t.getHours()+2:0),t):null},_setDate:function(t,e,i){var s=!e,n=t.selectedMonth,o=t.selectedYear,a=this._restrictMinMax(t,this._determineDate(t,e,new Date));t.selectedDay=t.currentDay=a.getDate(),t.drawMonth=t.selectedMonth=t.currentMonth=a.getMonth(),t.drawYear=t.selectedYear=t.currentYear=a.getFullYear(),n===t.selectedMonth&&o===t.selectedYear||i||this._notifyChange(t),this._adjustInstDate(t),t.input&&t.input.val(s?"":this._formatDate(t))},_getDate:function(t){var e=!t.currentYear||t.input&&""===t.input.val()?null:this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return e},_attachHandlers:function(e){var i=this._get(e,"stepMonths"),s="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){t.datepicker._adjustDate(s,-i,"M")},next:function(){t.datepicker._adjustDate(s,+i,"M")},hide:function(){t.datepicker._hideDatepicker()},today:function(){t.datepicker._gotoToday(s)},selectDay:function(){return t.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return t.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return t.datepicker._selectMonthYear(s,this,"Y"),!1}};t(this).on(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(t){var e,i,s,n,o,a,r,h,l,c,u,d,p,f,g,m,_,v,b,y,w,k,x,C,D,I,T,P,M,S,H,z,O,A,N,W,E,F,L,R=new Date,B=this._daylightSavingAdjust(new Date(R.getFullYear(),R.getMonth(),R.getDate())),Y=this._get(t,"isRTL"),j=this._get(t,"showButtonPanel"),q=this._get(t,"hideIfNoPrevNext"),K=this._get(t,"navigationAsDateFormat"),U=this._getNumberOfMonths(t),V=this._get(t,"showCurrentAtPos"),$=this._get(t,"stepMonths"),X=1!==U[0]||1!==U[1],G=this._daylightSavingAdjust(t.currentDay?new Date(t.currentYear,t.currentMonth,t.currentDay):new Date(9999,9,9)),Q=this._getMinMaxDate(t,"min"),J=this._getMinMaxDate(t,"max"),Z=t.drawMonth-V,te=t.drawYear;if(0>Z&&(Z+=12,te--),J)for(e=this._daylightSavingAdjust(new Date(J.getFullYear(),J.getMonth()-U[0]*U[1]+1,J.getDate())),e=Q&&Q>e?Q:e;this._daylightSavingAdjust(new Date(te,Z,1))>e;)Z--,0>Z&&(Z=11,te--);for(t.drawMonth=Z,t.drawYear=te,i=this._get(t,"prevText"),i=K?this.formatDate(i,this._daylightSavingAdjust(new Date(te,Z-$,1)),this._getFormatConfig(t)):i,s=this._canAdjustMonth(t,-1,te,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>":q?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>",n=this._get(t,"nextText"),n=K?this.formatDate(n,this._daylightSavingAdjust(new Date(te,Z+$,1)),this._getFormatConfig(t)):n,o=this._canAdjustMonth(t,1,te,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>":q?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>",a=this._get(t,"currentText"),r=this._get(t,"gotoCurrent")&&t.currentDay?G:B,a=K?this.formatDate(a,r,this._getFormatConfig(t)):a,h=t.inline?"":"<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>"+this._get(t,"closeText")+"</button>",l=j?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(Y?h:"")+(this._isInRange(t,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+a+"</button>":"")+(Y?"":h)+"</div>":"",c=parseInt(this._get(t,"firstDay"),10),c=isNaN(c)?0:c,u=this._get(t,"showWeek"),d=this._get(t,"dayNames"),p=this._get(t,"dayNamesMin"),f=this._get(t,"monthNames"),g=this._get(t,"monthNamesShort"),m=this._get(t,"beforeShowDay"),_=this._get(t,"showOtherMonths"),v=this._get(t,"selectOtherMonths"),b=this._getDefaultDate(t),y="",k=0;U[0]>k;k++){for(x="",this.maxRows=4,C=0;U[1]>C;C++){if(D=this._daylightSavingAdjust(new Date(te,Z,t.selectedDay)),I=" ui-corner-all",T="",X){if(T+="<div class='ui-datepicker-group",U[1]>1)switch(C){case 0:T+=" ui-datepicker-group-first",I=" ui-corner-"+(Y?"right":"left");break;case U[1]-1:T+=" ui-datepicker-group-last",I=" ui-corner-"+(Y?"left":"right");break;default:T+=" ui-datepicker-group-middle",I=""}T+="'>"}for(T+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+I+"'>"+(/all|left/.test(I)&&0===k?Y?o:s:"")+(/all|right/.test(I)&&0===k?Y?s:o:"")+this._generateMonthYearHeader(t,Z,te,Q,J,k>0||C>0,f,g)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",P=u?"<th class='ui-datepicker-week-col'>"+this._get(t,"weekHeader")+"</th>":"",w=0;7>w;w++)M=(w+c)%7,P+="<th scope='col'"+((w+c+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+d[M]+"'>"+p[M]+"</span></th>";for(T+=P+"</tr></thead><tbody>",S=this._getDaysInMonth(te,Z),te===t.selectedYear&&Z===t.selectedMonth&&(t.selectedDay=Math.min(t.selectedDay,S)),H=(this._getFirstDayOfMonth(te,Z)-c+7)%7,z=Math.ceil((H+S)/7),O=X?this.maxRows>z?this.maxRows:z:z,this.maxRows=O,A=this._daylightSavingAdjust(new Date(te,Z,1-H)),N=0;O>N;N++){for(T+="<tr>",W=u?"<td class='ui-datepicker-week-col'>"+this._get(t,"calculateWeek")(A)+"</td>":"",w=0;7>w;w++)E=m?m.apply(t.input?t.input[0]:null,[A]):[!0,""],F=A.getMonth()!==Z,L=F&&!v||!E[0]||Q&&Q>A||J&&A>J,W+="<td class='"+((w+c+6)%7>=5?" ui-datepicker-week-end":"")+(F?" ui-datepicker-other-month":"")+(A.getTime()===D.getTime()&&Z===t.selectedMonth&&t._keyEvent||b.getTime()===A.getTime()&&b.getTime()===D.getTime()?" "+this._dayOverClass:"")+(L?" "+this._unselectableClass+" ui-state-disabled":"")+(F&&!_?"":" "+E[1]+(A.getTime()===G.getTime()?" "+this._currentClass:"")+(A.getTime()===B.getTime()?" ui-datepicker-today":""))+"'"+(F&&!_||!E[2]?"":" title='"+E[2].replace(/'/g,"&#39;")+"'")+(L?"":" data-handler='selectDay' data-event='click' data-month='"+A.getMonth()+"' data-year='"+A.getFullYear()+"'")+">"+(F&&!_?"&#xa0;":L?"<span class='ui-state-default'>"+A.getDate()+"</span>":"<a class='ui-state-default"+(A.getTime()===B.getTime()?" ui-state-highlight":"")+(A.getTime()===G.getTime()?" ui-state-active":"")+(F?" ui-priority-secondary":"")+"' href='#'>"+A.getDate()+"</a>")+"</td>",A.setDate(A.getDate()+1),A=this._daylightSavingAdjust(A);T+=W+"</tr>"}Z++,Z>11&&(Z=0,te++),T+="</tbody></table>"+(X?"</div>"+(U[0]>0&&C===U[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),x+=T}y+=x}return y+=l,t._keyEvent=!1,y},_generateMonthYearHeader:function(t,e,i,s,n,o,a,r){var h,l,c,u,d,p,f,g,m=this._get(t,"changeMonth"),_=this._get(t,"changeYear"),v=this._get(t,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",y="";if(o||!m)y+="<span class='ui-datepicker-month'>"+a[e]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,y+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",c=0;12>c;c++)(!h||c>=s.getMonth())&&(!l||n.getMonth()>=c)&&(y+="<option value='"+c+"'"+(c===e?" selected='selected'":"")+">"+r[c]+"</option>");y+="</select>"}if(v||(b+=y+(!o&&m&&_?"":"&#xa0;")),!t.yearshtml)if(t.yearshtml="",o||!_)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(u=this._get(t,"yearRange").split(":"),d=(new Date).getFullYear(),p=function(t){var e=t.match(/c[+\-].*/)?i+parseInt(t.substring(1),10):t.match(/[+\-].*/)?d+parseInt(t,10):parseInt(t,10);return isNaN(e)?d:e},f=p(u[0]),g=Math.max(f,p(u[1]||"")),f=s?Math.max(f,s.getFullYear()):f,g=n?Math.min(g,n.getFullYear()):g,t.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";g>=f;f++)t.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";t.yearshtml+="</select>",b+=t.yearshtml,t.yearshtml=null}return b+=this._get(t,"yearSuffix"),v&&(b+=(!o&&m&&_?"":"&#xa0;")+y),b+="</div>"},_adjustInstDate:function(t,e,i){var s=t.selectedYear+("Y"===i?e:0),n=t.selectedMonth+("M"===i?e:0),o=Math.min(t.selectedDay,this._getDaysInMonth(s,n))+("D"===i?e:0),a=this._restrictMinMax(t,this._daylightSavingAdjust(new Date(s,n,o)));t.selectedDay=a.getDate(),t.drawMonth=t.selectedMonth=a.getMonth(),t.drawYear=t.selectedYear=a.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(t)},_restrictMinMax:function(t,e){var i=this._getMinMaxDate(t,"min"),s=this._getMinMaxDate(t,"max"),n=i&&i>e?i:e;return s&&n>s?s:n},_notifyChange:function(t){var e=this._get(t,"onChangeMonthYear");e&&e.apply(t.input?t.input[0]:null,[t.selectedYear,t.selectedMonth+1,t])},_getNumberOfMonths:function(t){var e=this._get(t,"numberOfMonths");return null==e?[1,1]:"number"==typeof e?[1,e]:e},_getMinMaxDate:function(t,e){return this._determineDate(t,this._get(t,e+"Date"),null)},_getDaysInMonth:function(t,e){return 32-this._daylightSavingAdjust(new Date(t,e,32)).getDate()},_getFirstDayOfMonth:function(t,e){return new Date(t,e,1).getDay()},_canAdjustMonth:function(t,e,i,s){var n=this._getNumberOfMonths(t),o=this._daylightSavingAdjust(new Date(i,s+(0>e?e:n[0]*n[1]),1));return 0>e&&o.setDate(this._getDaysInMonth(o.getFullYear(),o.getMonth())),this._isInRange(t,o)},_isInRange:function(t,e){var i,s,n=this._getMinMaxDate(t,"min"),o=this._getMinMaxDate(t,"max"),a=null,r=null,h=this._get(t,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),a=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(a+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||e.getTime()>=n.getTime())&&(!o||e.getTime()<=o.getTime())&&(!a||e.getFullYear()>=a)&&(!r||r>=e.getFullYear())},_getFormatConfig:function(t){var e=this._get(t,"shortYearCutoff");return e="string"!=typeof e?e:(new Date).getFullYear()%100+parseInt(e,10),{shortYearCutoff:e,dayNamesShort:this._get(t,"dayNamesShort"),dayNames:this._get(t,"dayNames"),monthNamesShort:this._get(t,"monthNamesShort"),monthNames:this._get(t,"monthNames")}},_formatDate:function(t,e,i,s){e||(t.currentDay=t.selectedDay,t.currentMonth=t.selectedMonth,t.currentYear=t.selectedYear);var n=e?"object"==typeof e?e:this._daylightSavingAdjust(new Date(s,i,e)):this._daylightSavingAdjust(new Date(t.currentYear,t.currentMonth,t.currentDay));return this.formatDate(this._get(t,"dateFormat"),n,this._getFormatConfig(t))}}),t.fn.datepicker=function(e){if(!this.length)return this;t.datepicker.initialized||(t(document).on("mousedown",t.datepicker._checkExternalClick),t.datepicker.initialized=!0),0===t("#"+t.datepicker._mainDivId).length&&t("body").append(t.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof e||"isDisabled"!==e&&"getDate"!==e&&"widget"!==e?"option"===e&&2===arguments.length&&"string"==typeof arguments[1]?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof e?t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this].concat(i)):t.datepicker._attachDatepicker(this,e)}):t.datepicker["_"+e+"Datepicker"].apply(t.datepicker,[this[0]].concat(i))},t.datepicker=new s,t.datepicker.initialized=!1,t.datepicker.uuid=(new Date).getTime(),t.datepicker.version="1.12.1",t.datepicker,t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var _=!1;t(document).on("mouseup",function(){_=!1}),t.widget("ui.mouse",{version:"1.12.1",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){if(!_){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,s=1===e.which,n="string"==typeof this.options.cancel&&e.target.nodeName?t(e.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(e)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(e)!==!1,!this._mouseStarted)?(e.preventDefault(),!0):(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),_=!0,!0)):!0}},_mouseMove:function(e){if(this._mouseMoved){if(t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button)return this._mouseUp(e);if(!e.which)if(e.originalEvent.altKey||e.originalEvent.ctrlKey||e.originalEvent.metaKey||e.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,_=!1,e.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),t.ui.plugin={add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;o.length>n;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},t.ui.safeBlur=function(e){e&&"body"!==e.nodeName.toLowerCase()&&t(e).trigger("blur")},t.widget("ui.draggable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(e){var i=this.options;return this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(this._blurActiveElement(e),this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("<div>").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=t.ui.safeActiveElement(this.document[0]),s=t(e.target);s.closest(i).length||t.ui.safeBlur(i)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp(new t.Event("mouseup",e)),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.trigger("focus"),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new t.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper),n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())} },_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(h=this.originalPageX),"x"===a.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){var t=this;t.isOver?(t.isOver=0,s.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,o=this;o.positionAbs=s.positionAbs,o.helperProportions=s.helperProportions,o.offset.click=s.offset.click,o._intersectsWith(o.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==o&&this._intersectsWith(this.containerCache)&&t.contains(o.element[0],this.element[0])&&(n=!1),n})),n?(o.isOver||(o.isOver=1,s._parent=i.helper.parent(),o.currentItem=i.helper.appendTo(o.element).data("ui-sortable-item",!0),o.options._helper=o.options.helper,o.options.helper=function(){return i.helper[0]},e.target=o.currentItem[0],o._mouseCapture(e,!0),o._mouseStart(e,!0,!0),o.offset.click.top=s.offset.click.top,o.offset.click.left=s.offset.click.left,o.offset.parent.left-=s.offset.parent.left-o.offset.parent.left,o.offset.parent.top-=s.offset.parent.top-o.offset.parent.top,s._trigger("toSortable",e),s.dropped=o.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,o.fromOutside=s),o.currentItem&&(o._mouseDrag(e),i.position=o.position)):o.isOver&&(o.isOver=0,o.cancelHelperRemoval=!0,o.options._revert=o.options.revert,o.options.revert=!1,o._trigger("out",e,o._uiHash(o)),o._mouseStop(e,!0),o.options.revert=o.options._revert,o.options.helper=o.options._helper,o.placeholder&&o.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),o=s.options;n.css("cursor")&&(o._cursor=n.css("cursor")),n.css("cursor",o.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("opacity")&&(o._opacity=n.css("opacity")),n.css("opacity",o.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(e,i,s){var n=s.options,o=!1,a=s.scrollParentNotHidden[0],r=s.document[0];a!==r&&"HTML"!==a.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+a.offsetHeight-e.pageY<n.scrollSensitivity?a.scrollTop=o=a.scrollTop+n.scrollSpeed:e.pageY-s.overflowOffset.top<n.scrollSensitivity&&(a.scrollTop=o=a.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+a.offsetWidth-e.pageX<n.scrollSensitivity?a.scrollLeft=o=a.scrollLeft+n.scrollSpeed:e.pageX-s.overflowOffset.left<n.scrollSensitivity&&(a.scrollLeft=o=a.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(e.pageY-t(r).scrollTop()<n.scrollSensitivity?o=t(r).scrollTop(t(r).scrollTop()-n.scrollSpeed):t(window).height()-(e.pageY-t(r).scrollTop())<n.scrollSensitivity&&(o=t(r).scrollTop(t(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(e.pageX-t(r).scrollLeft()<n.scrollSensitivity?o=t(r).scrollLeft(t(r).scrollLeft()-n.scrollSpeed):t(window).width()-(e.pageX-t(r).scrollLeft())<n.scrollSensitivity&&(o=t(r).scrollLeft(t(r).scrollLeft()+n.scrollSpeed)))),o!==!1&&t.ui.ddmanager&&!n.dropBehaviour&&t.ui.ddmanager.prepareOffsets(s,e)}}),t.ui.plugin.add("draggable","snap",{start:function(e,i,s){var n=s.options;s.snapElements=[],t(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var e=t(this),i=e.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:e.outerWidth(),height:e.outerHeight(),top:i.top,left:i.left})})},drag:function(e,i,s){var n,o,a,r,h,l,c,u,d,p,f=s.options,g=f.snapTolerance,m=i.offset.left,_=m+s.helperProportions.width,v=i.offset.top,b=v+s.helperProportions.height;for(d=s.snapElements.length-1;d>=0;d--)h=s.snapElements[d].left-s.margins.left,l=h+s.snapElements[d].width,c=s.snapElements[d].top-s.margins.top,u=c+s.snapElements[d].height,h-g>_||m>l+g||c-g>b||v>u+g||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)?(s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(n=g>=Math.abs(c-b),o=g>=Math.abs(u-v),a=g>=Math.abs(h-_),r=g>=Math.abs(l-m),n&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||o||a||r,"outer"!==f.snapMode&&(n=g>=Math.abs(c-v),o=g>=Math.abs(u-b),a=g>=Math.abs(h-m),r=g>=Math.abs(l-_),n&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||o||a||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||o||a||r||p)}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,o=s.options,a=t.makeArray(t(o.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});a.length&&(n=parseInt(t(a[0]).css("zIndex"),10)||0,t(a).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+a.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("zIndex")&&(o._zIndex=n.css("zIndex")),n.css("zIndex",o.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.resizable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)},_create:function(){var e,i=this.options,s=this;this._addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!i.aspectRatio,aspectRatio:i.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:i.helper||i.ghost||i.animate?i.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,e={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(e),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(e),this._proportionallyResize()),this._setupHandles(),i.autoHide&&t(this.element).on("mouseenter",function(){i.disabled||(s._removeClass("ui-resizable-autohide"),s._handles.show())}).on("mouseleave",function(){i.disabled||s.resizing||(s._addClass("ui-resizable-autohide"),s._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;default:}},_setupHandles:function(){var e,i,s,n,o,a=this.options,r=this;if(this.handles=a.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),s=this.handles.split(","),this.handles={},i=0;s.length>i;i++)e=t.trim(s[i]),n="ui-resizable-"+e,o=t("<div>"),this._addClass(o,"ui-resizable-handle "+n),o.css({zIndex:a.zIndex}),this.handles[e]=".ui-resizable-"+e,this.element.append(o);this._renderAxis=function(e){var i,s,n,o;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(o=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=o&&o[1]?o[1]:"se")}),a.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,o=this.options,a=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),o.containment&&(i+=t(o.containment).scrollLeft()||0,s+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),this._addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,o=this.axis,a=e.pageX-n.left||0,r=e.pageY-n.top||0,h=this._change[o];return this._updatePrevProperties(),h?(i=h.apply(this,[e,a,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,h,l=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:c.sizeDiff.height,o=s?0:c.sizeDiff.width,a={width:c.helper.width()-o,height:c.helper.height()-n},r=parseFloat(c.element.css("left"))+(c.position.left-c.originalPosition.left)||null,h=parseFloat(c.element.css("top"))+(c.position.top-c.originalPosition.top)||null,l.animate||this.element.css(t.extend(a,{top:h,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!l.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s,n,o,a=this.options;o={minWidth:this._isNumber(a.minWidth)?a.minWidth:0,maxWidth:this._isNumber(a.maxWidth)?a.maxWidth:1/0,minHeight:this._isNumber(a.minHeight)?a.minHeight:0,maxHeight:this._isNumber(a.maxHeight)?a.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,s=o.minWidth/this.aspectRatio,i=o.maxHeight*this.aspectRatio,n=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),s>o.minHeight&&(o.minHeight=s),o.maxWidth>i&&(o.maxWidth=i),o.maxHeight>n&&(o.maxHeight=n)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth<t.width,n=this._isNumber(t.height)&&e.maxHeight&&e.maxHeight<t.height,o=this._isNumber(t.width)&&e.minWidth&&e.minWidth>t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,h=this.originalPosition.top+this.originalSize.height,l=/sw|nw|w/.test(i),c=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&l&&(t.left=r-e.minWidth),s&&l&&(t.left=r-e.maxWidth),a&&c&&(t.top=h-e.minHeight),n&&c&&(t.top=h-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];4>e;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;this._proportionallyResizeElements.length>e;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("<div style='overflow:hidden;'></div>"),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-a},l=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,c=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(h,c&&l?{top:c,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,o,a,r,h=t(this).resizable("instance"),l=h.options,c=h.element,u=l.containment,d=u instanceof t?u.get(0):/parent/.test(u)?c.parent().get(0):u;d&&(h.containerElement=t(d),/document/.test(u)||u===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=h._num(e.css("padding"+s))}),h.containerOffset=e.offset(),h.containerPosition=e.position(),h.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,o=h.containerSize.width,a=h._hasScroll(d,"left")?d.scrollWidth:o,r=h._hasScroll(d)?d.scrollHeight:n,h.parentData={element:d,left:s.left,top:s.top,width:a,height:r}))},resize:function(e){var i,s,n,o,a=t(this).resizable("instance"),r=a.options,h=a.containerOffset,l=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(u=h),l.left<(a._helper?h.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-h.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio,p=!1),a.position.left=r.helper?h.left:0),l.top<(a._helper?h.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-h.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio,p=!1),a.position.top=a._helper?h.top:0),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o?(a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top):(a.offset.left=a.element.offset().left,a.offset.top=a.element.offset().top),i=Math.abs(a.sizeDiff.width+(a._helper?a.offset.left-u.left:a.offset.left-h.left)),s=Math.abs(a.sizeDiff.height+(a._helper?a.offset.top-u.top:a.offset.top-h.top)),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio,p=!1)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio,p=!1)),p||(a.position.left=a.prevPosition.left,a.position.top=a.prevPosition.top,a.size.width=a.prevSize.width,a.size.height=a.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),h=a.outerWidth()-e.sizeDiff.width,l=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance"),i=e.options;t(i.alsoResize).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseFloat(e.width()),height:parseFloat(e.height()),left:parseFloat(e.css("left")),top:parseFloat(e.css("top"))})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left:s.position.left-a.left||0};t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},o=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("ui-resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:i.height,width:i.width,margin:0,left:0,top:0}),e._addClass(e.ghost,"ui-resizable-ghost"),t.uiBackCompat!==!1&&"string"==typeof e.options.ghost&&e.ghost.addClass(this.options.ghost),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,o=i.originalSize,a=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,c=h[1]||1,u=Math.round((n.width-o.width)/l)*l,d=Math.round((n.height-o.height)/c)*c,p=o.width+u,f=o.height+d,g=s.maxWidth&&p>s.maxWidth,m=s.maxHeight&&f>s.maxHeight,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=h,_&&(p+=l),v&&(f+=c),g&&(p-=l),m&&(f-=c),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=a.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=a.left-u):((0>=f-c||0>=p-l)&&(e=i._getPaddingPlusBorderDimensions(this)),f-c>0?(i.size.height=f,i.position.top=a.top-d):(f=c-e.height,i.size.height=f,i.position.top=a.top+o.height-f),p-l>0?(i.size.width=p,i.position.left=a.left-u):(p=l-e.width,i.size.width=p,i.position.left=a.left+o.width-p))}}),t.ui.resizable,t.widget("ui.dialog",{version:"1.12.1",options:{appendTo:"body",autoOpen:!0,buttons:[],classes:{"ui-dialog":"ui-corner-all","ui-dialog-titlebar":"ui-corner-all"},closeOnEscape:!0,closeText:"Close",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(e){var i=t(this).css(e).offset().top;0>i&&t(this).css("top",e.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_create:function(){this.originalCss={display:this.element[0].style.display,width:this.element[0].style.width,minHeight:this.element[0].style.minHeight,maxHeight:this.element[0].style.maxHeight,height:this.element[0].style.height},this.originalPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.originalTitle=this.element.attr("title"),null==this.options.title&&null!=this.originalTitle&&(this.options.title=this.originalTitle),this.options.disabled&&(this.options.disabled=!1),this._createWrapper(),this.element.show().removeAttr("title").appendTo(this.uiDialog),this._addClass("ui-dialog-content","ui-widget-content"),this._createTitlebar(),this._createButtonPane(),this.options.draggable&&t.fn.draggable&&this._makeDraggable(),this.options.resizable&&t.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var e=this.options.appendTo;return e&&(e.jquery||e.nodeType)?t(e):this.document.find(e||"body").eq(0)},_destroy:function(){var t,e=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().css(this.originalCss).detach(),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),t=e.parent.children().eq(e.index),t.length&&t[0]!==this.element[0]?t.before(this.element):e.parent.append(this.element)},widget:function(){return this.uiDialog },disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t.ui.safeBlur(t.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(t.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_keepFocus:function(e){function i(){var e=t.ui.safeActiveElement(this.document[0]),i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this._removeClass(this.uiDialog,"ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,o={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(o).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){i._addClass(t(this),"ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,e(n))},drag:function(t,s){i._trigger("drag",t,e(s))},stop:function(n,o){var a=o.offset.left-i.document.scrollLeft(),r=o.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(a>=0?"+":"")+a+" "+"top"+(r>=0?"+":"")+r,of:i.window},i._removeClass(t(this),"ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,e(o))}})},_makeResizable:function(){function e(t){return{originalPosition:t.originalPosition,originalSize:t.originalSize,position:t.position,size:t.size}}var i=this,s=this.options,n=s.resizable,o=this.uiDialog.css("position"),a="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:a,start:function(s,n){i._addClass(t(this),"ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,e(n))},resize:function(t,s){i._trigger("resize",t,e(s))},stop:function(n,o){var a=i.uiDialog.offset(),r=a.left-i.document.scrollLeft(),h=a.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},i._removeClass(t(this),"ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,e(o))}}).css("position",o)},_trackFocus:function(){this._on(this.widget(),{focusin:function(e){this._makeFocusTarget(),this._focusedElement=t(e.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var e=this._trackingInstances(),i=t.inArray(this,e);-1!==i&&e.splice(i,1)},_trackingInstances:function(){var t=this.document.data("ui-dialog-instances");return t||(t=[],this.document.data("ui-dialog-instances",t)),t},_minHeight:function(){var t=this.options;return"auto"===t.height?t.minHeight:Math.min(t.minHeight,t.height)},_position:function(){var t=this.uiDialog.is(":visible");t||this.uiDialog.show(),this.uiDialog.position(this.options.position),t||this.uiDialog.hide()},_setOptions:function(e){var i=this,s=!1,n={};t.each(e,function(t,e){i._setOption(t,e),t in i.sizeRelatedOptions&&(s=!0),t in i.resizableRelatedOptions&&(n[t]=e)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(e,i){var s,n,o=this.uiDialog;"disabled"!==e&&(this._super(e,i),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:t("<a>").text(""+this.options.closeText).html()}),"draggable"===e&&(s=o.is(":data(ui-draggable)"),s&&!i&&o.draggable("destroy"),!s&&i&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(n=o.is(":data(ui-resizable)"),n&&!i&&o.resizable("destroy"),n&&"string"==typeof i&&o.resizable("option","handles",i),n||i===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var t,e,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),t=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),e=Math.max(0,s.minHeight-t),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-t):"none","auto"===s.height?this.element.css({minHeight:e,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-t)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var e=t(this);return t("<div>").css({position:"absolute",width:e.outerWidth(),height:e.outerHeight()}).appendTo(e.parent()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(e){return t(e.target).closest(".ui-dialog").length?!0:!!t(e.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var e=!0;this._delay(function(){e=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(t){e||this._allowInteraction(t)||(t.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=t("<div>").appendTo(this._appendTo()),this._addClass(this.overlay,null,"ui-widget-overlay ui-front"),this._on(this.overlay,{mousedown:"_keepFocus"}),this.document.data("ui-dialog-overlays",(this.document.data("ui-dialog-overlays")||0)+1)}},_destroyOverlay:function(){if(this.options.modal&&this.overlay){var t=this.document.data("ui-dialog-overlays")-1;t?this.document.data("ui-dialog-overlays",t):(this._off(this.document,"focusin"),this.document.removeData("ui-dialog-overlays")),this.overlay.remove(),this.overlay=null}}}),t.uiBackCompat!==!1&&t.widget("ui.dialog",t.ui.dialog,{options:{dialogClass:""},_createWrapper:function(){this._super(),this.uiDialog.addClass(this.options.dialogClass)},_setOption:function(t,e){"dialogClass"===t&&this.uiDialog.removeClass(this.options.dialogClass).addClass(e),this._superApply(arguments)}}),t.ui.dialog,t.widget("ui.droppable",{version:"1.12.1",widgetEventPrefix:"drop",options:{accept:"*",addClasses:!0,greedy:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var e,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=t.isFunction(s)?s:function(t){return t.is(s)},this.proportions=function(){return arguments.length?(e=arguments[0],void 0):e?e:e={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this._addClass("ui-droppable")},_addToManager:function(e){t.ui.ddmanager.droppables[e]=t.ui.ddmanager.droppables[e]||[],t.ui.ddmanager.droppables[e].push(this)},_splice:function(t){for(var e=0;t.length>e;e++)t[e]===this&&t.splice(e,1)},_destroy:function(){var e=t.ui.ddmanager.droppables[this.options.scope];this._splice(e)},_setOption:function(e,i){if("accept"===e)this.accept=t.isFunction(i)?i:function(t){return t.is(i)};else if("scope"===e){var s=t.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(e,i)},_activate:function(e){var i=t.ui.ddmanager.current;this._addActiveClass(),i&&this._trigger("activate",e,this.ui(i))},_deactivate:function(e){var i=t.ui.ddmanager.current;this._removeActiveClass(),i&&this._trigger("deactivate",e,this.ui(i))},_over:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._addHoverClass(),this._trigger("over",e,this.ui(i)))},_out:function(e){var i=t.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this._removeHoverClass(),this._trigger("out",e,this.ui(i)))},_drop:function(e,i){var s=i||t.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var i=t(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&v(s,t.extend(i,{offset:i.element.offset()}),i.options.tolerance,e)?(n=!0,!1):void 0}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this._removeActiveClass(),this._removeHoverClass(),this._trigger("drop",e,this.ui(s)),this.element):!1):!1},ui:function(t){return{draggable:t.currentItem||t.element,helper:t.helper,position:t.position,offset:t.positionAbs}},_addHoverClass:function(){this._addClass("ui-droppable-hover")},_removeHoverClass:function(){this._removeClass("ui-droppable-hover")},_addActiveClass:function(){this._addClass("ui-droppable-active")},_removeActiveClass:function(){this._removeClass("ui-droppable-active")}});var v=t.ui.intersect=function(){function t(t,e,i){return t>=e&&e+i>t}return function(e,i,s,n){if(!i.offset)return!1;var o=(e.positionAbs||e.position.absolute).left+e.margins.left,a=(e.positionAbs||e.position.absolute).top+e.margins.top,r=o+e.helperProportions.width,h=a+e.helperProportions.height,l=i.offset.left,c=i.offset.top,u=l+i.proportions().width,d=c+i.proportions().height;switch(s){case"fit":return o>=l&&u>=r&&a>=c&&d>=h;case"intersect":return o+e.helperProportions.width/2>l&&u>r-e.helperProportions.width/2&&a+e.helperProportions.height/2>c&&d>h-e.helperProportions.height/2;case"pointer":return t(n.pageY,c,i.proportions().height)&&t(n.pageX,l,i.proportions().width);case"touch":return(a>=c&&d>=a||h>=c&&d>=h||c>a&&h>d)&&(o>=l&&u>=o||r>=l&&u>=r||l>o&&r>u);default:return!1}}}();t.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,i){var s,n,o=t.ui.ddmanager.droppables[e.options.scope]||[],a=i?i.type:null,r=(e.currentItem||e.element).find(":data(ui-droppable)").addBack();t:for(s=0;o.length>s;s++)if(!(o[s].options.disabled||e&&!o[s].accept.call(o[s].element[0],e.currentItem||e.element))){for(n=0;r.length>n;n++)if(r[n]===o[s].element[0]){o[s].proportions().height=0;continue t}o[s].visible="none"!==o[s].element.css("display"),o[s].visible&&("mousedown"===a&&o[s]._activate.call(o[s],i),o[s].offset=o[s].element.offset(),o[s].proportions({width:o[s].element[0].offsetWidth,height:o[s].element[0].offsetHeight}))}},drop:function(e,i){var s=!1;return t.each((t.ui.ddmanager.droppables[e.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&v(e,this,this.options.tolerance,i)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],e.currentItem||e.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(e,i){e.element.parentsUntil("body").on("scroll.droppable",function(){e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)})},drag:function(e,i){e.options.refreshPositions&&t.ui.ddmanager.prepareOffsets(e,i),t.each(t.ui.ddmanager.droppables[e.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,o,a=v(e,this,this.options.tolerance,i),r=!a&&this.isover?"isout":a&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,o=this.element.parents(":data(ui-droppable)").filter(function(){return t(this).droppable("instance").options.scope===n}),o.length&&(s=t(o[0]).droppable("instance"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(e,i){e.element.parentsUntil("body").off("scroll.droppable"),e.options.refreshPositions||t.ui.ddmanager.prepareOffsets(e,i)}},t.uiBackCompat!==!1&&t.widget("ui.droppable",t.ui.droppable,{options:{hoverClass:!1,activeClass:!1},_addActiveClass:function(){this._super(),this.options.activeClass&&this.element.addClass(this.options.activeClass)},_removeActiveClass:function(){this._super(),this.options.activeClass&&this.element.removeClass(this.options.activeClass)},_addHoverClass:function(){this._super(),this.options.hoverClass&&this.element.addClass(this.options.hoverClass)},_removeHoverClass:function(){this._super(),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass)}}),t.ui.droppable,t.widget("ui.progressbar",{version:"1.12.1",options:{classes:{"ui-progressbar":"ui-corner-all","ui-progressbar-value":"ui-corner-left","ui-progressbar-complete":"ui-corner-right"},max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.attr({role:"progressbar","aria-valuemin":this.min}),this._addClass("ui-progressbar","ui-widget ui-widget-content"),this.valueDiv=t("<div>").appendTo(this.element),this._addClass(this.valueDiv,"ui-progressbar-value","ui-widget-header"),this._refreshValue()},_destroy:function(){this.element.removeAttr("role aria-valuemin aria-valuemax aria-valuenow"),this.valueDiv.remove()},value:function(t){return void 0===t?this.options.value:(this.options.value=this._constrainedValue(t),this._refreshValue(),void 0)},_constrainedValue:function(t){return void 0===t&&(t=this.options.value),this.indeterminate=t===!1,"number"!=typeof t&&(t=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,t))},_setOptions:function(t){var e=t.value;delete t.value,this._super(t),this.options.value=this._constrainedValue(e),this._refreshValue()},_setOption:function(t,e){"max"===t&&(e=Math.max(this.min,e)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var e=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||e>this.min).width(i.toFixed(0)+"%"),this._toggleClass(this.valueDiv,"ui-progressbar-complete",null,e===this.options.max)._toggleClass("ui-progressbar-indeterminate",null,this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=t("<div>").appendTo(this.valueDiv),this._addClass(this.overlayDiv,"ui-progressbar-overlay"))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":e}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==e&&(this.oldValue=e,this._trigger("change")),e===this.options.max&&this._trigger("complete")}}),t.widget("ui.selectable",t.ui.mouse,{version:"1.12.1",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var e=this;this._addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){e.elementPos=t(e.element[0]).offset(),e.selectees=t(e.options.filter,e.element[0]),e._addClass(e.selectees,"ui-selectee"),e.selectees.each(function(){var i=t(this),s=i.offset(),n={left:s.left-e.elementPos.left,top:s.top-e.elementPos.top};t.data(this,"selectable-item",{element:this,$element:i,left:n.left,top:n.top,right:n.left+i.outerWidth(),bottom:n.top+i.outerHeight(),startselected:!1,selected:i.hasClass("ui-selected"),selecting:i.hasClass("ui-selecting"),unselecting:i.hasClass("ui-unselecting")})})},this.refresh(),this._mouseInit(),this.helper=t("<div>"),this._addClass(this.helper,"ui-selectable-helper")},_destroy:function(){this.selectees.removeData("selectable-item"),this._mouseDestroy()},_mouseStart:function(e){var i=this,s=this.options;this.opos=[e.pageX,e.pageY],this.elementPos=t(this.element[0]).offset(),this.options.disabled||(this.selectees=t(s.filter,this.element[0]),this._trigger("start",e),t(s.appendTo).append(this.helper),this.helper.css({left:e.pageX,top:e.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=t.data(this,"selectable-item");s.startselected=!0,e.metaKey||e.ctrlKey||(i._removeClass(s.$element,"ui-selected"),s.selected=!1,i._addClass(s.$element,"ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",e,{unselecting:s.element}))}),t(e.target).parents().addBack().each(function(){var s,n=t.data(this,"selectable-item");return n?(s=!e.metaKey&&!e.ctrlKey||!n.$element.hasClass("ui-selected"),i._removeClass(n.$element,s?"ui-unselecting":"ui-selected")._addClass(n.$element,s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",e,{selecting:n.element}):i._trigger("unselecting",e,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(e){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,o=this.opos[0],a=this.opos[1],r=e.pageX,h=e.pageY;return o>r&&(i=r,r=o,o=i),a>h&&(i=h,h=a,a=i),this.helper.css({left:o,top:a,width:r-o,height:h-a}),this.selectees.each(function(){var i=t.data(this,"selectable-item"),l=!1,c={};i&&i.element!==s.element[0]&&(c.left=i.left+s.elementPos.left,c.right=i.right+s.elementPos.left,c.top=i.top+s.elementPos.top,c.bottom=i.bottom+s.elementPos.top,"touch"===n.tolerance?l=!(c.left>r||o>c.right||c.top>h||a>c.bottom):"fit"===n.tolerance&&(l=c.left>o&&r>c.right&&c.top>a&&h>c.bottom),l?(i.selected&&(s._removeClass(i.$element,"ui-selected"),i.selected=!1),i.unselecting&&(s._removeClass(i.$element,"ui-unselecting"),i.unselecting=!1),i.selecting||(s._addClass(i.$element,"ui-selecting"),i.selecting=!0,s._trigger("selecting",e,{selecting:i.element}))):(i.selecting&&((e.metaKey||e.ctrlKey)&&i.startselected?(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,s._addClass(i.$element,"ui-selected"),i.selected=!0):(s._removeClass(i.$element,"ui-selecting"),i.selecting=!1,i.startselected&&(s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",e,{unselecting:i.element}))),i.selected&&(e.metaKey||e.ctrlKey||i.startselected||(s._removeClass(i.$element,"ui-selected"),i.selected=!1,s._addClass(i.$element,"ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",e,{unselecting:i.element})))))}),!1}},_mouseStop:function(e){var i=this;return this.dragged=!1,t(".ui-unselecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",e,{unselected:s.element})}),t(".ui-selecting",this.element[0]).each(function(){var s=t.data(this,"selectable-item");i._removeClass(s.$element,"ui-selecting")._addClass(s.$element,"ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",e,{selected:s.element})}),this._trigger("stop",e),this.helper.remove(),!1}}),t.widget("ui.selectmenu",[t.ui.formResetMixin,{version:"1.12.1",defaultElement:"<select>",options:{appendTo:null,classes:{"ui-selectmenu-button-open":"ui-corner-top","ui-selectmenu-button-closed":"ui-corner-all"},disabled:null,icons:{button:"ui-icon-triangle-1-s"},position:{my:"left top",at:"left bottom",collision:"none"},width:!1,change:null,close:null,focus:null,open:null,select:null},_create:function(){var e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this._bindFormResetHandler(),this._rendered=!1,this.menuItems=t()},_drawButton:function(){var e,i=this,s=this._parseOption(this.element.find("option:selected"),this.element[0].selectedIndex);this.labels=this.element.labels().attr("for",this.ids.button),this._on(this.labels,{click:function(t){this.button.focus(),t.preventDefault()}}),this.element.hide(),this.button=t("<span>",{tabindex:this.options.disabled?-1:0,id:this.ids.button,role:"combobox","aria-expanded":"false","aria-autocomplete":"list","aria-owns":this.ids.menu,"aria-haspopup":"true",title:this.element.attr("title")}).insertAfter(this.element),this._addClass(this.button,"ui-selectmenu-button ui-selectmenu-button-closed","ui-button ui-widget"),e=t("<span>").appendTo(this.button),this._addClass(e,"ui-selectmenu-icon","ui-icon "+this.options.icons.button),this.buttonItem=this._renderButtonItem(s).appendTo(this.button),this.options.width!==!1&&this._resizeButton(),this._on(this.button,this._buttonEvents),this.button.one("focusin",function(){i._rendered||i._refreshMenu()})},_drawMenu:function(){var e=this;this.menu=t("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=t("<div>").append(this.menu),this._addClass(this.menuWrap,"ui-selectmenu-menu","ui-front"),this.menuWrap.appendTo(this._appendTo()),this.menuInstance=this.menu.menu({classes:{"ui-menu":"ui-corner-bottom"},role:"listbox",select:function(t,i){t.preventDefault(),e._setSelection(),e._select(i.item.data("ui-selectmenu-item"),t)},focus:function(t,i){var s=i.item.data("ui-selectmenu-item");null!=e.focusIndex&&s.index!==e.focusIndex&&(e._trigger("focus",t,{item:s}),e.isOpen||e._select(s,t)),e.focusIndex=s.index,e.button.attr("aria-activedescendant",e.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(this._getSelectedItem().data("ui-selectmenu-item")||{})),null===this.options.width&&this._resizeButton()},_refreshMenu:function(){var t,e=this.element.find("option");this.menu.empty(),this._parseOptions(e),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup").find(".ui-menu-item-wrapper"),this._rendered=!0,e.length&&(t=this._getSelectedItem(),this.menuInstance.focus(null,t),this._setAria(t.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(t){this.options.disabled||(this._rendered?(this._removeClass(this.menu.find(".ui-state-active"),null,"ui-state-active"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.menuItems.length&&(this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",t)))},_position:function(){this.menuWrap.position(t.extend({of:this.button},this.options.position))},close:function(t){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",t))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderButtonItem:function(e){var i=t("<span>");return this._setText(i,e.label),this._addClass(i,"ui-selectmenu-text"),i},_renderMenu:function(e,i){var s=this,n="";t.each(i,function(i,o){var a;o.optgroup!==n&&(a=t("<li>",{text:o.optgroup}),s._addClass(a,"ui-selectmenu-optgroup","ui-menu-divider"+(o.element.parent("optgroup").prop("disabled")?" ui-state-disabled":"")),a.appendTo(e),n=o.optgroup),s._renderItemData(e,o)})},_renderItemData:function(t,e){return this._renderItem(t,e).data("ui-selectmenu-item",e)},_renderItem:function(e,i){var s=t("<li>"),n=t("<div>",{title:i.element.attr("title")});return i.disabled&&this._addClass(s,null,"ui-state-disabled"),this._setText(n,i.label),s.append(n).appendTo(e)},_setText:function(t,e){e?t.text(e):t.html("&#160;")},_move:function(t,e){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex).parent("li"):(i=this.menuItems.eq(this.element[0].selectedIndex).parent("li"),n+=":not(.ui-state-disabled)"),s="first"===t||"last"===t?i["first"===t?"prevAll":"nextAll"](n).eq(-1):i[t+"All"](n).eq(0),s.length&&this.menuInstance.focus(e,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex).parent("li")},_toggle:function(t){this[this.isOpen?"close":"open"](t)},_setSelection:function(){var t;this.range&&(window.getSelection?(t=window.getSelection(),t.removeAllRanges(),t.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(e){this.isOpen&&(t(e.target).closest(".ui-selectmenu-menu, #"+t.ui.escapeSelector(this.ids.button)).length||this.close(e))}},_buttonEvents:{mousedown:function(){var t;window.getSelection?(t=window.getSelection(),t.rangeCount&&(this.range=t.getRangeAt(0))):this.range=document.selection.createRange()},click:function(t){this._setSelection(),this._toggle(t)},keydown:function(e){var i=!0;switch(e.keyCode){case t.ui.keyCode.TAB:case t.ui.keyCode.ESCAPE:this.close(e),i=!1;break;case t.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(e);break;case t.ui.keyCode.UP:e.altKey?this._toggle(e):this._move("prev",e);break;case t.ui.keyCode.DOWN:e.altKey?this._toggle(e):this._move("next",e);break;case t.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(e):this._toggle(e);break;case t.ui.keyCode.LEFT:this._move("prev",e);break;case t.ui.keyCode.RIGHT:this._move("next",e);break;case t.ui.keyCode.HOME:case t.ui.keyCode.PAGE_UP:this._move("first",e);break;case t.ui.keyCode.END:case t.ui.keyCode.PAGE_DOWN:this._move("last",e);break;default:this.menu.trigger(e),i=!1}i&&e.preventDefault()}},_selectFocusedItem:function(t){var e=this.menuItems.eq(this.focusIndex).parent("li");e.hasClass("ui-state-disabled")||this._select(e.data("ui-selectmenu-item"),t)},_select:function(t,e){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=t.index,this.buttonItem.replaceWith(this.buttonItem=this._renderButtonItem(t)),this._setAria(t),this._trigger("select",e,{item:t}),t.index!==i&&this._trigger("change",e,{item:t}),this.close(e)},_setAria:function(t){var e=this.menuItems.eq(t.index).attr("id");this.button.attr({"aria-labelledby":e,"aria-activedescendant":e}),this.menu.attr("aria-activedescendant",e)},_setOption:function(t,e){if("icons"===t){var i=this.button.find("span.ui-icon");this._removeClass(i,null,this.options.icons.button)._addClass(i,null,e.button)}this._super(t,e),"appendTo"===t&&this.menuWrap.appendTo(this._appendTo()),"width"===t&&this._resizeButton()},_setOptionDisabled:function(t){this._super(t),this.menuInstance.option("disabled",t),this.button.attr("aria-disabled",t),this._toggleClass(this.button,null,"ui-state-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_toggleAttr:function(){this.button.attr("aria-expanded",this.isOpen),this._removeClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"closed":"open"))._addClass(this.button,"ui-selectmenu-button-"+(this.isOpen?"open":"closed"))._toggleClass(this.menuWrap,"ui-selectmenu-open",null,this.isOpen),this.menu.attr("aria-hidden",!this.isOpen)},_resizeButton:function(){var t=this.options.width;return t===!1?(this.button.css("width",""),void 0):(null===t&&(t=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(t),void 0)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){var t=this._super();return t.disabled=this.element.prop("disabled"),t},_parseOptions:function(e){var i=this,s=[];e.each(function(e,n){s.push(i._parseOption(t(n),e))}),this.items=s},_parseOption:function(t,e){var i=t.parent("optgroup");return{element:t,index:e,value:t.val(),label:t.text(),optgroup:i.attr("label")||"",disabled:i.prop("disabled")||t.prop("disabled")}},_destroy:function(){this._unbindFormResetHandler(),this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.labels.attr("for",this.ids.element)}}]),t.widget("ui.slider",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"slide",options:{animate:!1,classes:{"ui-slider":"ui-corner-all","ui-slider-handle":"ui-corner-all","ui-slider-range":"ui-corner-all ui-widget-header"},distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this._calculateNewMax(),this._addClass("ui-slider ui-slider-"+this.orientation,"ui-widget ui-widget-content"),this._refresh(),this._animateOff=!1 },_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle"),o="<span tabindex='0'></span>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,this._addClass(o,null,"ui-state-active"),o.trigger("focus"),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n,o=this.value(),a=this.values();this._hasMultipleValues()&&(n=this.values(e?0:1),o=this.values(e),2===this.options.values.length&&this.options.range===!0&&(i=0===e?Math.min(n,i):Math.max(n,i)),a[e]=i),i!==o&&(s=this._trigger("slide",t,this._uiHash(e,i,a)),s!==!1&&(this._hasMultipleValues()?this.values(e,i):this.value(i)))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this._hasMultipleValues()?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),t.isArray(this.options.values)&&(n=this.options.values.length),this._super(e,i),e){case"orientation":this._detectOrientation(),this._removeClass("ui-slider-horizontal ui-slider-vertical")._addClass("ui-slider-"+this.orientation),this._refreshValue(),this.options.range&&this._refreshRange(i),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=n-1;s>=0;s--)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_setOptionDisabled:function(t){this._super(t),this._toggleClass(null,"ui-state-disabled",!!t)},_value:function(){var t=this.options.value;return t=this._trimAlignValue(t)},_values:function(t){var e,i,s;if(arguments.length)return e=this.options.values[t],e=this._trimAlignValue(e);if(this._hasMultipleValues()){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(t){if(this._valueMin()>=t)return this._valueMin();if(t>=this._valueMax())return this._valueMax();var e=this.options.step>0?this.options.step:1,i=(t-this._valueMin())%e,s=t-i;return 2*Math.abs(i)>=e&&(s+=i>0?e:-e),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var t=this.options.max,e=this._valueMin(),i=this.options.step,s=Math.round((t-e)/i)*i;t=s+e,t>this.options.max&&(t-=i),this.max=parseFloat(t.toFixed(this._precision()))},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshRange:function(t){"vertical"===t&&this.range.css({width:"",left:""}),"horizontal"===t&&this.range.css({height:"",bottom:""})},_refreshValue:function(){var e,i,s,n,o,a=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,c={};this._hasMultipleValues()?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),c["horizontal"===h.orientation?"left":"bottom"]=i+"%",t(this).stop(1,1)[l?"animate":"css"](c,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-e+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-e+"%"},{queue:!1,duration:r.animate}))),e=i}):(s=this.value(),n=this._valueMin(),o=this._valueMax(),i=o!==n?100*((s-n)/(o-n)):0,c["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](c,r.animate),"min"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===a&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:100-i+"%"},r.animate),"min"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===a&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:100-i+"%"},r.animate))},_handleEvents:{keydown:function(e){var i,s,n,o,a=t(e.target).data("ui-slider-handle-index");switch(e.keyCode){case t.ui.keyCode.HOME:case t.ui.keyCode.END:case t.ui.keyCode.PAGE_UP:case t.ui.keyCode.PAGE_DOWN:case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(e.preventDefault(),!this._keySliding&&(this._keySliding=!0,this._addClass(t(e.target),null,"ui-state-active"),i=this._start(e,a),i===!1))return}switch(o=this.options.step,s=n=this._hasMultipleValues()?this.values(a):this.value(),e.keyCode){case t.ui.keyCode.HOME:n=this._valueMin();break;case t.ui.keyCode.END:n=this._valueMax();break;case t.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case t.ui.keyCode.UP:case t.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+o);break;case t.ui.keyCode.DOWN:case t.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-o)}this._slide(e,a,n)},keyup:function(e){var i=t(e.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(e,i),this._change(e,i),this._removeClass(t(e.target),null,"ui-state-active"))}}}),t.widget("ui.sortable",t.ui.mouse,{version:"1.12.1",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return t>=e&&e+i>t},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var e=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),t.each(this.items,function(){e._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):void 0}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("<style>*{ cursor: "+a.cursor+" !important; }</style>").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<a.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+a.scrollSpeed:e.pageY-this.overflowOffset.top<a.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-a.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<a.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+a.scrollSpeed:e.pageX-this.overflowOffset.left<a.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-a.scrollSpeed)):(e.pageY-this.document.scrollTop()<a.scrollSensitivity?r=this.document.scrollTop(this.document.scrollTop()-a.scrollSpeed):this.window.height()-(e.pageY-this.document.scrollTop())<a.scrollSensitivity&&(r=this.document.scrollTop(this.document.scrollTop()+a.scrollSpeed)),e.pageX-this.document.scrollLeft()<a.scrollSensitivity?r=this.document.scrollLeft(this.document.scrollLeft()-a.scrollSpeed):this.window.width()-(e.pageX-this.document.scrollLeft())<a.scrollSensitivity&&(r=this.document.scrollLeft(this.document.scrollLeft()+a.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp(new t.Event("mouseup",{target:null})),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+l>r&&h>s+l,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var e,i,s="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),n="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),o=s&&n;return o?(e=this._getDragVerticalDirection(),i=this._getDragHorizontalDirection(),this.floating?"right"===i||"down"===e?2:1:e&&("down"===e?2:1)):!1},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,o,a,r=[],h=[],l=this._connectWith();if(l&&e)for(s=l.length-1;s>=0;s--)for(o=t(l[s],this.document[0]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&h.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(h.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i],this.document[0]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",a),c.push({item:h,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]);return e._addClass(n,"ui-sortable-placeholder",i||e.currentItem[0].className)._removeClass(n,"ui-sortable-helper"),"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("<tr>",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t("<td>&#160;</td>",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,o,a,r,h,l,c,u,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0);if(d)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,o=null,c=d.floating||this._isFloating(this.currentItem),a=c?"left":"top",r=c?"width":"height",u=c?"pageX":"pageY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[a],l=!1,e[u]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(e[u]-h)&&(n=Math.abs(e[u]-h),o=this.items[s],this.direction=l?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;o?this._rearrange(e,o,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(o=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(a=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter; this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.spinner",{version:"1.12.1",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var e=this.element[0]===t.ui.safeActiveElement(this.document[0]);e||(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===t.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinner.children("a").attr("tabIndex",-1).attr("aria-hidden",!0).button({classes:{"ui-button":""}}),this._removeClass(this.buttons,"ui-corner-all"),this._addClass(this.buttons.first(),"ui-spinner-button ui-spinner-up"),this._addClass(this.buttons.last(),"ui-spinner-button ui-spinner-down"),this.buttons.first().button({icon:this.options.icons.up,showLabel:!1}),this.buttons.last().button({icon:this.options.icons.down,showLabel:!1}),this.buttons.height()>Math.ceil(.5*this.uiSpinner.height())&&this.uiSpinner.height()>0&&this.uiSpinner.height(this.uiSpinner.height())},_keydown:function(e){var i=this.options,s=t.ui.keyCode;switch(e.keyCode){case s.UP:return this._repeat(null,1,e),!0;case s.DOWN:return this._repeat(null,-1,e),!0;case s.PAGE_UP:return this._repeat(null,i.page,e),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,e),!0}return!1},_start:function(t){return this.spinning||this._trigger("start",t)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(t,e,i){t=t||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,e,i)},t),this._spin(e*this.options.step,i)},_spin:function(t,e){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+t*this._increment(this.counter)),this.spinning&&this._trigger("spin",e,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(e){var i=this.options.incremental;return i?t.isFunction(i)?i(e):Math.floor(e*e*e/5e4-e*e/500+17*e/200+1):1},_precision:function(){var t=this._precisionOf(this.options.step);return null!==this.options.min&&(t=Math.max(t,this._precisionOf(this.options.min))),t},_precisionOf:function(t){var e=""+t,i=e.indexOf(".");return-1===i?0:e.length-i-1},_adjustValue:function(t){var e,i,s=this.options;return e=null!==s.min?s.min:0,i=t-e,i=Math.round(i/s.step)*s.step,t=e+i,t=parseFloat(t.toFixed(this._precision())),null!==s.max&&t>s.max?s.max:null!==s.min&&s.min>t?s.min:t},_stop:function(t){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",t))},_setOption:function(t,e){var i,s,n;return"culture"===t||"numberFormat"===t?(i=this._parse(this.element.val()),this.options[t]=e,this.element.val(this._format(i)),void 0):(("max"===t||"min"===t||"step"===t)&&"string"==typeof e&&(e=this._parse(e)),"icons"===t&&(s=this.buttons.first().find(".ui-icon"),this._removeClass(s,null,this.options.icons.up),this._addClass(s,null,e.up),n=this.buttons.last().find(".ui-icon"),this._removeClass(n,null,this.options.icons.down),this._addClass(n,null,e.down)),this._super(t,e),void 0)},_setOptionDisabled:function(t){this._super(t),this._toggleClass(this.uiSpinner,null,"ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable")},_setOptions:r(function(t){this._super(t)}),_parse:function(t){return"string"==typeof t&&""!==t&&(t=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(t,10,this.options.culture):+t),""===t||isNaN(t)?null:t},_format:function(t){return""===t?"":window.Globalize&&this.options.numberFormat?Globalize.format(t,this.options.numberFormat,this.options.culture):t},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var t=this.value();return null===t?!1:t===this._adjustValue(t)},_value:function(t,e){var i;""!==t&&(i=this._parse(t),null!==i&&(e||(i=this._adjustValue(i)),t=this._format(i))),this.element.val(t),this._refresh()},_destroy:function(){this.element.prop("disabled",!1).removeAttr("autocomplete role aria-valuemin aria-valuemax aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:r(function(t){this._stepUp(t)}),_stepUp:function(t){this._start()&&(this._spin((t||1)*this.options.step),this._stop())},stepDown:r(function(t){this._stepDown(t)}),_stepDown:function(t){this._start()&&(this._spin((t||1)*-this.options.step),this._stop())},pageUp:r(function(t){this._stepUp((t||1)*this.options.page)}),pageDown:r(function(t){this._stepDown((t||1)*this.options.page)}),value:function(t){return arguments.length?(r(this._value).call(this,t),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),t.uiBackCompat!==!1&&t.widget("ui.spinner",t.ui.spinner,{_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml())},_uiSpinnerHtml:function(){return"<span>"},_buttonHtml:function(){return"<a></a><a></a>"}}),t.ui.spinner,t.widget("ui.tabs",{version:"1.12.1",delay:300,options:{active:null,classes:{"ui-tabs":"ui-corner-all","ui-tabs-nav":"ui-corner-all","ui-tabs-panel":"ui-corner-bottom","ui-tabs-tab":"ui-corner-top"},collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(){var t=/#.*$/;return function(e){var i,s;i=e.href.replace(t,""),s=location.href.replace(t,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return e.hash.length>1&&i===s}}(),_create:function(){var e=this,i=this.options;this.running=!1,this._addClass("ui-tabs","ui-widget ui-widget-content"),this._toggleClass("ui-tabs-collapsible",null,i.collapsible),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var e=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===e&&(s&&this.tabs.each(function(i,n){return t(n).attr("aria-controls")===s?(e=i,!1):void 0}),null===e&&(e=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===e||-1===e)&&(e=this.tabs.length?0:!1)),e!==!1&&(e=this.tabs.index(this.tabs.eq(e)),-1===e&&(e=i?!1:0)),!i&&e===!1&&this.anchors.length&&(e=0),e},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(e){var i=t(t.ui.safeActiveElement(this.document[0])).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(e)){switch(e.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:s++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:n=!1,s--;break;case t.ui.keyCode.END:s=this.anchors.length-1;break;case t.ui.keyCode.HOME:s=0;break;case t.ui.keyCode.SPACE:return e.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case t.ui.keyCode.ENTER:return e.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}e.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),e.ctrlKey||e.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.trigger("focus"))},_handlePageNav:function(e){return e.altKey&&e.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):e.altKey&&e.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).trigger("focus"),t},_setOption:function(t,e){return"active"===t?(this._activate(e),void 0):(this._super(t,e),"collapsible"===t&&(this._toggleClass("ui-tabs-collapsible",null,e),e||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(e),"heightStyle"===t&&this._setupHeightStyle(e),void 0)},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setOptionDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-hidden":"true"}),this.active.length?(this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}),this._addClass(this.active,"ui-tabs-active","ui-state-active"),this._getPanelForTab(this.active).show().attr({"aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this,i=this.tabs,s=this.anchors,n=this.panels;this.tablist=this._getList().attr("role","tablist"),this._addClass(this.tablist,"ui-tabs-nav","ui-helper-reset ui-helper-clearfix ui-widget-header"),this.tablist.on("mousedown"+this.eventNamespace,"> li",function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).on("focus"+this.eventNamespace,".ui-tabs-anchor",function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this.tabs=this.tablist.find("> li:has(a[href])").attr({role:"tab",tabIndex:-1}),this._addClass(this.tabs,"ui-tabs-tab","ui-state-default"),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).attr({role:"presentation",tabIndex:-1}),this._addClass(this.anchors,"ui-tabs-anchor"),this.panels=t(),this.anchors.each(function(i,s){var n,o,a,r=t(s).uniqueId().attr("id"),h=t(s).closest("li"),l=h.attr("aria-controls");e._isLocal(s)?(n=s.hash,a=n.substring(1),o=e.element.find(e._sanitizeSelector(n))):(a=h.attr("aria-controls")||t({}).uniqueId()[0].id,n="#"+a,o=e.element.find(n),o.length||(o=e._createPanel(a),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":a,"aria-labelledby":r}),o.attr("aria-labelledby",r)}),this.panels.attr("role","tabpanel"),this._addClass(this.panels,"ui-tabs-panel","ui-widget-content"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol, ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).data("ui-tabs-destroy",!0)},_setOptionDisabled:function(e){var i,s,n;for(t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1),n=0;s=this.tabs[n];n++)i=t(s),e===!0||-1!==t.inArray(n,e)?(i.attr("aria-disabled","true"),this._addClass(i,null,"ui-state-disabled")):(i.removeAttr("aria-disabled"),this._removeClass(i,null,"ui-state-disabled"));this.options.disabled=e,this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,e===!0)},_setupEvents:function(e){var i={};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(t){t.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),o=n.closest("li"),a=o[0]===s[0],r=a&&i.collapsible,h=r?t():this._getPanelForTab(o),l=s.length?this._getPanelForTab(s):t(),c={oldTab:s,oldPanel:l,newTab:r?t():o,newPanel:h};e.preventDefault(),o.hasClass("ui-state-disabled")||o.hasClass("ui-tabs-loading")||this.running||a&&!i.collapsible||this._trigger("beforeActivate",e,c)===!1||(i.active=r?!1:this.tabs.index(o),this.active=a?t():o,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(o),e),this._toggle(e,c))},_toggle:function(e,i){function s(){o.running=!1,o._trigger("activate",e,i)}function n(){o._addClass(i.newTab.closest("li"),"ui-tabs-active","ui-state-active"),a.length&&o.options.show?o._show(a,o.options.show,s):(a.show(),s())}var o=this,a=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){o._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),n()}):(this._removeClass(i.oldTab.closest("li"),"ui-tabs-active","ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),a.length&&r.length?i.oldTab.attr("tabIndex",-1):a.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),a.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+t.ui.escapeSelector(e)+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.tablist.removeAttr("role").off(this.eventNamespace),this.anchors.removeAttr("role tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeAttr("role tabIndex aria-live aria-busy aria-selected aria-labelledby aria-hidden aria-expanded")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(e){var i=this.options.disabled;i!==!1&&(void 0===e?i=!1:(e=this._getIndex(e),i=t.isArray(i)?t.map(i,function(t){return t!==e?t:null}):t.map(this.tabs,function(t,i){return i!==e?i:null})),this._setOptionDisabled(i))},disable:function(e){var i=this.options.disabled;if(i!==!0){if(void 0===e)i=!0;else{if(e=this._getIndex(e),-1!==t.inArray(e,i))return;i=t.isArray(i)?t.merge([e],i).sort():[e]}this._setOptionDisabled(i)}},load:function(e,i){e=this._getIndex(e);var s=this,n=this.tabs.eq(e),o=n.find(".ui-tabs-anchor"),a=this._getPanelForTab(n),r={tab:n,panel:a},h=function(t,e){"abort"===e&&s.panels.stop(!1,!0),s._removeClass(n,"ui-tabs-loading"),a.removeAttr("aria-busy"),t===s.xhr&&delete s.xhr};this._isLocal(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(this._addClass(n,"ui-tabs-loading"),a.attr("aria-busy","true"),this.xhr.done(function(t,e,n){setTimeout(function(){a.html(t),s._trigger("load",i,r),h(n,e)},1)}).fail(function(t,e){setTimeout(function(){h(t,e)},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href").replace(/#.*$/,""),beforeSend:function(e,o){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:o},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}}),t.uiBackCompat!==!1&&t.widget("ui.tabs",t.ui.tabs,{_processTabs:function(){this._superApply(arguments),this._addClass(this.tabs,"ui-tab")}}),t.ui.tabs,t.widget("ui.tooltip",{version:"1.12.1",options:{classes:{"ui-tooltip":"ui-corner-all ui-widget-shadow"},content:function(){var e=t(this).attr("title")||"";return t("<a>").text(e).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,track:!1,close:null,open:null},_addDescribedBy:function(e,i){var s=(e.attr("aria-describedby")||"").split(/\s+/);s.push(i),e.data("ui-tooltip-id",i).attr("aria-describedby",t.trim(s.join(" ")))},_removeDescribedBy:function(e){var i=e.data("ui-tooltip-id"),s=(e.attr("aria-describedby")||"").split(/\s+/),n=t.inArray(i,s);-1!==n&&s.splice(n,1),e.removeData("ui-tooltip-id"),s=t.trim(s.join(" ")),s?e.attr("aria-describedby",s):e.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.liveRegion=t("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this.disabledTitles=t([])},_setOption:function(e,i){var s=this;this._super(e,i),"content"===e&&t.each(this.tooltips,function(t,e){s._updateContent(e.element)})},_setOptionDisabled:function(t){this[t?"_disable":"_enable"]()},_disable:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur");n.target=n.currentTarget=s.element[0],e.close(n,!0)}),this.disabledTitles=this.disabledTitles.add(this.element.find(this.options.items).addBack().filter(function(){var e=t(this);return e.is("[title]")?e.data("ui-tooltip-title",e.attr("title")).removeAttr("title"):void 0}))},_enable:function(){this.disabledTitles.each(function(){var e=t(this);e.data("ui-tooltip-title")&&e.attr("title",e.data("ui-tooltip-title"))}),this.disabledTitles=t([])},open:function(e){var i=this,s=t(e?e.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),e&&"mouseover"===e.type&&s.parents().each(function(){var e,s=t(this);s.data("ui-tooltip-open")&&(e=t.Event("blur"),e.target=e.currentTarget=this,i.close(e,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._registerCloseHandlers(e,s),this._updateContent(s,e))},_updateContent:function(t,e){var i,s=this.options.content,n=this,o=e?e.type:null;return"string"==typeof s||s.nodeType||s.jquery?this._open(e,t,s):(i=s.call(t[0],function(i){n._delay(function(){t.data("ui-tooltip-open")&&(e&&(e.type=o),this._open(e,t,i))})}),i&&this._open(e,t,i),void 0)},_open:function(e,i,s){function n(t){l.of=t,a.is(":hidden")||a.position(l)}var o,a,r,h,l=t.extend({},this.options.position);if(s){if(o=this._find(i))return o.tooltip.find(".ui-tooltip-content").html(s),void 0;i.is("[title]")&&(e&&"mouseover"===e.type?i.attr("title",""):i.removeAttr("title")),o=this._tooltip(i),a=o.tooltip,this._addDescribedBy(i,a.attr("id")),a.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),h=t("<div>").html(a.find(".ui-tooltip-content").html()),h.removeAttr("name").find("[name]").removeAttr("name"),h.removeAttr("id").find("[id]").removeAttr("id"),h.appendTo(this.liveRegion),this.options.track&&e&&/^mouse/.test(e.type)?(this._on(this.document,{mousemove:n}),n(e)):a.position(t.extend({of:i},this.options.position)),a.hide(),this._show(a,this.options.show),this.options.track&&this.options.show&&this.options.show.delay&&(r=this.delayedShow=setInterval(function(){a.is(":visible")&&(n(l.of),clearInterval(r))},t.fx.interval)),this._trigger("open",e,{tooltip:a})}},_registerCloseHandlers:function(e,i){var s={keyup:function(e){if(e.keyCode===t.ui.keyCode.ESCAPE){var s=t.Event(e);s.currentTarget=i[0],this.close(s,!0)}}};i[0]!==this.element[0]&&(s.remove=function(){this._removeTooltip(this._find(i).tooltip)}),e&&"mouseover"!==e.type||(s.mouseleave="close"),e&&"focusin"!==e.type||(s.focusout="close"),this._on(!0,i,s)},close:function(e){var i,s=this,n=t(e?e.currentTarget:this.element),o=this._find(n);return o?(i=o.tooltip,o.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),o.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(t(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),e&&"mouseleave"===e.type&&t.each(this.parents,function(e,i){t(i.element).attr("title",i.title),delete s.parents[e]}),o.closing=!0,this._trigger("close",e,{tooltip:i}),o.hiding||(o.closing=!1)),void 0):(n.removeData("ui-tooltip-open"),void 0)},_tooltip:function(e){var i=t("<div>").attr("role","tooltip"),s=t("<div>").appendTo(i),n=i.uniqueId().attr("id");return this._addClass(s,"ui-tooltip-content"),this._addClass(i,"ui-tooltip","ui-widget ui-widget-content"),i.appendTo(this._appendTo(e)),this.tooltips[n]={element:e,tooltip:i}},_find:function(t){var e=t.data("ui-tooltip-id");return e?this.tooltips[e]:null},_removeTooltip:function(t){t.remove(),delete this.tooltips[t.attr("id")]},_appendTo:function(t){var e=t.closest(".ui-front, dialog");return e.length||(e=this.document[0].body),e},_destroy:function(){var e=this;t.each(this.tooltips,function(i,s){var n=t.Event("blur"),o=s.element;n.target=n.currentTarget=o[0],e.close(n,!0),t("#"+i).remove(),o.data("ui-tooltip-title")&&(o.attr("title")||o.attr("title",o.data("ui-tooltip-title")),o.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}}),t.uiBackCompat!==!1&&t.widget("ui.tooltip",t.ui.tooltip,{options:{tooltipClass:null},_tooltip:function(){var t=this._superApply(arguments);return this.options.tooltipClass&&t.tooltip.addClass(this.options.tooltipClass),t}}),t.ui.tooltip});
27182812/ChatGLM-LLaMA-chinese-insturct
38,967
src/transformers/modeling_flax_outputs.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 Dict, Optional, Tuple import flax import jax.numpy as jnp from .utils import ModelOutput @flax.struct.dataclass class FlaxBaseModelOutput(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`jnp.ndarray` 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(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ last_hidden_state: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxBaseModelOutputWithPast(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. past_key_values (`Dict[str, jnp.ndarray]`): Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*. hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ last_hidden_state: jnp.ndarray = None past_key_values: Optional[Dict[str, jnp.ndarray]] = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxBaseModelOutputWithPooling(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`jnp.ndarray` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. The Linear layer weights are trained from the next sentence prediction (classification) objective during pretraining. hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ last_hidden_state: jnp.ndarray = None pooler_output: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxBaseModelOutputWithPoolingAndCrossAttentions(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. pooler_output (`jnp.ndarray` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) after further processing through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns the classification token after processing through a linear layer and a tanh activation function. The linear layer weights are trained from the next sentence prediction (classification) objective during pretraining. hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if `config.is_encoder_decoder=True` 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 optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. """ last_hidden_state: jnp.ndarray = None pooler_output: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxBaseModelOutputWithPastAndCrossAttentions(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`jnp.ndarray` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer 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 (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(jnp.ndarray)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if `config.is_encoder_decoder=True` 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 optionally if `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ last_hidden_state: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxSeq2SeqModelOutput(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 (`jnp.ndarray` 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 (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(jnp.ndarray)` 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. decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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 (`jnp.ndarray` 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(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ last_hidden_state: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None decoder_attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[jnp.ndarray]] = None encoder_last_hidden_state: Optional[jnp.ndarray] = None encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None encoder_attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxCausalLMOutputWithCrossAttentions(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. cross_attentions (`tuple(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Cross attentions weights after the attention softmax, used to compute the weighted average in the cross-attention heads. past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `jnp.ndarray` tuples of length `config.n_layers`, with each tuple containing the cached key, value states of the self-attention and the cross-attention layers if model is used in encoder-decoder setting. Only relevant if `config.is_decoder = True`. Contains pre-computed hidden-states (key and values in the attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. """ logits: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxMaskedLMOutput(ModelOutput): """ Base class for masked language models outputs. Args: logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None FlaxCausalLMOutput = FlaxMaskedLMOutput @flax.struct.dataclass class FlaxSeq2SeqLMOutput(ModelOutput): """ Base class for sequence-to-sequence language models outputs. Args: logits (`jnp.ndarray` 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 (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(jnp.ndarray)` 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. decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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 (`jnp.ndarray` 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(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ logits: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None decoder_attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[jnp.ndarray]] = None encoder_last_hidden_state: Optional[jnp.ndarray] = None encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None encoder_attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxNextSentencePredictorOutput(ModelOutput): """ Base class for outputs of models predicting if two sentences are consecutive or not. Args: logits (`jnp.ndarray` of shape `(batch_size, 2)`): Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxSequenceClassifierOutput(ModelOutput): """ Base class for outputs of sentence classification models. Args: logits (`jnp.ndarray` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxSeq2SeqSequenceClassifierOutput(ModelOutput): """ Base class for outputs of sequence-to-sequence sentence classification models. Args: logits (`jnp.ndarray` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(jnp.ndarray)` 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. decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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 (`jnp.ndarray` 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(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ logits: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None decoder_attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[jnp.ndarray]] = None encoder_last_hidden_state: Optional[jnp.ndarray] = None encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None encoder_attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxMultipleChoiceModelOutput(ModelOutput): """ Base class for outputs of multiple choice models. Args: logits (`jnp.ndarray` of shape `(batch_size, num_choices)`): *num_choices* is the second dimension of the input tensors. (see *input_ids* above). Classification scores (before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxTokenClassifierOutput(ModelOutput): """ Base class for outputs of token classification models. Args: logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.num_labels)`): Classification scores (before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxQuestionAnsweringModelOutput(ModelOutput): """ Base class for outputs of question answering models. Args: start_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Span-start scores (before SoftMax). end_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Span-end scores (before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ start_logits: jnp.ndarray = None end_logits: jnp.ndarray = None hidden_states: Optional[Tuple[jnp.ndarray]] = None attentions: Optional[Tuple[jnp.ndarray]] = None @flax.struct.dataclass class FlaxSeq2SeqQuestionAnsweringModelOutput(ModelOutput): """ Base class for outputs of sequence-to-sequence question answering models. Args: start_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Span-start scores (before SoftMax). end_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Span-end scores (before SoftMax). past_key_values (`tuple(tuple(jnp.ndarray))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(jnp.ndarray)` 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. decoder_hidden_states (`tuple(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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 (`jnp.ndarray` 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(jnp.ndarray)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `jnp.ndarray` (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(jnp.ndarray)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `jnp.ndarray` (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. """ start_logits: jnp.ndarray = None end_logits: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None decoder_attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[jnp.ndarray]] = None encoder_last_hidden_state: Optional[jnp.ndarray] = None encoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None encoder_attentions: Optional[Tuple[jnp.ndarray]] = None
274056675/springboot-openai-chatgpt
3,139
mng_web/src/components/third-register/main.vue
<template> <el-dialog title="账号注册" append-to-body :visible.sync="accountBox" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" width="20%"> <el-form :model="form" ref="form" label-width="80px"> <el-form-item label="租户编号"> <el-input v-model="form.tenantId" placeholder="请输入租户编号"></el-input> </el-form-item> <el-form-item label="用户姓名"> <el-input v-model="form.name" placeholder="请输入用户姓名"></el-input> </el-form-item> <el-form-item label="账号名称"> <el-input v-model="form.account" placeholder="请输入账号名称"></el-input> </el-form-item> <el-form-item label="账号密码"> <el-input v-model="form.password" placeholder="请输入账号密码"></el-input> </el-form-item> <el-form-item label="确认密码"> <el-input v-model="form.password2" placeholder="请输入确认密码"></el-input> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button type="primary" :loading="loading" @click="handleRegister">确 定</el-button> </span> </el-dialog> </template> <script> import {mapGetters} from "vuex"; import {validatenull} from "@/util/validate"; import {registerGuest} from "@/api/user"; export default { name: "thirdRegister", data() { return { form: { tenantId: '', name: '', account: '', password: '', password2: '', }, loading: false, accountBox: false, }; }, computed: { ...mapGetters(["userInfo"]), }, created() { }, mounted() { // 若未登录则弹出框进行绑定 if (validatenull(this.userInfo.userId) || this.userInfo.userId < 0) { this.form.name = this.userInfo.account; this.form.account = this.userInfo.account; this.accountBox = true; } }, methods: { handleRegister() { if (this.form.tenantId === '') { this.$message.warning("请先输入租户编号"); return; } if (this.form.account === '') { this.$message.warning("请先输入账号名称"); return; } if (this.form.password === '' || this.form.password2 === '') { this.$message.warning("请先输入密码"); return; } if (this.form.password !== this.form.password2) { this.$message.warning("两次密码输入不一致"); return; } this.loading = true; registerGuest(this.form, this.userInfo.oauthId).then(res => { this.loading = false; const data = res.data; if (data.success) { this.accountBox = false; this.$alert("注册申请已提交,请耐心等待管理员通过!", '注册提示').then(() => { this.$store.dispatch("LogOut").then(() => { this.$router.push({path: "/login"}); }); }) } else { this.$message.error(data.msg || '提交失败'); } }, error => { window.console.log(error); this.loading = false; }); }, }, }; </script>
233zzh/TitanDataOperationSystem
3,810
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/less/variables.less
@lobilist-wrapper-margin-bottom: 16px; @lobilist-wrapper-width: 360px; @lobilist-bg: #FFF; @lobilist-xxs-width : 100%; @lobilist-margin-right : 16px; @lobilist-box-shadow : 2px 2px 5px rgba(0, 0, 0, 0.1); @lobilist-header-min-height : 38px; @lobilist-header-padding-vertical : 6px; @lobilist-header-padding-horizontal : 8px; @lobilist-title-font-size : 18px; @lobilist-title-line-height : 26px; @lobilist-title-padding-left : 15px; @lobilist-title-edit-input-height : 30px; @lobilist-actions-btn-bg : rgba(0, 0, 0, 0.04); @lobilist-actions-btn-size : @lobilist-title-line-height; @lobilist-actions-finish-cancel-btn-size : @lobilist-title-edit-input-height; @lobilist-actions-finish-cancel-btn-font-size : 18px; @lobilist-actions-list-style-picker-width : 70px; @lobilist-actions-list-style-picker-item-margin : 4px; @lobilist-actions-list-style-picker-item-size : 25px; @lobilist-form-padding : 10px; @lobilist-items-padding : 10px; @lobilist-items-border-bottom : 1px solid darken(@gray-lighter, 5%); @lobilist-item-margin-bottom : 5px; @lobilist-item-padding-left : 35px; @lobilist-item-title-font-size : 16px; @lobilist-item-border-color : @gray-lighter; @lobilist-item-padding-top: 16px; @lobilist-item-padding-bottom: 4px; @lobilist-item-drag-handler-width : 5px; @lobilist-item-drag-handler-border : 2px dotted darken(@gray-lighter, 7%); @lobilist-item-check-left-offset : 7px; @lobilist-item-hover-bg : rgba(0, 0, 0, 0.02); @lobilist-item-edit-btn-color : lighten(@gray-light, 15%); @lobilist-item-edit-btn-font-size : 10px; @lobilist-item-edit-btn-size : 16px; @lobilist-footer-padding-vertical : @lobilist-header-padding-vertical; @lobilist-footer-padding-horizontal : @lobilist-header-padding-horizontal; @lobilist-default-header-bg : @gray-lighter; @lobilist-default-title-color : @gray; @lobilist-danger-header-bg : lighten(@brand-danger, 10%); @lobilist-danger-title-color : #FFF; @lobilist-success-header-bg : @brand-success; @lobilist-success-title-color : #FFF; @lobilist-warning-header-bg : @brand-warning; @lobilist-warning-title-color : #FFF; @lobilist-info-header-bg : @brand-info; @lobilist-info-title-color : #FFF; @lobilist-primary-header-bg : @brand-primary; @lobilist-primary-title-color : #FFF;
27182812/ChatGLM-LLaMA-chinese-insturct
23,845
src/transformers/trainer_callback.py
# coding=utf-8 # Copyright 2020-present 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. """ Callbacks to use with the Trainer class and customize the training loop. """ import dataclasses import json from dataclasses import dataclass from typing import Dict, List, Optional, Union import numpy as np from tqdm.auto import tqdm from .trainer_utils import IntervalStrategy, has_length from .training_args import TrainingArguments from .utils import logging logger = logging.get_logger(__name__) @dataclass class TrainerState: """ A class containing the [`Trainer`] inner state that will be saved along the model and optimizer when checkpointing and passed to the [`TrainerCallback`]. <Tip> In all this class, one step is to be understood as one update step. When using gradient accumulation, one update step may require several forward and backward passes: if you use `gradient_accumulation_steps=n`, then one update step requires going through *n* batches. </Tip> Args: epoch (`float`, *optional*): Only set during training, will represent the epoch the training is at (the decimal part being the percentage of the current epoch completed). global_step (`int`, *optional*, defaults to 0): During training, represents the number of update steps completed. max_steps (`int`, *optional*, defaults to 0): The number of update steps to do during the current training. total_flos (`float`, *optional*, defaults to 0): The total number of floating operations done by the model since the beginning of training (stored as floats to avoid overflow). log_history (`List[Dict[str, float]]`, *optional*): The list of logs done since the beginning of training. best_metric (`float`, *optional*): When tracking the best model, the value of the best metric encountered so far. best_model_checkpoint (`str`, *optional*): When tracking the best model, the value of the name of the checkpoint for the best model encountered so far. is_local_process_zero (`bool`, *optional*, defaults to `True`): Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several machines) main process. is_world_process_zero (`bool`, *optional*, defaults to `True`): Whether or not this process is the global main process (when training in a distributed fashion on several machines, this is only going to be `True` for one process). is_hyper_param_search (`bool`, *optional*, defaults to `False`): Whether we are in the process of a hyper parameter search using Trainer.hyperparameter_search. This will impact the way data will be logged in TensorBoard. """ epoch: Optional[float] = None global_step: int = 0 max_steps: int = 0 num_train_epochs: int = 0 total_flos: float = 0 log_history: List[Dict[str, float]] = None best_metric: Optional[float] = None best_model_checkpoint: Optional[str] = None is_local_process_zero: bool = True is_world_process_zero: bool = True is_hyper_param_search: bool = False trial_name: str = None trial_params: Dict[str, Union[str, float, int, bool]] = None def __post_init__(self): if self.log_history is None: self.log_history = [] def save_to_json(self, json_path: str): """Save the content of this instance in JSON format inside `json_path`.""" json_string = json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True) + "\n" with open(json_path, "w", encoding="utf-8") as f: f.write(json_string) @classmethod def load_from_json(cls, json_path: str): """Create an instance from the content of `json_path`.""" with open(json_path, "r", encoding="utf-8") as f: text = f.read() return cls(**json.loads(text)) @dataclass class TrainerControl: """ A class that handles the [`Trainer`] control flow. This class is used by the [`TrainerCallback`] to activate some switches in the training loop. Args: should_training_stop (`bool`, *optional*, defaults to `False`): Whether or not the training should be interrupted. If `True`, this variable will not be set back to `False`. The training will just stop. should_epoch_stop (`bool`, *optional*, defaults to `False`): Whether or not the current epoch should be interrupted. If `True`, this variable will be set back to `False` at the beginning of the next epoch. should_save (`bool`, *optional*, defaults to `False`): Whether or not the model should be saved at this step. If `True`, this variable will be set back to `False` at the beginning of the next step. should_evaluate (`bool`, *optional*, defaults to `False`): Whether or not the model should be evaluated at this step. If `True`, this variable will be set back to `False` at the beginning of the next step. should_log (`bool`, *optional*, defaults to `False`): Whether or not the logs should be reported at this step. If `True`, this variable will be set back to `False` at the beginning of the next step. """ should_training_stop: bool = False should_epoch_stop: bool = False should_save: bool = False should_evaluate: bool = False should_log: bool = False def _new_training(self): """Internal method that resets the variable for a new training.""" self.should_training_stop = False def _new_epoch(self): """Internal method that resets the variable for a new epoch.""" self.should_epoch_stop = False def _new_step(self): """Internal method that resets the variable for a new step.""" self.should_save = False self.should_evaluate = False self.should_log = False class TrainerCallback: """ A class for objects that will inspect the state of the training loop at some events and take some decisions. At each of those events the following arguments are available: Args: args ([`TrainingArguments`]): The training arguments used to instantiate the [`Trainer`]. state ([`TrainerState`]): The current state of the [`Trainer`]. control ([`TrainerControl`]): The object that is returned to the [`Trainer`] and can be used to make some decisions. model ([`PreTrainedModel`] or `torch.nn.Module`): The model being trained. tokenizer ([`PreTrainedTokenizer`]): The tokenizer used for encoding the data. optimizer (`torch.optim.Optimizer`): The optimizer used for the training steps. lr_scheduler (`torch.optim.lr_scheduler.LambdaLR`): The scheduler used for setting the learning rate. train_dataloader (`torch.utils.data.DataLoader`, *optional*): The current dataloader used for training. eval_dataloader (`torch.utils.data.DataLoader`, *optional*): The current dataloader used for training. metrics (`Dict[str, float]`): The metrics computed by the last evaluation phase. Those are only accessible in the event `on_evaluate`. logs (`Dict[str, float]`): The values to log. Those are only accessible in the event `on_log`. The `control` object is the only one that can be changed by the callback, in which case the event that changes it should return the modified version. The argument `args`, `state` and `control` are positionals for all events, all the others are grouped in `kwargs`. You can unpack the ones you need in the signature of the event using them. As an example, see the code of the simple [`~transformer.PrinterCallback`]. Example: ```python class PrinterCallback(TrainerCallback): def on_log(self, args, state, control, logs=None, **kwargs): _ = logs.pop("total_flos", None) if state.is_local_process_zero: print(logs) ```""" def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of the initialization of the [`Trainer`]. """ pass def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the beginning of training. """ pass def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of training. """ pass def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the beginning of an epoch. """ pass def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of an epoch. """ pass def on_step_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the beginning of a training step. If using gradient accumulation, one training step might take several inputs. """ pass def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of an substep during gradient accumulation. """ pass def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of a training step. If using gradient accumulation, one training step might take several inputs. """ pass def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after an evaluation phase. """ pass def on_predict(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics, **kwargs): """ Event called after a successful prediction. """ pass def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after a checkpoint save. """ pass def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after logging the last logs. """ pass def on_prediction_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after a prediction step. """ pass class CallbackHandler(TrainerCallback): """Internal class that just calls the list of callbacks in order.""" def __init__(self, callbacks, model, tokenizer, optimizer, lr_scheduler): self.callbacks = [] for cb in callbacks: self.add_callback(cb) self.model = model self.tokenizer = tokenizer self.optimizer = optimizer self.lr_scheduler = lr_scheduler self.train_dataloader = None self.eval_dataloader = None if not any(isinstance(cb, DefaultFlowCallback) for cb in self.callbacks): logger.warning( "The Trainer will not work properly if you don't have a `DefaultFlowCallback` in its callbacks. You\n" + "should add one before training with `trainer.add_callback(DefaultFlowCallback). The current list of" + "callbacks is\n:" + self.callback_list ) def add_callback(self, callback): cb = callback() if isinstance(callback, type) else callback cb_class = callback if isinstance(callback, type) else callback.__class__ if cb_class in [c.__class__ for c in self.callbacks]: logger.warning( f"You are adding a {cb_class} to the callbacks of this Trainer, but there is already one. The current" + "list of callbacks is\n:" + self.callback_list ) self.callbacks.append(cb) def pop_callback(self, callback): if isinstance(callback, type): for cb in self.callbacks: if isinstance(cb, callback): self.callbacks.remove(cb) return cb else: for cb in self.callbacks: if cb == callback: self.callbacks.remove(cb) return cb def remove_callback(self, callback): if isinstance(callback, type): for cb in self.callbacks: if isinstance(cb, callback): self.callbacks.remove(cb) return else: self.callbacks.remove(callback) @property def callback_list(self): return "\n".join(cb.__class__.__name__ for cb in self.callbacks) def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_init_end", args, state, control) def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_training_stop = False return self.call_event("on_train_begin", args, state, control) def on_train_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_train_end", args, state, control) def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_epoch_stop = False return self.call_event("on_epoch_begin", args, state, control) def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_epoch_end", args, state, control) def on_step_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_log = False control.should_evaluate = False control.should_save = False return self.call_event("on_step_begin", args, state, control) def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_substep_end", args, state, control) def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_step_end", args, state, control) def on_evaluate(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics): control.should_evaluate = False return self.call_event("on_evaluate", args, state, control, metrics=metrics) def on_predict(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, metrics): return self.call_event("on_predict", args, state, control, metrics=metrics) def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_save = False return self.call_event("on_save", args, state, control) def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, logs): control.should_log = False return self.call_event("on_log", args, state, control, logs=logs) def on_prediction_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_prediction_step", args, state, control) def call_event(self, event, args, state, control, **kwargs): for callback in self.callbacks: result = getattr(callback, event)( args, state, control, model=self.model, tokenizer=self.tokenizer, optimizer=self.optimizer, lr_scheduler=self.lr_scheduler, train_dataloader=self.train_dataloader, eval_dataloader=self.eval_dataloader, **kwargs, ) # A Callback can skip the return of `control` if it doesn't change it. if result is not None: control = result return control class DefaultFlowCallback(TrainerCallback): """ A [`TrainerCallback`] that handles the default flow of the training loop for logs, evaluation and checkpoints. """ def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): # Log if state.global_step == 1 and args.logging_first_step: control.should_log = True if args.logging_strategy == IntervalStrategy.STEPS and state.global_step % args.logging_steps == 0: control.should_log = True # Evaluate if ( args.evaluation_strategy == IntervalStrategy.STEPS and state.global_step % args.eval_steps == 0 and args.eval_delay <= state.global_step ): control.should_evaluate = True # Save if ( args.save_strategy == IntervalStrategy.STEPS and args.save_steps > 0 and state.global_step % args.save_steps == 0 ): control.should_save = True # End training if state.global_step >= state.max_steps: control.should_training_stop = True return control def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): # Log if args.logging_strategy == IntervalStrategy.EPOCH: control.should_log = True # Evaluate if args.evaluation_strategy == IntervalStrategy.EPOCH and args.eval_delay <= state.epoch: control.should_evaluate = True # Save if args.save_strategy == IntervalStrategy.EPOCH: control.should_save = True return control class ProgressCallback(TrainerCallback): """ A [`TrainerCallback`] that displays the progress of training or evaluation. """ def __init__(self): self.training_bar = None self.prediction_bar = None def on_train_begin(self, args, state, control, **kwargs): if state.is_local_process_zero: self.training_bar = tqdm(total=state.max_steps) self.current_step = 0 def on_step_end(self, args, state, control, **kwargs): if state.is_local_process_zero: self.training_bar.update(state.global_step - self.current_step) self.current_step = state.global_step def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs): if state.is_local_process_zero and has_length(eval_dataloader): if self.prediction_bar is None: self.prediction_bar = tqdm(total=len(eval_dataloader), leave=self.training_bar is None) self.prediction_bar.update(1) def on_evaluate(self, args, state, control, **kwargs): if state.is_local_process_zero: if self.prediction_bar is not None: self.prediction_bar.close() self.prediction_bar = None def on_predict(self, args, state, control, **kwargs): if state.is_local_process_zero: if self.prediction_bar is not None: self.prediction_bar.close() self.prediction_bar = None def on_log(self, args, state, control, logs=None, **kwargs): if state.is_local_process_zero and self.training_bar is not None: _ = logs.pop("total_flos", None) self.training_bar.write(str(logs)) def on_train_end(self, args, state, control, **kwargs): if state.is_local_process_zero: self.training_bar.close() self.training_bar = None class PrinterCallback(TrainerCallback): """ A bare [`TrainerCallback`] that just prints the logs. """ def on_log(self, args, state, control, logs=None, **kwargs): _ = logs.pop("total_flos", None) if state.is_local_process_zero: print(logs) class EarlyStoppingCallback(TrainerCallback): """ A [`TrainerCallback`] that handles early stopping. Args: early_stopping_patience (`int`): Use with `metric_for_best_model` to stop training when the specified metric worsens for `early_stopping_patience` evaluation calls. early_stopping_threshold(`float`, *optional*): Use with TrainingArguments `metric_for_best_model` and `early_stopping_patience` to denote how much the specified metric must improve to satisfy early stopping conditions. ` This callback depends on [`TrainingArguments`] argument *load_best_model_at_end* functionality to set best_metric in [`TrainerState`]. """ def __init__(self, early_stopping_patience: int = 1, early_stopping_threshold: Optional[float] = 0.0): self.early_stopping_patience = early_stopping_patience self.early_stopping_threshold = early_stopping_threshold # early_stopping_patience_counter denotes the number of times validation metrics failed to improve. self.early_stopping_patience_counter = 0 def check_metric_value(self, args, state, control, metric_value): # best_metric is set by code for load_best_model operator = np.greater if args.greater_is_better else np.less if state.best_metric is None or ( operator(metric_value, state.best_metric) and abs(metric_value - state.best_metric) > self.early_stopping_threshold ): self.early_stopping_patience_counter = 0 else: self.early_stopping_patience_counter += 1 def on_train_begin(self, args, state, control, **kwargs): assert args.load_best_model_at_end, "EarlyStoppingCallback requires load_best_model_at_end = True" assert ( args.metric_for_best_model is not None ), "EarlyStoppingCallback requires metric_for_best_model is defined" assert ( args.evaluation_strategy != IntervalStrategy.NO ), "EarlyStoppingCallback requires IntervalStrategy of steps or epoch" def on_evaluate(self, args, state, control, metrics, **kwargs): metric_to_check = args.metric_for_best_model if not metric_to_check.startswith("eval_"): metric_to_check = f"eval_{metric_to_check}" metric_value = metrics.get(metric_to_check) if metric_value is None: logger.warning( f"early stopping required metric_for_best_model, but did not find {metric_to_check} so early stopping" " is disabled" ) return self.check_metric_value(args, state, control, metric_value) if self.early_stopping_patience_counter >= self.early_stopping_patience: control.should_training_stop = True
274056675/springboot-openai-chatgpt
1,713
mng_web/src/page/index/logo.vue
<template> <div class="avue-logo"> <transition name="fade"> <span v-if="keyCollapse" class="avue-logo_subtitle" key="0"> <img src="img/bg/img-logo.png" width="30" /> </span> </transition> <transition-group name="fade"> <template v-if="!keyCollapse"> <span class="avue-logo_title" key="1"> <div> <img src="img/bg/img-logo.png" width="30" alt="">{{website.indexTitle}}</div> </span> </template> </transition-group> </div> </template> <script> import { mapGetters } from "vuex"; export default { name: "logo", data() { return {}; }, created() {}, computed: { ...mapGetters(["website", "keyCollapse"]) }, methods: {} }; </script> <style lang="scss"> .fade-leave-active { transition: opacity 0.2s; } .fade-enter-active { transition: opacity 2.5s; } .fade-enter, .fade-leave-to { opacity: 0; } .avue-logo { position: fixed; top: 0; left: 0; width: 240px; height: 64px; line-height: 64px; background-color: #20222a; font-size: 20px; overflow: hidden; box-sizing: border-box; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15); color: rgba(255, 255, 255, 0.8); z-index: 1024; &_title { display: block; text-align: center; font-weight: 300; font-size: 16px; div { display: flex; align-items: center; justify-content: center; width: 100%; img { margin-right: 5px; } } } &_subtitle { padding-top: 10px; display: block; text-align: center; font-size: 18px; font-weight: bold; color: #fff; } } </style>
233zzh/TitanDataOperationSystem
9,147
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/less/lobilist.less
@import "../../bower_components/bootstrap/less/variables.less"; @import "../../bower_components/bootstrap/less/mixins.less"; @import "variables"; @import "mixins"; .lobilists { .lobilist-wrapper { display: inline-block; float: left; border: 1px solid transparent; margin-bottom: @lobilist-wrapper-margin-bottom; width: @lobilist-wrapper-width; margin-right: @lobilist-margin-right; } .lobilist{ max-height: 100%; overflow: auto; background-color: @lobilist-bg; .box-shadow(@lobilist-box-shadow); &:last-child { margin-right: 0; } &.ui-sortable-helper { .rotate(2deg); } &:hover { .lobilist-actions { opacity: 1; } } &.lobilist-default { .lobilist-variant(@lobilist-default-header-bg, @lobilist-default-title-color); } &.lobilist-danger { .lobilist-variant(@lobilist-danger-header-bg, @lobilist-danger-title-color); } &.lobilist-success { .lobilist-variant(@lobilist-success-header-bg, @lobilist-success-title-color); } &.lobilist-warning { .lobilist-variant(@lobilist-warning-header-bg, @lobilist-warning-title-color); } &.lobilist-info { .lobilist-variant(@lobilist-info-header-bg, @lobilist-info-title-color); } &.lobilist-primary { .lobilist-variant(@lobilist-primary-header-bg, @lobilist-primary-title-color); } } .btn-finish-title-editing, .btn-cancel-title-editing { display: none; } .lobilist-header { position: relative; min-height: @lobilist-header-min-height; padding: @lobilist-header-padding-vertical @lobilist-header-padding-horizontal; input { background-color: transparent; height: @lobilist-title-edit-input-height; } &.title-editing { .lobilist-actions { opacity: 1; .btn { display: none; } .btn-finish-title-editing, .btn-cancel-title-editing { display: inline-block; font-size: @lobilist-actions-finish-cancel-btn-font-size; line-height: @lobilist-actions-finish-cancel-btn-size; .square(@lobilist-actions-finish-cancel-btn-size); } } } .clearfix(); } .lobilist-actions { position: absolute; top: @lobilist-header-padding-vertical; right: @lobilist-header-padding-horizontal; opacity: 0; > .dropdown { display: inline-block; } .dropdown-menu { height: 70px; width: 100px; box-sizing: content-box; min-width: 0; padding: 0; margin: 0; .lobilist-default, .lobilist-danger, .lobilist-success, .lobilist-warning, .lobilist-info, .lobilist-primary { display: inline-block; cursor: pointer; margin: @lobilist-actions-list-style-picker-item-margin; .square(@lobilist-actions-list-style-picker-item-size); } .lobilist-default { background-color: @lobilist-default-header-bg; &:hover { background-color: darken(@lobilist-default-header-bg, 5%); } } .lobilist-danger { background-color: @lobilist-danger-header-bg; &:hover { background-color: darken(@lobilist-danger-header-bg, 5%); } } .lobilist-success { background-color: @lobilist-success-header-bg; &:hover { background-color: darken(@lobilist-success-header-bg, 5%); } } .lobilist-warning { background-color: @lobilist-warning-header-bg; &:hover { background-color: darken(@lobilist-warning-header-bg, 5%); } } .lobilist-info { background-color: @lobilist-info-header-bg; &:hover { background-color: darken(@lobilist-info-header-bg, 5%); } } .lobilist-primary { background-color: @lobilist-primary-header-bg; &:hover { background-color: darken(@lobilist-primary-header-bg, 5%); } } } .btn.btn-default { background-color: transparent; border-color: transparent; .square(@lobilist-actions-btn-size); &:hover { background-color: @lobilist-actions-btn-bg; } } } .lobilist-title { padding-left: @lobilist-title-padding-left; font-size: @lobilist-title-font-size; } .lobilist-items { list-style: none; margin-bottom: 0; padding: @lobilist-items-padding; } .lobilist-item { border: 1px solid transparent; margin-bottom: @lobilist-item-margin-bottom; padding-top: @lobilist-item-padding-top; padding-bottom: @lobilist-item-padding-bottom; padding-left: @lobilist-item-padding-left; border-bottom: 1px solid @lobilist-item-border-color; .transition(background-color 0.2s); .drag-handler { position: absolute; left: 0; top: 0; bottom: 0; width: @lobilist-item-drag-handler-width; border-left: @lobilist-item-drag-handler-border; border-right: @lobilist-item-drag-handler-border; &:hover { cursor: move; } } .todo-actions { position: absolute; top: 2px; right: 4px; text-align: center; white-space: nowrap; font-size: @lobilist-item-edit-btn-font-size; color: @lobilist-item-edit-btn-color; line-height: @lobilist-item-edit-btn-size; } .todo-action { display: inline-block; .square(@lobilist-item-edit-btn-size); &:hover { cursor: pointer; color: darken(@lobilist-item-edit-btn-color, 25%); } } &:hover { background-color: @lobilist-item-hover-bg; } } .lobilist-item-title { font-weight: 600; font-size: @lobilist-item-title-font-size; } .lobilist-item-description { font-style: italic; } .lobilist-item-duedate { position: absolute; top: 2px; left: @lobilist-item-drag-handler-width + @lobilist-item-check-left-offset; font-style: italic; color: @gray-light; font-size: 85%; } .lobilist-check { position: absolute; left: @lobilist-item-drag-handler-width + @lobilist-item-check-left-offset; top: @lobilist-item-padding-top; &.lobicheck { margin-top: 3px; } } .lobilist-item { position: relative; &.item-done { text-decoration: line-through; } } .btn-show-form { outline: 0; } .lobilist-footer, .lobilist-form-footer { padding: @lobilist-footer-padding-vertical @lobilist-footer-padding-horizontal; } .lobilist-form-footer { margin-left: -@lobilist-form-padding; margin-right: -@lobilist-form-padding; margin-bottom: -@lobilist-form-padding; } .lobilist-add-todo-form { padding: @lobilist-form-padding; .form-group { margin-bottom: 5px; } .btn-add-todo { margin-right: 5px; } .btn-add-todo, .btn-discard-todo { height: 30px; } } .lobilist-placeholder { &:extend(.lobilists .lobilist-wrapper); background-color: #f9f5d1; border: 1px dashed @gray-light; } .lobilist-item-placeholder { &:extend(.lobilists .lobilist-item); background-color: rgba(0, 0, 0, 0.03); border: 1px dashed darken(@gray-lighter, 7%); } @media (max-width: @screen-xs-min) { .lobilist { width: @lobilist-xxs-width; } } &.single-line { overflow-x: auto; overflow-y: hidden; white-space: nowrap; height: 400px; .lobilist-wrapper, .lobilist-placeholder { float: none; white-space: normal; vertical-align: top; height: 100%; } } &.no-sortable{ .lobilist-item{ .drag-handler{ display: none; } } } .clearfix(); }
274056675/springboot-openai-chatgpt
2,731
mng_web/src/page/index/index.vue
<template> <div class="avue-contail" :class="{'avue--collapse':isCollapse}"> <div class="avue-header"> <!-- 顶部导航栏 --> <top /> </div> <div class="avue-layout"> <div class="avue-left"> <!-- 左侧导航栏 --> <sidebar /> </div> <div class="avue-main"> <!-- 顶部标签卡 --> <tags /> <!-- 主体视图层 --> <el-scrollbar style="height:100%"> <keep-alive> <router-view class="avue-view" :key="$route.fullPath" v-if="$route.meta.keepAlive" /> </keep-alive> <router-view class="avue-view" :key="$route.fullPath" v-if="!$route.meta.keepAlive" /> </el-scrollbar> </div> </div> <!-- <el-footer class="avue-footer"> <img src="/svg/logo.svg" alt="" class="logo"> <p class="copyright">© 2018 Avue designed by smallwei</p> </el-footer> --> <div class="avue-shade" @click="showCollapse"></div> </div> </template> <script> import { mapGetters } from "vuex"; import tags from "./tags"; import top from "./top/"; import sidebar from "./sidebar/"; import admin from "@/util/admin"; import {validatenull} from "@/util/validate"; import {calcDate} from "@/util/date.js"; import {getStore} from "@/util/store.js"; export default { components: { top, tags, sidebar }, name: "index", data() { return { //刷新token锁 refreshLock: false, //刷新token的时间 refreshTime: "" }; }, created() { //实时检测刷新token this.refreshToken(); }, mounted() { this.init(); }, computed: mapGetters(["isLock", "isCollapse", "website"]), props: [], methods: { showCollapse() { this.$store.commit("SET_COLLAPSE"); }, // 屏幕检测 init() { this.$store.commit("SET_SCREEN", admin.getScreen()); window.onresize = () => { setTimeout(() => { this.$store.commit("SET_SCREEN", admin.getScreen()); }, 0); }; }, // 定时检测一次token refreshToken() { this.refreshTime = setInterval(() => { const token = getStore({ name: "token", debug: true }) || {}; const date = calcDate(token.datetime, new Date().getTime()); if (validatenull(date)) return; if (date.seconds >= this.website.tokenTime && !this.refreshLock) { this.refreshLock = true; this.$store .dispatch("RefreshToken") .then(() => { this.refreshLock = false; }) .catch(() => { this.refreshLock = false; }); } }, 1000); } } }; </script>
274056675/springboot-openai-chatgpt
4,565
mng_web/src/page/index/tags.vue
<template> <div class="avue-tags" v-if="showTag"> <!-- tag盒子 --> <div v-if="contextmenuFlag" class="avue-tags__contentmenu" :style="{left:contentmenuX+'px',top:contentmenuY+'px'}"> <div class="item" @click="closeOthersTags">{{$t('tagsView.closeOthers')}}</div> <div class="item" @click="closeAllTags">{{$t('tagsView.closeAll')}}</div> </div> <div class="avue-tags__box" :class="{'avue-tags__box--close':!website.isFirstPage}"> <el-tabs v-model="active" type="card" @contextmenu.native="handleContextmenu" :closable="tagLen!==1" @tab-click="openTag" @edit="menuTag"> <el-tab-pane :key="item.value" v-for="item in tagList" :label="generateTitle(item)" :name="item.value"> </el-tab-pane> </el-tabs> <el-dropdown class="avue-tags__menu"> <el-button type="primary" size="mini"> {{$t('tagsView.menu')}} <i class="el-icon-arrow-down el-icon--right"></i> </el-button> <el-dropdown-menu slot="dropdown"> <el-dropdown-item @click.native="closeOthersTags">{{$t('tagsView.closeOthers')}}</el-dropdown-item> <el-dropdown-item @click.native="closeAllTags">{{$t('tagsView.closeAll')}}</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </div> </div> </template> <script> import { mapGetters, mapState } from "vuex"; export default { name: "tags", data() { return { active: "", contentmenuX: "", contentmenuY: "", contextmenuFlag: false }; }, created() {}, mounted() { this.setActive(); }, watch: { tag() { this.setActive(); }, contextmenuFlag() { window.addEventListener("mousedown", this.watchContextmenu); } }, computed: { ...mapGetters(["tagWel", "tagList", "tag", "website"]), ...mapState({ showTag: state => state.common.showTag }), tagLen() { return this.tagList.length || 0; } }, methods: { generateTitle(item) { return this.$router.$avueRouter.generateTitle( item.label, (item.meta || {}).i18n ); }, watchContextmenu(event) { if (!this.$el.contains(event.target) || event.button !== 0) { this.contextmenuFlag = false; } window.removeEventListener("mousedown", this.watchContextmenu); }, handleContextmenu(event) { let target = event.target; // 解决 https://github.com/d2-projects/d2-admin/issues/54 let flag = false; if (target.className.indexOf("el-tabs__item") > -1) flag = true; else if (target.parentNode.className.indexOf("el-tabs__item") > -1) { target = target.parentNode; flag = true; } if (flag) { event.preventDefault(); event.stopPropagation(); this.contentmenuX = event.clientX; this.contentmenuY = event.clientY; this.tagName = target.getAttribute("aria-controls").slice(5); this.contextmenuFlag = true; } }, //激活当前选项 setActive() { this.active = this.tag.value; }, menuTag(value, action) { if (action === "remove") { let { tag, key } = this.findTag(value); this.$store.commit("DEL_TAG", tag); if (tag.value === this.tag.value) { tag = this.tagList[key === 0 ? key : key - 1]; //如果关闭本标签让前推一个 this.openTag(tag); } } }, openTag(item) { let tag; if (item.name) { tag = this.findTag(item.name).tag; } else { tag = item; } this.$router.push({ path: this.$router.$avueRouter.getPath({ name: tag.label, src: tag.value, i18n: tag.meta.i18n }), query: tag.query }); }, closeOthersTags() { this.contextmenuFlag = false; this.$store.commit("DEL_TAG_OTHER"); }, findTag(value) { let tag, key; this.tagList.map((item, index) => { if (item.value === value) { tag = item; key = index; } }); return { tag: tag, key: key }; }, closeAllTags() { this.contextmenuFlag = false; this.$store.commit("DEL_ALL_TAG"); this.$router.push({ path: this.$router.$avueRouter.getPath({ src: this.tagWel.value }), query: this.tagWel.query }); } } }; </script>
27182812/ChatGLM-LLaMA-chinese-insturct
68,280
src/transformers/integrations.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. """ Integrations with other Python libraries. """ import functools import importlib.util import json import numbers import os import pickle import shutil import sys import tempfile from dataclasses import asdict from pathlib import Path from typing import TYPE_CHECKING, Dict, Optional import numpy as np from . import __version__ as version from .utils import flatten_dict, is_datasets_available, is_torch_available, logging logger = logging.get_logger(__name__) if is_torch_available(): import torch # comet_ml requires to be imported before any ML frameworks _has_comet = importlib.util.find_spec("comet_ml") is not None and os.getenv("COMET_MODE", "").upper() != "DISABLED" if _has_comet: try: import comet_ml # noqa: F401 if hasattr(comet_ml, "config") and comet_ml.config.get_config("comet.api_key"): _has_comet = True else: if os.getenv("COMET_MODE", "").upper() != "DISABLED": logger.warning("comet_ml is installed but `COMET_API_KEY` is not set.") _has_comet = False except (ImportError, ValueError): _has_comet = False _has_neptune = importlib.util.find_spec("neptune") is not None if TYPE_CHECKING and _has_neptune: from neptune.new.metadata_containers.run import Run from .trainer_callback import ProgressCallback, TrainerCallback # noqa: E402 from .trainer_utils import PREFIX_CHECKPOINT_DIR, BestRun, IntervalStrategy # noqa: E402 from .training_args import ParallelMode # noqa: E402 from .utils import ENV_VARS_TRUE_VALUES, is_torch_tpu_available # noqa: E402 # Integration functions: def is_wandb_available(): # any value of WANDB_DISABLED disables wandb if os.getenv("WANDB_DISABLED", "").upper() in ENV_VARS_TRUE_VALUES: logger.warning( "Using the `WANDB_DISABLED` environment variable is deprecated and will be removed in v5. Use the " "--report_to flag to control the integrations used for logging result (for instance --report_to none)." ) return False return importlib.util.find_spec("wandb") is not None def is_clearml_available(): return importlib.util.find_spec("clearml") is not None def is_comet_available(): return _has_comet def is_tensorboard_available(): return importlib.util.find_spec("tensorboard") is not None or importlib.util.find_spec("tensorboardX") is not None def is_optuna_available(): return importlib.util.find_spec("optuna") is not None def is_ray_available(): return importlib.util.find_spec("ray") is not None def is_ray_tune_available(): if not is_ray_available(): return False return importlib.util.find_spec("ray.tune") is not None def is_sigopt_available(): return importlib.util.find_spec("sigopt") is not None def is_azureml_available(): if importlib.util.find_spec("azureml") is None: return False if importlib.util.find_spec("azureml.core") is None: return False return importlib.util.find_spec("azureml.core.run") is not None def is_mlflow_available(): if os.getenv("DISABLE_MLFLOW_INTEGRATION", "FALSE").upper() == "TRUE": return False return importlib.util.find_spec("mlflow") is not None def is_dagshub_available(): return None not in [importlib.util.find_spec("dagshub"), importlib.util.find_spec("mlflow")] def is_fairscale_available(): return importlib.util.find_spec("fairscale") is not None def is_neptune_available(): return _has_neptune def is_codecarbon_available(): return importlib.util.find_spec("codecarbon") is not None def hp_params(trial): if is_optuna_available(): import optuna if isinstance(trial, optuna.Trial): return trial.params if is_ray_tune_available(): if isinstance(trial, dict): return trial if is_sigopt_available(): if isinstance(trial, dict): return trial if is_wandb_available(): if isinstance(trial, dict): return trial raise RuntimeError(f"Unknown type for trial {trial.__class__}") def default_hp_search_backend(): if is_optuna_available(): return "optuna" elif is_ray_tune_available(): return "ray" elif is_sigopt_available(): return "sigopt" def run_hp_search_optuna(trainer, n_trials: int, direction: str, **kwargs) -> BestRun: import optuna if trainer.args.process_index == 0: def _objective(trial, checkpoint_dir=None): checkpoint = None if checkpoint_dir: for subdir in os.listdir(checkpoint_dir): if subdir.startswith(PREFIX_CHECKPOINT_DIR): checkpoint = os.path.join(checkpoint_dir, subdir) trainer.objective = None if trainer.args.world_size > 1: if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED: raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.") trainer._hp_search_setup(trial) torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0) trainer.train(resume_from_checkpoint=checkpoint) else: trainer.train(resume_from_checkpoint=checkpoint, trial=trial) # If there hasn't been any evaluation during the training loop. if getattr(trainer, "objective", None) is None: metrics = trainer.evaluate() trainer.objective = trainer.compute_objective(metrics) return trainer.objective timeout = kwargs.pop("timeout", None) n_jobs = kwargs.pop("n_jobs", 1) study = optuna.create_study(direction=direction, **kwargs) study.optimize(_objective, n_trials=n_trials, timeout=timeout, n_jobs=n_jobs) best_trial = study.best_trial return BestRun(str(best_trial.number), best_trial.value, best_trial.params) else: for i in range(n_trials): trainer.objective = None args_main_rank = list(pickle.dumps(trainer.args)) if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED: raise RuntimeError("only support DDP optuna HPO for ParallelMode.DISTRIBUTED currently.") torch.distributed.broadcast_object_list(args_main_rank, src=0) args = pickle.loads(bytes(args_main_rank)) for key, value in asdict(args).items(): if key != "local_rank": setattr(trainer.args, key, value) trainer.train(resume_from_checkpoint=None) # If there hasn't been any evaluation during the training loop. if getattr(trainer, "objective", None) is None: metrics = trainer.evaluate() trainer.objective = trainer.compute_objective(metrics) return None def run_hp_search_ray(trainer, n_trials: int, direction: str, **kwargs) -> BestRun: import ray def _objective(trial, local_trainer, checkpoint_dir=None): try: from transformers.utils.notebook import NotebookProgressCallback if local_trainer.pop_callback(NotebookProgressCallback): local_trainer.add_callback(ProgressCallback) except ModuleNotFoundError: pass checkpoint = None if checkpoint_dir: for subdir in os.listdir(checkpoint_dir): if subdir.startswith(PREFIX_CHECKPOINT_DIR): checkpoint = os.path.join(checkpoint_dir, subdir) local_trainer.objective = None local_trainer.train(resume_from_checkpoint=checkpoint, trial=trial) # If there hasn't been any evaluation during the training loop. if getattr(local_trainer, "objective", None) is None: metrics = local_trainer.evaluate() local_trainer.objective = local_trainer.compute_objective(metrics) local_trainer._tune_save_checkpoint() ray.tune.report(objective=local_trainer.objective, **metrics, done=True) if not trainer._memory_tracker.skip_memory_metrics: from .trainer_utils import TrainerMemoryTracker logger.warning( "Memory tracking for your Trainer is currently " "enabled. Automatically disabling the memory tracker " "since the memory tracker is not serializable." ) trainer._memory_tracker = TrainerMemoryTracker(skip_memory_metrics=True) # The model and TensorBoard writer do not pickle so we have to remove them (if they exists) # while doing the ray hp search. _tb_writer = trainer.pop_callback(TensorBoardCallback) trainer.model = None # Setup default `resources_per_trial`. if "resources_per_trial" not in kwargs: # Default to 1 CPU and 1 GPU (if applicable) per trial. kwargs["resources_per_trial"] = {"cpu": 1} if trainer.args.n_gpu > 0: kwargs["resources_per_trial"]["gpu"] = 1 resource_msg = "1 CPU" + (" and 1 GPU" if trainer.args.n_gpu > 0 else "") logger.info( "No `resources_per_trial` arg was passed into " "`hyperparameter_search`. Setting it to a default value " f"of {resource_msg} for each trial." ) # Make sure each trainer only uses GPUs that were allocated per trial. gpus_per_trial = kwargs["resources_per_trial"].get("gpu", 0) trainer.args._n_gpu = gpus_per_trial # Setup default `progress_reporter`. if "progress_reporter" not in kwargs: from ray.tune import CLIReporter kwargs["progress_reporter"] = CLIReporter(metric_columns=["objective"]) if "keep_checkpoints_num" in kwargs and kwargs["keep_checkpoints_num"] > 0: # `keep_checkpoints_num=0` would disabled checkpointing trainer.use_tune_checkpoints = True if kwargs["keep_checkpoints_num"] > 1: logger.warning( f"Currently keeping {kwargs['keep_checkpoints_num']} checkpoints for each trial. " "Checkpoints are usually huge, " "consider setting `keep_checkpoints_num=1`." ) if "scheduler" in kwargs: from ray.tune.schedulers import ASHAScheduler, HyperBandForBOHB, MedianStoppingRule, PopulationBasedTraining # Check if checkpointing is enabled for PopulationBasedTraining if isinstance(kwargs["scheduler"], PopulationBasedTraining): if not trainer.use_tune_checkpoints: logger.warning( "You are using PopulationBasedTraining but you haven't enabled checkpointing. " "This means your trials will train from scratch everytime they are exploiting " "new configurations. Consider enabling checkpointing by passing " "`keep_checkpoints_num=1` as an additional argument to `Trainer.hyperparameter_search`." ) # Check for `do_eval` and `eval_during_training` for schedulers that require intermediate reporting. if isinstance( kwargs["scheduler"], (ASHAScheduler, MedianStoppingRule, HyperBandForBOHB, PopulationBasedTraining) ) and (not trainer.args.do_eval or trainer.args.evaluation_strategy == IntervalStrategy.NO): raise RuntimeError( "You are using {cls} as a scheduler but you haven't enabled evaluation during training. " "This means your trials will not report intermediate results to Ray Tune, and " "can thus not be stopped early or used to exploit other trials parameters. " "If this is what you want, do not use {cls}. If you would like to use {cls}, " "make sure you pass `do_eval=True` and `evaluation_strategy='steps'` in the " "Trainer `args`.".format(cls=type(kwargs["scheduler"]).__name__) ) trainable = ray.tune.with_parameters(_objective, local_trainer=trainer) @functools.wraps(trainable) def dynamic_modules_import_trainable(*args, **kwargs): """ Wrapper around `tune.with_parameters` to ensure datasets_modules are loaded on each Actor. Without this, an ImportError will be thrown. See https://github.com/huggingface/transformers/issues/11565. Assumes that `_objective`, defined above, is a function. """ if is_datasets_available(): import datasets.load dynamic_modules_path = os.path.join(datasets.load.init_dynamic_modules(), "__init__.py") # load dynamic_modules from path spec = importlib.util.spec_from_file_location("datasets_modules", dynamic_modules_path) datasets_modules = importlib.util.module_from_spec(spec) sys.modules[spec.name] = datasets_modules spec.loader.exec_module(datasets_modules) return trainable(*args, **kwargs) # special attr set by tune.with_parameters if hasattr(trainable, "__mixins__"): dynamic_modules_import_trainable.__mixins__ = trainable.__mixins__ analysis = ray.tune.run( dynamic_modules_import_trainable, config=trainer.hp_space(None), num_samples=n_trials, **kwargs, ) best_trial = analysis.get_best_trial(metric="objective", mode=direction[:3], scope=trainer.args.ray_scope) best_run = BestRun(best_trial.trial_id, best_trial.last_result["objective"], best_trial.config) if _tb_writer is not None: trainer.add_callback(_tb_writer) return best_run def run_hp_search_sigopt(trainer, n_trials: int, direction: str, **kwargs) -> BestRun: import sigopt from transformers.utils.versions import importlib_metadata if trainer.args.process_index == 0: if importlib_metadata.version("sigopt") >= "8.0.0": sigopt.set_project("huggingface") experiment = sigopt.create_experiment( name="huggingface-tune", type="offline", parameters=trainer.hp_space(None), metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}], parallel_bandwidth=1, budget=n_trials, ) logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}") for run in experiment.loop(): with run: trainer.objective = None if trainer.args.world_size > 1: if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED: raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.") trainer._hp_search_setup(run.run) torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0) trainer.train(resume_from_checkpoint=None) else: trainer.train(resume_from_checkpoint=None, trial=run.run) # If there hasn't been any evaluation during the training loop. if getattr(trainer, "objective", None) is None: metrics = trainer.evaluate() trainer.objective = trainer.compute_objective(metrics) run.log_metric("objective", trainer.objective) best = list(experiment.get_best_runs())[0] best_run = BestRun(best.id, best.values["objective"].value, best.assignments) else: from sigopt import Connection conn = Connection() proxies = kwargs.pop("proxies", None) if proxies is not None: conn.set_proxies(proxies) experiment = conn.experiments().create( name="huggingface-tune", parameters=trainer.hp_space(None), metrics=[{"name": "objective", "objective": direction, "strategy": "optimize"}], parallel_bandwidth=1, observation_budget=n_trials, project="huggingface", ) logger.info(f"created experiment: https://app.sigopt.com/experiment/{experiment.id}") while experiment.progress.observation_count < experiment.observation_budget: suggestion = conn.experiments(experiment.id).suggestions().create() trainer.objective = None if trainer.args.world_size > 1: if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED: raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.") trainer._hp_search_setup(suggestion) torch.distributed.broadcast_object_list(pickle.dumps(trainer.args), src=0) trainer.train(resume_from_checkpoint=None) else: trainer.train(resume_from_checkpoint=None, trial=suggestion) # If there hasn't been any evaluation during the training loop. if getattr(trainer, "objective", None) is None: metrics = trainer.evaluate() trainer.objective = trainer.compute_objective(metrics) values = [{"name": "objective", "value": trainer.objective}] obs = conn.experiments(experiment.id).observations().create(suggestion=suggestion.id, values=values) logger.info(f"[suggestion_id, observation_id]: [{suggestion.id}, {obs.id}]") experiment = conn.experiments(experiment.id).fetch() best = list(conn.experiments(experiment.id).best_assignments().fetch().iterate_pages())[0] best_run = BestRun(best.id, best.value, best.assignments) return best_run else: for i in range(n_trials): trainer.objective = None args_main_rank = list(pickle.dumps(trainer.args)) if trainer.args.parallel_mode != ParallelMode.DISTRIBUTED: raise RuntimeError("only support DDP Sigopt HPO for ParallelMode.DISTRIBUTED currently.") torch.distributed.broadcast_object_list(args_main_rank, src=0) args = pickle.loads(bytes(args_main_rank)) for key, value in asdict(args).items(): if key != "local_rank": setattr(trainer.args, key, value) trainer.train(resume_from_checkpoint=None) # If there hasn't been any evaluation during the training loop. if getattr(trainer, "objective", None) is None: metrics = trainer.evaluate() trainer.objective = trainer.compute_objective(metrics) return None def run_hp_search_wandb(trainer, n_trials: int, direction: str, **kwargs) -> BestRun: from .integrations import is_wandb_available if not is_wandb_available(): raise ImportError("This function needs wandb installed: `pip install wandb`") import wandb # add WandbCallback if not already added in trainer callbacks reporting_to_wandb = False for callback in trainer.callback_handler.callbacks: if isinstance(callback, WandbCallback): reporting_to_wandb = True break if not reporting_to_wandb: trainer.add_callback(WandbCallback()) trainer.args.report_to = "wandb" best_trial = {"run_id": None, "objective": None, "hyperparameters": None} sweep_id = kwargs.pop("sweep_id", None) project = kwargs.pop("project", None) name = kwargs.pop("name", None) entity = kwargs.pop("entity", None) metric = kwargs.pop("metric", "eval/loss") sweep_config = trainer.hp_space(None) sweep_config["metric"]["goal"] = direction sweep_config["metric"]["name"] = metric if name: sweep_config["name"] = name def _objective(): run = wandb.run if wandb.run else wandb.init() trainer.state.trial_name = run.name run.config.update({"assignments": {}, "metric": metric}) config = wandb.config trainer.objective = None trainer.train(resume_from_checkpoint=None, trial=vars(config)["_items"]) # If there hasn't been any evaluation during the training loop. if getattr(trainer, "objective", None) is None: metrics = trainer.evaluate() trainer.objective = trainer.compute_objective(metrics) format_metrics = rewrite_logs(metrics) if metric not in format_metrics: logger.warning( f"Provided metric {metric} not found. This might result in unexpected sweeps charts. The available" f" metrics are {format_metrics.keys()}" ) best_score = False if best_trial["run_id"] is not None: if direction == "minimize": best_score = trainer.objective < best_trial["objective"] elif direction == "maximize": best_score = trainer.objective > best_trial["objective"] if best_score or best_trial["run_id"] is None: best_trial["run_id"] = run.id best_trial["objective"] = trainer.objective best_trial["hyperparameters"] = dict(config) return trainer.objective sweep_id = wandb.sweep(sweep_config, project=project, entity=entity) if not sweep_id else sweep_id logger.info(f"wandb sweep id - {sweep_id}") wandb.agent(sweep_id, function=_objective, count=n_trials) return BestRun(best_trial["run_id"], best_trial["objective"], best_trial["hyperparameters"]) def get_available_reporting_integrations(): integrations = [] if is_azureml_available() and not is_mlflow_available(): integrations.append("azure_ml") if is_comet_available(): integrations.append("comet_ml") if is_dagshub_available(): integrations.append("dagshub") if is_mlflow_available(): integrations.append("mlflow") if is_neptune_available(): integrations.append("neptune") if is_tensorboard_available(): integrations.append("tensorboard") if is_wandb_available(): integrations.append("wandb") if is_codecarbon_available(): integrations.append("codecarbon") if is_clearml_available(): integrations.append("clearml") return integrations def rewrite_logs(d): new_d = {} eval_prefix = "eval_" eval_prefix_len = len(eval_prefix) test_prefix = "test_" test_prefix_len = len(test_prefix) for k, v in d.items(): if k.startswith(eval_prefix): new_d["eval/" + k[eval_prefix_len:]] = v elif k.startswith(test_prefix): new_d["test/" + k[test_prefix_len:]] = v else: new_d["train/" + k] = v return new_d class TensorBoardCallback(TrainerCallback): """ A [`TrainerCallback`] that sends the logs to [TensorBoard](https://www.tensorflow.org/tensorboard). Args: tb_writer (`SummaryWriter`, *optional*): The writer to use. Will instantiate one if not set. """ def __init__(self, tb_writer=None): has_tensorboard = is_tensorboard_available() if not has_tensorboard: raise RuntimeError( "TensorBoardCallback requires tensorboard to be installed. Either update your PyTorch version or" " install tensorboardX." ) if has_tensorboard: try: from torch.utils.tensorboard import SummaryWriter # noqa: F401 self._SummaryWriter = SummaryWriter except ImportError: try: from tensorboardX import SummaryWriter self._SummaryWriter = SummaryWriter except ImportError: self._SummaryWriter = None else: self._SummaryWriter = None self.tb_writer = tb_writer def _init_summary_writer(self, args, log_dir=None): log_dir = log_dir or args.logging_dir if self._SummaryWriter is not None: self.tb_writer = self._SummaryWriter(log_dir=log_dir) def on_train_begin(self, args, state, control, **kwargs): if not state.is_world_process_zero: return log_dir = None if state.is_hyper_param_search: trial_name = state.trial_name if trial_name is not None: log_dir = os.path.join(args.logging_dir, trial_name) if self.tb_writer is None: self._init_summary_writer(args, log_dir) if self.tb_writer is not None: self.tb_writer.add_text("args", args.to_json_string()) if "model" in kwargs: model = kwargs["model"] if hasattr(model, "config") and model.config is not None: model_config_json = model.config.to_json_string() self.tb_writer.add_text("model_config", model_config_json) # Version of TensorBoard coming from tensorboardX does not have this method. if hasattr(self.tb_writer, "add_hparams"): self.tb_writer.add_hparams(args.to_sanitized_dict(), metric_dict={}) def on_log(self, args, state, control, logs=None, **kwargs): if not state.is_world_process_zero: return if self.tb_writer is None: self._init_summary_writer(args) if self.tb_writer is not None: logs = rewrite_logs(logs) for k, v in logs.items(): if isinstance(v, (int, float)): self.tb_writer.add_scalar(k, v, state.global_step) else: logger.warning( "Trainer is attempting to log a value of " f'"{v}" of type {type(v)} for key "{k}" as a scalar. ' "This invocation of Tensorboard's writer.add_scalar() " "is incorrect so we dropped this attribute." ) self.tb_writer.flush() def on_train_end(self, args, state, control, **kwargs): if self.tb_writer: self.tb_writer.close() self.tb_writer = None class WandbCallback(TrainerCallback): """ A [`TrainerCallback`] that logs metrics, media, model checkpoints to [Weight and Biases](https://www.wandb.com/). """ def __init__(self): has_wandb = is_wandb_available() if not has_wandb: raise RuntimeError("WandbCallback requires wandb to be installed. Run `pip install wandb`.") if has_wandb: import wandb self._wandb = wandb self._initialized = False # log model if os.getenv("WANDB_LOG_MODEL", "FALSE").upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"}): DeprecationWarning( f"Setting `WANDB_LOG_MODEL` as {os.getenv('WANDB_LOG_MODEL')} is deprecated and will be removed in " "version 5 of transformers. Use one of `'end'` or `'checkpoint'` instead." ) logger.info(f"Setting `WANDB_LOG_MODEL` from {os.getenv('WANDB_LOG_MODEL')} to `end` instead") self._log_model = "end" else: self._log_model = os.getenv("WANDB_LOG_MODEL", "false").lower() def setup(self, args, state, model, **kwargs): """ Setup the optional Weights & Biases (*wandb*) integration. One can subclass and override this method to customize the setup if needed. Find more information [here](https://docs.wandb.ai/guides/integrations/huggingface). You can also override the following environment variables: Environment: - **WANDB_LOG_MODEL** (`str`, *optional*, defaults to `"false"`): Whether to log model and checkpoints during training. Can be `"end"`, `"checkpoint"` or `"false"`. If set to `"end"`, the model will be uploaded at the end of training. If set to `"checkpoint"`, the checkpoint will be uploaded every `args.save_steps` . If set to `"false"`, the model will not be uploaded. Use along with [`~transformers.TrainingArguments.load_best_model_at_end`] to upload best model. <Deprecated version="5.0"> Setting `WANDB_LOG_MODEL` as `bool` will be deprecated in version 5 of 🤗 Transformers. </Deprecated> - **WANDB_WATCH** (`str`, *optional* defaults to `"false"`): Can be `"gradients"`, `"all"`, `"parameters"`, or `"false"`. Set to `"all"` to log gradients and parameters. - **WANDB_PROJECT** (`str`, *optional*, defaults to `"huggingface"`): Set this to a custom string to store results in a different project. - **WANDB_DISABLED** (`bool`, *optional*, defaults to `False`): Whether to disable wandb entirely. Set `WANDB_DISABLED=true` to disable. """ if self._wandb is None: return self._initialized = True if state.is_world_process_zero: logger.info( 'Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"' ) combined_dict = {**args.to_sanitized_dict()} if hasattr(model, "config") and model.config is not None: model_config = model.config.to_dict() combined_dict = {**model_config, **combined_dict} trial_name = state.trial_name init_args = {} if trial_name is not None: init_args["name"] = trial_name init_args["group"] = args.run_name else: if not (args.run_name is None or args.run_name == args.output_dir): init_args["name"] = args.run_name if self._wandb.run is None: self._wandb.init( project=os.getenv("WANDB_PROJECT", "huggingface"), **init_args, ) # add config parameters (run may have been created manually) self._wandb.config.update(combined_dict, allow_val_change=True) # define default x-axis (for latest wandb versions) if getattr(self._wandb, "define_metric", None): self._wandb.define_metric("train/global_step") self._wandb.define_metric("*", step_metric="train/global_step", step_sync=True) # keep track of model topology and gradients, unsupported on TPU _watch_model = os.getenv("WANDB_WATCH", "false") if not is_torch_tpu_available() and _watch_model in ("all", "parameters", "gradients"): self._wandb.watch(model, log=_watch_model, log_freq=max(100, args.logging_steps)) def on_train_begin(self, args, state, control, model=None, **kwargs): if self._wandb is None: return hp_search = state.is_hyper_param_search if hp_search: self._wandb.finish() self._initialized = False args.run_name = None if not self._initialized: self.setup(args, state, model, **kwargs) def on_train_end(self, args, state, control, model=None, tokenizer=None, **kwargs): if self._wandb is None: return if self._log_model in ("end", "checkpoint") and self._initialized and state.is_world_process_zero: from .trainer import Trainer fake_trainer = Trainer(args=args, model=model, tokenizer=tokenizer) with tempfile.TemporaryDirectory() as temp_dir: fake_trainer.save_model(temp_dir) metadata = ( { k: v for k, v in dict(self._wandb.summary).items() if isinstance(v, numbers.Number) and not k.startswith("_") } if not args.load_best_model_at_end else { f"eval/{args.metric_for_best_model}": state.best_metric, "train/total_floss": state.total_flos, } ) logger.info("Logging model artifacts. ...") model_name = ( f"model-{self._wandb.run.id}" if (args.run_name is None or args.run_name == args.output_dir) else f"model-{self._wandb.run.name}" ) artifact = self._wandb.Artifact(name=model_name, type="model", metadata=metadata) for f in Path(temp_dir).glob("*"): if f.is_file(): with artifact.new_file(f.name, mode="wb") as fa: fa.write(f.read_bytes()) self._wandb.run.log_artifact(artifact) def on_log(self, args, state, control, model=None, logs=None, **kwargs): if self._wandb is None: return if not self._initialized: self.setup(args, state, model) if state.is_world_process_zero: logs = rewrite_logs(logs) self._wandb.log({**logs, "train/global_step": state.global_step}) def on_save(self, args, state, control, **kwargs): if self._log_model == "checkpoint" and self._initialized and state.is_world_process_zero: checkpoint_metadata = { k: v for k, v in dict(self._wandb.summary).items() if isinstance(v, numbers.Number) and not k.startswith("_") } ckpt_dir = f"checkpoint-{state.global_step}" artifact_path = os.path.join(args.output_dir, ckpt_dir) logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. ...") checkpoint_name = ( f"checkpoint-{self._wandb.run.id}" if (args.run_name is None or args.run_name == args.output_dir) else f"checkpoint-{self._wandb.run.name}" ) artifact = self._wandb.Artifact(name=checkpoint_name, type="model", metadata=checkpoint_metadata) artifact.add_dir(artifact_path) self._wandb.log_artifact(artifact, aliases=[f"checkpoint-{state.global_step}"]) class CometCallback(TrainerCallback): """ A [`TrainerCallback`] that sends the logs to [Comet ML](https://www.comet.ml/site/). """ def __init__(self): if not _has_comet: raise RuntimeError("CometCallback requires comet-ml to be installed. Run `pip install comet-ml`.") self._initialized = False self._log_assets = False def setup(self, args, state, model): """ Setup the optional Comet.ml integration. Environment: - **COMET_MODE** (`str`, *optional*, defaults to `ONLINE`): Whether to create an online, offline experiment or disable Comet logging. Can be `OFFLINE`, `ONLINE`, or `DISABLED`. - **COMET_PROJECT_NAME** (`str`, *optional*): Comet project name for experiments. - **COMET_OFFLINE_DIRECTORY** (`str`, *optional*): Folder to use for saving offline experiments when `COMET_MODE` is `OFFLINE`. - **COMET_LOG_ASSETS** (`str`, *optional*, defaults to `TRUE`): Whether or not to log training assets (tf event logs, checkpoints, etc), to Comet. Can be `TRUE`, or `FALSE`. For a number of configurable items in the environment, see [here](https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables). """ self._initialized = True log_assets = os.getenv("COMET_LOG_ASSETS", "FALSE").upper() if log_assets in {"TRUE", "1"}: self._log_assets = True if state.is_world_process_zero: comet_mode = os.getenv("COMET_MODE", "ONLINE").upper() experiment = None experiment_kwargs = {"project_name": os.getenv("COMET_PROJECT_NAME", "huggingface")} if comet_mode == "ONLINE": experiment = comet_ml.Experiment(**experiment_kwargs) experiment.log_other("Created from", "transformers") logger.info("Automatic Comet.ml online logging enabled") elif comet_mode == "OFFLINE": experiment_kwargs["offline_directory"] = os.getenv("COMET_OFFLINE_DIRECTORY", "./") experiment = comet_ml.OfflineExperiment(**experiment_kwargs) experiment.log_other("Created from", "transformers") logger.info("Automatic Comet.ml offline logging enabled; use `comet upload` when finished") if experiment is not None: experiment._set_model_graph(model, framework="transformers") experiment._log_parameters(args, prefix="args/", framework="transformers") if hasattr(model, "config"): experiment._log_parameters(model.config, prefix="config/", framework="transformers") def on_train_begin(self, args, state, control, model=None, **kwargs): if not self._initialized: self.setup(args, state, model) def on_log(self, args, state, control, model=None, logs=None, **kwargs): if not self._initialized: self.setup(args, state, model) if state.is_world_process_zero: experiment = comet_ml.config.get_global_experiment() if experiment is not None: experiment._log_metrics(logs, step=state.global_step, epoch=state.epoch, framework="transformers") def on_train_end(self, args, state, control, **kwargs): if self._initialized and state.is_world_process_zero: experiment = comet_ml.config.get_global_experiment() if experiment is not None: if self._log_assets is True: logger.info("Logging checkpoints. This may take time.") experiment.log_asset_folder( args.output_dir, recursive=True, log_file_name=True, step=state.global_step ) experiment.end() class AzureMLCallback(TrainerCallback): """ A [`TrainerCallback`] that sends the logs to [AzureML](https://pypi.org/project/azureml-sdk/). """ def __init__(self, azureml_run=None): if not is_azureml_available(): raise RuntimeError("AzureMLCallback requires azureml to be installed. Run `pip install azureml-sdk`.") self.azureml_run = azureml_run def on_init_end(self, args, state, control, **kwargs): from azureml.core.run import Run if self.azureml_run is None and state.is_world_process_zero: self.azureml_run = Run.get_context() def on_log(self, args, state, control, logs=None, **kwargs): if self.azureml_run and state.is_world_process_zero: for k, v in logs.items(): if isinstance(v, (int, float)): self.azureml_run.log(k, v, description=k) class MLflowCallback(TrainerCallback): """ A [`TrainerCallback`] that sends the logs to [MLflow](https://www.mlflow.org/). Can be disabled by setting environment variable `DISABLE_MLFLOW_INTEGRATION = TRUE`. """ def __init__(self): if not is_mlflow_available(): raise RuntimeError("MLflowCallback requires mlflow to be installed. Run `pip install mlflow`.") import mlflow self._MAX_PARAM_VAL_LENGTH = mlflow.utils.validation.MAX_PARAM_VAL_LENGTH self._MAX_PARAMS_TAGS_PER_BATCH = mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH self._initialized = False self._auto_end_run = False self._log_artifacts = False self._ml_flow = mlflow def setup(self, args, state, model): """ Setup the optional MLflow integration. Environment: - **HF_MLFLOW_LOG_ARTIFACTS** (`str`, *optional*): Whether to use MLflow `.log_artifact()` facility to log artifacts. This only makes sense if logging to a remote server, e.g. s3 or GCS. If set to `True` or *1*, will copy each saved checkpoint on each save in [`TrainingArguments`]'s `output_dir` to the local or remote artifact storage. Using it without a remote storage will just copy the files to your artifact location. - **MLFLOW_EXPERIMENT_NAME** (`str`, *optional*, defaults to `None`): Whether to use an MLflow experiment_name under which to launch the run. Default to `None` which will point to the `Default` experiment in MLflow. Otherwise, it is a case sensitive name of the experiment to be activated. If an experiment with this name does not exist, a new experiment with this name is created. - **MLFLOW_TAGS** (`str`, *optional*): A string dump of a dictionary of key/value pair to be added to the MLflow run as tags. Example: `os.environ['MLFLOW_TAGS']='{"release.candidate": "RC1", "release.version": "2.2.0"}'`. - **MLFLOW_NESTED_RUN** (`str`, *optional*): Whether to use MLflow nested runs. If set to `True` or *1*, will create a nested run inside the current run. - **MLFLOW_RUN_ID** (`str`, *optional*): Allow to reattach to an existing run which can be usefull when resuming training from a checkpoint. When `MLFLOW_RUN_ID` environment variable is set, `start_run` attempts to resume a run with the specified run ID and other parameters are ignored. - **MLFLOW_FLATTEN_PARAMS** (`str`, *optional*, defaults to `False`): Whether to flatten the parameters dictionary before logging. """ self._log_artifacts = os.getenv("HF_MLFLOW_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES self._nested_run = os.getenv("MLFLOW_NESTED_RUN", "FALSE").upper() in ENV_VARS_TRUE_VALUES self._experiment_name = os.getenv("MLFLOW_EXPERIMENT_NAME", None) self._flatten_params = os.getenv("MLFLOW_FLATTEN_PARAMS", "FALSE").upper() in ENV_VARS_TRUE_VALUES self._run_id = os.getenv("MLFLOW_RUN_ID", None) logger.debug( f"MLflow experiment_name={self._experiment_name}, run_name={args.run_name}, nested={self._nested_run}," f" tags={self._nested_run}" ) if state.is_world_process_zero: if self._ml_flow.active_run() is None or self._nested_run or self._run_id: if self._experiment_name: # Use of set_experiment() ensure that Experiment is created if not exists self._ml_flow.set_experiment(self._experiment_name) self._ml_flow.start_run(run_name=args.run_name, nested=self._nested_run) logger.debug(f"MLflow run started with run_id={self._ml_flow.active_run().info.run_id}") self._auto_end_run = True combined_dict = args.to_dict() if hasattr(model, "config") and model.config is not None: model_config = model.config.to_dict() combined_dict = {**model_config, **combined_dict} combined_dict = flatten_dict(combined_dict) if self._flatten_params else combined_dict # remove params that are too long for MLflow for name, value in list(combined_dict.items()): # internally, all values are converted to str in MLflow if len(str(value)) > self._MAX_PARAM_VAL_LENGTH: logger.warning( f'Trainer is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s' " log_param() only accepts values no longer than 250 characters so we dropped this attribute." " You can use `MLFLOW_FLATTEN_PARAMS` environment variable to flatten the parameters and" " avoid this message." ) del combined_dict[name] # MLflow cannot log more than 100 values in one go, so we have to split it combined_dict_items = list(combined_dict.items()) for i in range(0, len(combined_dict_items), self._MAX_PARAMS_TAGS_PER_BATCH): self._ml_flow.log_params(dict(combined_dict_items[i : i + self._MAX_PARAMS_TAGS_PER_BATCH])) mlflow_tags = os.getenv("MLFLOW_TAGS", None) if mlflow_tags: mlflow_tags = json.loads(mlflow_tags) self._ml_flow.set_tags(mlflow_tags) self._initialized = True def on_train_begin(self, args, state, control, model=None, **kwargs): if not self._initialized: self.setup(args, state, model) def on_log(self, args, state, control, logs, model=None, **kwargs): if not self._initialized: self.setup(args, state, model) if state.is_world_process_zero: metrics = {} for k, v in logs.items(): if isinstance(v, (int, float)): metrics[k] = v else: logger.warning( f'Trainer is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. ' "MLflow's log_metric() only accepts float and int types so we dropped this attribute." ) self._ml_flow.log_metrics(metrics=metrics, step=state.global_step) def on_train_end(self, args, state, control, **kwargs): if self._initialized and state.is_world_process_zero: if self._auto_end_run and self._ml_flow.active_run(): self._ml_flow.end_run() def on_save(self, args, state, control, **kwargs): if self._initialized and state.is_world_process_zero and self._log_artifacts: ckpt_dir = f"checkpoint-{state.global_step}" artifact_path = os.path.join(args.output_dir, ckpt_dir) logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. This may take time.") self._ml_flow.pyfunc.log_model( ckpt_dir, artifacts={"model_path": artifact_path}, python_model=self._ml_flow.pyfunc.PythonModel(), ) def __del__(self): # if the previous run is not terminated correctly, the fluent API will # not let you start a new run before the previous one is killed if ( self._auto_end_run and callable(getattr(self._ml_flow, "active_run", None)) and self._ml_flow.active_run() is not None ): self._ml_flow.end_run() class DagsHubCallback(MLflowCallback): """ A [`TrainerCallback`] that logs to [DagsHub](https://dagshub.com/). Extends [`MLflowCallback`] """ def __init__(self): super().__init__() if not is_dagshub_available(): raise ImportError("DagsHubCallback requires dagshub to be installed. Run `pip install dagshub`.") from dagshub.upload import Repo self.Repo = Repo def setup(self, *args, **kwargs): """ Setup the DagsHub's Logging integration. Environment: - **HF_DAGSHUB_LOG_ARTIFACTS** (`str`, *optional*): Whether to save the data and model artifacts for the experiment. Default to `False`. """ self.log_artifacts = os.getenv("HF_DAGSHUB_LOG_ARTIFACTS", "FALSE").upper() in ENV_VARS_TRUE_VALUES self.name = os.getenv("HF_DAGSHUB_MODEL_NAME") or "main" self.remote = os.getenv("MLFLOW_TRACKING_URI") self.repo = self.Repo( owner=self.remote.split(os.sep)[-2], name=self.remote.split(os.sep)[-1].split(".")[0], branch=os.getenv("BRANCH") or "main", ) self.path = Path("artifacts") if self.remote is None: raise RuntimeError( "DagsHubCallback requires the `MLFLOW_TRACKING_URI` environment variable to be set. Did you run" " `dagshub.init()`?" ) super().setup(*args, **kwargs) def on_train_end(self, args, state, control, **kwargs): if self.log_artifacts: if getattr(self, "train_dataloader", None): torch.save(self.train_dataloader.dataset, os.path.join(args.output_dir, "dataset.pt")) self.repo.directory(str(self.path)).add_dir(args.output_dir) class NeptuneMissingConfiguration(Exception): def __init__(self): super().__init__( """ ------ Unsupported ---- We were not able to create new runs. You provided a custom Neptune run to `NeptuneCallback` with the `run` argument. For the integration to work fully, provide your `api_token` and `project` by saving them as environment variables or passing them to the callback. """ ) class NeptuneCallback(TrainerCallback): """TrainerCallback that sends the logs to [Neptune](https://neptune.ai). Args: api_token (`str`, optional): Neptune API token obtained upon registration. You can leave this argument out if you have saved your token to the `NEPTUNE_API_TOKEN` environment variable (strongly recommended). See full setup instructions in the [docs](https://docs.neptune.ai/getting-started/installation). project (`str`, optional): Name of an existing Neptune project, in the form: "workspace-name/project-name". You can find and copy the name from the project Settings -> Properties in Neptune. If None (default), the value of the `NEPTUNE_PROJECT` environment variable will be used. name (`str`, optional): Custom name for the run. base_namespace (`str`, optional, defaults to "finetuning"): In the Neptune run, the root namespace that will contain all of the logged metadata. log_parameters (`bool`, optional, defaults to True): If True, logs all Trainer arguments and model parameters provided by the Trainer. log_checkpoints (`str`, optional, defaults to None): If "same", uploads checkpoints whenever they are saved by the Trainer. If "last", uploads only the most recently saved checkpoint. If "best", uploads the best checkpoint (among the ones saved by the Trainer). If None, does not upload checkpoints. run (`Run`, optional): Pass a Neptune run object if you want to continue logging to an existing run. Read more about resuming runs in the [docs](https://docs.neptune.ai/how-to-guides/neptune-api/resume-run). **neptune_run_kwargs (optional): Additional keyword arguments to be passed directly to the [neptune.init_run()](https://docs.neptune.ai/api-reference/neptune#.init_run) function when a new run is created. """ integration_version_key = "source_code/integrations/transformers" model_parameters_key = "model_parameters" trial_name_key = "trial" trial_params_key = "trial_params" trainer_parameters_key = "trainer_parameters" flat_metrics = {"train/epoch"} def __init__( self, *, api_token: Optional[str] = None, project: Optional[str] = None, name: Optional[str] = None, base_namespace: str = "finetuning", run: Optional["Run"] = None, log_parameters: bool = True, log_checkpoints: Optional[str] = None, **neptune_run_kwargs, ): if not is_neptune_available(): raise ValueError( "NeptuneCallback requires the Neptune client library to be installed. " "To install the library, run `pip install neptune-client`." ) from neptune.new.metadata_containers.run import Run try: from neptune.new.integrations.utils import verify_type except ImportError: from neptune.new.internal.utils import verify_type verify_type("api_token", api_token, (str, type(None))) verify_type("project", project, (str, type(None))) verify_type("name", name, (str, type(None))) verify_type("base_namespace", base_namespace, str) verify_type("run", run, (Run, type(None))) verify_type("log_parameters", log_parameters, bool) verify_type("log_checkpoints", log_checkpoints, (str, type(None))) self._base_namespace_path = base_namespace self._log_parameters = log_parameters self._log_checkpoints = log_checkpoints self._initial_run: Optional[Run] = run self._run = None self._is_monitoring_run = False self._run_id = None self._force_reset_monitoring_run = False self._init_run_kwargs = {"api_token": api_token, "project": project, "name": name, **neptune_run_kwargs} self._volatile_checkpoints_dir = None self._should_upload_checkpoint = self._log_checkpoints is not None self._recent_checkpoint_path = None if self._log_checkpoints in {"last", "best"}: self._target_checkpoints_namespace = f"checkpoints/{self._log_checkpoints}" self._should_clean_recently_uploaded_checkpoint = True else: self._target_checkpoints_namespace = "checkpoints" self._should_clean_recently_uploaded_checkpoint = False def _stop_run_if_exists(self): if self._run: self._run.stop() del self._run self._run = None def _initialize_run(self, **additional_neptune_kwargs): from neptune.new import init_run from neptune.new.exceptions import NeptuneMissingApiTokenException, NeptuneMissingProjectNameException self._stop_run_if_exists() try: self._run = init_run(**self._init_run_kwargs, **additional_neptune_kwargs) self._run_id = self._run["sys/id"].fetch() except (NeptuneMissingProjectNameException, NeptuneMissingApiTokenException) as e: raise NeptuneMissingConfiguration() from e def _use_initial_run(self): self._run = self._initial_run self._is_monitoring_run = True self._run_id = self._run["sys/id"].fetch() self._initial_run = None def _ensure_run_with_monitoring(self): if self._initial_run is not None: self._use_initial_run() else: if not self._force_reset_monitoring_run and self._is_monitoring_run: return if self._run and not self._is_monitoring_run and not self._force_reset_monitoring_run: self._initialize_run(run=self._run_id) self._is_monitoring_run = True else: self._initialize_run() self._force_reset_monitoring_run = False def _ensure_at_least_run_without_monitoring(self): if self._initial_run is not None: self._use_initial_run() else: if not self._run: self._initialize_run( run=self._run_id, capture_stdout=False, capture_stderr=False, capture_hardware_metrics=False, capture_traceback=False, ) self._is_monitoring_run = False @property def run(self): if self._run is None: self._ensure_at_least_run_without_monitoring() return self._run @property def _metadata_namespace(self): return self.run[self._base_namespace_path] def _log_integration_version(self): self.run[NeptuneCallback.integration_version_key] = version def _log_trainer_parameters(self, args): self._metadata_namespace[NeptuneCallback.trainer_parameters_key] = args.to_sanitized_dict() def _log_model_parameters(self, model): if model and hasattr(model, "config") and model.config is not None: self._metadata_namespace[NeptuneCallback.model_parameters_key] = model.config.to_dict() def _log_hyper_param_search_parameters(self, state): if state and hasattr(state, "trial_name"): self._metadata_namespace[NeptuneCallback.trial_name_key] = state.trial_name if state and hasattr(state, "trial_params") and state.trial_params is not None: self._metadata_namespace[NeptuneCallback.trial_params_key] = state.trial_params def _log_model_checkpoint(self, source_directory: str, checkpoint: str): target_path = relative_path = os.path.join(source_directory, checkpoint) if self._volatile_checkpoints_dir is not None: consistent_checkpoint_path = os.path.join(self._volatile_checkpoints_dir, checkpoint) try: shutil.copytree(relative_path, os.path.join(consistent_checkpoint_path, relative_path)) target_path = consistent_checkpoint_path except IOError as e: logger.warning( "NeptuneCallback was unable to made a copy of checkpoint due to I/O exception: '{}'." "Could fail trying to upload.".format(e) ) self._metadata_namespace[self._target_checkpoints_namespace].upload_files(target_path) if self._should_clean_recently_uploaded_checkpoint and self._recent_checkpoint_path is not None: self._metadata_namespace[self._target_checkpoints_namespace].delete_files(self._recent_checkpoint_path) self._recent_checkpoint_path = relative_path def on_init_end(self, args, state, control, **kwargs): self._volatile_checkpoints_dir = None if self._log_checkpoints and (args.overwrite_output_dir or args.save_total_limit is not None): self._volatile_checkpoints_dir = tempfile.TemporaryDirectory().name if self._log_checkpoints == "best" and not args.load_best_model_at_end: raise ValueError("To save the best model checkpoint, the load_best_model_at_end argument must be enabled.") def on_train_begin(self, args, state, control, model=None, **kwargs): if not state.is_world_process_zero: return self._ensure_run_with_monitoring() self._force_reset_monitoring_run = True self._log_integration_version() if self._log_parameters: self._log_trainer_parameters(args) self._log_model_parameters(model) if state.is_hyper_param_search: self._log_hyper_param_search_parameters(state) def on_train_end(self, args, state, control, **kwargs): self._stop_run_if_exists() def __del__(self): if self._volatile_checkpoints_dir is not None: shutil.rmtree(self._volatile_checkpoints_dir, ignore_errors=True) self._stop_run_if_exists() def on_save(self, args, state, control, **kwargs): if self._should_upload_checkpoint: self._log_model_checkpoint(args.output_dir, f"checkpoint-{state.global_step}") def on_evaluate(self, args, state, control, metrics=None, **kwargs): if self._log_checkpoints == "best": best_metric_name = args.metric_for_best_model if not best_metric_name.startswith("eval_"): best_metric_name = f"eval_{best_metric_name}" metric_value = metrics.get(best_metric_name) operator = np.greater if args.greater_is_better else np.less self._should_upload_checkpoint = state.best_metric is None or operator(metric_value, state.best_metric) @classmethod def get_run(cls, trainer): for callback in trainer.callback_handler.callbacks: if isinstance(callback, cls): return callback.run raise Exception("The trainer doesn't have a NeptuneCallback configured.") def on_log(self, args, state, control, logs: Optional[Dict[str, float]] = None, **kwargs): if not state.is_world_process_zero: return if logs is not None: for name, value in rewrite_logs(logs).items(): if isinstance(value, (int, float)): if name in NeptuneCallback.flat_metrics: self._metadata_namespace[name] = value else: self._metadata_namespace[name].log(value, step=state.global_step) class CodeCarbonCallback(TrainerCallback): """ A [`TrainerCallback`] that tracks the CO2 emission of training. """ def __init__(self): if not is_codecarbon_available(): raise RuntimeError( "CodeCarbonCallback requires `codecarbon` to be installed. Run `pip install codecarbon`." ) import codecarbon self._codecarbon = codecarbon self.tracker = None def on_init_end(self, args, state, control, **kwargs): if self.tracker is None and state.is_local_process_zero: # CodeCarbon will automatically handle environment variables for configuration self.tracker = self._codecarbon.EmissionsTracker(output_dir=args.output_dir) def on_train_begin(self, args, state, control, model=None, **kwargs): if self.tracker and state.is_local_process_zero: self.tracker.start() def on_train_end(self, args, state, control, **kwargs): if self.tracker and state.is_local_process_zero: self.tracker.stop() class ClearMLCallback(TrainerCallback): """ A [`TrainerCallback`] that sends the logs to [ClearML](https://clear.ml/). Environment: - **CLEARML_PROJECT** (`str`, *optional*, defaults to `HuggingFace Transformers`): ClearML project name. - **CLEARML_TASK** (`str`, *optional*, defaults to `Trainer`): ClearML task name. - **CLEARML_LOG_MODEL** (`bool`, *optional*, defaults to `False`): Whether to log models as artifacts during training. """ def __init__(self): if is_clearml_available(): import clearml self._clearml = clearml else: raise RuntimeError("ClearMLCallback requires 'clearml' to be installed. Run `pip install clearml`.") self._initialized = False self._clearml_task = None self._log_model = os.getenv("CLEARML_LOG_MODEL", "FALSE").upper() in ENV_VARS_TRUE_VALUES.union({"TRUE"}) def setup(self, args, state, model, tokenizer, **kwargs): if self._clearml is None: return if self._initialized: return if state.is_world_process_zero: logger.info("Automatic ClearML logging enabled.") if self._clearml_task is None: # This might happen when running inside of a pipeline, where the task is already initialized # from outside of Hugging Face if self._clearml.Task.current_task(): self._clearml_task = self._clearml.Task.current_task() self._initialized = True logger.info("External ClearML Task has been connected.") else: self._clearml_task = self._clearml.Task.init( project_name=os.getenv("CLEARML_PROJECT", "HuggingFace Transformers"), task_name=os.getenv("CLEARML_TASK", "Trainer"), auto_connect_frameworks={"tensorboard": False, "pytorch": False}, output_uri=True, ) self._initialized = True logger.info("ClearML Task has been initialized.") self._clearml_task.connect(args, "Args") if hasattr(model, "config") and model.config is not None: self._clearml_task.connect(model.config, "Model Configuration") def on_train_begin(self, args, state, control, model=None, tokenizer=None, **kwargs): if self._clearml is None: return if state.is_hyper_param_search: self._initialized = False if not self._initialized: self.setup(args, state, model, tokenizer, **kwargs) def on_train_end(self, args, state, control, model=None, tokenizer=None, metrics=None, logs=None, **kwargs): if self._clearml is None: return if self._clearml_task and state.is_world_process_zero: # Close ClearML Task at the end end of training self._clearml_task.close() def on_log(self, args, state, control, model=None, tokenizer=None, logs=None, **kwargs): if self._clearml is None: return if not self._initialized: self.setup(args, state, model, tokenizer, **kwargs) if state.is_world_process_zero: eval_prefix = "eval_" eval_prefix_len = len(eval_prefix) test_prefix = "test_" test_prefix_len = len(test_prefix) single_value_scalars = [ "train_runtime", "train_samples_per_second", "train_steps_per_second", "train_loss", "total_flos", "epoch", ] for k, v in logs.items(): if isinstance(v, (int, float)): if k in single_value_scalars: self._clearml_task.get_logger().report_single_value(name=k, value=v) elif k.startswith(eval_prefix): self._clearml_task.get_logger().report_scalar( title=k[eval_prefix_len:], series="eval", value=v, iteration=state.global_step ) elif k.startswith(test_prefix): self._clearml_task.get_logger().report_scalar( title=k[test_prefix_len:], series="test", value=v, iteration=state.global_step ) else: self._clearml_task.get_logger().report_scalar( title=k, series="train", value=v, iteration=state.global_step ) else: logger.warning( "Trainer is attempting to log a value of " f'"{v}" of type {type(v)} for key "{k}" as a scalar. ' "This invocation of ClearML logger's report_scalar() " "is incorrect so we dropped this attribute." ) def on_save(self, args, state, control, **kwargs): if self._log_model and self._clearml_task and state.is_world_process_zero: ckpt_dir = f"checkpoint-{state.global_step}" artifact_path = os.path.join(args.output_dir, ckpt_dir) logger.info(f"Logging checkpoint artifacts in {ckpt_dir}. This may take time.") self._clearml_task.update_output_model(artifact_path, iteration=state.global_step, auto_delete_file=False) INTEGRATION_TO_CALLBACK = { "azure_ml": AzureMLCallback, "comet_ml": CometCallback, "mlflow": MLflowCallback, "neptune": NeptuneCallback, "tensorboard": TensorBoardCallback, "wandb": WandbCallback, "codecarbon": CodeCarbonCallback, "clearml": ClearMLCallback, "dagshub": DagsHubCallback, } def get_reporting_integration_callbacks(report_to): for integration in report_to: if integration not in INTEGRATION_TO_CALLBACK: raise ValueError( f"{integration} is not supported, only {', '.join(INTEGRATION_TO_CALLBACK.keys())} are supported." ) return [INTEGRATION_TO_CALLBACK[integration] for integration in report_to]
27182812/ChatGLM-LLaMA-chinese-insturct
2,901
src/transformers/training_args_seq2seq.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. import logging from dataclasses import dataclass, field from typing import Optional from .training_args import TrainingArguments from .utils import add_start_docstrings logger = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__) class Seq2SeqTrainingArguments(TrainingArguments): """ Args: sortish_sampler (`bool`, *optional*, defaults to `False`): Whether to use a *sortish sampler* or not. Only possible if the underlying datasets are *Seq2SeqDataset* for now but will become generally available in the near future. It sorts the inputs according to lengths in order to minimize the padding size, with a bit of randomness for the training set. predict_with_generate (`bool`, *optional*, defaults to `False`): Whether to use generate to calculate generative metrics (ROUGE, BLEU). generation_max_length (`int`, *optional*): The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default to the `max_length` value of the model configuration. generation_num_beams (`int`, *optional*): The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default to the `num_beams` value of the model configuration. """ sortish_sampler: bool = field(default=False, metadata={"help": "Whether to use SortishSampler or not."}) predict_with_generate: bool = field( default=False, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) generation_max_length: Optional[int] = field( default=None, metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) }, ) generation_num_beams: Optional[int] = field( default=None, metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) }, )
233zzh/TitanDataOperationSystem
9,706
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/css/lobilist.min.css
.lobilists .lobilist-header.title-editing .lobilist-actions,.lobilists .lobilist:hover .lobilist-actions{opacity:1}.lobilists .lobilist-header:after,.lobilists:after{clear:both}.lobilists .lobilist-placeholder,.lobilists .lobilist-wrapper{display:inline-block;float:left;border:1px solid transparent;margin-bottom:16px;width:360px;margin-right:16px}.lobilists .btn-cancel-title-editing,.lobilists .btn-finish-title-editing,.lobilists .lobilist-header.title-editing .lobilist-actions .btn{display:none}.lobilists .lobilist{max-height:100%;overflow:auto;background-color:#FFF;-webkit-box-shadow:2px 2px 5px rgba(0,0,0,.1);box-shadow:2px 2px 5px rgba(0,0,0,.1)}.lobilists .lobilist:last-child{margin-right:0}.lobilists .lobilist.ui-sortable-helper{-webkit-transform:rotate(2deg);-ms-transform:rotate(2deg);-o-transform:rotate(2deg);transform:rotate(2deg)}.lobilists .lobilist.lobilist-default{border:1px solid #ddd}.lobilists .lobilist.lobilist-default .lobilist-header{border-bottom:1px solid #ddd;background-color:#eee}.lobilists .lobilist.lobilist-default .lobilist-header input{background-color:transparent;border-color:#555;color:#555}.lobilists .lobilist.lobilist-default .btn-show-form,.lobilists .lobilist.lobilist-default .lobilist-actions .btn,.lobilists .lobilist.lobilist-default .lobilist-title{color:#555}.lobilists .lobilist.lobilist-default .lobilist-footer,.lobilists .lobilist.lobilist-default .lobilist-form-footer{border-top:1px solid #ddd;background-color:#eee}.lobilists .lobilist.lobilist-danger{border:1px solid #dc5f5c}.lobilists .lobilist.lobilist-danger .lobilist-header{border-bottom:1px solid #dc5f5c;background-color:#e27c79}.lobilists .lobilist.lobilist-danger .lobilist-header input{background-color:transparent;border-color:#FFF;color:#FFF}.lobilists .lobilist.lobilist-danger .btn-show-form,.lobilists .lobilist.lobilist-danger .lobilist-actions .btn,.lobilists .lobilist.lobilist-danger .lobilist-title{color:#FFF}.lobilists .lobilist.lobilist-danger .lobilist-footer,.lobilists .lobilist.lobilist-danger .lobilist-form-footer{border-top:1px solid #dc5f5c;background-color:#e27c79}.lobilists .lobilist.lobilist-success{border:1px solid #49a749}.lobilists .lobilist.lobilist-success .lobilist-header{border-bottom:1px solid #49a749;background-color:#5cb85c}.lobilists .lobilist.lobilist-success .lobilist-header input{background-color:transparent;border-color:#FFF;color:#FFF}.lobilists .lobilist.lobilist-success .btn-show-form,.lobilists .lobilist.lobilist-success .lobilist-actions .btn,.lobilists .lobilist.lobilist-success .lobilist-title{color:#FFF}.lobilists .lobilist.lobilist-success .lobilist-footer,.lobilists .lobilist.lobilist-success .lobilist-form-footer{border-top:1px solid #49a749;background-color:#5cb85c}.lobilists .lobilist.lobilist-warning{border:1px solid #ed9e2d}.lobilists .lobilist.lobilist-warning .lobilist-header{border-bottom:1px solid #ed9e2d;background-color:#f0ad4e}.lobilists .lobilist.lobilist-warning .lobilist-header input{background-color:transparent;border-color:#FFF;color:#FFF}.lobilists .lobilist.lobilist-warning .btn-show-form,.lobilists .lobilist.lobilist-warning .lobilist-actions .btn,.lobilists .lobilist.lobilist-warning .lobilist-title{color:#FFF}.lobilists .lobilist.lobilist-warning .lobilist-footer,.lobilists .lobilist.lobilist-warning .lobilist-form-footer{border-top:1px solid #ed9e2d;background-color:#f0ad4e}.lobilists .lobilist.lobilist-info{border:1px solid #3db5d8}.lobilists .lobilist.lobilist-info .lobilist-header{border-bottom:1px solid #3db5d8;background-color:#5bc0de}.lobilists .lobilist.lobilist-info .lobilist-header input{background-color:transparent;border-color:#FFF;color:#FFF}.lobilists .lobilist.lobilist-info .btn-show-form,.lobilists .lobilist.lobilist-info .lobilist-actions .btn,.lobilists .lobilist.lobilist-info .lobilist-title{color:#FFF}.lobilists .lobilist.lobilist-info .lobilist-footer,.lobilists .lobilist.lobilist-info .lobilist-form-footer{border-top:1px solid #3db5d8;background-color:#5bc0de}.lobilists .lobilist.lobilist-primary{border:1px solid #2c689c}.lobilists .lobilist.lobilist-primary .lobilist-header{border-bottom:1px solid #2c689c;background-color:#337ab7}.lobilists .lobilist.lobilist-primary .lobilist-header input{background-color:transparent;border-color:#FFF;color:#FFF}.lobilists .lobilist.lobilist-primary .btn-show-form,.lobilists .lobilist.lobilist-primary .lobilist-actions .btn,.lobilists .lobilist.lobilist-primary .lobilist-title{color:#FFF}.lobilists .lobilist.lobilist-primary .lobilist-footer,.lobilists .lobilist.lobilist-primary .lobilist-form-footer{border-top:1px solid #2c689c;background-color:#337ab7}.lobilists .lobilist-header{position:relative;min-height:38px;padding:6px 8px}.lobilists .lobilist-header input{background-color:transparent;height:30px}.lobilists .lobilist-header.title-editing .lobilist-actions .btn-cancel-title-editing,.lobilists .lobilist-header.title-editing .lobilist-actions .btn-finish-title-editing{display:inline-block;font-size:18px;line-height:30px;width:30px;height:30px}.lobilists .lobilist-header:after,.lobilists .lobilist-header:before{content:" ";display:table}.lobilists .lobilist-actions{position:absolute;top:6px;right:8px;opacity:0}.lobilists .lobilist-actions>.dropdown{display:inline-block}.lobilists .lobilist-actions .dropdown-menu{height:70px;width:100px;box-sizing:content-box;min-width:0;padding:0;margin:0}.lobilists .lobilist-actions .dropdown-menu .lobilist-danger,.lobilists .lobilist-actions .dropdown-menu .lobilist-default,.lobilists .lobilist-actions .dropdown-menu .lobilist-info,.lobilists .lobilist-actions .dropdown-menu .lobilist-primary,.lobilists .lobilist-actions .dropdown-menu .lobilist-success,.lobilists .lobilist-actions .dropdown-menu .lobilist-warning{display:inline-block;cursor:pointer;margin:4px;width:25px;height:25px}.lobilists .lobilist-actions .dropdown-menu .lobilist-default{background-color:#eee}.lobilists .lobilist-actions .dropdown-menu .lobilist-default:hover{background-color:#e2e2e2}.lobilists .lobilist-actions .dropdown-menu .lobilist-danger{background-color:#e27c79}.lobilists .lobilist-actions .dropdown-menu .lobilist-danger:hover{background-color:#de6764}.lobilists .lobilist-actions .dropdown-menu .lobilist-success{background-color:#5cb85c}.lobilists .lobilist-actions .dropdown-menu .lobilist-success:hover{background-color:#4cae4c}.lobilists .lobilist-actions .dropdown-menu .lobilist-warning{background-color:#f0ad4e}.lobilists .lobilist-actions .dropdown-menu .lobilist-warning:hover{background-color:#eea236}.lobilists .lobilist-actions .dropdown-menu .lobilist-info{background-color:#5bc0de}.lobilists .lobilist-actions .dropdown-menu .lobilist-info:hover{background-color:#46b8da}.lobilists .lobilist-actions .dropdown-menu .lobilist-primary{background-color:#337ab7}.lobilists .lobilist-actions .dropdown-menu .lobilist-primary:hover{background-color:#2e6da4}.lobilists .lobilist-actions .btn{background-color:transparent;border-color:transparent;width:26px;height:26px}.lobilists .lobilist-actions .btn:hover{background-color:rgba(0,0,0,.04)}.lobilists .lobilist-title{padding-left:15px;font-size:18px}.lobilists .lobilist-items{list-style:none;margin-bottom:0;padding:10px}.lobilists .lobilist-item,.lobilists .lobilist-item-placeholder{border:1px solid transparent;margin-bottom:5px;padding-top:16px;padding-bottom:4px;padding-left:35px;border-bottom:1px solid #eee;-webkit-transition:background-color .2s;-o-transition:background-color .2s;transition:background-color .2s}.lobilists .lobilist-item .drag-handler{position:absolute;left:0;top:0;bottom:0;width:5px;border-left:2px dotted #ddd;border-right:2px dotted #ddd}.lobilists .lobilist-item .drag-handler:hover{cursor:move}.lobilists .lobilist-item .todo-actions{position:absolute;top:2px;right:4px;text-align:center;white-space:nowrap;font-size:10px;color:#9d9d9d;line-height:16px}.lobilists .lobilist-item .todo-action{display:inline-block;width:16px;height:16px}.lobilists .lobilist-item .todo-action:hover{cursor:pointer;color:#5e5e5e}.lobilists .lobilist-item:hover{background-color:rgba(0,0,0,.02)}.lobilists .lobilist-item-title{font-weight:600;font-size:16px}.lobilists .lobilist-item-description{font-style:italic}.lobilists .lobilist-item-duedate{position:absolute;top:2px;left:12px;font-style:italic;color:#777;font-size:85%}.lobilists .lobilist-check{position:absolute;left:12px;top:16px}.lobilists .lobilist-check.lobicheck{margin-top:3px}.lobilists .lobilist-item,.lobilists .lobilist-item-placeholder{position:relative}.lobilists .lobilist-item.item-done{text-decoration:line-through}.lobilists .btn-show-form{outline:0}.lobilists .lobilist-footer,.lobilists .lobilist-form-footer{padding:6px 8px}.lobilists .lobilist-form-footer{margin-left:-10px;margin-right:-10px;margin-bottom:-10px}.lobilists .lobilist-add-todo-form{padding:10px}.lobilists .lobilist-add-todo-form .form-group{margin-bottom:5px}.lobilists .lobilist-add-todo-form .btn-add-todo{margin-right:5px}.lobilists .lobilist-add-todo-form .btn-add-todo,.lobilists .lobilist-add-todo-form .btn-discard-todo{height:30px}.lobilists .lobilist-placeholder{background-color:#f9f5d1;border:1px dashed #777}.lobilists .lobilist-item-placeholder{background-color:rgba(0,0,0,.03);border:1px dashed #ddd}@media (max-width:480px){.lobilists .lobilist{width:100%}}.lobilists.single-line{overflow-x:auto;overflow-y:hidden;white-space:nowrap;height:400px}.lobilists.single-line .lobilist-placeholder,.lobilists.single-line .lobilist-wrapper{float:none;white-space:normal;vertical-align:top;height:100%}.lobilists.no-sortable .lobilist-item .drag-handler{display:none}.lobilists:after,.lobilists:before{content:" ";display:table}
274056675/springboot-openai-chatgpt
2,498
mng_web/src/page/lock/index.vue
<template> <div class="lock-container"> <div class="lock-form animated bounceInDown"> <div class="animated" :class="{'shake':passwdError,'bounceOut':pass}"> <h3 class="title">{{userInfo.username}}</h3> <el-input placeholder="请输入登录密码" type="password" class="input-with-select animated" v-model="passwd" @keyup.enter.native="handleLogin"> <el-button slot="append" icon="icon-bofangqi-suoping" @click="handleLogin"></el-button> <el-button slot="append" icon="icon-tuichu" @click="handleLogout"></el-button> </el-input> </div> </div> </div> </template> <script> import { mapGetters, mapState } from "vuex"; export default { name: "lock", data() { return { passwd: "", passwdError: false, pass: false }; }, created() {}, mounted() {}, computed: { ...mapState({ userInfo: state => state.user.userInfo }), ...mapGetters(["tag", "lockPasswd"]) }, props: [], methods: { handleLogout() { this.$confirm("是否退出系统, 是否继续?", "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }).then(() => { this.$store.dispatch("LogOut").then(() => { this.$router.push({ path: "/login" }); }); }); }, handleLogin() { if (this.passwd != this.lockPasswd) { this.passwd = ""; this.$message({ message: "解锁密码错误,请重新输入", type: "error" }); this.passwdError = true; setTimeout(() => { this.passwdError = false; }, 1000); return; } this.pass = true; setTimeout(() => { this.$store.commit("CLEAR_LOCK"); this.$router.push({ path: this.$router.$avueRouter.getPath({ src: this.tag.value }) }); }, 1000); } }, components: {} }; </script> <style lang="scss"> .lock-container { height: 100%; display: flex; align-items: center; justify-content: center; position: relative; .title { margin-bottom: 8px; color: #333; } } .lock-container::before { z-index: -999; content: ""; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background-image: url("/img/bg/login.png"); background-size: cover; } .lock-form { width: 300px; } </style>
274056675/springboot-openai-chatgpt
7,755
mng_web/src/page/login/userlogin.vue
<template> <el-form class="login-form" status-icon :rules="loginRules" ref="loginForm" :model="loginForm" label-width="0" > <el-form-item v-if="tenantMode" prop="tenantId"> <el-input size="small" @keyup.enter.native="handleLogin" v-model="loginForm.tenantId" auto-complete="off" :placeholder="$t('login.tenantId')" > <i slot="prefix" class="icon-quanxian" /> </el-input> </el-form-item> <el-form-item prop="username"> <el-input size="small" @keyup.enter.native="handleLogin" v-model="loginForm.username" auto-complete="off" :placeholder="$t('login.username')" > <i slot="prefix" class="icon-yonghu" /> </el-input> </el-form-item> <el-form-item prop="password"> <el-input size="small" @keyup.enter.native="handleLogin" :type="passwordType" v-model="loginForm.password" auto-complete="off" :placeholder="$t('login.password')" > <i class="el-icon-view el-input__icon" slot="suffix" @click="showPassword" /> <i slot="prefix" class="icon-mima" /> </el-input> </el-form-item> <el-form-item v-if="this.website.captchaMode" prop="code"> <el-row :span="24"> <el-col :span="16"> <el-input size="small" @keyup.enter.native="handleLogin" v-model="loginForm.code" auto-complete="off" :placeholder="$t('login.code')" > <i slot="prefix" class="icon-yanzhengma" /> </el-input> </el-col> <el-col :span="8"> <div class="login-code"> <img :src="loginForm.image" class="login-code-img" @click="refreshCode" /> </div> </el-col> </el-row> </el-form-item> <el-form-item> <el-button type="primary" size="small" @click.native.prevent="handleLogin" class="login-submit" >{{ $t("login.submit") }}</el-button > </el-form-item> <el-dialog title="用户信息选择" append-to-body :visible.sync="userBox" width="350px"> <avue-form :option="userOption" v-model="userForm" @submit="submitLogin" /> </el-dialog> </el-form> </template> <script> import { mapGetters } from "vuex"; import { info } from "@/api/system/tenant"; import { getCaptcha } from "@/api/user"; import { getTopUrl } from "@/util/util"; export default { name: "userlogin", data() { return { tenantMode: this.website.tenantMode, loginForm: { //租户ID tenantId: "000000", //部门ID deptId: "", //角色ID roleId: "", //用户名 username: "", //密码 password: "", //账号类型 type: "account", //验证码的值 code: "", //验证码的索引 key: "", //预加载白色背景 image: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", }, loginRules: { tenantId: [{ required: false, message: "请输入租户ID", trigger: "blur" }], username: [{ required: true, message: "请输入用户名", trigger: "blur" }], password: [ { required: true, message: "请输入密码", trigger: "blur" }, { min: 1, message: "密码长度最少为6位", trigger: "blur" }, ], }, passwordType: "password", userBox: false, userForm: { deptId: "", roleId: "", }, userOption: { labelWidth: 70, submitBtn: true, emptyBtn: false, submitText: "登录", column: [ { label: "部门", prop: "deptId", type: "select", props: { label: "deptName", value: "id", }, dicUrl: "/api/blade-system/dept/select", span: 24, display: false, rules: [ { required: true, message: "请选择部门", trigger: "blur", }, ], }, { label: "角色", prop: "roleId", type: "select", props: { label: "roleName", value: "id", }, dicUrl: "/api/blade-system/role/select", span: 24, display: false, rules: [ { required: true, message: "请选择角色", trigger: "blur", }, ], }, ], }, }; }, created() { this.getTenant(); this.refreshCode(); }, mounted() {}, watch: { "loginForm.deptId"() { const column = this.findObject(this.userOption.column, "deptId"); if (this.loginForm.deptId.includes(",")) { column.dicUrl = `/api/blade-system/dept/select?deptId=${this.loginForm.deptId}`; column.display = true; } else { column.dicUrl = ""; } }, "loginForm.roleId"() { const column = this.findObject(this.userOption.column, "roleId"); if (this.loginForm.roleId.includes(",")) { column.dicUrl = `/api/blade-system/role/select?roleId=${this.loginForm.roleId}`; column.display = true; } else { column.dicUrl = ""; } }, }, computed: { ...mapGetters(["tagWel", "userInfo"]), }, props: [], methods: { refreshCode() { if (this.website.captchaMode) { getCaptcha().then((res) => { if (res.data.code == 200) { const data = res.data.data; this.loginForm.key = data.key; this.loginForm.image = data.image; } }); } }, showPassword() { this.passwordType === "" ? (this.passwordType = "password") : (this.passwordType = ""); }, submitLogin(form, done) { if (form.deptId !== "") { this.loginForm.deptId = form.deptId; } if (form.roleId !== "") { this.loginForm.roleId = form.roleId; } this.handleLogin(); done(); }, handleLogin() { this.$refs.loginForm.validate((valid) => { if (valid) { const loading = this.$loading({ lock: true, text: "登录中,请稍后。。。", spinner: "el-icon-loading", }); this.$store .dispatch("LoginByUsername", this.loginForm) .then(() => { if (this.website.switchMode) { const deptId = this.userInfo.dept_id; const roleId = this.userInfo.role_id; if (deptId.includes(",") || roleId.includes(",")) { this.loginForm.deptId = deptId; this.loginForm.roleId = roleId; this.userBox = true; this.$store.dispatch("LogOut").then(() => { loading.close(); }); return false; } } this.$router.push({ path: this.tagWel.value }); loading.close(); }) .catch(() => { loading.close(); this.refreshCode(); }); } }); }, getTenant() { let domain = getTopUrl(); // 临时指定域名,方便测试 //domain = "https://bladex.vip"; info(domain).then((res) => { const data = res.data; if (data.success && data.data.tenantId) { this.tenantMode = false; this.loginForm.tenantId = data.data.tenantId; // this.$parent.$refs.login.style.backgroundImage = `url(${data.data.backgroundUrl})` } }); }, }, }; </script> <style></style>
27182812/ChatGLM-LLaMA-chinese-insturct
20,903
src/transformers/convert_graph_to_onnx.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. import warnings from argparse import ArgumentParser from os import listdir, makedirs from pathlib import Path from typing import Dict, List, Optional, Tuple from packaging.version import Version, parse from transformers.pipelines import Pipeline, pipeline from transformers.tokenization_utils import BatchEncoding from transformers.utils import ModelOutput, is_tf_available, is_torch_available # This is the minimal required version to # support some ONNX Runtime features ORT_QUANTIZE_MINIMUM_VERSION = parse("1.4.0") SUPPORTED_PIPELINES = [ "feature-extraction", "ner", "sentiment-analysis", "fill-mask", "question-answering", "text-generation", "translation_en_to_fr", "translation_en_to_de", "translation_en_to_ro", ] class OnnxConverterArgumentParser(ArgumentParser): """ Wraps all the script arguments supported to export transformers models to ONNX IR """ def __init__(self): super().__init__("ONNX Converter") self.add_argument( "--pipeline", type=str, choices=SUPPORTED_PIPELINES, default="feature-extraction", ) self.add_argument( "--model", type=str, required=True, help="Model's id or path (ex: bert-base-cased)", ) self.add_argument("--tokenizer", type=str, help="Tokenizer's id or path (ex: bert-base-cased)") self.add_argument( "--framework", type=str, choices=["pt", "tf"], help="Framework for loading the model", ) self.add_argument("--opset", type=int, default=11, help="ONNX opset to use") self.add_argument( "--check-loading", action="store_true", help="Check ONNX is able to load the model", ) self.add_argument( "--use-external-format", action="store_true", help="Allow exporting model >= than 2Gb", ) self.add_argument( "--quantize", action="store_true", help="Quantize the neural network to be run with int8", ) self.add_argument("output") def generate_identified_filename(filename: Path, identifier: str) -> Path: """ Append a string-identifier at the end (before the extension, if any) to the provided filepath Args: filename: pathlib.Path The actual path object we would like to add an identifier suffix identifier: The suffix to add Returns: String with concatenated identifier at the end of the filename """ return filename.parent.joinpath(filename.stem + identifier).with_suffix(filename.suffix) def check_onnxruntime_requirements(minimum_version: Version): """ Check onnxruntime is installed and if the installed version match is recent enough Raises: ImportError: If onnxruntime is not installed or too old version is found """ try: import onnxruntime # Parse the version of the installed onnxruntime ort_version = parse(onnxruntime.__version__) # We require 1.4.0 minimum if ort_version < ORT_QUANTIZE_MINIMUM_VERSION: raise ImportError( f"We found an older version of onnxruntime ({onnxruntime.__version__}) " f"but we require onnxruntime to be >= {minimum_version} to enable all the conversions options.\n" "Please update onnxruntime by running `pip install --upgrade onnxruntime`" ) except ImportError: raise ImportError( "onnxruntime doesn't seem to be currently installed. " "Please install the onnxruntime by running `pip install onnxruntime`" " and relaunch the conversion." ) def ensure_valid_input(model, tokens, input_names): """ Ensure inputs are presented in the correct order, without any Non Args: model: The model used to forward the input data tokens: BatchEncoding holding the input data input_names: The name of the inputs Returns: Tuple """ print("Ensuring inputs are in correct order") model_args_name = model.forward.__code__.co_varnames model_args, ordered_input_names = [], [] for arg_name in model_args_name[1:]: # start at index 1 to skip "self" argument if arg_name in input_names: ordered_input_names.append(arg_name) model_args.append(tokens[arg_name]) else: print(f"{arg_name} is not present in the generated input list.") break print(f"Generated inputs order: {ordered_input_names}") return ordered_input_names, tuple(model_args) def infer_shapes(nlp: Pipeline, framework: str) -> Tuple[List[str], List[str], Dict, BatchEncoding]: """ Attempt to infer the static vs dynamic axes for each input and output tensors for a specific model Args: nlp: The pipeline object holding the model to be exported framework: The framework identifier to dispatch to the correct inference scheme (pt/tf) Returns: - List of the inferred input variable names - List of the inferred output variable names - Dictionary with input/output variables names as key and shape tensor as value - a BatchEncoding reference which was used to infer all the above information """ def build_shape_dict(name: str, tensor, is_input: bool, seq_len: int): if isinstance(tensor, (tuple, list)): return [build_shape_dict(name, t, is_input, seq_len) for t in tensor] else: # Let's assume batch is the first axis with only 1 element (~~ might not be always true ...) axes = {[axis for axis, numel in enumerate(tensor.shape) if numel == 1][0]: "batch"} if is_input: if len(tensor.shape) == 2: axes[1] = "sequence" else: raise ValueError(f"Unable to infer tensor axes ({len(tensor.shape)})") else: seq_axes = [dim for dim, shape in enumerate(tensor.shape) if shape == seq_len] axes.update({dim: "sequence" for dim in seq_axes}) print(f"Found {'input' if is_input else 'output'} {name} with shape: {axes}") return axes tokens = nlp.tokenizer("This is a sample output", return_tensors=framework) seq_len = tokens.input_ids.shape[-1] outputs = nlp.model(**tokens) if framework == "pt" else nlp.model(tokens) if isinstance(outputs, ModelOutput): outputs = outputs.to_tuple() if not isinstance(outputs, (list, tuple)): outputs = (outputs,) # Generate input names & axes input_vars = list(tokens.keys()) input_dynamic_axes = {k: build_shape_dict(k, v, True, seq_len) for k, v in tokens.items()} # flatten potentially grouped outputs (past for gpt2, attentions) outputs_flat = [] for output in outputs: if isinstance(output, (tuple, list)): outputs_flat.extend(output) else: outputs_flat.append(output) # Generate output names & axes output_names = [f"output_{i}" for i in range(len(outputs_flat))] output_dynamic_axes = {k: build_shape_dict(k, v, False, seq_len) for k, v in zip(output_names, outputs_flat)} # Create the aggregated axes representation dynamic_axes = dict(input_dynamic_axes, **output_dynamic_axes) return input_vars, output_names, dynamic_axes, tokens def load_graph_from_args( pipeline_name: str, framework: str, model: str, tokenizer: Optional[str] = None, **models_kwargs ) -> Pipeline: """ Convert the set of arguments provided through the CLI to an actual pipeline reference (tokenizer + model Args: pipeline_name: The kind of pipeline to use (ner, question-answering, etc.) framework: The actual model to convert the pipeline from ("pt" or "tf") model: The model name which will be loaded by the pipeline tokenizer: The tokenizer name which will be loaded by the pipeline, default to the model's value Returns: Pipeline object """ # If no tokenizer provided if tokenizer is None: tokenizer = model # Check the wanted framework is available if framework == "pt" and not is_torch_available(): raise Exception("Cannot convert because PyTorch is not installed. Please install torch first.") if framework == "tf" and not is_tf_available(): raise Exception("Cannot convert because TF is not installed. Please install tensorflow first.") print(f"Loading pipeline (model: {model}, tokenizer: {tokenizer})") # Allocate tokenizer and model return pipeline(pipeline_name, model=model, tokenizer=tokenizer, framework=framework, model_kwargs=models_kwargs) def convert_pytorch(nlp: Pipeline, opset: int, output: Path, use_external_format: bool): """ Export a PyTorch backed pipeline to ONNX Intermediate Representation (IR Args: nlp: The pipeline to be exported opset: The actual version of the ONNX operator set to use output: Path where will be stored the generated ONNX model use_external_format: Split the model definition from its parameters to allow model bigger than 2GB Returns: """ if not is_torch_available(): raise Exception("Cannot convert because PyTorch is not installed. Please install torch first.") import torch from torch.onnx import export from transformers.pytorch_utils import is_torch_less_than_1_11 print(f"Using framework PyTorch: {torch.__version__}") with torch.no_grad(): input_names, output_names, dynamic_axes, tokens = infer_shapes(nlp, "pt") ordered_input_names, model_args = ensure_valid_input(nlp.model, tokens, input_names) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( nlp.model, model_args, f=output.as_posix(), input_names=ordered_input_names, output_names=output_names, dynamic_axes=dynamic_axes, do_constant_folding=True, use_external_data_format=use_external_format, enable_onnx_checker=True, opset_version=opset, ) else: export( nlp.model, model_args, f=output.as_posix(), input_names=ordered_input_names, output_names=output_names, dynamic_axes=dynamic_axes, do_constant_folding=True, opset_version=opset, ) def convert_tensorflow(nlp: Pipeline, opset: int, output: Path): """ Export a TensorFlow backed pipeline to ONNX Intermediate Representation (IR) Args: nlp: The pipeline to be exported opset: The actual version of the ONNX operator set to use output: Path where will be stored the generated ONNX model Notes: TensorFlow cannot export model bigger than 2GB due to internal constraint from TensorFlow """ if not is_tf_available(): raise Exception("Cannot convert because TF is not installed. Please install tensorflow first.") print("/!\\ Please note TensorFlow doesn't support exporting model > 2Gb /!\\") try: import tensorflow as tf import tf2onnx from tf2onnx import __version__ as t2ov print(f"Using framework TensorFlow: {tf.version.VERSION}, tf2onnx: {t2ov}") # Build input_names, output_names, dynamic_axes, tokens = infer_shapes(nlp, "tf") # Forward nlp.model.predict(tokens.data) input_signature = [tf.TensorSpec.from_tensor(tensor, name=key) for key, tensor in tokens.items()] model_proto, _ = tf2onnx.convert.from_keras( nlp.model, input_signature, opset=opset, output_path=output.as_posix() ) except ImportError as e: raise Exception( f"Cannot import {e.name} required to convert TF model to ONNX. Please install {e.name} first. {e}" ) def convert( framework: str, model: str, output: Path, opset: int, tokenizer: Optional[str] = None, use_external_format: bool = False, pipeline_name: str = "feature-extraction", **model_kwargs, ): """ Convert the pipeline object to the ONNX Intermediate Representation (IR) format Args: framework: The framework the pipeline is backed by ("pt" or "tf") model: The name of the model to load for the pipeline output: The path where the ONNX graph will be stored opset: The actual version of the ONNX operator set to use tokenizer: The name of the model to load for the pipeline, default to the model's name if not provided use_external_format: Split the model definition from its parameters to allow model bigger than 2GB (PyTorch only) pipeline_name: The kind of pipeline to instantiate (ner, question-answering, etc.) model_kwargs: Keyword arguments to be forwarded to the model constructor Returns: """ warnings.warn( "The `transformers.convert_graph_to_onnx` package is deprecated and will be removed in version 5 of" " Transformers", FutureWarning, ) print(f"ONNX opset version set to: {opset}") # Load the pipeline nlp = load_graph_from_args(pipeline_name, framework, model, tokenizer, **model_kwargs) if not output.parent.exists(): print(f"Creating folder {output.parent}") makedirs(output.parent.as_posix()) elif len(listdir(output.parent.as_posix())) > 0: raise Exception(f"Folder {output.parent.as_posix()} is not empty, aborting conversion") # Export the graph if framework == "pt": convert_pytorch(nlp, opset, output, use_external_format) else: convert_tensorflow(nlp, opset, output) def optimize(onnx_model_path: Path) -> Path: """ Load the model at the specified path and let onnxruntime look at transformations on the graph to enable all the optimizations possible Args: onnx_model_path: filepath where the model binary description is stored Returns: Path where the optimized model binary description has been saved """ from onnxruntime import InferenceSession, SessionOptions # Generate model name with suffix "optimized" opt_model_path = generate_identified_filename(onnx_model_path, "-optimized") sess_option = SessionOptions() sess_option.optimized_model_filepath = opt_model_path.as_posix() _ = InferenceSession(onnx_model_path.as_posix(), sess_option) print(f"Optimized model has been written at {opt_model_path}: \N{heavy check mark}") print("/!\\ Optimized model contains hardware specific operators which might not be portable. /!\\") return opt_model_path def quantize(onnx_model_path: Path) -> Path: """ Quantize the weights of the model from float32 to in8 to allow very efficient inference on modern CPU Args: onnx_model_path: Path to location the exported ONNX model is stored Returns: The Path generated for the quantized """ import onnx import onnxruntime from onnx.onnx_pb import ModelProto from onnxruntime.quantization import QuantizationMode from onnxruntime.quantization.onnx_quantizer import ONNXQuantizer from onnxruntime.quantization.registry import IntegerOpsRegistry # Load the ONNX model onnx_model = onnx.load(onnx_model_path.as_posix()) if parse(onnx.__version__) < parse("1.5.0"): print( "Models larger than 2GB will fail to quantize due to protobuf constraint.\n" "Please upgrade to onnxruntime >= 1.5.0." ) # Copy it copy_model = ModelProto() copy_model.CopyFrom(onnx_model) # Construct quantizer # onnxruntime renamed input_qType to activation_qType in v1.13.1, so we # check the onnxruntime version to ensure backward compatibility. # See also: https://github.com/microsoft/onnxruntime/pull/12873 if parse(onnxruntime.__version__) < parse("1.13.1"): quantizer = ONNXQuantizer( model=copy_model, per_channel=False, reduce_range=False, mode=QuantizationMode.IntegerOps, static=False, weight_qType=True, input_qType=False, tensors_range=None, nodes_to_quantize=None, nodes_to_exclude=None, op_types_to_quantize=list(IntegerOpsRegistry), ) else: quantizer = ONNXQuantizer( model=copy_model, per_channel=False, reduce_range=False, mode=QuantizationMode.IntegerOps, static=False, weight_qType=True, activation_qType=False, tensors_range=None, nodes_to_quantize=None, nodes_to_exclude=None, op_types_to_quantize=list(IntegerOpsRegistry), ) # Quantize and export quantizer.quantize_model() # Append "-quantized" at the end of the model's name quantized_model_path = generate_identified_filename(onnx_model_path, "-quantized") # Save model print(f"Quantized model has been written at {quantized_model_path}: \N{heavy check mark}") onnx.save_model(quantizer.model.model, quantized_model_path.as_posix()) return quantized_model_path def verify(path: Path): from onnxruntime import InferenceSession, SessionOptions from onnxruntime.capi.onnxruntime_pybind11_state import RuntimeException print(f"Checking ONNX model loading from: {path} ...") try: onnx_options = SessionOptions() _ = InferenceSession(path.as_posix(), onnx_options, providers=["CPUExecutionProvider"]) print(f"Model {path} correctly loaded: \N{heavy check mark}") except RuntimeException as re: print(f"Error while loading the model {re}: \N{heavy ballot x}") if __name__ == "__main__": parser = OnnxConverterArgumentParser() args = parser.parse_args() # Make sure output is absolute path args.output = Path(args.output).absolute() try: print("\n====== Converting model to ONNX ======") # Convert convert( args.framework, args.model, args.output, args.opset, args.tokenizer, args.use_external_format, args.pipeline, ) if args.quantize: # Ensure requirements for quantization on onnxruntime is met check_onnxruntime_requirements(ORT_QUANTIZE_MINIMUM_VERSION) # onnxruntime optimizations doesn't provide the same level of performances on TensorFlow than PyTorch if args.framework == "tf": print( "\t Using TensorFlow might not provide the same optimization level compared to PyTorch.\n" "\t For TensorFlow users you can try optimizing the model directly through onnxruntime_tools.\n" "\t For more information, please refer to the onnxruntime documentation:\n" "\t\thttps://github.com/microsoft/onnxruntime/tree/master/onnxruntime/python/tools/transformers\n" ) print("\n====== Optimizing ONNX model ======") # Quantization works best when using the optimized version of the model args.optimized_output = optimize(args.output) # Do the quantization on the right graph args.quantized_output = quantize(args.optimized_output) # And verify if args.check_loading: print("\n====== Check exported ONNX model(s) ======") verify(args.output) if hasattr(args, "optimized_output"): verify(args.optimized_output) if hasattr(args, "quantized_output"): verify(args.quantized_output) except Exception as e: print(f"Error while converting the model: {e}") exit(1)
274056675/springboot-openai-chatgpt
3,720
mng_web/src/page/login/index.vue
<template> <div class="login-container" ref="login" @keyup.enter.native="handleLogin"> <top-color v-show="false"></top-color> <div class="login-weaper animated bounceInDown"> <!-- <div class="login-left"> <div class="login-time">{{time}}</div> <p class="title">{{ $t('login.info') }}</p> <img class="img" src="/img/bg/login-bg.png" alt /> </div>--> <div class="login-border"> <div class="login-main"> <h4 class="login-title"> {{ $t('login.title') }}{{website.title}} <!-- <top-lang></top-lang> --> </h4> <userLogin v-if="activeName==='user'"></userLogin> <codeLogin v-else-if="activeName==='code'"></codeLogin> <thirdLogin v-else-if="activeName==='third'"></thirdLogin> <div class="login-menu"> <a href="#" @click.stop="activeName='user'">{{ $t('login.userLogin') }}</a> <!--<a href="#" @click.stop="activeName='code'">{{ $t('login.phoneLogin') }}</a>--> <a href="#" @click.stop="activeName='third'">{{ $t('login.thirdLogin') }}</a> </div> </div> </div> </div> </div> </template> <script> import userLogin from './userlogin' import codeLogin from './codelogin' import thirdLogin from './thirdlogin' import { mapGetters, mapMutations } from 'vuex' import { dateFormat } from '@/util/date' import { validatenull } from '@/util/validate' import topLang from '@/page/index/top/top-lang' import topColor from '@/page/index/top/top-color' import { getQueryString, getTopUrl } from '@/util/util' import { originUrl } from '@/config/url' export default { name: 'login', components: { userLogin, codeLogin, thirdLogin, topLang, topColor, }, data() { return { time: '', activeName: 'user', socialForm: { tenantId: '000000', source: '', code: '', state: '', }, } }, watch: { $route() { this.handleLogin() }, }, created() { this.handleLogin() this.getTime() }, mounted() { //清除本地缓存的菜单 this.SET_MENU_ALL_NULL() this.SET_MENU([]) }, computed: { ...mapGetters(['website', 'tagWel']), }, props: [], methods: { ...mapMutations(['SET_MENU_ALL_NULL', 'SET_MENU']), getTime() { setInterval(() => { this.time = dateFormat(new Date()) }, 1000) }, handleLogin() { const topUrl = getTopUrl() const redirectUrl = '/oauth/redirect/' this.socialForm.source = getQueryString('source') this.socialForm.code = getQueryString('code') this.socialForm.state = getQueryString('state') if ( validatenull(this.socialForm.source) && topUrl.includes(redirectUrl) ) { let source = topUrl.split('?')[0] source = source.split(redirectUrl)[1] this.socialForm.source = source } if ( !validatenull(this.socialForm.source) && !validatenull(this.socialForm.code) && !validatenull(this.socialForm.state) ) { const loading = this.$loading({ lock: true, text: '第三方系统登录中,请稍后。。。', spinner: 'el-icon-loading', }) this.$store .dispatch('LoginBySocial', this.socialForm) .then(() => { window.location.href = topUrl.split(redirectUrl)[0] this.$router.push({ path: this.tagWel.value }) loading.close() }) .catch(() => { loading.close() window.location.href = originUrl + '/#/login' }) } }, }, } </script> <style lang="scss"> @import '@/styles/login.scss'; </style>
274056675/springboot-openai-chatgpt
1,762
mng_web/src/page/login/thirdlogin.vue
<template> <div class="social-container"> <!-- <div @click="handleClick('github')"> <span class="container" :style="{backgroundColor:'#61676D'}"> <i icon-class="github" class="iconfont icongithub"></i> </span> <p class="title">{{$t('login.github')}}</p> </div> <div @click="handleClick('gitee')"> <span class="container" :style="{backgroundColor:'#c35152'}"> <i icon-class="gitee" class="iconfont icongitee2"></i> </span> <p class="title">{{$t('login.gitee')}}</p> </div>--> <div @click="handleClick('wechat_open')"> <span class="container" :style="{backgroundColor:'#8dc349'}"> <i icon-class="wechat" class="iconfont icon-weixin" /> </span> <p class="title">{{$t('login.wechat')}}</p> </div> <!-- <div @click="handleClick('qq')"> <span class="container" :style="{backgroundColor:'#6ba2d6'}"> <i icon-class="qq" class="iconfont icon-qq"/> </span> <p class="title">{{$t('login.qq')}}</p> </div>--> </div> </template> <script> import website from '@/config/website' export default { name: 'thirdLogin', methods: { handleClick(source) { window.location.href = `${website.authUrl}/${source}` }, }, } </script> <style rel="stylesheet/scss" lang="scss" scoped> .social-container { margin: 20px 0; display: flex; align-items: center; justify-content: space-around; .iconfont { color: #fff; font-size: 30px; } .container { $height: 50px; cursor: pointer; display: inline-block; width: $height; height: $height; line-height: $height; text-align: center; border-radius: 4px; margin-bottom: 10px; } .title { text-align: center; } } </style>
233zzh/TitanDataOperationSystem
31,552
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/css/jquery-ui.min.css
/*! jQuery UI - v1.12.1 - 2016-09-14 * http://jqueryui.com * Includes: core.css, accordion.css, autocomplete.css, menu.css, button.css, controlgroup.css, checkboxradio.css, datepicker.css, dialog.css, draggable.css, resizable.css, progressbar.css, selectable.css, selectmenu.css, slider.css, sortable.css, spinner.css, tabs.css, tooltip.css, theme.css * To view and modify this theme, visit http://jqueryui.com/themeroller/?ffDefault=Trebuchet%20MS%2CTahoma%2CVerdana%2CArial%2Csans-serif&fwDefault=bold&fsDefault=1.1em&cornerRadius=4px&bgColorHeader=f6a828&bgTextureHeader=gloss_wave&bgImgOpacityHeader=35&borderColorHeader=e78f08&fcHeader=ffffff&iconColorHeader=ffffff&bgColorContent=eeeeee&bgTextureContent=highlight_soft&bgImgOpacityContent=100&borderColorContent=dddddd&fcContent=333333&iconColorContent=222222&bgColorDefault=f6f6f6&bgTextureDefault=glass&bgImgOpacityDefault=100&borderColorDefault=cccccc&fcDefault=1c94c4&iconColorDefault=ef8c08&bgColorHover=fdf5ce&bgTextureHover=glass&bgImgOpacityHover=100&borderColorHover=fbcb09&fcHover=c77405&iconColorHover=ef8c08&bgColorActive=ffffff&bgTextureActive=glass&bgImgOpacityActive=65&borderColorActive=fbd850&fcActive=eb8f00&iconColorActive=ef8c08&bgColorHighlight=ffe45c&bgTextureHighlight=highlight_soft&bgImgOpacityHighlight=75&borderColorHighlight=fed22f&fcHighlight=363636&iconColorHighlight=228ef1&bgColorError=b81900&bgTextureError=diagonals_thick&bgImgOpacityError=18&borderColorError=cd0a0a&fcError=ffffff&iconColorError=ffd27a&bgColorOverlay=666666&bgTextureOverlay=diagonals_thick&bgImgOpacityOverlay=20&opacityOverlay=50&bgColorShadow=000000&bgTextureShadow=flat&bgImgOpacityShadow=10&opacityShadow=20&thicknessShadow=5px&offsetTopShadow=-5px&offsetLeftShadow=-5px&cornerRadiusShadow=5px * Copyright jQuery Foundation and other contributors; Licensed MIT */ .ui-helper-hidden{display:none}.ui-helper-hidden-accessible{border:0;clip:rect(0 0 0 0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.ui-helper-reset{margin:0;padding:0;border:0;outline:0;line-height:1.3;text-decoration:none;font-size:100%;list-style:none}.ui-helper-clearfix:before,.ui-helper-clearfix:after{content:"";display:table;border-collapse:collapse}.ui-helper-clearfix:after{clear:both}.ui-helper-zfix{width:100%;height:100%;top:0;left:0;position:absolute;opacity:0;filter:Alpha(Opacity=0)}.ui-front{z-index:100}.ui-state-disabled{cursor:default!important;pointer-events:none}.ui-icon{display:inline-block;vertical-align:middle;margin-top:-.25em;position:relative;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat}.ui-widget-icon-block{left:50%;margin-left:-8px;display:block}.ui-widget-overlay{position:fixed;top:0;left:0;width:100%;height:100%}.ui-accordion .ui-accordion-header{display:block;cursor:pointer;position:relative;margin:2px 0 0 0;padding:.5em .5em .5em .7em;font-size:100%}.ui-accordion .ui-accordion-content{padding:1em 2.2em;border-top:0;overflow:auto}.ui-autocomplete{position:absolute;top:0;left:0;cursor:default}.ui-menu{list-style:none;padding:0;margin:0;display:block;outline:0}.ui-menu .ui-menu{position:absolute}.ui-menu .ui-menu-item{margin:0;cursor:pointer;list-style-image:url("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")}.ui-menu .ui-menu-item-wrapper{position:relative;padding:3px 1em 3px .4em}.ui-menu .ui-menu-divider{margin:5px 0;height:0;font-size:0;line-height:0;border-width:1px 0 0 0}.ui-menu .ui-state-focus,.ui-menu .ui-state-active{margin:-1px}.ui-menu-icons{position:relative}.ui-menu-icons .ui-menu-item-wrapper{padding-left:2em}.ui-menu .ui-icon{position:absolute;top:0;bottom:0;left:.2em;margin:auto 0}.ui-menu .ui-menu-icon{left:auto;right:0}.ui-button{padding:.4em 1em;display:inline-block;position:relative;line-height:normal;margin-right:.1em;cursor:pointer;vertical-align:middle;text-align:center;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:visible}.ui-button,.ui-button:link,.ui-button:visited,.ui-button:hover,.ui-button:active{text-decoration:none}.ui-button-icon-only{width:2em;box-sizing:border-box;text-indent:-9999px;white-space:nowrap}input.ui-button.ui-button-icon-only{text-indent:0}.ui-button-icon-only .ui-icon{position:absolute;top:50%;left:50%;margin-top:-8px;margin-left:-8px}.ui-button.ui-icon-notext .ui-icon{padding:0;width:2.1em;height:2.1em;text-indent:-9999px;white-space:nowrap}input.ui-button.ui-icon-notext .ui-icon{width:auto;height:auto;text-indent:0;white-space:normal;padding:.4em 1em}input.ui-button::-moz-focus-inner,button.ui-button::-moz-focus-inner{border:0;padding:0}.ui-controlgroup{vertical-align:middle;display:inline-block}.ui-controlgroup > .ui-controlgroup-item{float:left;margin-left:0;margin-right:0}.ui-controlgroup > .ui-controlgroup-item:focus,.ui-controlgroup > .ui-controlgroup-item.ui-visual-focus{z-index:9999}.ui-controlgroup-vertical > .ui-controlgroup-item{display:block;float:none;width:100%;margin-top:0;margin-bottom:0;text-align:left}.ui-controlgroup-vertical .ui-controlgroup-item{box-sizing:border-box}.ui-controlgroup .ui-controlgroup-label{padding:.4em 1em}.ui-controlgroup .ui-controlgroup-label span{font-size:80%}.ui-controlgroup-horizontal .ui-controlgroup-label + .ui-controlgroup-item{border-left:none}.ui-controlgroup-vertical .ui-controlgroup-label + .ui-controlgroup-item{border-top:none}.ui-controlgroup-horizontal .ui-controlgroup-label.ui-widget-content{border-right:none}.ui-controlgroup-vertical .ui-controlgroup-label.ui-widget-content{border-bottom:none}.ui-controlgroup-vertical .ui-spinner-input{width:75%;width:calc( 100% - 2.4em )}.ui-controlgroup-vertical .ui-spinner .ui-spinner-up{border-top-style:solid}.ui-checkboxradio-label .ui-icon-background{box-shadow:inset 1px 1px 1px #ccc;border-radius:.12em;border:none}.ui-checkboxradio-radio-label .ui-icon-background{width:16px;height:16px;border-radius:1em;overflow:visible;border:none}.ui-checkboxradio-radio-label.ui-checkboxradio-checked .ui-icon,.ui-checkboxradio-radio-label.ui-checkboxradio-checked:hover .ui-icon{background-image:none;width:8px;height:8px;border-width:4px;border-style:solid}.ui-checkboxradio-disabled{pointer-events:none}.ui-datepicker{width:17em;padding:.2em .2em 0;display:none}.ui-datepicker .ui-datepicker-header{position:relative;padding:.2em 0}.ui-datepicker .ui-datepicker-prev,.ui-datepicker .ui-datepicker-next{position:absolute;top:2px;width:1.8em;height:1.8em}.ui-datepicker .ui-datepicker-prev-hover,.ui-datepicker .ui-datepicker-next-hover{top:1px}.ui-datepicker .ui-datepicker-prev{left:2px}.ui-datepicker .ui-datepicker-next{right:2px}.ui-datepicker .ui-datepicker-prev-hover{left:1px}.ui-datepicker .ui-datepicker-next-hover{right:1px}.ui-datepicker .ui-datepicker-prev span,.ui-datepicker .ui-datepicker-next span{display:block;position:absolute;left:50%;margin-left:-8px;top:50%;margin-top:-8px}.ui-datepicker .ui-datepicker-title{margin:0 2.3em;line-height:1.8em;text-align:center}.ui-datepicker .ui-datepicker-title select{font-size:1em;margin:1px 0}.ui-datepicker select.ui-datepicker-month,.ui-datepicker select.ui-datepicker-year{width:45%}.ui-datepicker table{width:100%;font-size:.9em;border-collapse:collapse;margin:0 0 .4em}.ui-datepicker th{padding:.7em .3em;text-align:center;font-weight:bold;border:0}.ui-datepicker td{border:0;padding:1px}.ui-datepicker td span,.ui-datepicker td a{display:block;padding:.2em;text-align:right;text-decoration:none}.ui-datepicker .ui-datepicker-buttonpane{background-image:none;margin:.7em 0 0 0;padding:0 .2em;border-left:0;border-right:0;border-bottom:0}.ui-datepicker .ui-datepicker-buttonpane button{float:right;margin:.5em .2em .4em;cursor:pointer;padding:.2em .6em .3em .6em;width:auto;overflow:visible}.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current{float:left}.ui-datepicker.ui-datepicker-multi{width:auto}.ui-datepicker-multi .ui-datepicker-group{float:left}.ui-datepicker-multi .ui-datepicker-group table{width:95%;margin:0 auto .4em}.ui-datepicker-multi-2 .ui-datepicker-group{width:50%}.ui-datepicker-multi-3 .ui-datepicker-group{width:33.3%}.ui-datepicker-multi-4 .ui-datepicker-group{width:25%}.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header{border-left-width:0}.ui-datepicker-multi .ui-datepicker-buttonpane{clear:left}.ui-datepicker-row-break{clear:both;width:100%;font-size:0}.ui-datepicker-rtl{direction:rtl}.ui-datepicker-rtl .ui-datepicker-prev{right:2px;left:auto}.ui-datepicker-rtl .ui-datepicker-next{left:2px;right:auto}.ui-datepicker-rtl .ui-datepicker-prev:hover{right:1px;left:auto}.ui-datepicker-rtl .ui-datepicker-next:hover{left:1px;right:auto}.ui-datepicker-rtl .ui-datepicker-buttonpane{clear:right}.ui-datepicker-rtl .ui-datepicker-buttonpane button{float:left}.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current,.ui-datepicker-rtl .ui-datepicker-group{float:right}.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header,.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header{border-right-width:0;border-left-width:1px}.ui-datepicker .ui-icon{display:block;text-indent:-99999px;overflow:hidden;background-repeat:no-repeat;left:.5em;top:.3em}.ui-dialog{position:absolute;top:0;left:0;padding:.2em;outline:0}.ui-dialog .ui-dialog-titlebar{padding:.4em 1em;position:relative}.ui-dialog .ui-dialog-title{float:left;margin:.1em 0;white-space:nowrap;width:90%;overflow:hidden;text-overflow:ellipsis}.ui-dialog .ui-dialog-titlebar-close{position:absolute;right:.3em;top:50%;width:20px;margin:-10px 0 0 0;padding:1px;height:20px}.ui-dialog .ui-dialog-content{position:relative;border:0;padding:.5em 1em;background:none;overflow:auto}.ui-dialog .ui-dialog-buttonpane{text-align:left;border-width:1px 0 0 0;background-image:none;margin-top:.5em;padding:.3em 1em .5em .4em}.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset{float:right}.ui-dialog .ui-dialog-buttonpane button{margin:.5em .4em .5em 0;cursor:pointer}.ui-dialog .ui-resizable-n{height:2px;top:0}.ui-dialog .ui-resizable-e{width:2px;right:0}.ui-dialog .ui-resizable-s{height:2px;bottom:0}.ui-dialog .ui-resizable-w{width:2px;left:0}.ui-dialog .ui-resizable-se,.ui-dialog .ui-resizable-sw,.ui-dialog .ui-resizable-ne,.ui-dialog .ui-resizable-nw{width:7px;height:7px}.ui-dialog .ui-resizable-se{right:0;bottom:0}.ui-dialog .ui-resizable-sw{left:0;bottom:0}.ui-dialog .ui-resizable-ne{right:0;top:0}.ui-dialog .ui-resizable-nw{left:0;top:0}.ui-draggable .ui-dialog-titlebar{cursor:move}.ui-draggable-handle{-ms-touch-action:none;touch-action:none}.ui-resizable{position:relative}.ui-resizable-handle{position:absolute;font-size:0.1px;display:block;-ms-touch-action:none;touch-action:none}.ui-resizable-disabled .ui-resizable-handle,.ui-resizable-autohide .ui-resizable-handle{display:none}.ui-resizable-n{cursor:n-resize;height:7px;width:100%;top:-5px;left:0}.ui-resizable-s{cursor:s-resize;height:7px;width:100%;bottom:-5px;left:0}.ui-resizable-e{cursor:e-resize;width:7px;right:-5px;top:0;height:100%}.ui-resizable-w{cursor:w-resize;width:7px;left:-5px;top:0;height:100%}.ui-resizable-se{cursor:se-resize;width:12px;height:12px;right:1px;bottom:1px}.ui-resizable-sw{cursor:sw-resize;width:9px;height:9px;left:-5px;bottom:-5px}.ui-resizable-nw{cursor:nw-resize;width:9px;height:9px;left:-5px;top:-5px}.ui-resizable-ne{cursor:ne-resize;width:9px;height:9px;right:-5px;top:-5px}.ui-progressbar{height:2em;text-align:left;overflow:hidden}.ui-progressbar .ui-progressbar-value{margin:-1px;height:100%}.ui-progressbar .ui-progressbar-overlay{background:url("data:image/gif;base64,R0lGODlhKAAoAIABAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAQABACwAAAAAKAAoAAACkYwNqXrdC52DS06a7MFZI+4FHBCKoDeWKXqymPqGqxvJrXZbMx7Ttc+w9XgU2FB3lOyQRWET2IFGiU9m1frDVpxZZc6bfHwv4c1YXP6k1Vdy292Fb6UkuvFtXpvWSzA+HycXJHUXiGYIiMg2R6W459gnWGfHNdjIqDWVqemH2ekpObkpOlppWUqZiqr6edqqWQAAIfkECQEAAQAsAAAAACgAKAAAApSMgZnGfaqcg1E2uuzDmmHUBR8Qil95hiPKqWn3aqtLsS18y7G1SzNeowWBENtQd+T1JktP05nzPTdJZlR6vUxNWWjV+vUWhWNkWFwxl9VpZRedYcflIOLafaa28XdsH/ynlcc1uPVDZxQIR0K25+cICCmoqCe5mGhZOfeYSUh5yJcJyrkZWWpaR8doJ2o4NYq62lAAACH5BAkBAAEALAAAAAAoACgAAAKVDI4Yy22ZnINRNqosw0Bv7i1gyHUkFj7oSaWlu3ovC8GxNso5fluz3qLVhBVeT/Lz7ZTHyxL5dDalQWPVOsQWtRnuwXaFTj9jVVh8pma9JjZ4zYSj5ZOyma7uuolffh+IR5aW97cHuBUXKGKXlKjn+DiHWMcYJah4N0lYCMlJOXipGRr5qdgoSTrqWSq6WFl2ypoaUAAAIfkECQEAAQAsAAAAACgAKAAAApaEb6HLgd/iO7FNWtcFWe+ufODGjRfoiJ2akShbueb0wtI50zm02pbvwfWEMWBQ1zKGlLIhskiEPm9R6vRXxV4ZzWT2yHOGpWMyorblKlNp8HmHEb/lCXjcW7bmtXP8Xt229OVWR1fod2eWqNfHuMjXCPkIGNileOiImVmCOEmoSfn3yXlJWmoHGhqp6ilYuWYpmTqKUgAAIfkECQEAAQAsAAAAACgAKAAAApiEH6kb58biQ3FNWtMFWW3eNVcojuFGfqnZqSebuS06w5V80/X02pKe8zFwP6EFWOT1lDFk8rGERh1TTNOocQ61Hm4Xm2VexUHpzjymViHrFbiELsefVrn6XKfnt2Q9G/+Xdie499XHd2g4h7ioOGhXGJboGAnXSBnoBwKYyfioubZJ2Hn0RuRZaflZOil56Zp6iioKSXpUAAAh+QQJAQABACwAAAAAKAAoAAACkoQRqRvnxuI7kU1a1UU5bd5tnSeOZXhmn5lWK3qNTWvRdQxP8qvaC+/yaYQzXO7BMvaUEmJRd3TsiMAgswmNYrSgZdYrTX6tSHGZO73ezuAw2uxuQ+BbeZfMxsexY35+/Qe4J1inV0g4x3WHuMhIl2jXOKT2Q+VU5fgoSUI52VfZyfkJGkha6jmY+aaYdirq+lQAACH5BAkBAAEALAAAAAAoACgAAAKWBIKpYe0L3YNKToqswUlvznigd4wiR4KhZrKt9Upqip61i9E3vMvxRdHlbEFiEXfk9YARYxOZZD6VQ2pUunBmtRXo1Lf8hMVVcNl8JafV38aM2/Fu5V16Bn63r6xt97j09+MXSFi4BniGFae3hzbH9+hYBzkpuUh5aZmHuanZOZgIuvbGiNeomCnaxxap2upaCZsq+1kAACH5BAkBAAEALAAAAAAoACgAAAKXjI8By5zf4kOxTVrXNVlv1X0d8IGZGKLnNpYtm8Lr9cqVeuOSvfOW79D9aDHizNhDJidFZhNydEahOaDH6nomtJjp1tutKoNWkvA6JqfRVLHU/QUfau9l2x7G54d1fl995xcIGAdXqMfBNadoYrhH+Mg2KBlpVpbluCiXmMnZ2Sh4GBqJ+ckIOqqJ6LmKSllZmsoq6wpQAAAh+QQJAQABACwAAAAAKAAoAAAClYx/oLvoxuJDkU1a1YUZbJ59nSd2ZXhWqbRa2/gF8Gu2DY3iqs7yrq+xBYEkYvFSM8aSSObE+ZgRl1BHFZNr7pRCavZ5BW2142hY3AN/zWtsmf12p9XxxFl2lpLn1rseztfXZjdIWIf2s5dItwjYKBgo9yg5pHgzJXTEeGlZuenpyPmpGQoKOWkYmSpaSnqKileI2FAAACH5BAkBAAEALAAAAAAoACgAAAKVjB+gu+jG4kORTVrVhRlsnn2dJ3ZleFaptFrb+CXmO9OozeL5VfP99HvAWhpiUdcwkpBH3825AwYdU8xTqlLGhtCosArKMpvfa1mMRae9VvWZfeB2XfPkeLmm18lUcBj+p5dnN8jXZ3YIGEhYuOUn45aoCDkp16hl5IjYJvjWKcnoGQpqyPlpOhr3aElaqrq56Bq7VAAAOw==");height:100%;filter:alpha(opacity=25);opacity:0.25}.ui-progressbar-indeterminate .ui-progressbar-value{background-image:none}.ui-selectable{-ms-touch-action:none;touch-action:none}.ui-selectable-helper{position:absolute;z-index:100;border:1px dotted black}.ui-selectmenu-menu{padding:0;margin:0;position:absolute;top:0;left:0;display:none}.ui-selectmenu-menu .ui-menu{overflow:auto;overflow-x:hidden;padding-bottom:1px}.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup{font-size:1em;font-weight:bold;line-height:1.5;padding:2px 0.4em;margin:0.5em 0 0 0;height:auto;border:0}.ui-selectmenu-open{display:block}.ui-selectmenu-text{display:block;margin-right:20px;overflow:hidden;text-overflow:ellipsis}.ui-selectmenu-button.ui-button{text-align:left;white-space:nowrap;width:14em}.ui-selectmenu-icon.ui-icon{float:right;margin-top:0}.ui-slider{position:relative;text-align:left}.ui-slider .ui-slider-handle{position:absolute;z-index:2;width:1.2em;height:1.2em;cursor:default;-ms-touch-action:none;touch-action:none}.ui-slider .ui-slider-range{position:absolute;z-index:1;font-size:.7em;display:block;border:0;background-position:0 0}.ui-slider.ui-state-disabled .ui-slider-handle,.ui-slider.ui-state-disabled .ui-slider-range{filter:inherit}.ui-slider-horizontal{height:.8em}.ui-slider-horizontal .ui-slider-handle{top:-.3em;margin-left:-.6em}.ui-slider-horizontal .ui-slider-range{top:0;height:100%}.ui-slider-horizontal .ui-slider-range-min{left:0}.ui-slider-horizontal .ui-slider-range-max{right:0}.ui-slider-vertical{width:.8em;height:100px}.ui-slider-vertical .ui-slider-handle{left:-.3em;margin-left:0;margin-bottom:-.6em}.ui-slider-vertical .ui-slider-range{left:0;width:100%}.ui-slider-vertical .ui-slider-range-min{bottom:0}.ui-slider-vertical .ui-slider-range-max{top:0}.ui-sortable-handle{-ms-touch-action:none;touch-action:none}.ui-spinner{position:relative;display:inline-block;overflow:hidden;padding:0;vertical-align:middle}.ui-spinner-input{border:none;background:none;color:inherit;padding:.222em 0;margin:.2em 0;vertical-align:middle;margin-left:.4em;margin-right:2em}.ui-spinner-button{width:1.6em;height:50%;font-size:.5em;padding:0;margin:0;text-align:center;position:absolute;cursor:default;display:block;overflow:hidden;right:0}.ui-spinner a.ui-spinner-button{border-top-style:none;border-bottom-style:none;border-right-style:none}.ui-spinner-up{top:0}.ui-spinner-down{bottom:0}.ui-tabs{position:relative;padding:.2em}.ui-tabs .ui-tabs-nav{margin:0;padding:.2em .2em 0}.ui-tabs .ui-tabs-nav li{list-style:none;float:left;position:relative;top:0;margin:1px .2em 0 0;border-bottom-width:0;padding:0;white-space:nowrap}.ui-tabs .ui-tabs-nav .ui-tabs-anchor{float:left;padding:.5em 1em;text-decoration:none}.ui-tabs .ui-tabs-nav li.ui-tabs-active{margin-bottom:-1px;padding-bottom:1px}.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor,.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor{cursor:text}.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor{cursor:pointer}.ui-tabs .ui-tabs-panel{display:block;border-width:0;padding:1em 1.4em;background:none}.ui-tooltip{padding:8px;position:absolute;z-index:9999;max-width:300px}body .ui-tooltip{border-width:2px}.ui-widget{font-family:Trebuchet MS,Tahoma,Verdana,Arial,sans-serif;font-size:1.1em}.ui-widget .ui-widget{font-size:1em}.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button{font-family:Trebuchet MS,Tahoma,Verdana,Arial,sans-serif;font-size:1em}.ui-widget.ui-widget-content{border:1px solid #ccc}.ui-widget-content{border:1px solid #ddd;background:#eee url("images/ui-bg_highlight-soft_100_eeeeee_1x100.png") 50% top repeat-x;color:#333}.ui-widget-content a{color:#333}.ui-widget-header{border:1px solid #e78f08;background:#f6a828 url("images/ui-bg_gloss-wave_35_f6a828_500x100.png") 50% 50% repeat-x;color:#fff;font-weight:bold}.ui-widget-header a{color:#fff}.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default,.ui-button,html .ui-button.ui-state-disabled:hover,html .ui-button.ui-state-disabled:active{border:1px solid #ccc;background:#f6f6f6 url("images/ui-bg_glass_100_f6f6f6_1x400.png") 50% 50% repeat-x;font-weight:bold;color:#1c94c4}.ui-state-default a,.ui-state-default a:link,.ui-state-default a:visited,a.ui-button,a:link.ui-button,a:visited.ui-button,.ui-button{color:#1c94c4;text-decoration:none}.ui-state-hover,.ui-widget-content .ui-state-hover,.ui-widget-header .ui-state-hover,.ui-state-focus,.ui-widget-content .ui-state-focus,.ui-widget-header .ui-state-focus,.ui-button:hover,.ui-button:focus{border:1px solid #fbcb09;background:#fdf5ce url("images/ui-bg_glass_100_fdf5ce_1x400.png") 50% 50% repeat-x;font-weight:bold;color:#c77405}.ui-state-hover a,.ui-state-hover a:hover,.ui-state-hover a:link,.ui-state-hover a:visited,.ui-state-focus a,.ui-state-focus a:hover,.ui-state-focus a:link,.ui-state-focus a:visited,a.ui-button:hover,a.ui-button:focus{color:#c77405;text-decoration:none}.ui-visual-focus{box-shadow:0 0 3px 1px rgb(94,158,214)}.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active,a.ui-button:active,.ui-button:active,.ui-button.ui-state-active:hover{border:1px solid #fbd850;background:#fff url("images/ui-bg_glass_65_ffffff_1x400.png") 50% 50% repeat-x;font-weight:bold;color:#eb8f00}.ui-icon-background,.ui-state-active .ui-icon-background{border:#fbd850;background-color:#eb8f00}.ui-state-active a,.ui-state-active a:link,.ui-state-active a:visited{color:#eb8f00;text-decoration:none}.ui-state-highlight,.ui-widget-content .ui-state-highlight,.ui-widget-header .ui-state-highlight{border:1px solid #fed22f;background:#ffe45c url("images/ui-bg_highlight-soft_75_ffe45c_1x100.png") 50% top repeat-x;color:#363636}.ui-state-checked{border:1px solid #fed22f;background:#ffe45c}.ui-state-highlight a,.ui-widget-content .ui-state-highlight a,.ui-widget-header .ui-state-highlight a{color:#363636}.ui-state-error,.ui-widget-content .ui-state-error,.ui-widget-header .ui-state-error{border:1px solid #cd0a0a;background:#b81900 url("images/ui-bg_diagonals-thick_18_b81900_40x40.png") 50% 50% repeat;color:#fff}.ui-state-error a,.ui-widget-content .ui-state-error a,.ui-widget-header .ui-state-error a{color:#fff}.ui-state-error-text,.ui-widget-content .ui-state-error-text,.ui-widget-header .ui-state-error-text{color:#fff}.ui-priority-primary,.ui-widget-content .ui-priority-primary,.ui-widget-header .ui-priority-primary{font-weight:bold}.ui-priority-secondary,.ui-widget-content .ui-priority-secondary,.ui-widget-header .ui-priority-secondary{opacity:.7;filter:Alpha(Opacity=70);font-weight:normal}.ui-state-disabled,.ui-widget-content .ui-state-disabled,.ui-widget-header .ui-state-disabled{opacity:.35;filter:Alpha(Opacity=35);background-image:none}.ui-state-disabled .ui-icon{filter:Alpha(Opacity=35)}.ui-icon{width:16px;height:16px}.ui-icon,.ui-widget-content .ui-icon{background-image:url("images/ui-icons_222222_256x240.png")}.ui-widget-header .ui-icon{background-image:url("images/ui-icons_ffffff_256x240.png")}.ui-state-hover .ui-icon,.ui-state-focus .ui-icon,.ui-button:hover .ui-icon,.ui-button:focus .ui-icon{background-image:url("images/ui-icons_ef8c08_256x240.png")}.ui-state-active .ui-icon,.ui-button:active .ui-icon{background-image:url("images/ui-icons_ef8c08_256x240.png")}.ui-state-highlight .ui-icon,.ui-button .ui-state-highlight.ui-icon{background-image:url("images/ui-icons_228ef1_256x240.png")}.ui-state-error .ui-icon,.ui-state-error-text .ui-icon{background-image:url("images/ui-icons_ffd27a_256x240.png")}.ui-button .ui-icon{background-image:url("images/ui-icons_ef8c08_256x240.png")}.ui-icon-blank{background-position:16px 16px}.ui-icon-caret-1-n{background-position:0 0}.ui-icon-caret-1-ne{background-position:-16px 0}.ui-icon-caret-1-e{background-position:-32px 0}.ui-icon-caret-1-se{background-position:-48px 0}.ui-icon-caret-1-s{background-position:-65px 0}.ui-icon-caret-1-sw{background-position:-80px 0}.ui-icon-caret-1-w{background-position:-96px 0}.ui-icon-caret-1-nw{background-position:-112px 0}.ui-icon-caret-2-n-s{background-position:-128px 0}.ui-icon-caret-2-e-w{background-position:-144px 0}.ui-icon-triangle-1-n{background-position:0 -16px}.ui-icon-triangle-1-ne{background-position:-16px -16px}.ui-icon-triangle-1-e{background-position:-32px -16px}.ui-icon-triangle-1-se{background-position:-48px -16px}.ui-icon-triangle-1-s{background-position:-65px -16px}.ui-icon-triangle-1-sw{background-position:-80px -16px}.ui-icon-triangle-1-w{background-position:-96px -16px}.ui-icon-triangle-1-nw{background-position:-112px -16px}.ui-icon-triangle-2-n-s{background-position:-128px -16px}.ui-icon-triangle-2-e-w{background-position:-144px -16px}.ui-icon-arrow-1-n{background-position:0 -32px}.ui-icon-arrow-1-ne{background-position:-16px -32px}.ui-icon-arrow-1-e{background-position:-32px -32px}.ui-icon-arrow-1-se{background-position:-48px -32px}.ui-icon-arrow-1-s{background-position:-65px -32px}.ui-icon-arrow-1-sw{background-position:-80px -32px}.ui-icon-arrow-1-w{background-position:-96px -32px}.ui-icon-arrow-1-nw{background-position:-112px -32px}.ui-icon-arrow-2-n-s{background-position:-128px -32px}.ui-icon-arrow-2-ne-sw{background-position:-144px -32px}.ui-icon-arrow-2-e-w{background-position:-160px -32px}.ui-icon-arrow-2-se-nw{background-position:-176px -32px}.ui-icon-arrowstop-1-n{background-position:-192px -32px}.ui-icon-arrowstop-1-e{background-position:-208px -32px}.ui-icon-arrowstop-1-s{background-position:-224px -32px}.ui-icon-arrowstop-1-w{background-position:-240px -32px}.ui-icon-arrowthick-1-n{background-position:1px -48px}.ui-icon-arrowthick-1-ne{background-position:-16px -48px}.ui-icon-arrowthick-1-e{background-position:-32px -48px}.ui-icon-arrowthick-1-se{background-position:-48px -48px}.ui-icon-arrowthick-1-s{background-position:-64px -48px}.ui-icon-arrowthick-1-sw{background-position:-80px -48px}.ui-icon-arrowthick-1-w{background-position:-96px -48px}.ui-icon-arrowthick-1-nw{background-position:-112px -48px}.ui-icon-arrowthick-2-n-s{background-position:-128px -48px}.ui-icon-arrowthick-2-ne-sw{background-position:-144px -48px}.ui-icon-arrowthick-2-e-w{background-position:-160px -48px}.ui-icon-arrowthick-2-se-nw{background-position:-176px -48px}.ui-icon-arrowthickstop-1-n{background-position:-192px -48px}.ui-icon-arrowthickstop-1-e{background-position:-208px -48px}.ui-icon-arrowthickstop-1-s{background-position:-224px -48px}.ui-icon-arrowthickstop-1-w{background-position:-240px -48px}.ui-icon-arrowreturnthick-1-w{background-position:0 -64px}.ui-icon-arrowreturnthick-1-n{background-position:-16px -64px}.ui-icon-arrowreturnthick-1-e{background-position:-32px -64px}.ui-icon-arrowreturnthick-1-s{background-position:-48px -64px}.ui-icon-arrowreturn-1-w{background-position:-64px -64px}.ui-icon-arrowreturn-1-n{background-position:-80px -64px}.ui-icon-arrowreturn-1-e{background-position:-96px -64px}.ui-icon-arrowreturn-1-s{background-position:-112px -64px}.ui-icon-arrowrefresh-1-w{background-position:-128px -64px}.ui-icon-arrowrefresh-1-n{background-position:-144px -64px}.ui-icon-arrowrefresh-1-e{background-position:-160px -64px}.ui-icon-arrowrefresh-1-s{background-position:-176px -64px}.ui-icon-arrow-4{background-position:0 -80px}.ui-icon-arrow-4-diag{background-position:-16px -80px}.ui-icon-extlink{background-position:-32px -80px}.ui-icon-newwin{background-position:-48px -80px}.ui-icon-refresh{background-position:-64px -80px}.ui-icon-shuffle{background-position:-80px -80px}.ui-icon-transfer-e-w{background-position:-96px -80px}.ui-icon-transferthick-e-w{background-position:-112px -80px}.ui-icon-folder-collapsed{background-position:0 -96px}.ui-icon-folder-open{background-position:-16px -96px}.ui-icon-document{background-position:-32px -96px}.ui-icon-document-b{background-position:-48px -96px}.ui-icon-note{background-position:-64px -96px}.ui-icon-mail-closed{background-position:-80px -96px}.ui-icon-mail-open{background-position:-96px -96px}.ui-icon-suitcase{background-position:-112px -96px}.ui-icon-comment{background-position:-128px -96px}.ui-icon-person{background-position:-144px -96px}.ui-icon-print{background-position:-160px -96px}.ui-icon-trash{background-position:-176px -96px}.ui-icon-locked{background-position:-192px -96px}.ui-icon-unlocked{background-position:-208px -96px}.ui-icon-bookmark{background-position:-224px -96px}.ui-icon-tag{background-position:-240px -96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px -112px}.ui-icon-calendar{background-position:-32px -112px}.ui-icon-cart{background-position:-48px -112px}.ui-icon-pencil{background-position:-64px -112px}.ui-icon-clock{background-position:-80px -112px}.ui-icon-disk{background-position:-96px -112px}.ui-icon-calculator{background-position:-112px -112px}.ui-icon-zoomin{background-position:-128px -112px}.ui-icon-zoomout{background-position:-144px -112px}.ui-icon-search{background-position:-160px -112px}.ui-icon-wrench{background-position:-176px -112px}.ui-icon-gear{background-position:-192px -112px}.ui-icon-heart{background-position:-208px -112px}.ui-icon-star{background-position:-224px -112px}.ui-icon-link{background-position:-240px -112px}.ui-icon-cancel{background-position:0 -128px}.ui-icon-plus{background-position:-16px -128px}.ui-icon-plusthick{background-position:-32px -128px}.ui-icon-minus{background-position:-48px -128px}.ui-icon-minusthick{background-position:-64px -128px}.ui-icon-close{background-position:-80px -128px}.ui-icon-closethick{background-position:-96px -128px}.ui-icon-key{background-position:-112px -128px}.ui-icon-lightbulb{background-position:-128px -128px}.ui-icon-scissors{background-position:-144px -128px}.ui-icon-clipboard{background-position:-160px -128px}.ui-icon-copy{background-position:-176px -128px}.ui-icon-contact{background-position:-192px -128px}.ui-icon-image{background-position:-208px -128px}.ui-icon-video{background-position:-224px -128px}.ui-icon-script{background-position:-240px -128px}.ui-icon-alert{background-position:0 -144px}.ui-icon-info{background-position:-16px -144px}.ui-icon-notice{background-position:-32px -144px}.ui-icon-help{background-position:-48px -144px}.ui-icon-check{background-position:-64px -144px}.ui-icon-bullet{background-position:-80px -144px}.ui-icon-radio-on{background-position:-96px -144px}.ui-icon-radio-off{background-position:-112px -144px}.ui-icon-pin-w{background-position:-128px -144px}.ui-icon-pin-s{background-position:-144px -144px}.ui-icon-play{background-position:0 -160px}.ui-icon-pause{background-position:-16px -160px}.ui-icon-seek-next{background-position:-32px -160px}.ui-icon-seek-prev{background-position:-48px -160px}.ui-icon-seek-end{background-position:-64px -160px}.ui-icon-seek-start{background-position:-80px -160px}.ui-icon-seek-first{background-position:-80px -160px}.ui-icon-stop{background-position:-96px -160px}.ui-icon-eject{background-position:-112px -160px}.ui-icon-volume-off{background-position:-128px -160px}.ui-icon-volume-on{background-position:-144px -160px}.ui-icon-power{background-position:0 -176px}.ui-icon-signal-diag{background-position:-16px -176px}.ui-icon-signal{background-position:-32px -176px}.ui-icon-battery-0{background-position:-48px -176px}.ui-icon-battery-1{background-position:-64px -176px}.ui-icon-battery-2{background-position:-80px -176px}.ui-icon-battery-3{background-position:-96px -176px}.ui-icon-circle-plus{background-position:0 -192px}.ui-icon-circle-minus{background-position:-16px -192px}.ui-icon-circle-close{background-position:-32px -192px}.ui-icon-circle-triangle-e{background-position:-48px -192px}.ui-icon-circle-triangle-s{background-position:-64px -192px}.ui-icon-circle-triangle-w{background-position:-80px -192px}.ui-icon-circle-triangle-n{background-position:-96px -192px}.ui-icon-circle-arrow-e{background-position:-112px -192px}.ui-icon-circle-arrow-s{background-position:-128px -192px}.ui-icon-circle-arrow-w{background-position:-144px -192px}.ui-icon-circle-arrow-n{background-position:-160px -192px}.ui-icon-circle-zoomin{background-position:-176px -192px}.ui-icon-circle-zoomout{background-position:-192px -192px}.ui-icon-circle-check{background-position:-208px -192px}.ui-icon-circlesmall-plus{background-position:0 -208px}.ui-icon-circlesmall-minus{background-position:-16px -208px}.ui-icon-circlesmall-close{background-position:-32px -208px}.ui-icon-squaresmall-plus{background-position:-48px -208px}.ui-icon-squaresmall-minus{background-position:-64px -208px}.ui-icon-squaresmall-close{background-position:-80px -208px}.ui-icon-grip-dotted-vertical{background-position:0 -224px}.ui-icon-grip-dotted-horizontal{background-position:-16px -224px}.ui-icon-grip-solid-vertical{background-position:-32px -224px}.ui-icon-grip-solid-horizontal{background-position:-48px -224px}.ui-icon-gripsmall-diagonal-se{background-position:-64px -224px}.ui-icon-grip-diagonal-se{background-position:-80px -224px}.ui-corner-all,.ui-corner-top,.ui-corner-left,.ui-corner-tl{border-top-left-radius:4px}.ui-corner-all,.ui-corner-top,.ui-corner-right,.ui-corner-tr{border-top-right-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-left,.ui-corner-bl{border-bottom-left-radius:4px}.ui-corner-all,.ui-corner-bottom,.ui-corner-right,.ui-corner-br{border-bottom-right-radius:4px}.ui-widget-overlay{background:#666 url("images/ui-bg_diagonals-thick_20_666666_40x40.png") 50% 50% repeat;opacity:.5;filter:Alpha(Opacity=50)}.ui-widget-shadow{-webkit-box-shadow:-5px -5px 5px #000;box-shadow:-5px -5px 5px #000}
27182812/ChatGLM-LLaMA-chinese-insturct
10,809
src/transformers/processing_utils.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. """ Processing saving/loading class for common processors. """ import os from pathlib import Path from .dynamic_module_utils import custom_object_save from .tokenization_utils_base import PreTrainedTokenizerBase from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging logger = logging.get_logger(__name__) # Dynamically import the Transformers module to grab the attribute classes of the processor form their names. transformers_module = direct_transformers_import(Path(__file__).parent) AUTO_TO_BASE_CLASS_MAPPING = { "AutoTokenizer": "PreTrainedTokenizerBase", "AutoFeatureExtractor": "FeatureExtractionMixin", "AutoImageProcessor": "ImageProcessingMixin", } class ProcessorMixin(PushToHubMixin): """ This is a mixin used to provide saving/loading functionality for all processor classes. """ attributes = ["feature_extractor", "tokenizer"] # Names need to be attr_class for attr in attributes feature_extractor_class = None tokenizer_class = None _auto_class = None # args have to match the attributes class attribute def __init__(self, *args, **kwargs): # Sanitize args and kwargs for key in kwargs: if key not in self.attributes: raise TypeError(f"Unexpected keyword argument {key}.") for arg, attribute_name in zip(args, self.attributes): if attribute_name in kwargs: raise TypeError(f"Got multiple values for argument {attribute_name}.") else: kwargs[attribute_name] = arg if len(kwargs) != len(self.attributes): raise ValueError( f"This processor requires {len(self.attributes)} arguments: {', '.join(self.attributes)}. Got " f"{len(args)} arguments instead." ) # Check each arg is of the proper class (this will also catch a user initializing in the wrong order) for attribute_name, arg in kwargs.items(): class_name = getattr(self, f"{attribute_name}_class") # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class. class_name = AUTO_TO_BASE_CLASS_MAPPING.get(class_name, class_name) if isinstance(class_name, tuple): proper_class = tuple(getattr(transformers_module, n) for n in class_name if n is not None) else: proper_class = getattr(transformers_module, class_name) if not isinstance(arg, proper_class): raise ValueError( f"Received a {type(arg).__name__} for argument {attribute_name}, but a {class_name} was expected." ) setattr(self, attribute_name, arg) def __repr__(self): attributes_repr = [f"- {name}: {repr(getattr(self, name))}" for name in self.attributes] attributes_repr = "\n".join(attributes_repr) return f"{self.__class__.__name__}:\n{attributes_repr}" def save_pretrained(self, save_directory, push_to_hub: bool = False, **kwargs): """ Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it can be reloaded using the [`~ProcessorMixin.from_pretrained`] method. <Tip> This class method is simply calling [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] and [`~tokenization_utils_base.PreTrainedTokenizerBase.save_pretrained`]. Please refer to the docstrings of the methods above for more information. </Tip> Args: save_directory (`str` or `os.PathLike`): Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs: Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = self._create_repo(repo_id, **kwargs) files_timestamps = self._get_files_timestamps(save_directory) # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: attrs = [getattr(self, attribute_name) for attribute_name in self.attributes] configs = [(a.init_kwargs if isinstance(a, PreTrainedTokenizerBase) else a) for a in attrs] custom_object_save(self, save_directory, config=configs) for attribute_name in self.attributes: attribute = getattr(self, attribute_name) # Include the processor class in the attribute config so this processor can then be reloaded with the # `AutoProcessor` API. if hasattr(attribute, "_set_processor_class"): attribute._set_processor_class(self.__class__.__name__) attribute.save_pretrained(save_directory) if self._auto_class is not None: # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up. for attribute_name in self.attributes: attribute = getattr(self, attribute_name) if isinstance(attribute, PreTrainedTokenizerBase): del attribute.init_kwargs["auto_map"] if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("use_auth_token"), ) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a processor associated with a pretrained model. <Tip> This class method is simply calling the feature extractor [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`], image processor [`~image_processing_utils.ImageProcessingMixin`] and the tokenizer [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`] methods. Please refer to the docstrings of the methods above for more information. </Tip> Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a feature extractor file saved using the [`~SequenceFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved feature extractor JSON *file*, e.g., `./my_model_directory/preprocessor_config.json`. **kwargs Additional keyword arguments passed along to both [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] and [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`]. """ args = cls._get_arguments_from_pretrained(pretrained_model_name_or_path, **kwargs) return cls(*args) @classmethod def register_for_auto_class(cls, auto_class="AutoProcessor"): """ Register this class with a given auto class. This should only be used for custom feature extractors as the ones in the library are already mapped with `AutoProcessor`. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. </Tip> Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoProcessor"`): The auto class to register this new feature extractor with. """ if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f"{auto_class} is not a valid auto class.") cls._auto_class = auto_class @classmethod def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, **kwargs): args = [] for attribute_name in cls.attributes: class_name = getattr(cls, f"{attribute_name}_class") if isinstance(class_name, tuple): classes = tuple(getattr(transformers_module, n) if n is not None else None for n in class_name) use_fast = kwargs.get("use_fast", True) if use_fast and classes[1] is not None: attribute_class = classes[1] else: attribute_class = classes[0] else: attribute_class = getattr(transformers_module, class_name) args.append(attribute_class.from_pretrained(pretrained_model_name_or_path, **kwargs)) return args @property def model_input_names(self): first_attribute = getattr(self, self.attributes[0]) return getattr(first_attribute, "model_input_names", None) ProcessorMixin.push_to_hub = copy_func(ProcessorMixin.push_to_hub) if ProcessorMixin.push_to_hub.__doc__ is not None: ProcessorMixin.push_to_hub.__doc__ = ProcessorMixin.push_to_hub.__doc__.format( object="processor", object_class="AutoProcessor", object_files="processor files" )
274056675/springboot-openai-chatgpt
3,459
mng_web/src/page/login/codelogin.vue
<template> <el-form class="login-form" status-icon :rules="loginRules" ref="loginForm" :model="loginForm" label-width="0"> <el-form-item prop="phone"> <el-input size="small" @keyup.enter.native="handleLogin" v-model="loginForm.phone" auto-complete="off" :placeholder="$t('login.phone')"> <i slot="prefix" class="icon-shouji"/> </el-input> </el-form-item> <el-form-item prop="code"> <el-input size="small" @keyup.enter.native="handleLogin" v-model="loginForm.code" auto-complete="off" :placeholder="$t('login.code')"> <i slot="prefix" class="icon-yanzhengma" style="margin-top:6px;"/> <template slot="append"> <span @click="handleSend" class="msg-text" :class="[{display:msgKey}]">{{msgText}}</span> </template> </el-input> </el-form-item> <el-form-item> <el-button size="small" type="primary" @click.native.prevent="handleLogin" class="login-submit">{{$t('login.submit')}}</el-button> </el-form-item> </el-form> </template> <script> import { isvalidatemobile } from "@/util/validate"; import { mapGetters } from "vuex"; export default { name: "codelogin", data() { const validatePhone = (rule, value, callback) => { if (isvalidatemobile(value)[0]) { callback(new Error(isvalidatemobile(value)[1])); } else { callback(); } }; const validateCode = (rule, value, callback) => { if (value.length !== 4) { callback(new Error("请输入4位数的验证码")); } else { callback(); } }; return { msgText: "", msgTime: "", msgKey: false, loginForm: { phone: "", code: "" }, loginRules: { phone: [{ required: true, trigger: "blur", validator: validatePhone }], code: [{ required: true, trigger: "blur", validator: validateCode }] } }; }, created() { this.msgText = this.config.MSGINIT; this.msgTime = this.config.MSGTIME; }, mounted() {}, computed: { ...mapGetters(["tagWel"]), config() { return { MSGINIT: this.$t("login.msgText"), MSGSCUCCESS: this.$t("login.msgSuccess"), MSGTIME: 60 }; } }, props: [], methods: { handleSend() { if (this.msgKey) return; this.msgText = this.msgTime + this.config.MSGSCUCCESS; this.msgKey = true; const time = setInterval(() => { this.msgTime--; this.msgText = this.msgTime + this.config.MSGSCUCCESS; if (this.msgTime === 0) { this.msgTime = this.config.MSGTIME; this.msgText = this.config.MSGINIT; this.msgKey = false; clearInterval(time); } }, 1000); }, handleLogin() { this.$refs.loginForm.validate(valid => { if (valid) { this.$store.dispatch("LoginByPhone", this.loginForm).then(() => { this.$router.push({ path: this.tagWel.value }); }); } }); } } }; </script> <style> .msg-text { display: block; width: 60px; font-size: 12px; text-align: center; cursor: pointer; } .msg-text.display { color: #ccc; } </style>
27182812/ChatGLM-LLaMA-chinese-insturct
16,631
src/transformers/convert_pytorch_checkpoint_to_tf2.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 pytorch checkpoints to TensorFlow""" import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPT2Config, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, T5Config, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPT2LMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFT5ForConditionalGeneration, TFTransfoXLLMHeadModel, TFWav2Vec2Model, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, Wav2Vec2Config, Wav2Vec2Model, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tf2_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPT2LMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, T5ForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() MODEL_CLASSES = { "bart": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), "bert": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-cased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-base-cased-finetuned-mrpc": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "dpr": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), "gpt2": ( GPT2Config, TFGPT2LMHeadModel, GPT2LMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlnet": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm-roberta": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "transfo-xl": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "openai-gpt": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "roberta": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "layoutlm": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), "roberta-large-mnli": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "camembert": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "flaubert": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert-base-distilled-squad": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert-visual-feature-encoder": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "ctrl": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "albert": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "t5": ( T5Config, TFT5ForConditionalGeneration, T5ForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "electra": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "wav2vec2": ( Wav2Vec2Config, TFWav2Vec2Model, Wav2Vec2Model, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def convert_pt_checkpoint_to_tf( model_type, pytorch_checkpoint_path, config_file, tf_dump_path, compare_with_pt_model=False, use_cached_models=True ): if model_type not in MODEL_CLASSES: raise ValueError(f"Unrecognized model type, should be one of {list(MODEL_CLASSES.keys())}.") config_class, model_class, pt_model_class, aws_config_map = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: config_file = cached_file(config_file, CONFIG_NAME, force_download=not use_cached_models) config = config_class.from_json_file(config_file) config.output_hidden_states = True config.output_attentions = True print(f"Building TensorFlow model from configuration: {config}") tf_model = model_class(config) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): pytorch_checkpoint_path = cached_file( pytorch_checkpoint_path, WEIGHTS_NAME, force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: tf_model = load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path) if compare_with_pt_model: tfo = tf_model(tf_model.dummy_inputs, training=False) # build the network state_dict = torch.load(pytorch_checkpoint_path, map_location="cpu") pt_model = pt_model_class.from_pretrained( pretrained_model_name_or_path=None, config=config, state_dict=state_dict ) with torch.no_grad(): pto = pt_model(**pt_model.dummy_inputs) np_pt = pto[0].numpy() np_tf = tfo[0].numpy() diff = np.amax(np.abs(np_pt - np_tf)) print(f"Max absolute difference between models outputs {diff}") assert diff <= 2e-2, f"Error, model absolute difference is >2e-2: {diff}" # Save pytorch-model print(f"Save TensorFlow model to {tf_dump_path}") tf_model.save_weights(tf_dump_path, save_format="h5") def convert_all_pt_checkpoints_to_tf( args_model_type, tf_dump_path, model_shortcut_names_or_path=None, config_shortcut_names_or_path=None, compare_with_pt_model=False, use_cached_models=False, remove_cached_files=False, only_convert_finetuned_models=False, ): if args_model_type is None: model_types = list(MODEL_CLASSES.keys()) else: model_types = [args_model_type] for j, model_type in enumerate(model_types, start=1): print("=" * 100) print(f" Converting model type {j}/{len(model_types)}: {model_type}") print("=" * 100) if model_type not in MODEL_CLASSES: raise ValueError(f"Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys())}.") config_class, model_class, pt_model_class, aws_model_maps, aws_config_map = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: model_shortcut_names_or_path = list(aws_model_maps.keys()) if config_shortcut_names_or_path is None: config_shortcut_names_or_path = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(model_shortcut_names_or_path, config_shortcut_names_or_path), start=1 ): print("-" * 100) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(f" Skipping finetuned checkpoint {model_shortcut_name}") continue model_type = model_shortcut_name elif only_convert_finetuned_models: print(f" Skipping not finetuned checkpoint {model_shortcut_name}") continue print( f" Converting checkpoint {i}/{len(aws_config_map)}: {model_shortcut_name} - model_type {model_type}" ) print("-" * 100) if config_shortcut_name in aws_config_map: config_file = cached_file(config_shortcut_name, CONFIG_NAME, force_download=not use_cached_models) else: config_file = config_shortcut_name if model_shortcut_name in aws_model_maps: model_file = cached_file(model_shortcut_name, WEIGHTS_NAME, force_download=not use_cached_models) else: model_file = model_shortcut_name if os.path.isfile(model_shortcut_name): model_shortcut_name = "converted_model" convert_pt_checkpoint_to_tf( model_type=model_type, pytorch_checkpoint_path=model_file, config_file=config_file, tf_dump_path=os.path.join(tf_dump_path, model_shortcut_name + "-tf_model.h5"), compare_with_pt_model=compare_with_pt_model, ) if remove_cached_files: os.remove(config_file) os.remove(model_file) if __name__ == "__main__": parser = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_dump_path", default=None, type=str, required=True, help="Path to the output Tensorflow dump file." ) parser.add_argument( "--model_type", default=None, type=str, help=( f"Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and " "convert all the models from AWS." ), ) parser.add_argument( "--pytorch_checkpoint_path", default=None, type=str, help=( "Path to the PyTorch checkpoint path or shortcut name to download from AWS. " "If not given, will download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--config_file", default=None, type=str, help=( "The config json file corresponding to the pre-trained model. \n" "This specifies the model architecture. If not given and " "--pytorch_checkpoint_path is not given or is a shortcut name " "use the configuration associated to the shortcut name on the AWS" ), ) parser.add_argument( "--compare_with_pt_model", action="store_true", help="Compare Tensorflow and PyTorch model predictions." ) parser.add_argument( "--use_cached_models", action="store_true", help="Use cached models if possible instead of updating to latest checkpoint versions.", ) parser.add_argument( "--remove_cached_files", action="store_true", help="Remove pytorch models after conversion (save memory when converting in batches).", ) parser.add_argument("--only_convert_finetuned_models", action="store_true", help="Only convert finetuned models.") args = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
274056675/springboot-openai-chatgpt
3,754
mng_web/src/page/index/sidebar/sidebarItem.vue
<template> <div class="menu-wrapper"> <template v-for="item in menu"> <el-menu-item v-if="validatenull(item[childrenKey]) && vaildRoles(item)" :index="item[pathKey]" @click="open(item)" :key="item[labelKey]" :class="{'is-active':vaildAvtive(item)}"> <i :class="item[iconKey]"></i> <span slot="title" :alt="item[pathKey]">{{generateTitle(item)}}</span> </el-menu-item> <el-submenu v-else-if="!validatenull(item[childrenKey])&&vaildRoles(item)" :index="item[pathKey]" :key="item[labelKey]"> <template slot="title"> <i :class="item[iconKey]"></i> <span slot="title" :class="{'el-menu--display':collapse && first}">{{generateTitle(item)}}</span> </template> <template v-for="(child,cindex) in item[childrenKey]"> <el-menu-item :index="child[pathKey],cindex" @click="open(child)" :class="{'is-active':vaildAvtive(child)}" v-if="validatenull(child[childrenKey])" :key="child[labelKey]"> <i :class="child[iconKey]"></i> <span slot="title">{{generateTitle(child)}}</span> </el-menu-item> <sidebar-item v-else :menu="[child]" :key="cindex" :props="props" :screen="screen" :collapse="collapse"></sidebar-item> </template> </el-submenu> </template> </div> </template> <script> import { mapGetters } from "vuex"; import { validatenull } from "@/util/validate"; import config from "./config.js"; export default { name: "sidebarItem", data() { return { config: config }; }, props: { menu: { type: Array }, screen: { type: Number }, first: { type: Boolean, default: false }, props: { type: Object, default: () => { return {}; } }, collapse: { type: Boolean } }, created() {}, mounted() {}, computed: { ...mapGetters(["roles"]), labelKey() { return this.props.label || this.config.propsDefault.label; }, pathKey() { return this.props.path || this.config.propsDefault.path; }, iconKey() { return this.props.icon || this.config.propsDefault.icon; }, childrenKey() { return this.props.children || this.config.propsDefault.children; }, nowTagValue() { return this.$router.$avueRouter.getValue(this.$route); } }, methods: { generateTitle(item) { return this.$router.$avueRouter.generateTitle( item[this.labelKey], (item.meta || {}).i18n ); }, vaildAvtive(item) { const groupFlag = (item["group"] || []).some(ele => this.$route.path.includes(ele) ); return this.nowTagValue === item[this.pathKey] || groupFlag; }, vaildRoles(item) { item.meta = item.meta || {}; return item.meta.roles ? item.meta.roles.includes(this.roles) : true; }, validatenull(val) { return validatenull(val); }, open(item) { if (this.screen <= 1) this.$store.commit("SET_COLLAPSE"); this.$router.$avueRouter.group = item.group; this.$router.$avueRouter.meta = item.meta; this.$router.push({ path: this.$router.$avueRouter.getPath({ name: item[this.labelKey], src: item[this.pathKey], i18n: (item.meta || {}).i18n }), query: { ...item.query } }); } } }; </script>
233zzh/TitanDataOperationSystem
12,175
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/taskboard/css/lobilist.css
.lobilists .lobilist-wrapper, .lobilists .lobilist-placeholder { display: inline-block; float: left; border: 1px solid transparent; margin-bottom: 16px; width: 360px; margin-right: 16px; } .lobilists .lobilist { max-height: 100%; overflow: auto; background-color: #FFF; -webkit-box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1); box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1); } .lobilists .lobilist:last-child { margin-right: 0; } .lobilists .lobilist.ui-sortable-helper { -webkit-transform: rotate(2deg); -ms-transform: rotate(2deg); -o-transform: rotate(2deg); transform: rotate(2deg); } .lobilists .lobilist:hover .lobilist-actions { opacity: 1; } .lobilists .lobilist.lobilist-default { border: 1px solid #dddddd; } .lobilists .lobilist.lobilist-default .lobilist-header { border-bottom: 1px solid #dddddd; background-color: #eeeeee; } .lobilists .lobilist.lobilist-default .lobilist-header input { background-color: transparent; border-color: #555555; color: #555555; } .lobilists .lobilist.lobilist-default .lobilist-title { color: #555555; } .lobilists .lobilist.lobilist-default .lobilist-actions .btn { color: #555555; } .lobilists .lobilist.lobilist-default .btn-show-form { color: #555555; } .lobilists .lobilist.lobilist-default .lobilist-form-footer { border-top: 1px solid #dddddd; background-color: #eeeeee; } .lobilists .lobilist.lobilist-default .lobilist-footer { border-top: 1px solid #dddddd; background-color: #eeeeee; } .lobilists .lobilist.lobilist-danger { border: 1px solid #dc5f5c; } .lobilists .lobilist.lobilist-danger .lobilist-header { border-bottom: 1px solid #dc5f5c; background-color: #e27c79; } .lobilists .lobilist.lobilist-danger .lobilist-header input { background-color: transparent; border-color: #FFF; color: #FFF; } .lobilists .lobilist.lobilist-danger .lobilist-title { color: #FFF; } .lobilists .lobilist.lobilist-danger .lobilist-actions .btn { color: #FFF; } .lobilists .lobilist.lobilist-danger .btn-show-form { color: #FFF; } .lobilists .lobilist.lobilist-danger .lobilist-form-footer { border-top: 1px solid #dc5f5c; background-color: #e27c79; } .lobilists .lobilist.lobilist-danger .lobilist-footer { border-top: 1px solid #dc5f5c; background-color: #e27c79; } .lobilists .lobilist.lobilist-success { border: 1px solid #49a749; } .lobilists .lobilist.lobilist-success .lobilist-header { border-bottom: 1px solid #49a749; background-color: #5cb85c; } .lobilists .lobilist.lobilist-success .lobilist-header input { background-color: transparent; border-color: #FFF; color: #FFF; } .lobilists .lobilist.lobilist-success .lobilist-title { color: #FFF; } .lobilists .lobilist.lobilist-success .lobilist-actions .btn { color: #FFF; } .lobilists .lobilist.lobilist-success .btn-show-form { color: #FFF; } .lobilists .lobilist.lobilist-success .lobilist-form-footer { border-top: 1px solid #49a749; background-color: #5cb85c; } .lobilists .lobilist.lobilist-success .lobilist-footer { border-top: 1px solid #49a749; background-color: #5cb85c; } .lobilists .lobilist.lobilist-warning { border: 1px solid #ed9e2d; } .lobilists .lobilist.lobilist-warning .lobilist-header { border-bottom: 1px solid #ed9e2d; background-color: #f0ad4e; } .lobilists .lobilist.lobilist-warning .lobilist-header input { background-color: transparent; border-color: #FFF; color: #FFF; } .lobilists .lobilist.lobilist-warning .lobilist-title { color: #FFF; } .lobilists .lobilist.lobilist-warning .lobilist-actions .btn { color: #FFF; } .lobilists .lobilist.lobilist-warning .btn-show-form { color: #FFF; } .lobilists .lobilist.lobilist-warning .lobilist-form-footer { border-top: 1px solid #ed9e2d; background-color: #f0ad4e; } .lobilists .lobilist.lobilist-warning .lobilist-footer { border-top: 1px solid #ed9e2d; background-color: #f0ad4e; } .lobilists .lobilist.lobilist-info { border: 1px solid #3db5d8; } .lobilists .lobilist.lobilist-info .lobilist-header { border-bottom: 1px solid #3db5d8; background-color: #5bc0de; } .lobilists .lobilist.lobilist-info .lobilist-header input { background-color: transparent; border-color: #FFF; color: #FFF; } .lobilists .lobilist.lobilist-info .lobilist-title { color: #FFF; } .lobilists .lobilist.lobilist-info .lobilist-actions .btn { color: #FFF; } .lobilists .lobilist.lobilist-info .btn-show-form { color: #FFF; } .lobilists .lobilist.lobilist-info .lobilist-form-footer { border-top: 1px solid #3db5d8; background-color: #5bc0de; } .lobilists .lobilist.lobilist-info .lobilist-footer { border-top: 1px solid #3db5d8; background-color: #5bc0de; } .lobilists .lobilist.lobilist-primary { border: 1px solid #2c689c; } .lobilists .lobilist.lobilist-primary .lobilist-header { border-bottom: 1px solid #2c689c; background-color: #337ab7; } .lobilists .lobilist.lobilist-primary .lobilist-header input { background-color: transparent; border-color: #FFF; color: #FFF; } .lobilists .lobilist.lobilist-primary .lobilist-title { color: #FFF; } .lobilists .lobilist.lobilist-primary .lobilist-actions .btn { color: #FFF; } .lobilists .lobilist.lobilist-primary .btn-show-form { color: #FFF; } .lobilists .lobilist.lobilist-primary .lobilist-form-footer { border-top: 1px solid #2c689c; background-color: #337ab7; } .lobilists .lobilist.lobilist-primary .lobilist-footer { border-top: 1px solid #2c689c; background-color: #337ab7; } .lobilists .btn-finish-title-editing, .lobilists .btn-cancel-title-editing { display: none; } .lobilists .lobilist-header { position: relative; min-height: 38px; padding: 6px 8px; } .lobilists .lobilist-header input { background-color: transparent; height: 30px; } .lobilists .lobilist-header.title-editing .lobilist-actions { opacity: 1; } .lobilists .lobilist-header.title-editing .lobilist-actions .btn { display: none; } .lobilists .lobilist-header.title-editing .lobilist-actions .btn-finish-title-editing, .lobilists .lobilist-header.title-editing .lobilist-actions .btn-cancel-title-editing { display: inline-block; font-size: 18px; line-height: 30px; width: 30px; height: 30px; } .lobilists .lobilist-header:before, .lobilists .lobilist-header:after { content: " "; display: table; } .lobilists .lobilist-header:after { clear: both; } .lobilists .lobilist-actions { position: absolute; top: 6px; right: 8px; opacity: 0; } .lobilists .lobilist-actions>.dropdown { display: inline-block; } .lobilists .lobilist-actions .dropdown-menu { height: 70px; width: 100px; box-sizing: content-box; min-width: 0; padding: 0; margin: 0; } .lobilists .lobilist-actions .dropdown-menu .lobilist-default, .lobilists .lobilist-actions .dropdown-menu .lobilist-danger, .lobilists .lobilist-actions .dropdown-menu .lobilist-success, .lobilists .lobilist-actions .dropdown-menu .lobilist-warning, .lobilists .lobilist-actions .dropdown-menu .lobilist-info, .lobilists .lobilist-actions .dropdown-menu .lobilist-primary { display: inline-block; cursor: pointer; margin: 4px; width: 25px; height: 25px; } .lobilists .lobilist-actions .dropdown-menu .lobilist-default { background-color: #eeeeee; } .lobilists .lobilist-actions .dropdown-menu .lobilist-default:hover { background-color: #e2e2e2; } .lobilists .lobilist-actions .dropdown-menu .lobilist-danger { background-color: #e27c79; } .lobilists .lobilist-actions .dropdown-menu .lobilist-danger:hover { background-color: #de6764; } .lobilists .lobilist-actions .dropdown-menu .lobilist-success { background-color: #5cb85c; } .lobilists .lobilist-actions .dropdown-menu .lobilist-success:hover { background-color: #4cae4c; } .lobilists .lobilist-actions .dropdown-menu .lobilist-warning { background-color: #f0ad4e; } .lobilists .lobilist-actions .dropdown-menu .lobilist-warning:hover { background-color: #eea236; } .lobilists .lobilist-actions .dropdown-menu .lobilist-info { background-color: #5bc0de; } .lobilists .lobilist-actions .dropdown-menu .lobilist-info:hover { background-color: #46b8da; } .lobilists .lobilist-actions .dropdown-menu .lobilist-primary { background-color: #337ab7; } .lobilists .lobilist-actions .dropdown-menu .lobilist-primary:hover { background-color: #2e6da4; } .lobilists .lobilist-actions .btn { background-color: transparent; border-color: transparent; width: 40px; height: 40px; } .lobilists .lobilist-actions .btn:hover { background-color: rgba(0, 0, 0, 0.04); } .lobilists .lobilist-title { padding-left: 15px; font-size: 18px; } .lobilists .lobilist-items { list-style: none; margin-bottom: 0; padding: 10px; } .lobilists .lobilist-item, .lobilists .lobilist-item-placeholder { border: 1px solid transparent; margin-bottom: 5px; padding-top: 16px; padding-bottom: 4px; padding-left: 35px; border-bottom: 1px solid #eeeeee; -webkit-transition: background-color 0.2s; -o-transition: background-color 0.2s; transition: background-color 0.2s; } .lobilists .lobilist-item .drag-handler { position: absolute; left: 0; top: 0; bottom: 0; width: 5px; border-left: 2px dotted #dddddd; border-right: 2px dotted #dddddd; } .lobilists .lobilist-item .drag-handler:hover { cursor: move; } .lobilists .lobilist-item .todo-actions { position: absolute; top: 2px; right: 4px; text-align: center; white-space: nowrap; font-size: 10px; color: #9d9d9d; line-height: 16px; } .lobilists .lobilist-item .todo-action { display: inline-block; width: 16px; height: 16px; } .lobilists .lobilist-item .todo-action:hover { cursor: pointer; color: #5e5e5e; } .lobilists .lobilist-item:hover { background-color: rgba(0, 0, 0, 0.02); } .lobilists .lobilist-item-title { font-weight: 500; font-size: 16px; } .lobilists .lobilist-item-description { font-style: italic; } .lobilists .lobilist-item-duedate { position: absolute; top: 2px; left: 12px; font-style: italic; color: #777777; font-size: 85%; } .lobilists .lobilist-check { position: absolute; left: 12px; top: 16px; } .lobilists .lobilist-check.lobicheck { margin-top: 3px; } .lobilists .lobilist-item, .lobilists .lobilist-item-placeholder { position: relative; } .lobilists .lobilist-item.item-done { text-decoration: line-through; } .lobilists .btn-show-form { outline: 0; } .lobilists .lobilist-footer, .lobilists .lobilist-form-footer { padding: 6px 8px; } .lobilists .lobilist-form-footer { margin-left: -10px; margin-right: -10px; margin-bottom: -10px; } .lobilists .lobilist-add-todo-form { padding: 10px; } .lobilists .lobilist-add-todo-form .form-group { margin-bottom: 5px; } .lobilists .lobilist-add-todo-form .btn-add-todo { margin-right: 5px; } .lobilists .lobilist-add-todo-form .btn-add-todo, .lobilists .lobilist-add-todo-form .btn-discard-todo { height: 30px; } .lobilists .lobilist-placeholder { background-color: #f9f5d1; border: 1px dashed #777777; } .lobilists .lobilist-item-placeholder { background-color: rgba(0, 0, 0, 0.03); border: 1px dashed #dddddd; } @media (max-width: 480px) { .lobilists .lobilist { width: 100%; } } .lobilists.single-line { overflow-x: auto; overflow-y: hidden; white-space: nowrap; height: 400px; } .lobilists.single-line .lobilist-wrapper, .lobilists.single-line .lobilist-placeholder { float: none; white-space: normal; vertical-align: top; height: 100%; } .lobilists.no-sortable .lobilist-item .drag-handler { display: none; } .lobilists:before, .lobilists:after { content: " "; display: table; } .lobilists:after { clear: both; }
274056675/springboot-openai-chatgpt
1,305
mng_web/src/page/index/sidebar/index.vue
<template> <div class="avue-sidebar"> <logo></logo> <el-scrollbar style="height:100%"> <div v-if="validatenull(menu)" class="avue-sidebar--tip">{{$t('menuTip')}}</div> <el-menu unique-opened :default-active="nowTagValue" mode="vertical" :show-timeout="200" :collapse="keyCollapse"> <sidebar-item :menu="menu" :screen="screen" first :props="website.menu.props" :collapse="keyCollapse"></sidebar-item> </el-menu> </el-scrollbar> </div> </template> <script> import { mapGetters } from "vuex"; import logo from "../logo"; import sidebarItem from "./sidebarItem"; export default { name: "sidebar", components: { sidebarItem, logo }, data() { return {}; }, created() { this.$store.dispatch("GetMenu").then(data => { if (data.length === 0) return; this.$router.$avueRouter.formatRoutes(data, true); }); }, computed: { ...mapGetters(["website", "menu", "tag", "keyCollapse", "screen"]), nowTagValue: function() { return this.$router.$avueRouter.getValue(this.$route); } }, mounted() {}, methods: {} }; </script> <style lang="scss" scoped> </style>
27182812/ChatGLM-LLaMA-chinese-insturct
7,377
src/transformers/activations.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. import math from collections import OrderedDict import torch from packaging import version from torch import Tensor, nn from .utils import logging logger = logging.get_logger(__name__) class PytorchGELUTanh(nn.Module): """ A fast C implementation of the tanh approximation of the GeLU activation function. See https://arxiv.org/abs/1606.08415. This implementation is equivalent to NewGELU and FastGELU but much faster. However, it is not an exact numerical match due to rounding errors. """ def __init__(self): super().__init__() if version.parse(torch.__version__) < version.parse("1.12.0"): raise ImportError( f"You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use " "PytorchGELUTanh. Please upgrade torch." ) def forward(self, input: Tensor) -> Tensor: return nn.functional.gelu(input, approximate="tanh") class NewGELUActivation(nn.Module): """ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415 """ def forward(self, input: Tensor) -> Tensor: return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0)))) class GELUActivation(nn.Module): """ Original Implementation of the GELU activation function in Google BERT repo when initially created. For information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in nn.functional Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415 """ def __init__(self, use_gelu_python: bool = False): super().__init__() if use_gelu_python: self.act = self._gelu_python else: self.act = nn.functional.gelu def _gelu_python(self, input: Tensor) -> Tensor: return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0))) def forward(self, input: Tensor) -> Tensor: return self.act(input) class FastGELUActivation(nn.Module): """ Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs """ def forward(self, input: Tensor) -> Tensor: return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input))) class QuickGELUActivation(nn.Module): """ Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs """ def forward(self, input: Tensor) -> Tensor: return input * torch.sigmoid(1.702 * input) class ClippedGELUActivation(nn.Module): """ Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to https://arxiv.org/abs/2004.09602. Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))). See https://arxiv.org/abs/1606.08415 """ def __init__(self, min: float, max: float): if min > max: raise ValueError(f"min should be < max (got min: {min}, max: {max})") super().__init__() self.min = min self.max = max def forward(self, x: Tensor) -> Tensor: return torch.clip(gelu(x), self.min, self.max) class SiLUActivation(nn.Module): """ See Gaussian Error Linear Units (Hendrycks et al., https://arxiv.org/abs/1606.08415) where the SiLU (Sigmoid Linear Unit) was originally introduced and coined, and see Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning (Elfwing et al., https://arxiv.org/abs/1702.03118) and Swish: a Self-Gated Activation Function (Ramachandran et al., https://arxiv.org/abs/1710.05941v1) where the SiLU was experimented with later. """ def forward(self, input: Tensor) -> Tensor: return nn.functional.silu(input) class MishActivation(nn.Module): """ See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://arxiv.org/abs/1908.08681). Also visit the official repository for the paper: https://github.com/digantamisra98/Mish """ def __init__(self): super().__init__() if version.parse(torch.__version__) < version.parse("1.9.0"): self.act = self._mish_python else: self.act = nn.functional.mish def _mish_python(self, input: Tensor) -> Tensor: return input * torch.tanh(nn.functional.softplus(input)) def forward(self, input: Tensor) -> Tensor: return self.act(input) class LinearActivation(nn.Module): """ Applies the linear activation function, i.e. forwarding input directly to output. """ def forward(self, input: Tensor) -> Tensor: return input class ClassInstantier(OrderedDict): def __getitem__(self, key): content = super().__getitem__(key) cls, kwargs = content if isinstance(content, tuple) else (content, {}) return cls(**kwargs) ACT2CLS = { "gelu": GELUActivation, "gelu_10": (ClippedGELUActivation, {"min": -10, "max": 10}), "gelu_fast": FastGELUActivation, "gelu_new": NewGELUActivation, "gelu_python": (GELUActivation, {"use_gelu_python": True}), "gelu_pytorch_tanh": PytorchGELUTanh, "linear": LinearActivation, "mish": MishActivation, "quick_gelu": QuickGELUActivation, "relu": nn.ReLU, "relu6": nn.ReLU6, "sigmoid": nn.Sigmoid, "silu": SiLUActivation, "swish": SiLUActivation, "tanh": nn.Tanh, } ACT2FN = ClassInstantier(ACT2CLS) def get_activation(activation_string): if activation_string in ACT2FN: return ACT2FN[activation_string] else: raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}") # For backwards compatibility with: from activations import gelu_python gelu_python = get_activation("gelu_python") gelu_new = get_activation("gelu_new") gelu = get_activation("gelu") gelu_fast = get_activation("gelu_fast") quick_gelu = get_activation("quick_gelu") silu = get_activation("silu") mish = get_activation("mish") linear_act = get_activation("linear")
274056675/springboot-openai-chatgpt
1,143
mng_web/src/page/index/top/top-lang.vue
<template> <el-dropdown trigger="click" @command="handleSetLanguage"> <i class="icon-zhongyingwen"></i> <el-dropdown-menu slot="dropdown"> <el-dropdown-item :disabled="language==='zh'" command="zh">中文 </el-dropdown-item> <el-dropdown-item :disabled="language==='en'" command="en">English </el-dropdown-item> </el-dropdown-menu> </el-dropdown> </template> <script> import {mapGetters} from "vuex"; export default { name: "top-lang", data() { return {}; }, created() { }, mounted() { }, computed: { ...mapGetters(["language", "tag"]) }, props: [], methods: { handleSetLanguage(lang) { this.$i18n.locale = lang; this.$store.commit("SET_LANGUAGE", lang); let tag = this.tag; let title = this.$router.$avueRouter.generateTitle( tag.label, (tag.meta || {}).i18n ); //根据当前的标签也获取label的值动态设置浏览器标题 this.$router.$avueRouter.setTitle(title); } } }; </script> <style lang="scss" scoped> </style>
274056675/springboot-openai-chatgpt
1,640
mng_web/src/page/index/top/top-lock.vue
<template> <span> <i class="icon-suoping" @click="handleLock"></i> <el-dialog title="设置锁屏密码" :visible.sync="box" width="30%" append-to-body> <el-form :model="form" ref="form" label-width="80px"> <el-form-item label="锁屏密码" prop="passwd" :rules="[{ required: true, message: '锁屏密码不能为空'}]"> <el-input v-model="form.passwd" placeholder="请输入锁屏密码"></el-input> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button type="primary" @click="handleSetLock">确 定</el-button> </span> </el-dialog> </span> </template> <script> import { validatenull } from "@/util/validate"; import { mapGetters } from "vuex"; export default { name: "top-lock", data() { return { box: false, form: { passwd: "" } }; }, created() {}, mounted() {}, computed: { ...mapGetters(["lockPasswd"]) }, props: [], methods: { handleSetLock() { this.$refs["form"].validate(valid => { if (valid) { this.$store.commit("SET_LOCK_PASSWD", this.form.passwd); this.handleLock(); } }); }, handleLock() { if (validatenull(this.lockPasswd)) { this.box = true; return; } this.$store.commit("SET_LOCK"); setTimeout(() => { this.$router.push({ path: "/lock" }); }, 100); } }, components: {} }; </script> <style lang="scss" scoped> </style>
274056675/springboot-openai-chatgpt
1,872
mng_web/src/page/index/top/top-menu.vue
<template> <div class="top-menu"> <el-menu :default-active="activeIndex" mode="horizontal" text-color="#333"> <template v-for="(item,index) in items"> <el-menu-item :index="item.parentId+''" @click.native="openMenu(item)" :key="index"> <template slot="title"> <i :class="item.icon"></i> <span>{{generateTitle(item)}}</span> </template> </el-menu-item> </template> </el-menu> </div> </template> <script> import { mapGetters } from "vuex"; export default { name: "top-menu", data() { return { activeIndex: "0", items: [] }; }, created() { this.getMenu(); }, computed: { ...mapGetters(["tagCurrent", "menu"]) }, methods: { getMenu() { this.$store.dispatch("GetTopMenu").then(res => { this.items = res; }); }, generateTitle(item) { return this.$router.$avueRouter.generateTitle( item.label, (item.meta || {}).i18n ); }, openMenu(item) { this.$store.dispatch("GetMenu", item.parentId).then(data => { if (data.length !== 0) { this.$router.$avueRouter.formatRoutes(data, true); } let itemActive, childItemActive = 0; if (item.path) { itemActive = item; } else { if (this.menu[childItemActive].length == 0) { itemActive = this.menu[childItemActive]; } else { itemActive = this.menu[childItemActive].children[childItemActive]; } } this.$router.push({ path: this.$router.$avueRouter.getPath({ name: itemActive.label, src: itemActive.path, i18n: itemActive.meta.i18n }) }); }); } } }; </script>
274056675/springboot-openai-chatgpt
4,942
mng_web/src/page/index/top/index.vue
<template> <div class="avue-top"> <div class="top-bar__left"> <div class="avue-breadcrumb" :class="[{ 'avue-breadcrumb--active': isCollapse }]" v-if="showCollapse"> <i class="icon-navicon" @click="setCollapse"></i> </div> </div> <div class="top-bar__title"> <div class="top-bar__item top-bar__item--show" v-if="showMenu"> <top-menu></top-menu> </div> <span class="top-bar__item" v-if="showSearch"> <top-search></top-search> </span> </div> <div class="top-bar__right"> <el-tooltip v-if="showColor" effect="dark" :content="$t('navbar.color')" placement="bottom"> <div class="top-bar__item"> <top-color></top-color> </div> </el-tooltip> <el-tooltip v-if="showDebug" effect="dark" :content="logsFlag?$t('navbar.bug'):logsLen+$t('navbar.bugs')" placement="bottom"> <div class="top-bar__item"> <top-logs></top-logs> </div> </el-tooltip> <el-tooltip v-if="showLock" effect="dark" :content="$t('navbar.lock')" placement="bottom"> <div class="top-bar__item"> <top-lock></top-lock> </div> </el-tooltip> <el-tooltip v-if="showTheme" effect="dark" :content="$t('navbar.theme')" placement="bottom"> <div class="top-bar__item top-bar__item--show"> <top-theme></top-theme> </div> </el-tooltip> <el-tooltip effect="dark" :content="$t('navbar.language')" placement="bottom"> <div class="top-bar__item top-bar__item--show"> <top-lang></top-lang> </div> </el-tooltip> <el-tooltip v-if="showFullScren" effect="dark" :content="isFullScren?$t('navbar.screenfullF'):$t('navbar.screenfull')" placement="bottom"> <div class="top-bar__item"> <i :class="isFullScren?'icon-tuichuquanping':'icon-quanping'" @click="handleScreen"></i> </div> </el-tooltip> <img class="top-bar__img" :src="userInfo.avatar"> <el-dropdown> <span class="el-dropdown-link"> {{userInfo.userName}} <i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item> <router-link to="/">{{$t('navbar.dashboard')}}</router-link> </el-dropdown-item> <el-dropdown-item> <router-link to="/info/index">{{$t('navbar.userinfo')}}</router-link> </el-dropdown-item> <el-dropdown-item @click.native="logout" divided>{{$t('navbar.logOut')}}</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </div> </div> </template> <script> import { mapGetters, mapState } from "vuex"; import { fullscreenToggel, listenfullscreen } from "@/util/util"; import topLock from "./top-lock"; import topMenu from "./top-menu"; import topSearch from "./top-search"; import topTheme from "./top-theme"; import topLogs from "./top-logs"; import topColor from "./top-color"; import topLang from "./top-lang"; export default { components: { topLock, topMenu, topSearch, topTheme, topLogs, topColor, topLang }, name: "top", data() { return {}; }, filters: {}, created() {}, mounted() { listenfullscreen(this.setScreen); }, computed: { ...mapState({ showDebug: state => state.common.showDebug, showTheme: state => state.common.showTheme, showLock: state => state.common.showLock, showFullScren: state => state.common.showFullScren, showCollapse: state => state.common.showCollapse, showSearch: state => state.common.showSearch, showMenu: state => state.common.showMenu, showColor: state => state.common.showColor }), ...mapGetters([ "userInfo", "isFullScren", "tagWel", "tagList", "isCollapse", "tag", "logsLen", "logsFlag" ]) }, methods: { handleScreen() { fullscreenToggel(); }, setCollapse() { this.$store.commit("SET_COLLAPSE"); }, setScreen() { this.$store.commit("SET_FULLSCREN"); }, logout() { this.$confirm(this.$t("logoutTip"), this.$t("tip"), { confirmButtonText: this.$t("submitText"), cancelButtonText: this.$t("cancelText"), type: "warning" }).then(() => { this.$store.dispatch("LogOut").then(() => { this.$router.push({ path: "/login" }); }); }); } } }; </script> <style lang="scss" scoped> </style>
274056675/springboot-openai-chatgpt
1,663
mng_web/src/page/index/top/top-theme.vue
<template> <div> <el-dialog title="选择" :visible.sync="box" width="50%"> <el-radio-group v-model="text" class="list"> <el-row :span="24"> <el-col v-for="(item,index) in list" :key="index" :md="4" :xs="12" :sm="4"> <el-radio :label="item.value">{{item.name}}</el-radio> </el-col> </el-row> </el-radio-group> </el-dialog> <span> <i class="icon-zhuti" @click="open"></i> </span> </div> </template> <script> import { setTheme } from "@/util/util"; import { mapGetters } from "vuex"; export default { data() { return { box: false, text: "", list: [ { name: "默认主题", value: "default" }, { name: "白色主题", value: "theme-white" }, { name: "炫彩主题", value: "theme-star" }, { name: "iview主题", value: "theme-iview" }, { name: "d2主题", value: "theme-d2" }, { name: "hey主题", value: "theme-hey" } ] }; }, watch: { text: function(val) { this.$store.commit("SET_THEME_NAME", val); setTheme(val); } }, computed: { ...mapGetters(["themeName"]) }, mounted() { this.text = this.themeName; if (!this.text) { this.text = ""; } }, methods: { open() { this.box = true; } } }; </script> <style lang="scss" scoped> .list { width: 100%; } </style>
27182812/ChatGLM-LLaMA-chinese-insturct
29,147
src/transformers/image_transforms.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. import warnings from typing import Iterable, List, Optional, Tuple, Union import numpy as np from .image_utils import ( ChannelDimension, ImageInput, get_channel_dimension_axis, get_image_size, infer_channel_dimension_format, to_numpy_array, ) from .utils import ExplicitEnum, TensorType, is_jax_tensor, is_tf_tensor, is_torch_tensor from .utils.import_utils import ( is_flax_available, is_tf_available, is_torch_available, is_vision_available, requires_backends, ) if is_vision_available(): import PIL from .image_utils import PILImageResampling if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf if is_flax_available(): import jax.numpy as jnp def to_channel_dimension_format( image: np.ndarray, channel_dim: Union[ChannelDimension, str], input_channel_dim: Optional[Union[ChannelDimension, str]] = None, ) -> np.ndarray: """ Converts `image` to the channel dimension format specified by `channel_dim`. Args: image (`numpy.ndarray`): The image to have its channel dimension set. channel_dim (`ChannelDimension`): The channel dimension format to use. Returns: `np.ndarray`: The image with the channel dimension set to `channel_dim`. """ if not isinstance(image, np.ndarray): raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}") if input_channel_dim is None: input_channel_dim = infer_channel_dimension_format(image) target_channel_dim = ChannelDimension(channel_dim) if input_channel_dim == target_channel_dim: return image if target_channel_dim == ChannelDimension.FIRST: image = image.transpose((2, 0, 1)) elif target_channel_dim == ChannelDimension.LAST: image = image.transpose((1, 2, 0)) else: raise ValueError("Unsupported channel dimension format: {}".format(channel_dim)) return image def rescale( image: np.ndarray, scale: float, data_format: Optional[ChannelDimension] = None, dtype=np.float32 ) -> np.ndarray: """ Rescales `image` by `scale`. Args: image (`np.ndarray`): The image to rescale. scale (`float`): The scale to use for rescaling the image. data_format (`ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. dtype (`np.dtype`, *optional*, defaults to `np.float32`): The dtype of the output image. Defaults to `np.float32`. Used for backwards compatibility with feature extractors. Returns: `np.ndarray`: The rescaled image. """ if not isinstance(image, np.ndarray): raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}") rescaled_image = image * scale if data_format is not None: rescaled_image = to_channel_dimension_format(rescaled_image, data_format) rescaled_image = rescaled_image.astype(dtype) return rescaled_image def to_pil_image( image: Union[np.ndarray, "PIL.Image.Image", "torch.Tensor", "tf.Tensor", "jnp.ndarray"], do_rescale: Optional[bool] = None, ) -> "PIL.Image.Image": """ Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if needed. Args: image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor` or `tf.Tensor`): The image to convert to the `PIL.Image` format. do_rescale (`bool`, *optional*): Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will default to `True` if the image type is a floating type, `False` otherwise. Returns: `PIL.Image.Image`: The converted image. """ requires_backends(to_pil_image, ["vision"]) if isinstance(image, PIL.Image.Image): return image # Convert all tensors to numpy arrays before converting to PIL image if is_torch_tensor(image) or is_tf_tensor(image): image = image.numpy() elif is_jax_tensor(image): image = np.array(image) elif not isinstance(image, np.ndarray): raise ValueError("Input image type not supported: {}".format(type(image))) # If the channel as been moved to first dim, we put it back at the end. image = to_channel_dimension_format(image, ChannelDimension.LAST) # If there is a single channel, we squeeze it, as otherwise PIL can't handle it. image = np.squeeze(image, axis=-1) if image.shape[-1] == 1 else image # PIL.Image can only store uint8 values, so we rescale the image to be between 0 and 255 if needed. do_rescale = isinstance(image.flat[0], (float, np.float32, np.float64)) if do_rescale is None else do_rescale if do_rescale: image = rescale(image, 255) image = image.astype(np.uint8) return PIL.Image.fromarray(image) # Logic adapted from torchvision resizing logic: https://github.com/pytorch/vision/blob/511924c1ced4ce0461197e5caa64ce5b9e558aab/torchvision/transforms/functional.py#L366 def get_resize_output_image_size( input_image: np.ndarray, size: Union[int, Tuple[int, int], List[int], Tuple[int]], default_to_square: bool = True, max_size: Optional[int] = None, ) -> tuple: """ Find the target (height, width) dimension of the output image after resizing given the input image and the desired size. Args: input_image (`np.ndarray`): The image to resize. size (`int` or `Tuple[int, int]` or List[int] or Tuple[int]): The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to this. If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this number. i.e, if height > width, then image will be rescaled to (size * height / width, size). default_to_square (`bool`, *optional*, defaults to `True`): How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square (`size`,`size`). If set to `False`, will replicate [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize) with support for resizing only the smallest edge and providing an optional `max_size`. max_size (`int`, *optional*): The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater than `max_size` after being resized according to `size`, then the image is resized again so that the longer edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter than `size`. Only used if `default_to_square` is `False`. Returns: `tuple`: The target (height, width) dimension of the output image after resizing. """ if isinstance(size, (tuple, list)): if len(size) == 2: return tuple(size) elif len(size) == 1: # Perform same logic as if size was an int size = size[0] else: raise ValueError("size must have 1 or 2 elements if it is a list or tuple") if default_to_square: return (size, size) height, width = get_image_size(input_image) short, long = (width, height) if width <= height else (height, width) requested_new_short = size new_short, new_long = requested_new_short, int(requested_new_short * long / short) if max_size is not None: if max_size <= requested_new_short: raise ValueError( f"max_size = {max_size} must be strictly greater than the requested " f"size for the smaller edge size = {size}" ) if new_long > max_size: new_short, new_long = int(max_size * new_short / new_long), max_size return (new_long, new_short) if width <= height else (new_short, new_long) def resize( image, size: Tuple[int, int], resample: "PILImageResampling" = None, reducing_gap: Optional[int] = None, data_format: Optional[ChannelDimension] = None, return_numpy: bool = True, ) -> np.ndarray: """ Resizes `image` to `(height, width)` specified by `size` using the PIL library. Args: image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`): The image to resize. size (`Tuple[int, int]`): The size to use for resizing the image. resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`): The filter to user for resampling. reducing_gap (`int`, *optional*): Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to the fair resampling. See corresponding Pillow documentation for more details. data_format (`ChannelDimension`, *optional*): The channel dimension format of the output image. If unset, will use the inferred format from the input. return_numpy (`bool`, *optional*, defaults to `True`): Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is returned. Returns: `np.ndarray`: The resized image. """ requires_backends(resize, ["vision"]) resample = resample if resample is not None else PILImageResampling.BILINEAR if not len(size) == 2: raise ValueError("size must have 2 elements") # For all transformations, we want to keep the same data format as the input image unless otherwise specified. # The resized image from PIL will always have channels last, so find the input format first. data_format = infer_channel_dimension_format(image) if data_format is None else data_format # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use # the pillow library to resize the image and then convert back to numpy if not isinstance(image, PIL.Image.Image): image = to_pil_image(image) height, width = size # PIL images are in the format (width, height) resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap) if return_numpy: resized_image = np.array(resized_image) # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image # so we need to add it back if necessary. resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image # The image is always in channels last format after converting from a PIL image resized_image = to_channel_dimension_format( resized_image, data_format, input_channel_dim=ChannelDimension.LAST ) return resized_image def normalize( image: np.ndarray, mean: Union[float, Iterable[float]], std: Union[float, Iterable[float]], data_format: Optional[ChannelDimension] = None, ) -> np.ndarray: """ Normalizes `image` using the mean and standard deviation specified by `mean` and `std`. image = (image - mean) / std Args: image (`np.ndarray`): The image to normalize. mean (`float` or `Iterable[float]`): The mean to use for normalization. std (`float` or `Iterable[float]`): The standard deviation to use for normalization. data_format (`ChannelDimension`, *optional*): The channel dimension format of the output image. If unset, will use the inferred format from the input. """ requires_backends(normalize, ["vision"]) if isinstance(image, PIL.Image.Image): warnings.warn( "PIL.Image.Image inputs are deprecated and will be removed in v4.26.0. Please use numpy arrays instead.", FutureWarning, ) # Convert PIL image to numpy array with the same logic as in the previous feature extractor normalize - # casting to numpy array and dividing by 255. image = to_numpy_array(image) image = rescale(image, scale=1 / 255) if not isinstance(image, np.ndarray): raise ValueError("image must be a numpy array") input_data_format = infer_channel_dimension_format(image) channel_axis = get_channel_dimension_axis(image) num_channels = image.shape[channel_axis] if isinstance(mean, Iterable): if len(mean) != num_channels: raise ValueError(f"mean must have {num_channels} elements if it is an iterable, got {len(mean)}") else: mean = [mean] * num_channels mean = np.array(mean, dtype=image.dtype) if isinstance(std, Iterable): if len(std) != num_channels: raise ValueError(f"std must have {num_channels} elements if it is an iterable, got {len(std)}") else: std = [std] * num_channels std = np.array(std, dtype=image.dtype) if input_data_format == ChannelDimension.LAST: image = (image - mean) / std else: image = ((image.T - mean) / std).T image = to_channel_dimension_format(image, data_format) if data_format is not None else image return image def center_crop( image: np.ndarray, size: Tuple[int, int], data_format: Optional[Union[str, ChannelDimension]] = None, return_numpy: Optional[bool] = None, ) -> np.ndarray: """ Crops the `image` to the specified `size` using a center crop. Note that 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`): The image to crop. size (`Tuple[int, int]`): The target size for the cropped image. data_format (`str` or `ChannelDimension`, *optional*): 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. If unset, will use the inferred format of the input image. return_numpy (`bool`, *optional*): Whether or not to return the cropped image as a numpy array. Used for backwards compatibility with the previous ImageFeatureExtractionMixin method. - Unset: will return the same type as the input image. - `True`: will return a numpy array. - `False`: will return a `PIL.Image.Image` object. Returns: `np.ndarray`: The cropped image. """ requires_backends(center_crop, ["vision"]) if isinstance(image, PIL.Image.Image): warnings.warn( "PIL.Image.Image inputs are deprecated and will be removed in v4.26.0. Please use numpy arrays instead.", FutureWarning, ) image = to_numpy_array(image) return_numpy = False if return_numpy is None else return_numpy else: return_numpy = True if return_numpy is None else return_numpy if not isinstance(image, np.ndarray): raise ValueError(f"Input image must be of type np.ndarray, got {type(image)}") if not isinstance(size, Iterable) or len(size) != 2: raise ValueError("size must have 2 elements representing the height and width of the output image") input_data_format = infer_channel_dimension_format(image) output_data_format = data_format if data_format is not None else input_data_format # We perform the crop in (C, H, W) format and then convert to the output format image = to_channel_dimension_format(image, ChannelDimension.FIRST) orig_height, orig_width = get_image_size(image) crop_height, crop_width = size crop_height, crop_width = int(crop_height), int(crop_width) # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result. top = (orig_height - crop_height) // 2 bottom = top + crop_height # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result. left = (orig_width - crop_width) // 2 right = left + crop_width # Check if cropped area is within image boundaries if top >= 0 and bottom <= orig_height and left >= 0 and right <= orig_width: image = image[..., top:bottom, left:right] image = to_channel_dimension_format(image, output_data_format) return image # Otherwise, we may need to pad if the image is too small. Oh joy... new_height = max(crop_height, orig_height) new_width = max(crop_width, orig_width) new_shape = image.shape[:-2] + (new_height, new_width) new_image = np.zeros_like(image, shape=new_shape) # If the image is too small, pad it with zeros top_pad = (new_height - orig_height) // 2 bottom_pad = top_pad + orig_height left_pad = (new_width - orig_width) // 2 right_pad = left_pad + orig_width new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image top += top_pad bottom += top_pad left += left_pad right += left_pad new_image = new_image[..., max(0, top) : min(new_height, bottom), max(0, left) : min(new_width, right)] new_image = to_channel_dimension_format(new_image, output_data_format) if not return_numpy: new_image = to_pil_image(new_image) return new_image def _center_to_corners_format_torch(bboxes_center: "torch.Tensor") -> "torch.Tensor": center_x, center_y, width, height = bboxes_center.unbind(-1) bbox_corners = torch.stack( # top left x, top left y, bottom right x, bottom right y [(center_x - 0.5 * width), (center_y - 0.5 * height), (center_x + 0.5 * width), (center_y + 0.5 * height)], dim=-1, ) return bbox_corners def _center_to_corners_format_numpy(bboxes_center: np.ndarray) -> np.ndarray: center_x, center_y, width, height = bboxes_center.T bboxes_corners = np.stack( # top left x, top left y, bottom right x, bottom right y [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height], axis=-1, ) return bboxes_corners def _center_to_corners_format_tf(bboxes_center: "tf.Tensor") -> "tf.Tensor": center_x, center_y, width, height = tf.unstack(bboxes_center, axis=-1) bboxes_corners = tf.stack( # top left x, top left y, bottom right x, bottom right y [center_x - 0.5 * width, center_y - 0.5 * height, center_x + 0.5 * width, center_y + 0.5 * height], axis=-1, ) return bboxes_corners # 2 functions below inspired by https://github.com/facebookresearch/detr/blob/master/util/box_ops.py def center_to_corners_format(bboxes_center: TensorType) -> TensorType: """ Converts bounding boxes from center format to corners format. center format: contains the coordinate for the center of the box and its width, height dimensions (center_x, center_y, width, height) corners format: contains the coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y) """ # Function is used during model forward pass, so we use the input framework if possible, without # converting to numpy if is_torch_tensor(bboxes_center): return _center_to_corners_format_torch(bboxes_center) elif isinstance(bboxes_center, np.ndarray): return _center_to_corners_format_numpy(bboxes_center) elif is_tf_tensor(bboxes_center): return _center_to_corners_format_tf(bboxes_center) raise ValueError(f"Unsupported input type {type(bboxes_center)}") def _corners_to_center_format_torch(bboxes_corners: "torch.Tensor") -> "torch.Tensor": top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.unbind(-1) b = [ (top_left_x + bottom_right_x) / 2, # center x (top_left_y + bottom_right_y) / 2, # center y (bottom_right_x - top_left_x), # width (bottom_right_y - top_left_y), # height ] return torch.stack(b, dim=-1) def _corners_to_center_format_numpy(bboxes_corners: np.ndarray) -> np.ndarray: top_left_x, top_left_y, bottom_right_x, bottom_right_y = bboxes_corners.T bboxes_center = np.stack( [ (top_left_x + bottom_right_x) / 2, # center x (top_left_y + bottom_right_y) / 2, # center y (bottom_right_x - top_left_x), # width (bottom_right_y - top_left_y), # height ], axis=-1, ) return bboxes_center def _corners_to_center_format_tf(bboxes_corners: "tf.Tensor") -> "tf.Tensor": top_left_x, top_left_y, bottom_right_x, bottom_right_y = tf.unstack(bboxes_corners, axis=-1) bboxes_center = tf.stack( [ (top_left_x + bottom_right_x) / 2, # center x (top_left_y + bottom_right_y) / 2, # center y (bottom_right_x - top_left_x), # width (bottom_right_y - top_left_y), # height ], axis=-1, ) return bboxes_center def corners_to_center_format(bboxes_corners: TensorType) -> TensorType: """ Converts bounding boxes from corners format to center format. corners format: contains the coodinates for the top-left and bottom-right corners of the box (top_left_x, top_left_y, bottom_right_x, bottom_right_y) center format: contains the coordinate for the center of the box and its the width, height dimensions (center_x, center_y, width, height) """ # Inverse function accepts different input types so implemented here too if is_torch_tensor(bboxes_corners): return _corners_to_center_format_torch(bboxes_corners) elif isinstance(bboxes_corners, np.ndarray): return _corners_to_center_format_numpy(bboxes_corners) elif is_tf_tensor(bboxes_corners): return _corners_to_center_format_tf(bboxes_corners) raise ValueError(f"Unsupported input type {type(bboxes_corners)}") # 2 functions below copied from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py # Copyright (c) 2018, Alexander Kirillov # All rights reserved. def rgb_to_id(color): """ Converts RGB color to unique ID. """ if isinstance(color, np.ndarray) and len(color.shape) == 3: if color.dtype == np.uint8: color = color.astype(np.int32) return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2] return int(color[0] + 256 * color[1] + 256 * 256 * color[2]) def id_to_rgb(id_map): """ Converts unique ID to RGB color. """ if isinstance(id_map, np.ndarray): id_map_copy = id_map.copy() rgb_shape = tuple(list(id_map.shape) + [3]) rgb_map = np.zeros(rgb_shape, dtype=np.uint8) for i in range(3): rgb_map[..., i] = id_map_copy % 256 id_map_copy //= 256 return rgb_map color = [] for _ in range(3): color.append(id_map % 256) id_map //= 256 return color class PaddingMode(ExplicitEnum): """ Enum class for the different padding modes to use when padding images. """ CONSTANT = "constant" REFLECT = "reflect" REPLICATE = "replicate" SYMMETRIC = "symmetric" def pad( image: np.ndarray, padding: Union[int, Tuple[int, int], Iterable[Tuple[int, int]]], mode: PaddingMode = PaddingMode.CONSTANT, constant_values: Union[float, Iterable[float]] = 0.0, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """ Pads the `image` with the specified (height, width) `padding` and `mode`. Args: image (`np.ndarray`): The image to pad. padding (`int` or `Tuple[int, int]` or `Iterable[Tuple[int, int]]`): Padding to apply to the edges of the height, width axes. Can be one of three formats: - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis. - `((before, after),)` yields same before and after pad for height and width. - `(pad,)` or int is a shortcut for before = after = pad width for all axes. mode (`PaddingMode`): The padding mode to use. Can be one of: - `"constant"`: pads with a constant value. - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the vector along each axis. - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis. - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array. constant_values (`float` or `Iterable[float]`, *optional*): The value to use for the padding if `mode` is `"constant"`. data_format (`str` or `ChannelDimension`, *optional*): 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. If unset, will use same as the input image. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format for the input 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. If unset, will use the inferred format of the input image. Returns: `np.ndarray`: The padded image. """ if input_data_format is None: input_data_format = infer_channel_dimension_format(image) def _expand_for_data_format(values): """ Convert values to be in the format expected by np.pad based on the data format. """ if isinstance(values, (int, float)): values = ((values, values), (values, values)) elif isinstance(values, tuple) and len(values) == 1: values = ((values[0], values[0]), (values[0], values[0])) elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], int): values = (values, values) elif isinstance(values, tuple) and len(values) == 2 and isinstance(values[0], tuple): values = values else: raise ValueError(f"Unsupported format: {values}") # add 0 for channel dimension values = ((0, 0), *values) if input_data_format == ChannelDimension.FIRST else (*values, (0, 0)) # Add additional padding if there's a batch dimension values = (0, *values) if image.ndim == 4 else values return values padding = _expand_for_data_format(padding) if mode == PaddingMode.CONSTANT: constant_values = _expand_for_data_format(constant_values) image = np.pad(image, padding, mode="constant", constant_values=constant_values) elif mode == PaddingMode.REFLECT: image = np.pad(image, padding, mode="reflect") elif mode == PaddingMode.REPLICATE: image = np.pad(image, padding, mode="edge") elif mode == PaddingMode.SYMMETRIC: image = np.pad(image, padding, mode="symmetric") else: raise ValueError(f"Invalid padding mode: {mode}") image = to_channel_dimension_format(image, data_format) if data_format is not None else image return image # TODO (Amy): Accept 1/3/4 channel numpy array as input and return np.array as default def convert_to_rgb(image: ImageInput) -> ImageInput: """ Converts an image to RGB format. Only converts if the image is of type PIL.Image.Image, otherwise returns the image as is. Args: image (Image): The image to convert. """ requires_backends(convert_to_rgb, ["vision"]) if not isinstance(image, PIL.Image.Image): return image image = image.convert("RGB") return image
27182812/ChatGLM-LLaMA-chinese-insturct
4,313
src/transformers/activations_tf.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. import math import tensorflow as tf from packaging import version def _gelu(x): """ Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see https://arxiv.org/abs/1606.08415 """ x = tf.convert_to_tensor(x) cdf = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0), x.dtype))) return x * cdf def _gelu_new(x): """ Gaussian Error Linear Unit. This is a smoother version of the GELU. Original paper: https://arxiv.org/abs/1606.0841 Args: x: float Tensor to perform activation Returns: `x` with the GELU activation applied. """ x = tf.convert_to_tensor(x) pi = tf.cast(math.pi, x.dtype) coeff = tf.cast(0.044715, x.dtype) cdf = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi) * (x + coeff * tf.pow(x, 3)))) return x * cdf def mish(x): x = tf.convert_to_tensor(x) return x * tf.tanh(tf.math.softplus(x)) def gelu_fast(x): x = tf.convert_to_tensor(x) coeff1 = tf.cast(0.044715, x.dtype) coeff2 = tf.cast(0.7978845608, x.dtype) return 0.5 * x * (1.0 + tf.tanh(x * coeff2 * (1.0 + coeff1 * x * x))) def quick_gelu(x): x = tf.convert_to_tensor(x) coeff = tf.cast(1.702, x.dtype) return x * tf.math.sigmoid(coeff * x) def gelu_10(x): """ Clip the range of possible GeLU outputs between [-10, 10]. This is especially useful for quantization purpose, as it allows mapping 2 negatives values in the GeLU spectrum. For more information on this trick, please refer to https://arxiv.org/abs/2004.09602 Gaussian Error Linear Unit. Original Implementation of the gelu activation function in Google Bert repo when initially created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see https://arxiv.org/abs/1606.08415 :param x: :return: """ return tf.clip_by_value(_gelu(x), -10, 10) def glu(x, axis=-1): """ Gated Linear Unit. Implementation as defined in the original paper (see https://arxiv.org/abs/1612.08083), where the input `x` is split in two halves across a dimension (`axis`), A and B, returning A * sigmoid(B). Args: `x`: float Tensor to perform activation `axis`: dimension across which `x` be split in half Returns: `x` with the GLU activation applied (with its size halved across the dimension `axis`). """ a, b = tf.split(x, 2, axis=axis) return a * tf.math.sigmoid(b) if version.parse(tf.version.VERSION) >= version.parse("2.4"): def approximate_gelu_wrap(x): return tf.keras.activations.gelu(x, approximate=True) gelu = tf.keras.activations.gelu gelu_new = approximate_gelu_wrap else: gelu = _gelu gelu_new = _gelu_new ACT2FN = { "gelu": gelu, "gelu_10": gelu_10, "gelu_fast": gelu_fast, "gelu_new": gelu_new, "glu": glu, "mish": mish, "quick_gelu": quick_gelu, "relu": tf.keras.activations.relu, "sigmoid": tf.keras.activations.sigmoid, "silu": tf.keras.activations.swish, "swish": tf.keras.activations.swish, "tanh": tf.keras.activations.tanh, } def get_tf_activation(activation_string): if activation_string in ACT2FN: return ACT2FN[activation_string] else: raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACT2FN.keys())}")
27182812/ChatGLM-LLaMA-chinese-insturct
17,506
src/transformers/deepspeed.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. """ Integration with Deepspeed """ import importlib.util import weakref from copy import deepcopy from functools import partialmethod from .dependency_versions_check import dep_version_check from .utils import is_accelerate_available, is_torch_available, logging if is_torch_available(): import torch logger = logging.get_logger(__name__) def is_deepspeed_available(): return importlib.util.find_spec("deepspeed") is not None if is_accelerate_available() and is_deepspeed_available(): from accelerate.utils.deepspeed import HfDeepSpeedConfig as DeepSpeedConfig else: # Inherits from a dummy `object` if accelerate is not available, so that python succeeds to import this file. # Deepspeed glue code will never inherit this dummy object as it checks if accelerate is available. from builtins import object as DeepSpeedConfig class HfDeepSpeedConfig(DeepSpeedConfig): """ This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage. A `weakref` of this object is stored in the module's globals to be able to access the config from areas where things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore it's important that this object remains alive while the program is still running. [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic the DeepSpeed configuration is not modified in any way. Args: config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict. """ def __init__(self, config_file_or_dict): # set global weakref object set_hf_deepspeed_config(self) dep_version_check("accelerate") dep_version_check("deepspeed") super().__init__(config_file_or_dict) class HfTrainerDeepSpeedConfig(HfDeepSpeedConfig): """ The `HfTrainerDeepSpeedConfig` object is meant to be created during `TrainingArguments` object creation and has the same lifespan as the latter. """ def __init__(self, config_file_or_dict): super().__init__(config_file_or_dict) self._dtype = None self.mismatches = [] def dtype(self): if self._dtype is None: raise ValueError("trainer_config_process() wasn't called yet to tell dtype") return self._dtype def is_auto(self, ds_key_long): val = self.get_value(ds_key_long) if val is None: return False else: return val == "auto" def fill_match(self, ds_key_long, hf_val, hf_key=None, must_match=True): """ A utility method that massages the config file and can optionally verify that the values match. 1. Replace "auto" values with `TrainingArguments` value. 2. If it wasn't "auto" and `must_match` is true, then check that DS config matches Trainer config values and if mismatched add the entry to `self.mismatched` - will assert during `trainer_config_finalize` for one or more mismatches. """ config, ds_key = self.find_config_node(ds_key_long) if config is None: return if config.get(ds_key) == "auto": config[ds_key] = hf_val return if not must_match: return ds_val = config.get(ds_key) if ds_val is not None and ds_val != hf_val: self.mismatches.append(f"- ds {ds_key_long}={ds_val} vs hf {hf_key}={hf_val}") fill_only = partialmethod(fill_match, must_match=False) def trainer_config_process(self, args): """ Adjust the config with `TrainingArguments` values. This stage is run during `TrainingArguments` object creation. """ # DeepSpeed does: # train_batch_size = world_size * train_micro_batch_size_per_gpu * gradient_accumulation_steps train_batch_size = args.world_size * args.per_device_train_batch_size * args.gradient_accumulation_steps self.fill_match( "train_micro_batch_size_per_gpu", args.per_device_train_batch_size, "per_device_train_batch_size" ) self.fill_match("gradient_accumulation_steps", args.gradient_accumulation_steps, "gradient_accumulation_steps") self.fill_match("train_batch_size", train_batch_size, "train_batch_size (calculated)") self.fill_match("gradient_clipping", args.max_grad_norm, "max_grad_norm") self.fill_match("optimizer.params.lr", args.learning_rate, "learning_rate") self.fill_match("optimizer.params.betas", [args.adam_beta1, args.adam_beta2], "adam_beta1+adam_beta2") self.fill_match("optimizer.params.eps", args.adam_epsilon, "adam_epsilon") self.fill_match("optimizer.params.weight_decay", args.weight_decay, "weight_decay") self.fill_only("scheduler.params.warmup_min_lr", 0) # not a trainer arg self.fill_match("scheduler.params.warmup_max_lr", args.learning_rate, "learning_rate") # total_num_steps - will get set in trainer_config_finalize # fp16 if args.fp16 or args.fp16_full_eval: fp16_backend = "apex" if args.fp16_backend == "apex" else "amp" else: fp16_backend = None if args.save_on_each_node: # deepspeed uses shared storage by default. Let's override this setting if save_on_each_node == True self.config["checkpoint"] = self.config.get("checkpoint", {}) self.config["checkpoint"]["use_node_local_storage"] = args.save_on_each_node # amp: similar to the pytorch native amp - it has a bunch of optional params but we won't set # any here unless the user did the work self.fill_match( "fp16.enabled", ((args.fp16 or args.fp16_full_eval) and fp16_backend == "amp"), "fp16|fp16_full_eval+fp16_backend(amp)", ) # apex: delegates amp work to apex (which needs to be available), but it cannot be used with any # ZeRO features self.fill_match("amp.enabled", fp16_backend == "apex", "fp16+fp16_backend(apex)") self.fill_match("amp.opt_level", args.fp16_opt_level, "fp16_opt_level") self.fill_match("bf16.enabled", (args.bf16 or args.bf16_full_eval), "bf16|bf16_full_eval") # deepspeed's default mode is fp16 unless there is a config that says differently if self.is_true("bf16.enabled"): self._dtype = torch.bfloat16 elif self.is_false("fp16.enabled"): self._dtype = torch.float32 else: self._dtype = torch.float16 def trainer_config_finalize(self, args, model, num_training_steps): """ This stage is run after we have the model and know num_training_steps. Now we can complete the configuration process. """ # zero # deal with config keys that use `auto` value and rely on model's hidden_size hidden_size_based_keys = [ "zero_optimization.reduce_bucket_size", "zero_optimization.stage3_prefetch_bucket_size", "zero_optimization.stage3_param_persistence_threshold", ] hidden_size_auto_keys = [x for x in hidden_size_based_keys if self.is_auto(x)] if len(hidden_size_auto_keys) > 0: if hasattr(model.config, "hidden_size"): hidden_size = model.config.hidden_size elif hasattr(model.config, "hidden_sizes"): # if there are many hidden sizes pick the largest one hidden_size = max(model.config.hidden_sizes) else: raise ValueError( "The model's config file has neither `hidden_size` nor `hidden_sizes` entry, " "therefore it's not possible to automatically fill out the following `auto` entries " f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing " "`auto` values for these keys with an integer value of your choice." ) self.fill_only("zero_optimization.reduce_bucket_size", hidden_size * hidden_size) if self.is_zero3(): # automatically assign the optimal config values based on model config self.fill_only("zero_optimization.stage3_prefetch_bucket_size", 0.9 * hidden_size * hidden_size) self.fill_only("zero_optimization.stage3_param_persistence_threshold", 10 * hidden_size) # scheduler self.fill_match("scheduler.params.total_num_steps", num_training_steps, "num_training_steps (calculated)") self.fill_match("scheduler.params.warmup_num_steps", args.get_warmup_steps(num_training_steps), "warmup_steps") if len(self.mismatches) > 0: mismatches = "\n".join(self.mismatches) raise ValueError( "Please correct the following DeepSpeed config values that mismatch TrainingArguments" f" values:\n{mismatches}\nThe easiest method is to set these DeepSpeed config values to 'auto'." ) # keep the config object global to be able to access it anywhere during TrainingArguments life-cycle _hf_deepspeed_config_weak_ref = None def set_hf_deepspeed_config(hf_deepspeed_config_obj): # this is a special weakref global object to allow us to get to Deepspeed config from APIs # that don't have an easy way to get to the Deepspeed config outside of the Trainer domain. global _hf_deepspeed_config_weak_ref # will go away automatically when HfDeepSpeedConfig is destroyed (when TrainingArguments is destroyed) _hf_deepspeed_config_weak_ref = weakref.ref(hf_deepspeed_config_obj) def unset_hf_deepspeed_config(): # useful for unit tests to ensure the global state doesn't leak - call from `tearDown` method global _hf_deepspeed_config_weak_ref _hf_deepspeed_config_weak_ref = None def is_deepspeed_zero3_enabled(): if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None: return _hf_deepspeed_config_weak_ref().is_zero3() else: return False def deepspeed_config(): if _hf_deepspeed_config_weak_ref is not None and _hf_deepspeed_config_weak_ref() is not None: return _hf_deepspeed_config_weak_ref().config else: return None def deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps): """ A convenience wrapper that deals with optimizer and lr scheduler configuration. """ config = hf_deepspeed_config.config # Optimizer + Scheduler # Currently supported combos: # 1. DS scheduler + DS optimizer: Yes # 2. HF scheduler + HF optimizer: Yes # 3. DS scheduler + HF optimizer: Yes # 4. HF scheduler + DS optimizer: Yes # # Unless Offload is enabled in which case it's: # 1. DS scheduler + DS optimizer: Yes # 2. HF scheduler + HF optimizer: Mostly* # 3. DS scheduler + HF optimizer: Mostly* # 4. HF scheduler + DS optimizer: Yes # # Mostly*: All non-native DeepSpeed optimizers that have both CPU and GPU implementation should work (except LAMB) optimizer = None if "optimizer" in config: if args.adafactor: raise ValueError( "--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. " "Only one optimizer can be configured." ) else: if hf_deepspeed_config.is_offload(): logger.info( "Detected ZeRO Offload and non-DeepSpeed optimizers: This combination should work as long as the" " custom optimizer has both CPU and GPU implementation (except LAMB)" ) # ds supports Adam, OneBitAdam, and Lamb optimizers and can import other optimizers from torch. # But trainer uses AdamW by default. optimizer = trainer.create_optimizer() # To use other optimizers requires voiding warranty with: `zero_allow_untested_optimizer` config["zero_allow_untested_optimizer"] = True def _lr_scheduler_callable(optimizer): return trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer) lr_scheduler = None if "scheduler" not in config: if optimizer is None: # Optimizer is not available, so use callable to defer lr_scheduler creation to DS init lr_scheduler = _lr_scheduler_callable else: lr_scheduler = trainer.create_scheduler(num_training_steps=num_training_steps, optimizer=optimizer) return optimizer, lr_scheduler def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None, inference=False): """ Init DeepSpeed, after updating the DeepSpeed configuration with any relevant Trainer's args. If `resume_from_checkpoint` was passed then an attempt to resume from a previously saved checkpoint will be made. Args: trainer: Trainer object num_training_steps: per single gpu resume_from_checkpoint: path to a checkpoint if to resume from after normal DeepSpeedEngine load inference: launch in inference mode (no optimizer and no lr scheduler) Returns: model, optimizer, lr_scheduler We may use `deepspeed_init` more than once during the life of Trainer, when we do - it's a temp hack based on: https://github.com/microsoft/DeepSpeed/issues/1394#issuecomment-937405374 until Deepspeed fixes a bug where it can't resume from a checkpoint after it did some stepping https://github.com/microsoft/DeepSpeed/issues/1612 """ import deepspeed from deepspeed.utils import logger as ds_logger model = trainer.model args = trainer.args if hasattr(trainer, "hf_deepspeed_config_orig"): hf_deepspeed_config = deepcopy(trainer.hf_deepspeed_config_orig) else: hf_deepspeed_config = args.hf_deepspeed_config trainer.hf_deepspeed_config_orig = deepcopy(args.hf_deepspeed_config) # resume config update - some bits like `model` and `num_training_steps` only become available during train hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps) config = hf_deepspeed_config.config # set the Deepspeed log level consistent with the Trainer ds_logger.setLevel(args.get_process_log_level()) if inference: # only Z3 makes sense for the inference if not hf_deepspeed_config.is_zero3(): raise ValueError("ZeRO inference only makes sense with ZeRO Stage 3 - please adjust your config") # in case the training config is re-used for inference hf_deepspeed_config.del_config_sub_tree("optimizer") hf_deepspeed_config.del_config_sub_tree("lr_scheduler") optimizer, lr_scheduler = None, None model_parameters = None else: trainer.optimizer = None # important for when deepspeed_init is used as re-init optimizer, lr_scheduler = deepspeed_optim_sched(trainer, hf_deepspeed_config, args, num_training_steps) model_parameters = list(filter(lambda p: p.requires_grad, model.parameters())) # keep for quick debug: # from pprint import pprint; pprint(config) kwargs = { "model": model, "model_parameters": model_parameters, "config_params": config, "optimizer": optimizer, "lr_scheduler": lr_scheduler, } deepspeed_engine, optimizer, _, lr_scheduler = deepspeed.initialize(**kwargs) if resume_from_checkpoint is not None: # it's possible that the user is trying to resume from model_path, which doesn't necessarily # contain a deepspeed checkpoint. e.g. examples just check if the dir exists and assume it's # a resume from a checkpoint and not just a local pretrained weight. So we check here if the # path contains what looks like a deepspeed checkpoint import glob deepspeed_checkpoint_dirs = sorted(glob.glob(f"{resume_from_checkpoint}/global_step*")) if len(deepspeed_checkpoint_dirs) > 0: logger.info(f"Attempting to resume from {resume_from_checkpoint}") # this magically updates self.optimizer and self.lr_scheduler load_path, _ = deepspeed_engine.load_checkpoint( resume_from_checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True ) if load_path is None: raise ValueError(f"[deepspeed] failed to resume from checkpoint {resume_from_checkpoint}") else: raise ValueError(f"Can't find a valid checkpoint at {resume_from_checkpoint}") return deepspeed_engine, optimizer, lr_scheduler
233zzh/TitanDataOperationSystem
3,382
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples</title> <link href="examples.css" rel="stylesheet" type="text/css"> <style> h3 { margin-top: 30px; margin-bottom: 5px; } </style> <script language="javascript" type="text/javascript" src="../jquery.js"></script> <script language="javascript" type="text/javascript" src="../jquery.flot.js"></script> <script type="text/javascript"> $(function() { // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Flot Examples</h2> </div> <div id="content"> <p>Here are some examples for <a href="http://www.flotcharts.org">Flot</a>, the Javascript charting library for jQuery:</p> <h3>Basic Usage</h3> <ul> <li><a href="basic-usage/index.html">Basic example</a></li> <li><a href="series-types/index.html">Different graph types</a> and <a href="categories/index.html">simple categories/textual data</a></li> <li><a href="basic-options/index.html">Setting various options</a> and <a href="annotating/index.html">annotating a chart</a></li> <li><a href="ajax/index.html">Updating graphs with AJAX</a> and <a href="realtime/index.html">real-time updates</a></li> </ul> <h3>Interactivity</h3> <ul> <li><a href="series-toggle/index.html">Turning series on/off</a></li> <li><a href="selection/index.html">Rectangular selection support and zooming</a> and <a href="zooming/index.html">zooming with overview</a> (both with selection plugin)</li> <li><a href="interacting/index.html">Interacting with the data points</a></li> <li><a href="navigate/index.html">Panning and zooming</a> (with navigation plugin)</li> <li><a href="resize/index.html">Automatically redraw when window is resized</a> (with resize plugin)</li> </ul> <h3>Additional Features</h3> <ul> <li><a href="symbols/index.html">Using other symbols than circles for points</a> (with symbol plugin)</li> <li><a href="axes-time/index.html">Plotting time series</a>, <a href="visitors/index.html">visitors per day with zooming and weekends</a> (with selection plugin) and <a href="axes-time-zones/index.html">time zone support</a></li> <li><a href="axes-multiple/index.html">Multiple axes</a> and <a href="axes-interacting/index.html">interacting with the axes</a></li> <li><a href="threshold/index.html">Thresholding the data</a> (with threshold plugin)</li> <li><a href="stacking/index.html">Stacked charts</a> (with stacking plugin)</li> <li><a href="percentiles/index.html">Using filled areas to plot percentiles</a> (with fillbetween plugin)</li> <li><a href="tracking/index.html">Tracking curves with crosshair</a> (with crosshair plugin)</li> <li><a href="image/index.html">Plotting prerendered images</a> (with image plugin)</li> <li><a href="series-errorbars/index.html">Plotting error bars</a> (with errorbars plugin)</li> <li><a href="series-pie/index.html">Pie charts</a> (with pie plugin)</li> <li><a href="canvas/index.html">Rendering text with canvas instead of HTML</a> (with canvas plugin)</li> </ul> </div> <div id="footer"> Copyright &copy; 2007 - 2013 IOLA and Ole Laursen </div> </body> </html>
274056675/springboot-openai-chatgpt
2,959
mng_web/src/page/index/top/top-search.vue
<template> <el-autocomplete class="top-search" popper-class="my-autocomplete" v-model="value" :fetch-suggestions="querySearch" :placeholder="$t('search')" @select="handleSelect"> <template slot-scope="{ item }"> <i :class="[item[iconKey],'icon']"></i> <div class="name">{{ item[labelKey] }}</div> <div class="addr">{{ item[pathKey] }}</div> </template> </el-autocomplete> </template> <script> import config from "../sidebar/config.js"; import { mapGetters } from "vuex"; export default { data() { return { config: config, value: "", menuList: [] }; }, created() { this.getMenuList(); }, watch: { menu() { this.getMenuList(); } }, computed: { labelKey() { return this.website.menu.props.label || this.config.propsDefault.label; }, pathKey() { return this.website.menu.props.path || this.config.propsDefault.path; }, iconKey() { return this.website.menu.props.icon || this.config.propsDefault.icon; }, childrenKey() { return ( this.website.menu.props.children || this.config.propsDefault.children ); }, ...mapGetters(["menu", "website"]) }, methods: { getMenuList() { const findMenu = list => { for (let i = 0; i < list.length; i++) { const ele = Object.assign({}, list[i]); if (this.validatenull(ele[this.childrenKey])) { this.menuList.push(ele); } else { findMenu(ele[this.childrenKey]); } } }; this.menuList = []; findMenu(this.menu); }, querySearch(queryString, cb) { var restaurants = this.menuList; var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants; // 调用 callback 返回建议列表的数据 cb(results); }, createFilter(queryString) { return restaurant => { return ( restaurant.label.toLowerCase().indexOf(queryString.toLowerCase()) === 0 ); }; }, handleSelect(item) { this.value = ""; this.$router.push({ path: this.$router.$avueRouter.getPath({ name: item[this.labelKey], src: item[this.pathKey], i18n: (item.meta || {}).i18n }), query: item.query }); } } }; </script> <style lang="scss"> .my-autocomplete { li { line-height: normal; padding: 7px; .icon { margin-right: 5px; display: inline-block; vertical-align: middle; } .name { display: inline-block; text-overflow: ellipsis; overflow: hidden; vertical-align: middle; } .addr { padding-top: 5px; width: 100%; font-size: 12px; color: #b4b4b4; } .highlighted .addr { color: #ddd; } } } </style>
274056675/springboot-openai-chatgpt
1,550
mng_web/src/router/page/index.js
import Layout from '@/page/index/' export default [{ path: '/login', name: '登录页', component: () => import( /* webpackChunkName: "page" */ '@/page/login/index'), meta: { keepAlive: true, isTab: false, isAuth: false } }, { path: '/lock', name: '锁屏页', component: () => import( /* webpackChunkName: "page" */ '@/page/lock/index'), meta: { keepAlive: true, isTab: false, isAuth: false } }, { path: '/404', component: () => import( /* webpackChunkName: "page" */ '@/components/error-page/404'), name: '404', meta: { keepAlive: true, isTab: false, isAuth: false } }, { path: '/403', component: () => import( /* webpackChunkName: "page" */ '@/components/error-page/403'), name: '403', meta: { keepAlive: true, isTab: false, isAuth: false } }, { path: '/500', component: () => import( /* webpackChunkName: "page" */ '@/components/error-page/500'), name: '500', meta: { keepAlive: true, isTab: false, isAuth: false } }, { path: '/', name: '主页', redirect: '/wel' }, { path: '/myiframe', component: Layout, redirect: '/myiframe', children: [{ path: ":routerPath", name: 'iframe', component: () => import( /* webpackChunkName: "page" */ '@/components/iframe/main'), props: true }] }, { path: '*', redirect: '/404' } ]
27182812/ChatGLM-LLaMA-chinese-insturct
20,775
src/transformers/keras_callbacks.py
import logging import os from pathlib import Path from time import sleep from typing import Callable, List, Optional, Union import numpy as np import tensorflow as tf from huggingface_hub import Repository, create_repo from packaging.version import parse from tensorflow.keras.callbacks import Callback from . import IntervalStrategy, PreTrainedTokenizerBase from .modelcard import TrainingSummary from .utils import get_full_repo_name logger = logging.getLogger(__name__) class KerasMetricCallback(Callback): """ Callback to compute metrics at the end of every epoch. Unlike normal Keras metrics, these do not need to be compilable by TF. It is particularly useful for common NLP metrics like BLEU and ROUGE that require string operations or generation loops that cannot be compiled. Predictions (or generations) will be computed on the `eval_dataset` before being passed to the `metric_fn` in `np.ndarray` format. The `metric_fn` should compute metrics and return a dict mapping metric names to metric values. We provide an example of a suitable metric_fn that computes ROUGE scores for a summarization model below. Note that this example skips some post-processing for readability and simplicity, and should probably not be used as-is! ```py from datasets import load_metric rouge_metric = load_metric("rouge") def rouge_fn(predictions, labels): decoded_predictions = tokenizer.batch_decode(predictions, skip_special_tokens=True) decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) result = rouge_metric.compute(predictions=decoded_predictions, references=decoded_labels) return {key: value.mid.fmeasure * 100 for key, value in result.items()} ``` The above function will return a dict containing values which will be logged like any other Keras metric: ``` {'rouge1': 37.4199, 'rouge2': 13.9768, 'rougeL': 34.361, 'rougeLsum': 35.0781 ``` Args: metric_fn (`Callable`): Metric function provided by the user. It will be called with two arguments - `predictions` and `labels`. These contain the model's outputs and matching labels from the dataset. It should return a dict mapping metric names to numerical values. eval_dataset (`tf.data.Dataset` or `dict` or `tuple` or `np.ndarray` or `tf.Tensor`): Validation data to be used to generate predictions for the `metric_fn`. output_cols (`List[str], *optional*): A list of columns to be retained from the model output as the predictions. Defaults to all. label_cols ('`List[str]`, *optional*'): A list of columns to be retained from the input dataset as the labels. Will be autodetected if this is not supplied. batch_size (`int`, *optional*): Batch size. Only used when the data is not a pre-batched `tf.data.Dataset`. predict_with_generate (`bool`, *optional*, defaults to `False`): Whether we should use `model.generate()` to get outputs for the model. use_xla_generation (`bool`, *optional*, defaults to `False`): If we're generating, whether to compile model generation with XLA. This can massively increase the speed of generation (up to 100X speedup) but will require a new XLA compilation for each input shape. When using XLA generation, it's a good idea to pad your inputs to the same size, or to use the `pad_to_multiple_of` argument in your `tokenizer` or `DataCollator`, which will reduce the number of unique input shapes and save a lot of compilation time. This option has no effect is `predict_with_generate` is `False`. generate_kwargs (`dict`, *optional*): Keyword arguments to pass to `model.generate()` when generating. Has no effect if `predict_with_generate` is `False`. """ def __init__( self, metric_fn: Callable, eval_dataset: Union[tf.data.Dataset, np.ndarray, tf.Tensor, tuple, dict], output_cols: Optional[List[str]] = None, label_cols: Optional[List[str]] = None, batch_size: Optional[int] = None, predict_with_generate: bool = False, use_xla_generation: bool = False, generate_kwargs: Optional[dict] = None, ): super().__init__() self.metric_fn = metric_fn self.batch_size = batch_size if not isinstance(eval_dataset, tf.data.Dataset): if batch_size is None: raise ValueError( "When passing data to KerasMetricCallback that is not a pre-batched tf.data.Dataset " "the batch_size argument must be set." ) # Wrap a tf.data.Dataset around it eval_dataset = tf.data.Dataset.from_tensor_slices(eval_dataset).batch(batch_size, drop_remainder=False) self.eval_dataset = eval_dataset self.predict_with_generate = predict_with_generate self.output_cols = output_cols # This next block attempts to parse out which elements of the dataset should be appended to the labels list # that is passed to the metric_fn if isinstance(eval_dataset.element_spec, tuple) and len(eval_dataset.element_spec) == 2: input_spec, label_spec = eval_dataset.element_spec else: input_spec = eval_dataset.element_spec label_spec = None if label_cols is not None: for label in label_cols: if label not in input_spec: raise ValueError(f"Label {label} is in label_cols but could not be found in the dataset inputs!") self.label_cols = label_cols self.use_keras_label = False elif label_spec is not None: # If the dataset inputs are split into a 2-tuple of inputs and labels, # assume the second element is the labels self.label_cols = None self.use_keras_label = True elif "labels" in input_spec: self.label_cols = ["labels"] self.use_keras_label = False logging.warning("No label_cols specified for KerasMetricCallback, assuming you want the 'labels' key.") elif "start_positions" in input_spec and "end_positions" in input_spec: self.label_cols = ["start_positions", "end_positions"] self.use_keras_label = False logging.warning( "No label_cols specified for KerasMetricCallback, assuming you want the " "start_positions and end_positions keys." ) else: raise ValueError("Could not autodetect label_cols for KerasMetricCallback, please specify them!") if parse(tf.__version__) < parse("2.7"): logging.warning("TF versions less than 2.7 may encounter issues with KerasMetricCallback!") self.use_xla_generation = use_xla_generation self.generate_kwargs = {} if generate_kwargs is None else generate_kwargs self.generation_function = None @staticmethod def _concatenate_batches(batches, padding_index=-100): # If all batches are unidimensional or same length, do a simple concatenation if batches[0].ndim == 1 or all([batch.shape[1] == batches[0].shape[1] for batch in batches]): return np.concatenate(batches, axis=0) # Welp, they're not the same length. Let's do some padding max_len = max([batch.shape[1] for batch in batches]) num_samples = sum([batch.shape[0] for batch in batches]) output = np.full_like( batches[0], fill_value=padding_index, shape=[num_samples, max_len] + list(batches[0].shape[2:]) ) # i keeps track of which part of the concatenated array we're writing the next batch to i = 0 for batch in batches: output[i : i + len(batch), : batch.shape[1]] = batch i += len(batch) return output def _postprocess_predictions_or_labels(self, inputs): if isinstance(inputs[0], dict): outputs = {} for key in inputs[0].keys(): outputs[key] = self._concatenate_batches([batch[key] for batch in inputs]) # If it's a dict with only one key, just return the array if len(outputs) == 1: outputs = list(outputs.values())[0] elif isinstance(inputs[0], list) or isinstance(inputs[0], tuple): outputs = [] for input_list in zip(*inputs): outputs.append(self._concatenate_batches(input_list)) if len(outputs) == 1: outputs = outputs[0] # If it's a list with only one element, just return the array elif isinstance(inputs[0], np.ndarray): outputs = self._concatenate_batches(inputs) elif isinstance(inputs[0], tf.Tensor): outputs = self._concatenate_batches([tensor.numpy() for tensor in inputs]) else: raise TypeError(f"Couldn't handle batch of type {type(inputs[0])}!") return outputs def on_epoch_end(self, epoch, logs=None): if hasattr(self.model, "config"): ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] main_input_name = None if self.predict_with_generate: # This dense conditional recognizes the case where we have an encoder-decoder model, but # avoids getting tangled up when we just have a model with a layer called 'encoder' if hasattr(self.model, "encoder") and hasattr(self.model.encoder, "main_input_name"): if self.model.encoder.main_input_name != self.model.main_input_name: main_input_name = self.model.encoder.main_input_name else: main_input_name = getattr(self.model, "main_input_name", "input_ids") if self.use_xla_generation and self.generation_function is None: def generation_function(inputs, attention_mask): return self.model.generate(inputs, attention_mask=attention_mask, **self.generate_kwargs) self.generation_function = tf.function(generation_function, jit_compile=True) prediction_list = [] label_list = [] # The whole predict/generate loop is handled inside this method for batch in self.eval_dataset: if isinstance(batch, tuple): batch, labels = batch else: labels = None if self.predict_with_generate: if isinstance(batch, dict): generation_inputs = batch[main_input_name] attention_mask = batch.get("attention_mask", None) else: generation_inputs = batch attention_mask = None if self.use_xla_generation: predictions = self.generation_function(generation_inputs, attention_mask=attention_mask) else: predictions = self.model.generate(generation_inputs, attention_mask=attention_mask) else: predictions = self.model.predict_on_batch(batch) if isinstance(predictions, dict): # This converts any dict-subclass to a regular dict # Keras REALLY doesn't like it when we pass around a BatchEncoding or other derived class predictions = dict(predictions) if self.output_cols is not None: predictions = {key: predictions[key] for key in self.output_cols} else: predictions = { key: val for key, val in predictions.items() if key not in ignore_keys + ["loss"] } prediction_list.append(predictions) if not self.use_keras_label: labels = {key: batch[key].numpy() for key in self.label_cols} elif isinstance(labels, dict): labels = {key: array.numpy() for key, array in labels.items()} elif isinstance(labels, list) or isinstance(labels, tuple): labels = [array.numpy() for array in labels] elif isinstance(labels, tf.Tensor): labels = labels.numpy() else: raise TypeError(f"Confused by labels of type {type(labels)}") label_list.append(labels) all_preds = self._postprocess_predictions_or_labels(prediction_list) all_labels = self._postprocess_predictions_or_labels(label_list) metric_output = self.metric_fn((all_preds, all_labels)) if not isinstance(metric_output, dict): raise TypeError( f"metric_fn should return a dict mapping metric names to values but instead returned {metric_output}" ) # This is the critical bit - Keras passes a dict containing the loss and standard metric values for this epoch # in the logs argument. Ordinarily, this is so the callback can read them, but in this case we write a bunch of # new keys in there, which will then get read by the History callback and treated like any other metric value. # I promise that I have it in writing from Chollet that this is okay. logs.update(metric_output) class PushToHubCallback(Callback): """ Callback that will save and push the model to the Hub regularly. By default, it pushes once per epoch, but this can be changed with the `save_strategy` argument. Pushed models can be accessed like any other model on the hub, such as with the `from_pretrained` method. ```py from transformers.keras_callbacks import PushToHubCallback push_to_hub_callback = PushToHubCallback( output_dir="./model_save", tokenizer=tokenizer, hub_model_id="gpt5-7xlarge", ) model.fit(train_dataset, callbacks=[push_to_hub_callback]) ``` Args: output_dir (`str`): The output directory where the model predictions and checkpoints will be written and synced with the repository on the Hub. save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"epoch"`): The checkpoint save strategy to adopt during training. Possible values are: - `"no"`: Save is done at the end of training. - `"epoch"`: Save is done at the end of each epoch. - `"steps"`: Save is done every `save_steps` save_steps (`int`, *optional*): The number of steps between saves when using the "steps" `save_strategy`. tokenizer (`PreTrainedTokenizerBase`, *optional*): The tokenizer used by the model. If supplied, will be uploaded to the repo alongside the weights. hub_model_id (`str`, *optional*): The name of the repository to keep in sync with the local `output_dir`. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance `"user_name/model"`, which allows you to push to an organization you are a member of with `"organization_name/model"`. Will default to the name of `output_dir`. hub_token (`str`, *optional*): The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with `huggingface-cli login`. checkpoint (`bool`, *optional*, defaults to `False`): Whether to save full training checkpoints (including epoch and optimizer state) to allow training to be resumed. Only usable when `save_strategy` is `"epoch"`. """ def __init__( self, output_dir: Union[str, Path], save_strategy: Union[str, IntervalStrategy] = "epoch", save_steps: Optional[int] = None, tokenizer: Optional[PreTrainedTokenizerBase] = None, hub_model_id: Optional[str] = None, hub_token: Optional[str] = None, checkpoint: bool = False, **model_card_args, ): super().__init__() if checkpoint and save_strategy != "epoch": raise ValueError("Cannot save checkpoints when save_strategy is not 'epoch'!") if isinstance(save_strategy, str): save_strategy = IntervalStrategy(save_strategy.lower()) self.save_strategy = save_strategy if self.save_strategy == IntervalStrategy.STEPS and (not isinstance(save_steps, int) or save_steps <= 0): raise ValueError("Please supply a positive integer argument for save_steps when save_strategy == 'steps'!") self.save_steps = save_steps output_dir = Path(output_dir) if hub_model_id is None: hub_model_id = output_dir.absolute().name if "/" not in hub_model_id: hub_model_id = get_full_repo_name(hub_model_id, token=hub_token) self.output_dir = output_dir self.hub_model_id = hub_model_id create_repo(self.hub_model_id, exist_ok=True) self.repo = Repository(str(self.output_dir), clone_from=self.hub_model_id, token=hub_token) self.tokenizer = tokenizer self.last_job = None self.checkpoint = checkpoint self.training_history = None self.model_card_args = model_card_args def on_train_begin(self, logs=None): # Although we can access model.history, we have no guarantees that the History callback will fire before this # one, so we keep track of it here too self.training_history = [] def on_train_batch_end(self, batch, logs=None): if self.save_strategy == IntervalStrategy.STEPS and (batch + 1) % self.save_steps == 0: if self.last_job is not None and not self.last_job.is_done: return # The last upload is still running, don't start another self.model.save_pretrained(self.output_dir) if self.tokenizer is not None: self.tokenizer.save_pretrained(self.output_dir) _, self.last_job = self.repo.push_to_hub( commit_message=f"Training in progress steps {batch}", blocking=False ) def on_epoch_end(self, epoch, logs=None): logs = logs.copy() # Don't accidentally write things that Keras will read later if "epoch" not in logs: logs["epoch"] = epoch self.training_history.append(logs) if self.save_strategy == IntervalStrategy.EPOCH: if self.last_job is not None and not self.last_job.is_done: return # The last upload is still running, don't start another self.model.save_pretrained(self.output_dir) if self.tokenizer is not None: self.tokenizer.save_pretrained(self.output_dir) if self.checkpoint: checkpoint_dir = os.path.join(self.output_dir, "checkpoint") self.model._save_checkpoint(checkpoint_dir, epoch) train_summary = TrainingSummary.from_keras( model=self.model, model_name=self.hub_model_id, keras_history=self.training_history, **self.model_card_args, ) model_card = train_summary.to_model_card() with (self.output_dir / "README.md").open("w") as f: f.write(model_card) _, self.last_job = self.repo.push_to_hub( commit_message=f"Training in progress epoch {epoch}", blocking=False ) def on_train_end(self, logs=None): # Makes sure the latest version of the model is uploaded if self.last_job is not None and not self.last_job.is_done: logging.info("Pushing the last epoch to the Hub, this may take a while...") while not self.last_job.is_done: sleep(1) else: self.model.save_pretrained(self.output_dir) if self.tokenizer is not None: self.tokenizer.save_pretrained(self.output_dir) train_summary = TrainingSummary.from_keras( model=self.model, model_name=self.hub_model_id, keras_history=self.training_history, **self.model_card_args, ) model_card = train_summary.to_model_card() with (self.output_dir / "README.md").open("w") as f: f.write(model_card) self.repo.push_to_hub(commit_message="End of training", blocking=True)
233zzh/TitanDataOperationSystem
1,738
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/examples.css
* { padding: 0; margin: 0; vertical-align: top; } body { background: url(background.png) repeat-x; font: 18px/1.5em "proxima-nova", Helvetica, Arial, sans-serif; } a { color: #069; } a:hover { color: #28b; } h2 { margin-top: 15px; font: normal 32px "omnes-pro", Helvetica, Arial, sans-serif; } h3 { margin-left: 30px; font: normal 26px "omnes-pro", Helvetica, Arial, sans-serif; color: #666; } p { margin-top: 10px; } button { font-size: 18px; padding: 1px 7px; } input { font-size: 18px; } input[type=checkbox] { margin: 7px; } #header { position: relative; width: 900px; margin: auto; } #header h2 { margin-left: 10px; vertical-align: middle; font-size: 42px; font-weight: bold; text-decoration: none; color: #000; } #content { width: 880px; margin: 0 auto; padding: 10px; } #footer { margin-top: 25px; margin-bottom: 10px; text-align: center; font-size: 12px; color: #999; } .demo-container { box-sizing: border-box; width: 850px; height: 450px; padding: 20px 15px 15px 15px; margin: 15px auto 30px auto; border: 1px solid #ddd; background: #fff; background: linear-gradient(#f6f6f6 0, #fff 50px); background: -o-linear-gradient(#f6f6f6 0, #fff 50px); background: -ms-linear-gradient(#f6f6f6 0, #fff 50px); background: -moz-linear-gradient(#f6f6f6 0, #fff 50px); background: -webkit-linear-gradient(#f6f6f6 0, #fff 50px); box-shadow: 0 3px 10px rgba(0,0,0,0.15); -o-box-shadow: 0 3px 10px rgba(0,0,0,0.1); -ms-box-shadow: 0 3px 10px rgba(0,0,0,0.1); -moz-box-shadow: 0 3px 10px rgba(0,0,0,0.1); -webkit-box-shadow: 0 3px 10px rgba(0,0,0,0.1); } .demo-placeholder { width: 100%; height: 100%; font-size: 14px; line-height: 1.2em; } .legend table { border-spacing: 5px; }
274056675/springboot-openai-chatgpt
1,078
mng_web/src/router/views/index.js
import Layout from '@/page/index/' import research from '@/research/router/index.js'; export default [{ path: '/wel', component: Layout, redirect: '/wel/index', children: [{ path: 'index', name: '首页', meta: { i18n: 'dashboard' }, component: () => import( /* webpackChunkName: "views" */ '@/views/wel/index') }, { path: 'dashboard', name: '控制台', meta: { i18n: 'dashboard', menu: false, }, component: () => import( /* webpackChunkName: "views" */ '@/views/wel/dashboard') }] }, { path: '/test', component: Layout, redirect: '/test/index', children: [{ path: 'index', name: '测试页', meta: { i18n: 'test' }, component: () => import( /* webpackChunkName: "views" */ '@/views/util/test') }] }, { path: '/info', component: Layout, redirect: '/info/index', children: [{ path: 'index', name: '个人信息', meta: { i18n: 'info' }, component: () => import( /* webpackChunkName: "views" */ '@/views/user/info') }] }, ...research, ]
274056675/springboot-openai-chatgpt
5,047
mng_web/src/research/util/print.js
// 打印类属性、方法定义 /* eslint-disable */ const Print = function (dom, options) { if (!(this instanceof Print)) return new Print(dom, options); this.options = this.extend({ 'noPrint': '.no-print' }, options); if ((typeof dom) === "string") { this.dom = document.querySelector(dom); } else { this.isDOM(dom) this.dom = this.isDOM(dom) ? dom : dom.$el; } this.init(); }; Print.prototype = { init: function () { var content = this.getStyle() + this.getHtml(); this.writeIframe(content); }, extend: function (obj, obj2) { for (var k in obj2) { obj[k] = obj2[k]; } return obj; }, getStyle: function () { var str = "", styles = document.querySelectorAll('style,link'); for (var i = 0; i < styles.length; i++) { str += styles[i].outerHTML; } str += "<style>" + (this.options.noPrint ? this.options.noPrint : '.no-print') + "{display:none;}</style>"; str += "<style>html,body,div{height: auto!important;font-size:14px}</style>"; return str; }, getHtml: function () { var inputs = document.querySelectorAll('input'); var textareas = document.querySelectorAll('textarea'); var selects = document.querySelectorAll('select'); for (var k = 0; k < inputs.length; k++) { if (inputs[k].type == "checkbox" || inputs[k].type == "radio") { if (inputs[k].checked == true) { inputs[k].setAttribute('checked', "checked") } else { inputs[k].removeAttribute('checked') } } else if (inputs[k].type == "text") { inputs[k].setAttribute('value', inputs[k].value) } else { inputs[k].setAttribute('value', inputs[k].value) } } for (var k2 = 0; k2 < textareas.length; k2++) { if (textareas[k2].type == 'textarea') { textareas[k2].innerHTML = textareas[k2].value } } for (var k3 = 0; k3 < selects.length; k3++) { if (selects[k3].type == 'select-one') { var child = selects[k3].children; for (var i in child) { if (child[i].tagName == 'OPTION') { if (child[i].selected == true) { child[i].setAttribute('selected', "selected") } else { child[i].removeAttribute('selected') } } } } } var outerHTML = this.wrapperRefDom(this.dom).outerHTML; // 修改html 进行分页 if (outerHTML.indexOf('class="avue-form-work-style">') != -1) { outerHTML = outerHTML.replace('</div></div></div></div></body></html>', '') outerHTML = outerHTML.split('class="avue-form-work-style">')[1] outerHTML = outerHTML.replace(`" id="test-print"`, ` avue-form-work-style" id="test-print"`) } else { outerHTML = outerHTML.replace('</div></div></div></div></body></html>', '') outerHTML = outerHTML.split('class="avue-form-form-style">')[1] } return outerHTML; }, // 向父级元素循环,包裹当前需要打印的元素 // 防止根级别开头的 css 选择器不生效 wrapperRefDom: function wrapperRefDom(refDom) { var prevDom = null; var currDom = refDom; // 判断当前元素是否在 body 中,不在文档中则直接返回该节点 if (!this.isInBody(currDom)) return currDom; while (currDom) { if (prevDom) { var element = currDom.cloneNode(false); element.appendChild(prevDom); prevDom = element; } else { prevDom = currDom.cloneNode(true); } currDom = currDom.parentElement; } return prevDom; }, writeIframe: function (content) { var w, doc, iframe = document.createElement('iframe'), f = document.body.appendChild(iframe); iframe.id = "myIframe"; //iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;"; iframe.setAttribute('style', 'position:absolute;width:0;height:0;top:-10px;left:-10px;'); w = f.contentWindow || f.contentDocument; doc = f.contentDocument || f.contentWindow.document; doc.open(); doc.write(content); doc.close(); var _this = this iframe.onload = function () { _this.toPrint(w); setTimeout(function () { document.body.removeChild(iframe) }, 100) } }, toPrint: function (frameWindow) { try { setTimeout(function () { frameWindow.focus(); try { if (!frameWindow.document.execCommand('print', false, null)) { frameWindow.print(); } } catch (e) { frameWindow.print(); } frameWindow.close(); }, 10); } catch (err) { } }, // 检查一个元素是否是 body 元素的后代元素且非 body 元素本身 isInBody: function isInBody(node) { return node === document.body ? false : document.body.contains(node); }, isDOM: (typeof HTMLElement === 'object') ? function (obj) { return obj instanceof HTMLElement; } : function (obj) { return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string'; } }; const MyPlugin = {} MyPlugin.install = function (Vue, options) { // 4. 添加实例方法 Vue.prototype.$print = Print } export default MyPlugin
27182812/ChatGLM-LLaMA-chinese-insturct
34,694
src/transformers/trainer_tf.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. """Tensorflow trainer class.""" import datetime import math import os import warnings from typing import Callable, Dict, Optional, Tuple from .utils import ENV_VARS_TRUE_VALUES # Integrations must be imported before ML frameworks: # isort: off from .integrations import ( is_comet_available, is_wandb_available, ) # isort: on import numpy as np import tensorflow as tf from tensorflow.python.distribute.values import PerReplica from .modeling_tf_utils import TFPreTrainedModel from .optimization_tf import GradientAccumulator, create_optimizer from .trainer_utils import ( PREFIX_CHECKPOINT_DIR, EvalPrediction, IntervalStrategy, PredictionOutput, enable_full_determinism, set_seed, ) from .training_args_tf import TFTrainingArguments from .utils import logging if is_wandb_available(): import wandb if is_comet_available(): import comet_ml logger = logging.get_logger(__name__) class TFTrainer: """ TFTrainer is a simple but feature-complete training and eval loop for TensorFlow, optimized for 🤗 Transformers. Args: model ([`TFPreTrainedModel`]): The model to train, evaluate or use for predictions. args ([`TFTrainingArguments`]): The arguments to tweak training. train_dataset ([`~tf.data.Dataset`], *optional*): The dataset to use for training. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labels` is the labels. If `labels` is a tensor, the loss is calculated by the model by calling `model(features, labels=labels)`. If `labels` is a dict, such as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling `model(features, **labels)`. eval_dataset ([`~tf.data.Dataset`], *optional*): The dataset to use for evaluation. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labels` is the labels. If `labels` is a tensor, the loss is calculated by the model by calling `model(features, labels=labels)`. If `labels` is a dict, such as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling `model(features, **labels)`. compute_metrics (`Callable[[EvalPrediction], Dict]`, *optional*): The function that will be used to compute metrics at evaluation. Must take a [`EvalPrediction`] and return a dictionary string to metric values. tb_writer (`tf.summary.SummaryWriter`, *optional*): Object to write to TensorBoard. optimizers (`Tuple[tf.keras.optimizers.Optimizer, tf.keras.optimizers.schedules.LearningRateSchedule]`, *optional*): A tuple containing the optimizer and the scheduler to use. The optimizer default to an instance of [`tf.keras.optimizers.Adam`] if `args.weight_decay_rate` is 0 else an instance of [`AdamWeightDecay`]. The scheduler will default to an instance of [`tf.keras.optimizers.schedules.PolynomialDecay`] if `args.num_warmup_steps` is 0 else an instance of [`WarmUp`]. """ def __init__( self, model: TFPreTrainedModel, args: TFTrainingArguments, train_dataset: Optional[tf.data.Dataset] = None, eval_dataset: Optional[tf.data.Dataset] = None, compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, tb_writer: Optional[tf.summary.SummaryWriter] = None, optimizers: Tuple[tf.keras.optimizers.Optimizer, tf.keras.optimizers.schedules.LearningRateSchedule] = ( None, None, ), ): self.model = model self.args = args self.train_dataset = train_dataset self.eval_dataset = eval_dataset self.compute_metrics = compute_metrics self.optimizer, self.lr_scheduler = optimizers self.gradient_accumulator = GradientAccumulator() self.global_step = 0 self.epoch_logging = 0 self.eval_loss = tf.keras.metrics.Sum() warnings.warn( "The class `TFTrainer` is deprecated and will be removed in version 5 of Transformers. " "We recommend using native Keras instead, by calling methods like `fit()` and `predict()` " "directly on the model object. Detailed examples of the Keras style can be found in our " "examples at https://github.com/huggingface/transformers/tree/main/examples/tensorflow", FutureWarning, ) if tb_writer is not None: self.tb_writer = tb_writer else: self.tb_writer = tf.summary.create_file_writer(self.args.logging_dir) if is_wandb_available(): self.setup_wandb() elif os.getenv("WANDB_DISABLED", "").upper() not in ENV_VARS_TRUE_VALUES: logger.info( "You are instantiating a Trainer but W&B is not installed. To use wandb logging, " "run `pip install wandb && wandb login` see https://docs.wandb.com/huggingface." ) if is_comet_available(): self.setup_comet() elif os.environ.get("COMET_MODE") != "DISABLED": logger.info( "To use comet_ml logging, run `pip/conda install comet_ml` " "see https://www.comet.ml/docs/python-sdk/huggingface/" ) enable_full_determinism(self.args.seed) if self.args.full_determinism else set_seed(self.args.seed) def get_train_tfdataset(self) -> tf.data.Dataset: """ Returns the training [`~tf.data.Dataset`]. Subclass and override this method if you want to inject some custom behavior. """ if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") self.total_train_batch_size = self.args.train_batch_size * self.args.gradient_accumulation_steps self.num_train_examples = self.train_dataset.cardinality().numpy() if self.num_train_examples < 0: raise ValueError("The training dataset must have an asserted cardinality") ds = ( self.train_dataset.repeat() .shuffle(self.num_train_examples, seed=self.args.seed) .batch(self.total_train_batch_size, drop_remainder=self.args.dataloader_drop_last) .prefetch(tf.data.experimental.AUTOTUNE) ) return self.args.strategy.experimental_distribute_dataset(ds) def get_eval_tfdataset(self, eval_dataset: Optional[tf.data.Dataset] = None) -> tf.data.Dataset: """ Returns the evaluation [`~tf.data.Dataset`]. Args: eval_dataset ([`~tf.data.Dataset`], *optional*): If provided, will override *self.eval_dataset*. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labels` is the labels. If `labels` is a tensor, the loss is calculated by the model by calling `model(features, labels=labels)`. If `labels` is a dict, such as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling `model(features, **labels)`. Subclass and override this method if you want to inject some custom behavior. """ if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset num_examples = eval_dataset.cardinality().numpy() if num_examples < 0: raise ValueError("The training dataset must have an asserted cardinality") approx = math.floor if self.args.dataloader_drop_last else math.ceil steps = approx(num_examples / self.args.eval_batch_size) ds = ( eval_dataset.repeat() .batch(self.args.eval_batch_size, drop_remainder=self.args.dataloader_drop_last) .prefetch(tf.data.experimental.AUTOTUNE) ) return self.args.strategy.experimental_distribute_dataset(ds), steps, num_examples def get_test_tfdataset(self, test_dataset: tf.data.Dataset) -> tf.data.Dataset: """ Returns a test [`~tf.data.Dataset`]. Args: test_dataset ([`~tf.data.Dataset`]): The dataset to use. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labels` is the labels. If `labels` is a tensor, the loss is calculated by the model by calling `model(features, labels=labels)`. If `labels` is a dict, such as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling `model(features, **labels)`. Subclass and override this method if you want to inject some custom behavior. """ num_examples = test_dataset.cardinality().numpy() if num_examples < 0: raise ValueError("The training dataset must have an asserted cardinality") steps = math.ceil(num_examples / self.args.eval_batch_size) ds = test_dataset.batch(self.args.eval_batch_size).prefetch(tf.data.experimental.AUTOTUNE) return self.args.strategy.experimental_distribute_dataset(ds), steps, num_examples def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the TFTrainer's init through `optimizers`, or subclass and override this method. """ if not self.optimizer and not self.lr_scheduler: warmup_steps = ( self.args.warmup_steps if self.args.warmup_steps > 0 else math.ceil(num_training_steps * self.args.warmup_ratio) ) self.optimizer, self.lr_scheduler = create_optimizer( self.args.learning_rate, num_training_steps, warmup_steps, adam_beta1=self.args.adam_beta1, adam_beta2=self.args.adam_beta2, adam_epsilon=self.args.adam_epsilon, weight_decay_rate=self.args.weight_decay, power=self.args.poly_power, ) def setup_wandb(self): """ Setup the optional Weights & Biases (`wandb`) integration. One can subclass and override this method to customize the setup if needed. Find more information `here <https://docs.wandb.com/huggingface>`__. You can also override the following environment variables: Environment: WANDB_PROJECT: (Optional): str - "huggingface" by default, set this to a custom string to store results in a different project. WANDB_DISABLED: (Optional): boolean - defaults to false, set to "true" to disable wandb entirely. """ logger.info('Automatic Weights & Biases logging enabled, to disable set os.environ["WANDB_DISABLED"] = "true"') combined_dict = {**self.model.config.to_dict(), **self.args.to_sanitized_dict()} wandb.init(project=os.getenv("WANDB_PROJECT", "huggingface"), config=combined_dict, name=self.args.run_name) def setup_comet(self): """ Setup the optional Comet.ml integration. Environment: COMET_MODE: (Optional): str - "OFFLINE", "ONLINE", or "DISABLED" COMET_PROJECT_NAME: (Optional): str - Comet.ml project name for experiments COMET_OFFLINE_DIRECTORY: (Optional): str - folder to use for saving offline experiments when `COMET_MODE` is "OFFLINE" For a number of configurable items in the environment, see `here <https://www.comet.ml/docs/python-sdk/advanced/#comet-configuration-variables>`__ """ comet_mode = os.getenv("COMET_MODE", "ONLINE").upper() args = {"project_name": os.getenv("COMET_PROJECT_NAME", "huggingface")} experiment = None if comet_mode == "ONLINE": experiment = comet_ml.Experiment(**args) logger.info("Automatic Comet.ml online logging enabled") elif comet_mode == "OFFLINE": args["offline_directory"] = os.getenv("COMET_OFFLINE_DIRECTORY", "./") experiment = comet_ml.OfflineExperiment(**args) logger.info("Automatic Comet.ml offline logging enabled; use `comet upload` when finished") if experiment is not None: experiment._set_model_graph(self.model, framework="transformers") experiment._log_parameters(self.args, prefix="args/", framework="transformers") experiment._log_parameters(self.model.config, prefix="config/", framework="transformers") def prediction_loop( self, dataset: tf.data.Dataset, steps: int, num_examples: int, description: str, prediction_loss_only: Optional[bool] = None, ) -> PredictionOutput: """ Prediction/evaluation loop, shared by [`~TFTrainer.evaluate`] and [`~TFTrainer.predict`]. Works both with or without labels. """ prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) logger.info(f"***** Running {description} *****") logger.info(f" Num examples in dataset = {num_examples}") if description == "Evaluation": logger.info(f" Num examples in used in evaluation = {self.args.eval_batch_size * steps}") logger.info(f" Batch size = {self.args.eval_batch_size}") label_ids: np.ndarray = None preds: np.ndarray = None self.eval_loss.reset_states() # Reset the past mems state at the beginning of the evaluation if necessary. if self.args.past_index >= 0: self._past = None for step, batch in enumerate(dataset): logits = self.distributed_prediction_steps(batch) _, labels = batch if not prediction_loss_only: if isinstance(logits, tuple): logits = logits[0] if isinstance(labels, tuple): labels = labels[0] if self.args.n_replicas > 1: for val in logits.values: if preds is None: preds = val.numpy() else: preds = np.append(preds, val.numpy(), axis=0) for val in labels.values: if label_ids is None: label_ids = val.numpy() else: label_ids = np.append(label_ids, val.numpy(), axis=0) else: if preds is None: preds = logits.numpy() else: preds = np.append(preds, logits.numpy(), axis=0) if label_ids is None: label_ids = labels.numpy() else: label_ids = np.append(label_ids, labels.numpy(), axis=0) if step == steps - 1: break if self.compute_metrics is not None and preds is not None and label_ids is not None: metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids)) else: metrics = {} metrics["eval_loss"] = self.eval_loss.result().numpy() / steps for key in list(metrics.keys()): if not key.startswith("eval_"): metrics[f"eval_{key}"] = metrics.pop(key) if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics) def log(self, logs: Dict[str, float]) -> None: """ Log `logs` on the various objects watching training. Subclass and override this method to inject custom behavior. Args: logs (`Dict[str, float]`): The values to log. """ logs["epoch"] = self.epoch_logging if self.tb_writer: with self.tb_writer.as_default(): for k, v in logs.items(): tf.summary.scalar(k, v, step=self.global_step) self.tb_writer.flush() if is_wandb_available(): wandb.log(logs, step=self.global_step) if is_comet_available(): experiment = comet_ml.config.get_global_experiment() if experiment is not None: experiment._log_metrics( logs, step=self.global_step, epoch=self.epoch_logging, framework="transformers" ) output = {**logs, **{"step": self.global_step}} logger.info(output) def evaluate(self, eval_dataset: Optional[tf.data.Dataset] = None) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). Args: eval_dataset ([`~tf.data.Dataset`], *optional*): Pass a dataset if you wish to override `self.eval_dataset`. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labels` is the labels. If `labels` is a tensor, the loss is calculated by the model by calling `model(features, labels=labels)`. If `labels` is a dict, such as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling `model(features, **labels)`. Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. """ eval_ds, steps, num_examples = self.get_eval_tfdataset(eval_dataset) output = self.prediction_loop(eval_ds, steps, num_examples, description="Evaluation") logs = {**output.metrics} logs["epoch"] = self.epoch_logging self.log(logs) return output.metrics def prediction_step( self, features: tf.Tensor, labels: tf.Tensor, nb_instances_in_global_batch: tf.Tensor ) -> tf.Tensor: """ Compute the prediction on features and update the loss with labels. Subclass and override to inject some custom behavior. """ per_example_loss, logits = self.run_model(features, labels, False) scaled_loss = per_example_loss / tf.cast(nb_instances_in_global_batch, dtype=per_example_loss.dtype) self.eval_loss.update_state(scaled_loss) return logits @tf.function def distributed_prediction_steps(self, batch): nb_instances_in_batch = self._compute_nb_instances(batch) inputs = self._get_step_inputs(batch, nb_instances_in_batch) logits = self.args.strategy.run(self.prediction_step, inputs) return logits def train(self) -> None: """ Train method to train the model. """ train_ds = self.get_train_tfdataset() if self.args.debug: tf.summary.trace_on(graph=True, profiler=True) self.gradient_accumulator.reset() num_update_steps_per_epoch = self.num_train_examples / self.total_train_batch_size # In fact, ``self.args.dataloader_drop_last`` has no effect in `trainer_tf.py`, because # the dataset is repeated before being batched. # It has the effect only when TPU is used which requires explicit tensor shape in order to make # the gradient accumulation implementation work. approx = math.floor if self.args.dataloader_drop_last else math.ceil num_update_steps_per_epoch = approx(num_update_steps_per_epoch) # At least one update for each epoch. num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) self.steps_per_epoch = num_update_steps_per_epoch if self.args.max_steps > 0: t_total = self.args.max_steps epochs = (self.args.max_steps // self.steps_per_epoch) + int( self.args.max_steps % self.steps_per_epoch > 0 ) else: t_total = self.steps_per_epoch * self.args.num_train_epochs epochs = self.args.num_train_epochs # Since ``self.args.num_train_epochs`` can be `float`, we make ``epochs`` be a `float` always. epochs = float(epochs) with self.args.strategy.scope(): self.create_optimizer_and_scheduler(num_training_steps=t_total) folder = os.path.join(self.args.output_dir, PREFIX_CHECKPOINT_DIR) ckpt = tf.train.Checkpoint(optimizer=self.optimizer, model=self.model) self.model.ckpt_manager = tf.train.CheckpointManager(ckpt, folder, max_to_keep=self.args.save_total_limit) iterations = self.optimizer.iterations epochs_trained = 0 steps_trained_in_current_epoch = 0 if self.model.ckpt_manager.latest_checkpoint: logger.info( f"Checkpoint file {self.model.ckpt_manager.latest_checkpoint} found and restoring from checkpoint" ) ckpt.restore(self.model.ckpt_manager.latest_checkpoint).expect_partial() self.global_step = iterations.numpy() epochs_trained = self.global_step // self.steps_per_epoch steps_trained_in_current_epoch = self.global_step % self.steps_per_epoch logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(f" Continuing training from epoch {epochs_trained}") logger.info(f" Continuing training from global step {self.global_step}") logger.info(f" Will skip the first {steps_trained_in_current_epoch} steps in the first epoch") tf.summary.experimental.set_step(self.global_step) with self.tb_writer.as_default(): tf.summary.text("args", self.args.to_json_string()) self.tb_writer.flush() logger.info("***** Running training *****") logger.info(f" Num examples = {self.num_train_examples}") # TODO: We might want to print a more precise ``epochs`` if self.args.max_steps > 0 ? logger.info(f" Num Epochs = {epochs}") logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size}") logger.info( f" Total train batch size (w. parallel, distributed & accumulation) = {self.total_train_batch_size}" ) logger.info(f" Gradient Accumulation steps = {self.args.gradient_accumulation_steps}") logger.info(f" Steps per epoch = {self.steps_per_epoch}") logger.info(f" Total optimization steps = {t_total}") self.train_loss = tf.keras.metrics.Sum() start_time = datetime.datetime.now() for epoch_iter in range(epochs_trained, int(epochs)): # Reset the past mems state at the beginning of each epoch if necessary. if self.args.past_index >= 0: self._past = None for step, batch in enumerate(train_ds): # Skip past any already trained steps if resuming training if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue self.distributed_training_steps(batch) self.global_step = iterations.numpy() self.epoch_logging = epoch_iter + (step + 1) / self.steps_per_epoch training_loss = self.train_loss.result() / (step + 1) if self.args.debug: logs = {} logs["loss"] = training_loss.numpy() logs["epoch"] = self.epoch_logging self.log(logs) if self.global_step == 1 and self.args.debug: with self.tb_writer.as_default(): tf.summary.trace_export( name="training", step=self.global_step, profiler_outdir=self.args.logging_dir ) if ( self.args.eval_steps > 0 and self.args.evaluation_strategy == IntervalStrategy.STEPS and self.global_step % self.args.eval_steps == 0 ): self.evaluate() if (self.args.logging_steps > 0 and self.global_step % self.args.logging_steps == 0) or ( self.global_step == 1 and self.args.logging_first_step ): logs = {} logs["loss"] = training_loss.numpy() logs["learning_rate"] = self.lr_scheduler(self.global_step).numpy() logs["epoch"] = self.epoch_logging self.log(logs) if self.args.save_steps > 0 and self.global_step % self.args.save_steps == 0: ckpt_save_path = self.model.ckpt_manager.save() logger.info(f"Saving checkpoint for step {self.global_step} at {ckpt_save_path}") if self.args.max_steps > 0 and self.global_step >= t_total: break if self.global_step % self.steps_per_epoch == 0: break self.train_loss.reset_states() if self.args.max_steps > 0 and self.global_step >= self.args.max_steps: break end_time = datetime.datetime.now() logger.info(f"Training took: {str(end_time - start_time)}") if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") def training_step(self, features, labels, nb_instances_in_global_batch): """ Perform a training step on features and labels. Subclass and override to inject some custom behavior. """ per_example_loss, _ = self.run_model(features, labels, True) scaled_loss = per_example_loss / tf.cast(nb_instances_in_global_batch, dtype=per_example_loss.dtype) gradients = tf.gradients(scaled_loss, self.model.trainable_variables) gradients = [ g if g is not None else tf.zeros_like(v) for g, v in zip(gradients, self.model.trainable_variables) ] if self.args.gradient_accumulation_steps > 1: self.gradient_accumulator(gradients) self.train_loss.update_state(scaled_loss) if self.args.gradient_accumulation_steps == 1: return gradients def apply_gradients(self, features, labels, nb_instances_in_global_batch): if self.args.gradient_accumulation_steps == 1: gradients = self.training_step(features, labels, nb_instances_in_global_batch) self.optimizer.apply_gradients(list(zip(gradients, self.model.trainable_variables))) else: for _ in tf.range(self.args.gradient_accumulation_steps): reduced_features = { k: ft[: self.args.train_batch_size // self.args.n_replicas] for k, ft in features.items() } if tf.is_tensor(labels): reduced_labels = labels[: self.args.train_batch_size // self.args.n_replicas] elif isinstance(labels, dict): reduced_labels = { k: lbl[: self.args.train_batch_size // self.args.n_replicas] for k, lbl in labels.items() } else: raise ValueError("The labels must be either a tf.Tensor or a dict.") self.training_step(reduced_features, reduced_labels, nb_instances_in_global_batch) features = { k: tf.concat( [ft[self.args.train_batch_size // self.args.n_replicas :], reduced_features[k]], axis=0, ) for k, ft in features.items() } if tf.is_tensor(labels): labels = tf.concat( [labels[self.args.train_batch_size // self.args.n_replicas :], reduced_labels], axis=0 ) elif isinstance(labels, dict): labels = { k: tf.concat( [lbl[self.args.train_batch_size // self.args.n_replicas :], reduced_labels[k]], axis=0, ) for k, lbl in labels.items() } else: raise ValueError("The labels must be either a tf.Tensor or a dict.") gradients = self.gradient_accumulator.gradients gradients = [ (tf.clip_by_value(grad, -self.args.max_grad_norm, self.args.max_grad_norm)) for grad in gradients ] self.optimizer.apply_gradients(list(zip(gradients, self.model.trainable_variables))) self.gradient_accumulator.reset() @tf.function def distributed_training_steps(self, batch): with self.args.strategy.scope(): nb_instances_in_batch = self._compute_nb_instances(batch) inputs = self._get_step_inputs(batch, nb_instances_in_batch) self.args.strategy.run(self.apply_gradients, inputs) @staticmethod def _compute_nb_instances(batch): labels = batch[-1] if isinstance(labels, PerReplica): labels = tf.concat(labels.values, axis=0) nb_instances = tf.reduce_sum(tf.cast(labels != -100, dtype=tf.int32)) return nb_instances @staticmethod def _get_step_inputs(batch, nb_instances): features, labels = batch if isinstance(labels, PerReplica): # need to make a `PerReplica` objects for ``nb_instances`` nb_instances = PerReplica([nb_instances] * len(labels.values)) step_inputs = (features, labels, nb_instances) return step_inputs def run_model(self, features, labels, training): """ Computes the loss of the given features and labels pair. Subclass and override this method if you want to inject some custom behavior. Args: features (`tf.Tensor`): A batch of input features. labels (`tf.Tensor`): A batch of labels. training (`bool`): Whether or not to run the model in training mode. Returns: A tuple of two `tf.Tensor`: The loss and logits. """ if self.args.past_index >= 0 and getattr(self, "_past", None) is not None: features["mems"] = self._past if isinstance(labels, (dict)): outputs = self.model(features, training=training, **labels)[:2] else: outputs = self.model(features, labels=labels, training=training)[:2] loss, logits = outputs[:2] if self.args.past_index >= 0: self._past = outputs[self.args.past_index] return loss, logits def predict(self, test_dataset: tf.data.Dataset) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset ([`~tf.data.Dataset`]): Dataset to run the predictions on. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labels` is the labels. If `labels` is a tensor, the loss is calculated by the model by calling `model(features, labels=labels)`. If `labels` is a dict, such as when using a QuestionAnswering head model with multiple targets, the loss is instead calculated by calling `model(features, **labels)` Returns: *NamedTuple* A namedtuple with the following keys: - predictions (`np.ndarray`): The predictions on `test_dataset`. - label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some). - metrics (`Dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained labels). """ test_ds, steps, num_examples = self.get_test_tfdataset(test_dataset) return self.prediction_loop(test_ds, steps, num_examples, description="Prediction") def save_model(self, output_dir: Optional[str] = None): """ Will save the model, so you can reload it using `from_pretrained()`. """ output_dir = output_dir if output_dir is not None else self.args.output_dir logger.info(f"Saving model in {output_dir}") if not isinstance(self.model, TFPreTrainedModel): raise ValueError("Trainer.model appears to not be a PreTrainedModel") self.model.save_pretrained(output_dir)
233zzh/TitanDataOperationSystem
4,333
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/ajax/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: AJAX</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script type="text/javascript"> $(function() { var options = { lines: { show: true }, points: { show: true }, xaxis: { tickDecimals: 0, tickSize: 1 } }; var data = []; $.plot("#placeholder", data, options); // Fetch one series, adding to what we already have var alreadyFetched = {}; $("button.fetchSeries").click(function () { var button = $(this); // Find the URL in the link right next to us, then fetch the data var dataurl = button.siblings("a").attr("href"); function onDataReceived(series) { // Extract the first coordinate pair; jQuery has parsed it, so // the data is now just an ordinary JavaScript object var firstcoordinate = "(" + series.data[0][0] + ", " + series.data[0][1] + ")"; button.siblings("span").text("Fetched " + series.label + ", first point: " + firstcoordinate); // Push the new data onto our existing data array if (!alreadyFetched[series.label]) { alreadyFetched[series.label] = true; data.push(series); } $.plot("#placeholder", data, options); } $.ajax({ url: dataurl, type: "GET", dataType: "json", success: onDataReceived }); }); // Initiate a recurring data update $("button.dataUpdate").click(function () { data = []; alreadyFetched = {}; $.plot("#placeholder", data, options); var iteration = 0; function fetchData() { ++iteration; function onDataReceived(series) { // Load all the data in one pass; if we only got partial // data we could merge it with what we already have. data = [ series ]; $.plot("#placeholder", data, options); } // Normally we call the same URL - a script connected to a // database - but in this case we only have static example // files, so we need to modify the URL. $.ajax({ url: "data-eu-gdp-growth-" + iteration + ".json", type: "GET", dataType: "json", success: onDataReceived }); if (iteration < 5) { setTimeout(fetchData, 1000); } else { data = []; alreadyFetched = {}; } } setTimeout(fetchData, 1000); }); // Load the first series by default, so we don't have an empty plot $("button.fetchSeries:first").click(); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>AJAX</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder"></div> </div> <p>Example of loading data dynamically with AJAX. Percentage change in GDP (source: <a href="http://epp.eurostat.ec.europa.eu/tgm/table.do?tab=table&init=1&plugin=1&language=en&pcode=tsieb020">Eurostat</a>). Click the buttons below:</p> <p>The data is fetched over HTTP, in this case directly from text files. Usually the URL would point to some web server handler (e.g. a PHP page or Java/.NET/Python/Ruby on Rails handler) that extracts it from a database and serializes it to JSON.</p> <p> <button class="fetchSeries">First dataset</button> [ <a href="data-eu-gdp-growth.json">see data</a> ] <span></span> </p> <p> <button class="fetchSeries">Second dataset</button> [ <a href="data-japan-gdp-growth.json">see data</a> ] <span></span> </p> <p> <button class="fetchSeries">Third dataset</button> [ <a href="data-usa-gdp-growth.json">see data</a> ] <span></span> </p> <p>If you combine AJAX with setTimeout, you can poll the server for new data.</p> <p> <button class="dataUpdate">Poll for data</button> </p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
27182812/ChatGLM-LLaMA-chinese-insturct
3,567
src/transformers/file_utils.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. """ File utilities: utilities related to download and cache models This module should not be update anymore and is only left for backward compatibility. """ from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_apex_available, is_bs4_available, is_coloredlogs_available, is_datasets_available, is_detectron2_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_py3nvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tf2onnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bf16_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_onnx_dict_inputs_support_available, is_torch_tf32_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, torch_version, )
27182812/ChatGLM-LLaMA-chinese-insturct
47,127
src/transformers/trainer_pt_utils.py
# coding=utf-8 # Copyright 2020-present 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. """ Torch utilities for the Trainer class. """ import datetime import json import math import os import sys import warnings from collections.abc import Mapping from contextlib import contextmanager from dataclasses import dataclass from logging import StreamHandler from typing import Any, Dict, Iterator, List, Optional, Union import numpy as np import torch import torch.distributed as dist from torch import nn from torch.utils.data import Dataset, IterableDataset, RandomSampler, Sampler from torch.utils.data.distributed import DistributedSampler from .tokenization_utils_base import BatchEncoding from .utils import is_sagemaker_mp_enabled, is_torch_tpu_available, is_training_run_on_sagemaker, logging if is_training_run_on_sagemaker(): logging.add_handler(StreamHandler(sys.stdout)) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm # this is used to suppress an undesired warning emitted by pytorch versions 1.4.2-1.7.0 try: from torch.optim.lr_scheduler import SAVE_STATE_WARNING except ImportError: SAVE_STATE_WARNING = "" logger = logging.get_logger(__name__) def atleast_1d(tensor_or_array: Union[torch.Tensor, np.ndarray]): if isinstance(tensor_or_array, torch.Tensor): if hasattr(torch, "atleast_1d"): tensor_or_array = torch.atleast_1d(tensor_or_array) elif tensor_or_array.ndim < 1: tensor_or_array = tensor_or_array[None] else: tensor_or_array = np.atleast_1d(tensor_or_array) return tensor_or_array def torch_pad_and_concatenate(tensor1, tensor2, padding_index=-100): """Concatenates `tensor1` and `tensor2` on first axis, applying padding on the second if necessary.""" tensor1 = atleast_1d(tensor1) tensor2 = atleast_1d(tensor2) if len(tensor1.shape) == 1 or tensor1.shape[1] == tensor2.shape[1]: return torch.cat((tensor1, tensor2), dim=0) # Let's figure out the new shape new_shape = (tensor1.shape[0] + tensor2.shape[0], max(tensor1.shape[1], tensor2.shape[1])) + tensor1.shape[2:] # Now let's fill the result tensor result = tensor1.new_full(new_shape, padding_index) result[: tensor1.shape[0], : tensor1.shape[1]] = tensor1 result[tensor1.shape[0] :, : tensor2.shape[1]] = tensor2 return result def numpy_pad_and_concatenate(array1, array2, padding_index=-100): """Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary.""" array1 = atleast_1d(array1) array2 = atleast_1d(array2) if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]: return np.concatenate((array1, array2), axis=0) # Let's figure out the new shape new_shape = (array1.shape[0] + array2.shape[0], max(array1.shape[1], array2.shape[1])) + array1.shape[2:] # Now let's fill the result tensor result = np.full_like(array1, padding_index, shape=new_shape) result[: array1.shape[0], : array1.shape[1]] = array1 result[array1.shape[0] :, : array2.shape[1]] = array2 return result def nested_concat(tensors, new_tensors, padding_index=-100): """ Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or nested list/tuples/dict of tensors. """ assert type(tensors) == type( new_tensors ), f"Expected `tensors` and `new_tensors` to have the same type but found {type(tensors)} and {type(new_tensors)}." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_concat(t, n, padding_index=padding_index) for t, n in zip(tensors, new_tensors)) elif isinstance(tensors, torch.Tensor): return torch_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index) elif isinstance(tensors, Mapping): return type(tensors)( {k: nested_concat(t, new_tensors[k], padding_index=padding_index) for k, t in tensors.items()} ) elif isinstance(tensors, np.ndarray): return numpy_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index) else: raise TypeError(f"Unsupported type for concatenation: got {type(tensors)}") def find_batch_size(tensors): """ Find the first dimension of a tensor in a nested list/tuple/dict of tensors. """ if isinstance(tensors, (list, tuple)): for t in tensors: result = find_batch_size(t) if result is not None: return result elif isinstance(tensors, Mapping): for key, value in tensors.items(): result = find_batch_size(value) if result is not None: return result elif isinstance(tensors, torch.Tensor): return tensors.shape[0] if len(tensors.shape) >= 1 else None elif isinstance(tensors, np.ndarray): return tensors.shape[0] if len(tensors.shape) >= 1 else None def nested_numpify(tensors): "Numpify `tensors` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_numpify(t) for t in tensors) if isinstance(tensors, Mapping): return type(tensors)({k: nested_numpify(t) for k, t in tensors.items()}) t = tensors.cpu() if t.dtype == torch.bfloat16: # As of Numpy 1.21.4, NumPy does not support bfloat16 (see # https://github.com/numpy/numpy/blob/a47ecdea856986cd60eabbd53265c2ca5916ad5d/doc/source/user/basics.types.rst ). # Until Numpy adds bfloat16, we must convert float32. t = t.to(torch.float32) return t.numpy() def nested_detach(tensors): "Detach `tensors` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_detach(t) for t in tensors) elif isinstance(tensors, Mapping): return type(tensors)({k: nested_detach(t) for k, t in tensors.items()}) return tensors.detach() def nested_xla_mesh_reduce(tensors, name): if is_torch_tpu_available(): import torch_xla.core.xla_model as xm if isinstance(tensors, (list, tuple)): return type(tensors)(nested_xla_mesh_reduce(t, f"{name}_{i}") for i, t in enumerate(tensors)) if isinstance(tensors, Mapping): return type(tensors)( {k: nested_xla_mesh_reduce(t, f"{name}_{i}") for i, (k, t) in enumerate(tensors.items())} ) tensors = atleast_1d(tensors) return xm.mesh_reduce(name, tensors, torch.cat) else: raise ImportError("Torch xla must be installed to use `nested_xla_mesh_reduce`") def distributed_concat(tensor: Any, num_total_examples: Optional[int] = None) -> Any: try: if isinstance(tensor, (tuple, list)): return type(tensor)(distributed_concat(t, num_total_examples) for t in tensor) if isinstance(tensor, Mapping): return type(tensor)({k: distributed_concat(t, num_total_examples) for k, t in tensor.items()}) tensor = atleast_1d(tensor).contiguous() output_tensors = [tensor.clone() for _ in range(dist.get_world_size())] dist.all_gather(output_tensors, tensor) concat = torch.cat(output_tensors, dim=0) # truncate the dummy elements added by SequentialDistributedSampler if num_total_examples is not None: concat = concat[:num_total_examples] return concat except AssertionError: raise AssertionError("Not currently using distributed training") def distributed_broadcast_scalars( scalars: List[Union[int, float]], num_total_examples: Optional[int] = None, device: Optional[torch.device] = torch.device("cuda"), ) -> torch.Tensor: try: tensorized_scalar = torch.tensor(scalars).to(device) output_tensors = [tensorized_scalar.clone() for _ in range(dist.get_world_size())] dist.all_gather(output_tensors, tensorized_scalar) concat = torch.cat(output_tensors, dim=0) # truncate the dummy elements added by SequentialDistributedSampler if num_total_examples is not None: concat = concat[:num_total_examples] return concat except AssertionError: raise AssertionError("Not currently using distributed training") def reissue_pt_warnings(caught_warnings): # Reissue warnings that are not the SAVE_STATE_WARNING if len(caught_warnings) > 1: for w in caught_warnings: if w.category != UserWarning or w.message != SAVE_STATE_WARNING: warnings.warn(w.message, w.category) @contextmanager def torch_distributed_zero_first(local_rank: int): """ Decorator to make all processes in distributed training wait for each local_master to do something. Args: local_rank (`int`): The rank of the local process. """ if local_rank not in [-1, 0]: dist.barrier() yield if local_rank == 0: dist.barrier() class DistributedSamplerWithLoop(DistributedSampler): """ Like a torch.utils.data.distributed.DistributedSampler` but loops at the end back to the beginning of the shuffled samples to make each process have a round multiple of batch_size samples. Args: dataset (`torch.utils.data.Dataset`): Dataset used for sampling. batch_size (`int`): The batch size used with this sampler kwargs: All other keyword arguments passed to `DistributedSampler`. """ def __init__(self, dataset, batch_size, **kwargs): super().__init__(dataset, **kwargs) self.batch_size = batch_size def __iter__(self): indices = list(super().__iter__()) remainder = 0 if len(indices) % self.batch_size == 0 else self.batch_size - len(indices) % self.batch_size # DistributedSampler already added samples from the beginning to make the number of samples a round multiple # of the world size, so we skip those. start_remainder = 1 if self.rank < len(self.dataset) % self.num_replicas else 0 indices += indices[start_remainder : start_remainder + remainder] return iter(indices) class SequentialDistributedSampler(Sampler): """ Distributed Sampler that subsamples indices sequentially, making it easier to collate all results at the end. Even though we only use this sampler for eval and predict (no training), which means that the model params won't have to be synced (i.e. will not hang for synchronization even if varied number of forward passes), we still add extra samples to the sampler to make it evenly divisible (like in `DistributedSampler`) to make it easy to `gather` or `reduce` resulting tensors at the end of the loop. """ def __init__(self, dataset, num_replicas=None, rank=None, batch_size=None): warnings.warn( "SequentialDistributedSampler is deprecated and will be removed in v5 of Transformers.", FutureWarning, ) if num_replicas is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") rank = dist.get_rank() self.dataset = dataset self.num_replicas = num_replicas self.rank = rank num_samples = len(self.dataset) # Add extra samples to make num_samples a multiple of batch_size if passed if batch_size is not None: self.num_samples = int(math.ceil(num_samples / (batch_size * num_replicas))) * batch_size else: self.num_samples = int(math.ceil(num_samples / num_replicas)) self.total_size = self.num_samples * self.num_replicas self.batch_size = batch_size def __iter__(self): indices = list(range(len(self.dataset))) # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] assert ( len(indices) == self.total_size ), f"Indices length {len(indices)} and total size {self.total_size} mismatched" # subsample indices = indices[self.rank * self.num_samples : (self.rank + 1) * self.num_samples] assert ( len(indices) == self.num_samples ), f"Indices length {len(indices)} and sample number {self.num_samples} mismatched" return iter(indices) def __len__(self): return self.num_samples def get_tpu_sampler(dataset: torch.utils.data.Dataset, batch_size: int): if xm.xrt_world_size() <= 1: return RandomSampler(dataset) return DistributedSampler(dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal()) def nested_new_like(arrays, num_samples, padding_index=-100): """Create the same nested structure as `arrays` with a first dimension always at `num_samples`.""" if isinstance(arrays, (list, tuple)): return type(arrays)(nested_new_like(x, num_samples) for x in arrays) return np.full_like(arrays, padding_index, shape=(num_samples, *arrays.shape[1:])) def expand_like(arrays, new_seq_length, padding_index=-100): """Expand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding.""" result = np.full_like(arrays, padding_index, shape=(arrays.shape[0], new_seq_length) + arrays.shape[2:]) result[:, : arrays.shape[1]] = arrays return result def nested_truncate(tensors, limit): "Truncate `tensors` at `limit` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_truncate(t, limit) for t in tensors) if isinstance(tensors, Mapping): return type(tensors)({k: nested_truncate(t, limit) for k, t in tensors.items()}) return tensors[:limit] class DistributedTensorGatherer: """ A class responsible for properly gathering tensors (or nested list/tuple of tensors) on the CPU by chunks. If our dataset has 16 samples with a batch size of 2 on 3 processes and we gather then transfer on CPU at every step, our sampler will generate the following indices: `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1]` to get something of size a multiple of 3 (so that each process gets the same dataset length). Then process 0, 1 and 2 will be responsible of making predictions for the following samples: - P0: `[0, 1, 2, 3, 4, 5]` - P1: `[6, 7, 8, 9, 10, 11]` - P2: `[12, 13, 14, 15, 0, 1]` The first batch treated on each process will be - P0: `[0, 1]` - P1: `[6, 7]` - P2: `[12, 13]` So if we gather at the end of the first batch, we will get a tensor (nested list/tuple of tensor) corresponding to the following indices: `[0, 1, 6, 7, 12, 13]` If we directly concatenate our results without taking any precautions, the user will then get the predictions for the indices in this order at the end of the prediction loop: `[0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1]` For some reason, that's not going to roll their boat. This class is there to solve that problem. Args: world_size (`int`): The number of processes used in the distributed training. num_samples (`int`): The number of samples in our dataset. make_multiple_of (`int`, *optional*): If passed, the class assumes the datasets passed to each process are made to be a multiple of this argument (by adding samples). padding_index (`int`, *optional*, defaults to -100): The padding index to use if the arrays don't all have the same sequence length. """ def __init__(self, world_size, num_samples, make_multiple_of=None, padding_index=-100): warnings.warn( "DistributedTensorGatherer is deprecated and will be removed in v5 of Transformers.", FutureWarning, ) self.world_size = world_size self.num_samples = num_samples total_size = world_size if make_multiple_of is None else world_size * make_multiple_of self.total_samples = int(np.ceil(num_samples / total_size)) * total_size self.process_length = self.total_samples // world_size self._storage = None self._offsets = None self.padding_index = padding_index def add_arrays(self, arrays): """ Add `arrays` to the internal storage, Will initialize the storage to the full size at the first arrays passed so that if we're bound to get an OOM, it happens at the beginning. """ if arrays is None: return if self._storage is None: self._storage = nested_new_like(arrays, self.total_samples, padding_index=self.padding_index) self._offsets = list(range(0, self.total_samples, self.process_length)) slice_len, self._storage = self._nested_set_tensors(self._storage, arrays) for i in range(self.world_size): self._offsets[i] += slice_len def _nested_set_tensors(self, storage, arrays): if isinstance(arrays, (list, tuple)): result = [self._nested_set_tensors(x, y) for x, y in zip(storage, arrays)] return result[0][0], type(arrays)(r[1] for r in result) assert ( arrays.shape[0] % self.world_size == 0 ), f"Arrays passed should all have a first dimension multiple of {self.world_size}, found {arrays.shape[0]}." slice_len = arrays.shape[0] // self.world_size for i in range(self.world_size): if len(arrays.shape) == 1: storage[self._offsets[i] : self._offsets[i] + slice_len] = arrays[i * slice_len : (i + 1) * slice_len] else: # Expand the array on the fly if needed. if len(storage.shape) > 1 and storage.shape[1] < arrays.shape[1]: storage = expand_like(storage, arrays.shape[1], padding_index=self.padding_index) storage[self._offsets[i] : self._offsets[i] + slice_len, : arrays.shape[1]] = arrays[ i * slice_len : (i + 1) * slice_len ] return slice_len, storage def finalize(self): """ Return the properly gathered arrays and truncate to the number of samples (since the sampler added some extras to get each process a dataset of the same length). """ if self._storage is None: return if self._offsets[0] != self.process_length: logger.warning("Not all data has been set. Are you sure you passed all values?") return nested_truncate(self._storage, self.num_samples) @dataclass class LabelSmoother: """ Adds label-smoothing on a pre-computed output from a Transformers model. Args: epsilon (`float`, *optional*, defaults to 0.1): The label smoothing factor. ignore_index (`int`, *optional*, defaults to -100): The index in the labels to ignore when computing the loss. """ epsilon: float = 0.1 ignore_index: int = -100 def __call__(self, model_output, labels, shift_labels=False): logits = model_output["logits"] if isinstance(model_output, dict) else model_output[0] if shift_labels: logits = logits[..., :-1, :].contiguous() labels = labels[..., 1:].contiguous() log_probs = -nn.functional.log_softmax(logits, dim=-1) if labels.dim() == log_probs.dim() - 1: labels = labels.unsqueeze(-1) padding_mask = labels.eq(self.ignore_index) # In case the ignore_index is -100, the gather will fail, so we replace labels by 0. The padding_mask # will ignore them in any case. labels = torch.clamp(labels, min=0) nll_loss = log_probs.gather(dim=-1, index=labels) # works for fp16 input tensor too, by internally upcasting it to fp32 smoothed_loss = log_probs.sum(dim=-1, keepdim=True, dtype=torch.float32) nll_loss.masked_fill_(padding_mask, 0.0) smoothed_loss.masked_fill_(padding_mask, 0.0) # Take the mean over the label dimensions, then divide by the number of active elements (i.e. not-padded): num_active_elements = padding_mask.numel() - padding_mask.long().sum() nll_loss = nll_loss.sum() / num_active_elements smoothed_loss = smoothed_loss.sum() / (num_active_elements * log_probs.shape[-1]) return (1 - self.epsilon) * nll_loss + self.epsilon * smoothed_loss def get_length_grouped_indices(lengths, batch_size, mega_batch_mult=None, generator=None): """ Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar lengths. To do this, the indices are: - randomly permuted - grouped in mega-batches of size `mega_batch_mult * batch_size` - sorted by length in each mega-batch The result is the concatenation of all mega-batches, with the batch of `batch_size` containing the element of maximum length placed first, so that an OOM happens sooner rather than later. """ # Default for mega_batch_mult: 50 or the number to get 4 megabatches, whichever is smaller. if mega_batch_mult is None: mega_batch_mult = min(len(lengths) // (batch_size * 4), 50) # Just in case, for tiny datasets if mega_batch_mult == 0: mega_batch_mult = 1 # We need to use torch for the random part as a distributed sampler will set the random seed for torch. indices = torch.randperm(len(lengths), generator=generator) megabatch_size = mega_batch_mult * batch_size megabatches = [indices[i : i + megabatch_size].tolist() for i in range(0, len(lengths), megabatch_size)] megabatches = [sorted(megabatch, key=lambda i: lengths[i], reverse=True) for megabatch in megabatches] # The rest is to get the biggest batch first. # Since each megabatch is sorted by descending length, the longest element is the first megabatch_maximums = [lengths[megabatch[0]] for megabatch in megabatches] max_idx = torch.argmax(torch.tensor(megabatch_maximums)).item() # Switch to put the longest element in first position megabatches[0][0], megabatches[max_idx][0] = megabatches[max_idx][0], megabatches[0][0] return [i for megabatch in megabatches for i in megabatch] class LengthGroupedSampler(Sampler): r""" Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while keeping a bit of randomness. """ def __init__( self, batch_size: int, dataset: Optional[Dataset] = None, lengths: Optional[List[int]] = None, model_input_name: Optional[str] = None, generator=None, ): if dataset is None and lengths is None: raise ValueError("One of dataset and lengths must be provided.") self.batch_size = batch_size if lengths is None: model_input_name = model_input_name if model_input_name is not None else "input_ids" if ( not (isinstance(dataset[0], dict) or isinstance(dataset[0], BatchEncoding)) or model_input_name not in dataset[0] ): raise ValueError( "Can only automatically infer lengths for datasets whose items are dictionaries with an " f"'{model_input_name}' key." ) lengths = [len(feature[model_input_name]) for feature in dataset] elif isinstance(lengths, torch.Tensor): logger.info( "If lengths is a torch.Tensor, LengthGroupedSampler will be slow. Converting lengths to List[int]..." ) lengths = lengths.tolist() self.lengths = lengths self.generator = generator def __len__(self): return len(self.lengths) def __iter__(self): indices = get_length_grouped_indices(self.lengths, self.batch_size, generator=self.generator) return iter(indices) class DistributedLengthGroupedSampler(DistributedSampler): r""" Distributed Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while keeping a bit of randomness. """ # Copied and adapted from PyTorch DistributedSampler. def __init__( self, batch_size: int, dataset: Optional[Dataset] = None, num_replicas: Optional[int] = None, rank: Optional[int] = None, seed: int = 0, drop_last: bool = False, lengths: Optional[List[int]] = None, model_input_name: Optional[str] = None, ): if dataset is None and lengths is None: raise ValueError("One of dataset and lengths must be provided.") if num_replicas is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") num_replicas = dist.get_world_size() if rank is None: if not dist.is_available(): raise RuntimeError("Requires distributed package to be available") rank = dist.get_rank() self.batch_size = batch_size self.num_replicas = num_replicas self.rank = rank self.epoch = 0 self.drop_last = drop_last if lengths is None: model_input_name = model_input_name if model_input_name is not None else "input_ids" if ( not (isinstance(dataset[0], dict) or isinstance(dataset[0], BatchEncoding)) or model_input_name not in dataset[0] ): raise ValueError( "Can only automatically infer lengths for datasets whose items are dictionaries with an " f"'{model_input_name}' key." ) lengths = [len(feature[model_input_name]) for feature in dataset] elif isinstance(lengths, torch.Tensor): logger.info( "If lengths is a torch.Tensor, DistributedLengthGroupedSampler will be slow. Converting lengths to" " List[int]..." ) lengths = lengths.tolist() self.lengths = lengths # If the dataset length is evenly divisible by # of replicas, then there # is no need to drop any data, since the dataset will be split equally. if self.drop_last and len(self.lengths) % self.num_replicas != 0: # Split to nearest available length that is evenly divisible. # This is to ensure each rank receives the same amount of data when # using this Sampler. self.num_samples = math.ceil((len(self.lengths) - self.num_replicas) / self.num_replicas) else: self.num_samples = math.ceil(len(self.lengths) / self.num_replicas) self.total_size = self.num_samples * self.num_replicas self.seed = seed def __iter__(self) -> Iterator: # Deterministically shuffle based on epoch and seed g = torch.Generator() g.manual_seed(self.seed + self.epoch) indices = get_length_grouped_indices(self.lengths, self.batch_size, generator=g) if not self.drop_last: # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] else: # remove tail of data to make it evenly divisible. indices = indices[: self.total_size] assert len(indices) == self.total_size # subsample indices = indices[self.rank : self.total_size : self.num_replicas] assert len(indices) == self.num_samples return iter(indices) class ShardSampler(Sampler): """ Sampler that shards batches between several processes. Dispatches indices batch by batch: on 2 processes with batch size 4, the first two batches are `[0, 1, 2, 3, 4, 5, 6, 7]` and `[8, 9, 10, 11, 12, 13, 14, 15]`, which shard into `[0, 1, 2, 3]` and `[8, 9, 10, 11]` for GPU-0 and `[4, 5, 6, 7]` and `[12, 13, 14, 15]` for GPU-1. The sampler thus yields `[0, 1, 2, 3, 8, 9, 10, 11]` on GPU-0 and `[4, 5, 6, 7, 12, 13, 14, 15]` on GPU-1. """ def __init__( self, dataset: Dataset, batch_size: int = 1, drop_last: bool = False, num_processes: int = 1, process_index: int = 0, ): self.dataset = dataset self.batch_size = batch_size self.drop_last = drop_last self.num_processes = num_processes self.process_index = process_index self.total_batch_size = total_batch_size = batch_size * num_processes num_batches = len(dataset) // total_batch_size if drop_last else math.ceil(len(dataset) / total_batch_size) self.total_num_samples = num_batches * total_batch_size def __iter__(self): indices = list(range(len(self.dataset))) # Add extra samples to make it evenly divisible. While loop is there in the edge case we have a tiny dataset # and it needs to be done several times. while len(indices) < self.total_num_samples: indices += indices[: (self.total_num_samples - len(indices))] result = [] for batch_start in range(self.batch_size * self.process_index, self.total_num_samples, self.total_batch_size): result += indices[batch_start : batch_start + self.batch_size] return iter(result) def __len__(self): # Each shard only sees a fraction of total_num_samples. return self.total_num_samples // self.num_processes class IterableDatasetShard(IterableDataset): """ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will always yield a number of samples that is a round multiple of the actual batch size (which is `batch_size x num_processes`). Depending on the value of the `drop_last` attribute, it will either stop the iteration at the first batch that would be too small or loop with indices from the beginning. On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]` with a batch size of 2: - the shard on process 0 will yield `[0, 1, 4, 5, 8, 9]` so will see batches `[0, 1]`, `[4, 5]`, `[8, 9]` - the shard on process 1 will yield `[2, 3, 6, 7, 10, 11]` so will see batches `[2, 3]`, `[6, 7]`, `[10, 11]` <Tip warning={true}> If your IterableDataset implements some randomization that needs to be applied the same way on all processes (for instance, a shuffling), you should use a `torch.Generator` in a `generator` attribute of the `dataset` to generate your random numbers and call the [`~trainer_pt_utils.IterableDatasetShard.set_epoch`] method of this object. It will set the seed of this `generator` to `seed + epoch` on all processes before starting the iteration. Alternatively, you can also implement a `set_epoch()` method in your iterable dataset to deal with this. </Tip> Args: dataset (`torch.utils.data.IterableDataset`): The batch sampler to split in several shards. batch_size (`int`, *optional*, defaults to 1): The size of the batches per shard. drop_last (`bool`, *optional*, defaults to `False`): Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the beginning. num_processes (`int`, *optional*, defaults to 1): The number of processes running concurrently. process_index (`int`, *optional*, defaults to 0): The index of the current process. seed (`int`, *optional*, defaults to 0): A random seed that will be used for the random number generation in [`~trainer_pt_utils.IterableDatasetShard.set_epoch`]. """ def __init__( self, dataset: IterableDataset, batch_size: int = 1, drop_last: bool = False, num_processes: int = 1, process_index: int = 0, seed: int = 0, ): self.dataset = dataset self.batch_size = batch_size self.drop_last = drop_last self.num_processes = num_processes self.process_index = process_index self.seed = seed self.epoch = 0 self.num_examples = 0 def set_epoch(self, epoch): self.epoch = epoch if hasattr(self.dataset, "set_epoch"): self.dataset.set_epoch(epoch) def __iter__(self): self.num_examples = 0 if ( not hasattr(self.dataset, "set_epoch") and hasattr(self.dataset, "generator") and isinstance(self.dataset.generator, torch.Generator) ): self.dataset.generator.manual_seed(self.seed + self.epoch) real_batch_size = self.batch_size * self.num_processes process_slice = range(self.process_index * self.batch_size, (self.process_index + 1) * self.batch_size) first_batch = None current_batch = [] for element in self.dataset: self.num_examples += 1 current_batch.append(element) # Wait to have a full batch before yielding elements. if len(current_batch) == real_batch_size: for i in process_slice: yield current_batch[i] if first_batch is None: first_batch = current_batch.copy() current_batch = [] # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning. if not self.drop_last and len(current_batch) > 0: if first_batch is None: first_batch = current_batch.copy() while len(current_batch) < real_batch_size: current_batch += first_batch for i in process_slice: yield current_batch[i] def __len__(self): # Will raise an error if the underlying dataset is not sized. if self.drop_last: return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size else: return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size # In order to keep `trainer.py` compact and easy to understand, place any secondary PT Trainer # helper methods here def _get_learning_rate(self): if self.deepspeed: # with deepspeed's fp16 and dynamic loss scale enabled the optimizer/scheduler steps may # not run for the first few dozen steps while loss scale is too large, and thus during # that time `get_last_lr` will fail if called during that warm up stage, so work around it: try: last_lr = self.lr_scheduler.get_last_lr()[0] except AssertionError as e: if "need to call step" in str(e): logger.warning("tried to get lr value before scheduler/optimizer started stepping, returning lr=0") last_lr = 0 else: raise else: last_lr = self.lr_scheduler.get_last_lr()[0] if torch.is_tensor(last_lr): last_lr = last_lr.item() return last_lr def _secs2timedelta(secs): """ convert seconds to hh:mm:ss.msec, msecs rounded to 2 decimals """ msec = int(abs(secs - int(secs)) * 100) return f"{datetime.timedelta(seconds=int(secs))}.{msec:02d}" def metrics_format(self, metrics: Dict[str, float]) -> Dict[str, float]: """ Reformat Trainer metrics values to a human-readable format Args: metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predict Returns: metrics (`Dict[str, float]`): The reformatted metrics """ metrics_copy = metrics.copy() for k, v in metrics_copy.items(): if "_mem_" in k: metrics_copy[k] = f"{ v >> 20 }MB" elif "_runtime" in k: metrics_copy[k] = _secs2timedelta(v) elif k == "total_flos": metrics_copy[k] = f"{ int(v) >> 30 }GF" elif type(metrics_copy[k]) == float: metrics_copy[k] = round(v, 4) return metrics_copy def log_metrics(self, split, metrics): """ Log metrics in a specially formatted way Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test` metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predictmetrics: metrics dict Notes on memory reports: In order to get memory usage report you need to install `psutil`. You can do that with `pip install psutil`. Now when this method is run, you will see a report that will include: : ``` init_mem_cpu_alloc_delta = 1301MB init_mem_cpu_peaked_delta = 154MB init_mem_gpu_alloc_delta = 230MB init_mem_gpu_peaked_delta = 0MB train_mem_cpu_alloc_delta = 1345MB train_mem_cpu_peaked_delta = 0MB train_mem_gpu_alloc_delta = 693MB train_mem_gpu_peaked_delta = 7MB ``` **Understanding the reports:** - the first segment, e.g., `train__`, tells you which stage the metrics are for. Reports starting with `init_` will be added to the first stage that gets run. So that if only evaluation is run, the memory usage for the `__init__` will be reported along with the `eval_` metrics. - the third segment, is either `cpu` or `gpu`, tells you whether it's the general RAM or the gpu0 memory metric. - `*_alloc_delta` - is the difference in the used/allocated memory counter between the end and the start of the stage - it can be negative if a function released more memory than it allocated. - `*_peaked_delta` - is any extra memory that was consumed and then freed - relative to the current allocated memory counter - it is never negative. When you look at the metrics of any stage you add up `alloc_delta` + `peaked_delta` and you know how much memory was needed to complete that stage. The reporting happens only for process of rank 0 and gpu 0 (if there is a gpu). Typically this is enough since the main process does the bulk of work, but it could be not quite so if model parallel is used and then other GPUs may use a different amount of gpu memory. This is also not the same under DataParallel where gpu0 may require much more memory than the rest since it stores the gradient and optimizer states for all participating GPUS. Perhaps in the future these reports will evolve to measure those too. The CPU RAM metric measures RSS (Resident Set Size) includes both the memory which is unique to the process and the memory shared with other processes. It is important to note that it does not include swapped out memory, so the reports could be imprecise. The CPU peak memory is measured using a sampling thread. Due to python's GIL it may miss some of the peak memory if that thread didn't get a chance to run when the highest memory was used. Therefore this report can be less than reality. Using `tracemalloc` would have reported the exact peak memory, but it doesn't report memory allocations outside of python. So if some C++ CUDA extension allocated its own memory it won't be reported. And therefore it was dropped in favor of the memory sampling approach, which reads the current process memory usage. The GPU allocated and peak memory reporting is done with `torch.cuda.memory_allocated()` and `torch.cuda.max_memory_allocated()`. This metric reports only "deltas" for pytorch-specific allocations, as `torch.cuda` memory management system doesn't track any memory allocated outside of pytorch. For example, the very first cuda call typically loads CUDA kernels, which may take from 0.5 to 2GB of GPU memory. Note that this tracker doesn't account for memory allocations outside of [`Trainer`]'s `__init__`, `train`, `evaluate` and `predict` calls. Because `evaluation` calls may happen during `train`, we can't handle nested invocations because `torch.cuda.max_memory_allocated` is a single counter, so if it gets reset by a nested eval call, `train`'s tracker will report incorrect info. If this [pytorch issue](https://github.com/pytorch/pytorch/issues/16266) gets resolved it will be possible to change this class to be re-entrant. Until then we will only track the outer level of `train`, `evaluate` and `predict` methods. Which means that if `eval` is called during `train`, it's the latter that will account for its memory usage and that of the former. This also means that if any other tool that is used along the [`Trainer`] calls `torch.cuda.reset_peak_memory_stats`, the gpu peak memory stats could be invalid. And the [`Trainer`] will disrupt the normal behavior of any such tools that rely on calling `torch.cuda.reset_peak_memory_stats` themselves. For best performance you may want to consider turning the memory profiling off for production runs. """ if not self.is_world_process_zero(): return print(f"***** {split} metrics *****") metrics_formatted = self.metrics_format(metrics) k_width = max(len(str(x)) for x in metrics_formatted.keys()) v_width = max(len(str(x)) for x in metrics_formatted.values()) for key in sorted(metrics_formatted.keys()): print(f" {key: <{k_width}} = {metrics_formatted[key]:>{v_width}}") def save_metrics(self, split, metrics, combined=True): """ Save metrics into a json file for that split, e.g. `train_results.json`. Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test`, `all` metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predict combined (`bool`, *optional*, defaults to `True`): Creates combined metrics by updating `all_results.json` with metrics of this call To understand the metrics please read the docstring of [`~Trainer.log_metrics`]. The only difference is that raw unformatted numbers are saved in the current method. """ if not self.is_world_process_zero(): return path = os.path.join(self.args.output_dir, f"{split}_results.json") with open(path, "w") as f: json.dump(metrics, f, indent=4, sort_keys=True) if combined: path = os.path.join(self.args.output_dir, "all_results.json") if os.path.exists(path): with open(path, "r") as f: all_metrics = json.load(f) else: all_metrics = {} all_metrics.update(metrics) with open(path, "w") as f: json.dump(all_metrics, f, indent=4, sort_keys=True) def save_state(self): """ Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model Under distributed environment this is done only for a process with rank 0. """ if not self.is_world_process_zero(): return path = os.path.join(self.args.output_dir, "trainer_state.json") self.state.save_to_json(path) def get_parameter_names(model, forbidden_layer_types): """ Returns the names of the model parameters that are not inside a forbidden layer. """ result = [] for name, child in model.named_children(): result += [ f"{name}.{n}" for n in get_parameter_names(child, forbidden_layer_types) if not isinstance(child, tuple(forbidden_layer_types)) ] # Add model specific parameters (defined with nn.Parameter) since they are not in any child. result += list(model._parameters.keys()) return result def get_module_class_from_name(module, name): """ Gets a class from a module by its name. Args: module (`torch.nn.Module`): The module to get the class from. name (`str`): The name of the class. """ modules_children = list(module.children()) if module.__class__.__name__ == name: return module.__class__ elif len(modules_children) == 0: return else: for child_module in modules_children: module_class = get_module_class_from_name(child_module, name) if module_class is not None: return module_class if is_sagemaker_mp_enabled(): import smdistributed.modelparallel.torch as smp @smp.step() def smp_forward_backward(model, inputs, gradient_accumulation_steps=1): outputs = model(**inputs) loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0] loss /= gradient_accumulation_steps model.backward(loss) return loss @smp.step() def smp_forward_only(model, inputs): return model(**inputs) def smp_gather(tensor): if isinstance(tensor, (list, tuple)): return type(tensor)(smp_gather(t) for t in tensor) elif isinstance(tensor, dict): return type(tensor)({k: smp_gather(v) for k, v in tensor.items()}) elif not isinstance(tensor, torch.Tensor): raise TypeError( f"Can't gather the values of type {type(tensor)}, only of nested list/tuple/dicts of tensors." ) all_tensors = smp.allgather(tensor, smp.CommGroup.DP_GROUP) all_tensors = [atleast_1d(t) for t in all_tensors] return torch.cat([t.cpu() for t in all_tensors], dim=0) def smp_nested_concat(tensor): if isinstance(tensor, (list, tuple)): return type(tensor)(smp_nested_concat(t) for t in tensor) elif isinstance(tensor, dict): return type(tensor)({k: smp_nested_concat(v) for k, v in tensor.items()}) # It doesn't seem possible to check here if `tensor` is a StepOutput because StepOutput lives in `smp.step` # which is also the name of the decorator so Python is confused. return tensor.concat().detach().cpu()
233zzh/TitanDataOperationSystem
1,543
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/categories/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Categories</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.categories.js"></script> <script type="text/javascript"> $(function() { var data = [ ["January", 10], ["February", 8], ["March", 4], ["April", 13], ["May", 17], ["June", 9] ]; $.plot("#placeholder", [ data ], { series: { bars: { show: true, barWidth: 0.6, align: "center" } }, xaxis: { mode: "categories", tickLength: 0 } }); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Categories</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder"></div> </div> <p>With the categories plugin you can plot categories/textual data easily.</p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
27182812/ChatGLM-LLaMA-chinese-insturct
23,945
src/transformers/trainer_utils.py
# coding=utf-8 # Copyright 2020-present 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. """ Utilities for the Trainer and TFTrainer class. Should be independent from PyTorch and TensorFlow. """ import copy import functools import gc import inspect import os import random import re import threading import time from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np from .utils import ( ExplicitEnum, is_psutil_available, is_tf_available, is_torch_available, is_torch_cuda_available, is_torch_tpu_available, requires_backends, ) if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf def seed_worker(_): """ Helper function to set worker seed during Dataloader initialization. """ worker_seed = torch.initial_seed() % 2**32 set_seed(worker_seed) def enable_full_determinism(seed: int): """ Helper function for reproducible behavior during distributed training. See - https://pytorch.org/docs/stable/notes/randomness.html for pytorch - https://www.tensorflow.org/api_docs/python/tf/config/experimental/enable_op_determinism for tensorflow """ # set seed first set_seed(seed) if is_torch_available(): # Enable PyTorch deterministic mode. This potentially requires either the environment # variable 'CUDA_LAUNCH_BLOCKING' or 'CUBLAS_WORKSPACE_CONFIG' to be set, # depending on the CUDA version, so we set them both here os.environ["CUDA_LAUNCH_BLOCKING"] = "1" os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":16:8" torch.use_deterministic_algorithms(True) # Enable CUDNN deterministic mode torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False if is_tf_available(): tf.config.experimental.enable_op_determinism() def set_seed(seed: int): """ Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` and/or `tf` (if installed). Args: seed (`int`): The seed to set. """ random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) # ^^ safe to call this function even if cuda is not available if is_tf_available(): tf.random.set_seed(seed) class EvalPrediction: """ Evaluation output (always contains labels), to be used to compute metrics. Parameters: predictions (`np.ndarray`): Predictions of the model. label_ids (`np.ndarray`): Targets to be matched. inputs (`np.ndarray`, *optional*) """ def __init__( self, predictions: Union[np.ndarray, Tuple[np.ndarray]], label_ids: Union[np.ndarray, Tuple[np.ndarray]], inputs: Optional[Union[np.ndarray, Tuple[np.ndarray]]] = None, ): self.predictions = predictions self.label_ids = label_ids self.inputs = inputs def __iter__(self): if self.inputs is not None: return iter((self.predictions, self.label_ids, self.inputs)) else: return iter((self.predictions, self.label_ids)) def __getitem__(self, idx): if idx < 0 or idx > 2: raise IndexError("tuple index out of range") if idx == 2 and self.inputs is None: raise IndexError("tuple index out of range") if idx == 0: return self.predictions elif idx == 1: return self.label_ids elif idx == 2: return self.inputs class EvalLoopOutput(NamedTuple): predictions: Union[np.ndarray, Tuple[np.ndarray]] label_ids: Optional[Union[np.ndarray, Tuple[np.ndarray]]] metrics: Optional[Dict[str, float]] num_samples: Optional[int] class PredictionOutput(NamedTuple): predictions: Union[np.ndarray, Tuple[np.ndarray]] label_ids: Optional[Union[np.ndarray, Tuple[np.ndarray]]] metrics: Optional[Dict[str, float]] class TrainOutput(NamedTuple): global_step: int training_loss: float metrics: Dict[str, float] PREFIX_CHECKPOINT_DIR = "checkpoint" _re_checkpoint = re.compile(r"^" + PREFIX_CHECKPOINT_DIR + r"\-(\d+)$") def get_last_checkpoint(folder): content = os.listdir(folder) checkpoints = [ path for path in content if _re_checkpoint.search(path) is not None and os.path.isdir(os.path.join(folder, path)) ] if len(checkpoints) == 0: return return os.path.join(folder, max(checkpoints, key=lambda x: int(_re_checkpoint.search(x).groups()[0]))) class IntervalStrategy(ExplicitEnum): NO = "no" STEPS = "steps" EPOCH = "epoch" class EvaluationStrategy(ExplicitEnum): NO = "no" STEPS = "steps" EPOCH = "epoch" class HubStrategy(ExplicitEnum): END = "end" EVERY_SAVE = "every_save" CHECKPOINT = "checkpoint" ALL_CHECKPOINTS = "all_checkpoints" class BestRun(NamedTuple): """ The best run found by an hyperparameter search (see [`~Trainer.hyperparameter_search`]). Parameters: run_id (`str`): The id of the best run (if models were saved, the corresponding checkpoint will be in the folder ending with run-{run_id}). objective (`float`): The objective that was obtained for this run. hyperparameters (`Dict[str, Any]`): The hyperparameters picked to get this run. """ run_id: str objective: float hyperparameters: Dict[str, Any] def default_compute_objective(metrics: Dict[str, float]) -> float: """ The default objective to maximize/minimize when doing an hyperparameter search. It is the evaluation loss if no metrics are provided to the [`Trainer`], the sum of all metrics otherwise. Args: metrics (`Dict[str, float]`): The metrics returned by the evaluate method. Return: `float`: The objective to minimize or maximize """ metrics = copy.deepcopy(metrics) loss = metrics.pop("eval_loss", None) _ = metrics.pop("epoch", None) # Remove speed metrics speed_metrics = [ m for m in metrics.keys() if m.endswith("_runtime") or m.endswith("_per_second") or m.endswith("_compilation_time") ] for sm in speed_metrics: _ = metrics.pop(sm, None) return loss if len(metrics) == 0 else sum(metrics.values()) def default_hp_space_optuna(trial) -> Dict[str, float]: from .integrations import is_optuna_available assert is_optuna_available(), "This function needs Optuna installed: `pip install optuna`" return { "learning_rate": trial.suggest_float("learning_rate", 1e-6, 1e-4, log=True), "num_train_epochs": trial.suggest_int("num_train_epochs", 1, 5), "seed": trial.suggest_int("seed", 1, 40), "per_device_train_batch_size": trial.suggest_categorical("per_device_train_batch_size", [4, 8, 16, 32, 64]), } def default_hp_space_ray(trial) -> Dict[str, float]: from .integrations import is_ray_tune_available assert is_ray_tune_available(), "This function needs ray installed: `pip install ray[tune]`" from ray import tune return { "learning_rate": tune.loguniform(1e-6, 1e-4), "num_train_epochs": tune.choice(list(range(1, 6))), "seed": tune.uniform(1, 40), "per_device_train_batch_size": tune.choice([4, 8, 16, 32, 64]), } def default_hp_space_sigopt(trial): return [ {"bounds": {"min": 1e-6, "max": 1e-4}, "name": "learning_rate", "type": "double", "transformamtion": "log"}, {"bounds": {"min": 1, "max": 6}, "name": "num_train_epochs", "type": "int"}, {"bounds": {"min": 1, "max": 40}, "name": "seed", "type": "int"}, { "categorical_values": ["4", "8", "16", "32", "64"], "name": "per_device_train_batch_size", "type": "categorical", }, ] def default_hp_space_wandb(trial) -> Dict[str, float]: from .integrations import is_wandb_available if not is_wandb_available(): raise ImportError("This function needs wandb installed: `pip install wandb`") return { "method": "random", "metric": {"name": "objective", "goal": "minimize"}, "parameters": { "learning_rate": {"distribution": "uniform", "min": 1e-6, "max": 1e-4}, "num_train_epochs": {"distribution": "int_uniform", "min": 1, "max": 6}, "seed": {"distribution": "int_uniform", "min": 1, "max": 40}, "per_device_train_batch_size": {"values": [4, 8, 16, 32, 64]}, }, } class HPSearchBackend(ExplicitEnum): OPTUNA = "optuna" RAY = "ray" SIGOPT = "sigopt" WANDB = "wandb" default_hp_space = { HPSearchBackend.OPTUNA: default_hp_space_optuna, HPSearchBackend.RAY: default_hp_space_ray, HPSearchBackend.SIGOPT: default_hp_space_sigopt, HPSearchBackend.WANDB: default_hp_space_wandb, } def is_main_process(local_rank): """ Whether or not the current process is the local process, based on `xm.get_ordinal()` (for TPUs) first, then on `local_rank`. """ if is_torch_tpu_available(check_device=True): import torch_xla.core.xla_model as xm return xm.get_ordinal() == 0 return local_rank in [-1, 0] def total_processes_number(local_rank): """ Return the number of processes launched in parallel. Works with `torch.distributed` and TPUs. """ if is_torch_tpu_available(check_device=True): import torch_xla.core.xla_model as xm return xm.xrt_world_size() elif local_rank != -1 and is_torch_available(): import torch return torch.distributed.get_world_size() return 1 def speed_metrics(split, start_time, num_samples=None, num_steps=None): """ Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be measured has completed. Args: - split: name to prefix metric (like train, eval, test...) - start_time: operation start time - num_samples: number of samples processed """ runtime = time.time() - start_time result = {f"{split}_runtime": round(runtime, 4)} if num_samples is not None: samples_per_second = num_samples / runtime result[f"{split}_samples_per_second"] = round(samples_per_second, 3) if num_steps is not None: steps_per_second = num_steps / runtime result[f"{split}_steps_per_second"] = round(steps_per_second, 3) return result class SchedulerType(ExplicitEnum): LINEAR = "linear" COSINE = "cosine" COSINE_WITH_RESTARTS = "cosine_with_restarts" POLYNOMIAL = "polynomial" CONSTANT = "constant" CONSTANT_WITH_WARMUP = "constant_with_warmup" INVERSE_SQRT = "inverse_sqrt" class TrainerMemoryTracker: """ A helper class that tracks cpu and gpu memory. This class will silently skip unless `psutil` is available. Install with `pip install psutil`. When a stage completes, it can pass metrics dict to update with the memory metrics gathered during this stage. Example : ```python self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics) self._memory_tracker.start() # code ... metrics = {"train_runtime": 10.5} self._memory_tracker.stop_and_update_metrics(metrics) ``` At the moment GPU tracking is only for `pytorch`, but can be extended to support `tensorflow`. To understand this class' intricacies please read the documentation of [`~Trainer.log_metrics`]. """ # map trainer methods to metrics prefix stages = { "__init__": "init", "train": "train", "_inner_training_loop": "train", "evaluate": "eval", "predict": "test", } def __init__(self, skip_memory_metrics=False): self.skip_memory_metrics = skip_memory_metrics if not is_psutil_available(): # soft dependency on psutil self.skip_memory_metrics = True if self.skip_memory_metrics: return import psutil # noqa if is_torch_cuda_available(): import torch self.torch = torch self.gpu = {} else: self.torch = None self.process = psutil.Process() self.cur_stage = None self.cpu = {} self.init_reported = False def derive_stage(self): """derives the stage/caller name automatically""" caller = inspect.currentframe().f_back.f_back.f_code.co_name if caller in self.stages: return self.stages[caller] else: raise ValueError( f"was called from {caller}, but only expect to be called from one of {self.stages.keys()}" ) def cpu_mem_used(self): """get resident set size memory for the current process""" return self.process.memory_info().rss def peak_monitor_func(self): self.cpu_mem_used_peak = -1 while True: self.cpu_mem_used_peak = max(self.cpu_mem_used(), self.cpu_mem_used_peak) # can't sleep or will not catch the peak right (this comment is here on purpose) # time.sleep(0.001) # 1msec if not self.peak_monitoring: break def start(self): """start tracking for the caller's stage""" if self.skip_memory_metrics: return stage = self.derive_stage() # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: return self.cur_stage = stage gc.collect() if self.torch is not None: self.torch.cuda.reset_peak_memory_stats() self.torch.cuda.empty_cache() # gpu if self.torch is not None: self.gpu_mem_used_at_start = self.torch.cuda.memory_allocated() # cpu self.cpu_mem_used_at_start = self.cpu_mem_used() self.peak_monitoring = True peak_monitor_thread = threading.Thread(target=self.peak_monitor_func) peak_monitor_thread.daemon = True peak_monitor_thread.start() def stop(self, stage): """stop tracking for the passed stage""" # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: return # this sends a signal to peak_monitor_func to complete its loop self.peak_monitoring = False # first ensure all objects get collected and their memory is freed gc.collect() if self.torch is not None: self.torch.cuda.empty_cache() # concepts: # - alloc_delta: the difference of allocated memory between the end and the start # - peaked_delta: the difference between the peak memory and the current memory # in order to know how much memory the measured code consumed one needs to sum these two # gpu if self.torch is not None: self.gpu_mem_used_now = self.torch.cuda.memory_allocated() self.gpu_mem_used_peak = self.torch.cuda.max_memory_allocated() self.gpu[self.cur_stage] = { "begin": self.gpu_mem_used_at_start, "end": self.gpu_mem_used_now, "alloc": (self.gpu_mem_used_now - self.gpu_mem_used_at_start), "peaked": max(0, self.gpu_mem_used_peak - self.gpu_mem_used_now), } # cpu self.cpu_mem_used_now = self.cpu_mem_used() self.cpu[self.cur_stage] = { "begin": self.cpu_mem_used_at_start, "end": self.cpu_mem_used_now, "alloc": (self.cpu_mem_used_now - self.cpu_mem_used_at_start), "peaked": max(0, self.cpu_mem_used_peak - self.cpu_mem_used_now), } # reset - cycle finished self.cur_stage = None def update_metrics(self, stage, metrics): """updates the metrics""" if self.skip_memory_metrics: return # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: return # since we don't have a way to return init metrics, we push them into the first of train/val/predict stages = [stage] if not self.init_reported: stages.insert(0, "init") self.init_reported = True for stage in stages: for t in ["alloc", "peaked"]: if stage in self.cpu and t in self.cpu[stage]: metrics[f"{stage}_mem_cpu_{t}_delta"] = self.cpu[stage][t] if self.torch is not None and stage in self.gpu and t in self.gpu[stage]: metrics[f"{stage}_mem_gpu_{t}_delta"] = self.gpu[stage][t] # if we need additional debug info, enable the following # for t in ["begin", "end"]: # if stage in self.cpu and t in self.cpu[stage]: # metrics[f"{stage}_mem_cpu_{t}"] = self.cpu[stage][t] # if self.torch is not None and stage in self.gpu and t in self.gpu[stage]: # metrics[f"{stage}_mem_gpu_{t}"] = self.gpu[stage][t] # since memory can be allocated before init, and it might be difficult to track overall # memory usage, in particular for GPU, let's report memory usage at the point init was called if stages[0] == "init": metrics["before_init_mem_cpu"] = self.cpu["init"]["begin"] if self.torch is not None: metrics["before_init_mem_gpu"] = self.gpu["init"]["begin"] # if we also wanted to report any additional memory allocations in between init and # whatever the next stage was we could also report this: # if self.cpu["init"]["end"] != self.cpu[stage]["begin"]: # metrics[f"after_init_mem_cpu_delta"] = self.cpu[stage]["begin"] - self.cpu["init"]["end"] # if self.torch is not None and self.gpu["init"]["end"] != self.gpu[stage]["begin"]: # metrics[f"after_init_mem_gpu_delta"] = self.gpu[stage]["begin"] - self.gpu["init"]["end"] def stop_and_update_metrics(self, metrics=None): """combine stop and metrics update in one call for simpler code""" if self.skip_memory_metrics: return stage = self.derive_stage() self.stop(stage) # init doesn't have metrics to update so we just save that data for later stages to retrieve if metrics is not None: self.update_metrics(stage, metrics) def has_length(dataset): """ Checks if the dataset implements __len__() and it doesn't raise an error """ try: return len(dataset) is not None except TypeError: # TypeError: len() of unsized object return False def denumpify_detensorize(metrics): """ Recursively calls `.item()` on the element of the dictionary passed """ if isinstance(metrics, (list, tuple)): return type(metrics)(denumpify_detensorize(m) for m in metrics) elif isinstance(metrics, dict): return type(metrics)({k: denumpify_detensorize(v) for k, v in metrics.items()}) elif isinstance(metrics, np.generic): return metrics.item() elif is_torch_available() and isinstance(metrics, torch.Tensor) and metrics.numel() == 1: return metrics.item() return metrics def number_of_arguments(func): """ Return the number of arguments of the passed function, even if it's a partial function. """ if isinstance(func, functools.partial): total_args = len(inspect.signature(func.func).parameters) return total_args - len(func.args) - len(func.keywords) return len(inspect.signature(func).parameters) class ShardedDDPOption(ExplicitEnum): SIMPLE = "simple" ZERO_DP_2 = "zero_dp_2" ZERO_DP_3 = "zero_dp_3" OFFLOAD = "offload" AUTO_WRAP = "auto_wrap" def find_executable_batch_size( function: callable = None, starting_batch_size: int = 128, auto_find_batch_size: bool = False ): """ Args: A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or CUDNN, the batch size is cut in half and passed to `function` `function` must take in a `batch_size` parameter as its first argument. function (`callable`, *optional*) A function to wrap starting_batch_size (`int`, *optional*) The batch size to try and fit into memory auto_find_batch_size (`bool`, *optional*) If False, will just execute `function` """ if function is None: return functools.partial( find_executable_batch_size, starting_batch_size=starting_batch_size, auto_find_batch_size=auto_find_batch_size, ) if auto_find_batch_size: requires_backends(find_executable_batch_size, "accelerate") from accelerate.utils import find_executable_batch_size as accelerate_find_executable_batch_size return accelerate_find_executable_batch_size(function=function, starting_batch_size=starting_batch_size) return functools.partial(function, batch_size=starting_batch_size) class FSDPOption(ExplicitEnum): FULL_SHARD = "full_shard" SHARD_GRAD_OP = "shard_grad_op" NO_SHARD = "no_shard" OFFLOAD = "offload" AUTO_WRAP = "auto_wrap" class RemoveColumnsCollator: """Wrap the data collator to remove unused columns before they are passed to the collator.""" def __init__( self, data_collator, signature_columns, logger=None, model_name: Optional[str] = None, description: Optional[str] = None, ): self.data_collator = data_collator self.signature_columns = signature_columns self.logger = logger self.description = description self.model_name = model_name self.message_logged = False def _remove_columns(self, feature: dict) -> dict: if not isinstance(feature, dict): return feature if not self.message_logged and self.logger and self.model_name: ignored_columns = list(set(feature.keys()) - set(self.signature_columns)) if len(ignored_columns) > 0: dset_description = "" if self.description is None else f"in the {self.description} set" self.logger.info( f"The following columns {dset_description} don't have a corresponding argument in " f"`{self.model_name}.forward` and have been ignored: {', '.join(ignored_columns)}." f" If {', '.join(ignored_columns)} are not expected by `{self.model_name}.forward`, " " you can safely ignore this message." ) self.message_logged = True return {k: v for k, v in feature.items() if k in self.signature_columns} def __call__(self, features: List[dict]): features = [self._remove_columns(feature) for feature in features] return self.data_collator(features)
27182812/ChatGLM-LLaMA-chinese-insturct
39,923
src/transformers/tokenization_utils.py
# coding=utf-8 # Copyright 2020 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 python tokenizers. For fast tokenizers (provided by HuggingFace's tokenizers library) see tokenization_utils_fast.py """ import bisect import itertools import re import unicodedata from collections import OrderedDict from typing import Any, Dict, List, Optional, Tuple, Union, overload from .tokenization_utils_base import ( ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING, INIT_TOKENIZER_DOCSTRING, AddedToken, BatchEncoding, EncodedInput, EncodedInputPair, PreTokenizedInput, PreTokenizedInputPair, PreTrainedTokenizerBase, TextInput, TextInputPair, TruncationStrategy, ) from .utils import PaddingStrategy, TensorType, add_end_docstrings, logging logger = logging.get_logger(__name__) # Slow tokenizers are saved in a vocabulary plus three separated files SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json" ADDED_TOKENS_FILE = "added_tokens.json" TOKENIZER_CONFIG_FILE = "tokenizer_config.json" class Trie: """ Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass Loose reference https://en.wikipedia.org/wiki/Trie """ def __init__(self): self.data = {} def add(self, word: str): """ Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation. The special key `""` is used to represent termination. This function is idempotent, adding twice the same word will leave the trie unchanged Example: ```python >>> trie = Trie() >>> trie.add("Hello 友達") >>> trie.data {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}} >>> trie.add("Hello") >>> trie.data {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}} ``` """ if not word: # Prevent empty string return ref = self.data for char in word: ref[char] = char in ref and ref[char] or {} ref = ref[char] ref[""] = 1 def split(self, text: str) -> List[str]: """ Will look for the words added to the trie within `text`. Output is the original string splitted along the boundaries of the words found. This trie will match the longest possible word first ! Example: ```python >>> trie = Trie() >>> trie.split("[CLS] This is a extra_id_100") ["[CLS] This is a extra_id_100"] >>> trie.add("[CLS]") >>> trie.add("extra_id_1") >>> trie.add("extra_id_100") >>> trie.split("[CLS] This is a extra_id_100") ["[CLS]", " This is a ", "extra_id_100"] ``` """ # indexes are counted left of the chars index. # "hello", index 0, is left of h, index 1 is between h and e. # index 5 is right of the "o". # States are going to capture every possible start (indexes as above) # as keys, and have as values, a pointer to the position in the trie # where we're at. This is a partial match for now. # This enables to keep track of multiple matches while we're iterating # the string # If the trie contains, "blowing", and "lower" and we encounter the # string "blower", we need to split into ["b", "lower"]. # This is where we need to keep track of multiple possible starts. states = OrderedDict() # This will contain every indices where we need # to cut. # We force to cut at offset 0 and len(text) (added later) offsets = [0] # This is used by the lookahead which needs to skip over # some text where the full match exceeded the place in the initial # for loop skip = 0 # Main loop, Giving this algorithm O(n) complexity for current, current_char in enumerate(text): if skip and current < skip: # Prevents the lookahead for matching twice # like extra_id_100 and id_100 continue # This will track every state # that stop matching, we need to stop tracking them. # If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then # fail on "b", we need to remove 0 from the valid states. to_remove = set() # Whenever we found a match, we need to drop everything # this is a greedy algorithm, it will match on the first found token reset = False # In this case, we already have partial matches (But unfinished) for start, trie_pointer in states.items(): if "" in trie_pointer: # This is a final match, we need to reset and # store the results in `offsets`. # Lookahead to match longest first # Important in case of extra_id_1 vs extra_id_100 # Here we are also actively looking for other earlier partial # matches # "[CLS]", "L", we need to match CLS even if L is special for lookstart, looktrie_pointer in states.items(): if lookstart > start: # This partial match is later, we can stop looking break elif lookstart < start: # This partial match is earlier, the trie pointer # was already updated, so index is + 1 lookahead_index = current + 1 end = current + 1 else: # Here lookstart == start and # looktrie_pointer == trie_pointer # It wasn't updated yet so indices are current ones lookahead_index = current end = current next_char = text[lookahead_index] if lookahead_index < len(text) else None if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index while next_char in looktrie_pointer: looktrie_pointer = looktrie_pointer[next_char] lookahead_index += 1 if "" in looktrie_pointer: start = lookstart end = lookahead_index skip = lookahead_index if lookahead_index == len(text): # End of string break next_char = text[lookahead_index] # End lookahead # Storing and resetting offsets.append(start) offsets.append(end) reset = True break elif current_char in trie_pointer: # The current character being looked at has a match within the trie # update the pointer (it will be stored back into states later). trie_pointer = trie_pointer[current_char] # Storing back the new pointer into the states. # Partial matches got longer by one. states[start] = trie_pointer else: # The new character has not match in the trie, we need # to stop keeping track of this partial match. # We can't do it directly within the loop because of how # python iteration works to_remove.add(start) # Either clearing the full start (we found a real match) # Or clearing only the partial matches that didn't work. if reset: states = {} else: for start in to_remove: del states[start] # If this character is a starting character within the trie # start keeping track of this partial match. if current >= skip and current_char in self.data: states[current] = self.data[current_char] # We have a cut at the end with states. for start, trie_pointer in states.items(): if "" in trie_pointer: # This is a final match, we need to reset and # store the results in `offsets`. end = len(text) offsets.append(start) offsets.append(end) # Longest cut is always the one with lower start so the first # item so we need to break. break return self.cut_text(text, offsets) def cut_text(self, text, offsets): # We have all the offsets now, we just need to do the actual splitting. # We need to eventually add the first part of the string and the eventual # last part. offsets.append(len(text)) tokens = [] start = 0 for end in offsets: if start > end: logger.error( "There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it" " anyway." ) continue elif start == end: # This might happen if there's a match at index 0 # we're also preventing zero-width cuts in case of two # consecutive matches continue tokens.append(text[start:end]) start = end return tokens def _is_whitespace(char): """Checks whether `char` is a whitespace character.""" # \t, \n, and \r are technically control characters but we treat them # as whitespace since they are generally considered as such. if char == " " or char == "\t" or char == "\n" or char == "\r": return True cat = unicodedata.category(char) if cat == "Zs": return True return False def _is_control(char): """Checks whether `char` is a control character.""" # These are technically control characters but we count them as whitespace # characters. if char == "\t" or char == "\n" or char == "\r": return False cat = unicodedata.category(char) if cat.startswith("C"): return True return False def _is_punctuation(char): """Checks whether `char` is a punctuation character.""" cp = ord(char) # We treat all non-letter/number ASCII as punctuation. # Characters such as "^", "$", and "`" are not in the Unicode # Punctuation class but we treat them as punctuation anyways, for # consistency. if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True cat = unicodedata.category(char) if cat.startswith("P"): return True return False def _is_end_of_word(text): """Checks whether the last character in text is one of a punctuation, control or whitespace character.""" last_char = text[-1] return bool(_is_control(last_char) | _is_punctuation(last_char) | _is_whitespace(last_char)) def _is_start_of_word(text): """Checks whether the first character in text is one of a punctuation, control or whitespace character.""" first_char = text[0] return bool(_is_control(first_char) | _is_punctuation(first_char) | _is_whitespace(first_char)) def _insert_one_token_to_ordered_list(token_list: List[str], new_token: str): """ Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted. """ insertion_idx = bisect.bisect_left(token_list, new_token) # Checks if new_token is already in the ordered token_list if insertion_idx < len(token_list) and token_list[insertion_idx] == new_token: # new_token is in token_list, don't add return else: token_list.insert(insertion_idx, new_token) @add_end_docstrings(INIT_TOKENIZER_DOCSTRING) class PreTrainedTokenizer(PreTrainedTokenizerBase): """ Base class for all slow tokenizers. Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`]. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading pretrained tokenizers as well as adding tokens to the vocabulary. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...). """ def __init__(self, **kwargs): super().__init__(**kwargs) # Added tokens - We store this for both slow and fast tokenizers # until the serialization of Fast tokenizers is updated self.added_tokens_encoder: Dict[str, int] = {} self.added_tokens_decoder: Dict[int, str] = {} self.unique_no_split_tokens: List[str] = [] self.tokens_trie = Trie() self._decode_use_source_tokenizer = False @property def is_fast(self) -> bool: return False @property def vocab_size(self) -> int: """ `int`: Size of the base vocabulary (without the added tokens). """ raise NotImplementedError def get_added_vocab(self) -> Dict[str, int]: """ Returns the added tokens in the vocabulary as a dictionary of token to index. Returns: `Dict[str, int]`: The added tokens. """ return self.added_tokens_encoder def __len__(self): """ Size of the full vocabulary with the added tokens. """ return self.vocab_size + len(self.added_tokens_encoder) def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int: """ Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to it with indices starting from length of the current vocabulary. Args: new_tokens (`List[str]`or `List[tokenizers.AddedToken]`): Token(s) to add in vocabulary. A token is only added if it's not already in the vocabulary (tested by checking if the tokenizer assign the index of the `unk_token` to them). special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the tokens should be added as special tokens. Returns: `int`: The number of tokens actually added to the vocabulary. Examples: ```python # Let's see how to increase the vocabulary of Bert model and tokenizer tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") model = BertModel.from_pretrained("bert-base-uncased") num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"]) print("We have added", num_added_toks, "tokens") # Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer. model.resize_token_embeddings(len(tokenizer)) ```""" new_tokens = [str(tok) for tok in new_tokens] tokens_to_add = [] for token in new_tokens: if not isinstance(token, str): raise TypeError(f"Token {token} is not a string but a {type(token)}.") if not special_tokens and hasattr(self, "do_lower_case") and self.do_lower_case: token = token.lower() if ( token != self.unk_token and self.convert_tokens_to_ids(token) == self.convert_tokens_to_ids(self.unk_token) and token not in tokens_to_add ): tokens_to_add.append(token) if self.verbose: logger.info(f"Adding {token} to the vocabulary") added_tok_encoder = {tok: len(self) + i for i, tok in enumerate(tokens_to_add)} added_tok_decoder = {v: k for k, v in added_tok_encoder.items()} self.added_tokens_encoder.update(added_tok_encoder) self.added_tokens_decoder.update(added_tok_decoder) # Make sure we don't split on any special tokens (even they were already in the vocab before e.g. for Albert) if special_tokens: if len(new_tokens) == 1: _insert_one_token_to_ordered_list(self.unique_no_split_tokens, new_tokens[0]) else: self.unique_no_split_tokens = sorted(set(self.unique_no_split_tokens).union(set(new_tokens))) else: # Or on the newly added tokens if len(tokens_to_add) == 1: _insert_one_token_to_ordered_list(self.unique_no_split_tokens, tokens_to_add[0]) else: self.unique_no_split_tokens = sorted(set(self.unique_no_split_tokens).union(set(tokens_to_add))) self._create_trie(self.unique_no_split_tokens) return len(tokens_to_add) def _create_trie(self, unique_no_split_tokens): trie = Trie() for token in unique_no_split_tokens: if hasattr(self, "do_lower_case") and self.do_lower_case and token not in self.all_special_tokens: trie.add(token.lower()) else: trie.add(token) self.tokens_trie = trie def num_special_tokens_to_add(self, pair: bool = False) -> int: """ Returns the number of added tokens when encoding a sequence with special tokens. <Tip> This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put this inside your training loop. </Tip> Args: pair (`bool`, *optional*, defaults to `False`): Whether the number of added tokens should be computed in the case of a sequence pair or a single sequence. Returns: `int`: Number of special tokens added to sequences. """ token_ids_0 = [] token_ids_1 = [] return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None)) def tokenize(self, text: TextInput, **kwargs) -> List[str]: """ Converts a string in a sequence of tokens, using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces). Takes care of added tokens. Args: text (`str`): The sequence to be encoded. **kwargs (additional keyword arguments): Passed along to the model-specific `prepare_for_tokenization` preprocessing method. Returns: `List[str]`: The list of tokens. """ # Simple mapping string => AddedToken for special tokens with specific tokenization behaviors all_special_tokens_extended = { str(t): t for t in self.all_special_tokens_extended if isinstance(t, AddedToken) } text, kwargs = self.prepare_for_tokenization(text, **kwargs) if kwargs: logger.warning(f"Keyword arguments {kwargs} not recognized.") # TODO: should this be in the base class? if hasattr(self, "do_lower_case") and self.do_lower_case: # convert non-special tokens to lowercase escaped_special_toks = [ re.escape(s_tok) for s_tok in (self.unique_no_split_tokens + self.all_special_tokens) ] pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)" text = re.sub(pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text) no_split_token = set(self.unique_no_split_tokens) tokens = self.tokens_trie.split(text) # ["This is something", "<special_token_1>", " else"] for i, token in enumerate(tokens): if token in no_split_token: tok_extended = all_special_tokens_extended.get(token, None) left = tokens[i - 1] if i > 0 else None right = tokens[i + 1] if i < len(tokens) - 1 else None if isinstance(tok_extended, AddedToken): if tok_extended.rstrip and right: # A bit counter-intuitive but we strip the left of the string # since tok_extended.rstrip means the special token is eating all white spaces on its right tokens[i + 1] = right.lstrip() # Strip white spaces on the left if tok_extended.lstrip and left: tokens[i - 1] = left.rstrip() # Opposite here else: # We strip left and right by default if right: tokens[i + 1] = right.lstrip() if left: tokens[i - 1] = left.rstrip() # ["This is something", "<special_token_1>", "else"] tokenized_text = [] for token in tokens: # Need to skip eventual empty (fully stripped) tokens if not token: continue if token in no_split_token: tokenized_text.append(token) else: tokenized_text.extend(self._tokenize(token)) # ["This", " is", " something", "<special_token_1>", "else"] return tokenized_text def _tokenize(self, text, **kwargs): """ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces). Do NOT take care of added tokens. """ raise NotImplementedError def convert_tokens_to_ids(self, tokens: Union[str, List[str]]) -> Union[int, List[int]]: """ Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the vocabulary. Args: tokens (`str` or `List[str]`): One or several token(s) to convert to token id(s). Returns: `int` or `List[int]`: The token id or list of token ids. """ if tokens is None: return None if isinstance(tokens, str): return self._convert_token_to_id_with_added_voc(tokens) ids = [] for token in tokens: ids.append(self._convert_token_to_id_with_added_voc(token)) return ids def _convert_token_to_id_with_added_voc(self, token): if token is None: return None if token in self.added_tokens_encoder: return self.added_tokens_encoder[token] return self._convert_token_to_id(token) def _convert_token_to_id(self, token): raise NotImplementedError def _encode_plus( self, text: Union[TextInput, PreTokenizedInput, EncodedInput], text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None, add_special_tokens: bool = True, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE, max_length: Optional[int] = None, stride: int = 0, is_split_into_words: bool = False, pad_to_multiple_of: Optional[int] = None, return_tensors: Optional[Union[str, TensorType]] = None, return_token_type_ids: Optional[bool] = None, return_attention_mask: Optional[bool] = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_offsets_mapping: bool = False, return_length: bool = False, verbose: bool = True, **kwargs, ) -> BatchEncoding: def get_input_ids(text): if isinstance(text, str): tokens = self.tokenize(text, **kwargs) return self.convert_tokens_to_ids(tokens) elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str): if is_split_into_words: tokens = list( itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text)) ) return self.convert_tokens_to_ids(tokens) else: return self.convert_tokens_to_ids(text) elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int): return text else: if is_split_into_words: raise ValueError( f"Input {text} is not valid. Should be a string or a list/tuple of strings when" " `is_split_into_words=True`." ) else: raise ValueError( f"Input {text} is not valid. Should be a string, a list/tuple of strings or a list/tuple of" " integers." ) if return_offsets_mapping: raise NotImplementedError( "return_offset_mapping is not available when using Python tokenizers. " "To use this feature, change your tokenizer to one deriving from " "transformers.PreTrainedTokenizerFast. " "More information on available tokenizers at " "https://github.com/huggingface/transformers/pull/2674" ) first_ids = get_input_ids(text) second_ids = get_input_ids(text_pair) if text_pair is not None else None return self.prepare_for_model( first_ids, pair_ids=second_ids, add_special_tokens=add_special_tokens, padding=padding_strategy.value, truncation=truncation_strategy.value, max_length=max_length, stride=stride, pad_to_multiple_of=pad_to_multiple_of, return_tensors=return_tensors, prepend_batch_axis=True, return_attention_mask=return_attention_mask, return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask, return_length=return_length, verbose=verbose, ) def _batch_encode_plus( self, batch_text_or_text_pairs: Union[ List[TextInput], List[TextInputPair], List[PreTokenizedInput], List[PreTokenizedInputPair], List[EncodedInput], List[EncodedInputPair], ], add_special_tokens: bool = True, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE, max_length: Optional[int] = None, stride: int = 0, is_split_into_words: bool = False, pad_to_multiple_of: Optional[int] = None, return_tensors: Optional[Union[str, TensorType]] = None, return_token_type_ids: Optional[bool] = None, return_attention_mask: Optional[bool] = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_offsets_mapping: bool = False, return_length: bool = False, verbose: bool = True, **kwargs, ) -> BatchEncoding: def get_input_ids(text): if isinstance(text, str): tokens = self.tokenize(text, **kwargs) return self.convert_tokens_to_ids(tokens) elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str): if is_split_into_words: tokens = list( itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text)) ) return self.convert_tokens_to_ids(tokens) else: return self.convert_tokens_to_ids(text) elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int): return text else: raise ValueError( "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers." ) if return_offsets_mapping: raise NotImplementedError( "return_offset_mapping is not available when using Python tokenizers. " "To use this feature, change your tokenizer to one deriving from " "transformers.PreTrainedTokenizerFast." ) input_ids = [] for ids_or_pair_ids in batch_text_or_text_pairs: if not isinstance(ids_or_pair_ids, (list, tuple)): ids, pair_ids = ids_or_pair_ids, None elif is_split_into_words and not isinstance(ids_or_pair_ids[0], (list, tuple)): ids, pair_ids = ids_or_pair_ids, None else: ids, pair_ids = ids_or_pair_ids first_ids = get_input_ids(ids) second_ids = get_input_ids(pair_ids) if pair_ids is not None else None input_ids.append((first_ids, second_ids)) batch_outputs = self._batch_prepare_for_model( input_ids, add_special_tokens=add_special_tokens, padding_strategy=padding_strategy, truncation_strategy=truncation_strategy, max_length=max_length, stride=stride, pad_to_multiple_of=pad_to_multiple_of, return_attention_mask=return_attention_mask, return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask, return_length=return_length, return_tensors=return_tensors, verbose=verbose, ) return BatchEncoding(batch_outputs) @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING) def _batch_prepare_for_model( self, batch_ids_pairs: List[Union[PreTokenizedInputPair, Tuple[List[int], None]]], add_special_tokens: bool = True, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE, max_length: Optional[int] = None, stride: int = 0, pad_to_multiple_of: Optional[int] = None, return_tensors: Optional[str] = None, return_token_type_ids: Optional[bool] = None, return_attention_mask: Optional[bool] = None, return_overflowing_tokens: bool = False, return_special_tokens_mask: bool = False, return_length: bool = False, verbose: bool = True, ) -> BatchEncoding: """ Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It adds special tokens, truncates sequences if overflowing while taking into account the special tokens and manages a moving window (with user defined stride) for overflowing tokens Args: batch_ids_pairs: list of tokenized input ids or input ids pairs """ batch_outputs = {} for first_ids, second_ids in batch_ids_pairs: outputs = self.prepare_for_model( first_ids, second_ids, add_special_tokens=add_special_tokens, padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward truncation=truncation_strategy.value, max_length=max_length, stride=stride, pad_to_multiple_of=None, # we pad in batch afterward return_attention_mask=False, # we pad in batch afterward return_token_type_ids=return_token_type_ids, return_overflowing_tokens=return_overflowing_tokens, return_special_tokens_mask=return_special_tokens_mask, return_length=return_length, return_tensors=None, # We convert the whole batch to tensors at the end prepend_batch_axis=False, verbose=verbose, ) for key, value in outputs.items(): if key not in batch_outputs: batch_outputs[key] = [] batch_outputs[key].append(value) batch_outputs = self.pad( batch_outputs, padding=padding_strategy.value, max_length=max_length, pad_to_multiple_of=pad_to_multiple_of, return_attention_mask=return_attention_mask, ) batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors) return batch_outputs def prepare_for_tokenization( self, text: str, is_split_into_words: bool = False, **kwargs ) -> Tuple[str, Dict[str, Any]]: """ Performs any necessary transformations before tokenization. This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the `kwargs` at the end of the encoding process to be sure all the arguments have been used. Args: text (`str`): The text to prepare. is_split_into_words (`bool`, *optional*, defaults to `False`): Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification. kwargs: Keyword arguments to use for the tokenization. Returns: `Tuple[str, Dict[str, Any]]`: The prepared text and the unused kwargs. """ return (text, kwargs) def get_special_tokens_mask( self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieves 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` or `encode_plus` methods. Args: token_ids_0 (`List[int]`): List of ids of the first sequence. token_ids_1 (`List[int]`, *optional*): List of ids of the second sequence. 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: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: if token_ids_1 is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True ) return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0)) @overload def convert_ids_to_tokens(self, ids: int, skip_special_tokens: bool = False) -> str: ... @overload def convert_ids_to_tokens(self, ids: List[int], skip_special_tokens: bool = False) -> List[str]: ... def convert_ids_to_tokens( self, ids: Union[int, List[int]], skip_special_tokens: bool = False ) -> Union[str, List[str]]: """ Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and added tokens. Args: ids (`int` or `List[int]`): The token id (or token ids) to convert to tokens. skip_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not to remove special tokens in the decoding. Returns: `str` or `List[str]`: The decoded token(s). """ if isinstance(ids, int): if ids in self.added_tokens_decoder: return self.added_tokens_decoder[ids] else: return self._convert_id_to_token(ids) tokens = [] for index in ids: index = int(index) if skip_special_tokens and index in self.all_special_ids: continue if index in self.added_tokens_decoder: tokens.append(self.added_tokens_decoder[index]) else: tokens.append(self._convert_id_to_token(index)) return tokens def _convert_id_to_token(self, index: int) -> str: raise NotImplementedError def convert_tokens_to_string(self, tokens: List[str]) -> str: return " ".join(tokens) def _decode( self, token_ids: List[int], skip_special_tokens: bool = False, clean_up_tokenization_spaces: bool = True, spaces_between_special_tokens: bool = True, **kwargs, ) -> str: self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False) filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 sub_texts = [] current_sub_text = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(current_sub_text)) current_sub_text = [] sub_texts.append(token) else: current_sub_text.append(token) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(current_sub_text)) if spaces_between_special_tokens: text = " ".join(sub_texts) else: text = "".join(sub_texts) if clean_up_tokenization_spaces: clean_text = self.clean_up_tokenization(text) return clean_text else: return text
27182812/ChatGLM-LLaMA-chinese-insturct
56,032
src/transformers/modeling_flax_utils.py
# coding=utf-8 # Copyright 2021 The Google Flax 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. import gc import json import os import re from functools import partial from pickle import UnpicklingError from typing import Any, Dict, Set, Tuple, Union import flax.linen as nn import jax import jax.numpy as jnp import msgpack.exceptions from flax.core.frozen_dict import FrozenDict, unfreeze from flax.serialization import from_bytes, to_bytes from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from .configuration_utils import PretrainedConfig from .dynamic_module_utils import custom_object_save from .generation import FlaxGenerationMixin, GenerationConfig from .modeling_flax_pytorch_utils import load_pytorch_checkpoint_in_flax_state_dict from .utils import ( FLAX_WEIGHTS_INDEX_NAME, FLAX_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, PushToHubMixin, add_code_sample_docstrings, add_start_docstrings_to_model_forward, cached_file, copy_func, download_url, has_file, is_offline_mode, is_remote_url, logging, replace_return_docstrings, ) from .utils.hub import convert_file_size_to_int, get_checkpoint_shard_files logger = logging.get_logger(__name__) def quick_gelu(x): return x * jax.nn.sigmoid(1.702 * x) ACT2FN = { "gelu": partial(nn.gelu, approximate=False), "relu": nn.relu, "silu": nn.swish, "swish": nn.swish, "gelu_new": partial(nn.gelu, approximate=True), "quick_gelu": quick_gelu, } def dtype_byte_size(dtype): """ Returns the size (in bytes) occupied by one parameter of type `dtype`. Example: ```py >>> dtype_byte_size(np.float32) 4 ``` """ if dtype == bool: return 1 / 8 bit_search = re.search(r"[^\d](\d+)$", dtype.name) if bit_search is None: raise ValueError(f"`dtype` is not a valid dtype: {dtype}.") bit_size = int(bit_search.groups()[0]) return bit_size // 8 def flax_shard_checkpoint(params, max_shard_size="10GB"): """ Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a given size. The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For example, if the limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], [6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB]. <Tip warning={true}> If one of the model's weight is bigger that `max_shard_size`, it will end up in its own sub-checkpoint which will have a size greater than `max_shard_size`. </Tip> Args: params (`Union[Dict, FrozenDict]`): A `PyTree` of model parameters. max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). """ max_shard_size = convert_file_size_to_int(max_shard_size) sharded_state_dicts = [] current_block = {} current_block_size = 0 total_size = 0 # flatten the weights to chunk weights = flatten_dict(params, sep="/") for item in weights: weight_size = weights[item].size * dtype_byte_size(weights[item].dtype) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: sharded_state_dicts.append(current_block) current_block = {} current_block_size = 0 current_block[item] = weights[item] current_block_size += weight_size total_size += weight_size # Add the last block sharded_state_dicts.append(current_block) # If we only have one shard, we return it if len(sharded_state_dicts) == 1: return {FLAX_WEIGHTS_NAME: sharded_state_dicts[0]}, None # Otherwise, let's build the index weight_map = {} shards = {} for idx, shard in enumerate(sharded_state_dicts): shard_file = FLAX_WEIGHTS_NAME.replace(".msgpack", f"-{idx+1:05d}-of-{len(sharded_state_dicts):05d}.msgpack") shards[shard_file] = shard for weight_name in shard.keys(): weight_map[weight_name] = shard_file # Add the metadata metadata = {"total_size": total_size} index = {"metadata": metadata, "weight_map": weight_map} return shards, index class FlaxPreTrainedModel(PushToHubMixin, FlaxGenerationMixin): r""" Base class for all models. [`FlaxPreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading, downloading and saving models. Class attributes (overridden by derived classes): - **config_class** ([`PretrainedConfig`]) -- A subclass of [`PretrainedConfig`] to use as configuration class for this model architecture. - **base_model_prefix** (`str`) -- A string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model. - **main_input_name** (`str`) -- The name of the principal input to the model (often `input_ids` for NLP models, `pixel_values` for vision models and `input_values` for speech models). """ config_class = None base_model_prefix = "" main_input_name = "input_ids" _auto_class = None _missing_keys = set() def __init__( self, config: PretrainedConfig, module: nn.Module, input_shape: Tuple = (1, 1), seed: int = 0, dtype: jnp.dtype = jnp.float32, _do_init: bool = True, ): if config is None: raise ValueError("config cannot be None") if module is None: raise ValueError("module cannot be None") # Those are private to be exposed as typed property on derived classes. self._config = config self._module = module # Those are public as their type is generic to every derived classes. self.key = PRNGKey(seed) self.dtype = dtype self.input_shape = input_shape self.generation_config = GenerationConfig.from_model_config(config) if self.can_generate() else None # To check if the model was intialized automatically. self._is_initialized = _do_init if _do_init: # randomly initialized parameters random_params = self.init_weights(self.key, input_shape) params_shape_tree = jax.eval_shape(lambda params: params, random_params) else: init_fn = partial(self.init_weights, input_shape=input_shape) params_shape_tree = jax.eval_shape(init_fn, self.key) logger.info( "Model weights are not initialized as `_do_init` is set to `False`. " f"Make sure to call `{self.__class__.__name__}.init_weights` manually to initialize the weights." ) # get the shape of the parameters self._params_shape_tree = params_shape_tree # save required_params as set self._required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys()) # initialize the parameters if _do_init: self.params = random_params def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> Dict: raise NotImplementedError(f"init method has to be implemented for {self}") def enable_gradient_checkpointing(self): raise NotImplementedError(f"gradient checkpointing method has to be implemented for {self}") @classmethod def _from_config(cls, config, **kwargs): """ All context managers that the model should be initialized under go here. """ return cls(config, **kwargs) @property def framework(self) -> str: """ :str: Identifies that this is a Flax model. """ return "flax" @property def config(self) -> PretrainedConfig: return self._config @property def module(self) -> nn.Module: return self._module @property def params(self) -> Union[Dict, FrozenDict]: if not self._is_initialized: raise ValueError( "`params` cannot be accessed from model when the model is created with `_do_init=False`. " "You must call `init_weights` manually and store the params outside of the model and " "pass it explicitly where needed." ) return self._params @property def required_params(self) -> Set: return self._required_params @property def params_shape_tree(self) -> Dict: return self._params_shape_tree @params.setter def params(self, params: Union[Dict, FrozenDict]): # don't set params if the model is not initialized if not self._is_initialized: raise ValueError( "`params` cannot be set from model when the model is created with `_do_init=False`. " "You store the params outside of the model." ) if isinstance(params, FrozenDict): params = unfreeze(params) param_keys = set(flatten_dict(params).keys()) if len(self.required_params - param_keys) > 0: raise ValueError( "Some parameters are missing. Make sure that `params` include the following " f"parameters {self.required_params - param_keys}" ) self._params = params def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any: """ Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`. """ # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27 def conditional_cast(param): if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating): param = param.astype(dtype) return param if mask is None: return jax.tree_util.tree_map(conditional_cast, params) flat_params = flatten_dict(params) flat_mask, _ = jax.tree_util.tree_flatten(mask) for masked, key in zip(flat_mask, flat_params.keys()): if masked: param = flat_params[key] flat_params[key] = conditional_cast(param) return unflatten_dict(flat_params) def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None): r""" Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast the `params` in place. This method can be used on TPU to explicitly convert the model parameters to bfloat16 precision to do full half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed. Arguments: params (`Union[Dict, FrozenDict]`): A `PyTree` of model parameters. mask (`Union[Dict, FrozenDict]`): A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params you want to cast, and should be `False` for those you want to skip. Examples: ```python >>> from transformers import FlaxBertModel >>> # load model >>> model = FlaxBertModel.from_pretrained("bert-base-cased") >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision >>> model.params = model.to_bf16(model.params) >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale) >>> # then pass the mask as follows >>> from flax import traverse_util >>> model = FlaxBertModel.from_pretrained("bert-base-cased") >>> flat_params = traverse_util.flatten_dict(model.params) >>> mask = { ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale")) ... for path in flat_params ... } >>> mask = traverse_util.unflatten_dict(mask) >>> model.params = model.to_bf16(model.params, mask) ```""" return self._cast_floating_to(params, jnp.bfloat16, mask) def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None): r""" Cast the floating-point `parmas` to `jax.numpy.float32`. This method can be used to explicitly convert the model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place. Arguments: params (`Union[Dict, FrozenDict]`): A `PyTree` of model parameters. mask (`Union[Dict, FrozenDict]`): A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params you want to cast, and should be `False` for those you want to skip Examples: ```python >>> from transformers import FlaxBertModel >>> # Download model and configuration from huggingface.co >>> model = FlaxBertModel.from_pretrained("bert-base-cased") >>> # By default, the model params will be in fp32, to illustrate the use of this method, >>> # we'll first cast to fp16 and back to fp32 >>> model.params = model.to_f16(model.params) >>> # now cast back to fp32 >>> model.params = model.to_fp32(model.params) ```""" return self._cast_floating_to(params, jnp.float32, mask) def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None): r""" Cast the floating-point `parmas` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the `params` in place. This method can be used on GPU to explicitly convert the model parameters to float16 precision to do full half-precision training or to save weights in float16 for inference in order to save memory and improve speed. Arguments: params (`Union[Dict, FrozenDict]`): A `PyTree` of model parameters. mask (`Union[Dict, FrozenDict]`): A `PyTree` with same structure as the `params` tree. The leaves should be booleans, `True` for params you want to cast, and should be `False` for those you want to skip Examples: ```python >>> from transformers import FlaxBertModel >>> # load model >>> model = FlaxBertModel.from_pretrained("bert-base-cased") >>> # By default, the model params will be in fp32, to cast these to float16 >>> model.params = model.to_fp16(model.params) >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale) >>> # then pass the mask as follows >>> from flax import traverse_util >>> model = FlaxBertModel.from_pretrained("bert-base-cased") >>> flat_params = traverse_util.flatten_dict(model.params) >>> mask = { ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale")) ... for path in flat_params ... } >>> mask = traverse_util.unflatten_dict(mask) >>> model.params = model.to_fp16(model.params, mask) ```""" return self._cast_floating_to(params, jnp.float16, mask) @classmethod def load_flax_sharded_weights(cls, shard_files): """ This is the same as [`flax.serialization.from_bytes`] (https:lax.readthedocs.io/en/latest/_modules/flax/serialization.html#from_bytes) but for a sharded checkpoint. This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and deleted after being loaded in the model. Args: shard_files (`List[str]`: The list of shard files to load. Returns: `Dict`: A nested dictionary of the model parameters, in the expected format for flax models : `{'model': {'params': {'...'}}}`. """ # Load the index state_sharded_dict = {} for shard_file in shard_files: # load using msgpack utils try: with open(shard_file, "rb") as state_f: state = from_bytes(cls, state_f.read()) except (UnpicklingError, msgpack.exceptions.ExtraData) as e: with open(shard_file) as f: if f.read().startswith("version"): raise OSError( "You seem to have cloned a repository without having git-lfs installed. Please" " install git-lfs and run `git lfs install` followed by `git lfs pull` in the" " folder you cloned." ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f"Unable to convert {shard_file} to Flax deserializable object. ") state = flatten_dict(state, sep="/") state_sharded_dict.update(state) del state gc.collect() # the state dict is unflattened to the match the format of model.params return unflatten_dict(state_sharded_dict, sep="/") def can_generate(self) -> bool: """ Returns whether this model can generate sequences with `.generate()`. Returns: `bool`: Whether this model can generate sequences with `.generate()`. """ # Detects whether `prepare_inputs_for_generation` has been overwritten, which is a requirement for generation if "GenerationMixin" in str(self.prepare_inputs_for_generation): return False return True @classmethod def from_pretrained( cls, pretrained_model_name_or_path: Union[str, os.PathLike], dtype: jnp.dtype = jnp.float32, *model_args, **kwargs, ): r""" Instantiate a pretrained flax model from a pre-trained model configuration. The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning task. The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those weights are discarded. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - A path to a *directory* containing model weights saved using [`~FlaxPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. - A path or url to a *pt index checkpoint file* (e.g, `./tf_model/model.ckpt.index`). In this case, `from_pt` should be set to `True`. dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`): The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and `jax.numpy.bfloat16` (on TPUs). This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If specified all the computation will be performed with the given `dtype`. **Note that this only specifies the dtype of the computation and does not influence the dtype of model parameters.** If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and [`~FlaxPreTrainedModel.to_bf16`]. model_args (sequence of positional arguments, *optional*): All remaining positional arguments will be passed to the underlying model's `__init__` method. config (`Union[PretrainedConfig, str, os.PathLike]`, *optional*): Can be either: - an instance of a class derived from [`PretrainedConfig`], - a string or path valid as input to [`~PretrainedConfig.from_pretrained`]. Configuration for the model to use instead of an automatically loaded configuration. Configuration can be automatically loaded when: - The model is a model provided by the library (loaded with the *model id* string of a pretrained model). - The model was saved using [`~PreTrainedModel.save_pretrained`] and is reloaded by supplying the save directory. - The model is loaded by supplying a local directory as `pretrained_model_name_or_path` and a configuration JSON file named *config.json* is found in the directory. cache_dir (`Union[str, os.PathLike]`, *optional*): Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used. from_pt (`bool`, *optional*, defaults to `False`): Load the model weights from a PyTorch checkpoint save file (see docstring of `pretrained_model_name_or_path` argument). ignore_mismatched_sizes (`bool`, *optional*, defaults to `False`): Whether or not to raise an error if some of the weights from the checkpoint do not have the same size as the weights of the model (if for instance, you are instantiating a model with 10 labels from a checkpoint with 3 labels). force_download (`bool`, *optional*, defaults to `False`): Whether or not to force the (re-)download of the model weights and configuration files, overriding the cached versions if they exist. resume_download (`bool`, *optional*, defaults to `False`): Whether or not to delete incompletely received files. Will attempt to resume the download if such a file exists. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request. local_files_only(`bool`, *optional*, defaults to `False`): Whether or not to only look at local files (i.e., do not try to download the model). use_auth_token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". </Tip> subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. kwargs (remaining dictionary of keyword arguments, *optional*): Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., `output_attentions=True`). Behaves differently depending on whether a `config` is provided or automatically loaded: - If a configuration is provided with `config`, `**kwargs` will be directly passed to the underlying model's `__init__` method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided, `kwargs` will be first passed to the configuration class initialization function ([`~PretrainedConfig.from_pretrained`]). Each key of `kwargs` that corresponds to a configuration attribute will be used to override said attribute with the supplied `kwargs` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's `__init__` function. Examples: ```python >>> from transformers import BertConfig, FlaxBertModel >>> # Download model and configuration from huggingface.co and cache. >>> model = FlaxBertModel.from_pretrained("bert-base-cased") >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable). >>> model = FlaxBertModel.from_pretrained("./test/saved_model/") >>> # Loading from a PyTorch checkpoint file instead of a PyTorch model (slower, for example purposes, not runnable). >>> config = BertConfig.from_json_file("./pt_model/config.json") >>> model = FlaxBertModel.from_pretrained("./pt_model/pytorch_model.bin", from_pt=True, config=config) ```""" config = kwargs.pop("config", None) cache_dir = kwargs.pop("cache_dir", None) from_pt = kwargs.pop("from_pt", False) ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False) force_download = kwargs.pop("force_download", False) resume_download = kwargs.pop("resume_download", False) proxies = kwargs.pop("proxies", None) local_files_only = kwargs.pop("local_files_only", False) use_auth_token = kwargs.pop("use_auth_token", None) revision = kwargs.pop("revision", None) trust_remote_code = kwargs.pop("trust_remote_code", None) from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) _do_init = kwargs.pop("_do_init", True) subfolder = kwargs.pop("subfolder", "") commit_hash = kwargs.pop("_commit_hash", None) if trust_remote_code is True: logger.warning( "The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is" " ignored." ) user_agent = {"file_type": "model", "framework": "flax", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True # Load config if we don't provide a configuration if not isinstance(config, PretrainedConfig): config_path = config if config is not None else pretrained_model_name_or_path config, model_kwargs = cls.config_class.from_pretrained( config_path, cache_dir=cache_dir, return_unused_kwargs=True, force_download=force_download, resume_download=resume_download, proxies=proxies, local_files_only=local_files_only, use_auth_token=use_auth_token, revision=revision, subfolder=subfolder, _from_auto=from_auto_class, _from_pipeline=from_pipeline, _commit_hash=commit_hash, **kwargs, ) else: model_kwargs = kwargs.copy() if commit_hash is None: commit_hash = getattr(config, "_commit_hash", None) # Add the dtype to model_kwargs model_kwargs["dtype"] = dtype # This variable will flag if we're loading a sharded checkpoint. In this case the archive file is just the # index of the files. is_sharded = False # Load model if pretrained_model_name_or_path is not None: pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isdir(pretrained_model_name_or_path): if from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)): # Load from a PyTorch checkpoint archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME) elif from_pt and os.path.isfile( os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME) ): # Load from a sharded pytorch checkpoint archive_file = os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_INDEX_NAME) is_sharded = True elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME)): # Load from a Flax checkpoint archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_NAME) elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME)): # Load from a sharded Flax checkpoint archive_file = os.path.join(pretrained_model_name_or_path, subfolder, FLAX_WEIGHTS_INDEX_NAME) is_sharded = True # At this stage we don't have a weight file so we will raise an error. elif os.path.isfile(os.path.join(pretrained_model_name_or_path, subfolder, WEIGHTS_NAME)): raise EnvironmentError( f"Error no file named {FLAX_WEIGHTS_NAME} found in directory {pretrained_model_name_or_path} " "but there is a file for PyTorch weights. Use `from_pt=True` to load this model from those " "weights." ) else: raise EnvironmentError( f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory " f"{pretrained_model_name_or_path}." ) elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)): archive_file = pretrained_model_name_or_path is_local = True elif is_remote_url(pretrained_model_name_or_path): filename = pretrained_model_name_or_path resolved_archive_file = download_url(pretrained_model_name_or_path) else: filename = WEIGHTS_NAME if from_pt else FLAX_WEIGHTS_NAME try: # Load from URL or cache if already cached cached_file_kwargs = { "cache_dir": cache_dir, "force_download": force_download, "proxies": proxies, "resume_download": resume_download, "local_files_only": local_files_only, "use_auth_token": use_auth_token, "user_agent": user_agent, "revision": revision, "subfolder": subfolder, "_raise_exceptions_for_missing_entries": False, "_commit_hash": commit_hash, } resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs) # Since we set _raise_exceptions_for_missing_entries=False, we don't get an expection but a None # result when internet is up, the repo and revision exist, but the file does not. if resolved_archive_file is None and filename == FLAX_WEIGHTS_NAME: # Maybe the checkpoint is sharded, we try to grab the index name in this case. resolved_archive_file = cached_file( pretrained_model_name_or_path, FLAX_WEIGHTS_INDEX_NAME, **cached_file_kwargs ) if resolved_archive_file is not None: is_sharded = True # Maybe the checkpoint is pytorch sharded, we try to grab the pytorch index name in this case. elif resolved_archive_file is None and from_pt: resolved_archive_file = cached_file( pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **cached_file_kwargs ) if resolved_archive_file is not None: is_sharded = True if resolved_archive_file is None: # Otherwise, maybe there is a TF or Flax model file. We try those to give a helpful error # message. has_file_kwargs = { "revision": revision, "proxies": proxies, "use_auth_token": use_auth_token, } if has_file(pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs): raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named" f" {FLAX_WEIGHTS_NAME} but there is a file for PyTorch weights. Use `from_pt=True` to" " load this model from those weights." ) elif has_file(pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **has_file_kwargs): raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named" f" {FLAX_WEIGHTS_INDEX_NAME} but there is a sharded file for PyTorch weights. Use" " `from_pt=True` to load this model from those weights." ) else: raise EnvironmentError( f"{pretrained_model_name_or_path} does not appear to have a file named" f" {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}." ) except EnvironmentError: # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted # to the original exception. raise except Exception: # For any other exception, we throw a generic error. raise EnvironmentError( f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it" " from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}." ) if is_local: logger.info(f"loading weights file {archive_file}") resolved_archive_file = archive_file else: logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}") else: resolved_archive_file = None # We'll need to download and cache each checkpoint shard if the checkpoint is sharded. if is_sharded: # resolved_archive_file becomes a list of files that point to the different checkpoint shards in this case. resolved_archive_file, _ = get_checkpoint_shard_files( pretrained_model_name_or_path, resolved_archive_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, local_files_only=local_files_only, use_auth_token=use_auth_token, user_agent=user_agent, revision=revision, subfolder=subfolder, _commit_hash=commit_hash, ) # init random models model = cls(config, *model_args, _do_init=_do_init, **model_kwargs) if from_pt: state = load_pytorch_checkpoint_in_flax_state_dict(model, resolved_archive_file, is_sharded) else: if is_sharded: state = cls.load_flax_sharded_weights(resolved_archive_file) else: try: with open(resolved_archive_file, "rb") as state_f: state = from_bytes(cls, state_f.read()) except (UnpicklingError, msgpack.exceptions.ExtraData) as e: try: with open(resolved_archive_file) as f: if f.read().startswith("version"): raise OSError( "You seem to have cloned a repository without having git-lfs installed. Please" " install git-lfs and run `git lfs install` followed by `git lfs pull` in the" " folder you cloned." ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(f"Unable to convert {archive_file} to Flax deserializable object. ") # make sure all arrays are stored as jnp.arrays # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4: # https://github.com/google/flax/issues/1261 if _do_init: state = jax.tree_util.tree_map(jnp.array, state) else: # keep the params on CPU if we don't want to initialize state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.devices("cpu")[0]), state) if "batch_stats" in state: # if flax model contains batch norm layers # if model is base model only use model_prefix key if ( cls.base_model_prefix not in dict(model.params_shape_tree["params"]) and cls.base_model_prefix in state["params"] ): state["params"] = state["params"][cls.base_model_prefix] state["batch_stats"] = state["batch_stats"][cls.base_model_prefix] # if model is head model and we are loading weights from base model # we initialize new params dict with base_model_prefix if ( cls.base_model_prefix in dict(model.params_shape_tree["params"]) and cls.base_model_prefix not in state["params"] ): state = { "params": {cls.base_model_prefix: state["params"]}, "batch_stats": {cls.base_model_prefix: state["batch_stats"]}, } else: # if model is base model only use model_prefix key if cls.base_model_prefix not in dict(model.params_shape_tree) and cls.base_model_prefix in state: state = state[cls.base_model_prefix] # if model is head model and we are loading weights from base model # we initialize new params dict with base_model_prefix if cls.base_model_prefix in dict(model.params_shape_tree) and cls.base_model_prefix not in state: state = {cls.base_model_prefix: state} # flatten dicts state = flatten_dict(state) random_state = flatten_dict(unfreeze(model.params if _do_init else model.params_shape_tree)) missing_keys = model.required_params - set(state.keys()) unexpected_keys = set(state.keys()) - model.required_params # Disabling warning when porting pytorch weights to flax, flax does not uses num_batches_tracked for unexpected_key in unexpected_keys.copy(): if "num_batches_tracked" in unexpected_key[-1]: unexpected_keys.remove(unexpected_key) if missing_keys and not _do_init: logger.warning( f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. " "Make sure to call model.init_weights to initialize the missing weights." ) cls._missing_keys = missing_keys # Mistmatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not # matching the weights in the model. mismatched_keys = [] for key in state.keys(): if key in random_state and state[key].shape != random_state[key].shape: if ignore_mismatched_sizes: mismatched_keys.append((key, state[key].shape, random_state[key].shape)) state[key] = random_state[key] else: raise ValueError( f"Trying to load the pretrained weight for {key} failed: checkpoint has shape " f"{state[key].shape} which is incompatible with the model shape {random_state[key].shape}. " "Using `ignore_mismatched_sizes=True` if you really want to load this checkpoint inside this " "model." ) # add missing keys as random parameters if we are initializing if missing_keys and _do_init: for missing_key in missing_keys: state[missing_key] = random_state[missing_key] # remove unexpected keys to not be saved again for unexpected_key in unexpected_keys: del state[unexpected_key] if len(unexpected_keys) > 0: logger.warning( f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when" f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are" f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or" " with another architecture (e.g. initializing a BertForSequenceClassification model from a" " BertForPreTraining model).\n- This IS NOT expected if you are initializing" f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly identical" " (initializing a BertForSequenceClassification model from a BertForSequenceClassification model)." ) else: logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n") if len(missing_keys) > 0: logger.warning( f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at" f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably" " TRAIN this model on a down-stream task to be able to use it for predictions and inference." ) elif len(mismatched_keys) == 0: logger.info( f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at" f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint" f" was trained on, you can already use {model.__class__.__name__} for predictions without further" " training." ) if len(mismatched_keys) > 0: mismatched_warning = "\n".join( [ f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated" for key, shape1, shape2 in mismatched_keys ] ) logger.warning( f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at" f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not" f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be able" " to use it for predictions and inference." ) # dictionary of key: dtypes for the model params param_dtypes = jax.tree_util.tree_map(lambda x: x.dtype, state) # extract keys of parameters not in jnp.float32 fp16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.float16] bf16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.bfloat16] # raise a warning if any of the parameters are not in jnp.float32 if len(fp16_params) > 0: logger.warning( f"Some of the weights of {model.__class__.__name__} were initialized in float16 precision from " f"the model checkpoint at {pretrained_model_name_or_path}:\n{fp16_params}\n" "You should probably UPCAST the model weights to float32 if this was not intended. " "See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this." ) if len(bf16_params) > 0: logger.warning( f"Some of the weights of {model.__class__.__name__} were initialized in bfloat16 precision from " f"the model checkpoint at {pretrained_model_name_or_path}:\n{bf16_params}\n" "You should probably UPCAST the model weights to float32 if this was not intended. " "See [`~FlaxPreTrainedModel.to_fp32`] for further information on how to do this." ) # If it is a model with generation capabilities, attempt to load the generation config if model.can_generate(): try: model.generation_config = GenerationConfig.from_pretrained( pretrained_model_name_or_path, cache_dir=cache_dir, force_download=force_download, resume_download=resume_download, proxies=proxies, local_files_only=local_files_only, use_auth_token=use_auth_token, revision=revision, subfolder=subfolder, _from_auto=from_auto_class, _from_pipeline=from_pipeline, **kwargs, ) except OSError: logger.info( "Generation config file not found, using a generation config created from the model config." ) pass if _do_init: # set correct parameters model.params = unflatten_dict(state) return model else: return model, unflatten_dict(state) def save_pretrained( self, save_directory: Union[str, os.PathLike], params=None, push_to_hub=False, max_shard_size="10GB", **kwargs ): """ Save a model and its configuration file to a directory, so that it can be re-loaded using the `[`~FlaxPreTrainedModel.from_pretrained`]` class method Arguments: save_directory (`str` or `os.PathLike`): Directory to which to save. Will be created if it doesn't exist. push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). <Tip warning={true}> If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard which will be bigger than `max_shard_size`. </Tip> kwargs: Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): logger.error(f"Provided path ({save_directory}) should be a directory, not a file") return os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = self._create_repo(repo_id, **kwargs) files_timestamps = self._get_files_timestamps(save_directory) # get abs dir save_directory = os.path.abspath(save_directory) # save config as well self.config.architectures = [self.__class__.__name__[4:]] # If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self.config) self.config.save_pretrained(save_directory) if self.can_generate(): self.generation_config.save_pretrained(save_directory) # save model output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME) shards, index = flax_shard_checkpoint(params if params is not None else self.params, max_shard_size) # Clean the folder from a previous save for filename in os.listdir(save_directory): full_filename = os.path.join(save_directory, filename) if ( filename.startswith(FLAX_WEIGHTS_NAME[:-4]) and os.path.isfile(full_filename) and filename not in shards.keys() ): os.remove(full_filename) if index is None: with open(output_model_file, "wb") as f: params = params if params is not None else self.params model_bytes = to_bytes(params) f.write(model_bytes) else: save_index_file = os.path.join(save_directory, FLAX_WEIGHTS_INDEX_NAME) # Save the index as well with open(save_index_file, "w", encoding="utf-8") as f: content = json.dumps(index, indent=2, sort_keys=True) + "\n" f.write(content) logger.info( f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be " f"split in {len(shards)} checkpoint shards. You can find where each parameters has been saved in the " f"index located at {save_index_file}." ) for shard_file, shard in shards.items(): # the shard item are unflattened, to save them we need to flatten them again with open(os.path.join(save_directory, shard_file), mode="wb") as f: params = unflatten_dict(shard, sep="/") shard_bytes = to_bytes(params) f.write(shard_bytes) logger.info(f"Model weights saved in {output_model_file}") if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("use_auth_token"), ) @classmethod def register_for_auto_class(cls, auto_class="FlaxAutoModel"): """ Register this class with a given auto class. This should only be used for custom models as the ones in the library are already mapped with an auto class. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. </Tip> Args: auto_class (`str` or `type`, *optional*, defaults to `"FlaxAutoModel"`): The auto class to register this new model with. """ if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f"{auto_class} is not a valid auto class.") cls._auto_class = auto_class # To update the docstring, we need to copy the method, otherwise we change the original docstring. FlaxPreTrainedModel.push_to_hub = copy_func(FlaxPreTrainedModel.push_to_hub) if FlaxPreTrainedModel.push_to_hub.__doc__ is not None: FlaxPreTrainedModel.push_to_hub.__doc__ = FlaxPreTrainedModel.push_to_hub.__doc__.format( object="model", object_class="FlaxAutoModel", object_files="model checkpoint" ) def overwrite_call_docstring(model_class, docstring): # copy __call__ function to be sure docstring is changed only for this function model_class.__call__ = copy_func(model_class.__call__) # delete existing docstring model_class.__call__.__doc__ = None # set correct docstring model_class.__call__ = add_start_docstrings_to_model_forward(docstring)(model_class.__call__) def append_call_sample_docstring(model_class, checkpoint, output_type, config_class, mask=None): model_class.__call__ = copy_func(model_class.__call__) model_class.__call__ = add_code_sample_docstrings( checkpoint=checkpoint, output_type=output_type, config_class=config_class, model_cls=model_class.__name__, )(model_class.__call__) def append_replace_return_docstrings(model_class, output_type, config_class): model_class.__call__ = copy_func(model_class.__call__) model_class.__call__ = replace_return_docstrings( output_type=output_type, config_class=config_class, )(model_class.__call__)
27182812/ChatGLM-LLaMA-chinese-insturct
18,210
src/transformers/modeling_flax_pytorch_utils.py
# coding=utf-8 # Copyright 2021 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 - Flax general utilities.""" import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging logger = logging.get_logger(__name__) ##################### # PyTorch => Flax # ##################### def load_pytorch_checkpoint_in_flax_state_dict( flax_model, pytorch_checkpoint_path, is_sharded, allow_missing_keys=False ): """Load pytorch checkpoints in a flax model""" try: import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise if not is_sharded: pt_path = os.path.abspath(pytorch_checkpoint_path) logger.info(f"Loading PyTorch weights from {pt_path}") pt_state_dict = torch.load(pt_path, map_location="cpu") logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()):,} parameters.") flax_state_dict = convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files flax_state_dict = convert_pytorch_sharded_state_dict_to_flax(pytorch_checkpoint_path, flax_model) return flax_state_dict def rename_key_and_reshape_tensor( pt_tuple_key: Tuple[str], pt_tensor: np.ndarray, random_flax_state_dict: Dict[str, jnp.ndarray], model_prefix: str, ) -> (Tuple[str], np.ndarray): """Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary""" def is_key_or_prefix_key_in_dict(key: Tuple[str]) -> bool: """Checks if `key` of `(prefix,) + key` is in random_flax_state_dict""" return len(set(random_flax_state_dict) & {key, (model_prefix,) + key}) > 0 # layer norm renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(renamed_pt_tuple_key): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean renamed_pt_tuple_key = pt_tuple_key[:-1] + ("mean",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(pt_tuple_key): return renamed_pt_tuple_key, pt_tensor # batch norm layer var renamed_pt_tuple_key = pt_tuple_key[:-1] + ("var",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(pt_tuple_key): return renamed_pt_tuple_key, pt_tensor # embedding renamed_pt_tuple_key = pt_tuple_key[:-1] + ("embedding",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(renamed_pt_tuple_key): return renamed_pt_tuple_key, pt_tensor # conv layer renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(pt_tuple_key): pt_tensor = pt_tensor.transpose(2, 3, 1, 0) return renamed_pt_tuple_key, pt_tensor # linear layer renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(pt_tuple_key): pt_tensor = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight renamed_pt_tuple_key = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias renamed_pt_tuple_key = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model): # convert pytorch tensor to numpy pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()} model_prefix = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: flax_model_params = flax_model.params["params"] else: flax_model_params = flax_model.params random_flax_state_dict = flatten_dict(flax_model_params) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: flax_batch_stats = flatten_dict(flax_model.params["batch_stats"]) random_flax_state_dict.update(flax_batch_stats) flax_state_dict = {} load_model_with_head_into_base_model = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()} ) load_base_model_into_model_with_head = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): pt_tuple_key = tuple(pt_key.split(".")) # remove base model prefix if necessary has_base_model_prefix = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: pt_tuple_key = pt_tuple_key[1:] # Correctly rename weight parameters flax_key, flax_tensor = rename_key_and_reshape_tensor( pt_tuple_key, pt_tensor, random_flax_state_dict, model_prefix ) # add model prefix if necessary require_base_model_prefix = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: flax_key = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: flax_state_dict[("batch_stats",) + flax_key] = jnp.asarray(flax_tensor) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(flax_key, None) continue # also add unexpected weight so that warning is thrown flax_state_dict[("params",) + flax_key] = jnp.asarray(flax_tensor) else: # also add unexpected weight so that warning is thrown flax_state_dict[flax_key] = jnp.asarray(flax_tensor) return unflatten_dict(flax_state_dict) ############################ # Sharded Pytorch => Flax # ############################ def convert_pytorch_sharded_state_dict_to_flax(shard_filenames, flax_model): import torch # Load the index flax_state_dict = {} for shard_file in shard_filenames: # load using msgpack utils pt_state_dict = torch.load(shard_file) pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()} model_prefix = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: flax_model_params = flax_model.params["params"] random_flax_state_dict = flatten_dict(flax_model_params) random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"])) else: flax_model_params = flax_model.params random_flax_state_dict = flatten_dict(flax_model_params) load_model_with_head_into_base_model = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()} ) load_base_model_into_model_with_head = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): pt_tuple_key = tuple(pt_key.split(".")) # remove base model prefix if necessary has_base_model_prefix = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: pt_tuple_key = pt_tuple_key[1:] # Correctly rename weight parameters flax_key, flax_tensor = rename_key_and_reshape_tensor( pt_tuple_key, pt_tensor, random_flax_state_dict, model_prefix ) # add model prefix if necessary require_base_model_prefix = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: flax_key = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: flax_state_dict[("batch_stats",) + flax_key] = jnp.asarray(flax_tensor) continue if "var" in flax_key[-1]: flax_state_dict[("batch_stats",) + flax_key] = jnp.asarray(flax_tensor) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(flax_key, None) continue # also add unexpected weight so that warning is thrown flax_state_dict[("params",) + flax_key] = jnp.asarray(flax_tensor) else: # also add unexpected weight so that warning is thrown flax_state_dict[flax_key] = jnp.asarray(flax_tensor) return unflatten_dict(flax_state_dict) ##################### # Flax => PyTorch # ##################### def load_flax_checkpoint_in_pytorch_model(model, flax_checkpoint_path): """Load flax checkpoints in a PyTorch model""" flax_checkpoint_path = os.path.abspath(flax_checkpoint_path) logger.info(f"Loading Flax weights from {flax_checkpoint_path}") # import correct flax class flax_cls = getattr(transformers, "Flax" + model.__class__.__name__) # load flax weight dict with open(flax_checkpoint_path, "rb") as state_f: try: flax_state_dict = from_bytes(flax_cls, state_f.read()) except UnpicklingError: raise EnvironmentError(f"Unable to convert {flax_checkpoint_path} to Flax deserializable object. ") return load_flax_weights_in_pytorch_model(model, flax_state_dict) def load_flax_weights_in_pytorch_model(pt_model, flax_state): """Load flax checkpoints in a PyTorch model""" try: import torch # noqa: F401 except ImportError: logger.error( "Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights is_type_bf16 = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype == jnp.bfloat16, flax_state)).values() if any(is_type_bf16): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) flax_state = jax.tree_util.tree_map( lambda params: params.astype(np.float32) if params.dtype == jnp.bfloat16 else params, flax_state ) flax_state_dict = flatten_dict(flax_state) pt_model_dict = pt_model.state_dict() load_model_with_head_into_base_model = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split(".")[0] for k in pt_model_dict.keys()} ) load_base_model_into_model_with_head = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split(".")[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys unexpected_keys = [] missing_keys = set(pt_model_dict.keys()) for flax_key_tuple, flax_tensor in flax_state_dict.items(): has_base_model_prefix = flax_key_tuple[0] == pt_model.base_model_prefix require_base_model_prefix = ".".join((pt_model.base_model_prefix,) + flax_key_tuple) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: flax_key_tuple = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: flax_key_tuple = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(flax_key_tuple) not in pt_model_dict: # conv layer flax_key_tuple = flax_key_tuple[:-1] + ("weight",) flax_tensor = jnp.transpose(flax_tensor, (3, 2, 0, 1)) elif flax_key_tuple[-1] == "kernel" and ".".join(flax_key_tuple) not in pt_model_dict: # linear layer flax_key_tuple = flax_key_tuple[:-1] + ("weight",) flax_tensor = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: flax_key_tuple = flax_key_tuple[:-1] + ("weight",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: flax_key_tuple = flax_key_tuple[:-1] + ("running_mean",) elif "var" in flax_key_tuple[-1]: flax_key_tuple = flax_key_tuple[:-1] + ("running_var",) if "batch_stats" in flax_state: flax_key = ".".join(flax_key_tuple[1:]) # Remove the params/batch_stats header else: flax_key = ".".join(flax_key_tuple) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}." ) else: # add weight to pytorch dict flax_tensor = np.asarray(flax_tensor) if not isinstance(flax_tensor, np.ndarray) else flax_tensor pt_model_dict[flax_key] = torch.from_numpy(flax_tensor) # remove from missing keys missing_keys.remove(flax_key) else: # weight is not expected by PyTorch model unexpected_keys.append(flax_key) pt_model.load_state_dict(pt_model_dict) # re-transform missing_keys to list missing_keys = list(missing_keys) if len(unexpected_keys) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) else: logger.warning(f"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n") if len(missing_keys) > 0: logger.warning( f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" " use it for predictions and inference." ) else: logger.warning( f"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n" "If your task is similar to the task the model of the checkpoint was trained on, " f"you can already use {pt_model.__class__.__name__} for predictions without further training." ) return pt_model
233zzh/TitanDataOperationSystem
7,221
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/percentiles/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Percentiles</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.fillbetween.js"></script> <script type="text/javascript"> $(function() { var males = {"15%": [[2, 88.0], [3, 93.3], [4, 102.0], [5, 108.5], [6, 115.7], [7, 115.6], [8, 124.6], [9, 130.3], [10, 134.3], [11, 141.4], [12, 146.5], [13, 151.7], [14, 159.9], [15, 165.4], [16, 167.8], [17, 168.7], [18, 169.5], [19, 168.0]], "90%": [[2, 96.8], [3, 105.2], [4, 113.9], [5, 120.8], [6, 127.0], [7, 133.1], [8, 139.1], [9, 143.9], [10, 151.3], [11, 161.1], [12, 164.8], [13, 173.5], [14, 179.0], [15, 182.0], [16, 186.9], [17, 185.2], [18, 186.3], [19, 186.6]], "25%": [[2, 89.2], [3, 94.9], [4, 104.4], [5, 111.4], [6, 117.5], [7, 120.2], [8, 127.1], [9, 132.9], [10, 136.8], [11, 144.4], [12, 149.5], [13, 154.1], [14, 163.1], [15, 169.2], [16, 170.4], [17, 171.2], [18, 172.4], [19, 170.8]], "10%": [[2, 86.9], [3, 92.6], [4, 99.9], [5, 107.0], [6, 114.0], [7, 113.5], [8, 123.6], [9, 129.2], [10, 133.0], [11, 140.6], [12, 145.2], [13, 149.7], [14, 158.4], [15, 163.5], [16, 166.9], [17, 167.5], [18, 167.1], [19, 165.3]], "mean": [[2, 91.9], [3, 98.5], [4, 107.1], [5, 114.4], [6, 120.6], [7, 124.7], [8, 131.1], [9, 136.8], [10, 142.3], [11, 150.0], [12, 154.7], [13, 161.9], [14, 168.7], [15, 173.6], [16, 175.9], [17, 176.6], [18, 176.8], [19, 176.7]], "75%": [[2, 94.5], [3, 102.1], [4, 110.8], [5, 117.9], [6, 124.0], [7, 129.3], [8, 134.6], [9, 141.4], [10, 147.0], [11, 156.1], [12, 160.3], [13, 168.3], [14, 174.7], [15, 178.0], [16, 180.2], [17, 181.7], [18, 181.3], [19, 182.5]], "85%": [[2, 96.2], [3, 103.8], [4, 111.8], [5, 119.6], [6, 125.6], [7, 131.5], [8, 138.0], [9, 143.3], [10, 149.3], [11, 159.8], [12, 162.5], [13, 171.3], [14, 177.5], [15, 180.2], [16, 183.8], [17, 183.4], [18, 183.5], [19, 185.5]], "50%": [[2, 91.9], [3, 98.2], [4, 106.8], [5, 114.6], [6, 120.8], [7, 125.2], [8, 130.3], [9, 137.1], [10, 141.5], [11, 149.4], [12, 153.9], [13, 162.2], [14, 169.0], [15, 174.8], [16, 176.0], [17, 176.8], [18, 176.4], [19, 177.4]]}; var females = {"15%": [[2, 84.8], [3, 93.7], [4, 100.6], [5, 105.8], [6, 113.3], [7, 119.3], [8, 124.3], [9, 131.4], [10, 136.9], [11, 143.8], [12, 149.4], [13, 151.2], [14, 152.3], [15, 155.9], [16, 154.7], [17, 157.0], [18, 156.1], [19, 155.4]], "90%": [[2, 95.6], [3, 104.1], [4, 111.9], [5, 119.6], [6, 127.6], [7, 133.1], [8, 138.7], [9, 147.1], [10, 152.8], [11, 161.3], [12, 166.6], [13, 167.9], [14, 169.3], [15, 170.1], [16, 172.4], [17, 169.2], [18, 171.1], [19, 172.4]], "25%": [[2, 87.2], [3, 95.9], [4, 101.9], [5, 107.4], [6, 114.8], [7, 121.4], [8, 126.8], [9, 133.4], [10, 138.6], [11, 146.2], [12, 152.0], [13, 153.8], [14, 155.7], [15, 158.4], [16, 157.0], [17, 158.5], [18, 158.4], [19, 158.1]], "10%": [[2, 84.0], [3, 91.9], [4, 99.2], [5, 105.2], [6, 112.7], [7, 118.0], [8, 123.3], [9, 130.2], [10, 135.0], [11, 141.1], [12, 148.3], [13, 150.0], [14, 150.7], [15, 154.3], [16, 153.6], [17, 155.6], [18, 154.7], [19, 153.1]], "mean": [[2, 90.2], [3, 98.3], [4, 105.2], [5, 112.2], [6, 119.0], [7, 125.8], [8, 131.3], [9, 138.6], [10, 144.2], [11, 151.3], [12, 156.7], [13, 158.6], [14, 160.5], [15, 162.1], [16, 162.9], [17, 162.2], [18, 163.0], [19, 163.1]], "75%": [[2, 93.2], [3, 101.5], [4, 107.9], [5, 116.6], [6, 122.8], [7, 129.3], [8, 135.2], [9, 143.7], [10, 148.7], [11, 156.9], [12, 160.8], [13, 163.0], [14, 165.0], [15, 165.8], [16, 168.7], [17, 166.2], [18, 167.6], [19, 168.0]], "85%": [[2, 94.5], [3, 102.8], [4, 110.4], [5, 119.0], [6, 125.7], [7, 131.5], [8, 137.9], [9, 146.0], [10, 151.3], [11, 159.9], [12, 164.0], [13, 166.5], [14, 167.5], [15, 168.5], [16, 171.5], [17, 168.0], [18, 169.8], [19, 170.3]], "50%": [[2, 90.2], [3, 98.1], [4, 105.2], [5, 111.7], [6, 118.2], [7, 125.6], [8, 130.5], [9, 138.3], [10, 143.7], [11, 151.4], [12, 156.7], [13, 157.7], [14, 161.0], [15, 162.0], [16, 162.8], [17, 162.2], [18, 162.8], [19, 163.3]]}; var dataset = [ { label: "Female mean", data: females["mean"], lines: { show: true }, color: "rgb(255,50,50)" }, { id: "f15%", data: females["15%"], lines: { show: true, lineWidth: 0, fill: false }, color: "rgb(255,50,50)" }, { id: "f25%", data: females["25%"], lines: { show: true, lineWidth: 0, fill: 0.2 }, color: "rgb(255,50,50)", fillBetween: "f15%" }, { id: "f50%", data: females["50%"], lines: { show: true, lineWidth: 0.5, fill: 0.4, shadowSize: 0 }, color: "rgb(255,50,50)", fillBetween: "f25%" }, { id: "f75%", data: females["75%"], lines: { show: true, lineWidth: 0, fill: 0.4 }, color: "rgb(255,50,50)", fillBetween: "f50%" }, { id: "f85%", data: females["85%"], lines: { show: true, lineWidth: 0, fill: 0.2 }, color: "rgb(255,50,50)", fillBetween: "f75%" }, { label: "Male mean", data: males["mean"], lines: { show: true }, color: "rgb(50,50,255)" }, { id: "m15%", data: males["15%"], lines: { show: true, lineWidth: 0, fill: false }, color: "rgb(50,50,255)" }, { id: "m25%", data: males["25%"], lines: { show: true, lineWidth: 0, fill: 0.2 }, color: "rgb(50,50,255)", fillBetween: "m15%" }, { id: "m50%", data: males["50%"], lines: { show: true, lineWidth: 0.5, fill: 0.4, shadowSize: 0 }, color: "rgb(50,50,255)", fillBetween: "m25%" }, { id: "m75%", data: males["75%"], lines: { show: true, lineWidth: 0, fill: 0.4 }, color: "rgb(50,50,255)", fillBetween: "m50%" }, { id: "m85%", data: males["85%"], lines: { show: true, lineWidth: 0, fill: 0.2 }, color: "rgb(50,50,255)", fillBetween: "m75%" } ]; $.plot($("#placeholder"), dataset, { xaxis: { tickDecimals: 0 }, yaxis: { tickFormatter: function (v) { return v + " cm"; } }, legend: { position: "se" } }); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Percentiles</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder"></div> </div> <p>Height in centimeters of individuals from the US (2003-2006) as function of age in years (source: <a href="http://www.cdc.gov/nchs/data/nhsr/nhsr010.pdf">CDC</a>). The 15%-85%, 25%-75% and 50% percentiles are indicated.</p> <p>For each point of a filled curve, you can specify an arbitrary bottom. As this example illustrates, this can be useful for plotting percentiles. If you have the data sets available without appropriate fill bottoms, you can use the fillbetween plugin to compute the data point bottoms automatically.</p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
274056675/springboot-openai-chatgpt
666,528
mng_web/src/research/util/city.js
import { setTreeDataUtil } from '@/research/util/myUtil' let cityAllData = [ { "area_name": "北京", "pinyin": "Beijing", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1, "area_id": 110000 }, { "area_name": "北京市", "pinyin": "Beijing", "level": 2, "area_code": 10, "post_code": 100000, "pid": 110000, "id": 2, "area_id": 110100 }, { "area_name": "东城区", "pinyin": "Dongcheng", "level": 3, "area_code": 10, "post_code": 100010, "pid": 110100, "id": 3, "area_id": 110101 }, { "area_name": "西城区", "pinyin": "Xicheng", "level": 3, "area_code": 10, "post_code": 100032, "pid": 110100, "id": 4, "area_id": 110102 }, { "area_name": "朝阳区", "pinyin": "Chaoyang", "level": 3, "area_code": 10, "post_code": 100020, "pid": 110100, "id": 5, "area_id": 110105 }, { "area_name": "丰台区", "pinyin": "Fengtai", "level": 3, "area_code": 10, "post_code": 100071, "pid": 110100, "id": 6, "area_id": 110106 }, { "area_name": "石景山区", "pinyin": "Shijingshan", "level": 3, "area_code": 10, "post_code": 100043, "pid": 110100, "id": 7, "area_id": 110107 }, { "area_name": "海淀区", "pinyin": "Haidian", "level": 3, "area_code": 10, "post_code": 100089, "pid": 110100, "id": 8, "area_id": 110108 }, { "area_name": "门头沟区", "pinyin": "Mentougou", "level": 3, "area_code": 10, "post_code": 102300, "pid": 110100, "id": 9, "area_id": 110109 }, { "area_name": "房山区", "pinyin": "Fangshan", "level": 3, "area_code": 10, "post_code": 102488, "pid": 110100, "id": 10, "area_id": 110111 }, { "area_name": "通州区", "pinyin": "Tongzhou", "level": 3, "area_code": 10, "post_code": 101149, "pid": 110100, "id": 11, "area_id": 110112 }, { "area_name": "顺义区", "pinyin": "Shunyi", "level": 3, "area_code": 10, "post_code": 101300, "pid": 110100, "id": 12, "area_id": 110113 }, { "area_name": "昌平区", "pinyin": "Changping", "level": 3, "area_code": 10, "post_code": 102200, "pid": 110100, "id": 13, "area_id": 110114 }, { "area_name": "大兴区", "pinyin": "Daxing", "level": 3, "area_code": 10, "post_code": 102600, "pid": 110100, "id": 14, "area_id": 110115 }, { "area_name": "怀柔区", "pinyin": "Huairou", "level": 3, "area_code": 10, "post_code": 101400, "pid": 110100, "id": 15, "area_id": 110116 }, { "area_name": "平谷区", "pinyin": "Pinggu", "level": 3, "area_code": 10, "post_code": 101200, "pid": 110100, "id": 16, "area_id": 110117 }, { "area_name": "密云县", "pinyin": "Miyun", "level": 3, "area_code": 10, "post_code": 101500, "pid": 110100, "id": 17, "area_id": 110228 }, { "area_name": "延庆县", "pinyin": "Yanqing", "level": 3, "area_code": 10, "post_code": 102100, "pid": 110100, "id": 18, "area_id": 110229 }, { "area_name": "天津", "pinyin": "Tianjin", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 19, "area_id": 120000 }, { "area_name": "天津市", "pinyin": "Tianjin", "level": 2, "area_code": 22, "post_code": 300000, "pid": 120000, "id": 20, "area_id": 120100 }, { "area_name": "和平区", "pinyin": "Heping", "level": 3, "area_code": 22, "post_code": 300041, "pid": 120100, "id": 21, "area_id": 120101 }, { "area_name": "河东区", "pinyin": "Hedong", "level": 3, "area_code": 22, "post_code": 300171, "pid": 120100, "id": 22, "area_id": 120102 }, { "area_name": "河西区", "pinyin": "Hexi", "level": 3, "area_code": 22, "post_code": 300202, "pid": 120100, "id": 23, "area_id": 120103 }, { "area_name": "南开区", "pinyin": "Nankai", "level": 3, "area_code": 22, "post_code": 300110, "pid": 120100, "id": 24, "area_id": 120104 }, { "area_name": "河北区", "pinyin": "Hebei", "level": 3, "area_code": 22, "post_code": 300143, "pid": 120100, "id": 25, "area_id": 120105 }, { "area_name": "红桥区", "pinyin": "Hongqiao", "level": 3, "area_code": 22, "post_code": 300131, "pid": 120100, "id": 26, "area_id": 120106 }, { "area_name": "东丽区", "pinyin": "Dongli", "level": 3, "area_code": 22, "post_code": 300300, "pid": 120100, "id": 27, "area_id": 120110 }, { "area_name": "西青区", "pinyin": "Xiqing", "level": 3, "area_code": 22, "post_code": 300380, "pid": 120100, "id": 28, "area_id": 120111 }, { "area_name": "津南区", "pinyin": "Jinnan", "level": 3, "area_code": 22, "post_code": 300350, "pid": 120100, "id": 29, "area_id": 120112 }, { "area_name": "北辰区", "pinyin": "Beichen", "level": 3, "area_code": 22, "post_code": 300400, "pid": 120100, "id": 30, "area_id": 120113 }, { "area_name": "武清区", "pinyin": "Wuqing", "level": 3, "area_code": 22, "post_code": 301700, "pid": 120100, "id": 31, "area_id": 120114 }, { "area_name": "宝坻区", "pinyin": "Baodi", "level": 3, "area_code": 22, "post_code": 301800, "pid": 120100, "id": 32, "area_id": 120115 }, { "area_name": "滨海新区", "pinyin": "Binhaixinqu", "level": 3, "area_code": 22, "post_code": 300451, "pid": 120100, "id": 33, "area_id": 120116 }, { "area_name": "宁河县", "pinyin": "Ninghe", "level": 3, "area_code": 22, "post_code": 301500, "pid": 120100, "id": 34, "area_id": 120221 }, { "area_name": "静海县", "pinyin": "Jinghai", "level": 3, "area_code": 22, "post_code": 301600, "pid": 120100, "id": 35, "area_id": 120223 }, { "area_name": "蓟县", "pinyin": "Jixian", "level": 3, "area_code": 22, "post_code": 301900, "pid": 120100, "id": 36, "area_id": 120225 }, { "area_name": "河北省", "pinyin": "Hebei", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 37, "area_id": 130000 }, { "area_name": "石家庄市", "pinyin": "Shijiazhuang", "level": 2, "area_code": 311, "post_code": 50011, "pid": 130000, "id": 38, "area_id": 130100 }, { "area_name": "长安区", "pinyin": "Chang'an", "level": 3, "area_code": 311, "post_code": 50011, "pid": 130100, "id": 39, "area_id": 130102 }, { "area_name": "桥西区", "pinyin": "Qiaoxi", "level": 3, "area_code": 311, "post_code": 50091, "pid": 130100, "id": 40, "area_id": 130104 }, { "area_name": "新华区", "pinyin": "Xinhua", "level": 3, "area_code": 311, "post_code": 50051, "pid": 130100, "id": 41, "area_id": 130105 }, { "area_name": "井陉矿区", "pinyin": "Jingxingkuangqu", "level": 3, "area_code": 311, "post_code": 50100, "pid": 130100, "id": 42, "area_id": 130107 }, { "area_name": "裕华区", "pinyin": "Yuhua", "level": 3, "area_code": 311, "post_code": 50031, "pid": 130100, "id": 43, "area_id": 130108 }, { "area_name": "藁城区", "pinyin": "Gaocheng", "level": 3, "area_code": 311, "post_code": 52160, "pid": 130100, "id": 44, "area_id": 130109 }, { "area_name": "鹿泉区", "pinyin": "Luquan", "level": 3, "area_code": 311, "post_code": 50200, "pid": 130100, "id": 45, "area_id": 130110 }, { "area_name": "栾城区", "pinyin": "Luancheng", "level": 3, "area_code": 311, "post_code": 51430, "pid": 130100, "id": 46, "area_id": 130111 }, { "area_name": "井陉县", "pinyin": "Jingxing", "level": 3, "area_code": 311, "post_code": 50300, "pid": 130100, "id": 47, "area_id": 130121 }, { "area_name": "正定县", "pinyin": "Zhengding", "level": 3, "area_code": 311, "post_code": 50800, "pid": 130100, "id": 48, "area_id": 130123 }, { "area_name": "行唐县", "pinyin": "Xingtang", "level": 3, "area_code": 311, "post_code": 50600, "pid": 130100, "id": 49, "area_id": 130125 }, { "area_name": "灵寿县", "pinyin": "Lingshou", "level": 3, "area_code": 311, "post_code": 50500, "pid": 130100, "id": 50, "area_id": 130126 }, { "area_name": "高邑县", "pinyin": "Gaoyi", "level": 3, "area_code": 311, "post_code": 51330, "pid": 130100, "id": 51, "area_id": 130127 }, { "area_name": "深泽县", "pinyin": "Shenze", "level": 3, "area_code": 311, "post_code": 52560, "pid": 130100, "id": 52, "area_id": 130128 }, { "area_name": "赞皇县", "pinyin": "Zanhuang", "level": 3, "area_code": 311, "post_code": 51230, "pid": 130100, "id": 53, "area_id": 130129 }, { "area_name": "无极县", "pinyin": "Wuji", "level": 3, "area_code": 311, "post_code": 52460, "pid": 130100, "id": 54, "area_id": 130130 }, { "area_name": "平山县", "pinyin": "Pingshan", "level": 3, "area_code": 311, "post_code": 50400, "pid": 130100, "id": 55, "area_id": 130131 }, { "area_name": "元氏县", "pinyin": "Yuanshi", "level": 3, "area_code": 311, "post_code": 51130, "pid": 130100, "id": 56, "area_id": 130132 }, { "area_name": "赵县", "pinyin": "Zhaoxian", "level": 3, "area_code": 311, "post_code": 51530, "pid": 130100, "id": 57, "area_id": 130133 }, { "area_name": "辛集市", "pinyin": "Xinji", "level": 3, "area_code": 311, "post_code": 52360, "pid": 130100, "id": 58, "area_id": 130181 }, { "area_name": "晋州市", "pinyin": "Jinzhou", "level": 3, "area_code": 311, "post_code": 52260, "pid": 130100, "id": 59, "area_id": 130183 }, { "area_name": "新乐市", "pinyin": "Xinle", "level": 3, "area_code": 311, "post_code": 50700, "pid": 130100, "id": 60, "area_id": 130184 }, { "area_name": "唐山市", "pinyin": "Tangshan", "level": 2, "area_code": 315, "post_code": 63000, "pid": 130000, "id": 61, "area_id": 130200 }, { "area_name": "路南区", "pinyin": "Lunan", "level": 3, "area_code": 315, "post_code": 63000, "pid": 130200, "id": 62, "area_id": 130202 }, { "area_name": "路北区", "pinyin": "Lubei", "level": 3, "area_code": 315, "post_code": 63000, "pid": 130200, "id": 63, "area_id": 130203 }, { "area_name": "古冶区", "pinyin": "Guye", "level": 3, "area_code": 315, "post_code": 63100, "pid": 130200, "id": 64, "area_id": 130204 }, { "area_name": "开平区", "pinyin": "Kaiping", "level": 3, "area_code": 315, "post_code": 63021, "pid": 130200, "id": 65, "area_id": 130205 }, { "area_name": "丰南区", "pinyin": "Fengnan", "level": 3, "area_code": 315, "post_code": 63300, "pid": 130200, "id": 66, "area_id": 130207 }, { "area_name": "丰润区", "pinyin": "Fengrun", "level": 3, "area_code": 315, "post_code": 64000, "pid": 130200, "id": 67, "area_id": 130208 }, { "area_name": "曹妃甸区", "pinyin": "Caofeidian", "level": 3, "area_code": 315, "post_code": 63200, "pid": 130200, "id": 68, "area_id": 130209 }, { "area_name": "滦县", "pinyin": "Luanxian", "level": 3, "area_code": 315, "post_code": 63700, "pid": 130200, "id": 69, "area_id": 130223 }, { "area_name": "滦南县", "pinyin": "Luannan", "level": 3, "area_code": 315, "post_code": 63500, "pid": 130200, "id": 70, "area_id": 130224 }, { "area_name": "乐亭县", "pinyin": "Laoting", "level": 3, "area_code": 315, "post_code": 63600, "pid": 130200, "id": 71, "area_id": 130225 }, { "area_name": "迁西县", "pinyin": "Qianxi", "level": 3, "area_code": 315, "post_code": 64300, "pid": 130200, "id": 72, "area_id": 130227 }, { "area_name": "玉田县", "pinyin": "Yutian", "level": 3, "area_code": 315, "post_code": 64100, "pid": 130200, "id": 73, "area_id": 130229 }, { "area_name": "遵化市", "pinyin": "Zunhua", "level": 3, "area_code": 315, "post_code": 64200, "pid": 130200, "id": 74, "area_id": 130281 }, { "area_name": "迁安市", "pinyin": "Qian'an", "level": 3, "area_code": 315, "post_code": 64400, "pid": 130200, "id": 75, "area_id": 130283 }, { "area_name": "秦皇岛市", "pinyin": "Qinhuangdao", "level": 2, "area_code": 335, "post_code": 66000, "pid": 130000, "id": 76, "area_id": 130300 }, { "area_name": "海港区", "pinyin": "Haigang", "level": 3, "area_code": 335, "post_code": 66000, "pid": 130300, "id": 77, "area_id": 130302 }, { "area_name": "山海关区", "pinyin": "Shanhaiguan", "level": 3, "area_code": 335, "post_code": 66200, "pid": 130300, "id": 78, "area_id": 130303 }, { "area_name": "北戴河区", "pinyin": "Beidaihe", "level": 3, "area_code": 335, "post_code": 66100, "pid": 130300, "id": 79, "area_id": 130304 }, { "area_name": "青龙满族自治县", "pinyin": "Qinglong", "level": 3, "area_code": 335, "post_code": 66500, "pid": 130300, "id": 80, "area_id": 130321 }, { "area_name": "昌黎县", "pinyin": "Changli", "level": 3, "area_code": 335, "post_code": 66600, "pid": 130300, "id": 81, "area_id": 130322 }, { "area_name": "抚宁县", "pinyin": "Funing", "level": 3, "area_code": 335, "post_code": 66300, "pid": 130300, "id": 82, "area_id": 130323 }, { "area_name": "卢龙县", "pinyin": "Lulong", "level": 3, "area_code": 335, "post_code": 66400, "pid": 130300, "id": 83, "area_id": 130324 }, { "area_name": "邯郸市", "pinyin": "Handan", "level": 2, "area_code": 310, "post_code": 56002, "pid": 130000, "id": 84, "area_id": 130400 }, { "area_name": "邯山区", "pinyin": "Hanshan", "level": 3, "area_code": 310, "post_code": 56001, "pid": 130400, "id": 85, "area_id": 130402 }, { "area_name": "丛台区", "pinyin": "Congtai", "level": 3, "area_code": 310, "post_code": 56002, "pid": 130400, "id": 86, "area_id": 130403 }, { "area_name": "复兴区", "pinyin": "Fuxing", "level": 3, "area_code": 310, "post_code": 56003, "pid": 130400, "id": 87, "area_id": 130404 }, { "area_name": "峰峰矿区", "pinyin": "Fengfengkuangqu", "level": 3, "area_code": 310, "post_code": 56200, "pid": 130400, "id": 88, "area_id": 130406 }, { "area_name": "邯郸县", "pinyin": "Handan", "level": 3, "area_code": 310, "post_code": 56101, "pid": 130400, "id": 89, "area_id": 130421 }, { "area_name": "临漳县", "pinyin": "Linzhang", "level": 3, "area_code": 310, "post_code": 56600, "pid": 130400, "id": 90, "area_id": 130423 }, { "area_name": "成安县", "pinyin": "Cheng'an", "level": 3, "area_code": 310, "post_code": 56700, "pid": 130400, "id": 91, "area_id": 130424 }, { "area_name": "大名县", "pinyin": "Daming", "level": 3, "area_code": 310, "post_code": 56900, "pid": 130400, "id": 92, "area_id": 130425 }, { "area_name": "涉县", "pinyin": "Shexian", "level": 3, "area_code": 310, "post_code": 56400, "pid": 130400, "id": 93, "area_id": 130426 }, { "area_name": "磁县", "pinyin": "Cixian", "level": 3, "area_code": 310, "post_code": 56500, "pid": 130400, "id": 94, "area_id": 130427 }, { "area_name": "肥乡县", "pinyin": "Feixiang", "level": 3, "area_code": 310, "post_code": 57550, "pid": 130400, "id": 95, "area_id": 130428 }, { "area_name": "永年县", "pinyin": "Yongnian", "level": 3, "area_code": 310, "post_code": 57150, "pid": 130400, "id": 96, "area_id": 130429 }, { "area_name": "邱县", "pinyin": "Qiuxian", "level": 3, "area_code": 310, "post_code": 57450, "pid": 130400, "id": 97, "area_id": 130430 }, { "area_name": "鸡泽县", "pinyin": "Jize", "level": 3, "area_code": 310, "post_code": 57350, "pid": 130400, "id": 98, "area_id": 130431 }, { "area_name": "广平县", "pinyin": "Guangping", "level": 3, "area_code": 310, "post_code": 57650, "pid": 130400, "id": 99, "area_id": 130432 }, { "area_name": "馆陶县", "pinyin": "Guantao", "level": 3, "area_code": 310, "post_code": 57750, "pid": 130400, "id": 100, "area_id": 130433 }, { "area_name": "魏县", "pinyin": "Weixian", "level": 3, "area_code": 310, "post_code": 56800, "pid": 130400, "id": 101, "area_id": 130434 }, { "area_name": "曲周县", "pinyin": "Quzhou", "level": 3, "area_code": 310, "post_code": 57250, "pid": 130400, "id": 102, "area_id": 130435 }, { "area_name": "武安市", "pinyin": "Wu'an", "level": 3, "area_code": 310, "post_code": 56300, "pid": 130400, "id": 103, "area_id": 130481 }, { "area_name": "邢台市", "pinyin": "Xingtai", "level": 2, "area_code": 319, "post_code": 54001, "pid": 130000, "id": 104, "area_id": 130500 }, { "area_name": "桥东区", "pinyin": "Qiaodong", "level": 3, "area_code": 319, "post_code": 54001, "pid": 130500, "id": 105, "area_id": 130502 }, { "area_name": "桥西区", "pinyin": "Qiaoxi", "level": 3, "area_code": 319, "post_code": 54000, "pid": 130500, "id": 106, "area_id": 130503 }, { "area_name": "邢台县", "pinyin": "Xingtai", "level": 3, "area_code": 319, "post_code": 54001, "pid": 130500, "id": 107, "area_id": 130521 }, { "area_name": "临城县", "pinyin": "Lincheng", "level": 3, "area_code": 319, "post_code": 54300, "pid": 130500, "id": 108, "area_id": 130522 }, { "area_name": "内丘县", "pinyin": "Neiqiu", "level": 3, "area_code": 319, "post_code": 54200, "pid": 130500, "id": 109, "area_id": 130523 }, { "area_name": "柏乡县", "pinyin": "Baixiang", "level": 3, "area_code": 319, "post_code": 55450, "pid": 130500, "id": 110, "area_id": 130524 }, { "area_name": "隆尧县", "pinyin": "Longyao", "level": 3, "area_code": 319, "post_code": 55350, "pid": 130500, "id": 111, "area_id": 130525 }, { "area_name": "任县", "pinyin": "Renxian", "level": 3, "area_code": 319, "post_code": 55150, "pid": 130500, "id": 112, "area_id": 130526 }, { "area_name": "南和县", "pinyin": "Nanhe", "level": 3, "area_code": 319, "post_code": 54400, "pid": 130500, "id": 113, "area_id": 130527 }, { "area_name": "宁晋县", "pinyin": "Ningjin", "level": 3, "area_code": 319, "post_code": 55550, "pid": 130500, "id": 114, "area_id": 130528 }, { "area_name": "巨鹿县", "pinyin": "Julu", "level": 3, "area_code": 319, "post_code": 55250, "pid": 130500, "id": 115, "area_id": 130529 }, { "area_name": "新河县", "pinyin": "Xinhe", "level": 3, "area_code": 319, "post_code": 55650, "pid": 130500, "id": 116, "area_id": 130530 }, { "area_name": "广宗县", "pinyin": "Guangzong", "level": 3, "area_code": 319, "post_code": 54600, "pid": 130500, "id": 117, "area_id": 130531 }, { "area_name": "平乡县", "pinyin": "Pingxiang", "level": 3, "area_code": 319, "post_code": 54500, "pid": 130500, "id": 118, "area_id": 130532 }, { "area_name": "威县", "pinyin": "Weixian", "level": 3, "area_code": 319, "post_code": 54700, "pid": 130500, "id": 119, "area_id": 130533 }, { "area_name": "清河县", "pinyin": "Qinghe", "level": 3, "area_code": 319, "post_code": 54800, "pid": 130500, "id": 120, "area_id": 130534 }, { "area_name": "临西县", "pinyin": "Linxi", "level": 3, "area_code": 319, "post_code": 54900, "pid": 130500, "id": 121, "area_id": 130535 }, { "area_name": "南宫市", "pinyin": "Nangong", "level": 3, "area_code": 319, "post_code": 55750, "pid": 130500, "id": 122, "area_id": 130581 }, { "area_name": "沙河市", "pinyin": "Shahe", "level": 3, "area_code": 319, "post_code": 54100, "pid": 130500, "id": 123, "area_id": 130582 }, { "area_name": "保定市", "pinyin": "Baoding", "level": 2, "area_code": 312, "post_code": 71052, "pid": 130000, "id": 124, "area_id": 130600 }, { "area_name": "新市区", "pinyin": "Xinshi", "level": 3, "area_code": 312, "post_code": 71051, "pid": 130600, "id": 125, "area_id": 130602 }, { "area_name": "北市区", "pinyin": "Beishi", "level": 3, "area_code": 312, "post_code": 71000, "pid": 130600, "id": 126, "area_id": 130603 }, { "area_name": "南市区", "pinyin": "Nanshi", "level": 3, "area_code": 312, "post_code": 71001, "pid": 130600, "id": 127, "area_id": 130604 }, { "area_name": "满城县", "pinyin": "Mancheng", "level": 3, "area_code": 312, "post_code": 72150, "pid": 130600, "id": 128, "area_id": 130621 }, { "area_name": "清苑县", "pinyin": "Qingyuan", "level": 3, "area_code": 312, "post_code": 71100, "pid": 130600, "id": 129, "area_id": 130622 }, { "area_name": "涞水县", "pinyin": "Laishui", "level": 3, "area_code": 312, "post_code": 74100, "pid": 130600, "id": 130, "area_id": 130623 }, { "area_name": "阜平县", "pinyin": "Fuping", "level": 3, "area_code": 312, "post_code": 73200, "pid": 130600, "id": 131, "area_id": 130624 }, { "area_name": "徐水县", "pinyin": "Xushui", "level": 3, "area_code": 312, "post_code": 72550, "pid": 130600, "id": 132, "area_id": 130625 }, { "area_name": "定兴县", "pinyin": "Dingxing", "level": 3, "area_code": 312, "post_code": 72650, "pid": 130600, "id": 133, "area_id": 130626 }, { "area_name": "唐县", "pinyin": "Tangxian", "level": 3, "area_code": 312, "post_code": 72350, "pid": 130600, "id": 134, "area_id": 130627 }, { "area_name": "高阳县", "pinyin": "Gaoyang", "level": 3, "area_code": 312, "post_code": 71500, "pid": 130600, "id": 135, "area_id": 130628 }, { "area_name": "容城县", "pinyin": "Rongcheng", "level": 3, "area_code": 312, "post_code": 71700, "pid": 130600, "id": 136, "area_id": 130629 }, { "area_name": "涞源县", "pinyin": "Laiyuan", "level": 3, "area_code": 312, "post_code": 74300, "pid": 130600, "id": 137, "area_id": 130630 }, { "area_name": "望都县", "pinyin": "Wangdu", "level": 3, "area_code": 312, "post_code": 72450, "pid": 130600, "id": 138, "area_id": 130631 }, { "area_name": "安新县", "pinyin": "Anxin", "level": 3, "area_code": 312, "post_code": 71600, "pid": 130600, "id": 139, "area_id": 130632 }, { "area_name": "易县", "pinyin": "Yixian", "level": 3, "area_code": 312, "post_code": 74200, "pid": 130600, "id": 140, "area_id": 130633 }, { "area_name": "曲阳县", "pinyin": "Quyang", "level": 3, "area_code": 312, "post_code": 73100, "pid": 130600, "id": 141, "area_id": 130634 }, { "area_name": "蠡县", "pinyin": "Lixian", "level": 3, "area_code": 312, "post_code": 71400, "pid": 130600, "id": 142, "area_id": 130635 }, { "area_name": "顺平县", "pinyin": "Shunping", "level": 3, "area_code": 312, "post_code": 72250, "pid": 130600, "id": 143, "area_id": 130636 }, { "area_name": "博野县", "pinyin": "Boye", "level": 3, "area_code": 312, "post_code": 71300, "pid": 130600, "id": 144, "area_id": 130637 }, { "area_name": "雄县", "pinyin": "Xiongxian", "level": 3, "area_code": 312, "post_code": 71800, "pid": 130600, "id": 145, "area_id": 130638 }, { "area_name": "涿州市", "pinyin": "Zhuozhou", "level": 3, "area_code": 312, "post_code": 72750, "pid": 130600, "id": 146, "area_id": 130681 }, { "area_name": "定州市", "pinyin": "Dingzhou", "level": 3, "area_code": 312, "post_code": 73000, "pid": 130600, "id": 147, "area_id": 130682 }, { "area_name": "安国市", "pinyin": "Anguo", "level": 3, "area_code": 312, "post_code": 71200, "pid": 130600, "id": 148, "area_id": 130683 }, { "area_name": "高碑店市", "pinyin": "Gaobeidian", "level": 3, "area_code": 312, "post_code": 74000, "pid": 130600, "id": 149, "area_id": 130684 }, { "area_name": "张家口市", "pinyin": "Zhangjiakou", "level": 2, "area_code": 313, "post_code": 75000, "pid": 130000, "id": 150, "area_id": 130700 }, { "area_name": "桥东区", "pinyin": "Qiaodong", "level": 3, "area_code": 313, "post_code": 75000, "pid": 130700, "id": 151, "area_id": 130702 }, { "area_name": "桥西区", "pinyin": "Qiaoxi", "level": 3, "area_code": 313, "post_code": 75061, "pid": 130700, "id": 152, "area_id": 130703 }, { "area_name": "宣化区", "pinyin": "Xuanhua", "level": 3, "area_code": 313, "post_code": 75100, "pid": 130700, "id": 153, "area_id": 130705 }, { "area_name": "下花园区", "pinyin": "Xiahuayuan", "level": 3, "area_code": 313, "post_code": 75300, "pid": 130700, "id": 154, "area_id": 130706 }, { "area_name": "宣化县", "pinyin": "Xuanhua", "level": 3, "area_code": 313, "post_code": 75100, "pid": 130700, "id": 155, "area_id": 130721 }, { "area_name": "张北县", "pinyin": "Zhangbei", "level": 3, "area_code": 313, "post_code": 76450, "pid": 130700, "id": 156, "area_id": 130722 }, { "area_name": "康保县", "pinyin": "Kangbao", "level": 3, "area_code": 313, "post_code": 76650, "pid": 130700, "id": 157, "area_id": 130723 }, { "area_name": "沽源县", "pinyin": "Guyuan", "level": 3, "area_code": 313, "post_code": 76550, "pid": 130700, "id": 158, "area_id": 130724 }, { "area_name": "尚义县", "pinyin": "Shangyi", "level": 3, "area_code": 313, "post_code": 76750, "pid": 130700, "id": 159, "area_id": 130725 }, { "area_name": "蔚县", "pinyin": "Yuxian", "level": 3, "area_code": 313, "post_code": 75700, "pid": 130700, "id": 160, "area_id": 130726 }, { "area_name": "阳原县", "pinyin": "Yangyuan", "level": 3, "area_code": 313, "post_code": 75800, "pid": 130700, "id": 161, "area_id": 130727 }, { "area_name": "怀安县", "pinyin": "Huai'an", "level": 3, "area_code": 313, "post_code": 76150, "pid": 130700, "id": 162, "area_id": 130728 }, { "area_name": "万全县", "pinyin": "Wanquan", "level": 3, "area_code": 313, "post_code": 76250, "pid": 130700, "id": 163, "area_id": 130729 }, { "area_name": "怀来县", "pinyin": "Huailai", "level": 3, "area_code": 313, "post_code": 75400, "pid": 130700, "id": 164, "area_id": 130730 }, { "area_name": "涿鹿县", "pinyin": "Zhuolu", "level": 3, "area_code": 313, "post_code": 75600, "pid": 130700, "id": 165, "area_id": 130731 }, { "area_name": "赤城县", "pinyin": "Chicheng", "level": 3, "area_code": 313, "post_code": 75500, "pid": 130700, "id": 166, "area_id": 130732 }, { "area_name": "崇礼县", "pinyin": "Chongli", "level": 3, "area_code": 313, "post_code": 76350, "pid": 130700, "id": 167, "area_id": 130733 }, { "area_name": "承德市", "pinyin": "Chengde", "level": 2, "area_code": 314, "post_code": 67000, "pid": 130000, "id": 168, "area_id": 130800 }, { "area_name": "双桥区", "pinyin": "Shuangqiao", "level": 3, "area_code": 314, "post_code": 67000, "pid": 130800, "id": 169, "area_id": 130802 }, { "area_name": "双滦区", "pinyin": "Shuangluan", "level": 3, "area_code": 314, "post_code": 67001, "pid": 130800, "id": 170, "area_id": 130803 }, { "area_name": "鹰手营子矿区", "pinyin": "Yingshouyingzikuangqu", "level": 3, "area_code": 314, "post_code": 67200, "pid": 130800, "id": 171, "area_id": 130804 }, { "area_name": "承德县", "pinyin": "Chengde", "level": 3, "area_code": 314, "post_code": 67400, "pid": 130800, "id": 172, "area_id": 130821 }, { "area_name": "兴隆县", "pinyin": "Xinglong", "level": 3, "area_code": 314, "post_code": 67300, "pid": 130800, "id": 173, "area_id": 130822 }, { "area_name": "平泉县", "pinyin": "Pingquan", "level": 3, "area_code": 314, "post_code": 67500, "pid": 130800, "id": 174, "area_id": 130823 }, { "area_name": "滦平县", "pinyin": "Luanping", "level": 3, "area_code": 314, "post_code": 68250, "pid": 130800, "id": 175, "area_id": 130824 }, { "area_name": "隆化县", "pinyin": "Longhua", "level": 3, "area_code": 314, "post_code": 68150, "pid": 130800, "id": 176, "area_id": 130825 }, { "area_name": "丰宁满族自治县", "pinyin": "Fengning", "level": 3, "area_code": 314, "post_code": 68350, "pid": 130800, "id": 177, "area_id": 130826 }, { "area_name": "宽城满族自治县", "pinyin": "Kuancheng", "level": 3, "area_code": 314, "post_code": 67600, "pid": 130800, "id": 178, "area_id": 130827 }, { "area_name": "围场满族蒙古族自治县", "pinyin": "Weichang", "level": 3, "area_code": 314, "post_code": 68450, "pid": 130800, "id": 179, "area_id": 130828 }, { "area_name": "沧州市", "pinyin": "Cangzhou", "level": 2, "area_code": 317, "post_code": 61001, "pid": 130000, "id": 180, "area_id": 130900 }, { "area_name": "新华区", "pinyin": "Xinhua", "level": 3, "area_code": 317, "post_code": 61000, "pid": 130900, "id": 181, "area_id": 130902 }, { "area_name": "运河区", "pinyin": "Yunhe", "level": 3, "area_code": 317, "post_code": 61001, "pid": 130900, "id": 182, "area_id": 130903 }, { "area_name": "沧县", "pinyin": "Cangxian", "level": 3, "area_code": 317, "post_code": 61000, "pid": 130900, "id": 183, "area_id": 130921 }, { "area_name": "青县", "pinyin": "Qingxian", "level": 3, "area_code": 317, "post_code": 62650, "pid": 130900, "id": 184, "area_id": 130922 }, { "area_name": "东光县", "pinyin": "Dongguang", "level": 3, "area_code": 317, "post_code": 61600, "pid": 130900, "id": 185, "area_id": 130923 }, { "area_name": "海兴县", "pinyin": "Haixing", "level": 3, "area_code": 317, "post_code": 61200, "pid": 130900, "id": 186, "area_id": 130924 }, { "area_name": "盐山县", "pinyin": "Yanshan", "level": 3, "area_code": 317, "post_code": 61300, "pid": 130900, "id": 187, "area_id": 130925 }, { "area_name": "肃宁县", "pinyin": "Suning", "level": 3, "area_code": 317, "post_code": 62350, "pid": 130900, "id": 188, "area_id": 130926 }, { "area_name": "南皮县", "pinyin": "Nanpi", "level": 3, "area_code": 317, "post_code": 61500, "pid": 130900, "id": 189, "area_id": 130927 }, { "area_name": "吴桥县", "pinyin": "Wuqiao", "level": 3, "area_code": 317, "post_code": 61800, "pid": 130900, "id": 190, "area_id": 130928 }, { "area_name": "献县", "pinyin": "Xianxian", "level": 3, "area_code": 317, "post_code": 62250, "pid": 130900, "id": 191, "area_id": 130929 }, { "area_name": "孟村回族自治县", "pinyin": "Mengcun", "level": 3, "area_code": 317, "post_code": 61400, "pid": 130900, "id": 192, "area_id": 130930 }, { "area_name": "泊头市", "pinyin": "Botou", "level": 3, "area_code": 317, "post_code": 62150, "pid": 130900, "id": 193, "area_id": 130981 }, { "area_name": "任丘市", "pinyin": "Renqiu", "level": 3, "area_code": 317, "post_code": 62550, "pid": 130900, "id": 194, "area_id": 130982 }, { "area_name": "黄骅市", "pinyin": "Huanghua", "level": 3, "area_code": 317, "post_code": 61100, "pid": 130900, "id": 195, "area_id": 130983 }, { "area_name": "河间市", "pinyin": "Hejian", "level": 3, "area_code": 317, "post_code": 62450, "pid": 130900, "id": 196, "area_id": 130984 }, { "area_name": "廊坊市", "pinyin": "Langfang", "level": 2, "area_code": 316, "post_code": 65000, "pid": 130000, "id": 197, "area_id": 131000 }, { "area_name": "安次区", "pinyin": "Anci", "level": 3, "area_code": 316, "post_code": 65000, "pid": 131000, "id": 198, "area_id": 131002 }, { "area_name": "广阳区", "pinyin": "Guangyang", "level": 3, "area_code": 316, "post_code": 65000, "pid": 131000, "id": 199, "area_id": 131003 }, { "area_name": "固安县", "pinyin": "Gu'an", "level": 3, "area_code": 316, "post_code": 65500, "pid": 131000, "id": 200, "area_id": 131022 }, { "area_name": "永清县", "pinyin": "Yongqing", "level": 3, "area_code": 316, "post_code": 65600, "pid": 131000, "id": 201, "area_id": 131023 }, { "area_name": "香河县", "pinyin": "Xianghe", "level": 3, "area_code": 316, "post_code": 65400, "pid": 131000, "id": 202, "area_id": 131024 }, { "area_name": "大城县", "pinyin": "Daicheng", "level": 3, "area_code": 316, "post_code": 65900, "pid": 131000, "id": 203, "area_id": 131025 }, { "area_name": "文安县", "pinyin": "Wen'an", "level": 3, "area_code": 316, "post_code": 65800, "pid": 131000, "id": 204, "area_id": 131026 }, { "area_name": "大厂回族自治县", "pinyin": "Dachang", "level": 3, "area_code": 316, "post_code": 65300, "pid": 131000, "id": 205, "area_id": 131028 }, { "area_name": "霸州市", "pinyin": "Bazhou", "level": 3, "area_code": 316, "post_code": 65700, "pid": 131000, "id": 206, "area_id": 131081 }, { "area_name": "三河市", "pinyin": "Sanhe", "level": 3, "area_code": 316, "post_code": 65200, "pid": 131000, "id": 207, "area_id": 131082 }, { "area_name": "衡水市", "pinyin": "Hengshui", "level": 2, "area_code": 318, "post_code": 53000, "pid": 130000, "id": 208, "area_id": 131100 }, { "area_name": "桃城区", "pinyin": "Taocheng", "level": 3, "area_code": 318, "post_code": 53000, "pid": 131100, "id": 209, "area_id": 131102 }, { "area_name": "枣强县", "pinyin": "Zaoqiang", "level": 3, "area_code": 318, "post_code": 53100, "pid": 131100, "id": 210, "area_id": 131121 }, { "area_name": "武邑县", "pinyin": "Wuyi", "level": 3, "area_code": 318, "post_code": 53400, "pid": 131100, "id": 211, "area_id": 131122 }, { "area_name": "武强县", "pinyin": "Wuqiang", "level": 3, "area_code": 318, "post_code": 53300, "pid": 131100, "id": 212, "area_id": 131123 }, { "area_name": "饶阳县", "pinyin": "Raoyang", "level": 3, "area_code": 318, "post_code": 53900, "pid": 131100, "id": 213, "area_id": 131124 }, { "area_name": "安平县", "pinyin": "Anping", "level": 3, "area_code": 318, "post_code": 53600, "pid": 131100, "id": 214, "area_id": 131125 }, { "area_name": "故城县", "pinyin": "Gucheng", "level": 3, "area_code": 318, "post_code": 53800, "pid": 131100, "id": 215, "area_id": 131126 }, { "area_name": "景县", "pinyin": "Jingxian", "level": 3, "area_code": 318, "post_code": 53500, "pid": 131100, "id": 216, "area_id": 131127 }, { "area_name": "阜城县", "pinyin": "Fucheng", "level": 3, "area_code": 318, "post_code": 53700, "pid": 131100, "id": 217, "area_id": 131128 }, { "area_name": "冀州市", "pinyin": "Jizhou", "level": 3, "area_code": 318, "post_code": 53200, "pid": 131100, "id": 218, "area_id": 131181 }, { "area_name": "深州市", "pinyin": "Shenzhou", "level": 3, "area_code": 318, "post_code": 53800, "pid": 131100, "id": 219, "area_id": 131182 }, { "area_name": "山西省", "pinyin": "Shanxi", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 220, "area_id": 140000 }, { "area_name": "太原市", "pinyin": "Taiyuan", "level": 2, "area_code": 351, "post_code": 30082, "pid": 140000, "id": 221, "area_id": 140100 }, { "area_name": "小店区", "pinyin": "Xiaodian", "level": 3, "area_code": 351, "post_code": 30032, "pid": 140100, "id": 222, "area_id": 140105 }, { "area_name": "迎泽区", "pinyin": "Yingze", "level": 3, "area_code": 351, "post_code": 30002, "pid": 140100, "id": 223, "area_id": 140106 }, { "area_name": "杏花岭区", "pinyin": "Xinghualing", "level": 3, "area_code": 351, "post_code": 30009, "pid": 140100, "id": 224, "area_id": 140107 }, { "area_name": "尖草坪区", "pinyin": "Jiancaoping", "level": 3, "area_code": 351, "post_code": 30023, "pid": 140100, "id": 225, "area_id": 140108 }, { "area_name": "万柏林区", "pinyin": "Wanbailin", "level": 3, "area_code": 351, "post_code": 30024, "pid": 140100, "id": 226, "area_id": 140109 }, { "area_name": "晋源区", "pinyin": "Jinyuan", "level": 3, "area_code": 351, "post_code": 30025, "pid": 140100, "id": 227, "area_id": 140110 }, { "area_name": "清徐县", "pinyin": "Qingxu", "level": 3, "area_code": 351, "post_code": 30400, "pid": 140100, "id": 228, "area_id": 140121 }, { "area_name": "阳曲县", "pinyin": "Yangqu", "level": 3, "area_code": 351, "post_code": 30100, "pid": 140100, "id": 229, "area_id": 140122 }, { "area_name": "娄烦县", "pinyin": "Loufan", "level": 3, "area_code": 351, "post_code": 30300, "pid": 140100, "id": 230, "area_id": 140123 }, { "area_name": "古交市", "pinyin": "Gujiao", "level": 3, "area_code": 351, "post_code": 30200, "pid": 140100, "id": 231, "area_id": 140181 }, { "area_name": "大同市", "pinyin": "Datong", "level": 2, "area_code": 352, "post_code": 37008, "pid": 140000, "id": 232, "area_id": 140200 }, { "area_name": "城区", "pinyin": "Chengqu", "level": 3, "area_code": 352, "post_code": 37008, "pid": 140200, "id": 233, "area_id": 140202 }, { "area_name": "矿区", "pinyin": "Kuangqu", "level": 3, "area_code": 352, "post_code": 37003, "pid": 140200, "id": 234, "area_id": 140203 }, { "area_name": "南郊区", "pinyin": "Nanjiao", "level": 3, "area_code": 352, "post_code": 37001, "pid": 140200, "id": 235, "area_id": 140211 }, { "area_name": "新荣区", "pinyin": "Xinrong", "level": 3, "area_code": 352, "post_code": 37002, "pid": 140200, "id": 236, "area_id": 140212 }, { "area_name": "阳高县", "pinyin": "Yanggao", "level": 3, "area_code": 352, "post_code": 38100, "pid": 140200, "id": 237, "area_id": 140221 }, { "area_name": "天镇县", "pinyin": "Tianzhen", "level": 3, "area_code": 352, "post_code": 38200, "pid": 140200, "id": 238, "area_id": 140222 }, { "area_name": "广灵县", "pinyin": "Guangling", "level": 3, "area_code": 352, "post_code": 37500, "pid": 140200, "id": 239, "area_id": 140223 }, { "area_name": "灵丘县", "pinyin": "Lingqiu", "level": 3, "area_code": 352, "post_code": 34400, "pid": 140200, "id": 240, "area_id": 140224 }, { "area_name": "浑源县", "pinyin": "Hunyuan", "level": 3, "area_code": 352, "post_code": 37400, "pid": 140200, "id": 241, "area_id": 140225 }, { "area_name": "左云县", "pinyin": "Zuoyun", "level": 3, "area_code": 352, "post_code": 37100, "pid": 140200, "id": 242, "area_id": 140226 }, { "area_name": "大同县", "pinyin": "Datong", "level": 3, "area_code": 352, "post_code": 37300, "pid": 140200, "id": 243, "area_id": 140227 }, { "area_name": "阳泉市", "pinyin": "Yangquan", "level": 2, "area_code": 353, "post_code": 45000, "pid": 140000, "id": 244, "area_id": 140300 }, { "area_name": "城区", "pinyin": "Chengqu", "level": 3, "area_code": 353, "post_code": 45000, "pid": 140300, "id": 245, "area_id": 140302 }, { "area_name": "矿区", "pinyin": "Kuangqu", "level": 3, "area_code": 353, "post_code": 45000, "pid": 140300, "id": 246, "area_id": 140303 }, { "area_name": "郊区", "pinyin": "Jiaoqu", "level": 3, "area_code": 353, "post_code": 45011, "pid": 140300, "id": 247, "area_id": 140311 }, { "area_name": "平定县", "pinyin": "Pingding", "level": 3, "area_code": 353, "post_code": 45200, "pid": 140300, "id": 248, "area_id": 140321 }, { "area_name": "盂县", "pinyin": "Yuxian", "level": 3, "area_code": 353, "post_code": 45100, "pid": 140300, "id": 249, "area_id": 140322 }, { "area_name": "长治市", "pinyin": "Changzhi", "level": 2, "area_code": 355, "post_code": 46000, "pid": 140000, "id": 250, "area_id": 140400 }, { "area_name": "城区", "pinyin": "Chengqu", "level": 3, "area_code": 355, "post_code": 46011, "pid": 140400, "id": 251, "area_id": 140402 }, { "area_name": "郊区", "pinyin": "Jiaoqu", "level": 3, "area_code": 355, "post_code": 46011, "pid": 140400, "id": 252, "area_id": 140411 }, { "area_name": "长治县", "pinyin": "Changzhi", "level": 3, "area_code": 355, "post_code": 47100, "pid": 140400, "id": 253, "area_id": 140421 }, { "area_name": "襄垣县", "pinyin": "Xiangyuan", "level": 3, "area_code": 355, "post_code": 46200, "pid": 140400, "id": 254, "area_id": 140423 }, { "area_name": "屯留县", "pinyin": "Tunliu", "level": 3, "area_code": 355, "post_code": 46100, "pid": 140400, "id": 255, "area_id": 140424 }, { "area_name": "平顺县", "pinyin": "Pingshun", "level": 3, "area_code": 355, "post_code": 47400, "pid": 140400, "id": 256, "area_id": 140425 }, { "area_name": "黎城县", "pinyin": "Licheng", "level": 3, "area_code": 355, "post_code": 47600, "pid": 140400, "id": 257, "area_id": 140426 }, { "area_name": "壶关县", "pinyin": "Huguan", "level": 3, "area_code": 355, "post_code": 47300, "pid": 140400, "id": 258, "area_id": 140427 }, { "area_name": "长子县", "pinyin": "Zhangzi", "level": 3, "area_code": 355, "post_code": 46600, "pid": 140400, "id": 259, "area_id": 140428 }, { "area_name": "武乡县", "pinyin": "Wuxiang", "level": 3, "area_code": 355, "post_code": 46300, "pid": 140400, "id": 260, "area_id": 140429 }, { "area_name": "沁县", "pinyin": "Qinxian", "level": 3, "area_code": 355, "post_code": 46400, "pid": 140400, "id": 261, "area_id": 140430 }, { "area_name": "沁源县", "pinyin": "Qinyuan", "level": 3, "area_code": 355, "post_code": 46500, "pid": 140400, "id": 262, "area_id": 140431 }, { "area_name": "潞城市", "pinyin": "Lucheng", "level": 3, "area_code": 355, "post_code": 47500, "pid": 140400, "id": 263, "area_id": 140481 }, { "area_name": "晋城市", "pinyin": "Jincheng", "level": 2, "area_code": 356, "post_code": 48000, "pid": 140000, "id": 264, "area_id": 140500 }, { "area_name": "城区", "pinyin": "Chengqu", "level": 3, "area_code": 356, "post_code": 48000, "pid": 140500, "id": 265, "area_id": 140502 }, { "area_name": "沁水县", "pinyin": "Qinshui", "level": 3, "area_code": 356, "post_code": 48200, "pid": 140500, "id": 266, "area_id": 140521 }, { "area_name": "阳城县", "pinyin": "Yangcheng", "level": 3, "area_code": 356, "post_code": 48100, "pid": 140500, "id": 267, "area_id": 140522 }, { "area_name": "陵川县", "pinyin": "Lingchuan", "level": 3, "area_code": 356, "post_code": 48300, "pid": 140500, "id": 268, "area_id": 140524 }, { "area_name": "泽州县", "pinyin": "Zezhou", "level": 3, "area_code": 356, "post_code": 48012, "pid": 140500, "id": 269, "area_id": 140525 }, { "area_name": "高平市", "pinyin": "Gaoping", "level": 3, "area_code": 356, "post_code": 48400, "pid": 140500, "id": 270, "area_id": 140581 }, { "area_name": "朔州市", "pinyin": "Shuozhou", "level": 2, "area_code": 349, "post_code": 38500, "pid": 140000, "id": 271, "area_id": 140600 }, { "area_name": "朔城区", "pinyin": "Shuocheng", "level": 3, "area_code": 349, "post_code": 36000, "pid": 140600, "id": 272, "area_id": 140602 }, { "area_name": "平鲁区", "pinyin": "Pinglu", "level": 3, "area_code": 349, "post_code": 38600, "pid": 140600, "id": 273, "area_id": 140603 }, { "area_name": "山阴县", "pinyin": "Shanyin", "level": 3, "area_code": 349, "post_code": 36900, "pid": 140600, "id": 274, "area_id": 140621 }, { "area_name": "应县", "pinyin": "Yingxian", "level": 3, "area_code": 349, "post_code": 37600, "pid": 140600, "id": 275, "area_id": 140622 }, { "area_name": "右玉县", "pinyin": "Youyu", "level": 3, "area_code": 349, "post_code": 37200, "pid": 140600, "id": 276, "area_id": 140623 }, { "area_name": "怀仁县", "pinyin": "Huairen", "level": 3, "area_code": 349, "post_code": 38300, "pid": 140600, "id": 277, "area_id": 140624 }, { "area_name": "晋中市", "pinyin": "Jinzhong", "level": 2, "area_code": 354, "post_code": 30600, "pid": 140000, "id": 278, "area_id": 140700 }, { "area_name": "榆次区", "pinyin": "Yuci", "level": 3, "area_code": 354, "post_code": 30600, "pid": 140700, "id": 279, "area_id": 140702 }, { "area_name": "榆社县", "pinyin": "Yushe", "level": 3, "area_code": 354, "post_code": 31800, "pid": 140700, "id": 280, "area_id": 140721 }, { "area_name": "左权县", "pinyin": "Zuoquan", "level": 3, "area_code": 354, "post_code": 32600, "pid": 140700, "id": 281, "area_id": 140722 }, { "area_name": "和顺县", "pinyin": "Heshun", "level": 3, "area_code": 354, "post_code": 32700, "pid": 140700, "id": 282, "area_id": 140723 }, { "area_name": "昔阳县", "pinyin": "Xiyang", "level": 3, "area_code": 354, "post_code": 45300, "pid": 140700, "id": 283, "area_id": 140724 }, { "area_name": "寿阳县", "pinyin": "Shouyang", "level": 3, "area_code": 354, "post_code": 45400, "pid": 140700, "id": 284, "area_id": 140725 }, { "area_name": "太谷县", "pinyin": "Taigu", "level": 3, "area_code": 354, "post_code": 30800, "pid": 140700, "id": 285, "area_id": 140726 }, { "area_name": "祁县", "pinyin": "Qixian", "level": 3, "area_code": 354, "post_code": 30900, "pid": 140700, "id": 286, "area_id": 140727 }, { "area_name": "平遥县", "pinyin": "Pingyao", "level": 3, "area_code": 354, "post_code": 31100, "pid": 140700, "id": 287, "area_id": 140728 }, { "area_name": "灵石县", "pinyin": "Lingshi", "level": 3, "area_code": 354, "post_code": 31300, "pid": 140700, "id": 288, "area_id": 140729 }, { "area_name": "介休市", "pinyin": "Jiexiu", "level": 3, "area_code": 354, "post_code": 32000, "pid": 140700, "id": 289, "area_id": 140781 }, { "area_name": "运城市", "pinyin": "Yuncheng", "level": 2, "area_code": 359, "post_code": 44000, "pid": 140000, "id": 290, "area_id": 140800 }, { "area_name": "盐湖区", "pinyin": "Yanhu", "level": 3, "area_code": 359, "post_code": 44000, "pid": 140800, "id": 291, "area_id": 140802 }, { "area_name": "临猗县", "pinyin": "Linyi", "level": 3, "area_code": 359, "post_code": 44100, "pid": 140800, "id": 292, "area_id": 140821 }, { "area_name": "万荣县", "pinyin": "Wanrong", "level": 3, "area_code": 359, "post_code": 44200, "pid": 140800, "id": 293, "area_id": 140822 }, { "area_name": "闻喜县", "pinyin": "Wenxi", "level": 3, "area_code": 359, "post_code": 43800, "pid": 140800, "id": 294, "area_id": 140823 }, { "area_name": "稷山县", "pinyin": "Jishan", "level": 3, "area_code": 359, "post_code": 43200, "pid": 140800, "id": 295, "area_id": 140824 }, { "area_name": "新绛县", "pinyin": "Xinjiang", "level": 3, "area_code": 359, "post_code": 43100, "pid": 140800, "id": 296, "area_id": 140825 }, { "area_name": "绛县", "pinyin": "Jiangxian", "level": 3, "area_code": 359, "post_code": 43600, "pid": 140800, "id": 297, "area_id": 140826 }, { "area_name": "垣曲县", "pinyin": "Yuanqu", "level": 3, "area_code": 359, "post_code": 43700, "pid": 140800, "id": 298, "area_id": 140827 }, { "area_name": "夏县", "pinyin": "Xiaxian", "level": 3, "area_code": 359, "post_code": 44400, "pid": 140800, "id": 299, "area_id": 140828 }, { "area_name": "平陆县", "pinyin": "Pinglu", "level": 3, "area_code": 359, "post_code": 44300, "pid": 140800, "id": 300, "area_id": 140829 }, { "area_name": "芮城县", "pinyin": "Ruicheng", "level": 3, "area_code": 359, "post_code": 44600, "pid": 140800, "id": 301, "area_id": 140830 }, { "area_name": "永济市", "pinyin": "Yongji", "level": 3, "area_code": 359, "post_code": 44500, "pid": 140800, "id": 302, "area_id": 140881 }, { "area_name": "河津市", "pinyin": "Hejin", "level": 3, "area_code": 359, "post_code": 43300, "pid": 140800, "id": 303, "area_id": 140882 }, { "area_name": "忻州市", "pinyin": "Xinzhou", "level": 2, "area_code": 350, "post_code": 34000, "pid": 140000, "id": 304, "area_id": 140900 }, { "area_name": "忻府区", "pinyin": "Xinfu", "level": 3, "area_code": 350, "post_code": 34000, "pid": 140900, "id": 305, "area_id": 140902 }, { "area_name": "定襄县", "pinyin": "Dingxiang", "level": 3, "area_code": 350, "post_code": 35400, "pid": 140900, "id": 306, "area_id": 140921 }, { "area_name": "五台县", "pinyin": "Wutai", "level": 3, "area_code": 350, "post_code": 35500, "pid": 140900, "id": 307, "area_id": 140922 }, { "area_name": "代县", "pinyin": "Daixian", "level": 3, "area_code": 350, "post_code": 34200, "pid": 140900, "id": 308, "area_id": 140923 }, { "area_name": "繁峙县", "pinyin": "Fanshi", "level": 3, "area_code": 350, "post_code": 34300, "pid": 140900, "id": 309, "area_id": 140924 }, { "area_name": "宁武县", "pinyin": "Ningwu", "level": 3, "area_code": 350, "post_code": 36700, "pid": 140900, "id": 310, "area_id": 140925 }, { "area_name": "静乐县", "pinyin": "Jingle", "level": 3, "area_code": 350, "post_code": 35100, "pid": 140900, "id": 311, "area_id": 140926 }, { "area_name": "神池县", "pinyin": "Shenchi", "level": 3, "area_code": 350, "post_code": 36100, "pid": 140900, "id": 312, "area_id": 140927 }, { "area_name": "五寨县", "pinyin": "Wuzhai", "level": 3, "area_code": 350, "post_code": 36200, "pid": 140900, "id": 313, "area_id": 140928 }, { "area_name": "岢岚县", "pinyin": "Kelan", "level": 3, "area_code": 350, "post_code": 36300, "pid": 140900, "id": 314, "area_id": 140929 }, { "area_name": "河曲县", "pinyin": "Hequ", "level": 3, "area_code": 350, "post_code": 36500, "pid": 140900, "id": 315, "area_id": 140930 }, { "area_name": "保德县", "pinyin": "Baode", "level": 3, "area_code": 350, "post_code": 36600, "pid": 140900, "id": 316, "area_id": 140931 }, { "area_name": "偏关县", "pinyin": "Pianguan", "level": 3, "area_code": 350, "post_code": 36400, "pid": 140900, "id": 317, "area_id": 140932 }, { "area_name": "原平市", "pinyin": "Yuanping", "level": 3, "area_code": 350, "post_code": 34100, "pid": 140900, "id": 318, "area_id": 140981 }, { "area_name": "临汾市", "pinyin": "Linfen", "level": 2, "area_code": 357, "post_code": 41000, "pid": 140000, "id": 319, "area_id": 141000 }, { "area_name": "尧都区", "pinyin": "Yaodu", "level": 3, "area_code": 357, "post_code": 41000, "pid": 141000, "id": 320, "area_id": 141002 }, { "area_name": "曲沃县", "pinyin": "Quwo", "level": 3, "area_code": 357, "post_code": 43400, "pid": 141000, "id": 321, "area_id": 141021 }, { "area_name": "翼城县", "pinyin": "Yicheng", "level": 3, "area_code": 357, "post_code": 43500, "pid": 141000, "id": 322, "area_id": 141022 }, { "area_name": "襄汾县", "pinyin": "Xiangfen", "level": 3, "area_code": 357, "post_code": 41500, "pid": 141000, "id": 323, "area_id": 141023 }, { "area_name": "洪洞县", "pinyin": "Hongtong", "level": 3, "area_code": 357, "post_code": 41600, "pid": 141000, "id": 324, "area_id": 141024 }, { "area_name": "古县", "pinyin": "Guxian", "level": 3, "area_code": 357, "post_code": 42400, "pid": 141000, "id": 325, "area_id": 141025 }, { "area_name": "安泽县", "pinyin": "Anze", "level": 3, "area_code": 357, "post_code": 42500, "pid": 141000, "id": 326, "area_id": 141026 }, { "area_name": "浮山县", "pinyin": "Fushan", "level": 3, "area_code": 357, "post_code": 42600, "pid": 141000, "id": 327, "area_id": 141027 }, { "area_name": "吉县", "pinyin": "Jixian", "level": 3, "area_code": 357, "post_code": 42200, "pid": 141000, "id": 328, "area_id": 141028 }, { "area_name": "乡宁县", "pinyin": "Xiangning", "level": 3, "area_code": 357, "post_code": 42100, "pid": 141000, "id": 329, "area_id": 141029 }, { "area_name": "大宁县", "pinyin": "Daning", "level": 3, "area_code": 357, "post_code": 42300, "pid": 141000, "id": 330, "area_id": 141030 }, { "area_name": "隰县", "pinyin": "Xixian", "level": 3, "area_code": 357, "post_code": 41300, "pid": 141000, "id": 331, "area_id": 141031 }, { "area_name": "永和县", "pinyin": "Yonghe", "level": 3, "area_code": 357, "post_code": 41400, "pid": 141000, "id": 332, "area_id": 141032 }, { "area_name": "蒲县", "pinyin": "Puxian", "level": 3, "area_code": 357, "post_code": 41200, "pid": 141000, "id": 333, "area_id": 141033 }, { "area_name": "汾西县", "pinyin": "Fenxi", "level": 3, "area_code": 357, "post_code": 31500, "pid": 141000, "id": 334, "area_id": 141034 }, { "area_name": "侯马市", "pinyin": "Houma", "level": 3, "area_code": 357, "post_code": 43000, "pid": 141000, "id": 335, "area_id": 141081 }, { "area_name": "霍州市", "pinyin": "Huozhou", "level": 3, "area_code": 357, "post_code": 31400, "pid": 141000, "id": 336, "area_id": 141082 }, { "area_name": "吕梁市", "pinyin": "Lvliang", "level": 2, "area_code": 358, "post_code": 33000, "pid": 140000, "id": 337, "area_id": 141100 }, { "area_name": "离石区", "pinyin": "Lishi", "level": 3, "area_code": 358, "post_code": 33000, "pid": 141100, "id": 338, "area_id": 141102 }, { "area_name": "文水县", "pinyin": "Wenshui", "level": 3, "area_code": 358, "post_code": 32100, "pid": 141100, "id": 339, "area_id": 141121 }, { "area_name": "交城县", "pinyin": "Jiaocheng", "level": 3, "area_code": 358, "post_code": 30500, "pid": 141100, "id": 340, "area_id": 141122 }, { "area_name": "兴县", "pinyin": "Xingxian", "level": 3, "area_code": 358, "post_code": 33600, "pid": 141100, "id": 341, "area_id": 141123 }, { "area_name": "临县", "pinyin": "Linxian", "level": 3, "area_code": 358, "post_code": 33200, "pid": 141100, "id": 342, "area_id": 141124 }, { "area_name": "柳林县", "pinyin": "Liulin", "level": 3, "area_code": 358, "post_code": 33300, "pid": 141100, "id": 343, "area_id": 141125 }, { "area_name": "石楼县", "pinyin": "Shilou", "level": 3, "area_code": 358, "post_code": 32500, "pid": 141100, "id": 344, "area_id": 141126 }, { "area_name": "岚县", "pinyin": "Lanxian", "level": 3, "area_code": 358, "post_code": 33500, "pid": 141100, "id": 345, "area_id": 141127 }, { "area_name": "方山县", "pinyin": "Fangshan", "level": 3, "area_code": 358, "post_code": 33100, "pid": 141100, "id": 346, "area_id": 141128 }, { "area_name": "中阳县", "pinyin": "Zhongyang", "level": 3, "area_code": 358, "post_code": 33400, "pid": 141100, "id": 347, "area_id": 141129 }, { "area_name": "交口县", "pinyin": "Jiaokou", "level": 3, "area_code": 358, "post_code": 32400, "pid": 141100, "id": 348, "area_id": 141130 }, { "area_name": "孝义市", "pinyin": "Xiaoyi", "level": 3, "area_code": 358, "post_code": 32300, "pid": 141100, "id": 349, "area_id": 141181 }, { "area_name": "汾阳市", "pinyin": "Fenyang", "level": 3, "area_code": 358, "post_code": 32200, "pid": 141100, "id": 350, "area_id": 141182 }, { "area_name": "内蒙古自治区", "pinyin": "Inner Mongolia", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 351, "area_id": 150000 }, { "area_name": "呼和浩特市", "pinyin": "Hohhot", "level": 2, "area_code": 471, "post_code": 10000, "pid": 150000, "id": 352, "area_id": 150100 }, { "area_name": "新城区", "pinyin": "Xincheng", "level": 3, "area_code": 471, "post_code": 10050, "pid": 150100, "id": 353, "area_id": 150102 }, { "area_name": "回民区", "pinyin": "Huimin", "level": 3, "area_code": 471, "post_code": 10030, "pid": 150100, "id": 354, "area_id": 150103 }, { "area_name": "玉泉区", "pinyin": "Yuquan", "level": 3, "area_code": 471, "post_code": 10020, "pid": 150100, "id": 355, "area_id": 150104 }, { "area_name": "赛罕区", "pinyin": "Saihan", "level": 3, "area_code": 471, "post_code": 10020, "pid": 150100, "id": 356, "area_id": 150105 }, { "area_name": "土默特左旗", "pinyin": "Tumotezuoqi", "level": 3, "area_code": 471, "post_code": 10100, "pid": 150100, "id": 357, "area_id": 150121 }, { "area_name": "托克托县", "pinyin": "Tuoketuo", "level": 3, "area_code": 471, "post_code": 10200, "pid": 150100, "id": 358, "area_id": 150122 }, { "area_name": "和林格尔县", "pinyin": "Helingeer", "level": 3, "area_code": 471, "post_code": 11500, "pid": 150100, "id": 359, "area_id": 150123 }, { "area_name": "清水河县", "pinyin": "Qingshuihe", "level": 3, "area_code": 471, "post_code": 11600, "pid": 150100, "id": 360, "area_id": 150124 }, { "area_name": "武川县", "pinyin": "Wuchuan", "level": 3, "area_code": 471, "post_code": 11700, "pid": 150100, "id": 361, "area_id": 150125 }, { "area_name": "包头市", "pinyin": "Baotou", "level": 2, "area_code": 472, "post_code": 14025, "pid": 150000, "id": 362, "area_id": 150200 }, { "area_name": "东河区", "pinyin": "Donghe", "level": 3, "area_code": 472, "post_code": 14040, "pid": 150200, "id": 363, "area_id": 150202 }, { "area_name": "昆都仑区", "pinyin": "Kundulun", "level": 3, "area_code": 472, "post_code": 14010, "pid": 150200, "id": 364, "area_id": 150203 }, { "area_name": "青山区", "pinyin": "Qingshan", "level": 3, "area_code": 472, "post_code": 14030, "pid": 150200, "id": 365, "area_id": 150204 }, { "area_name": "石拐区", "pinyin": "Shiguai", "level": 3, "area_code": 472, "post_code": 14070, "pid": 150200, "id": 366, "area_id": 150205 }, { "area_name": "白云鄂博矿区", "pinyin": "Baiyunebokuangqu", "level": 3, "area_code": 472, "post_code": 14080, "pid": 150200, "id": 367, "area_id": 150206 }, { "area_name": "九原区", "pinyin": "Jiuyuan", "level": 3, "area_code": 472, "post_code": 14060, "pid": 150200, "id": 368, "area_id": 150207 }, { "area_name": "土默特右旗", "pinyin": "Tumoteyouqi", "level": 3, "area_code": 472, "post_code": 14100, "pid": 150200, "id": 369, "area_id": 150221 }, { "area_name": "固阳县", "pinyin": "Guyang", "level": 3, "area_code": 472, "post_code": 14200, "pid": 150200, "id": 370, "area_id": 150222 }, { "area_name": "达尔罕茂明安联合旗", "pinyin": "Damaoqi", "level": 3, "area_code": 472, "post_code": 14500, "pid": 150200, "id": 371, "area_id": 150223 }, { "area_name": "乌海市", "pinyin": "Wuhai", "level": 2, "area_code": 473, "post_code": 16000, "pid": 150000, "id": 372, "area_id": 150300 }, { "area_name": "海勃湾区", "pinyin": "Haibowan", "level": 3, "area_code": 473, "post_code": 16000, "pid": 150300, "id": 373, "area_id": 150302 }, { "area_name": "海南区", "pinyin": "Hainan", "level": 3, "area_code": 473, "post_code": 16030, "pid": 150300, "id": 374, "area_id": 150303 }, { "area_name": "乌达区", "pinyin": "Wuda", "level": 3, "area_code": 473, "post_code": 16040, "pid": 150300, "id": 375, "area_id": 150304 }, { "area_name": "赤峰市", "pinyin": "Chifeng", "level": 2, "area_code": 476, "post_code": 24000, "pid": 150000, "id": 376, "area_id": 150400 }, { "area_name": "红山区", "pinyin": "Hongshan", "level": 3, "area_code": 476, "post_code": 24020, "pid": 150400, "id": 377, "area_id": 150402 }, { "area_name": "元宝山区", "pinyin": "Yuanbaoshan", "level": 3, "area_code": 476, "post_code": 24076, "pid": 150400, "id": 378, "area_id": 150403 }, { "area_name": "松山区", "pinyin": "Songshan", "level": 3, "area_code": 476, "post_code": 24005, "pid": 150400, "id": 379, "area_id": 150404 }, { "area_name": "阿鲁科尔沁旗", "pinyin": "Alukeerqinqi", "level": 3, "area_code": 476, "post_code": 25550, "pid": 150400, "id": 380, "area_id": 150421 }, { "area_name": "巴林左旗", "pinyin": "Balinzuoqi", "level": 3, "area_code": 476, "post_code": 25450, "pid": 150400, "id": 381, "area_id": 150422 }, { "area_name": "巴林右旗", "pinyin": "Balinyouqi", "level": 3, "area_code": 476, "post_code": 25150, "pid": 150400, "id": 382, "area_id": 150423 }, { "area_name": "林西县", "pinyin": "Linxi", "level": 3, "area_code": 476, "post_code": 25250, "pid": 150400, "id": 383, "area_id": 150424 }, { "area_name": "克什克腾旗", "pinyin": "Keshiketengqi", "level": 3, "area_code": 476, "post_code": 25350, "pid": 150400, "id": 384, "area_id": 150425 }, { "area_name": "翁牛特旗", "pinyin": "Wengniuteqi", "level": 3, "area_code": 476, "post_code": 24500, "pid": 150400, "id": 385, "area_id": 150426 }, { "area_name": "喀喇沁旗", "pinyin": "Kalaqinqi", "level": 3, "area_code": 476, "post_code": 24400, "pid": 150400, "id": 386, "area_id": 150428 }, { "area_name": "宁城县", "pinyin": "Ningcheng", "level": 3, "area_code": 476, "post_code": 24200, "pid": 150400, "id": 387, "area_id": 150429 }, { "area_name": "敖汉旗", "pinyin": "Aohanqi", "level": 3, "area_code": 476, "post_code": 24300, "pid": 150400, "id": 388, "area_id": 150430 }, { "area_name": "通辽市", "pinyin": "Tongliao", "level": 2, "area_code": 475, "post_code": 28000, "pid": 150000, "id": 389, "area_id": 150500 }, { "area_name": "科尔沁区", "pinyin": "Keerqin", "level": 3, "area_code": 475, "post_code": 28000, "pid": 150500, "id": 390, "area_id": 150502 }, { "area_name": "科尔沁左翼中旗", "pinyin": "Keerqinzuoyizhongqi", "level": 3, "area_code": 475, "post_code": 29300, "pid": 150500, "id": 391, "area_id": 150521 }, { "area_name": "科尔沁左翼后旗", "pinyin": "Keerqinzuoyihouqi", "level": 3, "area_code": 475, "post_code": 28100, "pid": 150500, "id": 392, "area_id": 150522 }, { "area_name": "开鲁县", "pinyin": "Kailu", "level": 3, "area_code": 475, "post_code": 28400, "pid": 150500, "id": 393, "area_id": 150523 }, { "area_name": "库伦旗", "pinyin": "Kulunqi", "level": 3, "area_code": 475, "post_code": 28200, "pid": 150500, "id": 394, "area_id": 150524 }, { "area_name": "奈曼旗", "pinyin": "Naimanqi", "level": 3, "area_code": 475, "post_code": 28300, "pid": 150500, "id": 395, "area_id": 150525 }, { "area_name": "扎鲁特旗", "pinyin": "Zhaluteqi", "level": 3, "area_code": 475, "post_code": 29100, "pid": 150500, "id": 396, "area_id": 150526 }, { "area_name": "霍林郭勒市", "pinyin": "Huolinguole", "level": 3, "area_code": 475, "post_code": 29200, "pid": 150500, "id": 397, "area_id": 150581 }, { "area_name": "鄂尔多斯市", "pinyin": "Ordos", "level": 2, "area_code": 477, "post_code": 17004, "pid": 150000, "id": 398, "area_id": 150600 }, { "area_name": "东胜区", "pinyin": "Dongsheng", "level": 3, "area_code": 477, "post_code": 17000, "pid": 150600, "id": 399, "area_id": 150602 }, { "area_name": "达拉特旗", "pinyin": "Dalateqi", "level": 3, "area_code": 477, "post_code": 14300, "pid": 150600, "id": 400, "area_id": 150621 }, { "area_name": "准格尔旗", "pinyin": "Zhungeerqi", "level": 3, "area_code": 477, "post_code": 17100, "pid": 150600, "id": 401, "area_id": 150622 }, { "area_name": "鄂托克前旗", "pinyin": "Etuokeqianqi", "level": 3, "area_code": 477, "post_code": 16200, "pid": 150600, "id": 402, "area_id": 150623 }, { "area_name": "鄂托克旗", "pinyin": "Etuokeqi", "level": 3, "area_code": 477, "post_code": 16100, "pid": 150600, "id": 403, "area_id": 150624 }, { "area_name": "杭锦旗", "pinyin": "Hangjinqi", "level": 3, "area_code": 477, "post_code": 17400, "pid": 150600, "id": 404, "area_id": 150625 }, { "area_name": "乌审旗", "pinyin": "Wushenqi", "level": 3, "area_code": 477, "post_code": 17300, "pid": 150600, "id": 405, "area_id": 150626 }, { "area_name": "伊金霍洛旗", "pinyin": "Yijinhuoluoqi", "level": 3, "area_code": 477, "post_code": 17200, "pid": 150600, "id": 406, "area_id": 150627 }, { "area_name": "呼伦贝尔市", "pinyin": "Hulunber", "level": 2, "area_code": 470, "post_code": 21008, "pid": 150000, "id": 407, "area_id": 150700 }, { "area_name": "海拉尔区", "pinyin": "Hailaer", "level": 3, "area_code": 470, "post_code": 21000, "pid": 150700, "id": 408, "area_id": 150702 }, { "area_name": "扎赉诺尔区", "pinyin": "Zhalainuoer", "level": 3, "area_code": 470, "post_code": 21410, "pid": 150700, "id": 409, "area_id": 150703 }, { "area_name": "阿荣旗", "pinyin": "Arongqi", "level": 3, "area_code": 470, "post_code": 162750, "pid": 150700, "id": 410, "area_id": 150721 }, { "area_name": "莫力达瓦达斡尔族自治旗", "pinyin": "Moqi", "level": 3, "area_code": 470, "post_code": 162850, "pid": 150700, "id": 411, "area_id": 150722 }, { "area_name": "鄂伦春自治旗", "pinyin": "Elunchun", "level": 3, "area_code": 470, "post_code": 165450, "pid": 150700, "id": 412, "area_id": 150723 }, { "area_name": "鄂温克族自治旗", "pinyin": "Ewen", "level": 3, "area_code": 470, "post_code": 21100, "pid": 150700, "id": 413, "area_id": 150724 }, { "area_name": "陈巴尔虎旗", "pinyin": "Chenbaerhuqi", "level": 3, "area_code": 470, "post_code": 21500, "pid": 150700, "id": 414, "area_id": 150725 }, { "area_name": "新巴尔虎左旗", "pinyin": "Xinbaerhuzuoqi", "level": 3, "area_code": 470, "post_code": 21200, "pid": 150700, "id": 415, "area_id": 150726 }, { "area_name": "新巴尔虎右旗", "pinyin": "Xinbaerhuyouqi", "level": 3, "area_code": 470, "post_code": 21300, "pid": 150700, "id": 416, "area_id": 150727 }, { "area_name": "满洲里市", "pinyin": "Manzhouli", "level": 3, "area_code": 470, "post_code": 21400, "pid": 150700, "id": 417, "area_id": 150781 }, { "area_name": "牙克石市", "pinyin": "Yakeshi", "level": 3, "area_code": 470, "post_code": 22150, "pid": 150700, "id": 418, "area_id": 150782 }, { "area_name": "扎兰屯市", "pinyin": "Zhalantun", "level": 3, "area_code": 470, "post_code": 162650, "pid": 150700, "id": 419, "area_id": 150783 }, { "area_name": "额尔古纳市", "pinyin": "Eerguna", "level": 3, "area_code": 470, "post_code": 22250, "pid": 150700, "id": 420, "area_id": 150784 }, { "area_name": "根河市", "pinyin": "Genhe", "level": 3, "area_code": 470, "post_code": 22350, "pid": 150700, "id": 421, "area_id": 150785 }, { "area_name": "巴彦淖尔市", "pinyin": "Bayan Nur", "level": 2, "area_code": 478, "post_code": 15001, "pid": 150000, "id": 422, "area_id": 150800 }, { "area_name": "临河区", "pinyin": "Linhe", "level": 3, "area_code": 478, "post_code": 15001, "pid": 150800, "id": 423, "area_id": 150802 }, { "area_name": "五原县", "pinyin": "Wuyuan", "level": 3, "area_code": 478, "post_code": 15100, "pid": 150800, "id": 424, "area_id": 150821 }, { "area_name": "磴口县", "pinyin": "Dengkou", "level": 3, "area_code": 478, "post_code": 15200, "pid": 150800, "id": 425, "area_id": 150822 }, { "area_name": "乌拉特前旗", "pinyin": "Wulateqianqi", "level": 3, "area_code": 478, "post_code": 14400, "pid": 150800, "id": 426, "area_id": 150823 }, { "area_name": "乌拉特中旗", "pinyin": "Wulatezhongqi", "level": 3, "area_code": 478, "post_code": 15300, "pid": 150800, "id": 427, "area_id": 150824 }, { "area_name": "乌拉特后旗", "pinyin": "Wulatehouqi", "level": 3, "area_code": 478, "post_code": 15500, "pid": 150800, "id": 428, "area_id": 150825 }, { "area_name": "杭锦后旗", "pinyin": "Hangjinhouqi", "level": 3, "area_code": 478, "post_code": 15400, "pid": 150800, "id": 429, "area_id": 150826 }, { "area_name": "乌兰察布市", "pinyin": "Ulanqab", "level": 2, "area_code": 474, "post_code": 12000, "pid": 150000, "id": 430, "area_id": 150900 }, { "area_name": "集宁区", "pinyin": "Jining", "level": 3, "area_code": 474, "post_code": 12000, "pid": 150900, "id": 431, "area_id": 150902 }, { "area_name": "卓资县", "pinyin": "Zhuozi", "level": 3, "area_code": 474, "post_code": 12300, "pid": 150900, "id": 432, "area_id": 150921 }, { "area_name": "化德县", "pinyin": "Huade", "level": 3, "area_code": 474, "post_code": 13350, "pid": 150900, "id": 433, "area_id": 150922 }, { "area_name": "商都县", "pinyin": "Shangdu", "level": 3, "area_code": 474, "post_code": 13450, "pid": 150900, "id": 434, "area_id": 150923 }, { "area_name": "兴和县", "pinyin": "Xinghe", "level": 3, "area_code": 474, "post_code": 13650, "pid": 150900, "id": 435, "area_id": 150924 }, { "area_name": "凉城县", "pinyin": "Liangcheng", "level": 3, "area_code": 474, "post_code": 13750, "pid": 150900, "id": 436, "area_id": 150925 }, { "area_name": "察哈尔右翼前旗", "pinyin": "Chayouqianqi", "level": 3, "area_code": 474, "post_code": 12200, "pid": 150900, "id": 437, "area_id": 150926 }, { "area_name": "察哈尔右翼中旗", "pinyin": "Chayouzhongqi", "level": 3, "area_code": 474, "post_code": 13550, "pid": 150900, "id": 438, "area_id": 150927 }, { "area_name": "察哈尔右翼后旗", "pinyin": "Chayouhouqi", "level": 3, "area_code": 474, "post_code": 12400, "pid": 150900, "id": 439, "area_id": 150928 }, { "area_name": "四子王旗", "pinyin": "Siziwangqi", "level": 3, "area_code": 474, "post_code": 11800, "pid": 150900, "id": 440, "area_id": 150929 }, { "area_name": "丰镇市", "pinyin": "Fengzhen", "level": 3, "area_code": 474, "post_code": 12100, "pid": 150900, "id": 441, "area_id": 150981 }, { "area_name": "兴安盟", "pinyin": "Hinggan", "level": 2, "area_code": 482, "post_code": 137401, "pid": 150000, "id": 442, "area_id": 152200 }, { "area_name": "乌兰浩特市", "pinyin": "Wulanhaote", "level": 3, "area_code": 482, "post_code": 137401, "pid": 152200, "id": 443, "area_id": 152201 }, { "area_name": "阿尔山市", "pinyin": "Aershan", "level": 3, "area_code": 482, "post_code": 137800, "pid": 152200, "id": 444, "area_id": 152202 }, { "area_name": "科尔沁右翼前旗", "pinyin": "Keyouqianqi", "level": 3, "area_code": 482, "post_code": 137423, "pid": 152200, "id": 445, "area_id": 152221 }, { "area_name": "科尔沁右翼中旗", "pinyin": "Keyouzhongqi", "level": 3, "area_code": 482, "post_code": 29400, "pid": 152200, "id": 446, "area_id": 152222 }, { "area_name": "扎赉特旗", "pinyin": "Zhalaiteqi", "level": 3, "area_code": 482, "post_code": 137600, "pid": 152200, "id": 447, "area_id": 152223 }, { "area_name": "突泉县", "pinyin": "Tuquan", "level": 3, "area_code": 482, "post_code": 137500, "pid": 152200, "id": 448, "area_id": 152224 }, { "area_name": "锡林郭勒盟", "pinyin": "Xilin Gol", "level": 2, "area_code": 479, "post_code": 26000, "pid": 150000, "id": 449, "area_id": 152500 }, { "area_name": "二连浩特市", "pinyin": "Erlianhaote", "level": 3, "area_code": 479, "post_code": 11100, "pid": 152500, "id": 450, "area_id": 152501 }, { "area_name": "锡林浩特市", "pinyin": "Xilinhaote", "level": 3, "area_code": 479, "post_code": 26021, "pid": 152500, "id": 451, "area_id": 152502 }, { "area_name": "阿巴嘎旗", "pinyin": "Abagaqi", "level": 3, "area_code": 479, "post_code": 11400, "pid": 152500, "id": 452, "area_id": 152522 }, { "area_name": "苏尼特左旗", "pinyin": "Sunitezuoqi", "level": 3, "area_code": 479, "post_code": 11300, "pid": 152500, "id": 453, "area_id": 152523 }, { "area_name": "苏尼特右旗", "pinyin": "Suniteyouqi", "level": 3, "area_code": 479, "post_code": 11200, "pid": 152500, "id": 454, "area_id": 152524 }, { "area_name": "东乌珠穆沁旗", "pinyin": "Dongwuqi", "level": 3, "area_code": 479, "post_code": 26300, "pid": 152500, "id": 455, "area_id": 152525 }, { "area_name": "西乌珠穆沁旗", "pinyin": "Xiwuqi", "level": 3, "area_code": 479, "post_code": 26200, "pid": 152500, "id": 456, "area_id": 152526 }, { "area_name": "太仆寺旗", "pinyin": "Taipusiqi", "level": 3, "area_code": 479, "post_code": 27000, "pid": 152500, "id": 457, "area_id": 152527 }, { "area_name": "镶黄旗", "pinyin": "Xianghuangqi", "level": 3, "area_code": 479, "post_code": 13250, "pid": 152500, "id": 458, "area_id": 152528 }, { "area_name": "正镶白旗", "pinyin": "Zhengxiangbaiqi", "level": 3, "area_code": 479, "post_code": 13800, "pid": 152500, "id": 459, "area_id": 152529 }, { "area_name": "正蓝旗", "pinyin": "Zhenglanqi", "level": 3, "area_code": 479, "post_code": 27200, "pid": 152500, "id": 460, "area_id": 152530 }, { "area_name": "多伦县", "pinyin": "Duolun", "level": 3, "area_code": 479, "post_code": 27300, "pid": 152500, "id": 461, "area_id": 152531 }, { "area_name": "阿拉善盟", "pinyin": "Alxa", "level": 2, "area_code": 483, "post_code": 750306, "pid": 150000, "id": 462, "area_id": 152900 }, { "area_name": "阿拉善左旗", "pinyin": "Alashanzuoqi", "level": 3, "area_code": 483, "post_code": 750306, "pid": 152900, "id": 463, "area_id": 152921 }, { "area_name": "阿拉善右旗", "pinyin": "Alashanyouqi", "level": 3, "area_code": 483, "post_code": 737300, "pid": 152900, "id": 464, "area_id": 152922 }, { "area_name": "额济纳旗", "pinyin": "Ejinaqi", "level": 3, "area_code": 483, "post_code": 735400, "pid": 152900, "id": 465, "area_id": 152923 }, { "area_name": "辽宁省", "pinyin": "Liaoning", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 466, "area_id": 210000 }, { "area_name": "沈阳市", "pinyin": "Shenyang", "level": 2, "area_code": 24, "post_code": 110013, "pid": 210000, "id": 467, "area_id": 210100 }, { "area_name": "和平区", "pinyin": "Heping", "level": 3, "area_code": 24, "post_code": 110001, "pid": 210100, "id": 468, "area_id": 210102 }, { "area_name": "沈河区", "pinyin": "Shenhe", "level": 3, "area_code": 24, "post_code": 110011, "pid": 210100, "id": 469, "area_id": 210103 }, { "area_name": "大东区", "pinyin": "Dadong", "level": 3, "area_code": 24, "post_code": 110041, "pid": 210100, "id": 470, "area_id": 210104 }, { "area_name": "皇姑区", "pinyin": "Huanggu", "level": 3, "area_code": 24, "post_code": 110031, "pid": 210100, "id": 471, "area_id": 210105 }, { "area_name": "铁西区", "pinyin": "Tiexi", "level": 3, "area_code": 24, "post_code": 110021, "pid": 210100, "id": 472, "area_id": 210106 }, { "area_name": "苏家屯区", "pinyin": "Sujiatun", "level": 3, "area_code": 24, "post_code": 110101, "pid": 210100, "id": 473, "area_id": 210111 }, { "area_name": "浑南区", "pinyin": "Hunnan", "level": 3, "area_code": 24, "post_code": 110015, "pid": 210100, "id": 474, "area_id": 210112 }, { "area_name": "沈北新区", "pinyin": "Shenbeixinqu", "level": 3, "area_code": 24, "post_code": 110121, "pid": 210100, "id": 475, "area_id": 210113 }, { "area_name": "于洪区", "pinyin": "Yuhong", "level": 3, "area_code": 24, "post_code": 110141, "pid": 210100, "id": 476, "area_id": 210114 }, { "area_name": "辽中县", "pinyin": "Liaozhong", "level": 3, "area_code": 24, "post_code": 110200, "pid": 210100, "id": 477, "area_id": 210122 }, { "area_name": "康平县", "pinyin": "Kangping", "level": 3, "area_code": 24, "post_code": 110500, "pid": 210100, "id": 478, "area_id": 210123 }, { "area_name": "法库县", "pinyin": "Faku", "level": 3, "area_code": 24, "post_code": 110400, "pid": 210100, "id": 479, "area_id": 210124 }, { "area_name": "新民市", "pinyin": "Xinmin", "level": 3, "area_code": 24, "post_code": 110300, "pid": 210100, "id": 480, "area_id": 210181 }, { "area_name": "大连市", "pinyin": "Dalian", "level": 2, "area_code": 411, "post_code": 116011, "pid": 210000, "id": 481, "area_id": 210200 }, { "area_name": "中山区", "pinyin": "Zhongshan", "level": 3, "area_code": 411, "post_code": 116001, "pid": 210200, "id": 482, "area_id": 210202 }, { "area_name": "西岗区", "pinyin": "Xigang", "level": 3, "area_code": 411, "post_code": 116011, "pid": 210200, "id": 483, "area_id": 210203 }, { "area_name": "沙河口区", "pinyin": "Shahekou", "level": 3, "area_code": 411, "post_code": 116021, "pid": 210200, "id": 484, "area_id": 210204 }, { "area_name": "甘井子区", "pinyin": "Ganjingzi", "level": 3, "area_code": 411, "post_code": 116033, "pid": 210200, "id": 485, "area_id": 210211 }, { "area_name": "旅顺口区", "pinyin": "Lvshunkou", "level": 3, "area_code": 411, "post_code": 116041, "pid": 210200, "id": 486, "area_id": 210212 }, { "area_name": "金州区", "pinyin": "Jinzhou", "level": 3, "area_code": 411, "post_code": 116100, "pid": 210200, "id": 487, "area_id": 210213 }, { "area_name": "长海县", "pinyin": "Changhai", "level": 3, "area_code": 411, "post_code": 116500, "pid": 210200, "id": 488, "area_id": 210224 }, { "area_name": "瓦房店市", "pinyin": "Wafangdian", "level": 3, "area_code": 411, "post_code": 116300, "pid": 210200, "id": 489, "area_id": 210281 }, { "area_name": "普兰店市", "pinyin": "Pulandian", "level": 3, "area_code": 411, "post_code": 116200, "pid": 210200, "id": 490, "area_id": 210282 }, { "area_name": "庄河市", "pinyin": "Zhuanghe", "level": 3, "area_code": 411, "post_code": 116400, "pid": 210200, "id": 491, "area_id": 210283 }, { "area_name": "鞍山市", "pinyin": "Anshan", "level": 2, "area_code": 412, "post_code": 114001, "pid": 210000, "id": 492, "area_id": 210300 }, { "area_name": "铁东区", "pinyin": "Tiedong", "level": 3, "area_code": 412, "post_code": 114001, "pid": 210300, "id": 493, "area_id": 210302 }, { "area_name": "铁西区", "pinyin": "Tiexi", "level": 3, "area_code": 413, "post_code": 114013, "pid": 210300, "id": 494, "area_id": 210303 }, { "area_name": "立山区", "pinyin": "Lishan", "level": 3, "area_code": 414, "post_code": 114031, "pid": 210300, "id": 495, "area_id": 210304 }, { "area_name": "千山区", "pinyin": "Qianshan", "level": 3, "area_code": 415, "post_code": 114041, "pid": 210300, "id": 496, "area_id": 210311 }, { "area_name": "台安县", "pinyin": "Tai'an", "level": 3, "area_code": 417, "post_code": 114100, "pid": 210300, "id": 497, "area_id": 210321 }, { "area_name": "岫岩满族自治县", "pinyin": "Xiuyan", "level": 3, "area_code": 418, "post_code": 114300, "pid": 210300, "id": 498, "area_id": 210323 }, { "area_name": "海城市", "pinyin": "Haicheng", "level": 3, "area_code": 416, "post_code": 114200, "pid": 210300, "id": 499, "area_id": 210381 }, { "area_name": "抚顺市", "pinyin": "Fushun", "level": 2, "area_code": 24, "post_code": 113008, "pid": 210000, "id": 500, "area_id": 210400 }, { "area_name": "新抚区", "pinyin": "Xinfu", "level": 3, "area_code": 24, "post_code": 113008, "pid": 210400, "id": 501, "area_id": 210402 }, { "area_name": "东洲区", "pinyin": "Dongzhou", "level": 3, "area_code": 24, "post_code": 113003, "pid": 210400, "id": 502, "area_id": 210403 }, { "area_name": "望花区", "pinyin": "Wanghua", "level": 3, "area_code": 24, "post_code": 113001, "pid": 210400, "id": 503, "area_id": 210404 }, { "area_name": "顺城区", "pinyin": "Shuncheng", "level": 3, "area_code": 24, "post_code": 113006, "pid": 210400, "id": 504, "area_id": 210411 }, { "area_name": "抚顺县", "pinyin": "Fushun", "level": 3, "area_code": 24, "post_code": 113006, "pid": 210400, "id": 505, "area_id": 210421 }, { "area_name": "新宾满族自治县", "pinyin": "Xinbin", "level": 3, "area_code": 24, "post_code": 113200, "pid": 210400, "id": 506, "area_id": 210422 }, { "area_name": "清原满族自治县", "pinyin": "Qingyuan", "level": 3, "area_code": 24, "post_code": 113300, "pid": 210400, "id": 507, "area_id": 210423 }, { "area_name": "本溪市", "pinyin": "Benxi", "level": 2, "area_code": 414, "post_code": 117000, "pid": 210000, "id": 508, "area_id": 210500 }, { "area_name": "平山区", "pinyin": "Pingshan", "level": 3, "area_code": 414, "post_code": 117000, "pid": 210500, "id": 509, "area_id": 210502 }, { "area_name": "溪湖区", "pinyin": "Xihu", "level": 3, "area_code": 414, "post_code": 117002, "pid": 210500, "id": 510, "area_id": 210503 }, { "area_name": "明山区", "pinyin": "Mingshan", "level": 3, "area_code": 414, "post_code": 117021, "pid": 210500, "id": 511, "area_id": 210504 }, { "area_name": "南芬区", "pinyin": "Nanfen", "level": 3, "area_code": 414, "post_code": 117014, "pid": 210500, "id": 512, "area_id": 210505 }, { "area_name": "本溪满族自治县", "pinyin": "Benxi", "level": 3, "area_code": 414, "post_code": 117100, "pid": 210500, "id": 513, "area_id": 210521 }, { "area_name": "桓仁满族自治县", "pinyin": "Huanren", "level": 3, "area_code": 414, "post_code": 117200, "pid": 210500, "id": 514, "area_id": 210522 }, { "area_name": "丹东市", "pinyin": "Dandong", "level": 2, "area_code": 415, "post_code": 118000, "pid": 210000, "id": 515, "area_id": 210600 }, { "area_name": "元宝区", "pinyin": "Yuanbao", "level": 3, "area_code": 415, "post_code": 118000, "pid": 210600, "id": 516, "area_id": 210602 }, { "area_name": "振兴区", "pinyin": "Zhenxing", "level": 3, "area_code": 415, "post_code": 118002, "pid": 210600, "id": 517, "area_id": 210603 }, { "area_name": "振安区", "pinyin": "Zhen'an", "level": 3, "area_code": 415, "post_code": 118001, "pid": 210600, "id": 518, "area_id": 210604 }, { "area_name": "宽甸满族自治县", "pinyin": "Kuandian", "level": 3, "area_code": 415, "post_code": 118200, "pid": 210600, "id": 519, "area_id": 210624 }, { "area_name": "东港市", "pinyin": "Donggang", "level": 3, "area_code": 415, "post_code": 118300, "pid": 210600, "id": 520, "area_id": 210681 }, { "area_name": "凤城市", "pinyin": "Fengcheng", "level": 3, "area_code": 415, "post_code": 118100, "pid": 210600, "id": 521, "area_id": 210682 }, { "area_name": "锦州市", "pinyin": "Jinzhou", "level": 2, "area_code": 416, "post_code": 121000, "pid": 210000, "id": 522, "area_id": 210700 }, { "area_name": "古塔区", "pinyin": "Guta", "level": 3, "area_code": 416, "post_code": 121001, "pid": 210700, "id": 523, "area_id": 210702 }, { "area_name": "凌河区", "pinyin": "Linghe", "level": 3, "area_code": 416, "post_code": 121000, "pid": 210700, "id": 524, "area_id": 210703 }, { "area_name": "太和区", "pinyin": "Taihe", "level": 3, "area_code": 416, "post_code": 121011, "pid": 210700, "id": 525, "area_id": 210711 }, { "area_name": "黑山县", "pinyin": "Heishan", "level": 3, "area_code": 416, "post_code": 121400, "pid": 210700, "id": 526, "area_id": 210726 }, { "area_name": "义县", "pinyin": "Yixian", "level": 3, "area_code": 416, "post_code": 121100, "pid": 210700, "id": 527, "area_id": 210727 }, { "area_name": "凌海市", "pinyin": "Linghai", "level": 3, "area_code": 416, "post_code": 121200, "pid": 210700, "id": 528, "area_id": 210781 }, { "area_name": "北镇市", "pinyin": "Beizhen", "level": 3, "area_code": 416, "post_code": 121300, "pid": 210700, "id": 529, "area_id": 210782 }, { "area_name": "营口市", "pinyin": "Yingkou", "level": 2, "area_code": 417, "post_code": 115003, "pid": 210000, "id": 530, "area_id": 210800 }, { "area_name": "站前区", "pinyin": "Zhanqian", "level": 3, "area_code": 417, "post_code": 115002, "pid": 210800, "id": 531, "area_id": 210802 }, { "area_name": "西市区", "pinyin": "Xishi", "level": 3, "area_code": 417, "post_code": 115004, "pid": 210800, "id": 532, "area_id": 210803 }, { "area_name": "鲅鱼圈区", "pinyin": "Bayuquan", "level": 3, "area_code": 417, "post_code": 115007, "pid": 210800, "id": 533, "area_id": 210804 }, { "area_name": "老边区", "pinyin": "Laobian", "level": 3, "area_code": 417, "post_code": 115005, "pid": 210800, "id": 534, "area_id": 210811 }, { "area_name": "盖州市", "pinyin": "Gaizhou", "level": 3, "area_code": 417, "post_code": 115200, "pid": 210800, "id": 535, "area_id": 210881 }, { "area_name": "大石桥市", "pinyin": "Dashiqiao", "level": 3, "area_code": 417, "post_code": 115100, "pid": 210800, "id": 536, "area_id": 210882 }, { "area_name": "阜新市", "pinyin": "Fuxin", "level": 2, "area_code": 418, "post_code": 123000, "pid": 210000, "id": 537, "area_id": 210900 }, { "area_name": "海州区", "pinyin": "Haizhou", "level": 3, "area_code": 418, "post_code": 123000, "pid": 210900, "id": 538, "area_id": 210902 }, { "area_name": "新邱区", "pinyin": "Xinqiu", "level": 3, "area_code": 418, "post_code": 123005, "pid": 210900, "id": 539, "area_id": 210903 }, { "area_name": "太平区", "pinyin": "Taiping", "level": 3, "area_code": 418, "post_code": 123003, "pid": 210900, "id": 540, "area_id": 210904 }, { "area_name": "清河门区", "pinyin": "Qinghemen", "level": 3, "area_code": 418, "post_code": 123006, "pid": 210900, "id": 541, "area_id": 210905 }, { "area_name": "细河区", "pinyin": "Xihe", "level": 3, "area_code": 418, "post_code": 123000, "pid": 210900, "id": 542, "area_id": 210911 }, { "area_name": "阜新蒙古族自治县", "pinyin": "Fuxin", "level": 3, "area_code": 418, "post_code": 123100, "pid": 210900, "id": 543, "area_id": 210921 }, { "area_name": "彰武县", "pinyin": "Zhangwu", "level": 3, "area_code": 418, "post_code": 123200, "pid": 210900, "id": 544, "area_id": 210922 }, { "area_name": "辽阳市", "pinyin": "Liaoyang", "level": 2, "area_code": 419, "post_code": 111000, "pid": 210000, "id": 545, "area_id": 211000 }, { "area_name": "白塔区", "pinyin": "Baita", "level": 3, "area_code": 419, "post_code": 111000, "pid": 211000, "id": 546, "area_id": 211002 }, { "area_name": "文圣区", "pinyin": "Wensheng", "level": 3, "area_code": 419, "post_code": 111000, "pid": 211000, "id": 547, "area_id": 211003 }, { "area_name": "宏伟区", "pinyin": "Hongwei", "level": 3, "area_code": 419, "post_code": 111003, "pid": 211000, "id": 548, "area_id": 211004 }, { "area_name": "弓长岭区", "pinyin": "Gongchangling", "level": 3, "area_code": 419, "post_code": 111008, "pid": 211000, "id": 549, "area_id": 211005 }, { "area_name": "太子河区", "pinyin": "Taizihe", "level": 3, "area_code": 419, "post_code": 111000, "pid": 211000, "id": 550, "area_id": 211011 }, { "area_name": "辽阳县", "pinyin": "Liaoyang", "level": 3, "area_code": 419, "post_code": 111200, "pid": 211000, "id": 551, "area_id": 211021 }, { "area_name": "灯塔市", "pinyin": "Dengta", "level": 3, "area_code": 419, "post_code": 111300, "pid": 211000, "id": 552, "area_id": 211081 }, { "area_name": "盘锦市", "pinyin": "Panjin", "level": 2, "area_code": 427, "post_code": 124010, "pid": 210000, "id": 553, "area_id": 211100 }, { "area_name": "双台子区", "pinyin": "Shuangtaizi", "level": 3, "area_code": 427, "post_code": 124000, "pid": 211100, "id": 554, "area_id": 211102 }, { "area_name": "兴隆台区", "pinyin": "Xinglongtai", "level": 3, "area_code": 427, "post_code": 124010, "pid": 211100, "id": 555, "area_id": 211103 }, { "area_name": "大洼县", "pinyin": "Dawa", "level": 3, "area_code": 427, "post_code": 124200, "pid": 211100, "id": 556, "area_id": 211121 }, { "area_name": "盘山县", "pinyin": "Panshan", "level": 3, "area_code": 427, "post_code": 124000, "pid": 211100, "id": 557, "area_id": 211122 }, { "area_name": "铁岭市", "pinyin": "Tieling", "level": 2, "area_code": 24, "post_code": 112000, "pid": 210000, "id": 558, "area_id": 211200 }, { "area_name": "银州区", "pinyin": "Yinzhou", "level": 3, "area_code": 24, "post_code": 112000, "pid": 211200, "id": 559, "area_id": 211202 }, { "area_name": "清河区", "pinyin": "Qinghe", "level": 3, "area_code": 24, "post_code": 112003, "pid": 211200, "id": 560, "area_id": 211204 }, { "area_name": "铁岭县", "pinyin": "Tieling", "level": 3, "area_code": 24, "post_code": 112000, "pid": 211200, "id": 561, "area_id": 211221 }, { "area_name": "西丰县", "pinyin": "Xifeng", "level": 3, "area_code": 24, "post_code": 112400, "pid": 211200, "id": 562, "area_id": 211223 }, { "area_name": "昌图县", "pinyin": "Changtu", "level": 3, "area_code": 24, "post_code": 112500, "pid": 211200, "id": 563, "area_id": 211224 }, { "area_name": "调兵山市", "pinyin": "Diaobingshan", "level": 3, "area_code": 24, "post_code": 112700, "pid": 211200, "id": 564, "area_id": 211281 }, { "area_name": "开原市", "pinyin": "Kaiyuan", "level": 3, "area_code": 24, "post_code": 112300, "pid": 211200, "id": 565, "area_id": 211282 }, { "area_name": "朝阳市", "pinyin": "Chaoyang", "level": 2, "area_code": 421, "post_code": 122000, "pid": 210000, "id": 566, "area_id": 211300 }, { "area_name": "双塔区", "pinyin": "Shuangta", "level": 3, "area_code": 421, "post_code": 122000, "pid": 211300, "id": 567, "area_id": 211302 }, { "area_name": "龙城区", "pinyin": "Longcheng", "level": 3, "area_code": 421, "post_code": 122000, "pid": 211300, "id": 568, "area_id": 211303 }, { "area_name": "朝阳县", "pinyin": "Chaoyang", "level": 3, "area_code": 421, "post_code": 122000, "pid": 211300, "id": 569, "area_id": 211321 }, { "area_name": "建平县", "pinyin": "Jianping", "level": 3, "area_code": 421, "post_code": 122400, "pid": 211300, "id": 570, "area_id": 211322 }, { "area_name": "喀喇沁左翼蒙古族自治县", "pinyin": "Kalaqinzuoyi", "level": 3, "area_code": 421, "post_code": 122300, "pid": 211300, "id": 571, "area_id": 211324 }, { "area_name": "北票市", "pinyin": "Beipiao", "level": 3, "area_code": 421, "post_code": 122100, "pid": 211300, "id": 572, "area_id": 211381 }, { "area_name": "凌源市", "pinyin": "Lingyuan", "level": 3, "area_code": 421, "post_code": 122500, "pid": 211300, "id": 573, "area_id": 211382 }, { "area_name": "葫芦岛市", "pinyin": "Huludao", "level": 2, "area_code": 429, "post_code": 125000, "pid": 210000, "id": 574, "area_id": 211400 }, { "area_name": "连山区", "pinyin": "Lianshan", "level": 3, "area_code": 429, "post_code": 125001, "pid": 211400, "id": 575, "area_id": 211402 }, { "area_name": "龙港区", "pinyin": "Longgang", "level": 3, "area_code": 429, "post_code": 125003, "pid": 211400, "id": 576, "area_id": 211403 }, { "area_name": "南票区", "pinyin": "Nanpiao", "level": 3, "area_code": 429, "post_code": 125027, "pid": 211400, "id": 577, "area_id": 211404 }, { "area_name": "绥中县", "pinyin": "Suizhong", "level": 3, "area_code": 429, "post_code": 125200, "pid": 211400, "id": 578, "area_id": 211421 }, { "area_name": "建昌县", "pinyin": "Jianchang", "level": 3, "area_code": 429, "post_code": 125300, "pid": 211400, "id": 579, "area_id": 211422 }, { "area_name": "兴城市", "pinyin": "Xingcheng", "level": 3, "area_code": 429, "post_code": 125100, "pid": 211400, "id": 580, "area_id": 211481 }, { "area_name": "金普新区", "pinyin": "Jinpuxinqu", "level": 2, "area_code": 411, "post_code": 116100, "pid": 210000, "id": 581, "area_id": 211500 }, { "area_name": "金州新区", "pinyin": "Jinzhouxinqu", "level": 3, "area_code": 411, "post_code": 116100, "pid": 211500, "id": 582, "area_id": 211501 }, { "area_name": "普湾新区", "pinyin": "Puwanxinqu", "level": 3, "area_code": 411, "post_code": 116200, "pid": 211500, "id": 583, "area_id": 211502 }, { "area_name": "保税区", "pinyin": "Baoshuiqu", "level": 3, "area_code": 411, "post_code": 116100, "pid": 211500, "id": 584, "area_id": 211503 }, { "area_name": "吉林省", "pinyin": "Jilin", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 585, "area_id": 220000 }, { "area_name": "长春市", "pinyin": "Changchun", "level": 2, "area_code": 431, "post_code": 130022, "pid": 220000, "id": 586, "area_id": 220100 }, { "area_name": "南关区", "pinyin": "Nanguan", "level": 3, "area_code": 431, "post_code": 130022, "pid": 220100, "id": 587, "area_id": 220102 }, { "area_name": "宽城区", "pinyin": "Kuancheng", "level": 3, "area_code": 431, "post_code": 130051, "pid": 220100, "id": 588, "area_id": 220103 }, { "area_name": "朝阳区", "pinyin": "Chaoyang", "level": 3, "area_code": 431, "post_code": 130012, "pid": 220100, "id": 589, "area_id": 220104 }, { "area_name": "二道区", "pinyin": "Erdao", "level": 3, "area_code": 431, "post_code": 130031, "pid": 220100, "id": 590, "area_id": 220105 }, { "area_name": "绿园区", "pinyin": "Lvyuan", "level": 3, "area_code": 431, "post_code": 130062, "pid": 220100, "id": 591, "area_id": 220106 }, { "area_name": "双阳区", "pinyin": "Shuangyang", "level": 3, "area_code": 431, "post_code": 130600, "pid": 220100, "id": 592, "area_id": 220112 }, { "area_name": "九台区", "pinyin": "Jiutai", "level": 3, "area_code": 431, "post_code": 130500, "pid": 220100, "id": 593, "area_id": 220113 }, { "area_name": "农安县", "pinyin": "Nong'an", "level": 3, "area_code": 431, "post_code": 130200, "pid": 220100, "id": 594, "area_id": 220122 }, { "area_name": "榆树市", "pinyin": "Yushu", "level": 3, "area_code": 431, "post_code": 130400, "pid": 220100, "id": 595, "area_id": 220182 }, { "area_name": "德惠市", "pinyin": "Dehui", "level": 3, "area_code": 431, "post_code": 130300, "pid": 220100, "id": 596, "area_id": 220183 }, { "area_name": "吉林市", "pinyin": "Jilin", "level": 2, "area_code": 432, "post_code": 132011, "pid": 220000, "id": 597, "area_id": 220200 }, { "area_name": "昌邑区", "pinyin": "Changyi", "level": 3, "area_code": 432, "post_code": 132002, "pid": 220200, "id": 598, "area_id": 220202 }, { "area_name": "龙潭区", "pinyin": "Longtan", "level": 3, "area_code": 432, "post_code": 132021, "pid": 220200, "id": 599, "area_id": 220203 }, { "area_name": "船营区", "pinyin": "Chuanying", "level": 3, "area_code": 432, "post_code": 132011, "pid": 220200, "id": 600, "area_id": 220204 }, { "area_name": "丰满区", "pinyin": "Fengman", "level": 3, "area_code": 432, "post_code": 132013, "pid": 220200, "id": 601, "area_id": 220211 }, { "area_name": "永吉县", "pinyin": "Yongji", "level": 3, "area_code": 432, "post_code": 132200, "pid": 220200, "id": 602, "area_id": 220221 }, { "area_name": "蛟河市", "pinyin": "Jiaohe", "level": 3, "area_code": 432, "post_code": 132500, "pid": 220200, "id": 603, "area_id": 220281 }, { "area_name": "桦甸市", "pinyin": "Huadian", "level": 3, "area_code": 432, "post_code": 132400, "pid": 220200, "id": 604, "area_id": 220282 }, { "area_name": "舒兰市", "pinyin": "Shulan", "level": 3, "area_code": 432, "post_code": 132600, "pid": 220200, "id": 605, "area_id": 220283 }, { "area_name": "磐石市", "pinyin": "Panshi", "level": 3, "area_code": 432, "post_code": 132300, "pid": 220200, "id": 606, "area_id": 220284 }, { "area_name": "四平市", "pinyin": "Siping", "level": 2, "area_code": 434, "post_code": 136000, "pid": 220000, "id": 607, "area_id": 220300 }, { "area_name": "铁西区", "pinyin": "Tiexi", "level": 3, "area_code": 434, "post_code": 136000, "pid": 220300, "id": 608, "area_id": 220302 }, { "area_name": "铁东区", "pinyin": "Tiedong", "level": 3, "area_code": 434, "post_code": 136001, "pid": 220300, "id": 609, "area_id": 220303 }, { "area_name": "梨树县", "pinyin": "Lishu", "level": 3, "area_code": 434, "post_code": 136500, "pid": 220300, "id": 610, "area_id": 220322 }, { "area_name": "伊通满族自治县", "pinyin": "Yitong", "level": 3, "area_code": 434, "post_code": 130700, "pid": 220300, "id": 611, "area_id": 220323 }, { "area_name": "公主岭市", "pinyin": "Gongzhuling", "level": 3, "area_code": 434, "post_code": 136100, "pid": 220300, "id": 612, "area_id": 220381 }, { "area_name": "双辽市", "pinyin": "Shuangliao", "level": 3, "area_code": 434, "post_code": 136400, "pid": 220300, "id": 613, "area_id": 220382 }, { "area_name": "辽源市", "pinyin": "Liaoyuan", "level": 2, "area_code": 437, "post_code": 136200, "pid": 220000, "id": 614, "area_id": 220400 }, { "area_name": "龙山区", "pinyin": "Longshan", "level": 3, "area_code": 437, "post_code": 136200, "pid": 220400, "id": 615, "area_id": 220402 }, { "area_name": "西安区", "pinyin": "Xi'an", "level": 3, "area_code": 437, "post_code": 136201, "pid": 220400, "id": 616, "area_id": 220403 }, { "area_name": "东丰县", "pinyin": "Dongfeng", "level": 3, "area_code": 437, "post_code": 136300, "pid": 220400, "id": 617, "area_id": 220421 }, { "area_name": "东辽县", "pinyin": "Dongliao", "level": 3, "area_code": 437, "post_code": 136600, "pid": 220400, "id": 618, "area_id": 220422 }, { "area_name": "通化市", "pinyin": "Tonghua", "level": 2, "area_code": 435, "post_code": 134001, "pid": 220000, "id": 619, "area_id": 220500 }, { "area_name": "东昌区", "pinyin": "Dongchang", "level": 3, "area_code": 435, "post_code": 134001, "pid": 220500, "id": 620, "area_id": 220502 }, { "area_name": "二道江区", "pinyin": "Erdaojiang", "level": 3, "area_code": 435, "post_code": 134003, "pid": 220500, "id": 621, "area_id": 220503 }, { "area_name": "通化县", "pinyin": "Tonghua", "level": 3, "area_code": 435, "post_code": 134100, "pid": 220500, "id": 622, "area_id": 220521 }, { "area_name": "辉南县", "pinyin": "Huinan", "level": 3, "area_code": 435, "post_code": 135100, "pid": 220500, "id": 623, "area_id": 220523 }, { "area_name": "柳河县", "pinyin": "Liuhe", "level": 3, "area_code": 435, "post_code": 135300, "pid": 220500, "id": 624, "area_id": 220524 }, { "area_name": "梅河口市", "pinyin": "Meihekou", "level": 3, "area_code": 435, "post_code": 135000, "pid": 220500, "id": 625, "area_id": 220581 }, { "area_name": "集安市", "pinyin": "Ji'an", "level": 3, "area_code": 435, "post_code": 134200, "pid": 220500, "id": 626, "area_id": 220582 }, { "area_name": "白山市", "pinyin": "Baishan", "level": 2, "area_code": 439, "post_code": 134300, "pid": 220000, "id": 627, "area_id": 220600 }, { "area_name": "浑江区", "pinyin": "Hunjiang", "level": 3, "area_code": 439, "post_code": 134300, "pid": 220600, "id": 628, "area_id": 220602 }, { "area_name": "江源区", "pinyin": "Jiangyuan", "level": 3, "area_code": 439, "post_code": 134700, "pid": 220600, "id": 629, "area_id": 220605 }, { "area_name": "抚松县", "pinyin": "Fusong", "level": 3, "area_code": 439, "post_code": 134500, "pid": 220600, "id": 630, "area_id": 220621 }, { "area_name": "靖宇县", "pinyin": "Jingyu", "level": 3, "area_code": 439, "post_code": 135200, "pid": 220600, "id": 631, "area_id": 220622 }, { "area_name": "长白朝鲜族自治县", "pinyin": "Changbai", "level": 3, "area_code": 439, "post_code": 134400, "pid": 220600, "id": 632, "area_id": 220623 }, { "area_name": "临江市", "pinyin": "Linjiang", "level": 3, "area_code": 439, "post_code": 134600, "pid": 220600, "id": 633, "area_id": 220681 }, { "area_name": "松原市", "pinyin": "Songyuan", "level": 2, "area_code": 438, "post_code": 138000, "pid": 220000, "id": 634, "area_id": 220700 }, { "area_name": "宁江区", "pinyin": "Ningjiang", "level": 3, "area_code": 438, "post_code": 138000, "pid": 220700, "id": 635, "area_id": 220702 }, { "area_name": "前郭尔罗斯蒙古族自治县", "pinyin": "Qianguoerluosi", "level": 3, "area_code": 438, "post_code": 138000, "pid": 220700, "id": 636, "area_id": 220721 }, { "area_name": "长岭县", "pinyin": "Changling", "level": 3, "area_code": 438, "post_code": 131500, "pid": 220700, "id": 637, "area_id": 220722 }, { "area_name": "乾安县", "pinyin": "Qian'an", "level": 3, "area_code": 438, "post_code": 131400, "pid": 220700, "id": 638, "area_id": 220723 }, { "area_name": "扶余市", "pinyin": "Fuyu", "level": 3, "area_code": 438, "post_code": 131200, "pid": 220700, "id": 639, "area_id": 220781 }, { "area_name": "白城市", "pinyin": "Baicheng", "level": 2, "area_code": 436, "post_code": 137000, "pid": 220000, "id": 640, "area_id": 220800 }, { "area_name": "洮北区", "pinyin": "Taobei", "level": 3, "area_code": 436, "post_code": 137000, "pid": 220800, "id": 641, "area_id": 220802 }, { "area_name": "镇赉县", "pinyin": "Zhenlai", "level": 3, "area_code": 436, "post_code": 137300, "pid": 220800, "id": 642, "area_id": 220821 }, { "area_name": "通榆县", "pinyin": "Tongyu", "level": 3, "area_code": 436, "post_code": 137200, "pid": 220800, "id": 643, "area_id": 220822 }, { "area_name": "洮南市", "pinyin": "Taonan", "level": 3, "area_code": 436, "post_code": 137100, "pid": 220800, "id": 644, "area_id": 220881 }, { "area_name": "大安市", "pinyin": "Da'an", "level": 3, "area_code": 436, "post_code": 131300, "pid": 220800, "id": 645, "area_id": 220882 }, { "area_name": "延边朝鲜族自治州", "pinyin": "Yanbian", "level": 2, "area_code": 433, "post_code": 133000, "pid": 220000, "id": 646, "area_id": 222400 }, { "area_name": "延吉市", "pinyin": "Yanji", "level": 3, "area_code": 433, "post_code": 133000, "pid": 222400, "id": 647, "area_id": 222401 }, { "area_name": "图们市", "pinyin": "Tumen", "level": 3, "area_code": 433, "post_code": 133100, "pid": 222400, "id": 648, "area_id": 222402 }, { "area_name": "敦化市", "pinyin": "Dunhua", "level": 3, "area_code": 433, "post_code": 133700, "pid": 222400, "id": 649, "area_id": 222403 }, { "area_name": "珲春市", "pinyin": "Hunchun", "level": 3, "area_code": 433, "post_code": 133300, "pid": 222400, "id": 650, "area_id": 222404 }, { "area_name": "龙井市", "pinyin": "Longjing", "level": 3, "area_code": 433, "post_code": 133400, "pid": 222400, "id": 651, "area_id": 222405 }, { "area_name": "和龙市", "pinyin": "Helong", "level": 3, "area_code": 433, "post_code": 133500, "pid": 222400, "id": 652, "area_id": 222406 }, { "area_name": "汪清县", "pinyin": "Wangqing", "level": 3, "area_code": 433, "post_code": 133200, "pid": 222400, "id": 653, "area_id": 222424 }, { "area_name": "安图县", "pinyin": "Antu", "level": 3, "area_code": 433, "post_code": 133600, "pid": 222400, "id": 654, "area_id": 222426 }, { "area_name": "黑龙江省", "pinyin": "Heilongjiang", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 655, "area_id": 230000 }, { "area_name": "哈尔滨市", "pinyin": "Harbin", "level": 2, "area_code": 451, "post_code": 150010, "pid": 230000, "id": 656, "area_id": 230100 }, { "area_name": "道里区", "pinyin": "Daoli", "level": 3, "area_code": 451, "post_code": 150010, "pid": 230100, "id": 657, "area_id": 230102 }, { "area_name": "南岗区", "pinyin": "Nangang", "level": 3, "area_code": 451, "post_code": 150006, "pid": 230100, "id": 658, "area_id": 230103 }, { "area_name": "道外区", "pinyin": "Daowai", "level": 3, "area_code": 451, "post_code": 150020, "pid": 230100, "id": 659, "area_id": 230104 }, { "area_name": "平房区", "pinyin": "Pingfang", "level": 3, "area_code": 451, "post_code": 150060, "pid": 230100, "id": 660, "area_id": 230108 }, { "area_name": "松北区", "pinyin": "Songbei", "level": 3, "area_code": 451, "post_code": 150028, "pid": 230100, "id": 661, "area_id": 230109 }, { "area_name": "香坊区", "pinyin": "Xiangfang", "level": 3, "area_code": 451, "post_code": 150036, "pid": 230100, "id": 662, "area_id": 230110 }, { "area_name": "呼兰区", "pinyin": "Hulan", "level": 3, "area_code": 451, "post_code": 150500, "pid": 230100, "id": 663, "area_id": 230111 }, { "area_name": "阿城区", "pinyin": "A'cheng", "level": 3, "area_code": 451, "post_code": 150300, "pid": 230100, "id": 664, "area_id": 230112 }, { "area_name": "双城区", "pinyin": "Shuangcheng", "level": 3, "area_code": 451, "post_code": 150100, "pid": 230100, "id": 665, "area_id": 230113 }, { "area_name": "依兰县", "pinyin": "Yilan", "level": 3, "area_code": 451, "post_code": 154800, "pid": 230100, "id": 666, "area_id": 230123 }, { "area_name": "方正县", "pinyin": "Fangzheng", "level": 3, "area_code": 451, "post_code": 150800, "pid": 230100, "id": 667, "area_id": 230124 }, { "area_name": "宾县", "pinyin": "Binxian", "level": 3, "area_code": 451, "post_code": 150400, "pid": 230100, "id": 668, "area_id": 230125 }, { "area_name": "巴彦县", "pinyin": "Bayan", "level": 3, "area_code": 451, "post_code": 151800, "pid": 230100, "id": 669, "area_id": 230126 }, { "area_name": "木兰县", "pinyin": "Mulan", "level": 3, "area_code": 451, "post_code": 151900, "pid": 230100, "id": 670, "area_id": 230127 }, { "area_name": "通河县", "pinyin": "Tonghe", "level": 3, "area_code": 451, "post_code": 150900, "pid": 230100, "id": 671, "area_id": 230128 }, { "area_name": "延寿县", "pinyin": "Yanshou", "level": 3, "area_code": 451, "post_code": 150700, "pid": 230100, "id": 672, "area_id": 230129 }, { "area_name": "尚志市", "pinyin": "Shangzhi", "level": 3, "area_code": 451, "post_code": 150600, "pid": 230100, "id": 673, "area_id": 230183 }, { "area_name": "五常市", "pinyin": "Wuchang", "level": 3, "area_code": 451, "post_code": 150200, "pid": 230100, "id": 674, "area_id": 230184 }, { "area_name": "齐齐哈尔市", "pinyin": "Qiqihar", "level": 2, "area_code": 452, "post_code": 161005, "pid": 230000, "id": 675, "area_id": 230200 }, { "area_name": "龙沙区", "pinyin": "Longsha", "level": 3, "area_code": 452, "post_code": 161000, "pid": 230200, "id": 676, "area_id": 230202 }, { "area_name": "建华区", "pinyin": "Jianhua", "level": 3, "area_code": 452, "post_code": 161006, "pid": 230200, "id": 677, "area_id": 230203 }, { "area_name": "铁锋区", "pinyin": "Tiefeng", "level": 3, "area_code": 452, "post_code": 161000, "pid": 230200, "id": 678, "area_id": 230204 }, { "area_name": "昂昂溪区", "pinyin": "Angangxi", "level": 3, "area_code": 452, "post_code": 161031, "pid": 230200, "id": 679, "area_id": 230205 }, { "area_name": "富拉尔基区", "pinyin": "Fulaerji", "level": 3, "area_code": 452, "post_code": 161041, "pid": 230200, "id": 680, "area_id": 230206 }, { "area_name": "碾子山区", "pinyin": "Nianzishan", "level": 3, "area_code": 452, "post_code": 161046, "pid": 230200, "id": 681, "area_id": 230207 }, { "area_name": "梅里斯达斡尔族区", "pinyin": "Meilisi", "level": 3, "area_code": 452, "post_code": 161021, "pid": 230200, "id": 682, "area_id": 230208 }, { "area_name": "龙江县", "pinyin": "Longjiang", "level": 3, "area_code": 452, "post_code": 161100, "pid": 230200, "id": 683, "area_id": 230221 }, { "area_name": "依安县", "pinyin": "Yi'an", "level": 3, "area_code": 452, "post_code": 161500, "pid": 230200, "id": 684, "area_id": 230223 }, { "area_name": "泰来县", "pinyin": "Tailai", "level": 3, "area_code": 452, "post_code": 162400, "pid": 230200, "id": 685, "area_id": 230224 }, { "area_name": "甘南县", "pinyin": "Gannan", "level": 3, "area_code": 452, "post_code": 162100, "pid": 230200, "id": 686, "area_id": 230225 }, { "area_name": "富裕县", "pinyin": "Fuyu", "level": 3, "area_code": 452, "post_code": 161200, "pid": 230200, "id": 687, "area_id": 230227 }, { "area_name": "克山县", "pinyin": "Keshan", "level": 3, "area_code": 452, "post_code": 161600, "pid": 230200, "id": 688, "area_id": 230229 }, { "area_name": "克东县", "pinyin": "Kedong", "level": 3, "area_code": 452, "post_code": 164800, "pid": 230200, "id": 689, "area_id": 230230 }, { "area_name": "拜泉县", "pinyin": "Baiquan", "level": 3, "area_code": 452, "post_code": 164700, "pid": 230200, "id": 690, "area_id": 230231 }, { "area_name": "讷河市", "pinyin": "Nehe", "level": 3, "area_code": 452, "post_code": 161300, "pid": 230200, "id": 691, "area_id": 230281 }, { "area_name": "鸡西市", "pinyin": "Jixi", "level": 2, "area_code": 467, "post_code": 158100, "pid": 230000, "id": 692, "area_id": 230300 }, { "area_name": "鸡冠区", "pinyin": "Jiguan", "level": 3, "area_code": 467, "post_code": 158100, "pid": 230300, "id": 693, "area_id": 230302 }, { "area_name": "恒山区", "pinyin": "Hengshan", "level": 3, "area_code": 467, "post_code": 158130, "pid": 230300, "id": 694, "area_id": 230303 }, { "area_name": "滴道区", "pinyin": "Didao", "level": 3, "area_code": 467, "post_code": 158150, "pid": 230300, "id": 695, "area_id": 230304 }, { "area_name": "梨树区", "pinyin": "Lishu", "level": 3, "area_code": 467, "post_code": 158160, "pid": 230300, "id": 696, "area_id": 230305 }, { "area_name": "城子河区", "pinyin": "Chengzihe", "level": 3, "area_code": 467, "post_code": 158170, "pid": 230300, "id": 697, "area_id": 230306 }, { "area_name": "麻山区", "pinyin": "Mashan", "level": 3, "area_code": 467, "post_code": 158180, "pid": 230300, "id": 698, "area_id": 230307 }, { "area_name": "鸡东县", "pinyin": "Jidong", "level": 3, "area_code": 467, "post_code": 158200, "pid": 230300, "id": 699, "area_id": 230321 }, { "area_name": "虎林市", "pinyin": "Hulin", "level": 3, "area_code": 467, "post_code": 158400, "pid": 230300, "id": 700, "area_id": 230381 }, { "area_name": "密山市", "pinyin": "Mishan", "level": 3, "area_code": 467, "post_code": 158300, "pid": 230300, "id": 701, "area_id": 230382 }, { "area_name": "鹤岗市", "pinyin": "Hegang", "level": 2, "area_code": 468, "post_code": 154100, "pid": 230000, "id": 702, "area_id": 230400 }, { "area_name": "向阳区", "pinyin": "Xiangyang", "level": 3, "area_code": 468, "post_code": 154100, "pid": 230400, "id": 703, "area_id": 230402 }, { "area_name": "工农区", "pinyin": "Gongnong", "level": 3, "area_code": 468, "post_code": 154101, "pid": 230400, "id": 704, "area_id": 230403 }, { "area_name": "南山区", "pinyin": "Nanshan", "level": 3, "area_code": 468, "post_code": 154104, "pid": 230400, "id": 705, "area_id": 230404 }, { "area_name": "兴安区", "pinyin": "Xing'an", "level": 3, "area_code": 468, "post_code": 154102, "pid": 230400, "id": 706, "area_id": 230405 }, { "area_name": "东山区", "pinyin": "Dongshan", "level": 3, "area_code": 468, "post_code": 154106, "pid": 230400, "id": 707, "area_id": 230406 }, { "area_name": "兴山区", "pinyin": "Xingshan", "level": 3, "area_code": 468, "post_code": 154105, "pid": 230400, "id": 708, "area_id": 230407 }, { "area_name": "萝北县", "pinyin": "Luobei", "level": 3, "area_code": 468, "post_code": 154200, "pid": 230400, "id": 709, "area_id": 230421 }, { "area_name": "绥滨县", "pinyin": "Suibin", "level": 3, "area_code": 468, "post_code": 156200, "pid": 230400, "id": 710, "area_id": 230422 }, { "area_name": "双鸭山市", "pinyin": "Shuangyashan", "level": 2, "area_code": 469, "post_code": 155100, "pid": 230000, "id": 711, "area_id": 230500 }, { "area_name": "尖山区", "pinyin": "Jianshan", "level": 3, "area_code": 469, "post_code": 155100, "pid": 230500, "id": 712, "area_id": 230502 }, { "area_name": "岭东区", "pinyin": "Lingdong", "level": 3, "area_code": 469, "post_code": 155120, "pid": 230500, "id": 713, "area_id": 230503 }, { "area_name": "四方台区", "pinyin": "Sifangtai", "level": 3, "area_code": 469, "post_code": 155130, "pid": 230500, "id": 714, "area_id": 230505 }, { "area_name": "宝山区", "pinyin": "Baoshan", "level": 3, "area_code": 469, "post_code": 155131, "pid": 230500, "id": 715, "area_id": 230506 }, { "area_name": "集贤县", "pinyin": "Jixian", "level": 3, "area_code": 469, "post_code": 155900, "pid": 230500, "id": 716, "area_id": 230521 }, { "area_name": "友谊县", "pinyin": "Youyi", "level": 3, "area_code": 469, "post_code": 155800, "pid": 230500, "id": 717, "area_id": 230522 }, { "area_name": "宝清县", "pinyin": "Baoqing", "level": 3, "area_code": 469, "post_code": 155600, "pid": 230500, "id": 718, "area_id": 230523 }, { "area_name": "饶河县", "pinyin": "Raohe", "level": 3, "area_code": 469, "post_code": 155700, "pid": 230500, "id": 719, "area_id": 230524 }, { "area_name": "大庆市", "pinyin": "Daqing", "level": 2, "area_code": 459, "post_code": 163000, "pid": 230000, "id": 720, "area_id": 230600 }, { "area_name": "萨尔图区", "pinyin": "Saertu", "level": 3, "area_code": 459, "post_code": 163001, "pid": 230600, "id": 721, "area_id": 230602 }, { "area_name": "龙凤区", "pinyin": "Longfeng", "level": 3, "area_code": 459, "post_code": 163711, "pid": 230600, "id": 722, "area_id": 230603 }, { "area_name": "让胡路区", "pinyin": "Ranghulu", "level": 3, "area_code": 459, "post_code": 163712, "pid": 230600, "id": 723, "area_id": 230604 }, { "area_name": "红岗区", "pinyin": "Honggang", "level": 3, "area_code": 459, "post_code": 163511, "pid": 230600, "id": 724, "area_id": 230605 }, { "area_name": "大同区", "pinyin": "Datong", "level": 3, "area_code": 459, "post_code": 163515, "pid": 230600, "id": 725, "area_id": 230606 }, { "area_name": "肇州县", "pinyin": "Zhaozhou", "level": 3, "area_code": 459, "post_code": 166400, "pid": 230600, "id": 726, "area_id": 230621 }, { "area_name": "肇源县", "pinyin": "Zhaoyuan", "level": 3, "area_code": 459, "post_code": 166500, "pid": 230600, "id": 727, "area_id": 230622 }, { "area_name": "林甸县", "pinyin": "Lindian", "level": 3, "area_code": 459, "post_code": 166300, "pid": 230600, "id": 728, "area_id": 230623 }, { "area_name": "杜尔伯特蒙古族自治县", "pinyin": "Duerbote", "level": 3, "area_code": 459, "post_code": 166200, "pid": 230600, "id": 729, "area_id": 230624 }, { "area_name": "伊春市", "pinyin": "Yichun", "level": 2, "area_code": 458, "post_code": 153000, "pid": 230000, "id": 730, "area_id": 230700 }, { "area_name": "伊春区", "pinyin": "Yichun", "level": 3, "area_code": 458, "post_code": 153000, "pid": 230700, "id": 731, "area_id": 230702 }, { "area_name": "南岔区", "pinyin": "Nancha", "level": 3, "area_code": 458, "post_code": 153100, "pid": 230700, "id": 732, "area_id": 230703 }, { "area_name": "友好区", "pinyin": "Youhao", "level": 3, "area_code": 458, "post_code": 153031, "pid": 230700, "id": 733, "area_id": 230704 }, { "area_name": "西林区", "pinyin": "Xilin", "level": 3, "area_code": 458, "post_code": 153025, "pid": 230700, "id": 734, "area_id": 230705 }, { "area_name": "翠峦区", "pinyin": "Cuiluan", "level": 3, "area_code": 458, "post_code": 153013, "pid": 230700, "id": 735, "area_id": 230706 }, { "area_name": "新青区", "pinyin": "Xinqing", "level": 3, "area_code": 458, "post_code": 153036, "pid": 230700, "id": 736, "area_id": 230707 }, { "area_name": "美溪区", "pinyin": "Meixi", "level": 3, "area_code": 458, "post_code": 153021, "pid": 230700, "id": 737, "area_id": 230708 }, { "area_name": "金山屯区", "pinyin": "Jinshantun", "level": 3, "area_code": 458, "post_code": 153026, "pid": 230700, "id": 738, "area_id": 230709 }, { "area_name": "五营区", "pinyin": "Wuying", "level": 3, "area_code": 458, "post_code": 153033, "pid": 230700, "id": 739, "area_id": 230710 }, { "area_name": "乌马河区", "pinyin": "Wumahe", "level": 3, "area_code": 458, "post_code": 153011, "pid": 230700, "id": 740, "area_id": 230711 }, { "area_name": "汤旺河区", "pinyin": "Tangwanghe", "level": 3, "area_code": 458, "post_code": 153037, "pid": 230700, "id": 741, "area_id": 230712 }, { "area_name": "带岭区", "pinyin": "Dailing", "level": 3, "area_code": 458, "post_code": 153106, "pid": 230700, "id": 742, "area_id": 230713 }, { "area_name": "乌伊岭区", "pinyin": "Wuyiling", "level": 3, "area_code": 458, "post_code": 153038, "pid": 230700, "id": 743, "area_id": 230714 }, { "area_name": "红星区", "pinyin": "Hongxing", "level": 3, "area_code": 458, "post_code": 153035, "pid": 230700, "id": 744, "area_id": 230715 }, { "area_name": "上甘岭区", "pinyin": "Shangganling", "level": 3, "area_code": 458, "post_code": 153032, "pid": 230700, "id": 745, "area_id": 230716 }, { "area_name": "嘉荫县", "pinyin": "Jiayin", "level": 3, "area_code": 458, "post_code": 153200, "pid": 230700, "id": 746, "area_id": 230722 }, { "area_name": "铁力市", "pinyin": "Tieli", "level": 3, "area_code": 458, "post_code": 152500, "pid": 230700, "id": 747, "area_id": 230781 }, { "area_name": "佳木斯市", "pinyin": "Jiamusi", "level": 2, "area_code": 454, "post_code": 154002, "pid": 230000, "id": 748, "area_id": 230800 }, { "area_name": "向阳区", "pinyin": "Xiangyang", "level": 3, "area_code": 454, "post_code": 154002, "pid": 230800, "id": 749, "area_id": 230803 }, { "area_name": "前进区", "pinyin": "Qianjin", "level": 3, "area_code": 454, "post_code": 154002, "pid": 230800, "id": 750, "area_id": 230804 }, { "area_name": "东风区", "pinyin": "Dongfeng", "level": 3, "area_code": 454, "post_code": 154005, "pid": 230800, "id": 751, "area_id": 230805 }, { "area_name": "郊区", "pinyin": "Jiaoqu", "level": 3, "area_code": 454, "post_code": 154004, "pid": 230800, "id": 752, "area_id": 230811 }, { "area_name": "桦南县", "pinyin": "Huanan", "level": 3, "area_code": 454, "post_code": 154400, "pid": 230800, "id": 753, "area_id": 230822 }, { "area_name": "桦川县", "pinyin": "Huachuan", "level": 3, "area_code": 454, "post_code": 154300, "pid": 230800, "id": 754, "area_id": 230826 }, { "area_name": "汤原县", "pinyin": "Tangyuan", "level": 3, "area_code": 454, "post_code": 154700, "pid": 230800, "id": 755, "area_id": 230828 }, { "area_name": "抚远县", "pinyin": "Fuyuan", "level": 3, "area_code": 454, "post_code": 156500, "pid": 230800, "id": 756, "area_id": 230833 }, { "area_name": "同江市", "pinyin": "Tongjiang", "level": 3, "area_code": 454, "post_code": 156400, "pid": 230800, "id": 757, "area_id": 230881 }, { "area_name": "富锦市", "pinyin": "Fujin", "level": 3, "area_code": 454, "post_code": 156100, "pid": 230800, "id": 758, "area_id": 230882 }, { "area_name": "七台河市", "pinyin": "Qitaihe", "level": 2, "area_code": 464, "post_code": 154600, "pid": 230000, "id": 759, "area_id": 230900 }, { "area_name": "新兴区", "pinyin": "Xinxing", "level": 3, "area_code": 464, "post_code": 154604, "pid": 230900, "id": 760, "area_id": 230902 }, { "area_name": "桃山区", "pinyin": "Taoshan", "level": 3, "area_code": 464, "post_code": 154600, "pid": 230900, "id": 761, "area_id": 230903 }, { "area_name": "茄子河区", "pinyin": "Qiezihe", "level": 3, "area_code": 464, "post_code": 154622, "pid": 230900, "id": 762, "area_id": 230904 }, { "area_name": "勃利县", "pinyin": "Boli", "level": 3, "area_code": 464, "post_code": 154500, "pid": 230900, "id": 763, "area_id": 230921 }, { "area_name": "牡丹江市", "pinyin": "Mudanjiang", "level": 2, "area_code": 453, "post_code": 157000, "pid": 230000, "id": 764, "area_id": 231000 }, { "area_name": "东安区", "pinyin": "Dong'an", "level": 3, "area_code": 453, "post_code": 157000, "pid": 231000, "id": 765, "area_id": 231002 }, { "area_name": "阳明区", "pinyin": "Yangming", "level": 3, "area_code": 453, "post_code": 157013, "pid": 231000, "id": 766, "area_id": 231003 }, { "area_name": "爱民区", "pinyin": "Aimin", "level": 3, "area_code": 453, "post_code": 157009, "pid": 231000, "id": 767, "area_id": 231004 }, { "area_name": "西安区", "pinyin": "Xi'an", "level": 3, "area_code": 453, "post_code": 157000, "pid": 231000, "id": 768, "area_id": 231005 }, { "area_name": "东宁县", "pinyin": "Dongning", "level": 3, "area_code": 453, "post_code": 157200, "pid": 231000, "id": 769, "area_id": 231024 }, { "area_name": "林口县", "pinyin": "Linkou", "level": 3, "area_code": 453, "post_code": 157600, "pid": 231000, "id": 770, "area_id": 231025 }, { "area_name": "绥芬河市", "pinyin": "Suifenhe", "level": 3, "area_code": 453, "post_code": 157300, "pid": 231000, "id": 771, "area_id": 231081 }, { "area_name": "海林市", "pinyin": "Hailin", "level": 3, "area_code": 453, "post_code": 157100, "pid": 231000, "id": 772, "area_id": 231083 }, { "area_name": "宁安市", "pinyin": "Ning'an", "level": 3, "area_code": 453, "post_code": 157400, "pid": 231000, "id": 773, "area_id": 231084 }, { "area_name": "穆棱市", "pinyin": "Muling", "level": 3, "area_code": 453, "post_code": 157500, "pid": 231000, "id": 774, "area_id": 231085 }, { "area_name": "黑河市", "pinyin": "Heihe", "level": 2, "area_code": 456, "post_code": 164300, "pid": 230000, "id": 775, "area_id": 231100 }, { "area_name": "爱辉区", "pinyin": "Aihui", "level": 3, "area_code": 456, "post_code": 164300, "pid": 231100, "id": 776, "area_id": 231102 }, { "area_name": "嫩江县", "pinyin": "Nenjiang", "level": 3, "area_code": 456, "post_code": 161400, "pid": 231100, "id": 777, "area_id": 231121 }, { "area_name": "逊克县", "pinyin": "Xunke", "level": 3, "area_code": 456, "post_code": 164400, "pid": 231100, "id": 778, "area_id": 231123 }, { "area_name": "孙吴县", "pinyin": "Sunwu", "level": 3, "area_code": 456, "post_code": 164200, "pid": 231100, "id": 779, "area_id": 231124 }, { "area_name": "北安市", "pinyin": "Bei'an", "level": 3, "area_code": 456, "post_code": 164000, "pid": 231100, "id": 780, "area_id": 231181 }, { "area_name": "五大连池市", "pinyin": "Wudalianchi", "level": 3, "area_code": 456, "post_code": 164100, "pid": 231100, "id": 781, "area_id": 231182 }, { "area_name": "绥化市", "pinyin": "Suihua", "level": 2, "area_code": 455, "post_code": 152000, "pid": 230000, "id": 782, "area_id": 231200 }, { "area_name": "北林区", "pinyin": "Beilin", "level": 3, "area_code": 455, "post_code": 152000, "pid": 231200, "id": 783, "area_id": 231202 }, { "area_name": "望奎县", "pinyin": "Wangkui", "level": 3, "area_code": 455, "post_code": 152100, "pid": 231200, "id": 784, "area_id": 231221 }, { "area_name": "兰西县", "pinyin": "Lanxi", "level": 3, "area_code": 455, "post_code": 151500, "pid": 231200, "id": 785, "area_id": 231222 }, { "area_name": "青冈县", "pinyin": "Qinggang", "level": 3, "area_code": 455, "post_code": 151600, "pid": 231200, "id": 786, "area_id": 231223 }, { "area_name": "庆安县", "pinyin": "Qing'an", "level": 3, "area_code": 455, "post_code": 152400, "pid": 231200, "id": 787, "area_id": 231224 }, { "area_name": "明水县", "pinyin": "Mingshui", "level": 3, "area_code": 455, "post_code": 151700, "pid": 231200, "id": 788, "area_id": 231225 }, { "area_name": "绥棱县", "pinyin": "Suileng", "level": 3, "area_code": 455, "post_code": 152200, "pid": 231200, "id": 789, "area_id": 231226 }, { "area_name": "安达市", "pinyin": "Anda", "level": 3, "area_code": 455, "post_code": 151400, "pid": 231200, "id": 790, "area_id": 231281 }, { "area_name": "肇东市", "pinyin": "Zhaodong", "level": 3, "area_code": 455, "post_code": 151100, "pid": 231200, "id": 791, "area_id": 231282 }, { "area_name": "海伦市", "pinyin": "Hailun", "level": 3, "area_code": 455, "post_code": 152300, "pid": 231200, "id": 792, "area_id": 231283 }, { "area_name": "大兴安岭地区", "pinyin": "DaXingAnLing", "level": 2, "area_code": 457, "post_code": 165000, "pid": 230000, "id": 793, "area_id": 232700 }, { "area_name": "加格达奇区", "pinyin": "Jiagedaqi", "level": 3, "area_code": 457, "post_code": 165000, "pid": 232700, "id": 794, "area_id": 232701 }, { "area_name": "新林区", "pinyin": "Xinlin", "level": 3, "area_code": 457, "post_code": 165000, "pid": 232700, "id": 795, "area_id": 232702 }, { "area_name": "松岭区", "pinyin": "Songling", "level": 3, "area_code": 457, "post_code": 165000, "pid": 232700, "id": 796, "area_id": 232703 }, { "area_name": "呼中区", "pinyin": "Huzhong", "level": 3, "area_code": 457, "post_code": 165000, "pid": 232700, "id": 797, "area_id": 232704 }, { "area_name": "呼玛县", "pinyin": "Huma", "level": 3, "area_code": 457, "post_code": 165100, "pid": 232700, "id": 798, "area_id": 232721 }, { "area_name": "塔河县", "pinyin": "Tahe", "level": 3, "area_code": 457, "post_code": 165200, "pid": 232700, "id": 799, "area_id": 232722 }, { "area_name": "漠河县", "pinyin": "Mohe", "level": 3, "area_code": 457, "post_code": 165300, "pid": 232700, "id": 800, "area_id": 232723 }, { "area_name": "上海", "pinyin": "Shanghai", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 801, "area_id": 310000 }, { "area_name": "上海市", "pinyin": "Shanghai", "level": 2, "area_code": 21, "post_code": 200000, "pid": 310000, "id": 802, "area_id": 310100 }, { "area_name": "黄浦区", "pinyin": "Huangpu", "level": 3, "area_code": 21, "post_code": 200001, "pid": 310100, "id": 803, "area_id": 310101 }, { "area_name": "徐汇区", "pinyin": "Xuhui", "level": 3, "area_code": 21, "post_code": 200030, "pid": 310100, "id": 804, "area_id": 310104 }, { "area_name": "长宁区", "pinyin": "Changning", "level": 3, "area_code": 21, "post_code": 200050, "pid": 310100, "id": 805, "area_id": 310105 }, { "area_name": "静安区", "pinyin": "Jing'an", "level": 3, "area_code": 21, "post_code": 200040, "pid": 310100, "id": 806, "area_id": 310106 }, { "area_name": "普陀区", "pinyin": "Putuo", "level": 3, "area_code": 21, "post_code": 200333, "pid": 310100, "id": 807, "area_id": 310107 }, { "area_name": "闸北区", "pinyin": "Zhabei", "level": 3, "area_code": 21, "post_code": 200070, "pid": 310100, "id": 808, "area_id": 310108 }, { "area_name": "虹口区", "pinyin": "Hongkou", "level": 3, "area_code": 21, "post_code": 200086, "pid": 310100, "id": 809, "area_id": 310109 }, { "area_name": "杨浦区", "pinyin": "Yangpu", "level": 3, "area_code": 21, "post_code": 200082, "pid": 310100, "id": 810, "area_id": 310110 }, { "area_name": "闵行区", "pinyin": "Minhang", "level": 3, "area_code": 21, "post_code": 201100, "pid": 310100, "id": 811, "area_id": 310112 }, { "area_name": "宝山区", "pinyin": "Baoshan", "level": 3, "area_code": 21, "post_code": 201900, "pid": 310100, "id": 812, "area_id": 310113 }, { "area_name": "嘉定区", "pinyin": "Jiading", "level": 3, "area_code": 21, "post_code": 201800, "pid": 310100, "id": 813, "area_id": 310114 }, { "area_name": "浦东新区", "pinyin": "Pudong", "level": 3, "area_code": 21, "post_code": 200135, "pid": 310100, "id": 814, "area_id": 310115 }, { "area_name": "金山区", "pinyin": "Jinshan", "level": 3, "area_code": 21, "post_code": 200540, "pid": 310100, "id": 815, "area_id": 310116 }, { "area_name": "松江区", "pinyin": "Songjiang", "level": 3, "area_code": 21, "post_code": 201600, "pid": 310100, "id": 816, "area_id": 310117 }, { "area_name": "青浦区", "pinyin": "Qingpu", "level": 3, "area_code": 21, "post_code": 201700, "pid": 310100, "id": 817, "area_id": 310118 }, { "area_name": "奉贤区", "pinyin": "Fengxian", "level": 3, "area_code": 21, "post_code": 201400, "pid": 310100, "id": 818, "area_id": 310120 }, { "area_name": "崇明县", "pinyin": "Chongming", "level": 3, "area_code": 21, "post_code": 202150, "pid": 310100, "id": 819, "area_id": 310230 }, { "area_name": "江苏省", "pinyin": "Jiangsu", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 820, "area_id": 320000 }, { "area_name": "南京市", "pinyin": "Nanjing", "level": 2, "area_code": 25, "post_code": 210008, "pid": 320000, "id": 821, "area_id": 320100 }, { "area_name": "玄武区", "pinyin": "Xuanwu", "level": 3, "area_code": 25, "post_code": 210018, "pid": 320100, "id": 822, "area_id": 320102 }, { "area_name": "秦淮区", "pinyin": "Qinhuai", "level": 3, "area_code": 25, "post_code": 210001, "pid": 320100, "id": 823, "area_id": 320104 }, { "area_name": "建邺区", "pinyin": "Jianye", "level": 3, "area_code": 25, "post_code": 210004, "pid": 320100, "id": 824, "area_id": 320105 }, { "area_name": "鼓楼区", "pinyin": "Gulou", "level": 3, "area_code": 25, "post_code": 210009, "pid": 320100, "id": 825, "area_id": 320106 }, { "area_name": "浦口区", "pinyin": "Pukou", "level": 3, "area_code": 25, "post_code": 211800, "pid": 320100, "id": 826, "area_id": 320111 }, { "area_name": "栖霞区", "pinyin": "Qixia", "level": 3, "area_code": 25, "post_code": 210046, "pid": 320100, "id": 827, "area_id": 320113 }, { "area_name": "雨花台区", "pinyin": "Yuhuatai", "level": 3, "area_code": 25, "post_code": 210012, "pid": 320100, "id": 828, "area_id": 320114 }, { "area_name": "江宁区", "pinyin": "Jiangning", "level": 3, "area_code": 25, "post_code": 211100, "pid": 320100, "id": 829, "area_id": 320115 }, { "area_name": "六合区", "pinyin": "Luhe", "level": 3, "area_code": 25, "post_code": 211500, "pid": 320100, "id": 830, "area_id": 320116 }, { "area_name": "溧水区", "pinyin": "Lishui", "level": 3, "area_code": 25, "post_code": 211200, "pid": 320100, "id": 831, "area_id": 320117 }, { "area_name": "高淳区", "pinyin": "Gaochun", "level": 3, "area_code": 25, "post_code": 211300, "pid": 320100, "id": 832, "area_id": 320118 }, { "area_name": "无锡市", "pinyin": "Wuxi", "level": 2, "area_code": 510, "post_code": 214000, "pid": 320000, "id": 833, "area_id": 320200 }, { "area_name": "崇安区", "pinyin": "Chong'an", "level": 3, "area_code": 510, "post_code": 214001, "pid": 320200, "id": 834, "area_id": 320202 }, { "area_name": "南长区", "pinyin": "Nanchang", "level": 3, "area_code": 510, "post_code": 214021, "pid": 320200, "id": 835, "area_id": 320203 }, { "area_name": "北塘区", "pinyin": "Beitang", "level": 3, "area_code": 510, "post_code": 214044, "pid": 320200, "id": 836, "area_id": 320204 }, { "area_name": "锡山区", "pinyin": "Xishan", "level": 3, "area_code": 510, "post_code": 214101, "pid": 320200, "id": 837, "area_id": 320205 }, { "area_name": "惠山区", "pinyin": "Huishan", "level": 3, "area_code": 510, "post_code": 214174, "pid": 320200, "id": 838, "area_id": 320206 }, { "area_name": "滨湖区", "pinyin": "Binhu", "level": 3, "area_code": 510, "post_code": 214123, "pid": 320200, "id": 839, "area_id": 320211 }, { "area_name": "江阴市", "pinyin": "Jiangyin", "level": 3, "area_code": 510, "post_code": 214431, "pid": 320200, "id": 840, "area_id": 320281 }, { "area_name": "宜兴市", "pinyin": "Yixing", "level": 3, "area_code": 510, "post_code": 214200, "pid": 320200, "id": 841, "area_id": 320282 }, { "area_name": "徐州市", "pinyin": "Xuzhou", "level": 2, "area_code": 516, "post_code": 221003, "pid": 320000, "id": 842, "area_id": 320300 }, { "area_name": "鼓楼区", "pinyin": "Gulou", "level": 3, "area_code": 516, "post_code": 221005, "pid": 320300, "id": 843, "area_id": 320302 }, { "area_name": "云龙区", "pinyin": "Yunlong", "level": 3, "area_code": 516, "post_code": 221007, "pid": 320300, "id": 844, "area_id": 320303 }, { "area_name": "贾汪区", "pinyin": "Jiawang", "level": 3, "area_code": 516, "post_code": 221003, "pid": 320300, "id": 845, "area_id": 320305 }, { "area_name": "泉山区", "pinyin": "Quanshan", "level": 3, "area_code": 516, "post_code": 221006, "pid": 320300, "id": 846, "area_id": 320311 }, { "area_name": "铜山区", "pinyin": "Tongshan", "level": 3, "area_code": 516, "post_code": 221106, "pid": 320300, "id": 847, "area_id": 320312 }, { "area_name": "丰县", "pinyin": "Fengxian", "level": 3, "area_code": 516, "post_code": 221700, "pid": 320300, "id": 848, "area_id": 320321 }, { "area_name": "沛县", "pinyin": "Peixian", "level": 3, "area_code": 516, "post_code": 221600, "pid": 320300, "id": 849, "area_id": 320322 }, { "area_name": "睢宁县", "pinyin": "Suining", "level": 3, "area_code": 516, "post_code": 221200, "pid": 320300, "id": 850, "area_id": 320324 }, { "area_name": "新沂市", "pinyin": "Xinyi", "level": 3, "area_code": 516, "post_code": 221400, "pid": 320300, "id": 851, "area_id": 320381 }, { "area_name": "邳州市", "pinyin": "Pizhou", "level": 3, "area_code": 516, "post_code": 221300, "pid": 320300, "id": 852, "area_id": 320382 }, { "area_name": "常州市", "pinyin": "Changzhou", "level": 2, "area_code": 519, "post_code": 213000, "pid": 320000, "id": 853, "area_id": 320400 }, { "area_name": "天宁区", "pinyin": "Tianning", "level": 3, "area_code": 519, "post_code": 213000, "pid": 320400, "id": 854, "area_id": 320402 }, { "area_name": "钟楼区", "pinyin": "Zhonglou", "level": 3, "area_code": 519, "post_code": 213023, "pid": 320400, "id": 855, "area_id": 320404 }, { "area_name": "戚墅堰区", "pinyin": "Qishuyan", "level": 3, "area_code": 519, "post_code": 213025, "pid": 320400, "id": 856, "area_id": 320405 }, { "area_name": "新北区", "pinyin": "Xinbei", "level": 3, "area_code": 519, "post_code": 213022, "pid": 320400, "id": 857, "area_id": 320411 }, { "area_name": "武进区", "pinyin": "Wujin", "level": 3, "area_code": 519, "post_code": 213100, "pid": 320400, "id": 858, "area_id": 320412 }, { "area_name": "溧阳市", "pinyin": "Liyang", "level": 3, "area_code": 519, "post_code": 213300, "pid": 320400, "id": 859, "area_id": 320481 }, { "area_name": "金坛市", "pinyin": "Jintan", "level": 3, "area_code": 519, "post_code": 213200, "pid": 320400, "id": 860, "area_id": 320482 }, { "area_name": "苏州市", "pinyin": "Suzhou", "level": 2, "area_code": 512, "post_code": 215002, "pid": 320000, "id": 861, "area_id": 320500 }, { "area_name": "虎丘区", "pinyin": "Huqiu", "level": 3, "area_code": 512, "post_code": 215004, "pid": 320500, "id": 862, "area_id": 320505 }, { "area_name": "吴中区", "pinyin": "Wuzhong", "level": 3, "area_code": 512, "post_code": 215128, "pid": 320500, "id": 863, "area_id": 320506 }, { "area_name": "相城区", "pinyin": "Xiangcheng", "level": 3, "area_code": 512, "post_code": 215131, "pid": 320500, "id": 864, "area_id": 320507 }, { "area_name": "姑苏区", "pinyin": "Gusu", "level": 3, "area_code": 512, "post_code": 215031, "pid": 320500, "id": 865, "area_id": 320508 }, { "area_name": "吴江区", "pinyin": "Wujiang", "level": 3, "area_code": 512, "post_code": 215200, "pid": 320500, "id": 866, "area_id": 320509 }, { "area_name": "常熟市", "pinyin": "Changshu", "level": 3, "area_code": 512, "post_code": 215500, "pid": 320500, "id": 867, "area_id": 320581 }, { "area_name": "张家港市", "pinyin": "Zhangjiagang", "level": 3, "area_code": 512, "post_code": 215600, "pid": 320500, "id": 868, "area_id": 320582 }, { "area_name": "昆山市", "pinyin": "Kunshan", "level": 3, "area_code": 512, "post_code": 215300, "pid": 320500, "id": 869, "area_id": 320583 }, { "area_name": "太仓市", "pinyin": "Taicang", "level": 3, "area_code": 512, "post_code": 215400, "pid": 320500, "id": 870, "area_id": 320585 }, { "area_name": "南通市", "pinyin": "Nantong", "level": 2, "area_code": 513, "post_code": 226001, "pid": 320000, "id": 871, "area_id": 320600 }, { "area_name": "崇川区", "pinyin": "Chongchuan", "level": 3, "area_code": 513, "post_code": 226001, "pid": 320600, "id": 872, "area_id": 320602 }, { "area_name": "港闸区", "pinyin": "Gangzha", "level": 3, "area_code": 513, "post_code": 226001, "pid": 320600, "id": 873, "area_id": 320611 }, { "area_name": "通州区", "pinyin": "Tongzhou", "level": 3, "area_code": 513, "post_code": 226300, "pid": 320600, "id": 874, "area_id": 320612 }, { "area_name": "海安县", "pinyin": "Hai'an", "level": 3, "area_code": 513, "post_code": 226600, "pid": 320600, "id": 875, "area_id": 320621 }, { "area_name": "如东县", "pinyin": "Rudong", "level": 3, "area_code": 513, "post_code": 226400, "pid": 320600, "id": 876, "area_id": 320623 }, { "area_name": "启东市", "pinyin": "Qidong", "level": 3, "area_code": 513, "post_code": 226200, "pid": 320600, "id": 877, "area_id": 320681 }, { "area_name": "如皋市", "pinyin": "Rugao", "level": 3, "area_code": 513, "post_code": 226500, "pid": 320600, "id": 878, "area_id": 320682 }, { "area_name": "海门市", "pinyin": "Haimen", "level": 3, "area_code": 513, "post_code": 226100, "pid": 320600, "id": 879, "area_id": 320684 }, { "area_name": "连云港市", "pinyin": "Lianyungang", "level": 2, "area_code": 518, "post_code": 222002, "pid": 320000, "id": 880, "area_id": 320700 }, { "area_name": "连云区", "pinyin": "Lianyun", "level": 3, "area_code": 518, "post_code": 222042, "pid": 320700, "id": 881, "area_id": 320703 }, { "area_name": "海州区", "pinyin": "Haizhou", "level": 3, "area_code": 518, "post_code": 222003, "pid": 320700, "id": 882, "area_id": 320706 }, { "area_name": "赣榆区", "pinyin": "Ganyu", "level": 3, "area_code": 518, "post_code": 222100, "pid": 320700, "id": 883, "area_id": 320707 }, { "area_name": "东海县", "pinyin": "Donghai", "level": 3, "area_code": 518, "post_code": 222300, "pid": 320700, "id": 884, "area_id": 320722 }, { "area_name": "灌云县", "pinyin": "Guanyun", "level": 3, "area_code": 518, "post_code": 222200, "pid": 320700, "id": 885, "area_id": 320723 }, { "area_name": "灌南县", "pinyin": "Guannan", "level": 3, "area_code": 518, "post_code": 222500, "pid": 320700, "id": 886, "area_id": 320724 }, { "area_name": "淮安市", "pinyin": "Huai'an", "level": 2, "area_code": 517, "post_code": 223001, "pid": 320000, "id": 887, "area_id": 320800 }, { "area_name": "清河区", "pinyin": "Qinghe", "level": 3, "area_code": 517, "post_code": 223001, "pid": 320800, "id": 888, "area_id": 320802 }, { "area_name": "淮安区", "pinyin": "Huai'an", "level": 3, "area_code": 517, "post_code": 223200, "pid": 320800, "id": 889, "area_id": 320803 }, { "area_name": "淮阴区", "pinyin": "Huaiyin", "level": 3, "area_code": 517, "post_code": 223300, "pid": 320800, "id": 890, "area_id": 320804 }, { "area_name": "清浦区", "pinyin": "Qingpu", "level": 3, "area_code": 517, "post_code": 223002, "pid": 320800, "id": 891, "area_id": 320811 }, { "area_name": "涟水县", "pinyin": "Lianshui", "level": 3, "area_code": 517, "post_code": 223400, "pid": 320800, "id": 892, "area_id": 320826 }, { "area_name": "洪泽县", "pinyin": "Hongze", "level": 3, "area_code": 517, "post_code": 223100, "pid": 320800, "id": 893, "area_id": 320829 }, { "area_name": "盱眙县", "pinyin": "Xuyi", "level": 3, "area_code": 517, "post_code": 211700, "pid": 320800, "id": 894, "area_id": 320830 }, { "area_name": "金湖县", "pinyin": "Jinhu", "level": 3, "area_code": 517, "post_code": 211600, "pid": 320800, "id": 895, "area_id": 320831 }, { "area_name": "盐城市", "pinyin": "Yancheng", "level": 2, "area_code": 515, "post_code": 224005, "pid": 320000, "id": 896, "area_id": 320900 }, { "area_name": "亭湖区", "pinyin": "Tinghu", "level": 3, "area_code": 515, "post_code": 224005, "pid": 320900, "id": 897, "area_id": 320902 }, { "area_name": "盐都区", "pinyin": "Yandu", "level": 3, "area_code": 515, "post_code": 224055, "pid": 320900, "id": 898, "area_id": 320903 }, { "area_name": "响水县", "pinyin": "Xiangshui", "level": 3, "area_code": 515, "post_code": 224600, "pid": 320900, "id": 899, "area_id": 320921 }, { "area_name": "滨海县", "pinyin": "Binhai", "level": 3, "area_code": 515, "post_code": 224500, "pid": 320900, "id": 900, "area_id": 320922 }, { "area_name": "阜宁县", "pinyin": "Funing", "level": 3, "area_code": 515, "post_code": 224400, "pid": 320900, "id": 901, "area_id": 320923 }, { "area_name": "射阳县", "pinyin": "Sheyang", "level": 3, "area_code": 515, "post_code": 224300, "pid": 320900, "id": 902, "area_id": 320924 }, { "area_name": "建湖县", "pinyin": "Jianhu", "level": 3, "area_code": 515, "post_code": 224700, "pid": 320900, "id": 903, "area_id": 320925 }, { "area_name": "东台市", "pinyin": "Dongtai", "level": 3, "area_code": 515, "post_code": 224200, "pid": 320900, "id": 904, "area_id": 320981 }, { "area_name": "大丰市", "pinyin": "Dafeng", "level": 3, "area_code": 515, "post_code": 224100, "pid": 320900, "id": 905, "area_id": 320982 }, { "area_name": "扬州市", "pinyin": "Yangzhou", "level": 2, "area_code": 514, "post_code": 225002, "pid": 320000, "id": 906, "area_id": 321000 }, { "area_name": "广陵区", "pinyin": "Guangling", "level": 3, "area_code": 514, "post_code": 225002, "pid": 321000, "id": 907, "area_id": 321002 }, { "area_name": "邗江区", "pinyin": "Hanjiang", "level": 3, "area_code": 514, "post_code": 225002, "pid": 321000, "id": 908, "area_id": 321003 }, { "area_name": "江都区", "pinyin": "Jiangdu", "level": 3, "area_code": 514, "post_code": 225200, "pid": 321000, "id": 909, "area_id": 321012 }, { "area_name": "宝应县", "pinyin": "Baoying", "level": 3, "area_code": 514, "post_code": 225800, "pid": 321000, "id": 910, "area_id": 321023 }, { "area_name": "仪征市", "pinyin": "Yizheng", "level": 3, "area_code": 514, "post_code": 211400, "pid": 321000, "id": 911, "area_id": 321081 }, { "area_name": "高邮市", "pinyin": "Gaoyou", "level": 3, "area_code": 514, "post_code": 225600, "pid": 321000, "id": 912, "area_id": 321084 }, { "area_name": "镇江市", "pinyin": "Zhenjiang", "level": 2, "area_code": 511, "post_code": 212004, "pid": 320000, "id": 913, "area_id": 321100 }, { "area_name": "京口区", "pinyin": "Jingkou", "level": 3, "area_code": 511, "post_code": 212003, "pid": 321100, "id": 914, "area_id": 321102 }, { "area_name": "润州区", "pinyin": "Runzhou", "level": 3, "area_code": 511, "post_code": 212005, "pid": 321100, "id": 915, "area_id": 321111 }, { "area_name": "丹徒区", "pinyin": "Dantu", "level": 3, "area_code": 511, "post_code": 212028, "pid": 321100, "id": 916, "area_id": 321112 }, { "area_name": "丹阳市", "pinyin": "Danyang", "level": 3, "area_code": 511, "post_code": 212300, "pid": 321100, "id": 917, "area_id": 321181 }, { "area_name": "扬中市", "pinyin": "Yangzhong", "level": 3, "area_code": 511, "post_code": 212200, "pid": 321100, "id": 918, "area_id": 321182 }, { "area_name": "句容市", "pinyin": "Jurong", "level": 3, "area_code": 511, "post_code": 212400, "pid": 321100, "id": 919, "area_id": 321183 }, { "area_name": "泰州市", "pinyin": "Taizhou", "level": 2, "area_code": 523, "post_code": 225300, "pid": 320000, "id": 920, "area_id": 321200 }, { "area_name": "海陵区", "pinyin": "Hailing", "level": 3, "area_code": 523, "post_code": 225300, "pid": 321200, "id": 921, "area_id": 321202 }, { "area_name": "高港区", "pinyin": "Gaogang", "level": 3, "area_code": 523, "post_code": 225321, "pid": 321200, "id": 922, "area_id": 321203 }, { "area_name": "姜堰区", "pinyin": "Jiangyan", "level": 3, "area_code": 523, "post_code": 225500, "pid": 321200, "id": 923, "area_id": 321204 }, { "area_name": "兴化市", "pinyin": "Xinghua", "level": 3, "area_code": 523, "post_code": 225700, "pid": 321200, "id": 924, "area_id": 321281 }, { "area_name": "靖江市", "pinyin": "Jingjiang", "level": 3, "area_code": 523, "post_code": 214500, "pid": 321200, "id": 925, "area_id": 321282 }, { "area_name": "泰兴市", "pinyin": "Taixing", "level": 3, "area_code": 523, "post_code": 225400, "pid": 321200, "id": 926, "area_id": 321283 }, { "area_name": "宿迁市", "pinyin": "Suqian", "level": 2, "area_code": 527, "post_code": 223800, "pid": 320000, "id": 927, "area_id": 321300 }, { "area_name": "宿城区", "pinyin": "Sucheng", "level": 3, "area_code": 527, "post_code": 223800, "pid": 321300, "id": 928, "area_id": 321302 }, { "area_name": "宿豫区", "pinyin": "Suyu", "level": 3, "area_code": 527, "post_code": 223800, "pid": 321300, "id": 929, "area_id": 321311 }, { "area_name": "沭阳县", "pinyin": "Shuyang", "level": 3, "area_code": 527, "post_code": 223600, "pid": 321300, "id": 930, "area_id": 321322 }, { "area_name": "泗阳县", "pinyin": "Siyang", "level": 3, "area_code": 527, "post_code": 223700, "pid": 321300, "id": 931, "area_id": 321323 }, { "area_name": "泗洪县", "pinyin": "Sihong", "level": 3, "area_code": 527, "post_code": 223900, "pid": 321300, "id": 932, "area_id": 321324 }, { "area_name": "浙江省", "pinyin": "Zhejiang", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 933, "area_id": 330000 }, { "area_name": "杭州市", "pinyin": "Hangzhou", "level": 2, "area_code": 571, "post_code": 310026, "pid": 330000, "id": 934, "area_id": 330100 }, { "area_name": "上城区", "pinyin": "Shangcheng", "level": 3, "area_code": 571, "post_code": 310002, "pid": 330100, "id": 935, "area_id": 330102 }, { "area_name": "下城区", "pinyin": "Xiacheng", "level": 3, "area_code": 571, "post_code": 310006, "pid": 330100, "id": 936, "area_id": 330103 }, { "area_name": "江干区", "pinyin": "Jianggan", "level": 3, "area_code": 571, "post_code": 310016, "pid": 330100, "id": 937, "area_id": 330104 }, { "area_name": "拱墅区", "pinyin": "Gongshu", "level": 3, "area_code": 571, "post_code": 310011, "pid": 330100, "id": 938, "area_id": 330105 }, { "area_name": "西湖区", "pinyin": "Xihu", "level": 3, "area_code": 571, "post_code": 310013, "pid": 330100, "id": 939, "area_id": 330106 }, { "area_name": "滨江区", "pinyin": "Binjiang", "level": 3, "area_code": 571, "post_code": 310051, "pid": 330100, "id": 940, "area_id": 330108 }, { "area_name": "萧山区", "pinyin": "Xiaoshan", "level": 3, "area_code": 571, "post_code": 311200, "pid": 330100, "id": 941, "area_id": 330109 }, { "area_name": "余杭区", "pinyin": "Yuhang", "level": 3, "area_code": 571, "post_code": 311100, "pid": 330100, "id": 942, "area_id": 330110 }, { "area_name": "桐庐县", "pinyin": "Tonglu", "level": 3, "area_code": 571, "post_code": 311500, "pid": 330100, "id": 943, "area_id": 330122 }, { "area_name": "淳安县", "pinyin": "Chun'an", "level": 3, "area_code": 571, "post_code": 311700, "pid": 330100, "id": 944, "area_id": 330127 }, { "area_name": "建德市", "pinyin": "Jiande", "level": 3, "area_code": 571, "post_code": 311600, "pid": 330100, "id": 945, "area_id": 330182 }, { "area_name": "富阳区", "pinyin": "Fuyang", "level": 3, "area_code": 571, "post_code": 311400, "pid": 330100, "id": 946, "area_id": 330183 }, { "area_name": "临安市", "pinyin": "Lin'an", "level": 3, "area_code": 571, "post_code": 311300, "pid": 330100, "id": 947, "area_id": 330185 }, { "area_name": "宁波市", "pinyin": "Ningbo", "level": 2, "area_code": 574, "post_code": 315000, "pid": 330000, "id": 948, "area_id": 330200 }, { "area_name": "海曙区", "pinyin": "Haishu", "level": 3, "area_code": 574, "post_code": 315000, "pid": 330200, "id": 949, "area_id": 330203 }, { "area_name": "江东区", "pinyin": "Jiangdong", "level": 3, "area_code": 574, "post_code": 315040, "pid": 330200, "id": 950, "area_id": 330204 }, { "area_name": "江北区", "pinyin": "Jiangbei", "level": 3, "area_code": 574, "post_code": 315020, "pid": 330200, "id": 951, "area_id": 330205 }, { "area_name": "北仑区", "pinyin": "Beilun", "level": 3, "area_code": 574, "post_code": 315800, "pid": 330200, "id": 952, "area_id": 330206 }, { "area_name": "镇海区", "pinyin": "Zhenhai", "level": 3, "area_code": 574, "post_code": 315200, "pid": 330200, "id": 953, "area_id": 330211 }, { "area_name": "鄞州区", "pinyin": "Yinzhou", "level": 3, "area_code": 574, "post_code": 315100, "pid": 330200, "id": 954, "area_id": 330212 }, { "area_name": "象山县", "pinyin": "Xiangshan", "level": 3, "area_code": 574, "post_code": 315700, "pid": 330200, "id": 955, "area_id": 330225 }, { "area_name": "宁海县", "pinyin": "Ninghai", "level": 3, "area_code": 574, "post_code": 315600, "pid": 330200, "id": 956, "area_id": 330226 }, { "area_name": "余姚市", "pinyin": "Yuyao", "level": 3, "area_code": 574, "post_code": 315400, "pid": 330200, "id": 957, "area_id": 330281 }, { "area_name": "慈溪市", "pinyin": "Cixi", "level": 3, "area_code": 574, "post_code": 315300, "pid": 330200, "id": 958, "area_id": 330282 }, { "area_name": "奉化市", "pinyin": "Fenghua", "level": 3, "area_code": 574, "post_code": 315500, "pid": 330200, "id": 959, "area_id": 330283 }, { "area_name": "温州市", "pinyin": "Wenzhou", "level": 2, "area_code": 577, "post_code": 325000, "pid": 330000, "id": 960, "area_id": 330300 }, { "area_name": "鹿城区", "pinyin": "Lucheng", "level": 3, "area_code": 577, "post_code": 325000, "pid": 330300, "id": 961, "area_id": 330302 }, { "area_name": "龙湾区", "pinyin": "Longwan", "level": 3, "area_code": 577, "post_code": 325013, "pid": 330300, "id": 962, "area_id": 330303 }, { "area_name": "瓯海区", "pinyin": "Ouhai", "level": 3, "area_code": 577, "post_code": 325005, "pid": 330300, "id": 963, "area_id": 330304 }, { "area_name": "洞头县", "pinyin": "Dongtou", "level": 3, "area_code": 577, "post_code": 325700, "pid": 330300, "id": 964, "area_id": 330322 }, { "area_name": "永嘉县", "pinyin": "Yongjia", "level": 3, "area_code": 577, "post_code": 325100, "pid": 330300, "id": 965, "area_id": 330324 }, { "area_name": "平阳县", "pinyin": "Pingyang", "level": 3, "area_code": 577, "post_code": 325400, "pid": 330300, "id": 966, "area_id": 330326 }, { "area_name": "苍南县", "pinyin": "Cangnan", "level": 3, "area_code": 577, "post_code": 325800, "pid": 330300, "id": 967, "area_id": 330327 }, { "area_name": "文成县", "pinyin": "Wencheng", "level": 3, "area_code": 577, "post_code": 325300, "pid": 330300, "id": 968, "area_id": 330328 }, { "area_name": "泰顺县", "pinyin": "Taishun", "level": 3, "area_code": 577, "post_code": 325500, "pid": 330300, "id": 969, "area_id": 330329 }, { "area_name": "瑞安市", "pinyin": "Rui'an", "level": 3, "area_code": 577, "post_code": 325200, "pid": 330300, "id": 970, "area_id": 330381 }, { "area_name": "乐清市", "pinyin": "Yueqing", "level": 3, "area_code": 577, "post_code": 325600, "pid": 330300, "id": 971, "area_id": 330382 }, { "area_name": "嘉兴市", "pinyin": "Jiaxing", "level": 2, "area_code": 573, "post_code": 314000, "pid": 330000, "id": 972, "area_id": 330400 }, { "area_name": "南湖区", "pinyin": "Nanhu", "level": 3, "area_code": 573, "post_code": 314051, "pid": 330400, "id": 973, "area_id": 330402 }, { "area_name": "秀洲区", "pinyin": "Xiuzhou", "level": 3, "area_code": 573, "post_code": 314031, "pid": 330400, "id": 974, "area_id": 330411 }, { "area_name": "嘉善县", "pinyin": "Jiashan", "level": 3, "area_code": 573, "post_code": 314100, "pid": 330400, "id": 975, "area_id": 330421 }, { "area_name": "海盐县", "pinyin": "Haiyan", "level": 3, "area_code": 573, "post_code": 314300, "pid": 330400, "id": 976, "area_id": 330424 }, { "area_name": "海宁市", "pinyin": "Haining", "level": 3, "area_code": 573, "post_code": 314400, "pid": 330400, "id": 977, "area_id": 330481 }, { "area_name": "平湖市", "pinyin": "Pinghu", "level": 3, "area_code": 573, "post_code": 314200, "pid": 330400, "id": 978, "area_id": 330482 }, { "area_name": "桐乡市", "pinyin": "Tongxiang", "level": 3, "area_code": 573, "post_code": 314500, "pid": 330400, "id": 979, "area_id": 330483 }, { "area_name": "湖州市", "pinyin": "Huzhou", "level": 2, "area_code": 572, "post_code": 313000, "pid": 330000, "id": 980, "area_id": 330500 }, { "area_name": "吴兴区", "pinyin": "Wuxing", "level": 3, "area_code": 572, "post_code": 313000, "pid": 330500, "id": 981, "area_id": 330502 }, { "area_name": "南浔区", "pinyin": "Nanxun", "level": 3, "area_code": 572, "post_code": 313009, "pid": 330500, "id": 982, "area_id": 330503 }, { "area_name": "德清县", "pinyin": "Deqing", "level": 3, "area_code": 572, "post_code": 313200, "pid": 330500, "id": 983, "area_id": 330521 }, { "area_name": "长兴县", "pinyin": "Changxing", "level": 3, "area_code": 572, "post_code": 313100, "pid": 330500, "id": 984, "area_id": 330522 }, { "area_name": "安吉县", "pinyin": "Anji", "level": 3, "area_code": 572, "post_code": 313300, "pid": 330500, "id": 985, "area_id": 330523 }, { "area_name": "绍兴市", "pinyin": "Shaoxing", "level": 2, "area_code": 575, "post_code": 312000, "pid": 330000, "id": 986, "area_id": 330600 }, { "area_name": "越城区", "pinyin": "Yuecheng", "level": 3, "area_code": 575, "post_code": 312000, "pid": 330600, "id": 987, "area_id": 330602 }, { "area_name": "柯桥区", "pinyin": "Keqiao ", "level": 3, "area_code": 575, "post_code": 312030, "pid": 330600, "id": 988, "area_id": 330603 }, { "area_name": "上虞区", "pinyin": "Shangyu", "level": 3, "area_code": 575, "post_code": 312300, "pid": 330600, "id": 989, "area_id": 330604 }, { "area_name": "新昌县", "pinyin": "Xinchang", "level": 3, "area_code": 575, "post_code": 312500, "pid": 330600, "id": 990, "area_id": 330624 }, { "area_name": "诸暨市", "pinyin": "Zhuji", "level": 3, "area_code": 575, "post_code": 311800, "pid": 330600, "id": 991, "area_id": 330681 }, { "area_name": "嵊州市", "pinyin": "Shengzhou", "level": 3, "area_code": 575, "post_code": 312400, "pid": 330600, "id": 992, "area_id": 330683 }, { "area_name": "金华市", "pinyin": "Jinhua", "level": 2, "area_code": 579, "post_code": 321000, "pid": 330000, "id": 993, "area_id": 330700 }, { "area_name": "婺城区", "pinyin": "Wucheng", "level": 3, "area_code": 579, "post_code": 321000, "pid": 330700, "id": 994, "area_id": 330702 }, { "area_name": "金东区", "pinyin": "Jindong", "level": 3, "area_code": 579, "post_code": 321000, "pid": 330700, "id": 995, "area_id": 330703 }, { "area_name": "武义县", "pinyin": "Wuyi", "level": 3, "area_code": 579, "post_code": 321200, "pid": 330700, "id": 996, "area_id": 330723 }, { "area_name": "浦江县", "pinyin": "Pujiang", "level": 3, "area_code": 579, "post_code": 322200, "pid": 330700, "id": 997, "area_id": 330726 }, { "area_name": "磐安县", "pinyin": "Pan'an", "level": 3, "area_code": 579, "post_code": 322300, "pid": 330700, "id": 998, "area_id": 330727 }, { "area_name": "兰溪市", "pinyin": "Lanxi", "level": 3, "area_code": 579, "post_code": 321100, "pid": 330700, "id": 999, "area_id": 330781 }, { "area_name": "义乌市", "pinyin": "Yiwu", "level": 3, "area_code": 579, "post_code": 322000, "pid": 330700, "id": 1000, "area_id": 330782 }, { "area_name": "东阳市", "pinyin": "Dongyang", "level": 3, "area_code": 579, "post_code": 322100, "pid": 330700, "id": 1001, "area_id": 330783 }, { "area_name": "永康市", "pinyin": "Yongkang", "level": 3, "area_code": 579, "post_code": 321300, "pid": 330700, "id": 1002, "area_id": 330784 }, { "area_name": "衢州市", "pinyin": "Quzhou", "level": 2, "area_code": 570, "post_code": 324002, "pid": 330000, "id": 1003, "area_id": 330800 }, { "area_name": "柯城区", "pinyin": "Kecheng", "level": 3, "area_code": 570, "post_code": 324100, "pid": 330800, "id": 1004, "area_id": 330802 }, { "area_name": "衢江区", "pinyin": "Qujiang", "level": 3, "area_code": 570, "post_code": 324022, "pid": 330800, "id": 1005, "area_id": 330803 }, { "area_name": "常山县", "pinyin": "Changshan", "level": 3, "area_code": 570, "post_code": 324200, "pid": 330800, "id": 1006, "area_id": 330822 }, { "area_name": "开化县", "pinyin": "Kaihua", "level": 3, "area_code": 570, "post_code": 324300, "pid": 330800, "id": 1007, "area_id": 330824 }, { "area_name": "龙游县", "pinyin": "Longyou", "level": 3, "area_code": 570, "post_code": 324400, "pid": 330800, "id": 1008, "area_id": 330825 }, { "area_name": "江山市", "pinyin": "Jiangshan", "level": 3, "area_code": 570, "post_code": 324100, "pid": 330800, "id": 1009, "area_id": 330881 }, { "area_name": "舟山市", "pinyin": "Zhoushan", "level": 2, "area_code": 580, "post_code": 316000, "pid": 330000, "id": 1010, "area_id": 330900 }, { "area_name": "定海区", "pinyin": "Dinghai", "level": 3, "area_code": 580, "post_code": 316000, "pid": 330900, "id": 1011, "area_id": 330902 }, { "area_name": "普陀区", "pinyin": "Putuo", "level": 3, "area_code": 580, "post_code": 316100, "pid": 330900, "id": 1012, "area_id": 330903 }, { "area_name": "岱山县", "pinyin": "Daishan", "level": 3, "area_code": 580, "post_code": 316200, "pid": 330900, "id": 1013, "area_id": 330921 }, { "area_name": "嵊泗县", "pinyin": "Shengsi", "level": 3, "area_code": 580, "post_code": 202450, "pid": 330900, "id": 1014, "area_id": 330922 }, { "area_name": "台州市", "pinyin": "Taizhou", "level": 2, "area_code": 576, "post_code": 318000, "pid": 330000, "id": 1015, "area_id": 331000 }, { "area_name": "椒江区", "pinyin": "Jiaojiang", "level": 3, "area_code": 576, "post_code": 318000, "pid": 331000, "id": 1016, "area_id": 331002 }, { "area_name": "黄岩区", "pinyin": "Huangyan", "level": 3, "area_code": 576, "post_code": 318020, "pid": 331000, "id": 1017, "area_id": 331003 }, { "area_name": "路桥区", "pinyin": "Luqiao", "level": 3, "area_code": 576, "post_code": 318050, "pid": 331000, "id": 1018, "area_id": 331004 }, { "area_name": "玉环县", "pinyin": "Yuhuan", "level": 3, "area_code": 576, "post_code": 317600, "pid": 331000, "id": 1019, "area_id": 331021 }, { "area_name": "三门县", "pinyin": "Sanmen", "level": 3, "area_code": 576, "post_code": 317100, "pid": 331000, "id": 1020, "area_id": 331022 }, { "area_name": "天台县", "pinyin": "Tiantai", "level": 3, "area_code": 576, "post_code": 317200, "pid": 331000, "id": 1021, "area_id": 331023 }, { "area_name": "仙居县", "pinyin": "Xianju", "level": 3, "area_code": 576, "post_code": 317300, "pid": 331000, "id": 1022, "area_id": 331024 }, { "area_name": "温岭市", "pinyin": "Wenling", "level": 3, "area_code": 576, "post_code": 317500, "pid": 331000, "id": 1023, "area_id": 331081 }, { "area_name": "临海市", "pinyin": "Linhai", "level": 3, "area_code": 576, "post_code": 317000, "pid": 331000, "id": 1024, "area_id": 331082 }, { "area_name": "丽水市", "pinyin": "Lishui", "level": 2, "area_code": 578, "post_code": 323000, "pid": 330000, "id": 1025, "area_id": 331100 }, { "area_name": "莲都区", "pinyin": "Liandu", "level": 3, "area_code": 578, "post_code": 323000, "pid": 331100, "id": 1026, "area_id": 331102 }, { "area_name": "青田县", "pinyin": "Qingtian", "level": 3, "area_code": 578, "post_code": 323900, "pid": 331100, "id": 1027, "area_id": 331121 }, { "area_name": "缙云县", "pinyin": "Jinyun", "level": 3, "area_code": 578, "post_code": 321400, "pid": 331100, "id": 1028, "area_id": 331122 }, { "area_name": "遂昌县", "pinyin": "Suichang", "level": 3, "area_code": 578, "post_code": 323300, "pid": 331100, "id": 1029, "area_id": 331123 }, { "area_name": "松阳县", "pinyin": "Songyang", "level": 3, "area_code": 578, "post_code": 323400, "pid": 331100, "id": 1030, "area_id": 331124 }, { "area_name": "云和县", "pinyin": "Yunhe", "level": 3, "area_code": 578, "post_code": 323600, "pid": 331100, "id": 1031, "area_id": 331125 }, { "area_name": "庆元县", "pinyin": "Qingyuan", "level": 3, "area_code": 578, "post_code": 323800, "pid": 331100, "id": 1032, "area_id": 331126 }, { "area_name": "景宁畲族自治县", "pinyin": "Jingning", "level": 3, "area_code": 578, "post_code": 323500, "pid": 331100, "id": 1033, "area_id": 331127 }, { "area_name": "龙泉市", "pinyin": "Longquan", "level": 3, "area_code": 578, "post_code": 323700, "pid": 331100, "id": 1034, "area_id": 331181 }, { "area_name": "舟山群岛新区", "pinyin": "Zhoushan", "level": 2, "area_code": 580, "post_code": 316000, "pid": 330000, "id": 1035, "area_id": 331200 }, { "area_name": "金塘岛", "pinyin": "Jintang", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1036, "area_id": 331201 }, { "area_name": "六横岛", "pinyin": "Liuheng", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1037, "area_id": 331202 }, { "area_name": "衢山岛", "pinyin": "Qushan", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1038, "area_id": 331203 }, { "area_name": "舟山本岛西北部", "pinyin": "Zhoushan", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1039, "area_id": 331204 }, { "area_name": "岱山岛西南部", "pinyin": "Daishan", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1040, "area_id": 331205 }, { "area_name": "泗礁岛", "pinyin": "Sijiao", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1041, "area_id": 331206 }, { "area_name": "朱家尖岛", "pinyin": "Zhujiajian", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1042, "area_id": 331207 }, { "area_name": "洋山岛", "pinyin": "Yangshan", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1043, "area_id": 331208 }, { "area_name": "长涂岛", "pinyin": "Changtu", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1044, "area_id": 331209 }, { "area_name": "虾峙岛", "pinyin": "Xiazhi", "level": 3, "area_code": 580, "post_code": 316000, "pid": 331200, "id": 1045, "area_id": 331210 }, { "area_name": "安徽省", "pinyin": "Anhui", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1046, "area_id": 340000 }, { "area_name": "合肥市", "pinyin": "Hefei", "level": 2, "area_code": 551, "post_code": 230001, "pid": 340000, "id": 1047, "area_id": 340100 }, { "area_name": "瑶海区", "pinyin": "Yaohai", "level": 3, "area_code": 551, "post_code": 230011, "pid": 340100, "id": 1048, "area_id": 340102 }, { "area_name": "庐阳区", "pinyin": "Luyang", "level": 3, "area_code": 551, "post_code": 230001, "pid": 340100, "id": 1049, "area_id": 340103 }, { "area_name": "蜀山区", "pinyin": "Shushan", "level": 3, "area_code": 551, "post_code": 230031, "pid": 340100, "id": 1050, "area_id": 340104 }, { "area_name": "包河区", "pinyin": "Baohe", "level": 3, "area_code": 551, "post_code": 230041, "pid": 340100, "id": 1051, "area_id": 340111 }, { "area_name": "长丰县", "pinyin": "Changfeng", "level": 3, "area_code": 551, "post_code": 231100, "pid": 340100, "id": 1052, "area_id": 340121 }, { "area_name": "肥东县", "pinyin": "Feidong", "level": 3, "area_code": 551, "post_code": 231600, "pid": 340100, "id": 1053, "area_id": 340122 }, { "area_name": "肥西县", "pinyin": "Feixi", "level": 3, "area_code": 551, "post_code": 231200, "pid": 340100, "id": 1054, "area_id": 340123 }, { "area_name": "庐江县", "pinyin": "Lujiang", "level": 3, "area_code": 565, "post_code": 231500, "pid": 340100, "id": 1055, "area_id": 340124 }, { "area_name": "巢湖市", "pinyin": "Chaohu", "level": 3, "area_code": 565, "post_code": 238000, "pid": 340100, "id": 1056, "area_id": 340181 }, { "area_name": "芜湖市", "pinyin": "Wuhu", "level": 2, "area_code": 551, "post_code": 241000, "pid": 340000, "id": 1057, "area_id": 340200 }, { "area_name": "镜湖区", "pinyin": "Jinghu", "level": 3, "area_code": 553, "post_code": 241000, "pid": 340200, "id": 1058, "area_id": 340202 }, { "area_name": "弋江区", "pinyin": "Yijiang", "level": 3, "area_code": 553, "post_code": 241000, "pid": 340200, "id": 1059, "area_id": 340203 }, { "area_name": "鸠江区", "pinyin": "Jiujiang", "level": 3, "area_code": 553, "post_code": 241000, "pid": 340200, "id": 1060, "area_id": 340207 }, { "area_name": "三山区", "pinyin": "Sanshan", "level": 3, "area_code": 553, "post_code": 241000, "pid": 340200, "id": 1061, "area_id": 340208 }, { "area_name": "芜湖县", "pinyin": "Wuhu", "level": 3, "area_code": 553, "post_code": 241100, "pid": 340200, "id": 1062, "area_id": 340221 }, { "area_name": "繁昌县", "pinyin": "Fanchang", "level": 3, "area_code": 553, "post_code": 241200, "pid": 340200, "id": 1063, "area_id": 340222 }, { "area_name": "南陵县", "pinyin": "Nanling", "level": 3, "area_code": 553, "post_code": 242400, "pid": 340200, "id": 1064, "area_id": 340223 }, { "area_name": "无为县", "pinyin": "Wuwei", "level": 3, "area_code": 565, "post_code": 238300, "pid": 340200, "id": 1065, "area_id": 340225 }, { "area_name": "蚌埠市", "pinyin": "Bengbu", "level": 2, "area_code": 552, "post_code": 233000, "pid": 340000, "id": 1066, "area_id": 340300 }, { "area_name": "龙子湖区", "pinyin": "Longzihu", "level": 3, "area_code": 552, "post_code": 233000, "pid": 340300, "id": 1067, "area_id": 340302 }, { "area_name": "蚌山区", "pinyin": "Bengshan", "level": 3, "area_code": 552, "post_code": 233000, "pid": 340300, "id": 1068, "area_id": 340303 }, { "area_name": "禹会区", "pinyin": "Yuhui", "level": 3, "area_code": 552, "post_code": 233010, "pid": 340300, "id": 1069, "area_id": 340304 }, { "area_name": "淮上区", "pinyin": "Huaishang", "level": 3, "area_code": 552, "post_code": 233002, "pid": 340300, "id": 1070, "area_id": 340311 }, { "area_name": "怀远县", "pinyin": "Huaiyuan", "level": 3, "area_code": 552, "post_code": 233400, "pid": 340300, "id": 1071, "area_id": 340321 }, { "area_name": "五河县", "pinyin": "Wuhe", "level": 3, "area_code": 552, "post_code": 233300, "pid": 340300, "id": 1072, "area_id": 340322 }, { "area_name": "固镇县", "pinyin": "Guzhen", "level": 3, "area_code": 552, "post_code": 233700, "pid": 340300, "id": 1073, "area_id": 340323 }, { "area_name": "淮南市", "pinyin": "Huainan", "level": 2, "area_code": 554, "post_code": 232001, "pid": 340000, "id": 1074, "area_id": 340400 }, { "area_name": "大通区", "pinyin": "Datong", "level": 3, "area_code": 554, "post_code": 232033, "pid": 340400, "id": 1075, "area_id": 340402 }, { "area_name": "田家庵区", "pinyin": "Tianjiaan", "level": 3, "area_code": 554, "post_code": 232000, "pid": 340400, "id": 1076, "area_id": 340403 }, { "area_name": "谢家集区", "pinyin": "Xiejiaji", "level": 3, "area_code": 554, "post_code": 232052, "pid": 340400, "id": 1077, "area_id": 340404 }, { "area_name": "八公山区", "pinyin": "Bagongshan", "level": 3, "area_code": 554, "post_code": 232072, "pid": 340400, "id": 1078, "area_id": 340405 }, { "area_name": "潘集区", "pinyin": "Panji", "level": 3, "area_code": 554, "post_code": 232082, "pid": 340400, "id": 1079, "area_id": 340406 }, { "area_name": "凤台县", "pinyin": "Fengtai", "level": 3, "area_code": 554, "post_code": 232100, "pid": 340400, "id": 1080, "area_id": 340421 }, { "area_name": "马鞍山市", "pinyin": "Ma'anshan", "level": 2, "area_code": 555, "post_code": 243001, "pid": 340000, "id": 1081, "area_id": 340500 }, { "area_name": "花山区", "pinyin": "Huashan", "level": 3, "area_code": 555, "post_code": 243000, "pid": 340500, "id": 1082, "area_id": 340503 }, { "area_name": "雨山区", "pinyin": "Yushan", "level": 3, "area_code": 555, "post_code": 243071, "pid": 340500, "id": 1083, "area_id": 340504 }, { "area_name": "博望区", "pinyin": "Bowang", "level": 3, "area_code": 555, "post_code": 243131, "pid": 340500, "id": 1084, "area_id": 340506 }, { "area_name": "当涂县", "pinyin": "Dangtu", "level": 3, "area_code": 555, "post_code": 243100, "pid": 340500, "id": 1085, "area_id": 340521 }, { "area_name": "含山县", "pinyin": "Hanshan ", "level": 3, "area_code": 555, "post_code": 238100, "pid": 340500, "id": 1086, "area_id": 340522 }, { "area_name": "和县", "pinyin": "Hexian", "level": 3, "area_code": 555, "post_code": 238200, "pid": 340500, "id": 1087, "area_id": 340523 }, { "area_name": "淮北市", "pinyin": "Huaibei", "level": 2, "area_code": 561, "post_code": 235000, "pid": 340000, "id": 1088, "area_id": 340600 }, { "area_name": "杜集区", "pinyin": "Duji", "level": 3, "area_code": 561, "post_code": 235000, "pid": 340600, "id": 1089, "area_id": 340602 }, { "area_name": "相山区", "pinyin": "Xiangshan", "level": 3, "area_code": 561, "post_code": 235000, "pid": 340600, "id": 1090, "area_id": 340603 }, { "area_name": "烈山区", "pinyin": "Lieshan", "level": 3, "area_code": 561, "post_code": 235000, "pid": 340600, "id": 1091, "area_id": 340604 }, { "area_name": "濉溪县", "pinyin": "Suixi", "level": 3, "area_code": 561, "post_code": 235100, "pid": 340600, "id": 1092, "area_id": 340621 }, { "area_name": "铜陵市", "pinyin": "Tongling", "level": 2, "area_code": 562, "post_code": 244000, "pid": 340000, "id": 1093, "area_id": 340700 }, { "area_name": "铜官山区", "pinyin": "Tongguanshan", "level": 3, "area_code": 562, "post_code": 244000, "pid": 340700, "id": 1094, "area_id": 340702 }, { "area_name": "狮子山区", "pinyin": "Shizishan", "level": 3, "area_code": 562, "post_code": 244000, "pid": 340700, "id": 1095, "area_id": 340703 }, { "area_name": "郊区", "pinyin": "Jiaoqu", "level": 3, "area_code": 562, "post_code": 244000, "pid": 340700, "id": 1096, "area_id": 340711 }, { "area_name": "铜陵县", "pinyin": "Tongling", "level": 3, "area_code": 562, "post_code": 244100, "pid": 340700, "id": 1097, "area_id": 340721 }, { "area_name": "安庆市", "pinyin": "Anqing", "level": 2, "area_code": 556, "post_code": 246001, "pid": 340000, "id": 1098, "area_id": 340800 }, { "area_name": "迎江区", "pinyin": "Yingjiang", "level": 3, "area_code": 556, "post_code": 246001, "pid": 340800, "id": 1099, "area_id": 340802 }, { "area_name": "大观区", "pinyin": "Daguan", "level": 3, "area_code": 556, "post_code": 246002, "pid": 340800, "id": 1100, "area_id": 340803 }, { "area_name": "宜秀区", "pinyin": "Yixiu", "level": 3, "area_code": 556, "post_code": 246003, "pid": 340800, "id": 1101, "area_id": 340811 }, { "area_name": "怀宁县", "pinyin": "Huaining", "level": 3, "area_code": 556, "post_code": 246100, "pid": 340800, "id": 1102, "area_id": 340822 }, { "area_name": "枞阳县", "pinyin": "Zongyang", "level": 3, "area_code": 556, "post_code": 246700, "pid": 340800, "id": 1103, "area_id": 340823 }, { "area_name": "潜山县", "pinyin": "Qianshan", "level": 3, "area_code": 556, "post_code": 246300, "pid": 340800, "id": 1104, "area_id": 340824 }, { "area_name": "太湖县", "pinyin": "Taihu", "level": 3, "area_code": 556, "post_code": 246400, "pid": 340800, "id": 1105, "area_id": 340825 }, { "area_name": "宿松县", "pinyin": "Susong", "level": 3, "area_code": 556, "post_code": 246500, "pid": 340800, "id": 1106, "area_id": 340826 }, { "area_name": "望江县", "pinyin": "Wangjiang", "level": 3, "area_code": 556, "post_code": 246200, "pid": 340800, "id": 1107, "area_id": 340827 }, { "area_name": "岳西县", "pinyin": "Yuexi", "level": 3, "area_code": 556, "post_code": 246600, "pid": 340800, "id": 1108, "area_id": 340828 }, { "area_name": "桐城市", "pinyin": "Tongcheng", "level": 3, "area_code": 556, "post_code": 231400, "pid": 340800, "id": 1109, "area_id": 340881 }, { "area_name": "黄山市", "pinyin": "Huangshan", "level": 2, "area_code": 559, "post_code": 245000, "pid": 340000, "id": 1110, "area_id": 341000 }, { "area_name": "屯溪区", "pinyin": "Tunxi", "level": 3, "area_code": 559, "post_code": 245000, "pid": 341000, "id": 1111, "area_id": 341002 }, { "area_name": "黄山区", "pinyin": "Huangshan", "level": 3, "area_code": 559, "post_code": 242700, "pid": 341000, "id": 1112, "area_id": 341003 }, { "area_name": "徽州区", "pinyin": "Huizhou", "level": 3, "area_code": 559, "post_code": 245061, "pid": 341000, "id": 1113, "area_id": 341004 }, { "area_name": "歙县", "pinyin": "Shexian", "level": 3, "area_code": 559, "post_code": 245200, "pid": 341000, "id": 1114, "area_id": 341021 }, { "area_name": "休宁县", "pinyin": "Xiuning", "level": 3, "area_code": 559, "post_code": 245400, "pid": 341000, "id": 1115, "area_id": 341022 }, { "area_name": "黟县", "pinyin": "Yixian", "level": 3, "area_code": 559, "post_code": 245500, "pid": 341000, "id": 1116, "area_id": 341023 }, { "area_name": "祁门县", "pinyin": "Qimen", "level": 3, "area_code": 559, "post_code": 245600, "pid": 341000, "id": 1117, "area_id": 341024 }, { "area_name": "滁州市", "pinyin": "Chuzhou", "level": 2, "area_code": 550, "post_code": 239000, "pid": 340000, "id": 1118, "area_id": 341100 }, { "area_name": "琅琊区", "pinyin": "Langya", "level": 3, "area_code": 550, "post_code": 239000, "pid": 341100, "id": 1119, "area_id": 341102 }, { "area_name": "南谯区", "pinyin": "Nanqiao", "level": 3, "area_code": 550, "post_code": 239000, "pid": 341100, "id": 1120, "area_id": 341103 }, { "area_name": "来安县", "pinyin": "Lai'an", "level": 3, "area_code": 550, "post_code": 239200, "pid": 341100, "id": 1121, "area_id": 341122 }, { "area_name": "全椒县", "pinyin": "Quanjiao", "level": 3, "area_code": 550, "post_code": 239500, "pid": 341100, "id": 1122, "area_id": 341124 }, { "area_name": "定远县", "pinyin": "Dingyuan", "level": 3, "area_code": 550, "post_code": 233200, "pid": 341100, "id": 1123, "area_id": 341125 }, { "area_name": "凤阳县", "pinyin": "Fengyang", "level": 3, "area_code": 550, "post_code": 233100, "pid": 341100, "id": 1124, "area_id": 341126 }, { "area_name": "天长市", "pinyin": "Tianchang", "level": 3, "area_code": 550, "post_code": 239300, "pid": 341100, "id": 1125, "area_id": 341181 }, { "area_name": "明光市", "pinyin": "Mingguang", "level": 3, "area_code": 550, "post_code": 239400, "pid": 341100, "id": 1126, "area_id": 341182 }, { "area_name": "阜阳市", "pinyin": "Fuyang", "level": 2, "area_code": 558, "post_code": 236033, "pid": 340000, "id": 1127, "area_id": 341200 }, { "area_name": "颍州区", "pinyin": "Yingzhou", "level": 3, "area_code": 558, "post_code": 236001, "pid": 341200, "id": 1128, "area_id": 341202 }, { "area_name": "颍东区", "pinyin": "Yingdong", "level": 3, "area_code": 558, "post_code": 236058, "pid": 341200, "id": 1129, "area_id": 341203 }, { "area_name": "颍泉区", "pinyin": "Yingquan", "level": 3, "area_code": 558, "post_code": 236045, "pid": 341200, "id": 1130, "area_id": 341204 }, { "area_name": "临泉县", "pinyin": "Linquan", "level": 3, "area_code": 558, "post_code": 236400, "pid": 341200, "id": 1131, "area_id": 341221 }, { "area_name": "太和县", "pinyin": "Taihe", "level": 3, "area_code": 558, "post_code": 236600, "pid": 341200, "id": 1132, "area_id": 341222 }, { "area_name": "阜南县", "pinyin": "Funan", "level": 3, "area_code": 558, "post_code": 236300, "pid": 341200, "id": 1133, "area_id": 341225 }, { "area_name": "颍上县", "pinyin": "Yingshang", "level": 3, "area_code": 558, "post_code": 236200, "pid": 341200, "id": 1134, "area_id": 341226 }, { "area_name": "界首市", "pinyin": "Jieshou", "level": 3, "area_code": 558, "post_code": 236500, "pid": 341200, "id": 1135, "area_id": 341282 }, { "area_name": "宿州市", "pinyin": "Suzhou", "level": 2, "area_code": 557, "post_code": 234000, "pid": 340000, "id": 1136, "area_id": 341300 }, { "area_name": "埇桥区", "pinyin": "Yongqiao", "level": 3, "area_code": 557, "post_code": 234000, "pid": 341300, "id": 1137, "area_id": 341302 }, { "area_name": "砀山县", "pinyin": "Dangshan", "level": 3, "area_code": 557, "post_code": 235300, "pid": 341300, "id": 1138, "area_id": 341321 }, { "area_name": "萧县", "pinyin": "Xiaoxian", "level": 3, "area_code": 557, "post_code": 235200, "pid": 341300, "id": 1139, "area_id": 341322 }, { "area_name": "灵璧县", "pinyin": "Lingbi", "level": 3, "area_code": 557, "post_code": 234200, "pid": 341300, "id": 1140, "area_id": 341323 }, { "area_name": "泗县", "pinyin": "Sixian", "level": 3, "area_code": 557, "post_code": 234300, "pid": 341300, "id": 1141, "area_id": 341324 }, { "area_name": "六安市", "pinyin": "Lu'an", "level": 2, "area_code": 564, "post_code": 237000, "pid": 340000, "id": 1142, "area_id": 341500 }, { "area_name": "金安区", "pinyin": "Jin'an", "level": 3, "area_code": 564, "post_code": 237005, "pid": 341500, "id": 1143, "area_id": 341502 }, { "area_name": "裕安区", "pinyin": "Yu'an", "level": 3, "area_code": 564, "post_code": 237010, "pid": 341500, "id": 1144, "area_id": 341503 }, { "area_name": "寿县", "pinyin": "Shouxian", "level": 3, "area_code": 564, "post_code": 232200, "pid": 341500, "id": 1145, "area_id": 341521 }, { "area_name": "霍邱县", "pinyin": "Huoqiu", "level": 3, "area_code": 564, "post_code": 237400, "pid": 341500, "id": 1146, "area_id": 341522 }, { "area_name": "舒城县", "pinyin": "Shucheng", "level": 3, "area_code": 564, "post_code": 231300, "pid": 341500, "id": 1147, "area_id": 341523 }, { "area_name": "金寨县", "pinyin": "Jinzhai", "level": 3, "area_code": 564, "post_code": 237300, "pid": 341500, "id": 1148, "area_id": 341524 }, { "area_name": "霍山县", "pinyin": "Huoshan", "level": 3, "area_code": 564, "post_code": 237200, "pid": 341500, "id": 1149, "area_id": 341525 }, { "area_name": "亳州市", "pinyin": "Bozhou", "level": 2, "area_code": 558, "post_code": 236802, "pid": 340000, "id": 1150, "area_id": 341600 }, { "area_name": "谯城区", "pinyin": "Qiaocheng", "level": 3, "area_code": 558, "post_code": 236800, "pid": 341600, "id": 1151, "area_id": 341602 }, { "area_name": "涡阳县", "pinyin": "Guoyang", "level": 3, "area_code": 558, "post_code": 233600, "pid": 341600, "id": 1152, "area_id": 341621 }, { "area_name": "蒙城县", "pinyin": "Mengcheng", "level": 3, "area_code": 558, "post_code": 233500, "pid": 341600, "id": 1153, "area_id": 341622 }, { "area_name": "利辛县", "pinyin": "Lixin", "level": 3, "area_code": 558, "post_code": 236700, "pid": 341600, "id": 1154, "area_id": 341623 }, { "area_name": "池州市", "pinyin": "Chizhou", "level": 2, "area_code": 566, "post_code": 247100, "pid": 340000, "id": 1155, "area_id": 341700 }, { "area_name": "贵池区", "pinyin": "Guichi", "level": 3, "area_code": 566, "post_code": 247100, "pid": 341700, "id": 1156, "area_id": 341702 }, { "area_name": "东至县", "pinyin": "Dongzhi", "level": 3, "area_code": 566, "post_code": 247200, "pid": 341700, "id": 1157, "area_id": 341721 }, { "area_name": "石台县", "pinyin": "Shitai", "level": 3, "area_code": 566, "post_code": 245100, "pid": 341700, "id": 1158, "area_id": 341722 }, { "area_name": "青阳县", "pinyin": "Qingyang", "level": 3, "area_code": 566, "post_code": 242800, "pid": 341700, "id": 1159, "area_id": 341723 }, { "area_name": "宣城市", "pinyin": "Xuancheng", "level": 2, "area_code": 563, "post_code": 242000, "pid": 340000, "id": 1160, "area_id": 341800 }, { "area_name": "宣州区", "pinyin": "Xuanzhou", "level": 3, "area_code": 563, "post_code": 242000, "pid": 341800, "id": 1161, "area_id": 341802 }, { "area_name": "郎溪县", "pinyin": "Langxi", "level": 3, "area_code": 563, "post_code": 242100, "pid": 341800, "id": 1162, "area_id": 341821 }, { "area_name": "广德县", "pinyin": "Guangde", "level": 3, "area_code": 563, "post_code": 242200, "pid": 341800, "id": 1163, "area_id": 341822 }, { "area_name": "泾县", "pinyin": "Jingxian", "level": 3, "area_code": 563, "post_code": 242500, "pid": 341800, "id": 1164, "area_id": 341823 }, { "area_name": "绩溪县", "pinyin": "Jixi", "level": 3, "area_code": 563, "post_code": 245300, "pid": 341800, "id": 1165, "area_id": 341824 }, { "area_name": "旌德县", "pinyin": "Jingde", "level": 3, "area_code": 563, "post_code": 242600, "pid": 341800, "id": 1166, "area_id": 341825 }, { "area_name": "宁国市", "pinyin": "Ningguo", "level": 3, "area_code": 563, "post_code": 242300, "pid": 341800, "id": 1167, "area_id": 341881 }, { "area_name": "福建省", "pinyin": "Fujian", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1168, "area_id": 350000 }, { "area_name": "福州市", "pinyin": "Fuzhou", "level": 2, "area_code": 591, "post_code": 350001, "pid": 350000, "id": 1169, "area_id": 350100 }, { "area_name": "鼓楼区", "pinyin": "Gulou", "level": 3, "area_code": 591, "post_code": 350001, "pid": 350100, "id": 1170, "area_id": 350102 }, { "area_name": "台江区", "pinyin": "Taijiang", "level": 3, "area_code": 591, "post_code": 350004, "pid": 350100, "id": 1171, "area_id": 350103 }, { "area_name": "仓山区", "pinyin": "Cangshan", "level": 3, "area_code": 591, "post_code": 350007, "pid": 350100, "id": 1172, "area_id": 350104 }, { "area_name": "马尾区", "pinyin": "Mawei", "level": 3, "area_code": 591, "post_code": 350015, "pid": 350100, "id": 1173, "area_id": 350105 }, { "area_name": "晋安区", "pinyin": "Jin'an", "level": 3, "area_code": 591, "post_code": 350011, "pid": 350100, "id": 1174, "area_id": 350111 }, { "area_name": "闽侯县", "pinyin": "Minhou", "level": 3, "area_code": 591, "post_code": 350100, "pid": 350100, "id": 1175, "area_id": 350121 }, { "area_name": "连江县", "pinyin": "Lianjiang", "level": 3, "area_code": 591, "post_code": 350500, "pid": 350100, "id": 1176, "area_id": 350122 }, { "area_name": "罗源县", "pinyin": "Luoyuan", "level": 3, "area_code": 591, "post_code": 350600, "pid": 350100, "id": 1177, "area_id": 350123 }, { "area_name": "闽清县", "pinyin": "Minqing", "level": 3, "area_code": 591, "post_code": 350800, "pid": 350100, "id": 1178, "area_id": 350124 }, { "area_name": "永泰县", "pinyin": "Yongtai", "level": 3, "area_code": 591, "post_code": 350700, "pid": 350100, "id": 1179, "area_id": 350125 }, { "area_name": "平潭县", "pinyin": "Pingtan", "level": 3, "area_code": 591, "post_code": 350400, "pid": 350100, "id": 1180, "area_id": 350128 }, { "area_name": "福清市", "pinyin": "Fuqing", "level": 3, "area_code": 591, "post_code": 350300, "pid": 350100, "id": 1181, "area_id": 350181 }, { "area_name": "长乐市", "pinyin": "Changle", "level": 3, "area_code": 591, "post_code": 350200, "pid": 350100, "id": 1182, "area_id": 350182 }, { "area_name": "厦门市", "pinyin": "Xiamen", "level": 2, "area_code": 592, "post_code": 361003, "pid": 350000, "id": 1183, "area_id": 350200 }, { "area_name": "思明区", "pinyin": "Siming", "level": 3, "area_code": 592, "post_code": 361001, "pid": 350200, "id": 1184, "area_id": 350203 }, { "area_name": "海沧区", "pinyin": "Haicang", "level": 3, "area_code": 592, "post_code": 361026, "pid": 350200, "id": 1185, "area_id": 350205 }, { "area_name": "湖里区", "pinyin": "Huli", "level": 3, "area_code": 592, "post_code": 361006, "pid": 350200, "id": 1186, "area_id": 350206 }, { "area_name": "集美区", "pinyin": "Jimei", "level": 3, "area_code": 592, "post_code": 361021, "pid": 350200, "id": 1187, "area_id": 350211 }, { "area_name": "同安区", "pinyin": "Tong'an", "level": 3, "area_code": 592, "post_code": 361100, "pid": 350200, "id": 1188, "area_id": 350212 }, { "area_name": "翔安区", "pinyin": "Xiang'an", "level": 3, "area_code": 592, "post_code": 361101, "pid": 350200, "id": 1189, "area_id": 350213 }, { "area_name": "莆田市", "pinyin": "Putian", "level": 2, "area_code": 594, "post_code": 351100, "pid": 350000, "id": 1190, "area_id": 350300 }, { "area_name": "城厢区", "pinyin": "Chengxiang", "level": 3, "area_code": 594, "post_code": 351100, "pid": 350300, "id": 1191, "area_id": 350302 }, { "area_name": "涵江区", "pinyin": "Hanjiang", "level": 3, "area_code": 594, "post_code": 351111, "pid": 350300, "id": 1192, "area_id": 350303 }, { "area_name": "荔城区", "pinyin": "Licheng", "level": 3, "area_code": 594, "post_code": 351100, "pid": 350300, "id": 1193, "area_id": 350304 }, { "area_name": "秀屿区", "pinyin": "Xiuyu", "level": 3, "area_code": 594, "post_code": 351152, "pid": 350300, "id": 1194, "area_id": 350305 }, { "area_name": "仙游县", "pinyin": "Xianyou", "level": 3, "area_code": 594, "post_code": 351200, "pid": 350300, "id": 1195, "area_id": 350322 }, { "area_name": "三明市", "pinyin": "Sanming", "level": 2, "area_code": 598, "post_code": 365000, "pid": 350000, "id": 1196, "area_id": 350400 }, { "area_name": "梅列区", "pinyin": "Meilie", "level": 3, "area_code": 598, "post_code": 365000, "pid": 350400, "id": 1197, "area_id": 350402 }, { "area_name": "三元区", "pinyin": "Sanyuan", "level": 3, "area_code": 598, "post_code": 365001, "pid": 350400, "id": 1198, "area_id": 350403 }, { "area_name": "明溪县", "pinyin": "Mingxi", "level": 3, "area_code": 598, "post_code": 365200, "pid": 350400, "id": 1199, "area_id": 350421 }, { "area_name": "清流县", "pinyin": "Qingliu", "level": 3, "area_code": 598, "post_code": 365300, "pid": 350400, "id": 1200, "area_id": 350423 }, { "area_name": "宁化县", "pinyin": "Ninghua", "level": 3, "area_code": 598, "post_code": 365400, "pid": 350400, "id": 1201, "area_id": 350424 }, { "area_name": "大田县", "pinyin": "Datian", "level": 3, "area_code": 598, "post_code": 366100, "pid": 350400, "id": 1202, "area_id": 350425 }, { "area_name": "尤溪县", "pinyin": "Youxi", "level": 3, "area_code": 598, "post_code": 365100, "pid": 350400, "id": 1203, "area_id": 350426 }, { "area_name": "沙县", "pinyin": "Shaxian", "level": 3, "area_code": 598, "post_code": 365500, "pid": 350400, "id": 1204, "area_id": 350427 }, { "area_name": "将乐县", "pinyin": "Jiangle", "level": 3, "area_code": 598, "post_code": 353300, "pid": 350400, "id": 1205, "area_id": 350428 }, { "area_name": "泰宁县", "pinyin": "Taining", "level": 3, "area_code": 598, "post_code": 354400, "pid": 350400, "id": 1206, "area_id": 350429 }, { "area_name": "建宁县", "pinyin": "Jianning", "level": 3, "area_code": 598, "post_code": 354500, "pid": 350400, "id": 1207, "area_id": 350430 }, { "area_name": "永安市", "pinyin": "Yong'an", "level": 3, "area_code": 598, "post_code": 366000, "pid": 350400, "id": 1208, "area_id": 350481 }, { "area_name": "泉州市", "pinyin": "Quanzhou", "level": 2, "area_code": 595, "post_code": 362000, "pid": 350000, "id": 1209, "area_id": 350500 }, { "area_name": "鲤城区", "pinyin": "Licheng", "level": 3, "area_code": 595, "post_code": 362000, "pid": 350500, "id": 1210, "area_id": 350502 }, { "area_name": "丰泽区", "pinyin": "Fengze", "level": 3, "area_code": 595, "post_code": 362000, "pid": 350500, "id": 1211, "area_id": 350503 }, { "area_name": "洛江区", "pinyin": "Luojiang", "level": 3, "area_code": 595, "post_code": 362011, "pid": 350500, "id": 1212, "area_id": 350504 }, { "area_name": "泉港区", "pinyin": "Quangang", "level": 3, "area_code": 595, "post_code": 362114, "pid": 350500, "id": 1213, "area_id": 350505 }, { "area_name": "惠安县", "pinyin": "Hui'an", "level": 3, "area_code": 595, "post_code": 362100, "pid": 350500, "id": 1214, "area_id": 350521 }, { "area_name": "安溪县", "pinyin": "Anxi", "level": 3, "area_code": 595, "post_code": 362400, "pid": 350500, "id": 1215, "area_id": 350524 }, { "area_name": "永春县", "pinyin": "Yongchun", "level": 3, "area_code": 595, "post_code": 362600, "pid": 350500, "id": 1216, "area_id": 350525 }, { "area_name": "德化县", "pinyin": "Dehua", "level": 3, "area_code": 595, "post_code": 362500, "pid": 350500, "id": 1217, "area_id": 350526 }, { "area_name": "金门县", "pinyin": "Jinmen", "level": 3, "area_code": null, "post_code": null, "pid": 350500, "id": 1218, "area_id": 350527 }, { "area_name": "石狮市", "pinyin": "Shishi", "level": 3, "area_code": 595, "post_code": 362700, "pid": 350500, "id": 1219, "area_id": 350581 }, { "area_name": "晋江市", "pinyin": "Jinjiang", "level": 3, "area_code": 595, "post_code": 362200, "pid": 350500, "id": 1220, "area_id": 350582 }, { "area_name": "南安市", "pinyin": "Nan'an", "level": 3, "area_code": 595, "post_code": 362300, "pid": 350500, "id": 1221, "area_id": 350583 }, { "area_name": "漳州市", "pinyin": "Zhangzhou", "level": 2, "area_code": 596, "post_code": 363005, "pid": 350000, "id": 1222, "area_id": 350600 }, { "area_name": "芗城区", "pinyin": "Xiangcheng", "level": 3, "area_code": 596, "post_code": 363000, "pid": 350600, "id": 1223, "area_id": 350602 }, { "area_name": "龙文区", "pinyin": "Longwen", "level": 3, "area_code": 596, "post_code": 363005, "pid": 350600, "id": 1224, "area_id": 350603 }, { "area_name": "云霄县", "pinyin": "Yunxiao", "level": 3, "area_code": 596, "post_code": 363300, "pid": 350600, "id": 1225, "area_id": 350622 }, { "area_name": "漳浦县", "pinyin": "Zhangpu", "level": 3, "area_code": 596, "post_code": 363200, "pid": 350600, "id": 1226, "area_id": 350623 }, { "area_name": "诏安县", "pinyin": "Zhao'an", "level": 3, "area_code": 596, "post_code": 363500, "pid": 350600, "id": 1227, "area_id": 350624 }, { "area_name": "长泰县", "pinyin": "Changtai", "level": 3, "area_code": 596, "post_code": 363900, "pid": 350600, "id": 1228, "area_id": 350625 }, { "area_name": "东山县", "pinyin": "Dongshan", "level": 3, "area_code": 596, "post_code": 363400, "pid": 350600, "id": 1229, "area_id": 350626 }, { "area_name": "南靖县", "pinyin": "Nanjing", "level": 3, "area_code": 596, "post_code": 363600, "pid": 350600, "id": 1230, "area_id": 350627 }, { "area_name": "平和县", "pinyin": "Pinghe", "level": 3, "area_code": 596, "post_code": 363700, "pid": 350600, "id": 1231, "area_id": 350628 }, { "area_name": "华安县", "pinyin": "Hua'an", "level": 3, "area_code": 596, "post_code": 363800, "pid": 350600, "id": 1232, "area_id": 350629 }, { "area_name": "龙海市", "pinyin": "Longhai", "level": 3, "area_code": 596, "post_code": 363100, "pid": 350600, "id": 1233, "area_id": 350681 }, { "area_name": "南平市", "pinyin": "Nanping", "level": 2, "area_code": 599, "post_code": 353000, "pid": 350000, "id": 1234, "area_id": 350700 }, { "area_name": "延平区", "pinyin": "Yanping", "level": 3, "area_code": 600, "post_code": 353000, "pid": 350700, "id": 1235, "area_id": 350702 }, { "area_name": "建阳区", "pinyin": "Jianyang", "level": 3, "area_code": 599, "post_code": 354200, "pid": 350700, "id": 1236, "area_id": 350703 }, { "area_name": "顺昌县", "pinyin": "Shunchang", "level": 3, "area_code": 605, "post_code": 353200, "pid": 350700, "id": 1237, "area_id": 350721 }, { "area_name": "浦城县", "pinyin": "Pucheng", "level": 3, "area_code": 606, "post_code": 353400, "pid": 350700, "id": 1238, "area_id": 350722 }, { "area_name": "光泽县", "pinyin": "Guangze", "level": 3, "area_code": 607, "post_code": 354100, "pid": 350700, "id": 1239, "area_id": 350723 }, { "area_name": "松溪县", "pinyin": "Songxi", "level": 3, "area_code": 608, "post_code": 353500, "pid": 350700, "id": 1240, "area_id": 350724 }, { "area_name": "政和县", "pinyin": "Zhenghe", "level": 3, "area_code": 609, "post_code": 353600, "pid": 350700, "id": 1241, "area_id": 350725 }, { "area_name": "邵武市", "pinyin": "Shaowu", "level": 3, "area_code": 601, "post_code": 354000, "pid": 350700, "id": 1242, "area_id": 350781 }, { "area_name": "武夷山市", "pinyin": "Wuyishan", "level": 3, "area_code": 602, "post_code": 354300, "pid": 350700, "id": 1243, "area_id": 350782 }, { "area_name": "建瓯市", "pinyin": "Jianou", "level": 3, "area_code": 603, "post_code": 353100, "pid": 350700, "id": 1244, "area_id": 350783 }, { "area_name": "龙岩市", "pinyin": "Longyan", "level": 2, "area_code": 597, "post_code": 364000, "pid": 350000, "id": 1245, "area_id": 350800 }, { "area_name": "新罗区", "pinyin": "Xinluo", "level": 3, "area_code": 597, "post_code": 364000, "pid": 350800, "id": 1246, "area_id": 350802 }, { "area_name": "长汀县", "pinyin": "Changting", "level": 3, "area_code": 597, "post_code": 366300, "pid": 350800, "id": 1247, "area_id": 350821 }, { "area_name": "永定区", "pinyin": "Yongding", "level": 3, "area_code": 597, "post_code": 364100, "pid": 350800, "id": 1248, "area_id": 350822 }, { "area_name": "上杭县", "pinyin": "Shanghang", "level": 3, "area_code": 597, "post_code": 364200, "pid": 350800, "id": 1249, "area_id": 350823 }, { "area_name": "武平县", "pinyin": "Wuping", "level": 3, "area_code": 597, "post_code": 364300, "pid": 350800, "id": 1250, "area_id": 350824 }, { "area_name": "连城县", "pinyin": "Liancheng", "level": 3, "area_code": 597, "post_code": 366200, "pid": 350800, "id": 1251, "area_id": 350825 }, { "area_name": "漳平市", "pinyin": "Zhangping", "level": 3, "area_code": 597, "post_code": 364400, "pid": 350800, "id": 1252, "area_id": 350881 }, { "area_name": "宁德市", "pinyin": "Ningde", "level": 2, "area_code": 593, "post_code": 352100, "pid": 350000, "id": 1253, "area_id": 350900 }, { "area_name": "蕉城区", "pinyin": "Jiaocheng", "level": 3, "area_code": 593, "post_code": 352100, "pid": 350900, "id": 1254, "area_id": 350902 }, { "area_name": "霞浦县", "pinyin": "Xiapu", "level": 3, "area_code": 593, "post_code": 355100, "pid": 350900, "id": 1255, "area_id": 350921 }, { "area_name": "古田县", "pinyin": "Gutian", "level": 3, "area_code": 593, "post_code": 352200, "pid": 350900, "id": 1256, "area_id": 350922 }, { "area_name": "屏南县", "pinyin": "Pingnan", "level": 3, "area_code": 593, "post_code": 352300, "pid": 350900, "id": 1257, "area_id": 350923 }, { "area_name": "寿宁县", "pinyin": "Shouning", "level": 3, "area_code": 593, "post_code": 355500, "pid": 350900, "id": 1258, "area_id": 350924 }, { "area_name": "周宁县", "pinyin": "Zhouning", "level": 3, "area_code": 593, "post_code": 355400, "pid": 350900, "id": 1259, "area_id": 350925 }, { "area_name": "柘荣县", "pinyin": "Zherong", "level": 3, "area_code": 593, "post_code": 355300, "pid": 350900, "id": 1260, "area_id": 350926 }, { "area_name": "福安市", "pinyin": "Fu'an", "level": 3, "area_code": 593, "post_code": 355000, "pid": 350900, "id": 1261, "area_id": 350981 }, { "area_name": "福鼎市", "pinyin": "Fuding", "level": 3, "area_code": 593, "post_code": 355200, "pid": 350900, "id": 1262, "area_id": 350982 }, { "area_name": "江西省", "pinyin": "Jiangxi", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1263, "area_id": 360000 }, { "area_name": "南昌市", "pinyin": "Nanchang", "level": 2, "area_code": 791, "post_code": 330008, "pid": 360000, "id": 1264, "area_id": 360100 }, { "area_name": "东湖区", "pinyin": "Donghu", "level": 3, "area_code": 791, "post_code": 330006, "pid": 360100, "id": 1265, "area_id": 360102 }, { "area_name": "西湖区", "pinyin": "Xihu", "level": 3, "area_code": 791, "post_code": 330009, "pid": 360100, "id": 1266, "area_id": 360103 }, { "area_name": "青云谱区", "pinyin": "Qingyunpu", "level": 3, "area_code": 791, "post_code": 330001, "pid": 360100, "id": 1267, "area_id": 360104 }, { "area_name": "湾里区", "pinyin": "Wanli", "level": 3, "area_code": 791, "post_code": 330004, "pid": 360100, "id": 1268, "area_id": 360105 }, { "area_name": "青山湖区", "pinyin": "Qingshanhu", "level": 3, "area_code": 791, "post_code": 330029, "pid": 360100, "id": 1269, "area_id": 360111 }, { "area_name": "南昌县", "pinyin": "Nanchang", "level": 3, "area_code": 791, "post_code": 330200, "pid": 360100, "id": 1270, "area_id": 360121 }, { "area_name": "新建县", "pinyin": "Xinjian", "level": 3, "area_code": 791, "post_code": 330100, "pid": 360100, "id": 1271, "area_id": 360122 }, { "area_name": "安义县", "pinyin": "Anyi", "level": 3, "area_code": 791, "post_code": 330500, "pid": 360100, "id": 1272, "area_id": 360123 }, { "area_name": "进贤县", "pinyin": "Jinxian", "level": 3, "area_code": 791, "post_code": 331700, "pid": 360100, "id": 1273, "area_id": 360124 }, { "area_name": "景德镇市", "pinyin": "Jingdezhen", "level": 2, "area_code": 798, "post_code": 333000, "pid": 360000, "id": 1274, "area_id": 360200 }, { "area_name": "昌江区", "pinyin": "Changjiang", "level": 3, "area_code": 799, "post_code": 333000, "pid": 360200, "id": 1275, "area_id": 360202 }, { "area_name": "珠山区", "pinyin": "Zhushan", "level": 3, "area_code": 800, "post_code": 333000, "pid": 360200, "id": 1276, "area_id": 360203 }, { "area_name": "浮梁县", "pinyin": "Fuliang", "level": 3, "area_code": 802, "post_code": 333400, "pid": 360200, "id": 1277, "area_id": 360222 }, { "area_name": "乐平市", "pinyin": "Leping", "level": 3, "area_code": 801, "post_code": 333300, "pid": 360200, "id": 1278, "area_id": 360281 }, { "area_name": "萍乡市", "pinyin": "Pingxiang", "level": 2, "area_code": 799, "post_code": 337000, "pid": 360000, "id": 1279, "area_id": 360300 }, { "area_name": "安源区", "pinyin": "Anyuan", "level": 3, "area_code": 800, "post_code": 337000, "pid": 360300, "id": 1280, "area_id": 360302 }, { "area_name": "湘东区", "pinyin": "Xiangdong", "level": 3, "area_code": 801, "post_code": 337016, "pid": 360300, "id": 1281, "area_id": 360313 }, { "area_name": "莲花县", "pinyin": "Lianhua", "level": 3, "area_code": 802, "post_code": 337100, "pid": 360300, "id": 1282, "area_id": 360321 }, { "area_name": "上栗县", "pinyin": "Shangli", "level": 3, "area_code": 803, "post_code": 337009, "pid": 360300, "id": 1283, "area_id": 360322 }, { "area_name": "芦溪县", "pinyin": "Luxi", "level": 3, "area_code": 804, "post_code": 337053, "pid": 360300, "id": 1284, "area_id": 360323 }, { "area_name": "九江市", "pinyin": "Jiujiang", "level": 2, "area_code": 792, "post_code": 332000, "pid": 360000, "id": 1285, "area_id": 360400 }, { "area_name": "庐山区", "pinyin": "Lushan", "level": 3, "area_code": 792, "post_code": 332005, "pid": 360400, "id": 1286, "area_id": 360402 }, { "area_name": "浔阳区", "pinyin": "Xunyang", "level": 3, "area_code": 792, "post_code": 332000, "pid": 360400, "id": 1287, "area_id": 360403 }, { "area_name": "九江县", "pinyin": "Jiujiang", "level": 3, "area_code": 792, "post_code": 332100, "pid": 360400, "id": 1288, "area_id": 360421 }, { "area_name": "武宁县", "pinyin": "Wuning", "level": 3, "area_code": 792, "post_code": 332300, "pid": 360400, "id": 1289, "area_id": 360423 }, { "area_name": "修水县", "pinyin": "Xiushui", "level": 3, "area_code": 792, "post_code": 332400, "pid": 360400, "id": 1290, "area_id": 360424 }, { "area_name": "永修县", "pinyin": "Yongxiu", "level": 3, "area_code": 792, "post_code": 330300, "pid": 360400, "id": 1291, "area_id": 360425 }, { "area_name": "德安县", "pinyin": "De'an", "level": 3, "area_code": 792, "post_code": 330400, "pid": 360400, "id": 1292, "area_id": 360426 }, { "area_name": "星子县", "pinyin": "Xingzi", "level": 3, "area_code": 792, "post_code": 332800, "pid": 360400, "id": 1293, "area_id": 360427 }, { "area_name": "都昌县", "pinyin": "Duchang", "level": 3, "area_code": 792, "post_code": 332600, "pid": 360400, "id": 1294, "area_id": 360428 }, { "area_name": "湖口县", "pinyin": "Hukou", "level": 3, "area_code": 792, "post_code": 332500, "pid": 360400, "id": 1295, "area_id": 360429 }, { "area_name": "彭泽县", "pinyin": "Pengze", "level": 3, "area_code": 792, "post_code": 332700, "pid": 360400, "id": 1296, "area_id": 360430 }, { "area_name": "瑞昌市", "pinyin": "Ruichang", "level": 3, "area_code": 792, "post_code": 332200, "pid": 360400, "id": 1297, "area_id": 360481 }, { "area_name": "共青城市", "pinyin": "Gongqingcheng", "level": 3, "area_code": 792, "post_code": 332020, "pid": 360400, "id": 1298, "area_id": 360482 }, { "area_name": "新余市", "pinyin": "Xinyu", "level": 2, "area_code": 790, "post_code": 338025, "pid": 360000, "id": 1299, "area_id": 360500 }, { "area_name": "渝水区", "pinyin": "Yushui", "level": 3, "area_code": 790, "post_code": 338025, "pid": 360500, "id": 1300, "area_id": 360502 }, { "area_name": "分宜县", "pinyin": "Fenyi", "level": 3, "area_code": 790, "post_code": 336600, "pid": 360500, "id": 1301, "area_id": 360521 }, { "area_name": "鹰潭市", "pinyin": "Yingtan", "level": 2, "area_code": 701, "post_code": 335000, "pid": 360000, "id": 1302, "area_id": 360600 }, { "area_name": "月湖区", "pinyin": "Yuehu", "level": 3, "area_code": 701, "post_code": 335000, "pid": 360600, "id": 1303, "area_id": 360602 }, { "area_name": "余江县", "pinyin": "Yujiang", "level": 3, "area_code": 701, "post_code": 335200, "pid": 360600, "id": 1304, "area_id": 360622 }, { "area_name": "贵溪市", "pinyin": "Guixi", "level": 3, "area_code": 701, "post_code": 335400, "pid": 360600, "id": 1305, "area_id": 360681 }, { "area_name": "赣州市", "pinyin": "Ganzhou", "level": 2, "area_code": 797, "post_code": 341000, "pid": 360000, "id": 1306, "area_id": 360700 }, { "area_name": "章贡区", "pinyin": "Zhanggong", "level": 3, "area_code": 797, "post_code": 341000, "pid": 360700, "id": 1307, "area_id": 360702 }, { "area_name": "南康区", "pinyin": "Nankang", "level": 3, "area_code": 797, "post_code": 341400, "pid": 360700, "id": 1308, "area_id": 360703 }, { "area_name": "赣县", "pinyin": "Ganxian", "level": 3, "area_code": 797, "post_code": 341100, "pid": 360700, "id": 1309, "area_id": 360721 }, { "area_name": "信丰县", "pinyin": "Xinfeng", "level": 3, "area_code": 797, "post_code": 341600, "pid": 360700, "id": 1310, "area_id": 360722 }, { "area_name": "大余县", "pinyin": "Dayu", "level": 3, "area_code": 797, "post_code": 341500, "pid": 360700, "id": 1311, "area_id": 360723 }, { "area_name": "上犹县", "pinyin": "Shangyou", "level": 3, "area_code": 797, "post_code": 341200, "pid": 360700, "id": 1312, "area_id": 360724 }, { "area_name": "崇义县", "pinyin": "Chongyi", "level": 3, "area_code": 797, "post_code": 341300, "pid": 360700, "id": 1313, "area_id": 360725 }, { "area_name": "安远县", "pinyin": "Anyuan", "level": 3, "area_code": 797, "post_code": 342100, "pid": 360700, "id": 1314, "area_id": 360726 }, { "area_name": "龙南县", "pinyin": "Longnan", "level": 3, "area_code": 797, "post_code": 341700, "pid": 360700, "id": 1315, "area_id": 360727 }, { "area_name": "定南县", "pinyin": "Dingnan", "level": 3, "area_code": 797, "post_code": 341900, "pid": 360700, "id": 1316, "area_id": 360728 }, { "area_name": "全南县", "pinyin": "Quannan", "level": 3, "area_code": 797, "post_code": 341800, "pid": 360700, "id": 1317, "area_id": 360729 }, { "area_name": "宁都县", "pinyin": "Ningdu", "level": 3, "area_code": 797, "post_code": 342800, "pid": 360700, "id": 1318, "area_id": 360730 }, { "area_name": "于都县", "pinyin": "Yudu", "level": 3, "area_code": 797, "post_code": 342300, "pid": 360700, "id": 1319, "area_id": 360731 }, { "area_name": "兴国县", "pinyin": "Xingguo", "level": 3, "area_code": 797, "post_code": 342400, "pid": 360700, "id": 1320, "area_id": 360732 }, { "area_name": "会昌县", "pinyin": "Huichang", "level": 3, "area_code": 797, "post_code": 342600, "pid": 360700, "id": 1321, "area_id": 360733 }, { "area_name": "寻乌县", "pinyin": "Xunwu", "level": 3, "area_code": 797, "post_code": 342200, "pid": 360700, "id": 1322, "area_id": 360734 }, { "area_name": "石城县", "pinyin": "Shicheng", "level": 3, "area_code": 797, "post_code": 342700, "pid": 360700, "id": 1323, "area_id": 360735 }, { "area_name": "瑞金市", "pinyin": "Ruijin", "level": 3, "area_code": 797, "post_code": 342500, "pid": 360700, "id": 1324, "area_id": 360781 }, { "area_name": "吉安市", "pinyin": "Ji'an", "level": 2, "area_code": 796, "post_code": 343000, "pid": 360000, "id": 1325, "area_id": 360800 }, { "area_name": "吉州区", "pinyin": "Jizhou", "level": 3, "area_code": 796, "post_code": 343000, "pid": 360800, "id": 1326, "area_id": 360802 }, { "area_name": "青原区", "pinyin": "Qingyuan", "level": 3, "area_code": 796, "post_code": 343009, "pid": 360800, "id": 1327, "area_id": 360803 }, { "area_name": "吉安县", "pinyin": "Ji'an", "level": 3, "area_code": 796, "post_code": 343100, "pid": 360800, "id": 1328, "area_id": 360821 }, { "area_name": "吉水县", "pinyin": "Jishui", "level": 3, "area_code": 796, "post_code": 331600, "pid": 360800, "id": 1329, "area_id": 360822 }, { "area_name": "峡江县", "pinyin": "Xiajiang", "level": 3, "area_code": 796, "post_code": 331409, "pid": 360800, "id": 1330, "area_id": 360823 }, { "area_name": "新干县", "pinyin": "Xingan", "level": 3, "area_code": 796, "post_code": 331300, "pid": 360800, "id": 1331, "area_id": 360824 }, { "area_name": "永丰县", "pinyin": "Yongfeng", "level": 3, "area_code": 796, "post_code": 331500, "pid": 360800, "id": 1332, "area_id": 360825 }, { "area_name": "泰和县", "pinyin": "Taihe", "level": 3, "area_code": 796, "post_code": 343700, "pid": 360800, "id": 1333, "area_id": 360826 }, { "area_name": "遂川县", "pinyin": "Suichuan", "level": 3, "area_code": 796, "post_code": 343900, "pid": 360800, "id": 1334, "area_id": 360827 }, { "area_name": "万安县", "pinyin": "Wan'an", "level": 3, "area_code": 796, "post_code": 343800, "pid": 360800, "id": 1335, "area_id": 360828 }, { "area_name": "安福县", "pinyin": "Anfu", "level": 3, "area_code": 796, "post_code": 343200, "pid": 360800, "id": 1336, "area_id": 360829 }, { "area_name": "永新县", "pinyin": "Yongxin", "level": 3, "area_code": 796, "post_code": 343400, "pid": 360800, "id": 1337, "area_id": 360830 }, { "area_name": "井冈山市", "pinyin": "Jinggangshan", "level": 3, "area_code": 796, "post_code": 343600, "pid": 360800, "id": 1338, "area_id": 360881 }, { "area_name": "宜春市", "pinyin": "Yichun", "level": 2, "area_code": 795, "post_code": 336000, "pid": 360000, "id": 1339, "area_id": 360900 }, { "area_name": "袁州区", "pinyin": "Yuanzhou", "level": 3, "area_code": 795, "post_code": 336000, "pid": 360900, "id": 1340, "area_id": 360902 }, { "area_name": "奉新县", "pinyin": "Fengxin", "level": 3, "area_code": 795, "post_code": 330700, "pid": 360900, "id": 1341, "area_id": 360921 }, { "area_name": "万载县", "pinyin": "Wanzai", "level": 3, "area_code": 795, "post_code": 336100, "pid": 360900, "id": 1342, "area_id": 360922 }, { "area_name": "上高县", "pinyin": "Shanggao", "level": 3, "area_code": 795, "post_code": 336400, "pid": 360900, "id": 1343, "area_id": 360923 }, { "area_name": "宜丰县", "pinyin": "Yifeng", "level": 3, "area_code": 795, "post_code": 336300, "pid": 360900, "id": 1344, "area_id": 360924 }, { "area_name": "靖安县", "pinyin": "Jing'an", "level": 3, "area_code": 795, "post_code": 330600, "pid": 360900, "id": 1345, "area_id": 360925 }, { "area_name": "铜鼓县", "pinyin": "Tonggu", "level": 3, "area_code": 795, "post_code": 336200, "pid": 360900, "id": 1346, "area_id": 360926 }, { "area_name": "丰城市", "pinyin": "Fengcheng", "level": 3, "area_code": 795, "post_code": 331100, "pid": 360900, "id": 1347, "area_id": 360981 }, { "area_name": "樟树市", "pinyin": "Zhangshu", "level": 3, "area_code": 795, "post_code": 331200, "pid": 360900, "id": 1348, "area_id": 360982 }, { "area_name": "高安市", "pinyin": "Gao'an", "level": 3, "area_code": 795, "post_code": 330800, "pid": 360900, "id": 1349, "area_id": 360983 }, { "area_name": "抚州市", "pinyin": "Fuzhou", "level": 2, "area_code": 794, "post_code": 344000, "pid": 360000, "id": 1350, "area_id": 361000 }, { "area_name": "临川区", "pinyin": "Linchuan", "level": 3, "area_code": 794, "post_code": 344000, "pid": 361000, "id": 1351, "area_id": 361002 }, { "area_name": "南城县", "pinyin": "Nancheng", "level": 3, "area_code": 794, "post_code": 344700, "pid": 361000, "id": 1352, "area_id": 361021 }, { "area_name": "黎川县", "pinyin": "Lichuan", "level": 3, "area_code": 794, "post_code": 344600, "pid": 361000, "id": 1353, "area_id": 361022 }, { "area_name": "南丰县", "pinyin": "Nanfeng", "level": 3, "area_code": 794, "post_code": 344500, "pid": 361000, "id": 1354, "area_id": 361023 }, { "area_name": "崇仁县", "pinyin": "Chongren", "level": 3, "area_code": 794, "post_code": 344200, "pid": 361000, "id": 1355, "area_id": 361024 }, { "area_name": "乐安县", "pinyin": "Le'an", "level": 3, "area_code": 794, "post_code": 344300, "pid": 361000, "id": 1356, "area_id": 361025 }, { "area_name": "宜黄县", "pinyin": "Yihuang", "level": 3, "area_code": 794, "post_code": 344400, "pid": 361000, "id": 1357, "area_id": 361026 }, { "area_name": "金溪县", "pinyin": "Jinxi", "level": 3, "area_code": 794, "post_code": 344800, "pid": 361000, "id": 1358, "area_id": 361027 }, { "area_name": "资溪县", "pinyin": "Zixi", "level": 3, "area_code": 794, "post_code": 335300, "pid": 361000, "id": 1359, "area_id": 361028 }, { "area_name": "东乡县", "pinyin": "Dongxiang", "level": 3, "area_code": 794, "post_code": 331800, "pid": 361000, "id": 1360, "area_id": 361029 }, { "area_name": "广昌县", "pinyin": "Guangchang", "level": 3, "area_code": 794, "post_code": 344900, "pid": 361000, "id": 1361, "area_id": 361030 }, { "area_name": "上饶市", "pinyin": "Shangrao", "level": 2, "area_code": 793, "post_code": 334000, "pid": 360000, "id": 1362, "area_id": 361100 }, { "area_name": "信州区", "pinyin": "Xinzhou", "level": 3, "area_code": 793, "post_code": 334000, "pid": 361100, "id": 1363, "area_id": 361102 }, { "area_name": "上饶县", "pinyin": "Shangrao", "level": 3, "area_code": 793, "post_code": 334100, "pid": 361100, "id": 1364, "area_id": 361121 }, { "area_name": "广丰县", "pinyin": "Guangfeng", "level": 3, "area_code": 793, "post_code": 334600, "pid": 361100, "id": 1365, "area_id": 361122 }, { "area_name": "玉山县", "pinyin": "Yushan", "level": 3, "area_code": 793, "post_code": 334700, "pid": 361100, "id": 1366, "area_id": 361123 }, { "area_name": "铅山县", "pinyin": "Yanshan", "level": 3, "area_code": 793, "post_code": 334500, "pid": 361100, "id": 1367, "area_id": 361124 }, { "area_name": "横峰县", "pinyin": "Hengfeng", "level": 3, "area_code": 793, "post_code": 334300, "pid": 361100, "id": 1368, "area_id": 361125 }, { "area_name": "弋阳县", "pinyin": "Yiyang", "level": 3, "area_code": 793, "post_code": 334400, "pid": 361100, "id": 1369, "area_id": 361126 }, { "area_name": "余干县", "pinyin": "Yugan", "level": 3, "area_code": 793, "post_code": 335100, "pid": 361100, "id": 1370, "area_id": 361127 }, { "area_name": "鄱阳县", "pinyin": "Poyang", "level": 3, "area_code": 793, "post_code": 333100, "pid": 361100, "id": 1371, "area_id": 361128 }, { "area_name": "万年县", "pinyin": "Wannian", "level": 3, "area_code": 793, "post_code": 335500, "pid": 361100, "id": 1372, "area_id": 361129 }, { "area_name": "婺源县", "pinyin": "Wuyuan", "level": 3, "area_code": 793, "post_code": 333200, "pid": 361100, "id": 1373, "area_id": 361130 }, { "area_name": "德兴市", "pinyin": "Dexing", "level": 3, "area_code": 793, "post_code": 334200, "pid": 361100, "id": 1374, "area_id": 361181 }, { "area_name": "山东省", "pinyin": "Shandong", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1375, "area_id": 370000 }, { "area_name": "济南市", "pinyin": "Jinan", "level": 2, "area_code": 531, "post_code": 250001, "pid": 370000, "id": 1376, "area_id": 370100 }, { "area_name": "历下区", "pinyin": "Lixia", "level": 3, "area_code": 531, "post_code": 250014, "pid": 370100, "id": 1377, "area_id": 370102 }, { "area_name": "市中区", "pinyin": "Shizhongqu", "level": 3, "area_code": 531, "post_code": 250001, "pid": 370100, "id": 1378, "area_id": 370103 }, { "area_name": "槐荫区", "pinyin": "Huaiyin", "level": 3, "area_code": 531, "post_code": 250117, "pid": 370100, "id": 1379, "area_id": 370104 }, { "area_name": "天桥区", "pinyin": "Tianqiao", "level": 3, "area_code": 531, "post_code": 250031, "pid": 370100, "id": 1380, "area_id": 370105 }, { "area_name": "历城区", "pinyin": "Licheng", "level": 3, "area_code": 531, "post_code": 250100, "pid": 370100, "id": 1381, "area_id": 370112 }, { "area_name": "长清区", "pinyin": "Changqing", "level": 3, "area_code": 531, "post_code": 250300, "pid": 370100, "id": 1382, "area_id": 370113 }, { "area_name": "平阴县", "pinyin": "Pingyin", "level": 3, "area_code": 531, "post_code": 250400, "pid": 370100, "id": 1383, "area_id": 370124 }, { "area_name": "济阳县", "pinyin": "Jiyang", "level": 3, "area_code": 531, "post_code": 251400, "pid": 370100, "id": 1384, "area_id": 370125 }, { "area_name": "商河县", "pinyin": "Shanghe", "level": 3, "area_code": 531, "post_code": 251600, "pid": 370100, "id": 1385, "area_id": 370126 }, { "area_name": "章丘市", "pinyin": "Zhangqiu", "level": 3, "area_code": 531, "post_code": 250200, "pid": 370100, "id": 1386, "area_id": 370181 }, { "area_name": "青岛市", "pinyin": "Qingdao", "level": 2, "area_code": 532, "post_code": 266001, "pid": 370000, "id": 1387, "area_id": 370200 }, { "area_name": "市南区", "pinyin": "Shinan", "level": 3, "area_code": 532, "post_code": 266001, "pid": 370200, "id": 1388, "area_id": 370202 }, { "area_name": "市北区", "pinyin": "Shibei", "level": 3, "area_code": 532, "post_code": 266011, "pid": 370200, "id": 1389, "area_id": 370203 }, { "area_name": "黄岛区", "pinyin": "Huangdao", "level": 3, "area_code": 532, "post_code": 266500, "pid": 370200, "id": 1390, "area_id": 370211 }, { "area_name": "崂山区", "pinyin": "Laoshan", "level": 3, "area_code": 532, "post_code": 266100, "pid": 370200, "id": 1391, "area_id": 370212 }, { "area_name": "李沧区", "pinyin": "Licang", "level": 3, "area_code": 532, "post_code": 266021, "pid": 370200, "id": 1392, "area_id": 370213 }, { "area_name": "城阳区", "pinyin": "Chengyang", "level": 3, "area_code": 532, "post_code": 266041, "pid": 370200, "id": 1393, "area_id": 370214 }, { "area_name": "胶州市", "pinyin": "Jiaozhou", "level": 3, "area_code": 532, "post_code": 266300, "pid": 370200, "id": 1394, "area_id": 370281 }, { "area_name": "即墨市", "pinyin": "Jimo", "level": 3, "area_code": 532, "post_code": 266200, "pid": 370200, "id": 1395, "area_id": 370282 }, { "area_name": "平度市", "pinyin": "Pingdu", "level": 3, "area_code": 532, "post_code": 266700, "pid": 370200, "id": 1396, "area_id": 370283 }, { "area_name": "莱西市", "pinyin": "Laixi", "level": 3, "area_code": 532, "post_code": 266600, "pid": 370200, "id": 1397, "area_id": 370285 }, { "area_name": "西海岸新区", "pinyin": "Xihai'an", "level": 3, "area_code": 532, "post_code": 266500, "pid": 370200, "id": 1398, "area_id": 370286 }, { "area_name": "淄博市", "pinyin": "Zibo", "level": 2, "area_code": 533, "post_code": 255039, "pid": 370000, "id": 1399, "area_id": 370300 }, { "area_name": "淄川区", "pinyin": "Zichuan", "level": 3, "area_code": 533, "post_code": 255100, "pid": 370300, "id": 1400, "area_id": 370302 }, { "area_name": "张店区", "pinyin": "Zhangdian", "level": 3, "area_code": 533, "post_code": 255022, "pid": 370300, "id": 1401, "area_id": 370303 }, { "area_name": "博山区", "pinyin": "Boshan", "level": 3, "area_code": 533, "post_code": 255200, "pid": 370300, "id": 1402, "area_id": 370304 }, { "area_name": "临淄区", "pinyin": "Linzi", "level": 3, "area_code": 533, "post_code": 255400, "pid": 370300, "id": 1403, "area_id": 370305 }, { "area_name": "周村区", "pinyin": "Zhoucun", "level": 3, "area_code": 533, "post_code": 255300, "pid": 370300, "id": 1404, "area_id": 370306 }, { "area_name": "桓台县", "pinyin": "Huantai", "level": 3, "area_code": 533, "post_code": 256400, "pid": 370300, "id": 1405, "area_id": 370321 }, { "area_name": "高青县", "pinyin": "Gaoqing", "level": 3, "area_code": 533, "post_code": 256300, "pid": 370300, "id": 1406, "area_id": 370322 }, { "area_name": "沂源县", "pinyin": "Yiyuan", "level": 3, "area_code": 533, "post_code": 256100, "pid": 370300, "id": 1407, "area_id": 370323 }, { "area_name": "枣庄市", "pinyin": "Zaozhuang", "level": 2, "area_code": 632, "post_code": 277101, "pid": 370000, "id": 1408, "area_id": 370400 }, { "area_name": "市中区", "pinyin": "Shizhongqu", "level": 3, "area_code": 632, "post_code": 277101, "pid": 370400, "id": 1409, "area_id": 370402 }, { "area_name": "薛城区", "pinyin": "Xuecheng", "level": 3, "area_code": 632, "post_code": 277000, "pid": 370400, "id": 1410, "area_id": 370403 }, { "area_name": "峄城区", "pinyin": "Yicheng", "level": 3, "area_code": 632, "post_code": 277300, "pid": 370400, "id": 1411, "area_id": 370404 }, { "area_name": "台儿庄区", "pinyin": "Taierzhuang", "level": 3, "area_code": 632, "post_code": 277400, "pid": 370400, "id": 1412, "area_id": 370405 }, { "area_name": "山亭区", "pinyin": "Shanting", "level": 3, "area_code": 632, "post_code": 277200, "pid": 370400, "id": 1413, "area_id": 370406 }, { "area_name": "滕州市", "pinyin": "Tengzhou", "level": 3, "area_code": 632, "post_code": 277500, "pid": 370400, "id": 1414, "area_id": 370481 }, { "area_name": "东营市", "pinyin": "Dongying", "level": 2, "area_code": 546, "post_code": 257093, "pid": 370000, "id": 1415, "area_id": 370500 }, { "area_name": "东营区", "pinyin": "Dongying", "level": 3, "area_code": 546, "post_code": 257029, "pid": 370500, "id": 1416, "area_id": 370502 }, { "area_name": "河口区", "pinyin": "Hekou", "level": 3, "area_code": 546, "post_code": 257200, "pid": 370500, "id": 1417, "area_id": 370503 }, { "area_name": "垦利县", "pinyin": "Kenli", "level": 3, "area_code": 546, "post_code": 257500, "pid": 370500, "id": 1418, "area_id": 370521 }, { "area_name": "利津县", "pinyin": "Lijin", "level": 3, "area_code": 546, "post_code": 257400, "pid": 370500, "id": 1419, "area_id": 370522 }, { "area_name": "广饶县", "pinyin": "Guangrao", "level": 3, "area_code": 546, "post_code": 257300, "pid": 370500, "id": 1420, "area_id": 370523 }, { "area_name": "烟台市", "pinyin": "Yantai", "level": 2, "area_code": 635, "post_code": 264010, "pid": 370000, "id": 1421, "area_id": 370600 }, { "area_name": "芝罘区", "pinyin": "Zhifu", "level": 3, "area_code": 635, "post_code": 264001, "pid": 370600, "id": 1422, "area_id": 370602 }, { "area_name": "福山区", "pinyin": "Fushan", "level": 3, "area_code": 635, "post_code": 265500, "pid": 370600, "id": 1423, "area_id": 370611 }, { "area_name": "牟平区", "pinyin": "Muping", "level": 3, "area_code": 635, "post_code": 264100, "pid": 370600, "id": 1424, "area_id": 370612 }, { "area_name": "莱山区", "pinyin": "Laishan", "level": 3, "area_code": 635, "post_code": 264600, "pid": 370600, "id": 1425, "area_id": 370613 }, { "area_name": "长岛县", "pinyin": "Changdao", "level": 3, "area_code": 635, "post_code": 265800, "pid": 370600, "id": 1426, "area_id": 370634 }, { "area_name": "龙口市", "pinyin": "Longkou", "level": 3, "area_code": 635, "post_code": 265700, "pid": 370600, "id": 1427, "area_id": 370681 }, { "area_name": "莱阳市", "pinyin": "Laiyang", "level": 3, "area_code": 635, "post_code": 265200, "pid": 370600, "id": 1428, "area_id": 370682 }, { "area_name": "莱州市", "pinyin": "Laizhou", "level": 3, "area_code": 635, "post_code": 261400, "pid": 370600, "id": 1429, "area_id": 370683 }, { "area_name": "蓬莱市", "pinyin": "Penglai", "level": 3, "area_code": 635, "post_code": 265600, "pid": 370600, "id": 1430, "area_id": 370684 }, { "area_name": "招远市", "pinyin": "Zhaoyuan", "level": 3, "area_code": 635, "post_code": 265400, "pid": 370600, "id": 1431, "area_id": 370685 }, { "area_name": "栖霞市", "pinyin": "Qixia", "level": 3, "area_code": 635, "post_code": 265300, "pid": 370600, "id": 1432, "area_id": 370686 }, { "area_name": "海阳市", "pinyin": "Haiyang", "level": 3, "area_code": 635, "post_code": 265100, "pid": 370600, "id": 1433, "area_id": 370687 }, { "area_name": "潍坊市", "pinyin": "Weifang", "level": 2, "area_code": 536, "post_code": 261041, "pid": 370000, "id": 1434, "area_id": 370700 }, { "area_name": "潍城区", "pinyin": "Weicheng", "level": 3, "area_code": 536, "post_code": 261021, "pid": 370700, "id": 1435, "area_id": 370702 }, { "area_name": "寒亭区", "pinyin": "Hanting", "level": 3, "area_code": 536, "post_code": 261100, "pid": 370700, "id": 1436, "area_id": 370703 }, { "area_name": "坊子区", "pinyin": "Fangzi", "level": 3, "area_code": 536, "post_code": 261200, "pid": 370700, "id": 1437, "area_id": 370704 }, { "area_name": "奎文区", "pinyin": "Kuiwen", "level": 3, "area_code": 536, "post_code": 261031, "pid": 370700, "id": 1438, "area_id": 370705 }, { "area_name": "临朐县", "pinyin": "Linqu", "level": 3, "area_code": 536, "post_code": 262600, "pid": 370700, "id": 1439, "area_id": 370724 }, { "area_name": "昌乐县", "pinyin": "Changle", "level": 3, "area_code": 536, "post_code": 262400, "pid": 370700, "id": 1440, "area_id": 370725 }, { "area_name": "青州市", "pinyin": "Qingzhou", "level": 3, "area_code": 536, "post_code": 262500, "pid": 370700, "id": 1441, "area_id": 370781 }, { "area_name": "诸城市", "pinyin": "Zhucheng", "level": 3, "area_code": 536, "post_code": 262200, "pid": 370700, "id": 1442, "area_id": 370782 }, { "area_name": "寿光市", "pinyin": "Shouguang", "level": 3, "area_code": 536, "post_code": 262700, "pid": 370700, "id": 1443, "area_id": 370783 }, { "area_name": "安丘市", "pinyin": "Anqiu", "level": 3, "area_code": 536, "post_code": 262100, "pid": 370700, "id": 1444, "area_id": 370784 }, { "area_name": "高密市", "pinyin": "Gaomi", "level": 3, "area_code": 536, "post_code": 261500, "pid": 370700, "id": 1445, "area_id": 370785 }, { "area_name": "昌邑市", "pinyin": "Changyi", "level": 3, "area_code": 536, "post_code": 261300, "pid": 370700, "id": 1446, "area_id": 370786 }, { "area_name": "济宁市", "pinyin": "Jining", "level": 2, "area_code": 537, "post_code": 272119, "pid": 370000, "id": 1447, "area_id": 370800 }, { "area_name": "任城区", "pinyin": "Rencheng", "level": 3, "area_code": 537, "post_code": 272113, "pid": 370800, "id": 1448, "area_id": 370811 }, { "area_name": "兖州区", "pinyin": "Yanzhou ", "level": 3, "area_code": 537, "post_code": 272000, "pid": 370800, "id": 1449, "area_id": 370812 }, { "area_name": "微山县", "pinyin": "Weishan", "level": 3, "area_code": 537, "post_code": 277600, "pid": 370800, "id": 1450, "area_id": 370826 }, { "area_name": "鱼台县", "pinyin": "Yutai", "level": 3, "area_code": 537, "post_code": 272300, "pid": 370800, "id": 1451, "area_id": 370827 }, { "area_name": "金乡县", "pinyin": "Jinxiang", "level": 3, "area_code": 537, "post_code": 272200, "pid": 370800, "id": 1452, "area_id": 370828 }, { "area_name": "嘉祥县", "pinyin": "Jiaxiang", "level": 3, "area_code": 537, "post_code": 272400, "pid": 370800, "id": 1453, "area_id": 370829 }, { "area_name": "汶上县", "pinyin": "Wenshang", "level": 3, "area_code": 537, "post_code": 272501, "pid": 370800, "id": 1454, "area_id": 370830 }, { "area_name": "泗水县", "pinyin": "Sishui", "level": 3, "area_code": 537, "post_code": 273200, "pid": 370800, "id": 1455, "area_id": 370831 }, { "area_name": "梁山县", "pinyin": "Liangshan", "level": 3, "area_code": 537, "post_code": 272600, "pid": 370800, "id": 1456, "area_id": 370832 }, { "area_name": "曲阜市", "pinyin": "Qufu", "level": 3, "area_code": 537, "post_code": 273100, "pid": 370800, "id": 1457, "area_id": 370881 }, { "area_name": "邹城市", "pinyin": "Zoucheng", "level": 3, "area_code": 537, "post_code": 273500, "pid": 370800, "id": 1458, "area_id": 370883 }, { "area_name": "泰安市", "pinyin": "Tai'an", "level": 2, "area_code": 538, "post_code": 271000, "pid": 370000, "id": 1459, "area_id": 370900 }, { "area_name": "泰山区", "pinyin": "Taishan", "level": 3, "area_code": 538, "post_code": 271000, "pid": 370900, "id": 1460, "area_id": 370902 }, { "area_name": "岱岳区", "pinyin": "Daiyue", "level": 3, "area_code": 538, "post_code": 271000, "pid": 370900, "id": 1461, "area_id": 370911 }, { "area_name": "宁阳县", "pinyin": "Ningyang", "level": 3, "area_code": 538, "post_code": 271400, "pid": 370900, "id": 1462, "area_id": 370921 }, { "area_name": "东平县", "pinyin": "Dongping", "level": 3, "area_code": 538, "post_code": 271500, "pid": 370900, "id": 1463, "area_id": 370923 }, { "area_name": "新泰市", "pinyin": "Xintai", "level": 3, "area_code": 538, "post_code": 271200, "pid": 370900, "id": 1464, "area_id": 370982 }, { "area_name": "肥城市", "pinyin": "Feicheng", "level": 3, "area_code": 538, "post_code": 271600, "pid": 370900, "id": 1465, "area_id": 370983 }, { "area_name": "威海市", "pinyin": "Weihai", "level": 2, "area_code": 631, "post_code": 264200, "pid": 370000, "id": 1466, "area_id": 371000 }, { "area_name": "环翠区", "pinyin": "Huancui", "level": 3, "area_code": 631, "post_code": 264200, "pid": 371000, "id": 1467, "area_id": 371002 }, { "area_name": "文登区", "pinyin": "Wendeng", "level": 3, "area_code": 631, "post_code": 266440, "pid": 371000, "id": 1468, "area_id": 371003 }, { "area_name": "荣成市", "pinyin": "Rongcheng", "level": 3, "area_code": 631, "post_code": 264300, "pid": 371000, "id": 1469, "area_id": 371082 }, { "area_name": "乳山市", "pinyin": "Rushan", "level": 3, "area_code": 631, "post_code": 264500, "pid": 371000, "id": 1470, "area_id": 371083 }, { "area_name": "日照市", "pinyin": "Rizhao", "level": 2, "area_code": 633, "post_code": 276800, "pid": 370000, "id": 1471, "area_id": 371100 }, { "area_name": "东港区", "pinyin": "Donggang", "level": 3, "area_code": 633, "post_code": 276800, "pid": 371100, "id": 1472, "area_id": 371102 }, { "area_name": "岚山区", "pinyin": "Lanshan", "level": 3, "area_code": 633, "post_code": 276808, "pid": 371100, "id": 1473, "area_id": 371103 }, { "area_name": "五莲县", "pinyin": "Wulian", "level": 3, "area_code": 633, "post_code": 262300, "pid": 371100, "id": 1474, "area_id": 371121 }, { "area_name": "莒县", "pinyin": "Juxian", "level": 3, "area_code": 633, "post_code": 276500, "pid": 371100, "id": 1475, "area_id": 371122 }, { "area_name": "莱芜市", "pinyin": "Laiwu", "level": 2, "area_code": 634, "post_code": 271100, "pid": 370000, "id": 1476, "area_id": 371200 }, { "area_name": "莱城区", "pinyin": "Laicheng", "level": 3, "area_code": 634, "post_code": 271199, "pid": 371200, "id": 1477, "area_id": 371202 }, { "area_name": "钢城区", "pinyin": "Gangcheng", "level": 3, "area_code": 634, "post_code": 271100, "pid": 371200, "id": 1478, "area_id": 371203 }, { "area_name": "临沂市", "pinyin": "Linyi", "level": 2, "area_code": 539, "post_code": 253000, "pid": 370000, "id": 1479, "area_id": 371300 }, { "area_name": "兰山区", "pinyin": "Lanshan", "level": 3, "area_code": 539, "post_code": 276002, "pid": 371300, "id": 1480, "area_id": 371302 }, { "area_name": "罗庄区", "pinyin": "Luozhuang", "level": 3, "area_code": 539, "post_code": 276022, "pid": 371300, "id": 1481, "area_id": 371311 }, { "area_name": "河东区", "pinyin": "Hedong", "level": 3, "area_code": 539, "post_code": 276034, "pid": 371300, "id": 1482, "area_id": 371312 }, { "area_name": "沂南县", "pinyin": "Yinan", "level": 3, "area_code": 539, "post_code": 276300, "pid": 371300, "id": 1483, "area_id": 371321 }, { "area_name": "郯城县", "pinyin": "Tancheng", "level": 3, "area_code": 539, "post_code": 276100, "pid": 371300, "id": 1484, "area_id": 371322 }, { "area_name": "沂水县", "pinyin": "Yishui", "level": 3, "area_code": 539, "post_code": 276400, "pid": 371300, "id": 1485, "area_id": 371323 }, { "area_name": "兰陵县", "pinyin": "Lanling", "level": 3, "area_code": 539, "post_code": 277700, "pid": 371300, "id": 1486, "area_id": 371324 }, { "area_name": "费县", "pinyin": "Feixian", "level": 3, "area_code": 539, "post_code": 273400, "pid": 371300, "id": 1487, "area_id": 371325 }, { "area_name": "平邑县", "pinyin": "Pingyi", "level": 3, "area_code": 539, "post_code": 273300, "pid": 371300, "id": 1488, "area_id": 371326 }, { "area_name": "莒南县", "pinyin": "Junan", "level": 3, "area_code": 539, "post_code": 276600, "pid": 371300, "id": 1489, "area_id": 371327 }, { "area_name": "蒙阴县", "pinyin": "Mengyin", "level": 3, "area_code": 539, "post_code": 276200, "pid": 371300, "id": 1490, "area_id": 371328 }, { "area_name": "临沭县", "pinyin": "Linshu", "level": 3, "area_code": 539, "post_code": 276700, "pid": 371300, "id": 1491, "area_id": 371329 }, { "area_name": "德州市", "pinyin": "Dezhou", "level": 2, "area_code": 534, "post_code": 253000, "pid": 370000, "id": 1492, "area_id": 371400 }, { "area_name": "德城区", "pinyin": "Decheng", "level": 3, "area_code": 534, "post_code": 253012, "pid": 371400, "id": 1493, "area_id": 371402 }, { "area_name": "陵城区", "pinyin": "Lingcheng", "level": 3, "area_code": 534, "post_code": 253500, "pid": 371400, "id": 1494, "area_id": 371403 }, { "area_name": "宁津县", "pinyin": "Ningjin", "level": 3, "area_code": 534, "post_code": 253400, "pid": 371400, "id": 1495, "area_id": 371422 }, { "area_name": "庆云县", "pinyin": "Qingyun", "level": 3, "area_code": 534, "post_code": 253700, "pid": 371400, "id": 1496, "area_id": 371423 }, { "area_name": "临邑县", "pinyin": "Linyi", "level": 3, "area_code": 534, "post_code": 251500, "pid": 371400, "id": 1497, "area_id": 371424 }, { "area_name": "齐河县", "pinyin": "Qihe", "level": 3, "area_code": 534, "post_code": 251100, "pid": 371400, "id": 1498, "area_id": 371425 }, { "area_name": "平原县", "pinyin": "Pingyuan", "level": 3, "area_code": 534, "post_code": 253100, "pid": 371400, "id": 1499, "area_id": 371426 }, { "area_name": "夏津县", "pinyin": "Xiajin", "level": 3, "area_code": 534, "post_code": 253200, "pid": 371400, "id": 1500, "area_id": 371427 }, { "area_name": "武城县", "pinyin": "Wucheng", "level": 3, "area_code": 534, "post_code": 253300, "pid": 371400, "id": 1501, "area_id": 371428 }, { "area_name": "乐陵市", "pinyin": "Leling", "level": 3, "area_code": 534, "post_code": 253600, "pid": 371400, "id": 1502, "area_id": 371481 }, { "area_name": "禹城市", "pinyin": "Yucheng", "level": 3, "area_code": 534, "post_code": 251200, "pid": 371400, "id": 1503, "area_id": 371482 }, { "area_name": "聊城市", "pinyin": "Liaocheng", "level": 2, "area_code": 635, "post_code": 252052, "pid": 370000, "id": 1504, "area_id": 371500 }, { "area_name": "东昌府区", "pinyin": "Dongchangfu", "level": 3, "area_code": 635, "post_code": 252000, "pid": 371500, "id": 1505, "area_id": 371502 }, { "area_name": "阳谷县", "pinyin": "Yanggu", "level": 3, "area_code": 635, "post_code": 252300, "pid": 371500, "id": 1506, "area_id": 371521 }, { "area_name": "莘县", "pinyin": "Shenxian", "level": 3, "area_code": 635, "post_code": 252400, "pid": 371500, "id": 1507, "area_id": 371522 }, { "area_name": "茌平县", "pinyin": "Chiping", "level": 3, "area_code": 635, "post_code": 252100, "pid": 371500, "id": 1508, "area_id": 371523 }, { "area_name": "东阿县", "pinyin": "Dong'e", "level": 3, "area_code": 635, "post_code": 252200, "pid": 371500, "id": 1509, "area_id": 371524 }, { "area_name": "冠县", "pinyin": "Guanxian", "level": 3, "area_code": 635, "post_code": 252500, "pid": 371500, "id": 1510, "area_id": 371525 }, { "area_name": "高唐县", "pinyin": "Gaotang", "level": 3, "area_code": 635, "post_code": 252800, "pid": 371500, "id": 1511, "area_id": 371526 }, { "area_name": "临清市", "pinyin": "Linqing", "level": 3, "area_code": 635, "post_code": 252600, "pid": 371500, "id": 1512, "area_id": 371581 }, { "area_name": "滨州市", "pinyin": "Binzhou", "level": 2, "area_code": 543, "post_code": 256619, "pid": 370000, "id": 1513, "area_id": 371600 }, { "area_name": "滨城区", "pinyin": "Bincheng", "level": 3, "area_code": 543, "post_code": 256613, "pid": 371600, "id": 1514, "area_id": 371602 }, { "area_name": "沾化区", "pinyin": "Zhanhua", "level": 3, "area_code": 543, "post_code": 256800, "pid": 371600, "id": 1515, "area_id": 371603 }, { "area_name": "惠民县", "pinyin": "Huimin", "level": 3, "area_code": 543, "post_code": 251700, "pid": 371600, "id": 1516, "area_id": 371621 }, { "area_name": "阳信县", "pinyin": "Yangxin", "level": 3, "area_code": 543, "post_code": 251800, "pid": 371600, "id": 1517, "area_id": 371622 }, { "area_name": "无棣县", "pinyin": "Wudi", "level": 3, "area_code": 543, "post_code": 251900, "pid": 371600, "id": 1518, "area_id": 371623 }, { "area_name": "博兴县", "pinyin": "Boxing", "level": 3, "area_code": 543, "post_code": 256500, "pid": 371600, "id": 1519, "area_id": 371625 }, { "area_name": "邹平县", "pinyin": "Zouping", "level": 3, "area_code": 543, "post_code": 256200, "pid": 371600, "id": 1520, "area_id": 371626 }, { "area_name": "北海新区", "pinyin": "Beihaixinqu", "level": 3, "area_code": 543, "post_code": 256200, "pid": 371600, "id": 1521, "area_id": 371627 }, { "area_name": "菏泽市", "pinyin": "Heze", "level": 2, "area_code": 530, "post_code": 274020, "pid": 370000, "id": 1522, "area_id": 371700 }, { "area_name": "牡丹区", "pinyin": "Mudan", "level": 3, "area_code": 530, "post_code": 274009, "pid": 371700, "id": 1523, "area_id": 371702 }, { "area_name": "曹县", "pinyin": "Caoxian", "level": 3, "area_code": 530, "post_code": 274400, "pid": 371700, "id": 1524, "area_id": 371721 }, { "area_name": "单县", "pinyin": "Shanxian", "level": 3, "area_code": 530, "post_code": 273700, "pid": 371700, "id": 1525, "area_id": 371722 }, { "area_name": "成武县", "pinyin": "Chengwu", "level": 3, "area_code": 530, "post_code": 274200, "pid": 371700, "id": 1526, "area_id": 371723 }, { "area_name": "巨野县", "pinyin": "Juye", "level": 3, "area_code": 530, "post_code": 274900, "pid": 371700, "id": 1527, "area_id": 371724 }, { "area_name": "郓城县", "pinyin": "Yuncheng", "level": 3, "area_code": 530, "post_code": 274700, "pid": 371700, "id": 1528, "area_id": 371725 }, { "area_name": "鄄城县", "pinyin": "Juancheng", "level": 3, "area_code": 530, "post_code": 274600, "pid": 371700, "id": 1529, "area_id": 371726 }, { "area_name": "定陶县", "pinyin": "Dingtao", "level": 3, "area_code": 530, "post_code": 274100, "pid": 371700, "id": 1530, "area_id": 371727 }, { "area_name": "东明县", "pinyin": "Dongming", "level": 3, "area_code": 530, "post_code": 274500, "pid": 371700, "id": 1531, "area_id": 371728 }, { "area_name": "河南省", "pinyin": "Henan", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1532, "area_id": 410000 }, { "area_name": "郑州市", "pinyin": "Zhengzhou", "level": 2, "area_code": 371, "post_code": 450000, "pid": 410000, "id": 1533, "area_id": 410100 }, { "area_name": "中原区", "pinyin": "Zhongyuan", "level": 3, "area_code": 371, "post_code": 450007, "pid": 410100, "id": 1534, "area_id": 410102 }, { "area_name": "二七区", "pinyin": "Erqi", "level": 3, "area_code": 371, "post_code": 450052, "pid": 410100, "id": 1535, "area_id": 410103 }, { "area_name": "管城回族区", "pinyin": "Guancheng", "level": 3, "area_code": 371, "post_code": 450000, "pid": 410100, "id": 1536, "area_id": 410104 }, { "area_name": "金水区", "pinyin": "Jinshui", "level": 3, "area_code": 371, "post_code": 450003, "pid": 410100, "id": 1537, "area_id": 410105 }, { "area_name": "上街区", "pinyin": "Shangjie", "level": 3, "area_code": 371, "post_code": 450041, "pid": 410100, "id": 1538, "area_id": 410106 }, { "area_name": "惠济区", "pinyin": "Huiji", "level": 3, "area_code": 371, "post_code": 450053, "pid": 410100, "id": 1539, "area_id": 410108 }, { "area_name": "中牟县", "pinyin": "Zhongmu", "level": 3, "area_code": 371, "post_code": 451450, "pid": 410100, "id": 1540, "area_id": 410122 }, { "area_name": "巩义市", "pinyin": "Gongyi", "level": 3, "area_code": 371, "post_code": 451200, "pid": 410100, "id": 1541, "area_id": 410181 }, { "area_name": "荥阳市", "pinyin": "Xingyang", "level": 3, "area_code": 371, "post_code": 450100, "pid": 410100, "id": 1542, "area_id": 410182 }, { "area_name": "新密市", "pinyin": "Xinmi", "level": 3, "area_code": 371, "post_code": 452300, "pid": 410100, "id": 1543, "area_id": 410183 }, { "area_name": "新郑市", "pinyin": "Xinzheng", "level": 3, "area_code": 371, "post_code": 451100, "pid": 410100, "id": 1544, "area_id": 410184 }, { "area_name": "登封市", "pinyin": "Dengfeng", "level": 3, "area_code": 371, "post_code": 452470, "pid": 410100, "id": 1545, "area_id": 410185 }, { "area_name": "开封市", "pinyin": "Kaifeng", "level": 2, "area_code": 378, "post_code": 475001, "pid": 410000, "id": 1546, "area_id": 410200 }, { "area_name": "龙亭区", "pinyin": "Longting", "level": 3, "area_code": 378, "post_code": 475100, "pid": 410200, "id": 1547, "area_id": 410202 }, { "area_name": "顺河回族区", "pinyin": "Shunhe", "level": 3, "area_code": 378, "post_code": 475000, "pid": 410200, "id": 1548, "area_id": 410203 }, { "area_name": "鼓楼区", "pinyin": "Gulou", "level": 3, "area_code": 378, "post_code": 475000, "pid": 410200, "id": 1549, "area_id": 410204 }, { "area_name": "禹王台区", "pinyin": "Yuwangtai", "level": 3, "area_code": 378, "post_code": 475003, "pid": 410200, "id": 1550, "area_id": 410205 }, { "area_name": "祥符区", "pinyin": "Xiangfu", "level": 3, "area_code": 378, "post_code": 475100, "pid": 410200, "id": 1551, "area_id": 410212 }, { "area_name": "杞县", "pinyin": "Qixian", "level": 3, "area_code": 378, "post_code": 475200, "pid": 410200, "id": 1552, "area_id": 410221 }, { "area_name": "通许县", "pinyin": "Tongxu", "level": 3, "area_code": 378, "post_code": 475400, "pid": 410200, "id": 1553, "area_id": 410222 }, { "area_name": "尉氏县", "pinyin": "Weishi", "level": 3, "area_code": 378, "post_code": 475500, "pid": 410200, "id": 1554, "area_id": 410223 }, { "area_name": "兰考县", "pinyin": "Lankao", "level": 3, "area_code": 378, "post_code": 475300, "pid": 410200, "id": 1555, "area_id": 410225 }, { "area_name": "洛阳市", "pinyin": "Luoyang", "level": 2, "area_code": 379, "post_code": 471000, "pid": 410000, "id": 1556, "area_id": 410300 }, { "area_name": "老城区", "pinyin": "Laocheng", "level": 3, "area_code": 379, "post_code": 471002, "pid": 410300, "id": 1557, "area_id": 410302 }, { "area_name": "西工区", "pinyin": "Xigong", "level": 3, "area_code": 379, "post_code": 471000, "pid": 410300, "id": 1558, "area_id": 410303 }, { "area_name": "瀍河回族区", "pinyin": "Chanhe", "level": 3, "area_code": 379, "post_code": 471002, "pid": 410300, "id": 1559, "area_id": 410304 }, { "area_name": "涧西区", "pinyin": "Jianxi", "level": 3, "area_code": 379, "post_code": 471003, "pid": 410300, "id": 1560, "area_id": 410305 }, { "area_name": "吉利区", "pinyin": "Jili", "level": 3, "area_code": 379, "post_code": 471012, "pid": 410300, "id": 1561, "area_id": 410306 }, { "area_name": "洛龙区", "pinyin": "Luolong", "level": 3, "area_code": 379, "post_code": 471000, "pid": 410300, "id": 1562, "area_id": 410311 }, { "area_name": "孟津县", "pinyin": "Mengjin", "level": 3, "area_code": 379, "post_code": 471100, "pid": 410300, "id": 1563, "area_id": 410322 }, { "area_name": "新安县", "pinyin": "Xin'an", "level": 3, "area_code": 379, "post_code": 471800, "pid": 410300, "id": 1564, "area_id": 410323 }, { "area_name": "栾川县", "pinyin": "Luanchuan", "level": 3, "area_code": 379, "post_code": 471500, "pid": 410300, "id": 1565, "area_id": 410324 }, { "area_name": "嵩县", "pinyin": "Songxian", "level": 3, "area_code": 379, "post_code": 471400, "pid": 410300, "id": 1566, "area_id": 410325 }, { "area_name": "汝阳县", "pinyin": "Ruyang", "level": 3, "area_code": 379, "post_code": 471200, "pid": 410300, "id": 1567, "area_id": 410326 }, { "area_name": "宜阳县", "pinyin": "Yiyang", "level": 3, "area_code": 379, "post_code": 471600, "pid": 410300, "id": 1568, "area_id": 410327 }, { "area_name": "洛宁县", "pinyin": "Luoning", "level": 3, "area_code": 379, "post_code": 471700, "pid": 410300, "id": 1569, "area_id": 410328 }, { "area_name": "伊川县", "pinyin": "Yichuan", "level": 3, "area_code": 379, "post_code": 471300, "pid": 410300, "id": 1570, "area_id": 410329 }, { "area_name": "偃师市", "pinyin": "Yanshi", "level": 3, "area_code": 379, "post_code": 471900, "pid": 410300, "id": 1571, "area_id": 410381 }, { "area_name": "平顶山市", "pinyin": "Pingdingshan", "level": 2, "area_code": 375, "post_code": 467000, "pid": 410000, "id": 1572, "area_id": 410400 }, { "area_name": "新华区", "pinyin": "Xinhua", "level": 3, "area_code": 375, "post_code": 467002, "pid": 410400, "id": 1573, "area_id": 410402 }, { "area_name": "卫东区", "pinyin": "Weidong", "level": 3, "area_code": 375, "post_code": 467021, "pid": 410400, "id": 1574, "area_id": 410403 }, { "area_name": "石龙区", "pinyin": "Shilong", "level": 3, "area_code": 375, "post_code": 467045, "pid": 410400, "id": 1575, "area_id": 410404 }, { "area_name": "湛河区", "pinyin": "Zhanhe", "level": 3, "area_code": 375, "post_code": 467000, "pid": 410400, "id": 1576, "area_id": 410411 }, { "area_name": "宝丰县", "pinyin": "Baofeng", "level": 3, "area_code": 375, "post_code": 467400, "pid": 410400, "id": 1577, "area_id": 410421 }, { "area_name": "叶县", "pinyin": "Yexian", "level": 3, "area_code": 375, "post_code": 467200, "pid": 410400, "id": 1578, "area_id": 410422 }, { "area_name": "鲁山县", "pinyin": "Lushan", "level": 3, "area_code": 375, "post_code": 467300, "pid": 410400, "id": 1579, "area_id": 410423 }, { "area_name": "郏县", "pinyin": "Jiaxian", "level": 3, "area_code": 375, "post_code": 467100, "pid": 410400, "id": 1580, "area_id": 410425 }, { "area_name": "舞钢市", "pinyin": "Wugang", "level": 3, "area_code": 375, "post_code": 462500, "pid": 410400, "id": 1581, "area_id": 410481 }, { "area_name": "汝州市", "pinyin": "Ruzhou", "level": 3, "area_code": 375, "post_code": 467500, "pid": 410400, "id": 1582, "area_id": 410482 }, { "area_name": "安阳市", "pinyin": "Anyang", "level": 2, "area_code": 372, "post_code": 455000, "pid": 410000, "id": 1583, "area_id": 410500 }, { "area_name": "文峰区", "pinyin": "Wenfeng", "level": 3, "area_code": 372, "post_code": 455000, "pid": 410500, "id": 1584, "area_id": 410502 }, { "area_name": "北关区", "pinyin": "Beiguan", "level": 3, "area_code": 372, "post_code": 455001, "pid": 410500, "id": 1585, "area_id": 410503 }, { "area_name": "殷都区", "pinyin": "Yindu", "level": 3, "area_code": 372, "post_code": 455004, "pid": 410500, "id": 1586, "area_id": 410505 }, { "area_name": "龙安区", "pinyin": "Long'an", "level": 3, "area_code": 372, "post_code": 455001, "pid": 410500, "id": 1587, "area_id": 410506 }, { "area_name": "安阳县", "pinyin": "Anyang", "level": 3, "area_code": 372, "post_code": 455000, "pid": 410500, "id": 1588, "area_id": 410522 }, { "area_name": "汤阴县", "pinyin": "Tangyin", "level": 3, "area_code": 372, "post_code": 456150, "pid": 410500, "id": 1589, "area_id": 410523 }, { "area_name": "滑县", "pinyin": "Huaxian", "level": 3, "area_code": 372, "post_code": 456400, "pid": 410500, "id": 1590, "area_id": 410526 }, { "area_name": "内黄县", "pinyin": "Neihuang", "level": 3, "area_code": 372, "post_code": 456350, "pid": 410500, "id": 1591, "area_id": 410527 }, { "area_name": "林州市", "pinyin": "Linzhou", "level": 3, "area_code": 372, "post_code": 456550, "pid": 410500, "id": 1592, "area_id": 410581 }, { "area_name": "鹤壁市", "pinyin": "Hebi", "level": 2, "area_code": 392, "post_code": 458030, "pid": 410000, "id": 1593, "area_id": 410600 }, { "area_name": "鹤山区", "pinyin": "Heshan", "level": 3, "area_code": 392, "post_code": 458010, "pid": 410600, "id": 1594, "area_id": 410602 }, { "area_name": "山城区", "pinyin": "Shancheng", "level": 3, "area_code": 392, "post_code": 458000, "pid": 410600, "id": 1595, "area_id": 410603 }, { "area_name": "淇滨区", "pinyin": "Qibin", "level": 3, "area_code": 392, "post_code": 458000, "pid": 410600, "id": 1596, "area_id": 410611 }, { "area_name": "浚县", "pinyin": "Xunxian", "level": 3, "area_code": 392, "post_code": 456250, "pid": 410600, "id": 1597, "area_id": 410621 }, { "area_name": "淇县", "pinyin": "Qixian", "level": 3, "area_code": 392, "post_code": 456750, "pid": 410600, "id": 1598, "area_id": 410622 }, { "area_name": "新乡市", "pinyin": "Xinxiang", "level": 2, "area_code": 373, "post_code": 453000, "pid": 410000, "id": 1599, "area_id": 410700 }, { "area_name": "红旗区", "pinyin": "Hongqi", "level": 3, "area_code": 373, "post_code": 453000, "pid": 410700, "id": 1600, "area_id": 410702 }, { "area_name": "卫滨区", "pinyin": "Weibin", "level": 3, "area_code": 373, "post_code": 453000, "pid": 410700, "id": 1601, "area_id": 410703 }, { "area_name": "凤泉区", "pinyin": "Fengquan", "level": 3, "area_code": 373, "post_code": 453011, "pid": 410700, "id": 1602, "area_id": 410704 }, { "area_name": "牧野区", "pinyin": "Muye", "level": 3, "area_code": 373, "post_code": 453002, "pid": 410700, "id": 1603, "area_id": 410711 }, { "area_name": "新乡县", "pinyin": "Xinxiang", "level": 3, "area_code": 373, "post_code": 453700, "pid": 410700, "id": 1604, "area_id": 410721 }, { "area_name": "获嘉县", "pinyin": "Huojia", "level": 3, "area_code": 373, "post_code": 453800, "pid": 410700, "id": 1605, "area_id": 410724 }, { "area_name": "原阳县", "pinyin": "Yuanyang", "level": 3, "area_code": 373, "post_code": 453500, "pid": 410700, "id": 1606, "area_id": 410725 }, { "area_name": "延津县", "pinyin": "Yanjin", "level": 3, "area_code": 373, "post_code": 453200, "pid": 410700, "id": 1607, "area_id": 410726 }, { "area_name": "封丘县", "pinyin": "Fengqiu", "level": 3, "area_code": 373, "post_code": 453300, "pid": 410700, "id": 1608, "area_id": 410727 }, { "area_name": "长垣县", "pinyin": "Changyuan", "level": 3, "area_code": 373, "post_code": 453400, "pid": 410700, "id": 1609, "area_id": 410728 }, { "area_name": "卫辉市", "pinyin": "Weihui", "level": 3, "area_code": 373, "post_code": 453100, "pid": 410700, "id": 1610, "area_id": 410781 }, { "area_name": "辉县市", "pinyin": "Huixian", "level": 3, "area_code": 373, "post_code": 453600, "pid": 410700, "id": 1611, "area_id": 410782 }, { "area_name": "焦作市", "pinyin": "Jiaozuo", "level": 2, "area_code": 391, "post_code": 454002, "pid": 410000, "id": 1612, "area_id": 410800 }, { "area_name": "解放区", "pinyin": "Jiefang", "level": 3, "area_code": 391, "post_code": 454000, "pid": 410800, "id": 1613, "area_id": 410802 }, { "area_name": "中站区", "pinyin": "Zhongzhan", "level": 3, "area_code": 391, "post_code": 454191, "pid": 410800, "id": 1614, "area_id": 410803 }, { "area_name": "马村区", "pinyin": "Macun", "level": 3, "area_code": 391, "post_code": 454171, "pid": 410800, "id": 1615, "area_id": 410804 }, { "area_name": "山阳区", "pinyin": "Shanyang", "level": 3, "area_code": 391, "post_code": 454002, "pid": 410800, "id": 1616, "area_id": 410811 }, { "area_name": "修武县", "pinyin": "Xiuwu", "level": 3, "area_code": 391, "post_code": 454350, "pid": 410800, "id": 1617, "area_id": 410821 }, { "area_name": "博爱县", "pinyin": "Boai", "level": 3, "area_code": 391, "post_code": 454450, "pid": 410800, "id": 1618, "area_id": 410822 }, { "area_name": "武陟县", "pinyin": "Wuzhi", "level": 3, "area_code": 391, "post_code": 454950, "pid": 410800, "id": 1619, "area_id": 410823 }, { "area_name": "温县", "pinyin": "Wenxian", "level": 3, "area_code": 391, "post_code": 454850, "pid": 410800, "id": 1620, "area_id": 410825 }, { "area_name": "沁阳市", "pinyin": "Qinyang", "level": 3, "area_code": 391, "post_code": 454550, "pid": 410800, "id": 1621, "area_id": 410882 }, { "area_name": "孟州市", "pinyin": "Mengzhou", "level": 3, "area_code": 391, "post_code": 454750, "pid": 410800, "id": 1622, "area_id": 410883 }, { "area_name": "濮阳市", "pinyin": "Puyang", "level": 2, "area_code": 393, "post_code": 457000, "pid": 410000, "id": 1623, "area_id": 410900 }, { "area_name": "华龙区", "pinyin": "Hualong", "level": 3, "area_code": 393, "post_code": 457001, "pid": 410900, "id": 1624, "area_id": 410902 }, { "area_name": "清丰县", "pinyin": "Qingfeng", "level": 3, "area_code": 393, "post_code": 457300, "pid": 410900, "id": 1625, "area_id": 410922 }, { "area_name": "南乐县", "pinyin": "Nanle", "level": 3, "area_code": 393, "post_code": 457400, "pid": 410900, "id": 1626, "area_id": 410923 }, { "area_name": "范县", "pinyin": "Fanxian", "level": 3, "area_code": 393, "post_code": 457500, "pid": 410900, "id": 1627, "area_id": 410926 }, { "area_name": "台前县", "pinyin": "Taiqian", "level": 3, "area_code": 393, "post_code": 457600, "pid": 410900, "id": 1628, "area_id": 410927 }, { "area_name": "濮阳县", "pinyin": "Puyang", "level": 3, "area_code": 393, "post_code": 457100, "pid": 410900, "id": 1629, "area_id": 410928 }, { "area_name": "许昌市", "pinyin": "Xuchang", "level": 2, "area_code": 374, "post_code": 461000, "pid": 410000, "id": 1630, "area_id": 411000 }, { "area_name": "魏都区", "pinyin": "Weidu", "level": 3, "area_code": 374, "post_code": 461000, "pid": 411000, "id": 1631, "area_id": 411002 }, { "area_name": "许昌县", "pinyin": "Xuchang", "level": 3, "area_code": 374, "post_code": 461100, "pid": 411000, "id": 1632, "area_id": 411023 }, { "area_name": "鄢陵县", "pinyin": "Yanling", "level": 3, "area_code": 374, "post_code": 461200, "pid": 411000, "id": 1633, "area_id": 411024 }, { "area_name": "襄城县", "pinyin": "Xiangcheng", "level": 3, "area_code": 374, "post_code": 461700, "pid": 411000, "id": 1634, "area_id": 411025 }, { "area_name": "禹州市", "pinyin": "Yuzhou", "level": 3, "area_code": 374, "post_code": 461670, "pid": 411000, "id": 1635, "area_id": 411081 }, { "area_name": "长葛市", "pinyin": "Changge", "level": 3, "area_code": 374, "post_code": 461500, "pid": 411000, "id": 1636, "area_id": 411082 }, { "area_name": "漯河市", "pinyin": "Luohe", "level": 2, "area_code": 395, "post_code": 462000, "pid": 410000, "id": 1637, "area_id": 411100 }, { "area_name": "源汇区", "pinyin": "Yuanhui", "level": 3, "area_code": 395, "post_code": 462000, "pid": 411100, "id": 1638, "area_id": 411102 }, { "area_name": "郾城区", "pinyin": "Yancheng", "level": 3, "area_code": 395, "post_code": 462300, "pid": 411100, "id": 1639, "area_id": 411103 }, { "area_name": "召陵区", "pinyin": "Zhaoling", "level": 3, "area_code": 395, "post_code": 462300, "pid": 411100, "id": 1640, "area_id": 411104 }, { "area_name": "舞阳县", "pinyin": "Wuyang", "level": 3, "area_code": 395, "post_code": 462400, "pid": 411100, "id": 1641, "area_id": 411121 }, { "area_name": "临颍县", "pinyin": "Linying", "level": 3, "area_code": 395, "post_code": 462600, "pid": 411100, "id": 1642, "area_id": 411122 }, { "area_name": "三门峡市", "pinyin": "Sanmenxia", "level": 2, "area_code": 398, "post_code": 472000, "pid": 410000, "id": 1643, "area_id": 411200 }, { "area_name": "湖滨区", "pinyin": "Hubin", "level": 3, "area_code": 398, "post_code": 472000, "pid": 411200, "id": 1644, "area_id": 411202 }, { "area_name": "渑池县", "pinyin": "Mianchi", "level": 3, "area_code": 398, "post_code": 472400, "pid": 411200, "id": 1645, "area_id": 411221 }, { "area_name": "陕县", "pinyin": "Shanxian", "level": 3, "area_code": 398, "post_code": 472100, "pid": 411200, "id": 1646, "area_id": 411222 }, { "area_name": "卢氏县", "pinyin": "Lushi", "level": 3, "area_code": 398, "post_code": 472200, "pid": 411200, "id": 1647, "area_id": 411224 }, { "area_name": "义马市", "pinyin": "Yima", "level": 3, "area_code": 398, "post_code": 472300, "pid": 411200, "id": 1648, "area_id": 411281 }, { "area_name": "灵宝市", "pinyin": "Lingbao", "level": 3, "area_code": 398, "post_code": 472500, "pid": 411200, "id": 1649, "area_id": 411282 }, { "area_name": "南阳市", "pinyin": "Nanyang", "level": 2, "area_code": 377, "post_code": 473002, "pid": 410000, "id": 1650, "area_id": 411300 }, { "area_name": "宛城区", "pinyin": "Wancheng", "level": 3, "area_code": 377, "post_code": 473001, "pid": 411300, "id": 1651, "area_id": 411302 }, { "area_name": "卧龙区", "pinyin": "Wolong", "level": 3, "area_code": 377, "post_code": 473003, "pid": 411300, "id": 1652, "area_id": 411303 }, { "area_name": "南召县", "pinyin": "Nanzhao", "level": 3, "area_code": 377, "post_code": 474650, "pid": 411300, "id": 1653, "area_id": 411321 }, { "area_name": "方城县", "pinyin": "Fangcheng", "level": 3, "area_code": 377, "post_code": 473200, "pid": 411300, "id": 1654, "area_id": 411322 }, { "area_name": "西峡县", "pinyin": "Xixia", "level": 3, "area_code": 377, "post_code": 474550, "pid": 411300, "id": 1655, "area_id": 411323 }, { "area_name": "镇平县", "pinyin": "Zhenping", "level": 3, "area_code": 377, "post_code": 474250, "pid": 411300, "id": 1656, "area_id": 411324 }, { "area_name": "内乡县", "pinyin": "Neixiang", "level": 3, "area_code": 377, "post_code": 474350, "pid": 411300, "id": 1657, "area_id": 411325 }, { "area_name": "淅川县", "pinyin": "Xichuan", "level": 3, "area_code": 377, "post_code": 474450, "pid": 411300, "id": 1658, "area_id": 411326 }, { "area_name": "社旗县", "pinyin": "Sheqi", "level": 3, "area_code": 377, "post_code": 473300, "pid": 411300, "id": 1659, "area_id": 411327 }, { "area_name": "唐河县", "pinyin": "Tanghe", "level": 3, "area_code": 377, "post_code": 473400, "pid": 411300, "id": 1660, "area_id": 411328 }, { "area_name": "新野县", "pinyin": "Xinye", "level": 3, "area_code": 377, "post_code": 473500, "pid": 411300, "id": 1661, "area_id": 411329 }, { "area_name": "桐柏县", "pinyin": "Tongbai", "level": 3, "area_code": 377, "post_code": 474750, "pid": 411300, "id": 1662, "area_id": 411330 }, { "area_name": "邓州市", "pinyin": "Dengzhou", "level": 3, "area_code": 377, "post_code": 474150, "pid": 411300, "id": 1663, "area_id": 411381 }, { "area_name": "商丘市", "pinyin": "Shangqiu", "level": 2, "area_code": 370, "post_code": 476000, "pid": 410000, "id": 1664, "area_id": 411400 }, { "area_name": "梁园区", "pinyin": "Liangyuan", "level": 3, "area_code": 370, "post_code": 476000, "pid": 411400, "id": 1665, "area_id": 411402 }, { "area_name": "睢阳区", "pinyin": "Suiyang", "level": 3, "area_code": 370, "post_code": 476100, "pid": 411400, "id": 1666, "area_id": 411403 }, { "area_name": "民权县", "pinyin": "Minquan", "level": 3, "area_code": 370, "post_code": 476800, "pid": 411400, "id": 1667, "area_id": 411421 }, { "area_name": "睢县", "pinyin": "Suixian", "level": 3, "area_code": 370, "post_code": 476900, "pid": 411400, "id": 1668, "area_id": 411422 }, { "area_name": "宁陵县", "pinyin": "Ningling", "level": 3, "area_code": 370, "post_code": 476700, "pid": 411400, "id": 1669, "area_id": 411423 }, { "area_name": "柘城县", "pinyin": "Zhecheng", "level": 3, "area_code": 370, "post_code": 476200, "pid": 411400, "id": 1670, "area_id": 411424 }, { "area_name": "虞城县", "pinyin": "Yucheng", "level": 3, "area_code": 370, "post_code": 476300, "pid": 411400, "id": 1671, "area_id": 411425 }, { "area_name": "夏邑县", "pinyin": "Xiayi", "level": 3, "area_code": 370, "post_code": 476400, "pid": 411400, "id": 1672, "area_id": 411426 }, { "area_name": "永城市", "pinyin": "Yongcheng", "level": 3, "area_code": 370, "post_code": 476600, "pid": 411400, "id": 1673, "area_id": 411481 }, { "area_name": "信阳市", "pinyin": "Xinyang", "level": 2, "area_code": 376, "post_code": 464000, "pid": 410000, "id": 1674, "area_id": 411500 }, { "area_name": "浉河区", "pinyin": "Shihe", "level": 3, "area_code": 376, "post_code": 464000, "pid": 411500, "id": 1675, "area_id": 411502 }, { "area_name": "平桥区", "pinyin": "Pingqiao", "level": 3, "area_code": 376, "post_code": 464100, "pid": 411500, "id": 1676, "area_id": 411503 }, { "area_name": "罗山县", "pinyin": "Luoshan", "level": 3, "area_code": 376, "post_code": 464200, "pid": 411500, "id": 1677, "area_id": 411521 }, { "area_name": "光山县", "pinyin": "Guangshan", "level": 3, "area_code": 376, "post_code": 465450, "pid": 411500, "id": 1678, "area_id": 411522 }, { "area_name": "新县", "pinyin": "Xinxian", "level": 3, "area_code": 376, "post_code": 465550, "pid": 411500, "id": 1679, "area_id": 411523 }, { "area_name": "商城县", "pinyin": "Shangcheng", "level": 3, "area_code": 376, "post_code": 465350, "pid": 411500, "id": 1680, "area_id": 411524 }, { "area_name": "固始县", "pinyin": "Gushi", "level": 3, "area_code": 376, "post_code": 465250, "pid": 411500, "id": 1681, "area_id": 411525 }, { "area_name": "潢川县", "pinyin": "Huangchuan", "level": 3, "area_code": 376, "post_code": 465150, "pid": 411500, "id": 1682, "area_id": 411526 }, { "area_name": "淮滨县", "pinyin": "Huaibin", "level": 3, "area_code": 376, "post_code": 464400, "pid": 411500, "id": 1683, "area_id": 411527 }, { "area_name": "息县", "pinyin": "Xixian", "level": 3, "area_code": 376, "post_code": 464300, "pid": 411500, "id": 1684, "area_id": 411528 }, { "area_name": "周口市", "pinyin": "Zhoukou", "level": 2, "area_code": 394, "post_code": 466000, "pid": 410000, "id": 1685, "area_id": 411600 }, { "area_name": "川汇区", "pinyin": "Chuanhui", "level": 3, "area_code": 394, "post_code": 466000, "pid": 411600, "id": 1686, "area_id": 411602 }, { "area_name": "扶沟县", "pinyin": "Fugou", "level": 3, "area_code": 394, "post_code": 461300, "pid": 411600, "id": 1687, "area_id": 411621 }, { "area_name": "西华县", "pinyin": "Xihua", "level": 3, "area_code": 394, "post_code": 466600, "pid": 411600, "id": 1688, "area_id": 411622 }, { "area_name": "商水县", "pinyin": "Shangshui", "level": 3, "area_code": 394, "post_code": 466100, "pid": 411600, "id": 1689, "area_id": 411623 }, { "area_name": "沈丘县", "pinyin": "Shenqiu", "level": 3, "area_code": 394, "post_code": 466300, "pid": 411600, "id": 1690, "area_id": 411624 }, { "area_name": "郸城县", "pinyin": "Dancheng", "level": 3, "area_code": 394, "post_code": 477150, "pid": 411600, "id": 1691, "area_id": 411625 }, { "area_name": "淮阳县", "pinyin": "Huaiyang", "level": 3, "area_code": 394, "post_code": 466700, "pid": 411600, "id": 1692, "area_id": 411626 }, { "area_name": "太康县", "pinyin": "Taikang", "level": 3, "area_code": 394, "post_code": 461400, "pid": 411600, "id": 1693, "area_id": 411627 }, { "area_name": "鹿邑县", "pinyin": "Luyi", "level": 3, "area_code": 394, "post_code": 477200, "pid": 411600, "id": 1694, "area_id": 411628 }, { "area_name": "项城市", "pinyin": "Xiangcheng", "level": 3, "area_code": 394, "post_code": 466200, "pid": 411600, "id": 1695, "area_id": 411681 }, { "area_name": "驻马店市", "pinyin": "Zhumadian", "level": 2, "area_code": 396, "post_code": 463000, "pid": 410000, "id": 1696, "area_id": 411700 }, { "area_name": "驿城区", "pinyin": "Yicheng", "level": 3, "area_code": 396, "post_code": 463000, "pid": 411700, "id": 1697, "area_id": 411702 }, { "area_name": "西平县", "pinyin": "Xiping", "level": 3, "area_code": 396, "post_code": 463900, "pid": 411700, "id": 1698, "area_id": 411721 }, { "area_name": "上蔡县", "pinyin": "Shangcai", "level": 3, "area_code": 396, "post_code": 463800, "pid": 411700, "id": 1699, "area_id": 411722 }, { "area_name": "平舆县", "pinyin": "Pingyu", "level": 3, "area_code": 396, "post_code": 463400, "pid": 411700, "id": 1700, "area_id": 411723 }, { "area_name": "正阳县", "pinyin": "Zhengyang", "level": 3, "area_code": 396, "post_code": 463600, "pid": 411700, "id": 1701, "area_id": 411724 }, { "area_name": "确山县", "pinyin": "Queshan", "level": 3, "area_code": 396, "post_code": 463200, "pid": 411700, "id": 1702, "area_id": 411725 }, { "area_name": "泌阳县", "pinyin": "Biyang", "level": 3, "area_code": 396, "post_code": 463700, "pid": 411700, "id": 1703, "area_id": 411726 }, { "area_name": "汝南县", "pinyin": "Runan", "level": 3, "area_code": 396, "post_code": 463300, "pid": 411700, "id": 1704, "area_id": 411727 }, { "area_name": "遂平县", "pinyin": "Suiping", "level": 3, "area_code": 396, "post_code": 463100, "pid": 411700, "id": 1705, "area_id": 411728 }, { "area_name": "新蔡县", "pinyin": "Xincai", "level": 3, "area_code": 396, "post_code": 463500, "pid": 411700, "id": 1706, "area_id": 411729 }, { "area_name": "直辖县级", "pinyin": "", "level": 2, "area_code": null, "post_code": null, "pid": 410000, "id": 1707, "area_id": 419000 }, { "area_name": "济源市", "pinyin": "Jiyuan", "level": 3, "area_code": 391, "post_code": 454650, "pid": 419000, "id": 1708, "area_id": 419001 }, { "area_name": "湖北省", "pinyin": "Hubei", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1709, "area_id": 420000 }, { "area_name": "武汉市", "pinyin": "Wuhan", "level": 2, "area_code": null, "post_code": 430014, "pid": 420000, "id": 1710, "area_id": 420100 }, { "area_name": "江岸区", "pinyin": "Jiang'an", "level": 3, "area_code": 27, "post_code": 430014, "pid": 420100, "id": 1711, "area_id": 420102 }, { "area_name": "江汉区", "pinyin": "Jianghan", "level": 3, "area_code": 27, "post_code": 430021, "pid": 420100, "id": 1712, "area_id": 420103 }, { "area_name": "硚口区", "pinyin": "Qiaokou", "level": 3, "area_code": 27, "post_code": 430033, "pid": 420100, "id": 1713, "area_id": 420104 }, { "area_name": "汉阳区", "pinyin": "Hanyang", "level": 3, "area_code": 27, "post_code": 430050, "pid": 420100, "id": 1714, "area_id": 420105 }, { "area_name": "武昌区", "pinyin": "Wuchang", "level": 3, "area_code": 27, "post_code": 430061, "pid": 420100, "id": 1715, "area_id": 420106 }, { "area_name": "青山区", "pinyin": "Qingshan", "level": 3, "area_code": 27, "post_code": 430080, "pid": 420100, "id": 1716, "area_id": 420107 }, { "area_name": "洪山区", "pinyin": "Hongshan", "level": 3, "area_code": 27, "post_code": 430070, "pid": 420100, "id": 1717, "area_id": 420111 }, { "area_name": "东西湖区", "pinyin": "Dongxihu", "level": 3, "area_code": 27, "post_code": 430040, "pid": 420100, "id": 1718, "area_id": 420112 }, { "area_name": "汉南区", "pinyin": "Hannan", "level": 3, "area_code": 27, "post_code": 430090, "pid": 420100, "id": 1719, "area_id": 420113 }, { "area_name": "蔡甸区", "pinyin": "Caidian", "level": 3, "area_code": 27, "post_code": 430100, "pid": 420100, "id": 1720, "area_id": 420114 }, { "area_name": "江夏区", "pinyin": "Jiangxia", "level": 3, "area_code": 27, "post_code": 430200, "pid": 420100, "id": 1721, "area_id": 420115 }, { "area_name": "黄陂区", "pinyin": "Huangpi", "level": 3, "area_code": 27, "post_code": 432200, "pid": 420100, "id": 1722, "area_id": 420116 }, { "area_name": "新洲区", "pinyin": "Xinzhou", "level": 3, "area_code": 27, "post_code": 431400, "pid": 420100, "id": 1723, "area_id": 420117 }, { "area_name": "黄石市", "pinyin": "Huangshi", "level": 2, "area_code": 714, "post_code": 435003, "pid": 420000, "id": 1724, "area_id": 420200 }, { "area_name": "黄石港区", "pinyin": "Huangshigang", "level": 3, "area_code": 714, "post_code": 435000, "pid": 420200, "id": 1725, "area_id": 420202 }, { "area_name": "西塞山区", "pinyin": "Xisaishan", "level": 3, "area_code": 714, "post_code": 435001, "pid": 420200, "id": 1726, "area_id": 420203 }, { "area_name": "下陆区", "pinyin": "Xialu", "level": 3, "area_code": 714, "post_code": 435005, "pid": 420200, "id": 1727, "area_id": 420204 }, { "area_name": "铁山区", "pinyin": "Tieshan", "level": 3, "area_code": 714, "post_code": 435006, "pid": 420200, "id": 1728, "area_id": 420205 }, { "area_name": "阳新县", "pinyin": "Yangxin", "level": 3, "area_code": 714, "post_code": 435200, "pid": 420200, "id": 1729, "area_id": 420222 }, { "area_name": "大冶市", "pinyin": "Daye", "level": 3, "area_code": 714, "post_code": 435100, "pid": 420200, "id": 1730, "area_id": 420281 }, { "area_name": "十堰市", "pinyin": "Shiyan", "level": 2, "area_code": 719, "post_code": 442000, "pid": 420000, "id": 1731, "area_id": 420300 }, { "area_name": "茅箭区", "pinyin": "Maojian", "level": 3, "area_code": 719, "post_code": 442012, "pid": 420300, "id": 1732, "area_id": 420302 }, { "area_name": "张湾区", "pinyin": "Zhangwan", "level": 3, "area_code": 719, "post_code": 442001, "pid": 420300, "id": 1733, "area_id": 420303 }, { "area_name": "郧阳区", "pinyin": "Yunyang", "level": 3, "area_code": 719, "post_code": 442500, "pid": 420300, "id": 1734, "area_id": 420304 }, { "area_name": "郧西县", "pinyin": "Yunxi", "level": 3, "area_code": 719, "post_code": 442600, "pid": 420300, "id": 1735, "area_id": 420322 }, { "area_name": "竹山县", "pinyin": "Zhushan", "level": 3, "area_code": 719, "post_code": 442200, "pid": 420300, "id": 1736, "area_id": 420323 }, { "area_name": "竹溪县", "pinyin": "Zhuxi", "level": 3, "area_code": 719, "post_code": 442300, "pid": 420300, "id": 1737, "area_id": 420324 }, { "area_name": "房县", "pinyin": "Fangxian", "level": 3, "area_code": 719, "post_code": 442100, "pid": 420300, "id": 1738, "area_id": 420325 }, { "area_name": "丹江口市", "pinyin": "Danjiangkou", "level": 3, "area_code": 719, "post_code": 442700, "pid": 420300, "id": 1739, "area_id": 420381 }, { "area_name": "宜昌市", "pinyin": "Yichang", "level": 2, "area_code": 717, "post_code": 443000, "pid": 420000, "id": 1740, "area_id": 420500 }, { "area_name": "西陵区", "pinyin": "Xiling", "level": 3, "area_code": 717, "post_code": 443000, "pid": 420500, "id": 1741, "area_id": 420502 }, { "area_name": "伍家岗区", "pinyin": "Wujiagang", "level": 3, "area_code": 717, "post_code": 443001, "pid": 420500, "id": 1742, "area_id": 420503 }, { "area_name": "点军区", "pinyin": "Dianjun", "level": 3, "area_code": 717, "post_code": 443006, "pid": 420500, "id": 1743, "area_id": 420504 }, { "area_name": "猇亭区", "pinyin": "Xiaoting", "level": 3, "area_code": 717, "post_code": 443007, "pid": 420500, "id": 1744, "area_id": 420505 }, { "area_name": "夷陵区", "pinyin": "Yiling", "level": 3, "area_code": 717, "post_code": 443100, "pid": 420500, "id": 1745, "area_id": 420506 }, { "area_name": "远安县", "pinyin": "Yuan'an", "level": 3, "area_code": 717, "post_code": 444200, "pid": 420500, "id": 1746, "area_id": 420525 }, { "area_name": "兴山县", "pinyin": "Xingshan", "level": 3, "area_code": 717, "post_code": 443711, "pid": 420500, "id": 1747, "area_id": 420526 }, { "area_name": "秭归县", "pinyin": "Zigui", "level": 3, "area_code": 717, "post_code": 443600, "pid": 420500, "id": 1748, "area_id": 420527 }, { "area_name": "长阳土家族自治县", "pinyin": "Changyang", "level": 3, "area_code": 717, "post_code": 443500, "pid": 420500, "id": 1749, "area_id": 420528 }, { "area_name": "五峰土家族自治县", "pinyin": "Wufeng", "level": 3, "area_code": 717, "post_code": 443413, "pid": 420500, "id": 1750, "area_id": 420529 }, { "area_name": "宜都市", "pinyin": "Yidu", "level": 3, "area_code": 717, "post_code": 443300, "pid": 420500, "id": 1751, "area_id": 420581 }, { "area_name": "当阳市", "pinyin": "Dangyang", "level": 3, "area_code": 717, "post_code": 444100, "pid": 420500, "id": 1752, "area_id": 420582 }, { "area_name": "枝江市", "pinyin": "Zhijiang", "level": 3, "area_code": 717, "post_code": 443200, "pid": 420500, "id": 1753, "area_id": 420583 }, { "area_name": "襄阳市", "pinyin": "Xiangyang", "level": 2, "area_code": 710, "post_code": 441021, "pid": 420000, "id": 1754, "area_id": 420600 }, { "area_name": "襄城区", "pinyin": "Xiangcheng", "level": 3, "area_code": 710, "post_code": 441021, "pid": 420600, "id": 1755, "area_id": 420602 }, { "area_name": "樊城区", "pinyin": "Fancheng", "level": 3, "area_code": 710, "post_code": 441001, "pid": 420600, "id": 1756, "area_id": 420606 }, { "area_name": "襄州区", "pinyin": "Xiangzhou", "level": 3, "area_code": 710, "post_code": 441100, "pid": 420600, "id": 1757, "area_id": 420607 }, { "area_name": "南漳县", "pinyin": "Nanzhang", "level": 3, "area_code": 710, "post_code": 441500, "pid": 420600, "id": 1758, "area_id": 420624 }, { "area_name": "谷城县", "pinyin": "Gucheng", "level": 3, "area_code": 710, "post_code": 441700, "pid": 420600, "id": 1759, "area_id": 420625 }, { "area_name": "保康县", "pinyin": "Baokang", "level": 3, "area_code": 710, "post_code": 441600, "pid": 420600, "id": 1760, "area_id": 420626 }, { "area_name": "老河口市", "pinyin": "Laohekou", "level": 3, "area_code": 710, "post_code": 441800, "pid": 420600, "id": 1761, "area_id": 420682 }, { "area_name": "枣阳市", "pinyin": "Zaoyang", "level": 3, "area_code": 710, "post_code": 441200, "pid": 420600, "id": 1762, "area_id": 420683 }, { "area_name": "宜城市", "pinyin": "Yicheng", "level": 3, "area_code": 710, "post_code": 441400, "pid": 420600, "id": 1763, "area_id": 420684 }, { "area_name": "鄂州市", "pinyin": "Ezhou", "level": 2, "area_code": 711, "post_code": 436000, "pid": 420000, "id": 1764, "area_id": 420700 }, { "area_name": "梁子湖区", "pinyin": "Liangzihu", "level": 3, "area_code": 711, "post_code": 436064, "pid": 420700, "id": 1765, "area_id": 420702 }, { "area_name": "华容区", "pinyin": "Huarong", "level": 3, "area_code": 711, "post_code": 436030, "pid": 420700, "id": 1766, "area_id": 420703 }, { "area_name": "鄂城区", "pinyin": "Echeng", "level": 3, "area_code": 711, "post_code": 436000, "pid": 420700, "id": 1767, "area_id": 420704 }, { "area_name": "荆门市", "pinyin": "Jingmen", "level": 2, "area_code": 724, "post_code": 448000, "pid": 420000, "id": 1768, "area_id": 420800 }, { "area_name": "东宝区", "pinyin": "Dongbao", "level": 3, "area_code": 724, "post_code": 448004, "pid": 420800, "id": 1769, "area_id": 420802 }, { "area_name": "掇刀区", "pinyin": "Duodao", "level": 3, "area_code": 724, "post_code": 448124, "pid": 420800, "id": 1770, "area_id": 420804 }, { "area_name": "京山县", "pinyin": "Jingshan", "level": 3, "area_code": 724, "post_code": 431800, "pid": 420800, "id": 1771, "area_id": 420821 }, { "area_name": "沙洋县", "pinyin": "Shayang", "level": 3, "area_code": 724, "post_code": 448200, "pid": 420800, "id": 1772, "area_id": 420822 }, { "area_name": "钟祥市", "pinyin": "Zhongxiang", "level": 3, "area_code": 724, "post_code": 431900, "pid": 420800, "id": 1773, "area_id": 420881 }, { "area_name": "孝感市", "pinyin": "Xiaogan", "level": 2, "area_code": 712, "post_code": 432100, "pid": 420000, "id": 1774, "area_id": 420900 }, { "area_name": "孝南区", "pinyin": "Xiaonan", "level": 3, "area_code": 712, "post_code": 432100, "pid": 420900, "id": 1775, "area_id": 420902 }, { "area_name": "孝昌县", "pinyin": "Xiaochang", "level": 3, "area_code": 712, "post_code": 432900, "pid": 420900, "id": 1776, "area_id": 420921 }, { "area_name": "大悟县", "pinyin": "Dawu", "level": 3, "area_code": 712, "post_code": 432800, "pid": 420900, "id": 1777, "area_id": 420922 }, { "area_name": "云梦县", "pinyin": "Yunmeng", "level": 3, "area_code": 712, "post_code": 432500, "pid": 420900, "id": 1778, "area_id": 420923 }, { "area_name": "应城市", "pinyin": "Yingcheng", "level": 3, "area_code": 712, "post_code": 432400, "pid": 420900, "id": 1779, "area_id": 420981 }, { "area_name": "安陆市", "pinyin": "Anlu", "level": 3, "area_code": 712, "post_code": 432600, "pid": 420900, "id": 1780, "area_id": 420982 }, { "area_name": "汉川市", "pinyin": "Hanchuan", "level": 3, "area_code": 712, "post_code": 432300, "pid": 420900, "id": 1781, "area_id": 420984 }, { "area_name": "荆州市", "pinyin": "Jingzhou", "level": 2, "area_code": 716, "post_code": 434000, "pid": 420000, "id": 1782, "area_id": 421000 }, { "area_name": "沙市区", "pinyin": "Shashi", "level": 3, "area_code": 716, "post_code": 434000, "pid": 421000, "id": 1783, "area_id": 421002 }, { "area_name": "荆州区", "pinyin": "Jingzhou", "level": 3, "area_code": 716, "post_code": 434020, "pid": 421000, "id": 1784, "area_id": 421003 }, { "area_name": "公安县", "pinyin": "Gong'an", "level": 3, "area_code": 716, "post_code": 434300, "pid": 421000, "id": 1785, "area_id": 421022 }, { "area_name": "监利县", "pinyin": "Jianli", "level": 3, "area_code": 716, "post_code": 433300, "pid": 421000, "id": 1786, "area_id": 421023 }, { "area_name": "江陵县", "pinyin": "Jiangling", "level": 3, "area_code": 716, "post_code": 434101, "pid": 421000, "id": 1787, "area_id": 421024 }, { "area_name": "石首市", "pinyin": "Shishou", "level": 3, "area_code": 716, "post_code": 434400, "pid": 421000, "id": 1788, "area_id": 421081 }, { "area_name": "洪湖市", "pinyin": "Honghu", "level": 3, "area_code": 716, "post_code": 433200, "pid": 421000, "id": 1789, "area_id": 421083 }, { "area_name": "松滋市", "pinyin": "Songzi", "level": 3, "area_code": 716, "post_code": 434200, "pid": 421000, "id": 1790, "area_id": 421087 }, { "area_name": "黄冈市", "pinyin": "Huanggang", "level": 2, "area_code": 713, "post_code": 438000, "pid": 420000, "id": 1791, "area_id": 421100 }, { "area_name": "黄州区", "pinyin": "Huangzhou", "level": 3, "area_code": 713, "post_code": 438000, "pid": 421100, "id": 1792, "area_id": 421102 }, { "area_name": "团风县", "pinyin": "Tuanfeng", "level": 3, "area_code": 713, "post_code": 438800, "pid": 421100, "id": 1793, "area_id": 421121 }, { "area_name": "红安县", "pinyin": "Hong'an", "level": 3, "area_code": 713, "post_code": 438401, "pid": 421100, "id": 1794, "area_id": 421122 }, { "area_name": "罗田县", "pinyin": "Luotian", "level": 3, "area_code": 713, "post_code": 438600, "pid": 421100, "id": 1795, "area_id": 421123 }, { "area_name": "英山县", "pinyin": "Yingshan", "level": 3, "area_code": 713, "post_code": 438700, "pid": 421100, "id": 1796, "area_id": 421124 }, { "area_name": "浠水县", "pinyin": "Xishui", "level": 3, "area_code": 713, "post_code": 438200, "pid": 421100, "id": 1797, "area_id": 421125 }, { "area_name": "蕲春县", "pinyin": "Qichun", "level": 3, "area_code": 713, "post_code": 435300, "pid": 421100, "id": 1798, "area_id": 421126 }, { "area_name": "黄梅县", "pinyin": "Huangmei", "level": 3, "area_code": 713, "post_code": 435500, "pid": 421100, "id": 1799, "area_id": 421127 }, { "area_name": "麻城市", "pinyin": "Macheng", "level": 3, "area_code": 713, "post_code": 438300, "pid": 421100, "id": 1800, "area_id": 421181 }, { "area_name": "武穴市", "pinyin": "Wuxue", "level": 3, "area_code": 713, "post_code": 435400, "pid": 421100, "id": 1801, "area_id": 421182 }, { "area_name": "咸宁市", "pinyin": "Xianning", "level": 2, "area_code": 715, "post_code": 437000, "pid": 420000, "id": 1802, "area_id": 421200 }, { "area_name": "咸安区", "pinyin": "Xian'an", "level": 3, "area_code": 715, "post_code": 437000, "pid": 421200, "id": 1803, "area_id": 421202 }, { "area_name": "嘉鱼县", "pinyin": "Jiayu", "level": 3, "area_code": 715, "post_code": 437200, "pid": 421200, "id": 1804, "area_id": 421221 }, { "area_name": "通城县", "pinyin": "Tongcheng", "level": 3, "area_code": 715, "post_code": 437400, "pid": 421200, "id": 1805, "area_id": 421222 }, { "area_name": "崇阳县", "pinyin": "Chongyang", "level": 3, "area_code": 715, "post_code": 437500, "pid": 421200, "id": 1806, "area_id": 421223 }, { "area_name": "通山县", "pinyin": "Tongshan", "level": 3, "area_code": 715, "post_code": 437600, "pid": 421200, "id": 1807, "area_id": 421224 }, { "area_name": "赤壁市", "pinyin": "Chibi", "level": 3, "area_code": 715, "post_code": 437300, "pid": 421200, "id": 1808, "area_id": 421281 }, { "area_name": "随州市", "pinyin": "Suizhou", "level": 2, "area_code": 722, "post_code": 441300, "pid": 420000, "id": 1809, "area_id": 421300 }, { "area_name": "曾都区", "pinyin": "Zengdu", "level": 3, "area_code": 722, "post_code": 441300, "pid": 421300, "id": 1810, "area_id": 421303 }, { "area_name": "随县", "pinyin": "Suixian", "level": 3, "area_code": 722, "post_code": 441309, "pid": 421300, "id": 1811, "area_id": 421321 }, { "area_name": "广水市", "pinyin": "Guangshui", "level": 3, "area_code": 722, "post_code": 432700, "pid": 421300, "id": 1812, "area_id": 421381 }, { "area_name": "恩施土家族苗族自治州", "pinyin": "Enshi", "level": 2, "area_code": 718, "post_code": 445000, "pid": 420000, "id": 1813, "area_id": 422800 }, { "area_name": "恩施市", "pinyin": "Enshi", "level": 3, "area_code": 718, "post_code": 445000, "pid": 422800, "id": 1814, "area_id": 422801 }, { "area_name": "利川市", "pinyin": "Lichuan", "level": 3, "area_code": 718, "post_code": 445400, "pid": 422800, "id": 1815, "area_id": 422802 }, { "area_name": "建始县", "pinyin": "Jianshi", "level": 3, "area_code": 718, "post_code": 445300, "pid": 422800, "id": 1816, "area_id": 422822 }, { "area_name": "巴东县", "pinyin": "Badong", "level": 3, "area_code": 718, "post_code": 444300, "pid": 422800, "id": 1817, "area_id": 422823 }, { "area_name": "宣恩县", "pinyin": "Xuanen", "level": 3, "area_code": 718, "post_code": 445500, "pid": 422800, "id": 1818, "area_id": 422825 }, { "area_name": "咸丰县", "pinyin": "Xianfeng", "level": 3, "area_code": 718, "post_code": 445600, "pid": 422800, "id": 1819, "area_id": 422826 }, { "area_name": "来凤县", "pinyin": "Laifeng", "level": 3, "area_code": 718, "post_code": 445700, "pid": 422800, "id": 1820, "area_id": 422827 }, { "area_name": "鹤峰县", "pinyin": "Hefeng", "level": 3, "area_code": 718, "post_code": 445800, "pid": 422800, "id": 1821, "area_id": 422828 }, { "area_name": "直辖县级", "pinyin": "", "level": 2, "area_code": null, "post_code": null, "pid": 420000, "id": 1822, "area_id": 429000 }, { "area_name": "仙桃市", "pinyin": "Xiantao", "level": 3, "area_code": 728, "post_code": 433000, "pid": 429000, "id": 1823, "area_id": 429004 }, { "area_name": "潜江市", "pinyin": "Qianjiang", "level": 3, "area_code": 728, "post_code": 433100, "pid": 429000, "id": 1824, "area_id": 429005 }, { "area_name": "天门市", "pinyin": "Tianmen", "level": 3, "area_code": 728, "post_code": 431700, "pid": 429000, "id": 1825, "area_id": 429006 }, { "area_name": "神农架林区", "pinyin": "Shennongjia", "level": 3, "area_code": 719, "post_code": 442400, "pid": 429000, "id": 1826, "area_id": 429021 }, { "area_name": "湖南省", "pinyin": "Hunan", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1827, "area_id": 430000 }, { "area_name": "长沙市", "pinyin": "Changsha", "level": 2, "area_code": 731, "post_code": 410005, "pid": 430000, "id": 1828, "area_id": 430100 }, { "area_name": "芙蓉区", "pinyin": "Furong", "level": 3, "area_code": 731, "post_code": 410011, "pid": 430100, "id": 1829, "area_id": 430102 }, { "area_name": "天心区", "pinyin": "Tianxin", "level": 3, "area_code": 731, "post_code": 410004, "pid": 430100, "id": 1830, "area_id": 430103 }, { "area_name": "岳麓区", "pinyin": "Yuelu", "level": 3, "area_code": 731, "post_code": 410013, "pid": 430100, "id": 1831, "area_id": 430104 }, { "area_name": "开福区", "pinyin": "Kaifu", "level": 3, "area_code": 731, "post_code": 410008, "pid": 430100, "id": 1832, "area_id": 430105 }, { "area_name": "雨花区", "pinyin": "Yuhua", "level": 3, "area_code": 731, "post_code": 410011, "pid": 430100, "id": 1833, "area_id": 430111 }, { "area_name": "望城区", "pinyin": "Wangcheng", "level": 3, "area_code": 731, "post_code": 410200, "pid": 430100, "id": 1834, "area_id": 430112 }, { "area_name": "长沙县", "pinyin": "Changsha", "level": 3, "area_code": 731, "post_code": 410100, "pid": 430100, "id": 1835, "area_id": 430121 }, { "area_name": "宁乡县", "pinyin": "Ningxiang", "level": 3, "area_code": 731, "post_code": 410600, "pid": 430100, "id": 1836, "area_id": 430124 }, { "area_name": "浏阳市", "pinyin": "Liuyang", "level": 3, "area_code": 731, "post_code": 410300, "pid": 430100, "id": 1837, "area_id": 430181 }, { "area_name": "株洲市", "pinyin": "Zhuzhou", "level": 2, "area_code": 731, "post_code": 412000, "pid": 430000, "id": 1838, "area_id": 430200 }, { "area_name": "荷塘区", "pinyin": "Hetang", "level": 3, "area_code": 731, "post_code": 412000, "pid": 430200, "id": 1839, "area_id": 430202 }, { "area_name": "芦淞区", "pinyin": "Lusong", "level": 3, "area_code": 731, "post_code": 412000, "pid": 430200, "id": 1840, "area_id": 430203 }, { "area_name": "石峰区", "pinyin": "Shifeng", "level": 3, "area_code": 731, "post_code": 412005, "pid": 430200, "id": 1841, "area_id": 430204 }, { "area_name": "天元区", "pinyin": "Tianyuan", "level": 3, "area_code": 731, "post_code": 412007, "pid": 430200, "id": 1842, "area_id": 430211 }, { "area_name": "株洲县", "pinyin": "Zhuzhou", "level": 3, "area_code": 731, "post_code": 412100, "pid": 430200, "id": 1843, "area_id": 430221 }, { "area_name": "攸县", "pinyin": "Youxian", "level": 3, "area_code": 731, "post_code": 412300, "pid": 430200, "id": 1844, "area_id": 430223 }, { "area_name": "茶陵县", "pinyin": "Chaling", "level": 3, "area_code": 731, "post_code": 412400, "pid": 430200, "id": 1845, "area_id": 430224 }, { "area_name": "炎陵县", "pinyin": "Yanling", "level": 3, "area_code": 731, "post_code": 412500, "pid": 430200, "id": 1846, "area_id": 430225 }, { "area_name": "醴陵市", "pinyin": "Liling", "level": 3, "area_code": 731, "post_code": 412200, "pid": 430200, "id": 1847, "area_id": 430281 }, { "area_name": "湘潭市", "pinyin": "Xiangtan", "level": 2, "area_code": 731, "post_code": 411100, "pid": 430000, "id": 1848, "area_id": 430300 }, { "area_name": "雨湖区", "pinyin": "Yuhu", "level": 3, "area_code": 731, "post_code": 411100, "pid": 430300, "id": 1849, "area_id": 430302 }, { "area_name": "岳塘区", "pinyin": "Yuetang", "level": 3, "area_code": 731, "post_code": 411101, "pid": 430300, "id": 1850, "area_id": 430304 }, { "area_name": "湘潭县", "pinyin": "Xiangtan", "level": 3, "area_code": 731, "post_code": 411228, "pid": 430300, "id": 1851, "area_id": 430321 }, { "area_name": "湘乡市", "pinyin": "Xiangxiang", "level": 3, "area_code": 731, "post_code": 411400, "pid": 430300, "id": 1852, "area_id": 430381 }, { "area_name": "韶山市", "pinyin": "Shaoshan", "level": 3, "area_code": 731, "post_code": 411300, "pid": 430300, "id": 1853, "area_id": 430382 }, { "area_name": "衡阳市", "pinyin": "Hengyang", "level": 2, "area_code": 734, "post_code": 421001, "pid": 430000, "id": 1854, "area_id": 430400 }, { "area_name": "珠晖区", "pinyin": "Zhuhui", "level": 3, "area_code": 734, "post_code": 421002, "pid": 430400, "id": 1855, "area_id": 430405 }, { "area_name": "雁峰区", "pinyin": "Yanfeng", "level": 3, "area_code": 734, "post_code": 421001, "pid": 430400, "id": 1856, "area_id": 430406 }, { "area_name": "石鼓区", "pinyin": "Shigu", "level": 3, "area_code": 734, "post_code": 421005, "pid": 430400, "id": 1857, "area_id": 430407 }, { "area_name": "蒸湘区", "pinyin": "Zhengxiang", "level": 3, "area_code": 734, "post_code": 421001, "pid": 430400, "id": 1858, "area_id": 430408 }, { "area_name": "南岳区", "pinyin": "Nanyue", "level": 3, "area_code": 734, "post_code": 421900, "pid": 430400, "id": 1859, "area_id": 430412 }, { "area_name": "衡阳县", "pinyin": "Hengyang", "level": 3, "area_code": 734, "post_code": 421200, "pid": 430400, "id": 1860, "area_id": 430421 }, { "area_name": "衡南县", "pinyin": "Hengnan", "level": 3, "area_code": 734, "post_code": 421131, "pid": 430400, "id": 1861, "area_id": 430422 }, { "area_name": "衡山县", "pinyin": "Hengshan", "level": 3, "area_code": 734, "post_code": 421300, "pid": 430400, "id": 1862, "area_id": 430423 }, { "area_name": "衡东县", "pinyin": "Hengdong", "level": 3, "area_code": 734, "post_code": 421400, "pid": 430400, "id": 1863, "area_id": 430424 }, { "area_name": "祁东县", "pinyin": "Qidong", "level": 3, "area_code": 734, "post_code": 421600, "pid": 430400, "id": 1864, "area_id": 430426 }, { "area_name": "耒阳市", "pinyin": "Leiyang", "level": 3, "area_code": 734, "post_code": 421800, "pid": 430400, "id": 1865, "area_id": 430481 }, { "area_name": "常宁市", "pinyin": "Changning", "level": 3, "area_code": 734, "post_code": 421500, "pid": 430400, "id": 1866, "area_id": 430482 }, { "area_name": "邵阳市", "pinyin": "Shaoyang", "level": 2, "area_code": 739, "post_code": 422000, "pid": 430000, "id": 1867, "area_id": 430500 }, { "area_name": "双清区", "pinyin": "Shuangqing", "level": 3, "area_code": 739, "post_code": 422001, "pid": 430500, "id": 1868, "area_id": 430502 }, { "area_name": "大祥区", "pinyin": "Daxiang", "level": 3, "area_code": 739, "post_code": 422000, "pid": 430500, "id": 1869, "area_id": 430503 }, { "area_name": "北塔区", "pinyin": "Beita", "level": 3, "area_code": 739, "post_code": 422007, "pid": 430500, "id": 1870, "area_id": 430511 }, { "area_name": "邵东县", "pinyin": "Shaodong", "level": 3, "area_code": 739, "post_code": 422800, "pid": 430500, "id": 1871, "area_id": 430521 }, { "area_name": "新邵县", "pinyin": "Xinshao", "level": 3, "area_code": 739, "post_code": 422900, "pid": 430500, "id": 1872, "area_id": 430522 }, { "area_name": "邵阳县", "pinyin": "Shaoyang", "level": 3, "area_code": 739, "post_code": 422100, "pid": 430500, "id": 1873, "area_id": 430523 }, { "area_name": "隆回县", "pinyin": "Longhui", "level": 3, "area_code": 739, "post_code": 422200, "pid": 430500, "id": 1874, "area_id": 430524 }, { "area_name": "洞口县", "pinyin": "Dongkou", "level": 3, "area_code": 739, "post_code": 422300, "pid": 430500, "id": 1875, "area_id": 430525 }, { "area_name": "绥宁县", "pinyin": "Suining", "level": 3, "area_code": 739, "post_code": 422600, "pid": 430500, "id": 1876, "area_id": 430527 }, { "area_name": "新宁县", "pinyin": "Xinning", "level": 3, "area_code": 739, "post_code": 422700, "pid": 430500, "id": 1877, "area_id": 430528 }, { "area_name": "城步苗族自治县", "pinyin": "Chengbu", "level": 3, "area_code": 739, "post_code": 422500, "pid": 430500, "id": 1878, "area_id": 430529 }, { "area_name": "武冈市", "pinyin": "Wugang", "level": 3, "area_code": 739, "post_code": 422400, "pid": 430500, "id": 1879, "area_id": 430581 }, { "area_name": "岳阳市", "pinyin": "Yueyang", "level": 2, "area_code": 730, "post_code": 414000, "pid": 430000, "id": 1880, "area_id": 430600 }, { "area_name": "岳阳楼区", "pinyin": "Yueyanglou", "level": 3, "area_code": 730, "post_code": 414000, "pid": 430600, "id": 1881, "area_id": 430602 }, { "area_name": "云溪区", "pinyin": "Yunxi", "level": 3, "area_code": 730, "post_code": 414009, "pid": 430600, "id": 1882, "area_id": 430603 }, { "area_name": "君山区", "pinyin": "Junshan", "level": 3, "area_code": 730, "post_code": 414005, "pid": 430600, "id": 1883, "area_id": 430611 }, { "area_name": "岳阳县", "pinyin": "Yueyang", "level": 3, "area_code": 730, "post_code": 414100, "pid": 430600, "id": 1884, "area_id": 430621 }, { "area_name": "华容县", "pinyin": "Huarong", "level": 3, "area_code": 730, "post_code": 414200, "pid": 430600, "id": 1885, "area_id": 430623 }, { "area_name": "湘阴县", "pinyin": "Xiangyin", "level": 3, "area_code": 730, "post_code": 414600, "pid": 430600, "id": 1886, "area_id": 430624 }, { "area_name": "平江县", "pinyin": "Pingjiang", "level": 3, "area_code": 730, "post_code": 414500, "pid": 430600, "id": 1887, "area_id": 430626 }, { "area_name": "汨罗市", "pinyin": "Miluo", "level": 3, "area_code": 730, "post_code": 414400, "pid": 430600, "id": 1888, "area_id": 430681 }, { "area_name": "临湘市", "pinyin": "Linxiang", "level": 3, "area_code": 730, "post_code": 414300, "pid": 430600, "id": 1889, "area_id": 430682 }, { "area_name": "常德市", "pinyin": "Changde", "level": 2, "area_code": 736, "post_code": 415000, "pid": 430000, "id": 1890, "area_id": 430700 }, { "area_name": "武陵区", "pinyin": "Wuling", "level": 3, "area_code": 736, "post_code": 415000, "pid": 430700, "id": 1891, "area_id": 430702 }, { "area_name": "鼎城区", "pinyin": "Dingcheng", "level": 3, "area_code": 736, "post_code": 415101, "pid": 430700, "id": 1892, "area_id": 430703 }, { "area_name": "安乡县", "pinyin": "Anxiang", "level": 3, "area_code": 736, "post_code": 415600, "pid": 430700, "id": 1893, "area_id": 430721 }, { "area_name": "汉寿县", "pinyin": "Hanshou", "level": 3, "area_code": 736, "post_code": 415900, "pid": 430700, "id": 1894, "area_id": 430722 }, { "area_name": "澧县", "pinyin": "Lixian", "level": 3, "area_code": 736, "post_code": 415500, "pid": 430700, "id": 1895, "area_id": 430723 }, { "area_name": "临澧县", "pinyin": "Linli", "level": 3, "area_code": 736, "post_code": 415200, "pid": 430700, "id": 1896, "area_id": 430724 }, { "area_name": "桃源县", "pinyin": "Taoyuan", "level": 3, "area_code": 736, "post_code": 415700, "pid": 430700, "id": 1897, "area_id": 430725 }, { "area_name": "石门县", "pinyin": "Shimen", "level": 3, "area_code": 736, "post_code": 415300, "pid": 430700, "id": 1898, "area_id": 430726 }, { "area_name": "津市市", "pinyin": "Jinshi", "level": 3, "area_code": 736, "post_code": 415400, "pid": 430700, "id": 1899, "area_id": 430781 }, { "area_name": "张家界市", "pinyin": "Zhangjiajie", "level": 2, "area_code": 744, "post_code": 427000, "pid": 430000, "id": 1900, "area_id": 430800 }, { "area_name": "永定区", "pinyin": "Yongding", "level": 3, "area_code": 744, "post_code": 427000, "pid": 430800, "id": 1901, "area_id": 430802 }, { "area_name": "武陵源区", "pinyin": "Wulingyuan", "level": 3, "area_code": 744, "post_code": 427400, "pid": 430800, "id": 1902, "area_id": 430811 }, { "area_name": "慈利县", "pinyin": "Cili", "level": 3, "area_code": 744, "post_code": 427200, "pid": 430800, "id": 1903, "area_id": 430821 }, { "area_name": "桑植县", "pinyin": "Sangzhi", "level": 3, "area_code": 744, "post_code": 427100, "pid": 430800, "id": 1904, "area_id": 430822 }, { "area_name": "益阳市", "pinyin": "Yiyang", "level": 2, "area_code": 737, "post_code": 413000, "pid": 430000, "id": 1905, "area_id": 430900 }, { "area_name": "资阳区", "pinyin": "Ziyang", "level": 3, "area_code": 737, "post_code": 413001, "pid": 430900, "id": 1906, "area_id": 430902 }, { "area_name": "赫山区", "pinyin": "Heshan", "level": 3, "area_code": 737, "post_code": 413002, "pid": 430900, "id": 1907, "area_id": 430903 }, { "area_name": "南县", "pinyin": "Nanxian", "level": 3, "area_code": 737, "post_code": 413200, "pid": 430900, "id": 1908, "area_id": 430921 }, { "area_name": "桃江县", "pinyin": "Taojiang", "level": 3, "area_code": 737, "post_code": 413400, "pid": 430900, "id": 1909, "area_id": 430922 }, { "area_name": "安化县", "pinyin": "Anhua", "level": 3, "area_code": 737, "post_code": 413500, "pid": 430900, "id": 1910, "area_id": 430923 }, { "area_name": "沅江市", "pinyin": "Yuanjiang", "level": 3, "area_code": 737, "post_code": 413100, "pid": 430900, "id": 1911, "area_id": 430981 }, { "area_name": "郴州市", "pinyin": "Chenzhou", "level": 2, "area_code": 735, "post_code": 423000, "pid": 430000, "id": 1912, "area_id": 431000 }, { "area_name": "北湖区", "pinyin": "Beihu", "level": 3, "area_code": 735, "post_code": 423000, "pid": 431000, "id": 1913, "area_id": 431002 }, { "area_name": "苏仙区", "pinyin": "Suxian", "level": 3, "area_code": 735, "post_code": 423000, "pid": 431000, "id": 1914, "area_id": 431003 }, { "area_name": "桂阳县", "pinyin": "Guiyang", "level": 3, "area_code": 735, "post_code": 424400, "pid": 431000, "id": 1915, "area_id": 431021 }, { "area_name": "宜章县", "pinyin": "Yizhang", "level": 3, "area_code": 735, "post_code": 424200, "pid": 431000, "id": 1916, "area_id": 431022 }, { "area_name": "永兴县", "pinyin": "Yongxing", "level": 3, "area_code": 735, "post_code": 423300, "pid": 431000, "id": 1917, "area_id": 431023 }, { "area_name": "嘉禾县", "pinyin": "Jiahe", "level": 3, "area_code": 735, "post_code": 424500, "pid": 431000, "id": 1918, "area_id": 431024 }, { "area_name": "临武县", "pinyin": "Linwu", "level": 3, "area_code": 735, "post_code": 424300, "pid": 431000, "id": 1919, "area_id": 431025 }, { "area_name": "汝城县", "pinyin": "Rucheng", "level": 3, "area_code": 735, "post_code": 424100, "pid": 431000, "id": 1920, "area_id": 431026 }, { "area_name": "桂东县", "pinyin": "Guidong", "level": 3, "area_code": 735, "post_code": 423500, "pid": 431000, "id": 1921, "area_id": 431027 }, { "area_name": "安仁县", "pinyin": "Anren", "level": 3, "area_code": 735, "post_code": 423600, "pid": 431000, "id": 1922, "area_id": 431028 }, { "area_name": "资兴市", "pinyin": "Zixing", "level": 3, "area_code": 735, "post_code": 423400, "pid": 431000, "id": 1923, "area_id": 431081 }, { "area_name": "永州市", "pinyin": "Yongzhou", "level": 2, "area_code": 746, "post_code": 425000, "pid": 430000, "id": 1924, "area_id": 431100 }, { "area_name": "零陵区", "pinyin": "Lingling", "level": 3, "area_code": 746, "post_code": 425100, "pid": 431100, "id": 1925, "area_id": 431102 }, { "area_name": "冷水滩区", "pinyin": "Lengshuitan", "level": 3, "area_code": 746, "post_code": 425100, "pid": 431100, "id": 1926, "area_id": 431103 }, { "area_name": "祁阳县", "pinyin": "Qiyang", "level": 3, "area_code": 746, "post_code": 426100, "pid": 431100, "id": 1927, "area_id": 431121 }, { "area_name": "东安县", "pinyin": "Dong'an", "level": 3, "area_code": 746, "post_code": 425900, "pid": 431100, "id": 1928, "area_id": 431122 }, { "area_name": "双牌县", "pinyin": "Shuangpai", "level": 3, "area_code": 746, "post_code": 425200, "pid": 431100, "id": 1929, "area_id": 431123 }, { "area_name": "道县", "pinyin": "Daoxian", "level": 3, "area_code": 746, "post_code": 425300, "pid": 431100, "id": 1930, "area_id": 431124 }, { "area_name": "江永县", "pinyin": "Jiangyong", "level": 3, "area_code": 746, "post_code": 425400, "pid": 431100, "id": 1931, "area_id": 431125 }, { "area_name": "宁远县", "pinyin": "Ningyuan", "level": 3, "area_code": 746, "post_code": 425600, "pid": 431100, "id": 1932, "area_id": 431126 }, { "area_name": "蓝山县", "pinyin": "Lanshan", "level": 3, "area_code": 746, "post_code": 425800, "pid": 431100, "id": 1933, "area_id": 431127 }, { "area_name": "新田县", "pinyin": "Xintian", "level": 3, "area_code": 746, "post_code": 425700, "pid": 431100, "id": 1934, "area_id": 431128 }, { "area_name": "江华瑶族自治县", "pinyin": "Jianghua", "level": 3, "area_code": 746, "post_code": 425500, "pid": 431100, "id": 1935, "area_id": 431129 }, { "area_name": "怀化市", "pinyin": "Huaihua", "level": 2, "area_code": 745, "post_code": 418000, "pid": 430000, "id": 1936, "area_id": 431200 }, { "area_name": "鹤城区", "pinyin": "Hecheng", "level": 3, "area_code": 745, "post_code": 418000, "pid": 431200, "id": 1937, "area_id": 431202 }, { "area_name": "中方县", "pinyin": "Zhongfang", "level": 3, "area_code": 745, "post_code": 418005, "pid": 431200, "id": 1938, "area_id": 431221 }, { "area_name": "沅陵县", "pinyin": "Yuanling", "level": 3, "area_code": 745, "post_code": 419600, "pid": 431200, "id": 1939, "area_id": 431222 }, { "area_name": "辰溪县", "pinyin": "Chenxi", "level": 3, "area_code": 745, "post_code": 419500, "pid": 431200, "id": 1940, "area_id": 431223 }, { "area_name": "溆浦县", "pinyin": "Xupu", "level": 3, "area_code": 745, "post_code": 419300, "pid": 431200, "id": 1941, "area_id": 431224 }, { "area_name": "会同县", "pinyin": "Huitong", "level": 3, "area_code": 745, "post_code": 418300, "pid": 431200, "id": 1942, "area_id": 431225 }, { "area_name": "麻阳苗族自治县", "pinyin": "Mayang", "level": 3, "area_code": 745, "post_code": 419400, "pid": 431200, "id": 1943, "area_id": 431226 }, { "area_name": "新晃侗族自治县", "pinyin": "Xinhuang", "level": 3, "area_code": 745, "post_code": 419200, "pid": 431200, "id": 1944, "area_id": 431227 }, { "area_name": "芷江侗族自治县", "pinyin": "Zhijiang", "level": 3, "area_code": 745, "post_code": 419100, "pid": 431200, "id": 1945, "area_id": 431228 }, { "area_name": "靖州苗族侗族自治县", "pinyin": "Jingzhou", "level": 3, "area_code": 745, "post_code": 418400, "pid": 431200, "id": 1946, "area_id": 431229 }, { "area_name": "通道侗族自治县", "pinyin": "Tongdao", "level": 3, "area_code": 745, "post_code": 418500, "pid": 431200, "id": 1947, "area_id": 431230 }, { "area_name": "洪江市", "pinyin": "Hongjiang", "level": 3, "area_code": 745, "post_code": 418100, "pid": 431200, "id": 1948, "area_id": 431281 }, { "area_name": "娄底市", "pinyin": "Loudi", "level": 2, "area_code": 738, "post_code": 417000, "pid": 430000, "id": 1949, "area_id": 431300 }, { "area_name": "娄星区", "pinyin": "Louxing", "level": 3, "area_code": 738, "post_code": 417000, "pid": 431300, "id": 1950, "area_id": 431302 }, { "area_name": "双峰县", "pinyin": "Shuangfeng", "level": 3, "area_code": 738, "post_code": 417700, "pid": 431300, "id": 1951, "area_id": 431321 }, { "area_name": "新化县", "pinyin": "Xinhua", "level": 3, "area_code": 738, "post_code": 417600, "pid": 431300, "id": 1952, "area_id": 431322 }, { "area_name": "冷水江市", "pinyin": "Lengshuijiang", "level": 3, "area_code": 738, "post_code": 417500, "pid": 431300, "id": 1953, "area_id": 431381 }, { "area_name": "涟源市", "pinyin": "Lianyuan", "level": 3, "area_code": 738, "post_code": 417100, "pid": 431300, "id": 1954, "area_id": 431382 }, { "area_name": "湘西土家族苗族自治州", "pinyin": "Xiangxi", "level": 2, "area_code": 743, "post_code": 416000, "pid": 430000, "id": 1955, "area_id": 433100 }, { "area_name": "吉首市", "pinyin": "Jishou", "level": 3, "area_code": 743, "post_code": 416000, "pid": 433100, "id": 1956, "area_id": 433101 }, { "area_name": "泸溪县", "pinyin": "Luxi", "level": 3, "area_code": 743, "post_code": 416100, "pid": 433100, "id": 1957, "area_id": 433122 }, { "area_name": "凤凰县", "pinyin": "Fenghuang", "level": 3, "area_code": 743, "post_code": 416200, "pid": 433100, "id": 1958, "area_id": 433123 }, { "area_name": "花垣县", "pinyin": "Huayuan", "level": 3, "area_code": 743, "post_code": 416400, "pid": 433100, "id": 1959, "area_id": 433124 }, { "area_name": "保靖县", "pinyin": "Baojing", "level": 3, "area_code": 743, "post_code": 416500, "pid": 433100, "id": 1960, "area_id": 433125 }, { "area_name": "古丈县", "pinyin": "Guzhang", "level": 3, "area_code": 743, "post_code": 416300, "pid": 433100, "id": 1961, "area_id": 433126 }, { "area_name": "永顺县", "pinyin": "Yongshun", "level": 3, "area_code": 743, "post_code": 416700, "pid": 433100, "id": 1962, "area_id": 433127 }, { "area_name": "龙山县", "pinyin": "Longshan", "level": 3, "area_code": 743, "post_code": 416800, "pid": 433100, "id": 1963, "area_id": 433130 }, { "area_name": "广东省", "pinyin": "Guangdong", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 1964, "area_id": 440000 }, { "area_name": "广州市", "pinyin": "Guangzhou", "level": 2, "area_code": 20, "post_code": 510032, "pid": 440000, "id": 1965, "area_id": 440100 }, { "area_name": "荔湾区", "pinyin": "Liwan", "level": 3, "area_code": 20, "post_code": 510170, "pid": 440100, "id": 1966, "area_id": 440103 }, { "area_name": "越秀区", "pinyin": "Yuexiu", "level": 3, "area_code": 20, "post_code": 510030, "pid": 440100, "id": 1967, "area_id": 440104 }, { "area_name": "海珠区", "pinyin": "Haizhu", "level": 3, "area_code": 20, "post_code": 510300, "pid": 440100, "id": 1968, "area_id": 440105 }, { "area_name": "天河区", "pinyin": "Tianhe", "level": 3, "area_code": 20, "post_code": 510665, "pid": 440100, "id": 1969, "area_id": 440106 }, { "area_name": "白云区", "pinyin": "Baiyun", "level": 3, "area_code": 20, "post_code": 510405, "pid": 440100, "id": 1970, "area_id": 440111 }, { "area_name": "黄埔区", "pinyin": "Huangpu", "level": 3, "area_code": 20, "post_code": 510700, "pid": 440100, "id": 1971, "area_id": 440112 }, { "area_name": "番禺区", "pinyin": "Panyu", "level": 3, "area_code": 20, "post_code": 511400, "pid": 440100, "id": 1972, "area_id": 440113 }, { "area_name": "花都区", "pinyin": "Huadu", "level": 3, "area_code": 20, "post_code": 510800, "pid": 440100, "id": 1973, "area_id": 440114 }, { "area_name": "南沙区", "pinyin": "Nansha", "level": 3, "area_code": 20, "post_code": 511458, "pid": 440100, "id": 1974, "area_id": 440115 }, { "area_name": "从化区", "pinyin": "Conghua", "level": 3, "area_code": 20, "post_code": 510900, "pid": 440100, "id": 1975, "area_id": 440117 }, { "area_name": "增城区", "pinyin": "Zengcheng", "level": 3, "area_code": 20, "post_code": 511300, "pid": 440100, "id": 1976, "area_id": 440118 }, { "area_name": "韶关市", "pinyin": "Shaoguan", "level": 2, "area_code": 751, "post_code": 512002, "pid": 440000, "id": 1977, "area_id": 440200 }, { "area_name": "武江区", "pinyin": "Wujiang", "level": 3, "area_code": 751, "post_code": 512026, "pid": 440200, "id": 1978, "area_id": 440203 }, { "area_name": "浈江区", "pinyin": "Zhenjiang", "level": 3, "area_code": 751, "post_code": 512023, "pid": 440200, "id": 1979, "area_id": 440204 }, { "area_name": "曲江区", "pinyin": "Qujiang", "level": 3, "area_code": 751, "post_code": 512101, "pid": 440200, "id": 1980, "area_id": 440205 }, { "area_name": "始兴县", "pinyin": "Shixing", "level": 3, "area_code": 751, "post_code": 512500, "pid": 440200, "id": 1981, "area_id": 440222 }, { "area_name": "仁化县", "pinyin": "Renhua", "level": 3, "area_code": 751, "post_code": 512300, "pid": 440200, "id": 1982, "area_id": 440224 }, { "area_name": "翁源县", "pinyin": "Wengyuan", "level": 3, "area_code": 751, "post_code": 512600, "pid": 440200, "id": 1983, "area_id": 440229 }, { "area_name": "乳源瑶族自治县", "pinyin": "Ruyuan", "level": 3, "area_code": 751, "post_code": 512700, "pid": 440200, "id": 1984, "area_id": 440232 }, { "area_name": "新丰县", "pinyin": "Xinfeng", "level": 3, "area_code": 751, "post_code": 511100, "pid": 440200, "id": 1985, "area_id": 440233 }, { "area_name": "乐昌市", "pinyin": "Lechang", "level": 3, "area_code": 751, "post_code": 512200, "pid": 440200, "id": 1986, "area_id": 440281 }, { "area_name": "南雄市", "pinyin": "Nanxiong", "level": 3, "area_code": 751, "post_code": 512400, "pid": 440200, "id": 1987, "area_id": 440282 }, { "area_name": "深圳市", "pinyin": "Shenzhen", "level": 2, "area_code": 755, "post_code": 518035, "pid": 440000, "id": 1988, "area_id": 440300 }, { "area_name": "罗湖区", "pinyin": "Luohu", "level": 3, "area_code": 755, "post_code": 518021, "pid": 440300, "id": 1989, "area_id": 440303 }, { "area_name": "福田区", "pinyin": "Futian", "level": 3, "area_code": 755, "post_code": 518048, "pid": 440300, "id": 1990, "area_id": 440304 }, { "area_name": "南山区", "pinyin": "Nanshan", "level": 3, "area_code": 755, "post_code": 518051, "pid": 440300, "id": 1991, "area_id": 440305 }, { "area_name": "宝安区", "pinyin": "Bao'an", "level": 3, "area_code": 755, "post_code": 518101, "pid": 440300, "id": 1992, "area_id": 440306 }, { "area_name": "龙岗区", "pinyin": "Longgang", "level": 3, "area_code": 755, "post_code": 518172, "pid": 440300, "id": 1993, "area_id": 440307 }, { "area_name": "盐田区", "pinyin": "Yantian", "level": 3, "area_code": 755, "post_code": 518081, "pid": 440300, "id": 1994, "area_id": 440308 }, { "area_name": "光明新区", "pinyin": "Guangmingxinqu", "level": 3, "area_code": 755, "post_code": 518100, "pid": 440300, "id": 1995, "area_id": 440309 }, { "area_name": "坪山新区", "pinyin": "Pingshanxinqu", "level": 3, "area_code": 755, "post_code": 518000, "pid": 440300, "id": 1996, "area_id": 440310 }, { "area_name": "大鹏新区", "pinyin": "Dapengxinqu", "level": 3, "area_code": 755, "post_code": 518000, "pid": 440300, "id": 1997, "area_id": 440311 }, { "area_name": "龙华新区", "pinyin": "Longhuaxinqu", "level": 3, "area_code": 755, "post_code": 518100, "pid": 440300, "id": 1998, "area_id": 440312 }, { "area_name": "珠海市", "pinyin": "Zhuhai", "level": 2, "area_code": 756, "post_code": 519000, "pid": 440000, "id": 1999, "area_id": 440400 }, { "area_name": "香洲区", "pinyin": "Xiangzhou", "level": 3, "area_code": 756, "post_code": 519000, "pid": 440400, "id": 2000, "area_id": 440402 }, { "area_name": "斗门区", "pinyin": "Doumen", "level": 3, "area_code": 756, "post_code": 519110, "pid": 440400, "id": 2001, "area_id": 440403 }, { "area_name": "金湾区", "pinyin": "Jinwan", "level": 3, "area_code": 756, "post_code": 519040, "pid": 440400, "id": 2002, "area_id": 440404 }, { "area_name": "汕头市", "pinyin": "Shantou", "level": 2, "area_code": 754, "post_code": 515041, "pid": 440000, "id": 2003, "area_id": 440500 }, { "area_name": "龙湖区", "pinyin": "Longhu", "level": 3, "area_code": 754, "post_code": 515041, "pid": 440500, "id": 2004, "area_id": 440507 }, { "area_name": "金平区", "pinyin": "Jinping", "level": 3, "area_code": 754, "post_code": 515041, "pid": 440500, "id": 2005, "area_id": 440511 }, { "area_name": "濠江区", "pinyin": "Haojiang", "level": 3, "area_code": 754, "post_code": 515071, "pid": 440500, "id": 2006, "area_id": 440512 }, { "area_name": "潮阳区", "pinyin": "Chaoyang", "level": 3, "area_code": 754, "post_code": 515100, "pid": 440500, "id": 2007, "area_id": 440513 }, { "area_name": "潮南区", "pinyin": "Chaonan", "level": 3, "area_code": 754, "post_code": 515144, "pid": 440500, "id": 2008, "area_id": 440514 }, { "area_name": "澄海区", "pinyin": "Chenghai", "level": 3, "area_code": 754, "post_code": 515800, "pid": 440500, "id": 2009, "area_id": 440515 }, { "area_name": "南澳县", "pinyin": "Nanao", "level": 3, "area_code": 754, "post_code": 515900, "pid": 440500, "id": 2010, "area_id": 440523 }, { "area_name": "佛山市", "pinyin": "Foshan", "level": 2, "area_code": 757, "post_code": 528000, "pid": 440000, "id": 2011, "area_id": 440600 }, { "area_name": "禅城区", "pinyin": "Chancheng", "level": 3, "area_code": 757, "post_code": 528000, "pid": 440600, "id": 2012, "area_id": 440604 }, { "area_name": "南海区", "pinyin": "Nanhai", "level": 3, "area_code": 757, "post_code": 528251, "pid": 440600, "id": 2013, "area_id": 440605 }, { "area_name": "顺德区", "pinyin": "Shunde", "level": 3, "area_code": 757, "post_code": 528300, "pid": 440600, "id": 2014, "area_id": 440606 }, { "area_name": "三水区", "pinyin": "Sanshui", "level": 3, "area_code": 757, "post_code": 528133, "pid": 440600, "id": 2015, "area_id": 440607 }, { "area_name": "高明区", "pinyin": "Gaoming", "level": 3, "area_code": 757, "post_code": 528500, "pid": 440600, "id": 2016, "area_id": 440608 }, { "area_name": "江门市", "pinyin": "Jiangmen", "level": 2, "area_code": 750, "post_code": 529000, "pid": 440000, "id": 2017, "area_id": 440700 }, { "area_name": "蓬江区", "pinyin": "Pengjiang", "level": 3, "area_code": 750, "post_code": 529000, "pid": 440700, "id": 2018, "area_id": 440703 }, { "area_name": "江海区", "pinyin": "Jianghai", "level": 3, "area_code": 750, "post_code": 529040, "pid": 440700, "id": 2019, "area_id": 440704 }, { "area_name": "新会区", "pinyin": "Xinhui", "level": 3, "area_code": 750, "post_code": 529100, "pid": 440700, "id": 2020, "area_id": 440705 }, { "area_name": "台山市", "pinyin": "Taishan", "level": 3, "area_code": 750, "post_code": 529200, "pid": 440700, "id": 2021, "area_id": 440781 }, { "area_name": "开平市", "pinyin": "Kaiping", "level": 3, "area_code": 750, "post_code": 529337, "pid": 440700, "id": 2022, "area_id": 440783 }, { "area_name": "鹤山市", "pinyin": "Heshan", "level": 3, "area_code": 750, "post_code": 529700, "pid": 440700, "id": 2023, "area_id": 440784 }, { "area_name": "恩平市", "pinyin": "Enping", "level": 3, "area_code": 750, "post_code": 529400, "pid": 440700, "id": 2024, "area_id": 440785 }, { "area_name": "湛江市", "pinyin": "Zhanjiang", "level": 2, "area_code": 759, "post_code": 524047, "pid": 440000, "id": 2025, "area_id": 440800 }, { "area_name": "赤坎区", "pinyin": "Chikan", "level": 3, "area_code": 759, "post_code": 524033, "pid": 440800, "id": 2026, "area_id": 440802 }, { "area_name": "霞山区", "pinyin": "Xiashan", "level": 3, "area_code": 759, "post_code": 524011, "pid": 440800, "id": 2027, "area_id": 440803 }, { "area_name": "坡头区", "pinyin": "Potou", "level": 3, "area_code": 759, "post_code": 524057, "pid": 440800, "id": 2028, "area_id": 440804 }, { "area_name": "麻章区", "pinyin": "Mazhang", "level": 3, "area_code": 759, "post_code": 524094, "pid": 440800, "id": 2029, "area_id": 440811 }, { "area_name": "遂溪县", "pinyin": "Suixi", "level": 3, "area_code": 759, "post_code": 524300, "pid": 440800, "id": 2030, "area_id": 440823 }, { "area_name": "徐闻县", "pinyin": "Xuwen", "level": 3, "area_code": 759, "post_code": 524100, "pid": 440800, "id": 2031, "area_id": 440825 }, { "area_name": "廉江市", "pinyin": "Lianjiang", "level": 3, "area_code": 759, "post_code": 524400, "pid": 440800, "id": 2032, "area_id": 440881 }, { "area_name": "雷州市", "pinyin": "Leizhou", "level": 3, "area_code": 759, "post_code": 524200, "pid": 440800, "id": 2033, "area_id": 440882 }, { "area_name": "吴川市", "pinyin": "Wuchuan", "level": 3, "area_code": 759, "post_code": 524500, "pid": 440800, "id": 2034, "area_id": 440883 }, { "area_name": "茂名市", "pinyin": "Maoming", "level": 2, "area_code": 668, "post_code": 525000, "pid": 440000, "id": 2035, "area_id": 440900 }, { "area_name": "茂南区", "pinyin": "Maonan", "level": 3, "area_code": 668, "post_code": 525000, "pid": 440900, "id": 2036, "area_id": 440902 }, { "area_name": "电白区", "pinyin": "Dianbai", "level": 3, "area_code": 668, "post_code": 525400, "pid": 440900, "id": 2037, "area_id": 440904 }, { "area_name": "高州市", "pinyin": "Gaozhou", "level": 3, "area_code": 668, "post_code": 525200, "pid": 440900, "id": 2038, "area_id": 440981 }, { "area_name": "化州市", "pinyin": "Huazhou", "level": 3, "area_code": 668, "post_code": 525100, "pid": 440900, "id": 2039, "area_id": 440982 }, { "area_name": "信宜市", "pinyin": "Xinyi", "level": 3, "area_code": 668, "post_code": 525300, "pid": 440900, "id": 2040, "area_id": 440983 }, { "area_name": "肇庆市", "pinyin": "Zhaoqing", "level": 2, "area_code": 758, "post_code": 526040, "pid": 440000, "id": 2041, "area_id": 441200 }, { "area_name": "端州区", "pinyin": "Duanzhou", "level": 3, "area_code": 758, "post_code": 526060, "pid": 441200, "id": 2042, "area_id": 441202 }, { "area_name": "鼎湖区", "pinyin": "Dinghu", "level": 3, "area_code": 758, "post_code": 526070, "pid": 441200, "id": 2043, "area_id": 441203 }, { "area_name": "广宁县", "pinyin": "Guangning", "level": 3, "area_code": 758, "post_code": 526300, "pid": 441200, "id": 2044, "area_id": 441223 }, { "area_name": "怀集县", "pinyin": "Huaiji", "level": 3, "area_code": 758, "post_code": 526400, "pid": 441200, "id": 2045, "area_id": 441224 }, { "area_name": "封开县", "pinyin": "Fengkai", "level": 3, "area_code": 758, "post_code": 526500, "pid": 441200, "id": 2046, "area_id": 441225 }, { "area_name": "德庆县", "pinyin": "Deqing", "level": 3, "area_code": 758, "post_code": 526600, "pid": 441200, "id": 2047, "area_id": 441226 }, { "area_name": "高要市", "pinyin": "Gaoyao", "level": 3, "area_code": 758, "post_code": 526100, "pid": 441200, "id": 2048, "area_id": 441283 }, { "area_name": "四会市", "pinyin": "Sihui", "level": 3, "area_code": 758, "post_code": 526200, "pid": 441200, "id": 2049, "area_id": 441284 }, { "area_name": "惠州市", "pinyin": "Huizhou", "level": 2, "area_code": 752, "post_code": 516000, "pid": 440000, "id": 2050, "area_id": 441300 }, { "area_name": "惠城区", "pinyin": "Huicheng", "level": 3, "area_code": 752, "post_code": 516008, "pid": 441300, "id": 2051, "area_id": 441302 }, { "area_name": "惠阳区", "pinyin": "Huiyang", "level": 3, "area_code": 752, "post_code": 516211, "pid": 441300, "id": 2052, "area_id": 441303 }, { "area_name": "博罗县", "pinyin": "Boluo", "level": 3, "area_code": 752, "post_code": 516100, "pid": 441300, "id": 2053, "area_id": 441322 }, { "area_name": "惠东县", "pinyin": "Huidong", "level": 3, "area_code": 752, "post_code": 516300, "pid": 441300, "id": 2054, "area_id": 441323 }, { "area_name": "龙门县", "pinyin": "Longmen", "level": 3, "area_code": 752, "post_code": 516800, "pid": 441300, "id": 2055, "area_id": 441324 }, { "area_name": "梅州市", "pinyin": "Meizhou", "level": 2, "area_code": 753, "post_code": 514021, "pid": 440000, "id": 2056, "area_id": 441400 }, { "area_name": "梅江区", "pinyin": "Meijiang", "level": 3, "area_code": 753, "post_code": 514000, "pid": 441400, "id": 2057, "area_id": 441402 }, { "area_name": "梅县区", "pinyin": "Meixian", "level": 3, "area_code": 753, "post_code": 514787, "pid": 441400, "id": 2058, "area_id": 441403 }, { "area_name": "大埔县", "pinyin": "Dabu", "level": 3, "area_code": 753, "post_code": 514200, "pid": 441400, "id": 2059, "area_id": 441422 }, { "area_name": "丰顺县", "pinyin": "Fengshun", "level": 3, "area_code": 753, "post_code": 514300, "pid": 441400, "id": 2060, "area_id": 441423 }, { "area_name": "五华县", "pinyin": "Wuhua", "level": 3, "area_code": 753, "post_code": 514400, "pid": 441400, "id": 2061, "area_id": 441424 }, { "area_name": "平远县", "pinyin": "Pingyuan", "level": 3, "area_code": 753, "post_code": 514600, "pid": 441400, "id": 2062, "area_id": 441426 }, { "area_name": "蕉岭县", "pinyin": "Jiaoling", "level": 3, "area_code": 753, "post_code": 514100, "pid": 441400, "id": 2063, "area_id": 441427 }, { "area_name": "兴宁市", "pinyin": "Xingning", "level": 3, "area_code": 753, "post_code": 514500, "pid": 441400, "id": 2064, "area_id": 441481 }, { "area_name": "汕尾市", "pinyin": "Shanwei", "level": 2, "area_code": 660, "post_code": 516600, "pid": 440000, "id": 2065, "area_id": 441500 }, { "area_name": "城区", "pinyin": "Chengqu", "level": 3, "area_code": 660, "post_code": 516600, "pid": 441500, "id": 2066, "area_id": 441502 }, { "area_name": "海丰县", "pinyin": "Haifeng", "level": 3, "area_code": 660, "post_code": 516400, "pid": 441500, "id": 2067, "area_id": 441521 }, { "area_name": "陆河县", "pinyin": "Luhe", "level": 3, "area_code": 660, "post_code": 516700, "pid": 441500, "id": 2068, "area_id": 441523 }, { "area_name": "陆丰市", "pinyin": "Lufeng", "level": 3, "area_code": 660, "post_code": 516500, "pid": 441500, "id": 2069, "area_id": 441581 }, { "area_name": "河源市", "pinyin": "Heyuan", "level": 2, "area_code": 762, "post_code": 517000, "pid": 440000, "id": 2070, "area_id": 441600 }, { "area_name": "源城区", "pinyin": "Yuancheng", "level": 3, "area_code": 762, "post_code": 517000, "pid": 441600, "id": 2071, "area_id": 441602 }, { "area_name": "紫金县", "pinyin": "Zijin", "level": 3, "area_code": 762, "post_code": 517400, "pid": 441600, "id": 2072, "area_id": 441621 }, { "area_name": "龙川县", "pinyin": "Longchuan", "level": 3, "area_code": 762, "post_code": 517300, "pid": 441600, "id": 2073, "area_id": 441622 }, { "area_name": "连平县", "pinyin": "Lianping", "level": 3, "area_code": 762, "post_code": 517100, "pid": 441600, "id": 2074, "area_id": 441623 }, { "area_name": "和平县", "pinyin": "Heping", "level": 3, "area_code": 762, "post_code": 517200, "pid": 441600, "id": 2075, "area_id": 441624 }, { "area_name": "东源县", "pinyin": "Dongyuan", "level": 3, "area_code": 762, "post_code": 517583, "pid": 441600, "id": 2076, "area_id": 441625 }, { "area_name": "阳江市", "pinyin": "Yangjiang", "level": 2, "area_code": 662, "post_code": 529500, "pid": 440000, "id": 2077, "area_id": 441700 }, { "area_name": "江城区", "pinyin": "Jiangcheng", "level": 3, "area_code": 662, "post_code": 529500, "pid": 441700, "id": 2078, "area_id": 441702 }, { "area_name": "阳东区", "pinyin": "Yangdong", "level": 3, "area_code": 662, "post_code": 529900, "pid": 441700, "id": 2079, "area_id": 441704 }, { "area_name": "阳西县", "pinyin": "Yangxi", "level": 3, "area_code": 662, "post_code": 529800, "pid": 441700, "id": 2080, "area_id": 441721 }, { "area_name": "阳春市", "pinyin": "Yangchun", "level": 3, "area_code": 662, "post_code": 529600, "pid": 441700, "id": 2081, "area_id": 441781 }, { "area_name": "清远市", "pinyin": "Qingyuan", "level": 2, "area_code": 763, "post_code": 511500, "pid": 440000, "id": 2082, "area_id": 441800 }, { "area_name": "清城区", "pinyin": "Qingcheng", "level": 3, "area_code": 763, "post_code": 511515, "pid": 441800, "id": 2083, "area_id": 441802 }, { "area_name": "清新区", "pinyin": "Qingxin", "level": 3, "area_code": 763, "post_code": 511810, "pid": 441800, "id": 2084, "area_id": 441803 }, { "area_name": "佛冈县", "pinyin": "Fogang", "level": 3, "area_code": 763, "post_code": 511600, "pid": 441800, "id": 2085, "area_id": 441821 }, { "area_name": "阳山县", "pinyin": "Yangshan", "level": 3, "area_code": 763, "post_code": 513100, "pid": 441800, "id": 2086, "area_id": 441823 }, { "area_name": "连山壮族瑶族自治县", "pinyin": "Lianshan", "level": 3, "area_code": 763, "post_code": 513200, "pid": 441800, "id": 2087, "area_id": 441825 }, { "area_name": "连南瑶族自治县", "pinyin": "Liannan", "level": 3, "area_code": 763, "post_code": 513300, "pid": 441800, "id": 2088, "area_id": 441826 }, { "area_name": "英德市", "pinyin": "Yingde", "level": 3, "area_code": 763, "post_code": 513000, "pid": 441800, "id": 2089, "area_id": 441881 }, { "area_name": "连州市", "pinyin": "Lianzhou", "level": 3, "area_code": 763, "post_code": 513400, "pid": 441800, "id": 2090, "area_id": 441882 }, { "area_name": "东莞市", "pinyin": "Dongguan", "level": 2, "area_code": 769, "post_code": 523888, "pid": 440000, "id": 2091, "area_id": 441900 }, { "area_name": "莞城区", "pinyin": "Guancheng", "level": 3, "area_code": 769, "post_code": 523128, "pid": 441900, "id": 2092, "area_id": 441901 }, { "area_name": "南城区", "pinyin": "Nancheng", "level": 3, "area_code": 769, "post_code": 523617, "pid": 441900, "id": 2093, "area_id": 441902 }, { "area_name": "万江区", "pinyin": "Wanjiang", "level": 3, "area_code": 769, "post_code": 523039, "pid": 441900, "id": 2094, "area_id": 441904 }, { "area_name": "石碣镇", "pinyin": "Shijie", "level": 3, "area_code": 769, "post_code": 523290, "pid": 441900, "id": 2095, "area_id": 441905 }, { "area_name": "石龙镇", "pinyin": "Shilong", "level": 3, "area_code": 769, "post_code": 523326, "pid": 441900, "id": 2096, "area_id": 441906 }, { "area_name": "茶山镇", "pinyin": "Chashan", "level": 3, "area_code": 769, "post_code": 523380, "pid": 441900, "id": 2097, "area_id": 441907 }, { "area_name": "石排镇", "pinyin": "Shipai", "level": 3, "area_code": 769, "post_code": 523346, "pid": 441900, "id": 2098, "area_id": 441908 }, { "area_name": "企石镇", "pinyin": "Qishi", "level": 3, "area_code": 769, "post_code": 523507, "pid": 441900, "id": 2099, "area_id": 441909 }, { "area_name": "横沥镇", "pinyin": "Hengli", "level": 3, "area_code": 769, "post_code": 523471, "pid": 441900, "id": 2100, "area_id": 441910 }, { "area_name": "桥头镇", "pinyin": "Qiaotou", "level": 3, "area_code": 769, "post_code": 523520, "pid": 441900, "id": 2101, "area_id": 441911 }, { "area_name": "谢岗镇", "pinyin": "Xiegang", "level": 3, "area_code": 769, "post_code": 523592, "pid": 441900, "id": 2102, "area_id": 441912 }, { "area_name": "东坑镇", "pinyin": "Dongkeng", "level": 3, "area_code": 769, "post_code": 523451, "pid": 441900, "id": 2103, "area_id": 441913 }, { "area_name": "常平镇", "pinyin": "Changping", "level": 3, "area_code": 769, "post_code": 523560, "pid": 441900, "id": 2104, "area_id": 441914 }, { "area_name": "寮步镇", "pinyin": "Liaobu", "level": 3, "area_code": 769, "post_code": 523411, "pid": 441900, "id": 2105, "area_id": 441915 }, { "area_name": "大朗镇", "pinyin": "Dalang", "level": 3, "area_code": 769, "post_code": 523770, "pid": 441900, "id": 2106, "area_id": 441916 }, { "area_name": "麻涌镇", "pinyin": "Machong", "level": 3, "area_code": 769, "post_code": 523143, "pid": 441900, "id": 2107, "area_id": 441917 }, { "area_name": "中堂镇", "pinyin": "Zhongtang", "level": 3, "area_code": 769, "post_code": 523233, "pid": 441900, "id": 2108, "area_id": 441918 }, { "area_name": "高埗镇", "pinyin": "Gaobu", "level": 3, "area_code": 769, "post_code": 523282, "pid": 441900, "id": 2109, "area_id": 441919 }, { "area_name": "樟木头镇", "pinyin": "Zhangmutou", "level": 3, "area_code": 769, "post_code": 523619, "pid": 441900, "id": 2110, "area_id": 441920 }, { "area_name": "大岭山镇", "pinyin": "Dalingshan", "level": 3, "area_code": 769, "post_code": 523835, "pid": 441900, "id": 2111, "area_id": 441921 }, { "area_name": "望牛墩镇", "pinyin": "Wangniudun", "level": 3, "area_code": 769, "post_code": 523203, "pid": 441900, "id": 2112, "area_id": 441922 }, { "area_name": "黄江镇", "pinyin": "Huangjiang", "level": 3, "area_code": 769, "post_code": 523755, "pid": 441900, "id": 2113, "area_id": 441923 }, { "area_name": "洪梅镇", "pinyin": "Hongmei", "level": 3, "area_code": 769, "post_code": 523163, "pid": 441900, "id": 2114, "area_id": 441924 }, { "area_name": "清溪镇", "pinyin": "Qingxi", "level": 3, "area_code": 769, "post_code": 523660, "pid": 441900, "id": 2115, "area_id": 441925 }, { "area_name": "沙田镇", "pinyin": "Shatian", "level": 3, "area_code": 769, "post_code": 523988, "pid": 441900, "id": 2116, "area_id": 441926 }, { "area_name": "道滘镇", "pinyin": "Daojiao", "level": 3, "area_code": 769, "post_code": 523171, "pid": 441900, "id": 2117, "area_id": 441927 }, { "area_name": "塘厦镇", "pinyin": "Tangxia", "level": 3, "area_code": 769, "post_code": 523713, "pid": 441900, "id": 2118, "area_id": 441928 }, { "area_name": "虎门镇", "pinyin": "Humen", "level": 3, "area_code": 769, "post_code": 523932, "pid": 441900, "id": 2119, "area_id": 441929 }, { "area_name": "厚街镇", "pinyin": "Houjie", "level": 3, "area_code": 769, "post_code": 523960, "pid": 441900, "id": 2120, "area_id": 441930 }, { "area_name": "凤岗镇", "pinyin": "Fenggang", "level": 3, "area_code": 769, "post_code": 523690, "pid": 441900, "id": 2121, "area_id": 441931 }, { "area_name": "长安镇", "pinyin": "Chang'an", "level": 3, "area_code": 769, "post_code": 523850, "pid": 441900, "id": 2122, "area_id": 441932 }, { "area_name": "中山市", "pinyin": "Zhongshan", "level": 2, "area_code": 760, "post_code": 528403, "pid": 440000, "id": 2123, "area_id": 442000 }, { "area_name": "石岐区", "pinyin": "Shiqi", "level": 3, "area_code": 760, "post_code": 528400, "pid": 442000, "id": 2124, "area_id": 442001 }, { "area_name": "南区", "pinyin": "Nanqu", "level": 3, "area_code": 760, "post_code": 528400, "pid": 442000, "id": 2125, "area_id": 442004 }, { "area_name": "五桂山区", "pinyin": "Wuguishan", "level": 3, "area_code": 760, "post_code": 528458, "pid": 442000, "id": 2126, "area_id": 442005 }, { "area_name": "火炬开发区", "pinyin": "Huoju", "level": 3, "area_code": 760, "post_code": 528437, "pid": 442000, "id": 2127, "area_id": 442006 }, { "area_name": "黄圃镇", "pinyin": "Huangpu", "level": 3, "area_code": 760, "post_code": 528429, "pid": 442000, "id": 2128, "area_id": 442007 }, { "area_name": "南头镇", "pinyin": "Nantou", "level": 3, "area_code": 760, "post_code": 528421, "pid": 442000, "id": 2129, "area_id": 442008 }, { "area_name": "东凤镇", "pinyin": "Dongfeng", "level": 3, "area_code": 760, "post_code": 528425, "pid": 442000, "id": 2130, "area_id": 442009 }, { "area_name": "阜沙镇", "pinyin": "Fusha", "level": 3, "area_code": 760, "post_code": 528434, "pid": 442000, "id": 2131, "area_id": 442010 }, { "area_name": "小榄镇", "pinyin": "Xiaolan", "level": 3, "area_code": 760, "post_code": 528415, "pid": 442000, "id": 2132, "area_id": 442011 }, { "area_name": "东升镇", "pinyin": "Dongsheng", "level": 3, "area_code": 760, "post_code": 528400, "pid": 442000, "id": 2133, "area_id": 442012 }, { "area_name": "古镇镇", "pinyin": "Guzhen", "level": 3, "area_code": 760, "post_code": 528422, "pid": 442000, "id": 2134, "area_id": 442013 }, { "area_name": "横栏镇", "pinyin": "Henglan", "level": 3, "area_code": 760, "post_code": 528478, "pid": 442000, "id": 2135, "area_id": 442014 }, { "area_name": "三角镇", "pinyin": "Sanjiao", "level": 3, "area_code": 760, "post_code": 528422, "pid": 442000, "id": 2136, "area_id": 442015 }, { "area_name": "民众镇", "pinyin": "Minzhong", "level": 3, "area_code": 760, "post_code": 528441, "pid": 442000, "id": 2137, "area_id": 442016 }, { "area_name": "南朗镇", "pinyin": "Nanlang", "level": 3, "area_code": 760, "post_code": 528454, "pid": 442000, "id": 2138, "area_id": 442017 }, { "area_name": "港口镇", "pinyin": "Gangkou", "level": 3, "area_code": 760, "post_code": 528447, "pid": 442000, "id": 2139, "area_id": 442018 }, { "area_name": "大涌镇", "pinyin": "Dayong", "level": 3, "area_code": 760, "post_code": 528476, "pid": 442000, "id": 2140, "area_id": 442019 }, { "area_name": "沙溪镇", "pinyin": "Shaxi", "level": 3, "area_code": 760, "post_code": 528471, "pid": 442000, "id": 2141, "area_id": 442020 }, { "area_name": "三乡镇", "pinyin": "Sanxiang", "level": 3, "area_code": 760, "post_code": 528463, "pid": 442000, "id": 2142, "area_id": 442021 }, { "area_name": "板芙镇", "pinyin": "Banfu", "level": 3, "area_code": 760, "post_code": 528459, "pid": 442000, "id": 2143, "area_id": 442022 }, { "area_name": "神湾镇", "pinyin": "Shenwan", "level": 3, "area_code": 760, "post_code": 528462, "pid": 442000, "id": 2144, "area_id": 442023 }, { "area_name": "坦洲镇", "pinyin": "Tanzhou", "level": 3, "area_code": 760, "post_code": 528467, "pid": 442000, "id": 2145, "area_id": 442024 }, { "area_name": "潮州市", "pinyin": "Chaozhou", "level": 2, "area_code": 768, "post_code": 521000, "pid": 440000, "id": 2146, "area_id": 445100 }, { "area_name": "湘桥区", "pinyin": "Xiangqiao", "level": 3, "area_code": 768, "post_code": 521000, "pid": 445100, "id": 2147, "area_id": 445102 }, { "area_name": "潮安区", "pinyin": "Chao'an", "level": 3, "area_code": 768, "post_code": 515638, "pid": 445100, "id": 2148, "area_id": 445103 }, { "area_name": "饶平县", "pinyin": "Raoping", "level": 3, "area_code": 768, "post_code": 515700, "pid": 445100, "id": 2149, "area_id": 445122 }, { "area_name": "揭阳市", "pinyin": "Jieyang", "level": 2, "area_code": 633, "post_code": 522000, "pid": 440000, "id": 2150, "area_id": 445200 }, { "area_name": "榕城区", "pinyin": "Rongcheng", "level": 3, "area_code": 633, "post_code": 522000, "pid": 445200, "id": 2151, "area_id": 445202 }, { "area_name": "揭东区", "pinyin": "Jiedong", "level": 3, "area_code": 633, "post_code": 515500, "pid": 445200, "id": 2152, "area_id": 445203 }, { "area_name": "揭西县", "pinyin": "Jiexi", "level": 3, "area_code": 633, "post_code": 515400, "pid": 445200, "id": 2153, "area_id": 445222 }, { "area_name": "惠来县", "pinyin": "Huilai", "level": 3, "area_code": 633, "post_code": 515200, "pid": 445200, "id": 2154, "area_id": 445224 }, { "area_name": "普宁市", "pinyin": "Puning", "level": 3, "area_code": 633, "post_code": 515300, "pid": 445200, "id": 2155, "area_id": 445281 }, { "area_name": "云浮市", "pinyin": "Yunfu", "level": 2, "area_code": 766, "post_code": 527300, "pid": 440000, "id": 2156, "area_id": 445300 }, { "area_name": "云城区", "pinyin": "Yuncheng", "level": 3, "area_code": 766, "post_code": 527300, "pid": 445300, "id": 2157, "area_id": 445302 }, { "area_name": "云安区", "pinyin": "Yun'an", "level": 3, "area_code": 766, "post_code": 527500, "pid": 445300, "id": 2158, "area_id": 445303 }, { "area_name": "新兴县", "pinyin": "Xinxing", "level": 3, "area_code": 766, "post_code": 527400, "pid": 445300, "id": 2159, "area_id": 445321 }, { "area_name": "郁南县", "pinyin": "Yunan", "level": 3, "area_code": 766, "post_code": 527100, "pid": 445300, "id": 2160, "area_id": 445322 }, { "area_name": "罗定市", "pinyin": "Luoding", "level": 3, "area_code": 766, "post_code": 527200, "pid": 445300, "id": 2161, "area_id": 445381 }, { "area_name": "广西壮族自治区", "pinyin": "Guangxi", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2162, "area_id": 450000 }, { "area_name": "南宁市", "pinyin": "Nanning", "level": 2, "area_code": 771, "post_code": 530028, "pid": 450000, "id": 2163, "area_id": 450100 }, { "area_name": "兴宁区", "pinyin": "Xingning", "level": 3, "area_code": 771, "post_code": 530023, "pid": 450100, "id": 2164, "area_id": 450102 }, { "area_name": "青秀区", "pinyin": "Qingxiu", "level": 3, "area_code": 771, "post_code": 530213, "pid": 450100, "id": 2165, "area_id": 450103 }, { "area_name": "江南区", "pinyin": "Jiangnan", "level": 3, "area_code": 771, "post_code": 530031, "pid": 450100, "id": 2166, "area_id": 450105 }, { "area_name": "西乡塘区", "pinyin": "Xixiangtang", "level": 3, "area_code": 771, "post_code": 530001, "pid": 450100, "id": 2167, "area_id": 450107 }, { "area_name": "良庆区", "pinyin": "Liangqing", "level": 3, "area_code": 771, "post_code": 530219, "pid": 450100, "id": 2168, "area_id": 450108 }, { "area_name": "邕宁区", "pinyin": "Yongning", "level": 3, "area_code": 771, "post_code": 530200, "pid": 450100, "id": 2169, "area_id": 450109 }, { "area_name": "武鸣县", "pinyin": "Wuming", "level": 3, "area_code": 771, "post_code": 530100, "pid": 450100, "id": 2170, "area_id": 450122 }, { "area_name": "隆安县", "pinyin": "Long'an", "level": 3, "area_code": 771, "post_code": 532700, "pid": 450100, "id": 2171, "area_id": 450123 }, { "area_name": "马山县", "pinyin": "Mashan", "level": 3, "area_code": 771, "post_code": 530600, "pid": 450100, "id": 2172, "area_id": 450124 }, { "area_name": "上林县", "pinyin": "Shanglin", "level": 3, "area_code": 771, "post_code": 530500, "pid": 450100, "id": 2173, "area_id": 450125 }, { "area_name": "宾阳县", "pinyin": "Binyang", "level": 3, "area_code": 771, "post_code": 530400, "pid": 450100, "id": 2174, "area_id": 450126 }, { "area_name": "横县", "pinyin": "Hengxian", "level": 3, "area_code": 771, "post_code": 530300, "pid": 450100, "id": 2175, "area_id": 450127 }, { "area_name": "埌东新区", "pinyin": "Langdong", "level": 3, "area_code": 771, "post_code": 530000, "pid": 450100, "id": 2176, "area_id": 450128 }, { "area_name": "柳州市", "pinyin": "Liuzhou", "level": 2, "area_code": 772, "post_code": 545001, "pid": 450000, "id": 2177, "area_id": 450200 }, { "area_name": "城中区", "pinyin": "Chengzhong", "level": 3, "area_code": 772, "post_code": 545001, "pid": 450200, "id": 2178, "area_id": 450202 }, { "area_name": "鱼峰区", "pinyin": "Yufeng", "level": 3, "area_code": 772, "post_code": 545005, "pid": 450200, "id": 2179, "area_id": 450203 }, { "area_name": "柳南区", "pinyin": "Liunan", "level": 3, "area_code": 772, "post_code": 545007, "pid": 450200, "id": 2180, "area_id": 450204 }, { "area_name": "柳北区", "pinyin": "Liubei", "level": 3, "area_code": 772, "post_code": 545002, "pid": 450200, "id": 2181, "area_id": 450205 }, { "area_name": "柳江县", "pinyin": "Liujiang", "level": 3, "area_code": 772, "post_code": 545100, "pid": 450200, "id": 2182, "area_id": 450221 }, { "area_name": "柳城县", "pinyin": "Liucheng", "level": 3, "area_code": 772, "post_code": 545200, "pid": 450200, "id": 2183, "area_id": 450222 }, { "area_name": "鹿寨县", "pinyin": "Luzhai", "level": 3, "area_code": 772, "post_code": 545600, "pid": 450200, "id": 2184, "area_id": 450223 }, { "area_name": "融安县", "pinyin": "Rong'an", "level": 3, "area_code": 772, "post_code": 545400, "pid": 450200, "id": 2185, "area_id": 450224 }, { "area_name": "融水苗族自治县", "pinyin": "Rongshui", "level": 3, "area_code": 772, "post_code": 545300, "pid": 450200, "id": 2186, "area_id": 450225 }, { "area_name": "三江侗族自治县", "pinyin": "Sanjiang", "level": 3, "area_code": 772, "post_code": 545500, "pid": 450200, "id": 2187, "area_id": 450226 }, { "area_name": "柳东新区", "pinyin": "Liudong", "level": 3, "area_code": 772, "post_code": 545000, "pid": 450200, "id": 2188, "area_id": 450227 }, { "area_name": "桂林市", "pinyin": "Guilin", "level": 2, "area_code": 773, "post_code": 541100, "pid": 450000, "id": 2189, "area_id": 450300 }, { "area_name": "秀峰区", "pinyin": "Xiufeng", "level": 3, "area_code": 773, "post_code": 541001, "pid": 450300, "id": 2190, "area_id": 450302 }, { "area_name": "叠彩区", "pinyin": "Diecai", "level": 3, "area_code": 773, "post_code": 541001, "pid": 450300, "id": 2191, "area_id": 450303 }, { "area_name": "象山区", "pinyin": "Xiangshan", "level": 3, "area_code": 773, "post_code": 541002, "pid": 450300, "id": 2192, "area_id": 450304 }, { "area_name": "七星区", "pinyin": "Qixing", "level": 3, "area_code": 773, "post_code": 541004, "pid": 450300, "id": 2193, "area_id": 450305 }, { "area_name": "雁山区", "pinyin": "Yanshan", "level": 3, "area_code": 773, "post_code": 541006, "pid": 450300, "id": 2194, "area_id": 450311 }, { "area_name": "临桂区", "pinyin": "Lingui", "level": 3, "area_code": 773, "post_code": 541100, "pid": 450300, "id": 2195, "area_id": 450312 }, { "area_name": "阳朔县", "pinyin": "Yangshuo", "level": 3, "area_code": 773, "post_code": 541900, "pid": 450300, "id": 2196, "area_id": 450321 }, { "area_name": "灵川县", "pinyin": "Lingchuan", "level": 3, "area_code": 773, "post_code": 541200, "pid": 450300, "id": 2197, "area_id": 450323 }, { "area_name": "全州县", "pinyin": "Quanzhou", "level": 3, "area_code": 773, "post_code": 541503, "pid": 450300, "id": 2198, "area_id": 450324 }, { "area_name": "兴安县", "pinyin": "Xing'an", "level": 3, "area_code": 773, "post_code": 541300, "pid": 450300, "id": 2199, "area_id": 450325 }, { "area_name": "永福县", "pinyin": "Yongfu", "level": 3, "area_code": 773, "post_code": 541800, "pid": 450300, "id": 2200, "area_id": 450326 }, { "area_name": "灌阳县", "pinyin": "Guanyang", "level": 3, "area_code": 773, "post_code": 541600, "pid": 450300, "id": 2201, "area_id": 450327 }, { "area_name": "龙胜各族自治县", "pinyin": "Longsheng", "level": 3, "area_code": 773, "post_code": 541700, "pid": 450300, "id": 2202, "area_id": 450328 }, { "area_name": "资源县", "pinyin": "Ziyuan", "level": 3, "area_code": 773, "post_code": 541400, "pid": 450300, "id": 2203, "area_id": 450329 }, { "area_name": "平乐县", "pinyin": "Pingle", "level": 3, "area_code": 773, "post_code": 542400, "pid": 450300, "id": 2204, "area_id": 450330 }, { "area_name": "荔浦县", "pinyin": "Lipu", "level": 3, "area_code": 773, "post_code": 546600, "pid": 450300, "id": 2205, "area_id": 450331 }, { "area_name": "恭城瑶族自治县", "pinyin": "Gongcheng", "level": 3, "area_code": 773, "post_code": 542500, "pid": 450300, "id": 2206, "area_id": 450332 }, { "area_name": "梧州市", "pinyin": "Wuzhou", "level": 2, "area_code": 774, "post_code": 543002, "pid": 450000, "id": 2207, "area_id": 450400 }, { "area_name": "万秀区", "pinyin": "Wanxiu", "level": 3, "area_code": 774, "post_code": 543000, "pid": 450400, "id": 2208, "area_id": 450403 }, { "area_name": "长洲区", "pinyin": "Changzhou", "level": 3, "area_code": 774, "post_code": 543003, "pid": 450400, "id": 2209, "area_id": 450405 }, { "area_name": "龙圩区", "pinyin": "Longxu", "level": 3, "area_code": 774, "post_code": 543002, "pid": 450400, "id": 2210, "area_id": 450406 }, { "area_name": "苍梧县", "pinyin": "Cangwu", "level": 3, "area_code": 774, "post_code": 543100, "pid": 450400, "id": 2211, "area_id": 450421 }, { "area_name": "藤县", "pinyin": "Tengxian", "level": 3, "area_code": 774, "post_code": 543300, "pid": 450400, "id": 2212, "area_id": 450422 }, { "area_name": "蒙山县", "pinyin": "Mengshan", "level": 3, "area_code": 774, "post_code": 546700, "pid": 450400, "id": 2213, "area_id": 450423 }, { "area_name": "岑溪市", "pinyin": "Cenxi", "level": 3, "area_code": 774, "post_code": 543200, "pid": 450400, "id": 2214, "area_id": 450481 }, { "area_name": "北海市", "pinyin": "Beihai", "level": 2, "area_code": 779, "post_code": 536000, "pid": 450000, "id": 2215, "area_id": 450500 }, { "area_name": "海城区", "pinyin": "Haicheng", "level": 3, "area_code": 779, "post_code": 536000, "pid": 450500, "id": 2216, "area_id": 450502 }, { "area_name": "银海区", "pinyin": "Yinhai", "level": 3, "area_code": 779, "post_code": 536000, "pid": 450500, "id": 2217, "area_id": 450503 }, { "area_name": "铁山港区", "pinyin": "Tieshangang", "level": 3, "area_code": 779, "post_code": 536017, "pid": 450500, "id": 2218, "area_id": 450512 }, { "area_name": "合浦县", "pinyin": "Hepu", "level": 3, "area_code": 779, "post_code": 536100, "pid": 450500, "id": 2219, "area_id": 450521 }, { "area_name": "防城港市", "pinyin": "Fangchenggang", "level": 2, "area_code": 770, "post_code": 538001, "pid": 450000, "id": 2220, "area_id": 450600 }, { "area_name": "港口区", "pinyin": "Gangkou", "level": 3, "area_code": 770, "post_code": 538001, "pid": 450600, "id": 2221, "area_id": 450602 }, { "area_name": "防城区", "pinyin": "Fangcheng", "level": 3, "area_code": 770, "post_code": 538021, "pid": 450600, "id": 2222, "area_id": 450603 }, { "area_name": "上思县", "pinyin": "Shangsi", "level": 3, "area_code": 770, "post_code": 535500, "pid": 450600, "id": 2223, "area_id": 450621 }, { "area_name": "东兴市", "pinyin": "Dongxing", "level": 3, "area_code": 770, "post_code": 538100, "pid": 450600, "id": 2224, "area_id": 450681 }, { "area_name": "钦州市", "pinyin": "Qinzhou", "level": 2, "area_code": 777, "post_code": 535099, "pid": 450000, "id": 2225, "area_id": 450700 }, { "area_name": "钦南区", "pinyin": "Qinnan", "level": 3, "area_code": 777, "post_code": 535099, "pid": 450700, "id": 2226, "area_id": 450702 }, { "area_name": "钦北区", "pinyin": "Qinbei", "level": 3, "area_code": 777, "post_code": 535099, "pid": 450700, "id": 2227, "area_id": 450703 }, { "area_name": "灵山县", "pinyin": "Lingshan", "level": 3, "area_code": 777, "post_code": 535099, "pid": 450700, "id": 2228, "area_id": 450721 }, { "area_name": "浦北县", "pinyin": "Pubei", "level": 3, "area_code": 777, "post_code": 535099, "pid": 450700, "id": 2229, "area_id": 450722 }, { "area_name": "贵港市", "pinyin": "Guigang", "level": 2, "area_code": 775, "post_code": 537100, "pid": 450000, "id": 2230, "area_id": 450800 }, { "area_name": "港北区", "pinyin": "Gangbei", "level": 3, "area_code": 775, "post_code": 537100, "pid": 450800, "id": 2231, "area_id": 450802 }, { "area_name": "港南区", "pinyin": "Gangnan", "level": 3, "area_code": 775, "post_code": 537100, "pid": 450800, "id": 2232, "area_id": 450803 }, { "area_name": "覃塘区", "pinyin": "Qintang", "level": 3, "area_code": 775, "post_code": 537121, "pid": 450800, "id": 2233, "area_id": 450804 }, { "area_name": "平南县", "pinyin": "Pingnan", "level": 3, "area_code": 775, "post_code": 537300, "pid": 450800, "id": 2234, "area_id": 450821 }, { "area_name": "桂平市", "pinyin": "Guiping", "level": 3, "area_code": 775, "post_code": 537200, "pid": 450800, "id": 2235, "area_id": 450881 }, { "area_name": "玉林市", "pinyin": "Yulin", "level": 2, "area_code": 775, "post_code": 537000, "pid": 450000, "id": 2236, "area_id": 450900 }, { "area_name": "玉州区", "pinyin": "Yuzhou", "level": 3, "area_code": 775, "post_code": 537000, "pid": 450900, "id": 2237, "area_id": 450902 }, { "area_name": "福绵区", "pinyin": "Fumian", "level": 3, "area_code": 775, "post_code": 537023, "pid": 450900, "id": 2238, "area_id": 450903 }, { "area_name": "玉东新区", "pinyin": "Yudong", "level": 3, "area_code": 775, "post_code": 537000, "pid": 450900, "id": 2239, "area_id": 450904 }, { "area_name": "容县", "pinyin": "Rongxian", "level": 3, "area_code": 775, "post_code": 537500, "pid": 450900, "id": 2240, "area_id": 450921 }, { "area_name": "陆川县", "pinyin": "Luchuan", "level": 3, "area_code": 775, "post_code": 537700, "pid": 450900, "id": 2241, "area_id": 450922 }, { "area_name": "博白县", "pinyin": "Bobai", "level": 3, "area_code": 775, "post_code": 537600, "pid": 450900, "id": 2242, "area_id": 450923 }, { "area_name": "兴业县", "pinyin": "Xingye", "level": 3, "area_code": 775, "post_code": 537800, "pid": 450900, "id": 2243, "area_id": 450924 }, { "area_name": "北流市", "pinyin": "Beiliu", "level": 3, "area_code": 775, "post_code": 537400, "pid": 450900, "id": 2244, "area_id": 450981 }, { "area_name": "百色市", "pinyin": "Baise", "level": 2, "area_code": 776, "post_code": 533000, "pid": 450000, "id": 2245, "area_id": 451000 }, { "area_name": "右江区", "pinyin": "Youjiang", "level": 3, "area_code": 776, "post_code": 533000, "pid": 451000, "id": 2246, "area_id": 451002 }, { "area_name": "田阳县", "pinyin": "Tianyang", "level": 3, "area_code": 776, "post_code": 533600, "pid": 451000, "id": 2247, "area_id": 451021 }, { "area_name": "田东县", "pinyin": "Tiandong", "level": 3, "area_code": 776, "post_code": 531500, "pid": 451000, "id": 2248, "area_id": 451022 }, { "area_name": "平果县", "pinyin": "Pingguo", "level": 3, "area_code": 776, "post_code": 531400, "pid": 451000, "id": 2249, "area_id": 451023 }, { "area_name": "德保县", "pinyin": "Debao", "level": 3, "area_code": 776, "post_code": 533700, "pid": 451000, "id": 2250, "area_id": 451024 }, { "area_name": "靖西县", "pinyin": "Jingxi", "level": 3, "area_code": 776, "post_code": 533800, "pid": 451000, "id": 2251, "area_id": 451025 }, { "area_name": "那坡县", "pinyin": "Napo", "level": 3, "area_code": 776, "post_code": 533900, "pid": 451000, "id": 2252, "area_id": 451026 }, { "area_name": "凌云县", "pinyin": "Lingyun", "level": 3, "area_code": 776, "post_code": 533100, "pid": 451000, "id": 2253, "area_id": 451027 }, { "area_name": "乐业县", "pinyin": "Leye", "level": 3, "area_code": 776, "post_code": 533200, "pid": 451000, "id": 2254, "area_id": 451028 }, { "area_name": "田林县", "pinyin": "Tianlin", "level": 3, "area_code": 776, "post_code": 533300, "pid": 451000, "id": 2255, "area_id": 451029 }, { "area_name": "西林县", "pinyin": "Xilin", "level": 3, "area_code": 776, "post_code": 533500, "pid": 451000, "id": 2256, "area_id": 451030 }, { "area_name": "隆林各族自治县", "pinyin": "Longlin", "level": 3, "area_code": 776, "post_code": 533400, "pid": 451000, "id": 2257, "area_id": 451031 }, { "area_name": "贺州市", "pinyin": "Hezhou", "level": 2, "area_code": 774, "post_code": 542800, "pid": 450000, "id": 2258, "area_id": 451100 }, { "area_name": "八步区", "pinyin": "Babu", "level": 3, "area_code": 774, "post_code": 542800, "pid": 451100, "id": 2259, "area_id": 451102 }, { "area_name": "昭平县", "pinyin": "Zhaoping", "level": 3, "area_code": 774, "post_code": 546800, "pid": 451100, "id": 2260, "area_id": 451121 }, { "area_name": "钟山县", "pinyin": "Zhongshan", "level": 3, "area_code": 774, "post_code": 542600, "pid": 451100, "id": 2261, "area_id": 451122 }, { "area_name": "富川瑶族自治县", "pinyin": "Fuchuan", "level": 3, "area_code": 774, "post_code": 542700, "pid": 451100, "id": 2262, "area_id": 451123 }, { "area_name": "平桂管理区", "pinyin": "Pingui", "level": 3, "area_code": 774, "post_code": 542800, "pid": 451100, "id": 2263, "area_id": 451124 }, { "area_name": "河池市", "pinyin": "Hechi", "level": 2, "area_code": 778, "post_code": 547000, "pid": 450000, "id": 2264, "area_id": 451200 }, { "area_name": "金城江区", "pinyin": "Jinchengjiang", "level": 3, "area_code": 779, "post_code": 547000, "pid": 451200, "id": 2265, "area_id": 451202 }, { "area_name": "南丹县", "pinyin": "Nandan", "level": 3, "area_code": 781, "post_code": 547200, "pid": 451200, "id": 2266, "area_id": 451221 }, { "area_name": "天峨县", "pinyin": "Tiane", "level": 3, "area_code": 782, "post_code": 547300, "pid": 451200, "id": 2267, "area_id": 451222 }, { "area_name": "凤山县", "pinyin": "Fengshan", "level": 3, "area_code": 783, "post_code": 547600, "pid": 451200, "id": 2268, "area_id": 451223 }, { "area_name": "东兰县", "pinyin": "Donglan", "level": 3, "area_code": 784, "post_code": 547400, "pid": 451200, "id": 2269, "area_id": 451224 }, { "area_name": "罗城仫佬族自治县", "pinyin": "Luocheng", "level": 3, "area_code": 785, "post_code": 546400, "pid": 451200, "id": 2270, "area_id": 451225 }, { "area_name": "环江毛南族自治县", "pinyin": "Huanjiang", "level": 3, "area_code": 786, "post_code": 547100, "pid": 451200, "id": 2271, "area_id": 451226 }, { "area_name": "巴马瑶族自治县", "pinyin": "Bama", "level": 3, "area_code": 787, "post_code": 547500, "pid": 451200, "id": 2272, "area_id": 451227 }, { "area_name": "都安瑶族自治县", "pinyin": "Du'an", "level": 3, "area_code": 788, "post_code": 530700, "pid": 451200, "id": 2273, "area_id": 451228 }, { "area_name": "大化瑶族自治县", "pinyin": "Dahua", "level": 3, "area_code": 789, "post_code": 530800, "pid": 451200, "id": 2274, "area_id": 451229 }, { "area_name": "宜州市", "pinyin": "Yizhou", "level": 3, "area_code": 780, "post_code": 546300, "pid": 451200, "id": 2275, "area_id": 451281 }, { "area_name": "来宾市", "pinyin": "Laibin", "level": 2, "area_code": 772, "post_code": 546100, "pid": 450000, "id": 2276, "area_id": 451300 }, { "area_name": "兴宾区", "pinyin": "Xingbin", "level": 3, "area_code": 772, "post_code": 546100, "pid": 451300, "id": 2277, "area_id": 451302 }, { "area_name": "忻城县", "pinyin": "Xincheng", "level": 3, "area_code": 772, "post_code": 546200, "pid": 451300, "id": 2278, "area_id": 451321 }, { "area_name": "象州县", "pinyin": "Xiangzhou", "level": 3, "area_code": 772, "post_code": 545800, "pid": 451300, "id": 2279, "area_id": 451322 }, { "area_name": "武宣县", "pinyin": "Wuxuan", "level": 3, "area_code": 772, "post_code": 545900, "pid": 451300, "id": 2280, "area_id": 451323 }, { "area_name": "金秀瑶族自治县", "pinyin": "Jinxiu", "level": 3, "area_code": 772, "post_code": 545799, "pid": 451300, "id": 2281, "area_id": 451324 }, { "area_name": "合山市", "pinyin": "Heshan", "level": 3, "area_code": 772, "post_code": 546500, "pid": 451300, "id": 2282, "area_id": 451381 }, { "area_name": "崇左市", "pinyin": "Chongzuo", "level": 2, "area_code": 771, "post_code": 532299, "pid": 450000, "id": 2283, "area_id": 451400 }, { "area_name": "江州区", "pinyin": "Jiangzhou", "level": 3, "area_code": 771, "post_code": 532299, "pid": 451400, "id": 2284, "area_id": 451402 }, { "area_name": "扶绥县", "pinyin": "Fusui", "level": 3, "area_code": 771, "post_code": 532199, "pid": 451400, "id": 2285, "area_id": 451421 }, { "area_name": "宁明县", "pinyin": "Ningming", "level": 3, "area_code": 771, "post_code": 532599, "pid": 451400, "id": 2286, "area_id": 451422 }, { "area_name": "龙州县", "pinyin": "Longzhou", "level": 3, "area_code": 771, "post_code": 532499, "pid": 451400, "id": 2287, "area_id": 451423 }, { "area_name": "大新县", "pinyin": "Daxin", "level": 3, "area_code": 771, "post_code": 532399, "pid": 451400, "id": 2288, "area_id": 451424 }, { "area_name": "天等县", "pinyin": "Tiandeng", "level": 3, "area_code": 771, "post_code": 532899, "pid": 451400, "id": 2289, "area_id": 451425 }, { "area_name": "凭祥市", "pinyin": "Pingxiang", "level": 3, "area_code": 771, "post_code": 532699, "pid": 451400, "id": 2290, "area_id": 451481 }, { "area_name": "海南省", "pinyin": "Hainan", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2291, "area_id": 460000 }, { "area_name": "海口市", "pinyin": "Haikou", "level": 2, "area_code": 898, "post_code": 570000, "pid": 460000, "id": 2292, "area_id": 460100 }, { "area_name": "秀英区", "pinyin": "Xiuying", "level": 3, "area_code": 898, "post_code": 570311, "pid": 460100, "id": 2293, "area_id": 460105 }, { "area_name": "龙华区", "pinyin": "Longhua", "level": 3, "area_code": 898, "post_code": 570145, "pid": 460100, "id": 2294, "area_id": 460106 }, { "area_name": "琼山区", "pinyin": "Qiongshan", "level": 3, "area_code": 898, "post_code": 571100, "pid": 460100, "id": 2295, "area_id": 460107 }, { "area_name": "美兰区", "pinyin": "Meilan", "level": 3, "area_code": 898, "post_code": 570203, "pid": 460100, "id": 2296, "area_id": 460108 }, { "area_name": "三亚市", "pinyin": "Sanya", "level": 2, "area_code": 898, "post_code": 572000, "pid": 460000, "id": 2297, "area_id": 460200 }, { "area_name": "海棠区", "pinyin": "Haitang", "level": 3, "area_code": 898, "post_code": 572000, "pid": 460200, "id": 2298, "area_id": 460202 }, { "area_name": "吉阳区", "pinyin": "Jiyang", "level": 3, "area_code": 898, "post_code": 572000, "pid": 460200, "id": 2299, "area_id": 460203 }, { "area_name": "天涯区", "pinyin": "Tianya", "level": 3, "area_code": 898, "post_code": 572000, "pid": 460200, "id": 2300, "area_id": 460204 }, { "area_name": "崖州区", "pinyin": "Yazhou", "level": 3, "area_code": 898, "post_code": 572000, "pid": 460200, "id": 2301, "area_id": 460205 }, { "area_name": "三沙市", "pinyin": "Sansha", "level": 2, "area_code": 898, "post_code": 573199, "pid": 460000, "id": 2302, "area_id": 460300 }, { "area_name": "西沙群岛", "pinyin": "Xisha Islands", "level": 3, "area_code": 898, "post_code": 572000, "pid": 460300, "id": 2303, "area_id": 460321 }, { "area_name": "南沙群岛", "pinyin": "Nansha Islands", "level": 3, "area_code": 898, "post_code": 573100, "pid": 460300, "id": 2304, "area_id": 460322 }, { "area_name": "中沙群岛", "pinyin": "Zhongsha Islands", "level": 3, "area_code": 898, "post_code": 573100, "pid": 460300, "id": 2305, "area_id": 460323 }, { "area_name": "直辖县级", "pinyin": "", "level": 2, "area_code": null, "post_code": null, "pid": 460000, "id": 2306, "area_id": 469000 }, { "area_name": "五指山市", "pinyin": "Wuzhishan", "level": 3, "area_code": 898, "post_code": 572200, "pid": 469000, "id": 2307, "area_id": 469001 }, { "area_name": "琼海市", "pinyin": "Qionghai", "level": 3, "area_code": 898, "post_code": 571400, "pid": 469000, "id": 2308, "area_id": 469002 }, { "area_name": "儋州市", "pinyin": "Danzhou", "level": 3, "area_code": 898, "post_code": 571700, "pid": 469000, "id": 2309, "area_id": 469003 }, { "area_name": "文昌市", "pinyin": "Wenchang", "level": 3, "area_code": 898, "post_code": 571339, "pid": 469000, "id": 2310, "area_id": 469005 }, { "area_name": "万宁市", "pinyin": "Wanning", "level": 3, "area_code": 898, "post_code": 571500, "pid": 469000, "id": 2311, "area_id": 469006 }, { "area_name": "东方市", "pinyin": "Dongfang", "level": 3, "area_code": 898, "post_code": 572600, "pid": 469000, "id": 2312, "area_id": 469007 }, { "area_name": "定安县", "pinyin": "Ding'an", "level": 3, "area_code": 898, "post_code": 571200, "pid": 469000, "id": 2313, "area_id": 469021 }, { "area_name": "屯昌县", "pinyin": "Tunchang", "level": 3, "area_code": 898, "post_code": 571600, "pid": 469000, "id": 2314, "area_id": 469022 }, { "area_name": "澄迈县", "pinyin": "Chengmai", "level": 3, "area_code": 898, "post_code": 571900, "pid": 469000, "id": 2315, "area_id": 469023 }, { "area_name": "临高县", "pinyin": "Lingao", "level": 3, "area_code": 898, "post_code": 571800, "pid": 469000, "id": 2316, "area_id": 469024 }, { "area_name": "白沙黎族自治县", "pinyin": "Baisha", "level": 3, "area_code": 898, "post_code": 572800, "pid": 469000, "id": 2317, "area_id": 469025 }, { "area_name": "昌江黎族自治县", "pinyin": "Changjiang", "level": 3, "area_code": 898, "post_code": 572700, "pid": 469000, "id": 2318, "area_id": 469026 }, { "area_name": "乐东黎族自治县", "pinyin": "Ledong", "level": 3, "area_code": 898, "post_code": 572500, "pid": 469000, "id": 2319, "area_id": 469027 }, { "area_name": "陵水黎族自治县", "pinyin": "Lingshui", "level": 3, "area_code": 898, "post_code": 572400, "pid": 469000, "id": 2320, "area_id": 469028 }, { "area_name": "保亭黎族苗族自治县", "pinyin": "Baoting", "level": 3, "area_code": 898, "post_code": 572300, "pid": 469000, "id": 2321, "area_id": 469029 }, { "area_name": "琼中黎族苗族自治县", "pinyin": "Qiongzhong", "level": 3, "area_code": 898, "post_code": 572900, "pid": 469000, "id": 2322, "area_id": 469030 }, { "area_name": "重庆", "pinyin": "Chongqing", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2323, "area_id": 500000 }, { "area_name": "重庆市", "pinyin": "Chongqing", "level": 2, "area_code": 23, "post_code": 400000, "pid": 500000, "id": 2324, "area_id": 500100 }, { "area_name": "万州区", "pinyin": "Wanzhou", "level": 3, "area_code": 23, "post_code": 404000, "pid": 500100, "id": 2325, "area_id": 500101 }, { "area_name": "涪陵区", "pinyin": "Fuling", "level": 3, "area_code": 23, "post_code": 408000, "pid": 500100, "id": 2326, "area_id": 500102 }, { "area_name": "渝中区", "pinyin": "Yuzhong", "level": 3, "area_code": 23, "post_code": 400010, "pid": 500100, "id": 2327, "area_id": 500103 }, { "area_name": "大渡口区", "pinyin": "Dadukou", "level": 3, "area_code": 23, "post_code": 400080, "pid": 500100, "id": 2328, "area_id": 500104 }, { "area_name": "江北区", "pinyin": "Jiangbei", "level": 3, "area_code": 23, "post_code": 400020, "pid": 500100, "id": 2329, "area_id": 500105 }, { "area_name": "沙坪坝区", "pinyin": "Shapingba", "level": 3, "area_code": 23, "post_code": 400030, "pid": 500100, "id": 2330, "area_id": 500106 }, { "area_name": "九龙坡区", "pinyin": "Jiulongpo", "level": 3, "area_code": 23, "post_code": 400050, "pid": 500100, "id": 2331, "area_id": 500107 }, { "area_name": "南岸区", "pinyin": "Nan'an", "level": 3, "area_code": 23, "post_code": 400064, "pid": 500100, "id": 2332, "area_id": 500108 }, { "area_name": "北碚区", "pinyin": "Beibei", "level": 3, "area_code": 23, "post_code": 400700, "pid": 500100, "id": 2333, "area_id": 500109 }, { "area_name": "綦江区", "pinyin": "Qijiang", "level": 3, "area_code": 23, "post_code": 400800, "pid": 500100, "id": 2334, "area_id": 500110 }, { "area_name": "大足区", "pinyin": "Dazu", "level": 3, "area_code": 23, "post_code": 400900, "pid": 500100, "id": 2335, "area_id": 500111 }, { "area_name": "渝北区", "pinyin": "Yubei", "level": 3, "area_code": 23, "post_code": 401120, "pid": 500100, "id": 2336, "area_id": 500112 }, { "area_name": "巴南区", "pinyin": "Banan", "level": 3, "area_code": 23, "post_code": 401320, "pid": 500100, "id": 2337, "area_id": 500113 }, { "area_name": "黔江区", "pinyin": "Qianjiang", "level": 3, "area_code": 23, "post_code": 409700, "pid": 500100, "id": 2338, "area_id": 500114 }, { "area_name": "长寿区", "pinyin": "Changshou", "level": 3, "area_code": 23, "post_code": 401220, "pid": 500100, "id": 2339, "area_id": 500115 }, { "area_name": "江津区", "pinyin": "Jiangjin", "level": 3, "area_code": 23, "post_code": 402260, "pid": 500100, "id": 2340, "area_id": 500116 }, { "area_name": "合川区", "pinyin": "Hechuan", "level": 3, "area_code": 23, "post_code": 401520, "pid": 500100, "id": 2341, "area_id": 500117 }, { "area_name": "永川区", "pinyin": "Yongchuan", "level": 3, "area_code": 23, "post_code": 402160, "pid": 500100, "id": 2342, "area_id": 500118 }, { "area_name": "南川区", "pinyin": "Nanchuan", "level": 3, "area_code": 23, "post_code": 408400, "pid": 500100, "id": 2343, "area_id": 500119 }, { "area_name": "璧山区", "pinyin": "Bishan", "level": 3, "area_code": 23, "post_code": 402760, "pid": 500100, "id": 2344, "area_id": 500120 }, { "area_name": "铜梁区", "pinyin": "Tongliang", "level": 3, "area_code": 23, "post_code": 402560, "pid": 500100, "id": 2345, "area_id": 500151 }, { "area_name": "潼南县", "pinyin": "Tongnan", "level": 3, "area_code": 23, "post_code": 402660, "pid": 500100, "id": 2346, "area_id": 500223 }, { "area_name": "荣昌县", "pinyin": "Rongchang", "level": 3, "area_code": 23, "post_code": 402460, "pid": 500100, "id": 2347, "area_id": 500226 }, { "area_name": "梁平县", "pinyin": "Liangping", "level": 3, "area_code": 23, "post_code": 405200, "pid": 500100, "id": 2348, "area_id": 500228 }, { "area_name": "城口县", "pinyin": "Chengkou", "level": 3, "area_code": 23, "post_code": 405900, "pid": 500100, "id": 2349, "area_id": 500229 }, { "area_name": "丰都县", "pinyin": "Fengdu", "level": 3, "area_code": 23, "post_code": 408200, "pid": 500100, "id": 2350, "area_id": 500230 }, { "area_name": "垫江县", "pinyin": "Dianjiang", "level": 3, "area_code": 23, "post_code": 408300, "pid": 500100, "id": 2351, "area_id": 500231 }, { "area_name": "武隆县", "pinyin": "Wulong", "level": 3, "area_code": 23, "post_code": 408500, "pid": 500100, "id": 2352, "area_id": 500232 }, { "area_name": "忠县", "pinyin": "Zhongxian", "level": 3, "area_code": 23, "post_code": 404300, "pid": 500100, "id": 2353, "area_id": 500233 }, { "area_name": "开县", "pinyin": "Kaixian", "level": 3, "area_code": 23, "post_code": 405400, "pid": 500100, "id": 2354, "area_id": 500234 }, { "area_name": "云阳县", "pinyin": "Yunyang", "level": 3, "area_code": 23, "post_code": 404500, "pid": 500100, "id": 2355, "area_id": 500235 }, { "area_name": "奉节县", "pinyin": "Fengjie", "level": 3, "area_code": 23, "post_code": 404600, "pid": 500100, "id": 2356, "area_id": 500236 }, { "area_name": "巫山县", "pinyin": "Wushan", "level": 3, "area_code": 23, "post_code": 404700, "pid": 500100, "id": 2357, "area_id": 500237 }, { "area_name": "巫溪县", "pinyin": "Wuxi", "level": 3, "area_code": 23, "post_code": 405800, "pid": 500100, "id": 2358, "area_id": 500238 }, { "area_name": "石柱土家族自治县", "pinyin": "Shizhu", "level": 3, "area_code": 23, "post_code": 409100, "pid": 500100, "id": 2359, "area_id": 500240 }, { "area_name": "秀山土家族苗族自治县", "pinyin": "Xiushan", "level": 3, "area_code": 23, "post_code": 409900, "pid": 500100, "id": 2360, "area_id": 500241 }, { "area_name": "酉阳土家族苗族自治县", "pinyin": "Youyang", "level": 3, "area_code": 23, "post_code": 409800, "pid": 500100, "id": 2361, "area_id": 500242 }, { "area_name": "彭水苗族土家族自治县", "pinyin": "Pengshui", "level": 3, "area_code": 23, "post_code": 409600, "pid": 500100, "id": 2362, "area_id": 500243 }, { "area_name": "两江新区", "pinyin": "Liangjiangxinqu", "level": 2, "area_code": 23, "post_code": 400000, "pid": 500000, "id": 2363, "area_id": 500300 }, { "area_name": "北部新区", "pinyin": "Beibuxinqu", "level": 3, "area_code": 23, "post_code": 400000, "pid": 500300, "id": 2364, "area_id": 500301 }, { "area_name": "保税港区", "pinyin": "Baoshuigangqu", "level": 3, "area_code": 23, "post_code": 400000, "pid": 500300, "id": 2365, "area_id": 500302 }, { "area_name": "工业园区", "pinyin": "Gongyeyuanqu", "level": 3, "area_code": 23, "post_code": 400000, "pid": 500300, "id": 2366, "area_id": 500303 }, { "area_name": "四川省", "pinyin": "Sichuan", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2367, "area_id": 510000 }, { "area_name": "成都市", "pinyin": "Chengdu", "level": 2, "area_code": 28, "post_code": 610015, "pid": 510000, "id": 2368, "area_id": 510100 }, { "area_name": "锦江区", "pinyin": "Jinjiang", "level": 3, "area_code": 28, "post_code": 610021, "pid": 510100, "id": 2369, "area_id": 510104 }, { "area_name": "青羊区", "pinyin": "Qingyang", "level": 3, "area_code": 28, "post_code": 610031, "pid": 510100, "id": 2370, "area_id": 510105 }, { "area_name": "金牛区", "pinyin": "Jinniu", "level": 3, "area_code": 28, "post_code": 610036, "pid": 510100, "id": 2371, "area_id": 510106 }, { "area_name": "武侯区", "pinyin": "Wuhou", "level": 3, "area_code": 28, "post_code": 610041, "pid": 510100, "id": 2372, "area_id": 510107 }, { "area_name": "成华区", "pinyin": "Chenghua", "level": 3, "area_code": 28, "post_code": 610066, "pid": 510100, "id": 2373, "area_id": 510108 }, { "area_name": "龙泉驿区", "pinyin": "Longquanyi", "level": 3, "area_code": 28, "post_code": 610100, "pid": 510100, "id": 2374, "area_id": 510112 }, { "area_name": "青白江区", "pinyin": "Qingbaijiang", "level": 3, "area_code": 28, "post_code": 610300, "pid": 510100, "id": 2375, "area_id": 510113 }, { "area_name": "新都区", "pinyin": "Xindu", "level": 3, "area_code": 28, "post_code": 610500, "pid": 510100, "id": 2376, "area_id": 510114 }, { "area_name": "温江区", "pinyin": "Wenjiang", "level": 3, "area_code": 28, "post_code": 611130, "pid": 510100, "id": 2377, "area_id": 510115 }, { "area_name": "金堂县", "pinyin": "Jintang", "level": 3, "area_code": 28, "post_code": 610400, "pid": 510100, "id": 2378, "area_id": 510121 }, { "area_name": "双流县", "pinyin": "Shuangliu", "level": 3, "area_code": 28, "post_code": 610200, "pid": 510100, "id": 2379, "area_id": 510122 }, { "area_name": "郫县", "pinyin": "Pixian", "level": 3, "area_code": 28, "post_code": 611730, "pid": 510100, "id": 2380, "area_id": 510124 }, { "area_name": "大邑县", "pinyin": "Dayi", "level": 3, "area_code": 28, "post_code": 611330, "pid": 510100, "id": 2381, "area_id": 510129 }, { "area_name": "蒲江县", "pinyin": "Pujiang", "level": 3, "area_code": 28, "post_code": 611630, "pid": 510100, "id": 2382, "area_id": 510131 }, { "area_name": "新津县", "pinyin": "Xinjin", "level": 3, "area_code": 28, "post_code": 611430, "pid": 510100, "id": 2383, "area_id": 510132 }, { "area_name": "都江堰市", "pinyin": "Dujiangyan", "level": 3, "area_code": 28, "post_code": 611830, "pid": 510100, "id": 2384, "area_id": 510181 }, { "area_name": "彭州市", "pinyin": "Pengzhou", "level": 3, "area_code": 28, "post_code": 611930, "pid": 510100, "id": 2385, "area_id": 510182 }, { "area_name": "邛崃市", "pinyin": "Qionglai", "level": 3, "area_code": 28, "post_code": 611530, "pid": 510100, "id": 2386, "area_id": 510183 }, { "area_name": "崇州市", "pinyin": "Chongzhou", "level": 3, "area_code": 28, "post_code": 611230, "pid": 510100, "id": 2387, "area_id": 510184 }, { "area_name": "自贡市", "pinyin": "Zigong", "level": 2, "area_code": 813, "post_code": 643000, "pid": 510000, "id": 2388, "area_id": 510300 }, { "area_name": "自流井区", "pinyin": "Ziliujing", "level": 3, "area_code": 813, "post_code": 643000, "pid": 510300, "id": 2389, "area_id": 510302 }, { "area_name": "贡井区", "pinyin": "Gongjing", "level": 3, "area_code": 813, "post_code": 643020, "pid": 510300, "id": 2390, "area_id": 510303 }, { "area_name": "大安区", "pinyin": "Da'an", "level": 3, "area_code": 813, "post_code": 643010, "pid": 510300, "id": 2391, "area_id": 510304 }, { "area_name": "沿滩区", "pinyin": "Yantan", "level": 3, "area_code": 813, "post_code": 643030, "pid": 510300, "id": 2392, "area_id": 510311 }, { "area_name": "荣县", "pinyin": "Rongxian", "level": 3, "area_code": 813, "post_code": 643100, "pid": 510300, "id": 2393, "area_id": 510321 }, { "area_name": "富顺县", "pinyin": "Fushun", "level": 3, "area_code": 813, "post_code": 643200, "pid": 510300, "id": 2394, "area_id": 510322 }, { "area_name": "攀枝花市", "pinyin": "Panzhihua", "level": 2, "area_code": 812, "post_code": 617000, "pid": 510000, "id": 2395, "area_id": 510400 }, { "area_name": "东区", "pinyin": "Dongqu", "level": 3, "area_code": 812, "post_code": 617067, "pid": 510400, "id": 2396, "area_id": 510402 }, { "area_name": "西区", "pinyin": "Xiqu", "level": 3, "area_code": 812, "post_code": 617068, "pid": 510400, "id": 2397, "area_id": 510403 }, { "area_name": "仁和区", "pinyin": "Renhe", "level": 3, "area_code": 812, "post_code": 617061, "pid": 510400, "id": 2398, "area_id": 510411 }, { "area_name": "米易县", "pinyin": "Miyi", "level": 3, "area_code": 812, "post_code": 617200, "pid": 510400, "id": 2399, "area_id": 510421 }, { "area_name": "盐边县", "pinyin": "Yanbian", "level": 3, "area_code": 812, "post_code": 617100, "pid": 510400, "id": 2400, "area_id": 510422 }, { "area_name": "泸州市", "pinyin": "Luzhou", "level": 2, "area_code": 830, "post_code": 646000, "pid": 510000, "id": 2401, "area_id": 510500 }, { "area_name": "江阳区", "pinyin": "Jiangyang", "level": 3, "area_code": 830, "post_code": 646000, "pid": 510500, "id": 2402, "area_id": 510502 }, { "area_name": "纳溪区", "pinyin": "Naxi", "level": 3, "area_code": 830, "post_code": 646300, "pid": 510500, "id": 2403, "area_id": 510503 }, { "area_name": "龙马潭区", "pinyin": "Longmatan", "level": 3, "area_code": 830, "post_code": 646000, "pid": 510500, "id": 2404, "area_id": 510504 }, { "area_name": "泸县", "pinyin": "Luxian", "level": 3, "area_code": 830, "post_code": 646106, "pid": 510500, "id": 2405, "area_id": 510521 }, { "area_name": "合江县", "pinyin": "Hejiang", "level": 3, "area_code": 830, "post_code": 646200, "pid": 510500, "id": 2406, "area_id": 510522 }, { "area_name": "叙永县", "pinyin": "Xuyong", "level": 3, "area_code": 830, "post_code": 646400, "pid": 510500, "id": 2407, "area_id": 510524 }, { "area_name": "古蔺县", "pinyin": "Gulin", "level": 3, "area_code": 830, "post_code": 646500, "pid": 510500, "id": 2408, "area_id": 510525 }, { "area_name": "德阳市", "pinyin": "Deyang", "level": 2, "area_code": 838, "post_code": 618000, "pid": 510000, "id": 2409, "area_id": 510600 }, { "area_name": "旌阳区", "pinyin": "Jingyang", "level": 3, "area_code": 838, "post_code": 618000, "pid": 510600, "id": 2410, "area_id": 510603 }, { "area_name": "中江县", "pinyin": "Zhongjiang", "level": 3, "area_code": 838, "post_code": 618100, "pid": 510600, "id": 2411, "area_id": 510623 }, { "area_name": "罗江县", "pinyin": "Luojiang", "level": 3, "area_code": 838, "post_code": 618500, "pid": 510600, "id": 2412, "area_id": 510626 }, { "area_name": "广汉市", "pinyin": "Guanghan", "level": 3, "area_code": 838, "post_code": 618300, "pid": 510600, "id": 2413, "area_id": 510681 }, { "area_name": "什邡市", "pinyin": "Shifang", "level": 3, "area_code": 838, "post_code": 618400, "pid": 510600, "id": 2414, "area_id": 510682 }, { "area_name": "绵竹市", "pinyin": "Mianzhu", "level": 3, "area_code": 838, "post_code": 618200, "pid": 510600, "id": 2415, "area_id": 510683 }, { "area_name": "绵阳市", "pinyin": "Mianyang", "level": 2, "area_code": 816, "post_code": 621000, "pid": 510000, "id": 2416, "area_id": 510700 }, { "area_name": "涪城区", "pinyin": "Fucheng", "level": 3, "area_code": 816, "post_code": 621000, "pid": 510700, "id": 2417, "area_id": 510703 }, { "area_name": "游仙区", "pinyin": "Youxian", "level": 3, "area_code": 816, "post_code": 621022, "pid": 510700, "id": 2418, "area_id": 510704 }, { "area_name": "三台县", "pinyin": "Santai", "level": 3, "area_code": 816, "post_code": 621100, "pid": 510700, "id": 2419, "area_id": 510722 }, { "area_name": "盐亭县", "pinyin": "Yanting", "level": 3, "area_code": 816, "post_code": 621600, "pid": 510700, "id": 2420, "area_id": 510723 }, { "area_name": "安县", "pinyin": "Anxian", "level": 3, "area_code": 816, "post_code": 622650, "pid": 510700, "id": 2421, "area_id": 510724 }, { "area_name": "梓潼县", "pinyin": "Zitong", "level": 3, "area_code": 816, "post_code": 622150, "pid": 510700, "id": 2422, "area_id": 510725 }, { "area_name": "北川羌族自治县", "pinyin": "Beichuan", "level": 3, "area_code": 816, "post_code": 622750, "pid": 510700, "id": 2423, "area_id": 510726 }, { "area_name": "平武县", "pinyin": "Pingwu", "level": 3, "area_code": 816, "post_code": 622550, "pid": 510700, "id": 2424, "area_id": 510727 }, { "area_name": "江油市", "pinyin": "Jiangyou", "level": 3, "area_code": 816, "post_code": 621700, "pid": 510700, "id": 2425, "area_id": 510781 }, { "area_name": "广元市", "pinyin": "Guangyuan", "level": 2, "area_code": 839, "post_code": 628000, "pid": 510000, "id": 2426, "area_id": 510800 }, { "area_name": "利州区", "pinyin": "Lizhou", "level": 3, "area_code": 839, "post_code": 628017, "pid": 510800, "id": 2427, "area_id": 510802 }, { "area_name": "昭化区", "pinyin": "Zhaohua", "level": 3, "area_code": 839, "post_code": 628017, "pid": 510800, "id": 2428, "area_id": 510811 }, { "area_name": "朝天区", "pinyin": "Chaotian", "level": 3, "area_code": 839, "post_code": 628017, "pid": 510800, "id": 2429, "area_id": 510812 }, { "area_name": "旺苍县", "pinyin": "Wangcang", "level": 3, "area_code": 839, "post_code": 628200, "pid": 510800, "id": 2430, "area_id": 510821 }, { "area_name": "青川县", "pinyin": "Qingchuan", "level": 3, "area_code": 839, "post_code": 628100, "pid": 510800, "id": 2431, "area_id": 510822 }, { "area_name": "剑阁县", "pinyin": "Jiange", "level": 3, "area_code": 839, "post_code": 628300, "pid": 510800, "id": 2432, "area_id": 510823 }, { "area_name": "苍溪县", "pinyin": "Cangxi", "level": 3, "area_code": 839, "post_code": 628400, "pid": 510800, "id": 2433, "area_id": 510824 }, { "area_name": "遂宁市", "pinyin": "Suining", "level": 2, "area_code": 825, "post_code": 629000, "pid": 510000, "id": 2434, "area_id": 510900 }, { "area_name": "船山区", "pinyin": "Chuanshan", "level": 3, "area_code": 825, "post_code": 629000, "pid": 510900, "id": 2435, "area_id": 510903 }, { "area_name": "安居区", "pinyin": "Anju", "level": 3, "area_code": 825, "post_code": 629000, "pid": 510900, "id": 2436, "area_id": 510904 }, { "area_name": "蓬溪县", "pinyin": "Pengxi", "level": 3, "area_code": 825, "post_code": 629100, "pid": 510900, "id": 2437, "area_id": 510921 }, { "area_name": "射洪县", "pinyin": "Shehong", "level": 3, "area_code": 825, "post_code": 629200, "pid": 510900, "id": 2438, "area_id": 510922 }, { "area_name": "大英县", "pinyin": "Daying", "level": 3, "area_code": 825, "post_code": 629300, "pid": 510900, "id": 2439, "area_id": 510923 }, { "area_name": "内江市", "pinyin": "Neijiang", "level": 2, "area_code": 832, "post_code": 641000, "pid": 510000, "id": 2440, "area_id": 511000 }, { "area_name": "市中区", "pinyin": "Shizhongqu", "level": 3, "area_code": 832, "post_code": 641000, "pid": 511000, "id": 2441, "area_id": 511002 }, { "area_name": "东兴区", "pinyin": "Dongxing", "level": 3, "area_code": 832, "post_code": 641100, "pid": 511000, "id": 2442, "area_id": 511011 }, { "area_name": "威远县", "pinyin": "Weiyuan", "level": 3, "area_code": 832, "post_code": 642450, "pid": 511000, "id": 2443, "area_id": 511024 }, { "area_name": "资中县", "pinyin": "Zizhong", "level": 3, "area_code": 832, "post_code": 641200, "pid": 511000, "id": 2444, "area_id": 511025 }, { "area_name": "隆昌县", "pinyin": "Longchang", "level": 3, "area_code": 832, "post_code": 642150, "pid": 511000, "id": 2445, "area_id": 511028 }, { "area_name": "乐山市", "pinyin": "Leshan", "level": 2, "area_code": 833, "post_code": 614000, "pid": 510000, "id": 2446, "area_id": 511100 }, { "area_name": "市中区", "pinyin": "Shizhongqu", "level": 3, "area_code": 833, "post_code": 614000, "pid": 511100, "id": 2447, "area_id": 511102 }, { "area_name": "沙湾区", "pinyin": "Shawan", "level": 3, "area_code": 833, "post_code": 614900, "pid": 511100, "id": 2448, "area_id": 511111 }, { "area_name": "五通桥区", "pinyin": "Wutongqiao", "level": 3, "area_code": 833, "post_code": 614800, "pid": 511100, "id": 2449, "area_id": 511112 }, { "area_name": "金口河区", "pinyin": "Jinkouhe", "level": 3, "area_code": 833, "post_code": 614700, "pid": 511100, "id": 2450, "area_id": 511113 }, { "area_name": "犍为县", "pinyin": "Qianwei", "level": 3, "area_code": 833, "post_code": 614400, "pid": 511100, "id": 2451, "area_id": 511123 }, { "area_name": "井研县", "pinyin": "Jingyan", "level": 3, "area_code": 833, "post_code": 613100, "pid": 511100, "id": 2452, "area_id": 511124 }, { "area_name": "夹江县", "pinyin": "Jiajiang", "level": 3, "area_code": 833, "post_code": 614100, "pid": 511100, "id": 2453, "area_id": 511126 }, { "area_name": "沐川县", "pinyin": "Muchuan", "level": 3, "area_code": 833, "post_code": 614500, "pid": 511100, "id": 2454, "area_id": 511129 }, { "area_name": "峨边彝族自治县", "pinyin": "Ebian", "level": 3, "area_code": 833, "post_code": 614300, "pid": 511100, "id": 2455, "area_id": 511132 }, { "area_name": "马边彝族自治县", "pinyin": "Mabian", "level": 3, "area_code": 833, "post_code": 614600, "pid": 511100, "id": 2456, "area_id": 511133 }, { "area_name": "峨眉山市", "pinyin": "Emeishan", "level": 3, "area_code": 833, "post_code": 614200, "pid": 511100, "id": 2457, "area_id": 511181 }, { "area_name": "南充市", "pinyin": "Nanchong", "level": 2, "area_code": 817, "post_code": 637000, "pid": 510000, "id": 2458, "area_id": 511300 }, { "area_name": "顺庆区", "pinyin": "Shunqing", "level": 3, "area_code": 817, "post_code": 637000, "pid": 511300, "id": 2459, "area_id": 511302 }, { "area_name": "高坪区", "pinyin": "Gaoping", "level": 3, "area_code": 817, "post_code": 637100, "pid": 511300, "id": 2460, "area_id": 511303 }, { "area_name": "嘉陵区", "pinyin": "Jialing", "level": 3, "area_code": 817, "post_code": 637100, "pid": 511300, "id": 2461, "area_id": 511304 }, { "area_name": "南部县", "pinyin": "Nanbu", "level": 3, "area_code": 817, "post_code": 637300, "pid": 511300, "id": 2462, "area_id": 511321 }, { "area_name": "营山县", "pinyin": "Yingshan", "level": 3, "area_code": 817, "post_code": 637700, "pid": 511300, "id": 2463, "area_id": 511322 }, { "area_name": "蓬安县", "pinyin": "Peng'an", "level": 3, "area_code": 817, "post_code": 637800, "pid": 511300, "id": 2464, "area_id": 511323 }, { "area_name": "仪陇县", "pinyin": "Yilong", "level": 3, "area_code": 817, "post_code": 637600, "pid": 511300, "id": 2465, "area_id": 511324 }, { "area_name": "西充县", "pinyin": "Xichong", "level": 3, "area_code": 817, "post_code": 637200, "pid": 511300, "id": 2466, "area_id": 511325 }, { "area_name": "阆中市", "pinyin": "Langzhong", "level": 3, "area_code": 817, "post_code": 637400, "pid": 511300, "id": 2467, "area_id": 511381 }, { "area_name": "眉山市", "pinyin": "Meishan", "level": 2, "area_code": 28, "post_code": 620020, "pid": 510000, "id": 2468, "area_id": 511400 }, { "area_name": "东坡区", "pinyin": "Dongpo", "level": 3, "area_code": 28, "post_code": 620010, "pid": 511400, "id": 2469, "area_id": 511402 }, { "area_name": "彭山区", "pinyin": "Pengshan", "level": 3, "area_code": 28, "post_code": 620860, "pid": 511400, "id": 2470, "area_id": 511403 }, { "area_name": "仁寿县", "pinyin": "Renshou", "level": 3, "area_code": 28, "post_code": 620500, "pid": 511400, "id": 2471, "area_id": 511421 }, { "area_name": "洪雅县", "pinyin": "Hongya", "level": 3, "area_code": 28, "post_code": 620360, "pid": 511400, "id": 2472, "area_id": 511423 }, { "area_name": "丹棱县", "pinyin": "Danling", "level": 3, "area_code": 28, "post_code": 620200, "pid": 511400, "id": 2473, "area_id": 511424 }, { "area_name": "青神县", "pinyin": "Qingshen", "level": 3, "area_code": 28, "post_code": 620460, "pid": 511400, "id": 2474, "area_id": 511425 }, { "area_name": "宜宾市", "pinyin": "Yibin", "level": 2, "area_code": 831, "post_code": 644000, "pid": 510000, "id": 2475, "area_id": 511500 }, { "area_name": "翠屏区", "pinyin": "Cuiping", "level": 3, "area_code": 831, "post_code": 644000, "pid": 511500, "id": 2476, "area_id": 511502 }, { "area_name": "南溪区", "pinyin": "Nanxi", "level": 3, "area_code": 831, "post_code": 644100, "pid": 511500, "id": 2477, "area_id": 511503 }, { "area_name": "宜宾县", "pinyin": "Yibin", "level": 3, "area_code": 831, "post_code": 644600, "pid": 511500, "id": 2478, "area_id": 511521 }, { "area_name": "江安县", "pinyin": "Jiang'an", "level": 3, "area_code": 831, "post_code": 644200, "pid": 511500, "id": 2479, "area_id": 511523 }, { "area_name": "长宁县", "pinyin": "Changning", "level": 3, "area_code": 831, "post_code": 644300, "pid": 511500, "id": 2480, "area_id": 511524 }, { "area_name": "高县", "pinyin": "Gaoxian", "level": 3, "area_code": 831, "post_code": 645150, "pid": 511500, "id": 2481, "area_id": 511525 }, { "area_name": "珙县", "pinyin": "Gongxian", "level": 3, "area_code": 831, "post_code": 644500, "pid": 511500, "id": 2482, "area_id": 511526 }, { "area_name": "筠连县", "pinyin": "Junlian", "level": 3, "area_code": 831, "post_code": 645250, "pid": 511500, "id": 2483, "area_id": 511527 }, { "area_name": "兴文县", "pinyin": "Xingwen", "level": 3, "area_code": 831, "post_code": 644400, "pid": 511500, "id": 2484, "area_id": 511528 }, { "area_name": "屏山县", "pinyin": "Pingshan", "level": 3, "area_code": 831, "post_code": 645350, "pid": 511500, "id": 2485, "area_id": 511529 }, { "area_name": "广安市", "pinyin": "Guang'an", "level": 2, "area_code": 826, "post_code": 638000, "pid": 510000, "id": 2486, "area_id": 511600 }, { "area_name": "广安区", "pinyin": "Guang'an", "level": 3, "area_code": 826, "post_code": 638000, "pid": 511600, "id": 2487, "area_id": 511602 }, { "area_name": "前锋区", "pinyin": "Qianfeng", "level": 3, "area_code": 826, "post_code": 638019, "pid": 511600, "id": 2488, "area_id": 511603 }, { "area_name": "岳池县", "pinyin": "Yuechi", "level": 3, "area_code": 826, "post_code": 638300, "pid": 511600, "id": 2489, "area_id": 511621 }, { "area_name": "武胜县", "pinyin": "Wusheng", "level": 3, "area_code": 826, "post_code": 638400, "pid": 511600, "id": 2490, "area_id": 511622 }, { "area_name": "邻水县", "pinyin": "Linshui", "level": 3, "area_code": 826, "post_code": 638500, "pid": 511600, "id": 2491, "area_id": 511623 }, { "area_name": "华蓥市", "pinyin": "Huaying", "level": 3, "area_code": 826, "post_code": 638600, "pid": 511600, "id": 2492, "area_id": 511681 }, { "area_name": "达州市", "pinyin": "Dazhou", "level": 2, "area_code": 818, "post_code": 635000, "pid": 510000, "id": 2493, "area_id": 511700 }, { "area_name": "通川区", "pinyin": "Tongchuan", "level": 3, "area_code": 818, "post_code": 635000, "pid": 511700, "id": 2494, "area_id": 511702 }, { "area_name": "达川区", "pinyin": "Dachuan", "level": 3, "area_code": 818, "post_code": 635000, "pid": 511700, "id": 2495, "area_id": 511703 }, { "area_name": "宣汉县", "pinyin": "Xuanhan", "level": 3, "area_code": 818, "post_code": 636150, "pid": 511700, "id": 2496, "area_id": 511722 }, { "area_name": "开江县", "pinyin": "Kaijiang", "level": 3, "area_code": 818, "post_code": 636250, "pid": 511700, "id": 2497, "area_id": 511723 }, { "area_name": "大竹县", "pinyin": "Dazhu", "level": 3, "area_code": 818, "post_code": 635100, "pid": 511700, "id": 2498, "area_id": 511724 }, { "area_name": "渠县", "pinyin": "Quxian", "level": 3, "area_code": 818, "post_code": 635200, "pid": 511700, "id": 2499, "area_id": 511725 }, { "area_name": "万源市", "pinyin": "Wanyuan", "level": 3, "area_code": 818, "post_code": 636350, "pid": 511700, "id": 2500, "area_id": 511781 }, { "area_name": "雅安市", "pinyin": "Ya'an", "level": 2, "area_code": 835, "post_code": 625000, "pid": 510000, "id": 2501, "area_id": 511800 }, { "area_name": "雨城区", "pinyin": "Yucheng", "level": 3, "area_code": 835, "post_code": 625000, "pid": 511800, "id": 2502, "area_id": 511802 }, { "area_name": "名山区", "pinyin": "Mingshan", "level": 3, "area_code": 835, "post_code": 625100, "pid": 511800, "id": 2503, "area_id": 511803 }, { "area_name": "荥经县", "pinyin": "Yingjing", "level": 3, "area_code": 835, "post_code": 625200, "pid": 511800, "id": 2504, "area_id": 511822 }, { "area_name": "汉源县", "pinyin": "Hanyuan", "level": 3, "area_code": 835, "post_code": 625300, "pid": 511800, "id": 2505, "area_id": 511823 }, { "area_name": "石棉县", "pinyin": "Shimian", "level": 3, "area_code": 835, "post_code": 625400, "pid": 511800, "id": 2506, "area_id": 511824 }, { "area_name": "天全县", "pinyin": "Tianquan", "level": 3, "area_code": 835, "post_code": 625500, "pid": 511800, "id": 2507, "area_id": 511825 }, { "area_name": "芦山县", "pinyin": "Lushan", "level": 3, "area_code": 835, "post_code": 625600, "pid": 511800, "id": 2508, "area_id": 511826 }, { "area_name": "宝兴县", "pinyin": "Baoxing", "level": 3, "area_code": 835, "post_code": 625700, "pid": 511800, "id": 2509, "area_id": 511827 }, { "area_name": "巴中市", "pinyin": "Bazhong", "level": 2, "area_code": 827, "post_code": 636000, "pid": 510000, "id": 2510, "area_id": 511900 }, { "area_name": "巴州区", "pinyin": "Bazhou", "level": 3, "area_code": 827, "post_code": 636001, "pid": 511900, "id": 2511, "area_id": 511902 }, { "area_name": "恩阳区", "pinyin": "Enyang", "level": 3, "area_code": 827, "post_code": 636064, "pid": 511900, "id": 2512, "area_id": 511903 }, { "area_name": "通江县", "pinyin": "Tongjiang", "level": 3, "area_code": 827, "post_code": 636700, "pid": 511900, "id": 2513, "area_id": 511921 }, { "area_name": "南江县", "pinyin": "Nanjiang", "level": 3, "area_code": 827, "post_code": 636600, "pid": 511900, "id": 2514, "area_id": 511922 }, { "area_name": "平昌县", "pinyin": "Pingchang", "level": 3, "area_code": 827, "post_code": 636400, "pid": 511900, "id": 2515, "area_id": 511923 }, { "area_name": "资阳市", "pinyin": "Ziyang", "level": 2, "area_code": 28, "post_code": 641300, "pid": 510000, "id": 2516, "area_id": 512000 }, { "area_name": "雁江区", "pinyin": "Yanjiang", "level": 3, "area_code": 28, "post_code": 641300, "pid": 512000, "id": 2517, "area_id": 512002 }, { "area_name": "安岳县", "pinyin": "Anyue", "level": 3, "area_code": 28, "post_code": 642350, "pid": 512000, "id": 2518, "area_id": 512021 }, { "area_name": "乐至县", "pinyin": "Lezhi", "level": 3, "area_code": 28, "post_code": 641500, "pid": 512000, "id": 2519, "area_id": 512022 }, { "area_name": "简阳市", "pinyin": "Jianyang", "level": 3, "area_code": 28, "post_code": 641400, "pid": 512000, "id": 2520, "area_id": 512081 }, { "area_name": "阿坝藏族羌族自治州", "pinyin": "Aba", "level": 2, "area_code": 837, "post_code": 624000, "pid": 510000, "id": 2521, "area_id": 513200 }, { "area_name": "汶川县", "pinyin": "Wenchuan", "level": 3, "area_code": 837, "post_code": 623000, "pid": 513200, "id": 2522, "area_id": 513221 }, { "area_name": "理县", "pinyin": "Lixian", "level": 3, "area_code": 837, "post_code": 623100, "pid": 513200, "id": 2523, "area_id": 513222 }, { "area_name": "茂县", "pinyin": "Maoxian", "level": 3, "area_code": 837, "post_code": 623200, "pid": 513200, "id": 2524, "area_id": 513223 }, { "area_name": "松潘县", "pinyin": "Songpan", "level": 3, "area_code": 837, "post_code": 623300, "pid": 513200, "id": 2525, "area_id": 513224 }, { "area_name": "九寨沟县", "pinyin": "Jiuzhaigou", "level": 3, "area_code": 837, "post_code": 623400, "pid": 513200, "id": 2526, "area_id": 513225 }, { "area_name": "金川县", "pinyin": "Jinchuan", "level": 3, "area_code": 837, "post_code": 624100, "pid": 513200, "id": 2527, "area_id": 513226 }, { "area_name": "小金县", "pinyin": "Xiaojin", "level": 3, "area_code": 837, "post_code": 624200, "pid": 513200, "id": 2528, "area_id": 513227 }, { "area_name": "黑水县", "pinyin": "Heishui", "level": 3, "area_code": 837, "post_code": 623500, "pid": 513200, "id": 2529, "area_id": 513228 }, { "area_name": "马尔康县", "pinyin": "Maerkang", "level": 3, "area_code": 837, "post_code": 624000, "pid": 513200, "id": 2530, "area_id": 513229 }, { "area_name": "壤塘县", "pinyin": "Rangtang", "level": 3, "area_code": 837, "post_code": 624300, "pid": 513200, "id": 2531, "area_id": 513230 }, { "area_name": "阿坝县", "pinyin": "Aba", "level": 3, "area_code": 837, "post_code": 624600, "pid": 513200, "id": 2532, "area_id": 513231 }, { "area_name": "若尔盖县", "pinyin": "Ruoergai", "level": 3, "area_code": 837, "post_code": 624500, "pid": 513200, "id": 2533, "area_id": 513232 }, { "area_name": "红原县", "pinyin": "Hongyuan", "level": 3, "area_code": 837, "post_code": 624400, "pid": 513200, "id": 2534, "area_id": 513233 }, { "area_name": "甘孜藏族自治州", "pinyin": "Garze", "level": 2, "area_code": 836, "post_code": 626000, "pid": 510000, "id": 2535, "area_id": 513300 }, { "area_name": "康定县", "pinyin": "Kangding", "level": 3, "area_code": 836, "post_code": 626000, "pid": 513300, "id": 2536, "area_id": 513321 }, { "area_name": "泸定县", "pinyin": "Luding", "level": 3, "area_code": 836, "post_code": 626100, "pid": 513300, "id": 2537, "area_id": 513322 }, { "area_name": "丹巴县", "pinyin": "Danba", "level": 3, "area_code": 836, "post_code": 626300, "pid": 513300, "id": 2538, "area_id": 513323 }, { "area_name": "九龙县", "pinyin": "Jiulong", "level": 3, "area_code": 836, "post_code": 626200, "pid": 513300, "id": 2539, "area_id": 513324 }, { "area_name": "雅江县", "pinyin": "Yajiang", "level": 3, "area_code": 836, "post_code": 627450, "pid": 513300, "id": 2540, "area_id": 513325 }, { "area_name": "道孚县", "pinyin": "Daofu", "level": 3, "area_code": 836, "post_code": 626400, "pid": 513300, "id": 2541, "area_id": 513326 }, { "area_name": "炉霍县", "pinyin": "Luhuo", "level": 3, "area_code": 836, "post_code": 626500, "pid": 513300, "id": 2542, "area_id": 513327 }, { "area_name": "甘孜县", "pinyin": "Ganzi", "level": 3, "area_code": 836, "post_code": 626700, "pid": 513300, "id": 2543, "area_id": 513328 }, { "area_name": "新龙县", "pinyin": "Xinlong", "level": 3, "area_code": 836, "post_code": 626800, "pid": 513300, "id": 2544, "area_id": 513329 }, { "area_name": "德格县", "pinyin": "Dege", "level": 3, "area_code": 836, "post_code": 627250, "pid": 513300, "id": 2545, "area_id": 513330 }, { "area_name": "白玉县", "pinyin": "Baiyu", "level": 3, "area_code": 836, "post_code": 627150, "pid": 513300, "id": 2546, "area_id": 513331 }, { "area_name": "石渠县", "pinyin": "Shiqu", "level": 3, "area_code": 836, "post_code": 627350, "pid": 513300, "id": 2547, "area_id": 513332 }, { "area_name": "色达县", "pinyin": "Seda", "level": 3, "area_code": 836, "post_code": 626600, "pid": 513300, "id": 2548, "area_id": 513333 }, { "area_name": "理塘县", "pinyin": "Litang", "level": 3, "area_code": 836, "post_code": 627550, "pid": 513300, "id": 2549, "area_id": 513334 }, { "area_name": "巴塘县", "pinyin": "Batang", "level": 3, "area_code": 836, "post_code": 627650, "pid": 513300, "id": 2550, "area_id": 513335 }, { "area_name": "乡城县", "pinyin": "Xiangcheng", "level": 3, "area_code": 836, "post_code": 627850, "pid": 513300, "id": 2551, "area_id": 513336 }, { "area_name": "稻城县", "pinyin": "Daocheng", "level": 3, "area_code": 836, "post_code": 627750, "pid": 513300, "id": 2552, "area_id": 513337 }, { "area_name": "得荣县", "pinyin": "Derong", "level": 3, "area_code": 836, "post_code": 627950, "pid": 513300, "id": 2553, "area_id": 513338 }, { "area_name": "凉山彝族自治州", "pinyin": "Liangshan", "level": 2, "area_code": 834, "post_code": 615000, "pid": 510000, "id": 2554, "area_id": 513400 }, { "area_name": "西昌市", "pinyin": "Xichang", "level": 3, "area_code": 835, "post_code": 615000, "pid": 513400, "id": 2555, "area_id": 513401 }, { "area_name": "木里藏族自治县", "pinyin": "Muli", "level": 3, "area_code": 851, "post_code": 615800, "pid": 513400, "id": 2556, "area_id": 513422 }, { "area_name": "盐源县", "pinyin": "Yanyuan", "level": 3, "area_code": 836, "post_code": 615700, "pid": 513400, "id": 2557, "area_id": 513423 }, { "area_name": "德昌县", "pinyin": "Dechang", "level": 3, "area_code": 837, "post_code": 615500, "pid": 513400, "id": 2558, "area_id": 513424 }, { "area_name": "会理县", "pinyin": "Huili", "level": 3, "area_code": 838, "post_code": 615100, "pid": 513400, "id": 2559, "area_id": 513425 }, { "area_name": "会东县", "pinyin": "Huidong", "level": 3, "area_code": 839, "post_code": 615200, "pid": 513400, "id": 2560, "area_id": 513426 }, { "area_name": "宁南县", "pinyin": "Ningnan", "level": 3, "area_code": 840, "post_code": 615400, "pid": 513400, "id": 2561, "area_id": 513427 }, { "area_name": "普格县", "pinyin": "Puge", "level": 3, "area_code": 841, "post_code": 615300, "pid": 513400, "id": 2562, "area_id": 513428 }, { "area_name": "布拖县", "pinyin": "Butuo", "level": 3, "area_code": 842, "post_code": 616350, "pid": 513400, "id": 2563, "area_id": 513429 }, { "area_name": "金阳县", "pinyin": "Jinyang", "level": 3, "area_code": 843, "post_code": 616250, "pid": 513400, "id": 2564, "area_id": 513430 }, { "area_name": "昭觉县", "pinyin": "Zhaojue", "level": 3, "area_code": 844, "post_code": 616150, "pid": 513400, "id": 2565, "area_id": 513431 }, { "area_name": "喜德县", "pinyin": "Xide", "level": 3, "area_code": 845, "post_code": 616750, "pid": 513400, "id": 2566, "area_id": 513432 }, { "area_name": "冕宁县", "pinyin": "Mianning", "level": 3, "area_code": 846, "post_code": 615600, "pid": 513400, "id": 2567, "area_id": 513433 }, { "area_name": "越西县", "pinyin": "Yuexi", "level": 3, "area_code": 847, "post_code": 616650, "pid": 513400, "id": 2568, "area_id": 513434 }, { "area_name": "甘洛县", "pinyin": "Ganluo", "level": 3, "area_code": 848, "post_code": 616850, "pid": 513400, "id": 2569, "area_id": 513435 }, { "area_name": "美姑县", "pinyin": "Meigu", "level": 3, "area_code": 849, "post_code": 616450, "pid": 513400, "id": 2570, "area_id": 513436 }, { "area_name": "雷波县", "pinyin": "Leibo", "level": 3, "area_code": 850, "post_code": 616550, "pid": 513400, "id": 2571, "area_id": 513437 }, { "area_name": "贵州省", "pinyin": "Guizhou", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2572, "area_id": 520000 }, { "area_name": "贵阳市", "pinyin": "Guiyang", "level": 2, "area_code": 851, "post_code": 550001, "pid": 520000, "id": 2573, "area_id": 520100 }, { "area_name": "南明区", "pinyin": "Nanming", "level": 3, "area_code": 851, "post_code": 550001, "pid": 520100, "id": 2574, "area_id": 520102 }, { "area_name": "云岩区", "pinyin": "Yunyan", "level": 3, "area_code": 851, "post_code": 550001, "pid": 520100, "id": 2575, "area_id": 520103 }, { "area_name": "花溪区", "pinyin": "Huaxi", "level": 3, "area_code": 851, "post_code": 550025, "pid": 520100, "id": 2576, "area_id": 520111 }, { "area_name": "乌当区", "pinyin": "Wudang", "level": 3, "area_code": 851, "post_code": 550018, "pid": 520100, "id": 2577, "area_id": 520112 }, { "area_name": "白云区", "pinyin": "Baiyun", "level": 3, "area_code": 851, "post_code": 550014, "pid": 520100, "id": 2578, "area_id": 520113 }, { "area_name": "观山湖区", "pinyin": "Guanshanhu", "level": 3, "area_code": 851, "post_code": 550009, "pid": 520100, "id": 2579, "area_id": 520115 }, { "area_name": "开阳县", "pinyin": "Kaiyang", "level": 3, "area_code": 851, "post_code": 550300, "pid": 520100, "id": 2580, "area_id": 520121 }, { "area_name": "息烽县", "pinyin": "Xifeng", "level": 3, "area_code": 851, "post_code": 551100, "pid": 520100, "id": 2581, "area_id": 520122 }, { "area_name": "修文县", "pinyin": "Xiuwen", "level": 3, "area_code": 851, "post_code": 550200, "pid": 520100, "id": 2582, "area_id": 520123 }, { "area_name": "清镇市", "pinyin": "Qingzhen", "level": 3, "area_code": 851, "post_code": 551400, "pid": 520100, "id": 2583, "area_id": 520181 }, { "area_name": "六盘水市", "pinyin": "Liupanshui", "level": 2, "area_code": 858, "post_code": 553400, "pid": 520000, "id": 2584, "area_id": 520200 }, { "area_name": "钟山区", "pinyin": "Zhongshan", "level": 3, "area_code": 858, "post_code": 553000, "pid": 520200, "id": 2585, "area_id": 520201 }, { "area_name": "六枝特区", "pinyin": "Liuzhi", "level": 3, "area_code": 858, "post_code": 553400, "pid": 520200, "id": 2586, "area_id": 520203 }, { "area_name": "水城县", "pinyin": "Shuicheng", "level": 3, "area_code": 858, "post_code": 553000, "pid": 520200, "id": 2587, "area_id": 520221 }, { "area_name": "盘县", "pinyin": "Panxian", "level": 3, "area_code": 858, "post_code": 561601, "pid": 520200, "id": 2588, "area_id": 520222 }, { "area_name": "遵义市", "pinyin": "Zunyi", "level": 2, "area_code": 852, "post_code": 563000, "pid": 520000, "id": 2589, "area_id": 520300 }, { "area_name": "红花岗区", "pinyin": "Honghuagang", "level": 3, "area_code": 852, "post_code": 563000, "pid": 520300, "id": 2590, "area_id": 520302 }, { "area_name": "汇川区", "pinyin": "Huichuan", "level": 3, "area_code": 852, "post_code": 563000, "pid": 520300, "id": 2591, "area_id": 520303 }, { "area_name": "遵义县", "pinyin": "Zunyi", "level": 3, "area_code": 852, "post_code": 563100, "pid": 520300, "id": 2592, "area_id": 520321 }, { "area_name": "桐梓县", "pinyin": "Tongzi", "level": 3, "area_code": 852, "post_code": 563200, "pid": 520300, "id": 2593, "area_id": 520322 }, { "area_name": "绥阳县", "pinyin": "Suiyang", "level": 3, "area_code": 852, "post_code": 563300, "pid": 520300, "id": 2594, "area_id": 520323 }, { "area_name": "正安县", "pinyin": "Zheng'an", "level": 3, "area_code": 852, "post_code": 563400, "pid": 520300, "id": 2595, "area_id": 520324 }, { "area_name": "道真仡佬族苗族自治县", "pinyin": "Daozhen", "level": 3, "area_code": 852, "post_code": 563500, "pid": 520300, "id": 2596, "area_id": 520325 }, { "area_name": "务川仡佬族苗族自治县", "pinyin": "Wuchuan", "level": 3, "area_code": 852, "post_code": 564300, "pid": 520300, "id": 2597, "area_id": 520326 }, { "area_name": "凤冈县", "pinyin": "Fenggang", "level": 3, "area_code": 852, "post_code": 564200, "pid": 520300, "id": 2598, "area_id": 520327 }, { "area_name": "湄潭县", "pinyin": "Meitan", "level": 3, "area_code": 852, "post_code": 564100, "pid": 520300, "id": 2599, "area_id": 520328 }, { "area_name": "余庆县", "pinyin": "Yuqing", "level": 3, "area_code": 852, "post_code": 564400, "pid": 520300, "id": 2600, "area_id": 520329 }, { "area_name": "习水县", "pinyin": "Xishui", "level": 3, "area_code": 852, "post_code": 564600, "pid": 520300, "id": 2601, "area_id": 520330 }, { "area_name": "赤水市", "pinyin": "Chishui", "level": 3, "area_code": 852, "post_code": 564700, "pid": 520300, "id": 2602, "area_id": 520381 }, { "area_name": "仁怀市", "pinyin": "Renhuai", "level": 3, "area_code": 852, "post_code": 564500, "pid": 520300, "id": 2603, "area_id": 520382 }, { "area_name": "安顺市", "pinyin": "Anshun", "level": 2, "area_code": 853, "post_code": 561000, "pid": 520000, "id": 2604, "area_id": 520400 }, { "area_name": "西秀区", "pinyin": "Xixiu", "level": 3, "area_code": 853, "post_code": 561000, "pid": 520400, "id": 2605, "area_id": 520402 }, { "area_name": "平坝区", "pinyin": "Pingba", "level": 3, "area_code": 853, "post_code": 561100, "pid": 520400, "id": 2606, "area_id": 520421 }, { "area_name": "普定县", "pinyin": "Puding", "level": 3, "area_code": 853, "post_code": 562100, "pid": 520400, "id": 2607, "area_id": 520422 }, { "area_name": "镇宁布依族苗族自治县", "pinyin": "Zhenning", "level": 3, "area_code": 853, "post_code": 561200, "pid": 520400, "id": 2608, "area_id": 520423 }, { "area_name": "关岭布依族苗族自治县", "pinyin": "Guanling", "level": 3, "area_code": 853, "post_code": 561300, "pid": 520400, "id": 2609, "area_id": 520424 }, { "area_name": "紫云苗族布依族自治县", "pinyin": "Ziyun", "level": 3, "area_code": 853, "post_code": 550800, "pid": 520400, "id": 2610, "area_id": 520425 }, { "area_name": "毕节市", "pinyin": "Bijie", "level": 2, "area_code": 857, "post_code": 551700, "pid": 520000, "id": 2611, "area_id": 520500 }, { "area_name": "七星关区", "pinyin": "Qixingguan", "level": 3, "area_code": 857, "post_code": 551700, "pid": 520500, "id": 2612, "area_id": 520502 }, { "area_name": "大方县", "pinyin": "Dafang", "level": 3, "area_code": 857, "post_code": 551600, "pid": 520500, "id": 2613, "area_id": 520521 }, { "area_name": "黔西县", "pinyin": "Qianxi", "level": 3, "area_code": 857, "post_code": 551500, "pid": 520500, "id": 2614, "area_id": 520522 }, { "area_name": "金沙县", "pinyin": "Jinsha", "level": 3, "area_code": 857, "post_code": 551800, "pid": 520500, "id": 2615, "area_id": 520523 }, { "area_name": "织金县", "pinyin": "Zhijin", "level": 3, "area_code": 857, "post_code": 552100, "pid": 520500, "id": 2616, "area_id": 520524 }, { "area_name": "纳雍县", "pinyin": "Nayong", "level": 3, "area_code": 857, "post_code": 553300, "pid": 520500, "id": 2617, "area_id": 520525 }, { "area_name": "威宁彝族回族苗族自治县", "pinyin": "Weining", "level": 3, "area_code": 857, "post_code": 553100, "pid": 520500, "id": 2618, "area_id": 520526 }, { "area_name": "赫章县", "pinyin": "Hezhang", "level": 3, "area_code": 857, "post_code": 553200, "pid": 520500, "id": 2619, "area_id": 520527 }, { "area_name": "铜仁市", "pinyin": "Tongren", "level": 2, "area_code": 856, "post_code": 554300, "pid": 520000, "id": 2620, "area_id": 520600 }, { "area_name": "碧江区", "pinyin": "Bijiang", "level": 3, "area_code": 856, "post_code": 554300, "pid": 520600, "id": 2621, "area_id": 520602 }, { "area_name": "万山区", "pinyin": "Wanshan", "level": 3, "area_code": 856, "post_code": 554200, "pid": 520600, "id": 2622, "area_id": 520603 }, { "area_name": "江口县", "pinyin": "Jiangkou", "level": 3, "area_code": 856, "post_code": 554400, "pid": 520600, "id": 2623, "area_id": 520621 }, { "area_name": "玉屏侗族自治县", "pinyin": "Yuping", "level": 3, "area_code": 856, "post_code": 554004, "pid": 520600, "id": 2624, "area_id": 520622 }, { "area_name": "石阡县", "pinyin": "Shiqian", "level": 3, "area_code": 856, "post_code": 555100, "pid": 520600, "id": 2625, "area_id": 520623 }, { "area_name": "思南县", "pinyin": "Sinan", "level": 3, "area_code": 856, "post_code": 565100, "pid": 520600, "id": 2626, "area_id": 520624 }, { "area_name": "印江土家族苗族自治县", "pinyin": "Yinjiang", "level": 3, "area_code": 856, "post_code": 555200, "pid": 520600, "id": 2627, "area_id": 520625 }, { "area_name": "德江县", "pinyin": "Dejiang", "level": 3, "area_code": 856, "post_code": 565200, "pid": 520600, "id": 2628, "area_id": 520626 }, { "area_name": "沿河土家族自治县", "pinyin": "Yuanhe", "level": 3, "area_code": 856, "post_code": 565300, "pid": 520600, "id": 2629, "area_id": 520627 }, { "area_name": "松桃苗族自治县", "pinyin": "Songtao", "level": 3, "area_code": 856, "post_code": 554100, "pid": 520600, "id": 2630, "area_id": 520628 }, { "area_name": "黔西南布依族苗族自治州", "pinyin": "Qianxinan", "level": 2, "area_code": 859, "post_code": 562400, "pid": 520000, "id": 2631, "area_id": 522300 }, { "area_name": "兴义市", "pinyin": "Xingyi", "level": 3, "area_code": 859, "post_code": 562400, "pid": 522300, "id": 2632, "area_id": 522301 }, { "area_name": "兴仁县", "pinyin": "Xingren", "level": 3, "area_code": 859, "post_code": 562300, "pid": 522300, "id": 2633, "area_id": 522322 }, { "area_name": "普安县", "pinyin": "Pu'an", "level": 3, "area_code": 859, "post_code": 561500, "pid": 522300, "id": 2634, "area_id": 522323 }, { "area_name": "晴隆县", "pinyin": "Qinglong", "level": 3, "area_code": 859, "post_code": 561400, "pid": 522300, "id": 2635, "area_id": 522324 }, { "area_name": "贞丰县", "pinyin": "Zhenfeng", "level": 3, "area_code": 859, "post_code": 562200, "pid": 522300, "id": 2636, "area_id": 522325 }, { "area_name": "望谟县", "pinyin": "Wangmo", "level": 3, "area_code": 859, "post_code": 552300, "pid": 522300, "id": 2637, "area_id": 522326 }, { "area_name": "册亨县", "pinyin": "Ceheng", "level": 3, "area_code": 859, "post_code": 552200, "pid": 522300, "id": 2638, "area_id": 522327 }, { "area_name": "安龙县", "pinyin": "Anlong", "level": 3, "area_code": 859, "post_code": 552400, "pid": 522300, "id": 2639, "area_id": 522328 }, { "area_name": "黔东南苗族侗族自治州", "pinyin": "Qiandongnan", "level": 2, "area_code": 855, "post_code": 556000, "pid": 520000, "id": 2640, "area_id": 522600 }, { "area_name": "凯里市", "pinyin": "Kaili", "level": 3, "area_code": 855, "post_code": 556000, "pid": 522600, "id": 2641, "area_id": 522601 }, { "area_name": "黄平县", "pinyin": "Huangping", "level": 3, "area_code": 855, "post_code": 556100, "pid": 522600, "id": 2642, "area_id": 522622 }, { "area_name": "施秉县", "pinyin": "Shibing", "level": 3, "area_code": 855, "post_code": 556200, "pid": 522600, "id": 2643, "area_id": 522623 }, { "area_name": "三穗县", "pinyin": "Sansui", "level": 3, "area_code": 855, "post_code": 556500, "pid": 522600, "id": 2644, "area_id": 522624 }, { "area_name": "镇远县", "pinyin": "Zhenyuan", "level": 3, "area_code": 855, "post_code": 557700, "pid": 522600, "id": 2645, "area_id": 522625 }, { "area_name": "岑巩县", "pinyin": "Cengong", "level": 3, "area_code": 855, "post_code": 557800, "pid": 522600, "id": 2646, "area_id": 522626 }, { "area_name": "天柱县", "pinyin": "Tianzhu", "level": 3, "area_code": 855, "post_code": 556600, "pid": 522600, "id": 2647, "area_id": 522627 }, { "area_name": "锦屏县", "pinyin": "Jinping", "level": 3, "area_code": 855, "post_code": 556700, "pid": 522600, "id": 2648, "area_id": 522628 }, { "area_name": "剑河县", "pinyin": "Jianhe", "level": 3, "area_code": 855, "post_code": 556400, "pid": 522600, "id": 2649, "area_id": 522629 }, { "area_name": "台江县", "pinyin": "Taijiang", "level": 3, "area_code": 855, "post_code": 556300, "pid": 522600, "id": 2650, "area_id": 522630 }, { "area_name": "黎平县", "pinyin": "Liping", "level": 3, "area_code": 855, "post_code": 557300, "pid": 522600, "id": 2651, "area_id": 522631 }, { "area_name": "榕江县", "pinyin": "Rongjiang", "level": 3, "area_code": 855, "post_code": 557200, "pid": 522600, "id": 2652, "area_id": 522632 }, { "area_name": "从江县", "pinyin": "Congjiang", "level": 3, "area_code": 855, "post_code": 557400, "pid": 522600, "id": 2653, "area_id": 522633 }, { "area_name": "雷山县", "pinyin": "Leishan", "level": 3, "area_code": 855, "post_code": 557100, "pid": 522600, "id": 2654, "area_id": 522634 }, { "area_name": "麻江县", "pinyin": "Majiang", "level": 3, "area_code": 855, "post_code": 557600, "pid": 522600, "id": 2655, "area_id": 522635 }, { "area_name": "丹寨县", "pinyin": "Danzhai", "level": 3, "area_code": 855, "post_code": 557500, "pid": 522600, "id": 2656, "area_id": 522636 }, { "area_name": "黔南布依族苗族自治州", "pinyin": "Qiannan", "level": 2, "area_code": 854, "post_code": 558000, "pid": 520000, "id": 2657, "area_id": 522700 }, { "area_name": "都匀市", "pinyin": "Duyun", "level": 3, "area_code": 854, "post_code": 558000, "pid": 522700, "id": 2658, "area_id": 522701 }, { "area_name": "福泉市", "pinyin": "Fuquan", "level": 3, "area_code": 854, "post_code": 550500, "pid": 522700, "id": 2659, "area_id": 522702 }, { "area_name": "荔波县", "pinyin": "Libo", "level": 3, "area_code": 854, "post_code": 558400, "pid": 522700, "id": 2660, "area_id": 522722 }, { "area_name": "贵定县", "pinyin": "Guiding", "level": 3, "area_code": 854, "post_code": 551300, "pid": 522700, "id": 2661, "area_id": 522723 }, { "area_name": "瓮安县", "pinyin": "Weng'an", "level": 3, "area_code": 854, "post_code": 550400, "pid": 522700, "id": 2662, "area_id": 522725 }, { "area_name": "独山县", "pinyin": "Dushan", "level": 3, "area_code": 854, "post_code": 558200, "pid": 522700, "id": 2663, "area_id": 522726 }, { "area_name": "平塘县", "pinyin": "Pingtang", "level": 3, "area_code": 854, "post_code": 558300, "pid": 522700, "id": 2664, "area_id": 522727 }, { "area_name": "罗甸县", "pinyin": "Luodian", "level": 3, "area_code": 854, "post_code": 550100, "pid": 522700, "id": 2665, "area_id": 522728 }, { "area_name": "长顺县", "pinyin": "Changshun", "level": 3, "area_code": 854, "post_code": 550700, "pid": 522700, "id": 2666, "area_id": 522729 }, { "area_name": "龙里县", "pinyin": "Longli", "level": 3, "area_code": 854, "post_code": 551200, "pid": 522700, "id": 2667, "area_id": 522730 }, { "area_name": "惠水县", "pinyin": "Huishui", "level": 3, "area_code": 854, "post_code": 550600, "pid": 522700, "id": 2668, "area_id": 522731 }, { "area_name": "三都水族自治县", "pinyin": "Sandu", "level": 3, "area_code": 854, "post_code": 558100, "pid": 522700, "id": 2669, "area_id": 522732 }, { "area_name": "云南省", "pinyin": "Yunnan", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2670, "area_id": 530000 }, { "area_name": "昆明市", "pinyin": "Kunming", "level": 2, "area_code": 871, "post_code": 650500, "pid": 530000, "id": 2671, "area_id": 530100 }, { "area_name": "五华区", "pinyin": "Wuhua", "level": 3, "area_code": 871, "post_code": 650021, "pid": 530100, "id": 2672, "area_id": 530102 }, { "area_name": "盘龙区", "pinyin": "Panlong", "level": 3, "area_code": 871, "post_code": 650051, "pid": 530100, "id": 2673, "area_id": 530103 }, { "area_name": "官渡区", "pinyin": "Guandu", "level": 3, "area_code": 871, "post_code": 650200, "pid": 530100, "id": 2674, "area_id": 530111 }, { "area_name": "西山区", "pinyin": "Xishan", "level": 3, "area_code": 871, "post_code": 650118, "pid": 530100, "id": 2675, "area_id": 530112 }, { "area_name": "东川区", "pinyin": "Dongchuan", "level": 3, "area_code": 871, "post_code": 654100, "pid": 530100, "id": 2676, "area_id": 530113 }, { "area_name": "呈贡区", "pinyin": "Chenggong", "level": 3, "area_code": 871, "post_code": 650500, "pid": 530100, "id": 2677, "area_id": 530114 }, { "area_name": "晋宁县", "pinyin": "Jinning", "level": 3, "area_code": 871, "post_code": 650600, "pid": 530100, "id": 2678, "area_id": 530122 }, { "area_name": "富民县", "pinyin": "Fumin", "level": 3, "area_code": 871, "post_code": 650400, "pid": 530100, "id": 2679, "area_id": 530124 }, { "area_name": "宜良县", "pinyin": "Yiliang", "level": 3, "area_code": 871, "post_code": 652100, "pid": 530100, "id": 2680, "area_id": 530125 }, { "area_name": "石林彝族自治县", "pinyin": "Shilin", "level": 3, "area_code": 871, "post_code": 652200, "pid": 530100, "id": 2681, "area_id": 530126 }, { "area_name": "嵩明县", "pinyin": "Songming", "level": 3, "area_code": 871, "post_code": 651700, "pid": 530100, "id": 2682, "area_id": 530127 }, { "area_name": "禄劝彝族苗族自治县", "pinyin": "Luquan", "level": 3, "area_code": 871, "post_code": 651500, "pid": 530100, "id": 2683, "area_id": 530128 }, { "area_name": "寻甸回族彝族自治县", "pinyin": "Xundian", "level": 3, "area_code": 871, "post_code": 655200, "pid": 530100, "id": 2684, "area_id": 530129 }, { "area_name": "安宁市", "pinyin": "Anning", "level": 3, "area_code": 871, "post_code": 650300, "pid": 530100, "id": 2685, "area_id": 530181 }, { "area_name": "曲靖市", "pinyin": "Qujing", "level": 2, "area_code": 874, "post_code": 655000, "pid": 530000, "id": 2686, "area_id": 530300 }, { "area_name": "麒麟区", "pinyin": "Qilin", "level": 3, "area_code": 874, "post_code": 655000, "pid": 530300, "id": 2687, "area_id": 530302 }, { "area_name": "马龙县", "pinyin": "Malong", "level": 3, "area_code": 874, "post_code": 655100, "pid": 530300, "id": 2688, "area_id": 530321 }, { "area_name": "陆良县", "pinyin": "Luliang", "level": 3, "area_code": 874, "post_code": 655600, "pid": 530300, "id": 2689, "area_id": 530322 }, { "area_name": "师宗县", "pinyin": "Shizong", "level": 3, "area_code": 874, "post_code": 655700, "pid": 530300, "id": 2690, "area_id": 530323 }, { "area_name": "罗平县", "pinyin": "Luoping", "level": 3, "area_code": 874, "post_code": 655800, "pid": 530300, "id": 2691, "area_id": 530324 }, { "area_name": "富源县", "pinyin": "Fuyuan", "level": 3, "area_code": 874, "post_code": 655500, "pid": 530300, "id": 2692, "area_id": 530325 }, { "area_name": "会泽县", "pinyin": "Huize", "level": 3, "area_code": 874, "post_code": 654200, "pid": 530300, "id": 2693, "area_id": 530326 }, { "area_name": "沾益县", "pinyin": "Zhanyi", "level": 3, "area_code": 874, "post_code": 655331, "pid": 530300, "id": 2694, "area_id": 530328 }, { "area_name": "宣威市", "pinyin": "Xuanwei", "level": 3, "area_code": 874, "post_code": 655400, "pid": 530300, "id": 2695, "area_id": 530381 }, { "area_name": "玉溪市", "pinyin": "Yuxi", "level": 2, "area_code": 877, "post_code": 653100, "pid": 530000, "id": 2696, "area_id": 530400 }, { "area_name": "红塔区", "pinyin": "Hongta", "level": 3, "area_code": 877, "post_code": 653100, "pid": 530400, "id": 2697, "area_id": 530402 }, { "area_name": "江川县", "pinyin": "Jiangchuan", "level": 3, "area_code": 877, "post_code": 652600, "pid": 530400, "id": 2698, "area_id": 530421 }, { "area_name": "澄江县", "pinyin": "Chengjiang", "level": 3, "area_code": 877, "post_code": 652500, "pid": 530400, "id": 2699, "area_id": 530422 }, { "area_name": "通海县", "pinyin": "Tonghai", "level": 3, "area_code": 877, "post_code": 652700, "pid": 530400, "id": 2700, "area_id": 530423 }, { "area_name": "华宁县", "pinyin": "Huaning", "level": 3, "area_code": 877, "post_code": 652800, "pid": 530400, "id": 2701, "area_id": 530424 }, { "area_name": "易门县", "pinyin": "Yimen", "level": 3, "area_code": 877, "post_code": 651100, "pid": 530400, "id": 2702, "area_id": 530425 }, { "area_name": "峨山彝族自治县", "pinyin": "Eshan", "level": 3, "area_code": 877, "post_code": 653200, "pid": 530400, "id": 2703, "area_id": 530426 }, { "area_name": "新平彝族傣族自治县", "pinyin": "Xinping", "level": 3, "area_code": 877, "post_code": 653400, "pid": 530400, "id": 2704, "area_id": 530427 }, { "area_name": "元江哈尼族彝族傣族自治县", "pinyin": "Yuanjiang", "level": 3, "area_code": 877, "post_code": 653300, "pid": 530400, "id": 2705, "area_id": 530428 }, { "area_name": "保山市", "pinyin": "Baoshan", "level": 2, "area_code": 875, "post_code": 678000, "pid": 530000, "id": 2706, "area_id": 530500 }, { "area_name": "隆阳区", "pinyin": "Longyang", "level": 3, "area_code": 875, "post_code": 678000, "pid": 530500, "id": 2707, "area_id": 530502 }, { "area_name": "施甸县", "pinyin": "Shidian", "level": 3, "area_code": 875, "post_code": 678200, "pid": 530500, "id": 2708, "area_id": 530521 }, { "area_name": "腾冲县", "pinyin": "Tengchong", "level": 3, "area_code": 875, "post_code": 679100, "pid": 530500, "id": 2709, "area_id": 530522 }, { "area_name": "龙陵县", "pinyin": "Longling", "level": 3, "area_code": 875, "post_code": 678300, "pid": 530500, "id": 2710, "area_id": 530523 }, { "area_name": "昌宁县", "pinyin": "Changning", "level": 3, "area_code": 875, "post_code": 678100, "pid": 530500, "id": 2711, "area_id": 530524 }, { "area_name": "昭通市", "pinyin": "Zhaotong", "level": 2, "area_code": 870, "post_code": 657000, "pid": 530000, "id": 2712, "area_id": 530600 }, { "area_name": "昭阳区", "pinyin": "Zhaoyang", "level": 3, "area_code": 870, "post_code": 657000, "pid": 530600, "id": 2713, "area_id": 530602 }, { "area_name": "鲁甸县", "pinyin": "Ludian", "level": 3, "area_code": 870, "post_code": 657100, "pid": 530600, "id": 2714, "area_id": 530621 }, { "area_name": "巧家县", "pinyin": "Qiaojia", "level": 3, "area_code": 870, "post_code": 654600, "pid": 530600, "id": 2715, "area_id": 530622 }, { "area_name": "盐津县", "pinyin": "Yanjin", "level": 3, "area_code": 870, "post_code": 657500, "pid": 530600, "id": 2716, "area_id": 530623 }, { "area_name": "大关县", "pinyin": "Daguan", "level": 3, "area_code": 870, "post_code": 657400, "pid": 530600, "id": 2717, "area_id": 530624 }, { "area_name": "永善县", "pinyin": "Yongshan", "level": 3, "area_code": 870, "post_code": 657300, "pid": 530600, "id": 2718, "area_id": 530625 }, { "area_name": "绥江县", "pinyin": "Suijiang", "level": 3, "area_code": 870, "post_code": 657700, "pid": 530600, "id": 2719, "area_id": 530626 }, { "area_name": "镇雄县", "pinyin": "Zhenxiong", "level": 3, "area_code": 870, "post_code": 657200, "pid": 530600, "id": 2720, "area_id": 530627 }, { "area_name": "彝良县", "pinyin": "Yiliang", "level": 3, "area_code": 870, "post_code": 657600, "pid": 530600, "id": 2721, "area_id": 530628 }, { "area_name": "威信县", "pinyin": "Weixin", "level": 3, "area_code": 870, "post_code": 657900, "pid": 530600, "id": 2722, "area_id": 530629 }, { "area_name": "水富县", "pinyin": "Shuifu", "level": 3, "area_code": 870, "post_code": 657800, "pid": 530600, "id": 2723, "area_id": 530630 }, { "area_name": "丽江市", "pinyin": "Lijiang", "level": 2, "area_code": 888, "post_code": 674100, "pid": 530000, "id": 2724, "area_id": 530700 }, { "area_name": "古城区", "pinyin": "Gucheng", "level": 3, "area_code": 888, "post_code": 674100, "pid": 530700, "id": 2725, "area_id": 530702 }, { "area_name": "玉龙纳西族自治县", "pinyin": "Yulong", "level": 3, "area_code": 888, "post_code": 674100, "pid": 530700, "id": 2726, "area_id": 530721 }, { "area_name": "永胜县", "pinyin": "Yongsheng", "level": 3, "area_code": 888, "post_code": 674200, "pid": 530700, "id": 2727, "area_id": 530722 }, { "area_name": "华坪县", "pinyin": "Huaping", "level": 3, "area_code": 888, "post_code": 674800, "pid": 530700, "id": 2728, "area_id": 530723 }, { "area_name": "宁蒗彝族自治县", "pinyin": "Ninglang", "level": 3, "area_code": 888, "post_code": 674300, "pid": 530700, "id": 2729, "area_id": 530724 }, { "area_name": "普洱市", "pinyin": "Pu'er", "level": 2, "area_code": 879, "post_code": 665000, "pid": 530000, "id": 2730, "area_id": 530800 }, { "area_name": "思茅区", "pinyin": "Simao", "level": 3, "area_code": 879, "post_code": 665000, "pid": 530800, "id": 2731, "area_id": 530802 }, { "area_name": "宁洱哈尼族彝族自治县", "pinyin": "Ninger", "level": 3, "area_code": 879, "post_code": 665100, "pid": 530800, "id": 2732, "area_id": 530821 }, { "area_name": "墨江哈尼族自治县", "pinyin": "Mojiang", "level": 3, "area_code": 879, "post_code": 654800, "pid": 530800, "id": 2733, "area_id": 530822 }, { "area_name": "景东彝族自治县", "pinyin": "Jingdong", "level": 3, "area_code": 879, "post_code": 676200, "pid": 530800, "id": 2734, "area_id": 530823 }, { "area_name": "景谷傣族彝族自治县", "pinyin": "Jinggu", "level": 3, "area_code": 879, "post_code": 666400, "pid": 530800, "id": 2735, "area_id": 530824 }, { "area_name": "镇沅彝族哈尼族拉祜族自治县", "pinyin": "Zhenyuan", "level": 3, "area_code": 879, "post_code": 666500, "pid": 530800, "id": 2736, "area_id": 530825 }, { "area_name": "江城哈尼族彝族自治县", "pinyin": "Jiangcheng", "level": 3, "area_code": 879, "post_code": 665900, "pid": 530800, "id": 2737, "area_id": 530826 }, { "area_name": "孟连傣族拉祜族佤族自治县", "pinyin": "Menglian", "level": 3, "area_code": 879, "post_code": 665800, "pid": 530800, "id": 2738, "area_id": 530827 }, { "area_name": "澜沧拉祜族自治县", "pinyin": "Lancang", "level": 3, "area_code": 879, "post_code": 665600, "pid": 530800, "id": 2739, "area_id": 530828 }, { "area_name": "西盟佤族自治县", "pinyin": "Ximeng", "level": 3, "area_code": 879, "post_code": 665700, "pid": 530800, "id": 2740, "area_id": 530829 }, { "area_name": "临沧市", "pinyin": "Lincang", "level": 2, "area_code": 883, "post_code": 677000, "pid": 530000, "id": 2741, "area_id": 530900 }, { "area_name": "临翔区", "pinyin": "Linxiang", "level": 3, "area_code": 883, "post_code": 677000, "pid": 530900, "id": 2742, "area_id": 530902 }, { "area_name": "凤庆县", "pinyin": "Fengqing", "level": 3, "area_code": 883, "post_code": 675900, "pid": 530900, "id": 2743, "area_id": 530921 }, { "area_name": "云县", "pinyin": "Yunxian", "level": 3, "area_code": 883, "post_code": 675800, "pid": 530900, "id": 2744, "area_id": 530922 }, { "area_name": "永德县", "pinyin": "Yongde", "level": 3, "area_code": 883, "post_code": 677600, "pid": 530900, "id": 2745, "area_id": 530923 }, { "area_name": "镇康县", "pinyin": "Zhenkang", "level": 3, "area_code": 883, "post_code": 677704, "pid": 530900, "id": 2746, "area_id": 530924 }, { "area_name": "双江拉祜族佤族布朗族傣族自治县", "pinyin": "Shuangjiang", "level": 3, "area_code": 883, "post_code": 677300, "pid": 530900, "id": 2747, "area_id": 530925 }, { "area_name": "耿马傣族佤族自治县", "pinyin": "Gengma", "level": 3, "area_code": 883, "post_code": 677500, "pid": 530900, "id": 2748, "area_id": 530926 }, { "area_name": "沧源佤族自治县", "pinyin": "Cangyuan", "level": 3, "area_code": 883, "post_code": 677400, "pid": 530900, "id": 2749, "area_id": 530927 }, { "area_name": "楚雄彝族自治州", "pinyin": "Chuxiong", "level": 2, "area_code": 878, "post_code": 675000, "pid": 530000, "id": 2750, "area_id": 532300 }, { "area_name": "楚雄市", "pinyin": "Chuxiong", "level": 3, "area_code": 878, "post_code": 675000, "pid": 532300, "id": 2751, "area_id": 532301 }, { "area_name": "双柏县", "pinyin": "Shuangbai", "level": 3, "area_code": 878, "post_code": 675100, "pid": 532300, "id": 2752, "area_id": 532322 }, { "area_name": "牟定县", "pinyin": "Mouding", "level": 3, "area_code": 878, "post_code": 675500, "pid": 532300, "id": 2753, "area_id": 532323 }, { "area_name": "南华县", "pinyin": "Nanhua", "level": 3, "area_code": 878, "post_code": 675200, "pid": 532300, "id": 2754, "area_id": 532324 }, { "area_name": "姚安县", "pinyin": "Yao'an", "level": 3, "area_code": 878, "post_code": 675300, "pid": 532300, "id": 2755, "area_id": 532325 }, { "area_name": "大姚县", "pinyin": "Dayao", "level": 3, "area_code": 878, "post_code": 675400, "pid": 532300, "id": 2756, "area_id": 532326 }, { "area_name": "永仁县", "pinyin": "Yongren", "level": 3, "area_code": 878, "post_code": 651400, "pid": 532300, "id": 2757, "area_id": 532327 }, { "area_name": "元谋县", "pinyin": "Yuanmou", "level": 3, "area_code": 878, "post_code": 651300, "pid": 532300, "id": 2758, "area_id": 532328 }, { "area_name": "武定县", "pinyin": "Wuding", "level": 3, "area_code": 878, "post_code": 651600, "pid": 532300, "id": 2759, "area_id": 532329 }, { "area_name": "禄丰县", "pinyin": "Lufeng", "level": 3, "area_code": 878, "post_code": 651200, "pid": 532300, "id": 2760, "area_id": 532331 }, { "area_name": "红河哈尼族彝族自治州", "pinyin": "Honghe", "level": 2, "area_code": 873, "post_code": 661400, "pid": 530000, "id": 2761, "area_id": 532500 }, { "area_name": "个旧市", "pinyin": "Gejiu", "level": 3, "area_code": 873, "post_code": 661000, "pid": 532500, "id": 2762, "area_id": 532501 }, { "area_name": "开远市", "pinyin": "Kaiyuan", "level": 3, "area_code": 873, "post_code": 661600, "pid": 532500, "id": 2763, "area_id": 532502 }, { "area_name": "蒙自市", "pinyin": "Mengzi", "level": 3, "area_code": 873, "post_code": 661101, "pid": 532500, "id": 2764, "area_id": 532503 }, { "area_name": "弥勒市", "pinyin": "Mile ", "level": 3, "area_code": 873, "post_code": 652300, "pid": 532500, "id": 2765, "area_id": 532504 }, { "area_name": "屏边苗族自治县", "pinyin": "Pingbian", "level": 3, "area_code": 873, "post_code": 661200, "pid": 532500, "id": 2766, "area_id": 532523 }, { "area_name": "建水县", "pinyin": "Jianshui", "level": 3, "area_code": 873, "post_code": 654300, "pid": 532500, "id": 2767, "area_id": 532524 }, { "area_name": "石屏县", "pinyin": "Shiping", "level": 3, "area_code": 873, "post_code": 662200, "pid": 532500, "id": 2768, "area_id": 532525 }, { "area_name": "泸西县", "pinyin": "Luxi", "level": 3, "area_code": 873, "post_code": 652400, "pid": 532500, "id": 2769, "area_id": 532527 }, { "area_name": "元阳县", "pinyin": "Yuanyang", "level": 3, "area_code": 873, "post_code": 662400, "pid": 532500, "id": 2770, "area_id": 532528 }, { "area_name": "红河县", "pinyin": "Honghexian", "level": 3, "area_code": 873, "post_code": 654400, "pid": 532500, "id": 2771, "area_id": 532529 }, { "area_name": "金平苗族瑶族傣族自治县", "pinyin": "Jinping", "level": 3, "area_code": 873, "post_code": 661500, "pid": 532500, "id": 2772, "area_id": 532530 }, { "area_name": "绿春县", "pinyin": "Lvchun", "level": 3, "area_code": 873, "post_code": 662500, "pid": 532500, "id": 2773, "area_id": 532531 }, { "area_name": "河口瑶族自治县", "pinyin": "Hekou", "level": 3, "area_code": 873, "post_code": 661300, "pid": 532500, "id": 2774, "area_id": 532532 }, { "area_name": "文山壮族苗族自治州", "pinyin": "Wenshan", "level": 2, "area_code": 876, "post_code": 663000, "pid": 530000, "id": 2775, "area_id": 532600 }, { "area_name": "文山市", "pinyin": "Wenshan", "level": 3, "area_code": 876, "post_code": 663000, "pid": 532600, "id": 2776, "area_id": 532601 }, { "area_name": "砚山县", "pinyin": "Yanshan", "level": 3, "area_code": 876, "post_code": 663100, "pid": 532600, "id": 2777, "area_id": 532622 }, { "area_name": "西畴县", "pinyin": "Xichou", "level": 3, "area_code": 876, "post_code": 663500, "pid": 532600, "id": 2778, "area_id": 532623 }, { "area_name": "麻栗坡县", "pinyin": "Malipo", "level": 3, "area_code": 876, "post_code": 663600, "pid": 532600, "id": 2779, "area_id": 532624 }, { "area_name": "马关县", "pinyin": "Maguan", "level": 3, "area_code": 876, "post_code": 663700, "pid": 532600, "id": 2780, "area_id": 532625 }, { "area_name": "丘北县", "pinyin": "Qiubei", "level": 3, "area_code": 876, "post_code": 663200, "pid": 532600, "id": 2781, "area_id": 532626 }, { "area_name": "广南县", "pinyin": "Guangnan", "level": 3, "area_code": 876, "post_code": 663300, "pid": 532600, "id": 2782, "area_id": 532627 }, { "area_name": "富宁县", "pinyin": "Funing", "level": 3, "area_code": 876, "post_code": 663400, "pid": 532600, "id": 2783, "area_id": 532628 }, { "area_name": "西双版纳傣族自治州", "pinyin": "Xishuangbanna", "level": 2, "area_code": 691, "post_code": 666100, "pid": 530000, "id": 2784, "area_id": 532800 }, { "area_name": "景洪市", "pinyin": "Jinghong", "level": 3, "area_code": 691, "post_code": 666100, "pid": 532800, "id": 2785, "area_id": 532801 }, { "area_name": "勐海县", "pinyin": "Menghai", "level": 3, "area_code": 691, "post_code": 666200, "pid": 532800, "id": 2786, "area_id": 532822 }, { "area_name": "勐腊县", "pinyin": "Mengla", "level": 3, "area_code": 691, "post_code": 666300, "pid": 532800, "id": 2787, "area_id": 532823 }, { "area_name": "大理白族自治州", "pinyin": "Dali", "level": 2, "area_code": 872, "post_code": 671000, "pid": 530000, "id": 2788, "area_id": 532900 }, { "area_name": "大理市", "pinyin": "Dali", "level": 3, "area_code": 872, "post_code": 671000, "pid": 532900, "id": 2789, "area_id": 532901 }, { "area_name": "漾濞彝族自治县", "pinyin": "Yangbi", "level": 3, "area_code": 872, "post_code": 672500, "pid": 532900, "id": 2790, "area_id": 532922 }, { "area_name": "祥云县", "pinyin": "Xiangyun", "level": 3, "area_code": 872, "post_code": 672100, "pid": 532900, "id": 2791, "area_id": 532923 }, { "area_name": "宾川县", "pinyin": "Binchuan", "level": 3, "area_code": 872, "post_code": 671600, "pid": 532900, "id": 2792, "area_id": 532924 }, { "area_name": "弥渡县", "pinyin": "Midu", "level": 3, "area_code": 872, "post_code": 675600, "pid": 532900, "id": 2793, "area_id": 532925 }, { "area_name": "南涧彝族自治县", "pinyin": "Nanjian", "level": 3, "area_code": 872, "post_code": 675700, "pid": 532900, "id": 2794, "area_id": 532926 }, { "area_name": "巍山彝族回族自治县", "pinyin": "Weishan", "level": 3, "area_code": 872, "post_code": 672400, "pid": 532900, "id": 2795, "area_id": 532927 }, { "area_name": "永平县", "pinyin": "Yongping", "level": 3, "area_code": 872, "post_code": 672600, "pid": 532900, "id": 2796, "area_id": 532928 }, { "area_name": "云龙县", "pinyin": "Yunlong", "level": 3, "area_code": 872, "post_code": 672700, "pid": 532900, "id": 2797, "area_id": 532929 }, { "area_name": "洱源县", "pinyin": "Eryuan", "level": 3, "area_code": 872, "post_code": 671200, "pid": 532900, "id": 2798, "area_id": 532930 }, { "area_name": "剑川县", "pinyin": "Jianchuan", "level": 3, "area_code": 872, "post_code": 671300, "pid": 532900, "id": 2799, "area_id": 532931 }, { "area_name": "鹤庆县", "pinyin": "Heqing", "level": 3, "area_code": 872, "post_code": 671500, "pid": 532900, "id": 2800, "area_id": 532932 }, { "area_name": "德宏傣族景颇族自治州", "pinyin": "Dehong", "level": 2, "area_code": 692, "post_code": 678400, "pid": 530000, "id": 2801, "area_id": 533100 }, { "area_name": "瑞丽市", "pinyin": "Ruili", "level": 3, "area_code": 692, "post_code": 678600, "pid": 533100, "id": 2802, "area_id": 533102 }, { "area_name": "芒市", "pinyin": "Mangshi", "level": 3, "area_code": 692, "post_code": 678400, "pid": 533100, "id": 2803, "area_id": 533103 }, { "area_name": "梁河县", "pinyin": "Lianghe", "level": 3, "area_code": 692, "post_code": 679200, "pid": 533100, "id": 2804, "area_id": 533122 }, { "area_name": "盈江县", "pinyin": "Yingjiang", "level": 3, "area_code": 692, "post_code": 679300, "pid": 533100, "id": 2805, "area_id": 533123 }, { "area_name": "陇川县", "pinyin": "Longchuan", "level": 3, "area_code": 692, "post_code": 678700, "pid": 533100, "id": 2806, "area_id": 533124 }, { "area_name": "怒江傈僳族自治州", "pinyin": "Nujiang", "level": 2, "area_code": 886, "post_code": 673100, "pid": 530000, "id": 2807, "area_id": 533300 }, { "area_name": "泸水县", "pinyin": "Lushui", "level": 3, "area_code": 886, "post_code": 673100, "pid": 533300, "id": 2808, "area_id": 533321 }, { "area_name": "福贡县", "pinyin": "Fugong", "level": 3, "area_code": 886, "post_code": 673400, "pid": 533300, "id": 2809, "area_id": 533323 }, { "area_name": "贡山独龙族怒族自治县", "pinyin": "Gongshan", "level": 3, "area_code": 886, "post_code": 673500, "pid": 533300, "id": 2810, "area_id": 533324 }, { "area_name": "兰坪白族普米族自治县", "pinyin": "Lanping", "level": 3, "area_code": 886, "post_code": 671400, "pid": 533300, "id": 2811, "area_id": 533325 }, { "area_name": "迪庆藏族自治州", "pinyin": "Deqen", "level": 2, "area_code": 887, "post_code": 674400, "pid": 530000, "id": 2812, "area_id": 533400 }, { "area_name": "香格里拉市", "pinyin": "Xianggelila", "level": 3, "area_code": 887, "post_code": 674400, "pid": 533400, "id": 2813, "area_id": 533421 }, { "area_name": "德钦县", "pinyin": "Deqin", "level": 3, "area_code": 887, "post_code": 674500, "pid": 533400, "id": 2814, "area_id": 533422 }, { "area_name": "维西傈僳族自治县", "pinyin": "Weixi", "level": 3, "area_code": 887, "post_code": 674600, "pid": 533400, "id": 2815, "area_id": 533423 }, { "area_name": "西藏自治区", "pinyin": "Tibet", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2816, "area_id": 540000 }, { "area_name": "拉萨市", "pinyin": "Lhasa", "level": 2, "area_code": 891, "post_code": 850000, "pid": 540000, "id": 2817, "area_id": 540100 }, { "area_name": "城关区", "pinyin": "Chengguan", "level": 3, "area_code": 891, "post_code": 850000, "pid": 540100, "id": 2818, "area_id": 540102 }, { "area_name": "林周县", "pinyin": "Linzhou", "level": 3, "area_code": 891, "post_code": 851600, "pid": 540100, "id": 2819, "area_id": 540121 }, { "area_name": "当雄县", "pinyin": "Dangxiong", "level": 3, "area_code": 891, "post_code": 851500, "pid": 540100, "id": 2820, "area_id": 540122 }, { "area_name": "尼木县", "pinyin": "Nimu", "level": 3, "area_code": 891, "post_code": 851300, "pid": 540100, "id": 2821, "area_id": 540123 }, { "area_name": "曲水县", "pinyin": "Qushui", "level": 3, "area_code": 891, "post_code": 850600, "pid": 540100, "id": 2822, "area_id": 540124 }, { "area_name": "堆龙德庆县", "pinyin": "Duilongdeqing", "level": 3, "area_code": 891, "post_code": 851400, "pid": 540100, "id": 2823, "area_id": 540125 }, { "area_name": "达孜县", "pinyin": "Dazi", "level": 3, "area_code": 891, "post_code": 850100, "pid": 540100, "id": 2824, "area_id": 540126 }, { "area_name": "墨竹工卡县", "pinyin": "Mozhugongka", "level": 3, "area_code": 891, "post_code": 850200, "pid": 540100, "id": 2825, "area_id": 540127 }, { "area_name": "日喀则市", "pinyin": "Rikaze", "level": 2, "area_code": 892, "post_code": 857000, "pid": 540000, "id": 2826, "area_id": 540200 }, { "area_name": "桑珠孜区", "pinyin": "Sangzhuzi", "level": 3, "area_code": 892, "post_code": 857000, "pid": 540200, "id": 2827, "area_id": 540202 }, { "area_name": "南木林县", "pinyin": "Nanmulin", "level": 3, "area_code": 892, "post_code": 857100, "pid": 540200, "id": 2828, "area_id": 540221 }, { "area_name": "江孜县", "pinyin": "Jiangzi", "level": 3, "area_code": 892, "post_code": 857400, "pid": 540200, "id": 2829, "area_id": 540222 }, { "area_name": "定日县", "pinyin": "Dingri", "level": 3, "area_code": 892, "post_code": 858200, "pid": 540200, "id": 2830, "area_id": 540223 }, { "area_name": "萨迦县", "pinyin": "Sajia", "level": 3, "area_code": 892, "post_code": 857800, "pid": 540200, "id": 2831, "area_id": 540224 }, { "area_name": "拉孜县", "pinyin": "Lazi", "level": 3, "area_code": 892, "post_code": 858100, "pid": 540200, "id": 2832, "area_id": 540225 }, { "area_name": "昂仁县", "pinyin": "Angren", "level": 3, "area_code": 892, "post_code": 858500, "pid": 540200, "id": 2833, "area_id": 540226 }, { "area_name": "谢通门县", "pinyin": "Xietongmen", "level": 3, "area_code": 892, "post_code": 858900, "pid": 540200, "id": 2834, "area_id": 540227 }, { "area_name": "白朗县", "pinyin": "Bailang", "level": 3, "area_code": 892, "post_code": 857300, "pid": 540200, "id": 2835, "area_id": 540228 }, { "area_name": "仁布县", "pinyin": "Renbu", "level": 3, "area_code": 892, "post_code": 857200, "pid": 540200, "id": 2836, "area_id": 540229 }, { "area_name": "康马县", "pinyin": "Kangma", "level": 3, "area_code": 892, "post_code": 857500, "pid": 540200, "id": 2837, "area_id": 540230 }, { "area_name": "定结县", "pinyin": "Dingjie", "level": 3, "area_code": 892, "post_code": 857900, "pid": 540200, "id": 2838, "area_id": 540231 }, { "area_name": "仲巴县", "pinyin": "Zhongba", "level": 3, "area_code": 892, "post_code": 858800, "pid": 540200, "id": 2839, "area_id": 540232 }, { "area_name": "亚东县", "pinyin": "Yadong", "level": 3, "area_code": 892, "post_code": 857600, "pid": 540200, "id": 2840, "area_id": 540233 }, { "area_name": "吉隆县", "pinyin": "Jilong", "level": 3, "area_code": 892, "post_code": 858700, "pid": 540200, "id": 2841, "area_id": 540234 }, { "area_name": "聂拉木县", "pinyin": "Nielamu", "level": 3, "area_code": 892, "post_code": 858300, "pid": 540200, "id": 2842, "area_id": 540235 }, { "area_name": "萨嘎县", "pinyin": "Saga", "level": 3, "area_code": 892, "post_code": 857800, "pid": 540200, "id": 2843, "area_id": 540236 }, { "area_name": "岗巴县", "pinyin": "Gangba", "level": 3, "area_code": 892, "post_code": 857700, "pid": 540200, "id": 2844, "area_id": 540237 }, { "area_name": "昌都市", "pinyin": "Qamdo", "level": 2, "area_code": 895, "post_code": 854000, "pid": 540000, "id": 2845, "area_id": 540300 }, { "area_name": "卡若区", "pinyin": "Karuo", "level": 3, "area_code": 895, "post_code": 854000, "pid": 540300, "id": 2846, "area_id": 540302 }, { "area_name": "江达县", "pinyin": "Jiangda", "level": 3, "area_code": 895, "post_code": 854100, "pid": 540300, "id": 2847, "area_id": 540321 }, { "area_name": "贡觉县", "pinyin": "Gongjue", "level": 3, "area_code": 895, "post_code": 854200, "pid": 540300, "id": 2848, "area_id": 540322 }, { "area_name": "类乌齐县", "pinyin": "Leiwuqi", "level": 3, "area_code": 895, "post_code": 855600, "pid": 540300, "id": 2849, "area_id": 540323 }, { "area_name": "丁青县", "pinyin": "Dingqing", "level": 3, "area_code": 895, "post_code": 855700, "pid": 540300, "id": 2850, "area_id": 540324 }, { "area_name": "察雅县", "pinyin": "Chaya", "level": 3, "area_code": 895, "post_code": 854300, "pid": 540300, "id": 2851, "area_id": 540325 }, { "area_name": "八宿县", "pinyin": "Basu", "level": 3, "area_code": 895, "post_code": 854600, "pid": 540300, "id": 2852, "area_id": 540326 }, { "area_name": "左贡县", "pinyin": "Zuogong", "level": 3, "area_code": 895, "post_code": 854400, "pid": 540300, "id": 2853, "area_id": 540327 }, { "area_name": "芒康县", "pinyin": "Mangkang", "level": 3, "area_code": 895, "post_code": 854500, "pid": 540300, "id": 2854, "area_id": 540328 }, { "area_name": "洛隆县", "pinyin": "Luolong", "level": 3, "area_code": 895, "post_code": 855400, "pid": 540300, "id": 2855, "area_id": 540329 }, { "area_name": "边坝县", "pinyin": "Bianba", "level": 3, "area_code": 895, "post_code": 855500, "pid": 540300, "id": 2856, "area_id": 540330 }, { "area_name": "山南地区", "pinyin": "Shannan", "level": 2, "area_code": 893, "post_code": 856000, "pid": 540000, "id": 2857, "area_id": 542200 }, { "area_name": "乃东县", "pinyin": "Naidong", "level": 3, "area_code": 893, "post_code": 856100, "pid": 542200, "id": 2858, "area_id": 542221 }, { "area_name": "扎囊县", "pinyin": "Zhanang", "level": 3, "area_code": 893, "post_code": 850800, "pid": 542200, "id": 2859, "area_id": 542222 }, { "area_name": "贡嘎县", "pinyin": "Gongga", "level": 3, "area_code": 893, "post_code": 850700, "pid": 542200, "id": 2860, "area_id": 542223 }, { "area_name": "桑日县", "pinyin": "Sangri", "level": 3, "area_code": 893, "post_code": 856200, "pid": 542200, "id": 2861, "area_id": 542224 }, { "area_name": "琼结县", "pinyin": "Qiongjie", "level": 3, "area_code": 893, "post_code": 856800, "pid": 542200, "id": 2862, "area_id": 542225 }, { "area_name": "曲松县", "pinyin": "Qusong", "level": 3, "area_code": 893, "post_code": 856300, "pid": 542200, "id": 2863, "area_id": 542226 }, { "area_name": "措美县", "pinyin": "Cuomei", "level": 3, "area_code": 893, "post_code": 856900, "pid": 542200, "id": 2864, "area_id": 542227 }, { "area_name": "洛扎县", "pinyin": "Luozha", "level": 3, "area_code": 893, "post_code": 856600, "pid": 542200, "id": 2865, "area_id": 542228 }, { "area_name": "加查县", "pinyin": "Jiacha", "level": 3, "area_code": 893, "post_code": 856400, "pid": 542200, "id": 2866, "area_id": 542229 }, { "area_name": "隆子县", "pinyin": "Longzi", "level": 3, "area_code": 893, "post_code": 856600, "pid": 542200, "id": 2867, "area_id": 542231 }, { "area_name": "错那县", "pinyin": "Cuona", "level": 3, "area_code": 893, "post_code": 856700, "pid": 542200, "id": 2868, "area_id": 542232 }, { "area_name": "浪卡子县", "pinyin": "Langkazi", "level": 3, "area_code": 893, "post_code": 851100, "pid": 542200, "id": 2869, "area_id": 542233 }, { "area_name": "那曲地区", "pinyin": "Nagqu", "level": 2, "area_code": 896, "post_code": 852000, "pid": 540000, "id": 2870, "area_id": 542400 }, { "area_name": "那曲县", "pinyin": "Naqu", "level": 3, "area_code": 896, "post_code": 852000, "pid": 542400, "id": 2871, "area_id": 542421 }, { "area_name": "嘉黎县", "pinyin": "Jiali", "level": 3, "area_code": 896, "post_code": 852400, "pid": 542400, "id": 2872, "area_id": 542422 }, { "area_name": "比如县", "pinyin": "Biru", "level": 3, "area_code": 896, "post_code": 852300, "pid": 542400, "id": 2873, "area_id": 542423 }, { "area_name": "聂荣县", "pinyin": "Nierong", "level": 3, "area_code": 896, "post_code": 853500, "pid": 542400, "id": 2874, "area_id": 542424 }, { "area_name": "安多县", "pinyin": "Anduo", "level": 3, "area_code": 896, "post_code": 853400, "pid": 542400, "id": 2875, "area_id": 542425 }, { "area_name": "申扎县", "pinyin": "Shenzha", "level": 3, "area_code": 896, "post_code": 853100, "pid": 542400, "id": 2876, "area_id": 542426 }, { "area_name": "索县", "pinyin": "Suoxian", "level": 3, "area_code": 896, "post_code": 852200, "pid": 542400, "id": 2877, "area_id": 542427 }, { "area_name": "班戈县", "pinyin": "Bange", "level": 3, "area_code": 896, "post_code": 852500, "pid": 542400, "id": 2878, "area_id": 542428 }, { "area_name": "巴青县", "pinyin": "Baqing", "level": 3, "area_code": 896, "post_code": 852100, "pid": 542400, "id": 2879, "area_id": 542429 }, { "area_name": "尼玛县", "pinyin": "Nima", "level": 3, "area_code": 896, "post_code": 852600, "pid": 542400, "id": 2880, "area_id": 542430 }, { "area_name": "双湖县", "pinyin": "Shuanghu", "level": 3, "area_code": 896, "post_code": 852600, "pid": 542400, "id": 2881, "area_id": 542431 }, { "area_name": "阿里地区", "pinyin": "Ngari", "level": 2, "area_code": 897, "post_code": 859000, "pid": 540000, "id": 2882, "area_id": 542500 }, { "area_name": "普兰县", "pinyin": "Pulan", "level": 3, "area_code": 897, "post_code": 859500, "pid": 542500, "id": 2883, "area_id": 542521 }, { "area_name": "札达县", "pinyin": "Zhada", "level": 3, "area_code": 897, "post_code": 859600, "pid": 542500, "id": 2884, "area_id": 542522 }, { "area_name": "噶尔县", "pinyin": "Gaer", "level": 3, "area_code": 897, "post_code": 859400, "pid": 542500, "id": 2885, "area_id": 542523 }, { "area_name": "日土县", "pinyin": "Ritu", "level": 3, "area_code": 897, "post_code": 859700, "pid": 542500, "id": 2886, "area_id": 542524 }, { "area_name": "革吉县", "pinyin": "Geji", "level": 3, "area_code": 897, "post_code": 859100, "pid": 542500, "id": 2887, "area_id": 542525 }, { "area_name": "改则县", "pinyin": "Gaize", "level": 3, "area_code": 897, "post_code": 859200, "pid": 542500, "id": 2888, "area_id": 542526 }, { "area_name": "措勤县", "pinyin": "Cuoqin", "level": 3, "area_code": 897, "post_code": 859300, "pid": 542500, "id": 2889, "area_id": 542527 }, { "area_name": "林芝地区", "pinyin": "Nyingchi", "level": 2, "area_code": 894, "post_code": 850400, "pid": 540000, "id": 2890, "area_id": 542600 }, { "area_name": "林芝县", "pinyin": "Linzhi", "level": 3, "area_code": 894, "post_code": 850400, "pid": 542600, "id": 2891, "area_id": 542621 }, { "area_name": "工布江达县", "pinyin": "Gongbujiangda", "level": 3, "area_code": 894, "post_code": 850300, "pid": 542600, "id": 2892, "area_id": 542622 }, { "area_name": "米林县", "pinyin": "Milin", "level": 3, "area_code": 894, "post_code": 850500, "pid": 542600, "id": 2893, "area_id": 542623 }, { "area_name": "墨脱县", "pinyin": "Motuo", "level": 3, "area_code": 894, "post_code": 855300, "pid": 542600, "id": 2894, "area_id": 542624 }, { "area_name": "波密县", "pinyin": "Bomi", "level": 3, "area_code": 894, "post_code": 855200, "pid": 542600, "id": 2895, "area_id": 542625 }, { "area_name": "察隅县", "pinyin": "Chayu", "level": 3, "area_code": 894, "post_code": 855100, "pid": 542600, "id": 2896, "area_id": 542626 }, { "area_name": "朗县", "pinyin": "Langxian", "level": 3, "area_code": 894, "post_code": 856500, "pid": 542600, "id": 2897, "area_id": 542627 }, { "area_name": "陕西省", "pinyin": "Shaanxi", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 2898, "area_id": 610000 }, { "area_name": "西安市", "pinyin": "Xi'an", "level": 2, "area_code": 29, "post_code": 710003, "pid": 610000, "id": 2899, "area_id": 610100 }, { "area_name": "新城区", "pinyin": "Xincheng", "level": 3, "area_code": 29, "post_code": 710004, "pid": 610100, "id": 2900, "area_id": 610102 }, { "area_name": "碑林区", "pinyin": "Beilin", "level": 3, "area_code": 29, "post_code": 710001, "pid": 610100, "id": 2901, "area_id": 610103 }, { "area_name": "莲湖区", "pinyin": "Lianhu", "level": 3, "area_code": 29, "post_code": 710003, "pid": 610100, "id": 2902, "area_id": 610104 }, { "area_name": "灞桥区", "pinyin": "Baqiao", "level": 3, "area_code": 29, "post_code": 710038, "pid": 610100, "id": 2903, "area_id": 610111 }, { "area_name": "未央区", "pinyin": "Weiyang", "level": 3, "area_code": 29, "post_code": 710014, "pid": 610100, "id": 2904, "area_id": 610112 }, { "area_name": "雁塔区", "pinyin": "Yanta", "level": 3, "area_code": 29, "post_code": 710061, "pid": 610100, "id": 2905, "area_id": 610113 }, { "area_name": "阎良区", "pinyin": "Yanliang", "level": 3, "area_code": 29, "post_code": 710087, "pid": 610100, "id": 2906, "area_id": 610114 }, { "area_name": "临潼区", "pinyin": "Lintong", "level": 3, "area_code": 29, "post_code": 710600, "pid": 610100, "id": 2907, "area_id": 610115 }, { "area_name": "长安区", "pinyin": "Chang'an", "level": 3, "area_code": 29, "post_code": 710100, "pid": 610100, "id": 2908, "area_id": 610116 }, { "area_name": "蓝田县", "pinyin": "Lantian", "level": 3, "area_code": 29, "post_code": 710500, "pid": 610100, "id": 2909, "area_id": 610122 }, { "area_name": "周至县", "pinyin": "Zhouzhi", "level": 3, "area_code": 29, "post_code": 710400, "pid": 610100, "id": 2910, "area_id": 610124 }, { "area_name": "户县", "pinyin": "Huxian", "level": 3, "area_code": 29, "post_code": 710300, "pid": 610100, "id": 2911, "area_id": 610125 }, { "area_name": "高陵区", "pinyin": "Gaoling", "level": 3, "area_code": 29, "post_code": 710200, "pid": 610100, "id": 2912, "area_id": 610126 }, { "area_name": "铜川市", "pinyin": "Tongchuan", "level": 2, "area_code": 919, "post_code": 727100, "pid": 610000, "id": 2913, "area_id": 610200 }, { "area_name": "王益区", "pinyin": "Wangyi", "level": 3, "area_code": 919, "post_code": 727000, "pid": 610200, "id": 2914, "area_id": 610202 }, { "area_name": "印台区", "pinyin": "Yintai", "level": 3, "area_code": 919, "post_code": 727007, "pid": 610200, "id": 2915, "area_id": 610203 }, { "area_name": "耀州区", "pinyin": "Yaozhou", "level": 3, "area_code": 919, "post_code": 727100, "pid": 610200, "id": 2916, "area_id": 610204 }, { "area_name": "宜君县", "pinyin": "Yijun", "level": 3, "area_code": 919, "post_code": 727200, "pid": 610200, "id": 2917, "area_id": 610222 }, { "area_name": "宝鸡市", "pinyin": "Baoji", "level": 2, "area_code": 917, "post_code": 721000, "pid": 610000, "id": 2918, "area_id": 610300 }, { "area_name": "渭滨区", "pinyin": "Weibin", "level": 3, "area_code": 917, "post_code": 721000, "pid": 610300, "id": 2919, "area_id": 610302 }, { "area_name": "金台区", "pinyin": "Jintai", "level": 3, "area_code": 917, "post_code": 721000, "pid": 610300, "id": 2920, "area_id": 610303 }, { "area_name": "陈仓区", "pinyin": "Chencang", "level": 3, "area_code": 917, "post_code": 721300, "pid": 610300, "id": 2921, "area_id": 610304 }, { "area_name": "凤翔县", "pinyin": "Fengxiang", "level": 3, "area_code": 917, "post_code": 721400, "pid": 610300, "id": 2922, "area_id": 610322 }, { "area_name": "岐山县", "pinyin": "Qishan", "level": 3, "area_code": 917, "post_code": 722400, "pid": 610300, "id": 2923, "area_id": 610323 }, { "area_name": "扶风县", "pinyin": "Fufeng", "level": 3, "area_code": 917, "post_code": 722200, "pid": 610300, "id": 2924, "area_id": 610324 }, { "area_name": "眉县", "pinyin": "Meixian", "level": 3, "area_code": 917, "post_code": 722300, "pid": 610300, "id": 2925, "area_id": 610326 }, { "area_name": "陇县", "pinyin": "Longxian", "level": 3, "area_code": 917, "post_code": 721200, "pid": 610300, "id": 2926, "area_id": 610327 }, { "area_name": "千阳县", "pinyin": "Qianyang", "level": 3, "area_code": 917, "post_code": 721100, "pid": 610300, "id": 2927, "area_id": 610328 }, { "area_name": "麟游县", "pinyin": "Linyou", "level": 3, "area_code": 917, "post_code": 721500, "pid": 610300, "id": 2928, "area_id": 610329 }, { "area_name": "凤县", "pinyin": "Fengxian", "level": 3, "area_code": 917, "post_code": 721700, "pid": 610300, "id": 2929, "area_id": 610330 }, { "area_name": "太白县", "pinyin": "Taibai", "level": 3, "area_code": 917, "post_code": 721600, "pid": 610300, "id": 2930, "area_id": 610331 }, { "area_name": "咸阳市", "pinyin": "Xianyang", "level": 2, "area_code": 29, "post_code": 712000, "pid": 610000, "id": 2931, "area_id": 610400 }, { "area_name": "秦都区", "pinyin": "Qindu", "level": 3, "area_code": 29, "post_code": 712000, "pid": 610400, "id": 2932, "area_id": 610402 }, { "area_name": "杨陵区", "pinyin": "Yangling", "level": 3, "area_code": 29, "post_code": 712100, "pid": 610400, "id": 2933, "area_id": 610403 }, { "area_name": "渭城区", "pinyin": "Weicheng", "level": 3, "area_code": 29, "post_code": 712000, "pid": 610400, "id": 2934, "area_id": 610404 }, { "area_name": "三原县", "pinyin": "Sanyuan", "level": 3, "area_code": 29, "post_code": 713800, "pid": 610400, "id": 2935, "area_id": 610422 }, { "area_name": "泾阳县", "pinyin": "Jingyang", "level": 3, "area_code": 29, "post_code": 713700, "pid": 610400, "id": 2936, "area_id": 610423 }, { "area_name": "乾县", "pinyin": "Qianxian", "level": 3, "area_code": 29, "post_code": 713300, "pid": 610400, "id": 2937, "area_id": 610424 }, { "area_name": "礼泉县", "pinyin": "Liquan", "level": 3, "area_code": 29, "post_code": 713200, "pid": 610400, "id": 2938, "area_id": 610425 }, { "area_name": "永寿县", "pinyin": "Yongshou", "level": 3, "area_code": 29, "post_code": 713400, "pid": 610400, "id": 2939, "area_id": 610426 }, { "area_name": "彬县", "pinyin": "Binxian", "level": 3, "area_code": 29, "post_code": 713500, "pid": 610400, "id": 2940, "area_id": 610427 }, { "area_name": "长武县", "pinyin": "Changwu", "level": 3, "area_code": 29, "post_code": 713600, "pid": 610400, "id": 2941, "area_id": 610428 }, { "area_name": "旬邑县", "pinyin": "Xunyi", "level": 3, "area_code": 29, "post_code": 711300, "pid": 610400, "id": 2942, "area_id": 610429 }, { "area_name": "淳化县", "pinyin": "Chunhua", "level": 3, "area_code": 29, "post_code": 711200, "pid": 610400, "id": 2943, "area_id": 610430 }, { "area_name": "武功县", "pinyin": "Wugong", "level": 3, "area_code": 29, "post_code": 712200, "pid": 610400, "id": 2944, "area_id": 610431 }, { "area_name": "兴平市", "pinyin": "Xingping", "level": 3, "area_code": 29, "post_code": 713100, "pid": 610400, "id": 2945, "area_id": 610481 }, { "area_name": "渭南市", "pinyin": "Weinan", "level": 2, "area_code": 913, "post_code": 714000, "pid": 610000, "id": 2946, "area_id": 610500 }, { "area_name": "临渭区", "pinyin": "Linwei", "level": 3, "area_code": 913, "post_code": 714000, "pid": 610500, "id": 2947, "area_id": 610502 }, { "area_name": "华县", "pinyin": "Huaxian", "level": 3, "area_code": 913, "post_code": 714100, "pid": 610500, "id": 2948, "area_id": 610521 }, { "area_name": "潼关县", "pinyin": "Tongguan", "level": 3, "area_code": 913, "post_code": 714300, "pid": 610500, "id": 2949, "area_id": 610522 }, { "area_name": "大荔县", "pinyin": "Dali", "level": 3, "area_code": 913, "post_code": 715100, "pid": 610500, "id": 2950, "area_id": 610523 }, { "area_name": "合阳县", "pinyin": "Heyang", "level": 3, "area_code": 913, "post_code": 715300, "pid": 610500, "id": 2951, "area_id": 610524 }, { "area_name": "澄城县", "pinyin": "Chengcheng", "level": 3, "area_code": 913, "post_code": 715200, "pid": 610500, "id": 2952, "area_id": 610525 }, { "area_name": "蒲城县", "pinyin": "Pucheng", "level": 3, "area_code": 913, "post_code": 715500, "pid": 610500, "id": 2953, "area_id": 610526 }, { "area_name": "白水县", "pinyin": "Baishui", "level": 3, "area_code": 913, "post_code": 715600, "pid": 610500, "id": 2954, "area_id": 610527 }, { "area_name": "富平县", "pinyin": "Fuping", "level": 3, "area_code": 913, "post_code": 711700, "pid": 610500, "id": 2955, "area_id": 610528 }, { "area_name": "韩城市", "pinyin": "Hancheng", "level": 3, "area_code": 913, "post_code": 715400, "pid": 610500, "id": 2956, "area_id": 610581 }, { "area_name": "华阴市", "pinyin": "Huayin", "level": 3, "area_code": 913, "post_code": 714200, "pid": 610500, "id": 2957, "area_id": 610582 }, { "area_name": "延安市", "pinyin": "Yan'an", "level": 2, "area_code": 911, "post_code": 716000, "pid": 610000, "id": 2958, "area_id": 610600 }, { "area_name": "宝塔区", "pinyin": "Baota", "level": 3, "area_code": 911, "post_code": 716000, "pid": 610600, "id": 2959, "area_id": 610602 }, { "area_name": "延长县", "pinyin": "Yanchang", "level": 3, "area_code": 911, "post_code": 717100, "pid": 610600, "id": 2960, "area_id": 610621 }, { "area_name": "延川县", "pinyin": "Yanchuan", "level": 3, "area_code": 911, "post_code": 717200, "pid": 610600, "id": 2961, "area_id": 610622 }, { "area_name": "子长县", "pinyin": "Zichang", "level": 3, "area_code": 911, "post_code": 717300, "pid": 610600, "id": 2962, "area_id": 610623 }, { "area_name": "安塞县", "pinyin": "Ansai", "level": 3, "area_code": 911, "post_code": 717400, "pid": 610600, "id": 2963, "area_id": 610624 }, { "area_name": "志丹县", "pinyin": "Zhidan", "level": 3, "area_code": 911, "post_code": 717500, "pid": 610600, "id": 2964, "area_id": 610625 }, { "area_name": "吴起县", "pinyin": "Wuqi", "level": 3, "area_code": 911, "post_code": 717600, "pid": 610600, "id": 2965, "area_id": 610626 }, { "area_name": "甘泉县", "pinyin": "Ganquan", "level": 3, "area_code": 911, "post_code": 716100, "pid": 610600, "id": 2966, "area_id": 610627 }, { "area_name": "富县", "pinyin": "Fuxian", "level": 3, "area_code": 911, "post_code": 727500, "pid": 610600, "id": 2967, "area_id": 610628 }, { "area_name": "洛川县", "pinyin": "Luochuan", "level": 3, "area_code": 911, "post_code": 727400, "pid": 610600, "id": 2968, "area_id": 610629 }, { "area_name": "宜川县", "pinyin": "Yichuan", "level": 3, "area_code": 911, "post_code": 716200, "pid": 610600, "id": 2969, "area_id": 610630 }, { "area_name": "黄龙县", "pinyin": "Huanglong", "level": 3, "area_code": 911, "post_code": 715700, "pid": 610600, "id": 2970, "area_id": 610631 }, { "area_name": "黄陵县", "pinyin": "Huangling", "level": 3, "area_code": 911, "post_code": 727300, "pid": 610600, "id": 2971, "area_id": 610632 }, { "area_name": "汉中市", "pinyin": "Hanzhong", "level": 2, "area_code": 916, "post_code": 723000, "pid": 610000, "id": 2972, "area_id": 610700 }, { "area_name": "汉台区", "pinyin": "Hantai", "level": 3, "area_code": 916, "post_code": 723000, "pid": 610700, "id": 2973, "area_id": 610702 }, { "area_name": "南郑县", "pinyin": "Nanzheng", "level": 3, "area_code": 916, "post_code": 723100, "pid": 610700, "id": 2974, "area_id": 610721 }, { "area_name": "城固县", "pinyin": "Chenggu", "level": 3, "area_code": 916, "post_code": 723200, "pid": 610700, "id": 2975, "area_id": 610722 }, { "area_name": "洋县", "pinyin": "Yangxian", "level": 3, "area_code": 916, "post_code": 723300, "pid": 610700, "id": 2976, "area_id": 610723 }, { "area_name": "西乡县", "pinyin": "Xixiang", "level": 3, "area_code": 916, "post_code": 723500, "pid": 610700, "id": 2977, "area_id": 610724 }, { "area_name": "勉县", "pinyin": "Mianxian", "level": 3, "area_code": 916, "post_code": 724200, "pid": 610700, "id": 2978, "area_id": 610725 }, { "area_name": "宁强县", "pinyin": "Ningqiang", "level": 3, "area_code": 916, "post_code": 724400, "pid": 610700, "id": 2979, "area_id": 610726 }, { "area_name": "略阳县", "pinyin": "Lueyang", "level": 3, "area_code": 916, "post_code": 724300, "pid": 610700, "id": 2980, "area_id": 610727 }, { "area_name": "镇巴县", "pinyin": "Zhenba", "level": 3, "area_code": 916, "post_code": 723600, "pid": 610700, "id": 2981, "area_id": 610728 }, { "area_name": "留坝县", "pinyin": "Liuba", "level": 3, "area_code": 916, "post_code": 724100, "pid": 610700, "id": 2982, "area_id": 610729 }, { "area_name": "佛坪县", "pinyin": "Foping", "level": 3, "area_code": 916, "post_code": 723400, "pid": 610700, "id": 2983, "area_id": 610730 }, { "area_name": "榆林市", "pinyin": "Yulin", "level": 2, "area_code": 912, "post_code": 719000, "pid": 610000, "id": 2984, "area_id": 610800 }, { "area_name": "榆阳区", "pinyin": "Yuyang", "level": 3, "area_code": 912, "post_code": 719000, "pid": 610800, "id": 2985, "area_id": 610802 }, { "area_name": "神木县", "pinyin": "Shenmu", "level": 3, "area_code": 912, "post_code": 719300, "pid": 610800, "id": 2986, "area_id": 610821 }, { "area_name": "府谷县", "pinyin": "Fugu", "level": 3, "area_code": 912, "post_code": 719400, "pid": 610800, "id": 2987, "area_id": 610822 }, { "area_name": "横山县", "pinyin": "Hengshan", "level": 3, "area_code": 912, "post_code": 719100, "pid": 610800, "id": 2988, "area_id": 610823 }, { "area_name": "靖边县", "pinyin": "Jingbian", "level": 3, "area_code": 912, "post_code": 718500, "pid": 610800, "id": 2989, "area_id": 610824 }, { "area_name": "定边县", "pinyin": "Dingbian", "level": 3, "area_code": 912, "post_code": 718600, "pid": 610800, "id": 2990, "area_id": 610825 }, { "area_name": "绥德县", "pinyin": "Suide", "level": 3, "area_code": 912, "post_code": 718000, "pid": 610800, "id": 2991, "area_id": 610826 }, { "area_name": "米脂县", "pinyin": "Mizhi", "level": 3, "area_code": 912, "post_code": 718100, "pid": 610800, "id": 2992, "area_id": 610827 }, { "area_name": "佳县", "pinyin": "Jiaxian", "level": 3, "area_code": 912, "post_code": 719200, "pid": 610800, "id": 2993, "area_id": 610828 }, { "area_name": "吴堡县", "pinyin": "Wubu", "level": 3, "area_code": 912, "post_code": 718200, "pid": 610800, "id": 2994, "area_id": 610829 }, { "area_name": "清涧县", "pinyin": "Qingjian", "level": 3, "area_code": 912, "post_code": 718300, "pid": 610800, "id": 2995, "area_id": 610830 }, { "area_name": "子洲县", "pinyin": "Zizhou", "level": 3, "area_code": 912, "post_code": 718400, "pid": 610800, "id": 2996, "area_id": 610831 }, { "area_name": "安康市", "pinyin": "Ankang", "level": 2, "area_code": 915, "post_code": 725000, "pid": 610000, "id": 2997, "area_id": 610900 }, { "area_name": "汉滨区", "pinyin": "Hanbin", "level": 3, "area_code": 915, "post_code": 725000, "pid": 610900, "id": 2998, "area_id": 610902 }, { "area_name": "汉阴县", "pinyin": "Hanyin", "level": 3, "area_code": 915, "post_code": 725100, "pid": 610900, "id": 2999, "area_id": 610921 }, { "area_name": "石泉县", "pinyin": "Shiquan", "level": 3, "area_code": 915, "post_code": 725200, "pid": 610900, "id": 3000, "area_id": 610922 }, { "area_name": "宁陕县", "pinyin": "Ningshan", "level": 3, "area_code": 915, "post_code": 711600, "pid": 610900, "id": 3001, "area_id": 610923 }, { "area_name": "紫阳县", "pinyin": "Ziyang", "level": 3, "area_code": 915, "post_code": 725300, "pid": 610900, "id": 3002, "area_id": 610924 }, { "area_name": "岚皋县", "pinyin": "Langao", "level": 3, "area_code": 915, "post_code": 725400, "pid": 610900, "id": 3003, "area_id": 610925 }, { "area_name": "平利县", "pinyin": "Pingli", "level": 3, "area_code": 915, "post_code": 725500, "pid": 610900, "id": 3004, "area_id": 610926 }, { "area_name": "镇坪县", "pinyin": "Zhenping", "level": 3, "area_code": 915, "post_code": 725600, "pid": 610900, "id": 3005, "area_id": 610927 }, { "area_name": "旬阳县", "pinyin": "Xunyang", "level": 3, "area_code": 915, "post_code": 725700, "pid": 610900, "id": 3006, "area_id": 610928 }, { "area_name": "白河县", "pinyin": "Baihe", "level": 3, "area_code": 915, "post_code": 725800, "pid": 610900, "id": 3007, "area_id": 610929 }, { "area_name": "商洛市", "pinyin": "Shangluo", "level": 2, "area_code": 914, "post_code": 726000, "pid": 610000, "id": 3008, "area_id": 611000 }, { "area_name": "商州区", "pinyin": "Shangzhou", "level": 3, "area_code": 914, "post_code": 726000, "pid": 611000, "id": 3009, "area_id": 611002 }, { "area_name": "洛南县", "pinyin": "Luonan", "level": 3, "area_code": 914, "post_code": 726100, "pid": 611000, "id": 3010, "area_id": 611021 }, { "area_name": "丹凤县", "pinyin": "Danfeng", "level": 3, "area_code": 914, "post_code": 726200, "pid": 611000, "id": 3011, "area_id": 611022 }, { "area_name": "商南县", "pinyin": "Shangnan", "level": 3, "area_code": 914, "post_code": 726300, "pid": 611000, "id": 3012, "area_id": 611023 }, { "area_name": "山阳县", "pinyin": "Shanyang", "level": 3, "area_code": 914, "post_code": 726400, "pid": 611000, "id": 3013, "area_id": 611024 }, { "area_name": "镇安县", "pinyin": "Zhen'an", "level": 3, "area_code": 914, "post_code": 711500, "pid": 611000, "id": 3014, "area_id": 611025 }, { "area_name": "柞水县", "pinyin": "Zhashui", "level": 3, "area_code": 914, "post_code": 711400, "pid": 611000, "id": 3015, "area_id": 611026 }, { "area_name": "西咸新区", "pinyin": "Xixian", "level": 2, "area_code": 29, "post_code": 712000, "pid": 610000, "id": 3016, "area_id": 611100 }, { "area_name": "空港新城", "pinyin": "Konggang", "level": 3, "area_code": 374, "post_code": 461000, "pid": 611100, "id": 3017, "area_id": 611101 }, { "area_name": "沣东新城", "pinyin": "Fengdong", "level": 3, "area_code": 29, "post_code": 710000, "pid": 611100, "id": 3018, "area_id": 611102 }, { "area_name": "秦汉新城", "pinyin": "Qinhan", "level": 3, "area_code": 29, "post_code": 712000, "pid": 611100, "id": 3019, "area_id": 611103 }, { "area_name": "沣西新城", "pinyin": "Fengxi", "level": 3, "area_code": 29, "post_code": 710000, "pid": 611100, "id": 3020, "area_id": 611104 }, { "area_name": "泾河新城", "pinyin": "Jinghe", "level": 3, "area_code": 29, "post_code": 713700, "pid": 611100, "id": 3021, "area_id": 611105 }, { "area_name": "甘肃省", "pinyin": "Gansu", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3022, "area_id": 620000 }, { "area_name": "兰州市", "pinyin": "Lanzhou", "level": 2, "area_code": 931, "post_code": 730030, "pid": 620000, "id": 3023, "area_id": 620100 }, { "area_name": "城关区", "pinyin": "Chengguan", "level": 3, "area_code": 931, "post_code": 730030, "pid": 620100, "id": 3024, "area_id": 620102 }, { "area_name": "七里河区", "pinyin": "Qilihe", "level": 3, "area_code": 931, "post_code": 730050, "pid": 620100, "id": 3025, "area_id": 620103 }, { "area_name": "西固区", "pinyin": "Xigu", "level": 3, "area_code": 931, "post_code": 730060, "pid": 620100, "id": 3026, "area_id": 620104 }, { "area_name": "安宁区", "pinyin": "Anning", "level": 3, "area_code": 931, "post_code": 730070, "pid": 620100, "id": 3027, "area_id": 620105 }, { "area_name": "红古区", "pinyin": "Honggu", "level": 3, "area_code": 931, "post_code": 730084, "pid": 620100, "id": 3028, "area_id": 620111 }, { "area_name": "永登县", "pinyin": "Yongdeng", "level": 3, "area_code": 931, "post_code": 730300, "pid": 620100, "id": 3029, "area_id": 620121 }, { "area_name": "皋兰县", "pinyin": "Gaolan", "level": 3, "area_code": 931, "post_code": 730200, "pid": 620100, "id": 3030, "area_id": 620122 }, { "area_name": "榆中县", "pinyin": "Yuzhong", "level": 3, "area_code": 931, "post_code": 730100, "pid": 620100, "id": 3031, "area_id": 620123 }, { "area_name": "嘉峪关市", "pinyin": "Jiayuguan", "level": 2, "area_code": 937, "post_code": 735100, "pid": 620000, "id": 3032, "area_id": 620200 }, { "area_name": "雄关区", "pinyin": "Xiongguan", "level": 3, "area_code": 937, "post_code": 735100, "pid": 620200, "id": 3033, "area_id": 620201 }, { "area_name": "长城区", "pinyin": "Changcheng", "level": 3, "area_code": 937, "post_code": 735106, "pid": 620200, "id": 3034, "area_id": 620202 }, { "area_name": "镜铁区", "pinyin": "Jingtie", "level": 3, "area_code": 937, "post_code": 735100, "pid": 620200, "id": 3035, "area_id": 620203 }, { "area_name": "金昌市", "pinyin": "Jinchang", "level": 2, "area_code": 935, "post_code": 737100, "pid": 620000, "id": 3036, "area_id": 620300 }, { "area_name": "金川区", "pinyin": "Jinchuan", "level": 3, "area_code": 935, "post_code": 737100, "pid": 620300, "id": 3037, "area_id": 620302 }, { "area_name": "永昌县", "pinyin": "Yongchang", "level": 3, "area_code": 935, "post_code": 737200, "pid": 620300, "id": 3038, "area_id": 620321 }, { "area_name": "白银市", "pinyin": "Baiyin", "level": 2, "area_code": 943, "post_code": 730900, "pid": 620000, "id": 3039, "area_id": 620400 }, { "area_name": "白银区", "pinyin": "Baiyin", "level": 3, "area_code": 943, "post_code": 730900, "pid": 620400, "id": 3040, "area_id": 620402 }, { "area_name": "平川区", "pinyin": "Pingchuan", "level": 3, "area_code": 943, "post_code": 730913, "pid": 620400, "id": 3041, "area_id": 620403 }, { "area_name": "靖远县", "pinyin": "Jingyuan", "level": 3, "area_code": 943, "post_code": 730600, "pid": 620400, "id": 3042, "area_id": 620421 }, { "area_name": "会宁县", "pinyin": "Huining", "level": 3, "area_code": 943, "post_code": 730700, "pid": 620400, "id": 3043, "area_id": 620422 }, { "area_name": "景泰县", "pinyin": "Jingtai", "level": 3, "area_code": 943, "post_code": 730400, "pid": 620400, "id": 3044, "area_id": 620423 }, { "area_name": "天水市", "pinyin": "Tianshui", "level": 2, "area_code": 938, "post_code": 741000, "pid": 620000, "id": 3045, "area_id": 620500 }, { "area_name": "秦州区", "pinyin": "Qinzhou", "level": 3, "area_code": 938, "post_code": 741000, "pid": 620500, "id": 3046, "area_id": 620502 }, { "area_name": "麦积区", "pinyin": "Maiji", "level": 3, "area_code": 938, "post_code": 741020, "pid": 620500, "id": 3047, "area_id": 620503 }, { "area_name": "清水县", "pinyin": "Qingshui", "level": 3, "area_code": 938, "post_code": 741400, "pid": 620500, "id": 3048, "area_id": 620521 }, { "area_name": "秦安县", "pinyin": "Qin'an", "level": 3, "area_code": 938, "post_code": 741600, "pid": 620500, "id": 3049, "area_id": 620522 }, { "area_name": "甘谷县", "pinyin": "Gangu", "level": 3, "area_code": 938, "post_code": 741200, "pid": 620500, "id": 3050, "area_id": 620523 }, { "area_name": "武山县", "pinyin": "Wushan", "level": 3, "area_code": 938, "post_code": 741300, "pid": 620500, "id": 3051, "area_id": 620524 }, { "area_name": "张家川回族自治县", "pinyin": "Zhangjiachuan", "level": 3, "area_code": 938, "post_code": 741500, "pid": 620500, "id": 3052, "area_id": 620525 }, { "area_name": "武威市", "pinyin": "Wuwei", "level": 2, "area_code": 935, "post_code": 733000, "pid": 620000, "id": 3053, "area_id": 620600 }, { "area_name": "凉州区", "pinyin": "Liangzhou", "level": 3, "area_code": 935, "post_code": 733000, "pid": 620600, "id": 3054, "area_id": 620602 }, { "area_name": "民勤县", "pinyin": "Minqin", "level": 3, "area_code": 935, "post_code": 733300, "pid": 620600, "id": 3055, "area_id": 620621 }, { "area_name": "古浪县", "pinyin": "Gulang", "level": 3, "area_code": 935, "post_code": 733100, "pid": 620600, "id": 3056, "area_id": 620622 }, { "area_name": "天祝藏族自治县", "pinyin": "Tianzhu", "level": 3, "area_code": 935, "post_code": 733200, "pid": 620600, "id": 3057, "area_id": 620623 }, { "area_name": "张掖市", "pinyin": "Zhangye", "level": 2, "area_code": 936, "post_code": 734000, "pid": 620000, "id": 3058, "area_id": 620700 }, { "area_name": "甘州区", "pinyin": "Ganzhou", "level": 3, "area_code": 936, "post_code": 734000, "pid": 620700, "id": 3059, "area_id": 620702 }, { "area_name": "肃南裕固族自治县", "pinyin": "Sunan", "level": 3, "area_code": 936, "post_code": 734400, "pid": 620700, "id": 3060, "area_id": 620721 }, { "area_name": "民乐县", "pinyin": "Minle", "level": 3, "area_code": 936, "post_code": 734500, "pid": 620700, "id": 3061, "area_id": 620722 }, { "area_name": "临泽县", "pinyin": "Linze", "level": 3, "area_code": 936, "post_code": 734200, "pid": 620700, "id": 3062, "area_id": 620723 }, { "area_name": "高台县", "pinyin": "Gaotai", "level": 3, "area_code": 936, "post_code": 734300, "pid": 620700, "id": 3063, "area_id": 620724 }, { "area_name": "山丹县", "pinyin": "Shandan", "level": 3, "area_code": 936, "post_code": 734100, "pid": 620700, "id": 3064, "area_id": 620725 }, { "area_name": "平凉市", "pinyin": "Pingliang", "level": 2, "area_code": 933, "post_code": 744000, "pid": 620000, "id": 3065, "area_id": 620800 }, { "area_name": "崆峒区", "pinyin": "Kongtong", "level": 3, "area_code": 933, "post_code": 744000, "pid": 620800, "id": 3066, "area_id": 620802 }, { "area_name": "泾川县", "pinyin": "Jingchuan", "level": 3, "area_code": 933, "post_code": 744300, "pid": 620800, "id": 3067, "area_id": 620821 }, { "area_name": "灵台县", "pinyin": "Lingtai", "level": 3, "area_code": 933, "post_code": 744400, "pid": 620800, "id": 3068, "area_id": 620822 }, { "area_name": "崇信县", "pinyin": "Chongxin", "level": 3, "area_code": 933, "post_code": 744200, "pid": 620800, "id": 3069, "area_id": 620823 }, { "area_name": "华亭县", "pinyin": "Huating", "level": 3, "area_code": 933, "post_code": 744100, "pid": 620800, "id": 3070, "area_id": 620824 }, { "area_name": "庄浪县", "pinyin": "Zhuanglang", "level": 3, "area_code": 933, "post_code": 744600, "pid": 620800, "id": 3071, "area_id": 620825 }, { "area_name": "静宁县", "pinyin": "Jingning", "level": 3, "area_code": 933, "post_code": 743400, "pid": 620800, "id": 3072, "area_id": 620826 }, { "area_name": "酒泉市", "pinyin": "Jiuquan", "level": 2, "area_code": 937, "post_code": 735000, "pid": 620000, "id": 3073, "area_id": 620900 }, { "area_name": "肃州区", "pinyin": "Suzhou", "level": 3, "area_code": 937, "post_code": 735000, "pid": 620900, "id": 3074, "area_id": 620902 }, { "area_name": "金塔县", "pinyin": "Jinta", "level": 3, "area_code": 937, "post_code": 735300, "pid": 620900, "id": 3075, "area_id": 620921 }, { "area_name": "瓜州县", "pinyin": "Guazhou", "level": 3, "area_code": 937, "post_code": 736100, "pid": 620900, "id": 3076, "area_id": 620922 }, { "area_name": "肃北蒙古族自治县", "pinyin": "Subei", "level": 3, "area_code": 937, "post_code": 736300, "pid": 620900, "id": 3077, "area_id": 620923 }, { "area_name": "阿克塞哈萨克族自治县", "pinyin": "Akesai", "level": 3, "area_code": 937, "post_code": 736400, "pid": 620900, "id": 3078, "area_id": 620924 }, { "area_name": "玉门市", "pinyin": "Yumen", "level": 3, "area_code": 937, "post_code": 735200, "pid": 620900, "id": 3079, "area_id": 620981 }, { "area_name": "敦煌市", "pinyin": "Dunhuang", "level": 3, "area_code": 937, "post_code": 736200, "pid": 620900, "id": 3080, "area_id": 620982 }, { "area_name": "庆阳市", "pinyin": "Qingyang", "level": 2, "area_code": 934, "post_code": 745000, "pid": 620000, "id": 3081, "area_id": 621000 }, { "area_name": "西峰区", "pinyin": "Xifeng", "level": 3, "area_code": 934, "post_code": 745000, "pid": 621000, "id": 3082, "area_id": 621002 }, { "area_name": "庆城县", "pinyin": "Qingcheng", "level": 3, "area_code": 934, "post_code": 745100, "pid": 621000, "id": 3083, "area_id": 621021 }, { "area_name": "环县", "pinyin": "Huanxian", "level": 3, "area_code": 934, "post_code": 745700, "pid": 621000, "id": 3084, "area_id": 621022 }, { "area_name": "华池县", "pinyin": "Huachi", "level": 3, "area_code": 934, "post_code": 745600, "pid": 621000, "id": 3085, "area_id": 621023 }, { "area_name": "合水县", "pinyin": "Heshui", "level": 3, "area_code": 934, "post_code": 745400, "pid": 621000, "id": 3086, "area_id": 621024 }, { "area_name": "正宁县", "pinyin": "Zhengning", "level": 3, "area_code": 934, "post_code": 745300, "pid": 621000, "id": 3087, "area_id": 621025 }, { "area_name": "宁县", "pinyin": "Ningxian", "level": 3, "area_code": 934, "post_code": 745200, "pid": 621000, "id": 3088, "area_id": 621026 }, { "area_name": "镇原县", "pinyin": "Zhenyuan", "level": 3, "area_code": 934, "post_code": 744500, "pid": 621000, "id": 3089, "area_id": 621027 }, { "area_name": "定西市", "pinyin": "Dingxi", "level": 2, "area_code": 932, "post_code": 743000, "pid": 620000, "id": 3090, "area_id": 621100 }, { "area_name": "安定区", "pinyin": "Anding", "level": 3, "area_code": 932, "post_code": 743000, "pid": 621100, "id": 3091, "area_id": 621102 }, { "area_name": "通渭县", "pinyin": "Tongwei", "level": 3, "area_code": 932, "post_code": 743300, "pid": 621100, "id": 3092, "area_id": 621121 }, { "area_name": "陇西县", "pinyin": "Longxi", "level": 3, "area_code": 932, "post_code": 748100, "pid": 621100, "id": 3093, "area_id": 621122 }, { "area_name": "渭源县", "pinyin": "Weiyuan", "level": 3, "area_code": 932, "post_code": 748200, "pid": 621100, "id": 3094, "area_id": 621123 }, { "area_name": "临洮县", "pinyin": "Lintao", "level": 3, "area_code": 932, "post_code": 730500, "pid": 621100, "id": 3095, "area_id": 621124 }, { "area_name": "漳县", "pinyin": "Zhangxian", "level": 3, "area_code": 932, "post_code": 748300, "pid": 621100, "id": 3096, "area_id": 621125 }, { "area_name": "岷县", "pinyin": "Minxian", "level": 3, "area_code": 932, "post_code": 748400, "pid": 621100, "id": 3097, "area_id": 621126 }, { "area_name": "陇南市", "pinyin": "Longnan", "level": 2, "area_code": 939, "post_code": 746000, "pid": 620000, "id": 3098, "area_id": 621200 }, { "area_name": "武都区", "pinyin": "Wudu", "level": 3, "area_code": 939, "post_code": 746000, "pid": 621200, "id": 3099, "area_id": 621202 }, { "area_name": "成县", "pinyin": "Chengxian", "level": 3, "area_code": 939, "post_code": 742500, "pid": 621200, "id": 3100, "area_id": 621221 }, { "area_name": "文县", "pinyin": "Wenxian", "level": 3, "area_code": 939, "post_code": 746400, "pid": 621200, "id": 3101, "area_id": 621222 }, { "area_name": "宕昌县", "pinyin": "Dangchang", "level": 3, "area_code": 939, "post_code": 748500, "pid": 621200, "id": 3102, "area_id": 621223 }, { "area_name": "康县", "pinyin": "Kangxian", "level": 3, "area_code": 939, "post_code": 746500, "pid": 621200, "id": 3103, "area_id": 621224 }, { "area_name": "西和县", "pinyin": "Xihe", "level": 3, "area_code": 939, "post_code": 742100, "pid": 621200, "id": 3104, "area_id": 621225 }, { "area_name": "礼县", "pinyin": "Lixian", "level": 3, "area_code": 939, "post_code": 742200, "pid": 621200, "id": 3105, "area_id": 621226 }, { "area_name": "徽县", "pinyin": "Huixian", "level": 3, "area_code": 939, "post_code": 742300, "pid": 621200, "id": 3106, "area_id": 621227 }, { "area_name": "两当县", "pinyin": "Liangdang", "level": 3, "area_code": 939, "post_code": 742400, "pid": 621200, "id": 3107, "area_id": 621228 }, { "area_name": "临夏回族自治州", "pinyin": "Linxia", "level": 2, "area_code": 930, "post_code": 731100, "pid": 620000, "id": 3108, "area_id": 622900 }, { "area_name": "临夏市", "pinyin": "Linxia", "level": 3, "area_code": 930, "post_code": 731100, "pid": 622900, "id": 3109, "area_id": 622901 }, { "area_name": "临夏县", "pinyin": "Linxia", "level": 3, "area_code": 930, "post_code": 731800, "pid": 622900, "id": 3110, "area_id": 622921 }, { "area_name": "康乐县", "pinyin": "Kangle", "level": 3, "area_code": 930, "post_code": 731500, "pid": 622900, "id": 3111, "area_id": 622922 }, { "area_name": "永靖县", "pinyin": "Yongjing", "level": 3, "area_code": 930, "post_code": 731600, "pid": 622900, "id": 3112, "area_id": 622923 }, { "area_name": "广河县", "pinyin": "Guanghe", "level": 3, "area_code": 930, "post_code": 731300, "pid": 622900, "id": 3113, "area_id": 622924 }, { "area_name": "和政县", "pinyin": "Hezheng", "level": 3, "area_code": 930, "post_code": 731200, "pid": 622900, "id": 3114, "area_id": 622925 }, { "area_name": "东乡族自治县", "pinyin": "Dongxiangzu", "level": 3, "area_code": 930, "post_code": 731400, "pid": 622900, "id": 3115, "area_id": 622926 }, { "area_name": "积石山保安族东乡族撒拉族自治县", "pinyin": "Jishishan", "level": 3, "area_code": 930, "post_code": 731700, "pid": 622900, "id": 3116, "area_id": 622927 }, { "area_name": "甘南藏族自治州", "pinyin": "Gannan", "level": 2, "area_code": 941, "post_code": 747000, "pid": 620000, "id": 3117, "area_id": 623000 }, { "area_name": "合作市", "pinyin": "Hezuo", "level": 3, "area_code": 941, "post_code": 747000, "pid": 623000, "id": 3118, "area_id": 623001 }, { "area_name": "临潭县", "pinyin": "Lintan", "level": 3, "area_code": 941, "post_code": 747500, "pid": 623000, "id": 3119, "area_id": 623021 }, { "area_name": "卓尼县", "pinyin": "Zhuoni", "level": 3, "area_code": 941, "post_code": 747600, "pid": 623000, "id": 3120, "area_id": 623022 }, { "area_name": "舟曲县", "pinyin": "Zhouqu", "level": 3, "area_code": 941, "post_code": 746300, "pid": 623000, "id": 3121, "area_id": 623023 }, { "area_name": "迭部县", "pinyin": "Diebu", "level": 3, "area_code": 941, "post_code": 747400, "pid": 623000, "id": 3122, "area_id": 623024 }, { "area_name": "玛曲县", "pinyin": "Maqu", "level": 3, "area_code": 941, "post_code": 747300, "pid": 623000, "id": 3123, "area_id": 623025 }, { "area_name": "碌曲县", "pinyin": "Luqu", "level": 3, "area_code": 941, "post_code": 747200, "pid": 623000, "id": 3124, "area_id": 623026 }, { "area_name": "夏河县", "pinyin": "Xiahe", "level": 3, "area_code": 941, "post_code": 747100, "pid": 623000, "id": 3125, "area_id": 623027 }, { "area_name": "青海省", "pinyin": "Qinghai", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3126, "area_id": 630000 }, { "area_name": "西宁市", "pinyin": "Xining", "level": 2, "area_code": 971, "post_code": 810000, "pid": 630000, "id": 3127, "area_id": 630100 }, { "area_name": "城东区", "pinyin": "Chengdong", "level": 3, "area_code": 971, "post_code": 810007, "pid": 630100, "id": 3128, "area_id": 630102 }, { "area_name": "城中区", "pinyin": "Chengzhong", "level": 3, "area_code": 971, "post_code": 810000, "pid": 630100, "id": 3129, "area_id": 630103 }, { "area_name": "城西区", "pinyin": "Chengxi", "level": 3, "area_code": 971, "post_code": 810001, "pid": 630100, "id": 3130, "area_id": 630104 }, { "area_name": "城北区", "pinyin": "Chengbei", "level": 3, "area_code": 971, "post_code": 810003, "pid": 630100, "id": 3131, "area_id": 630105 }, { "area_name": "大通回族土族自治县", "pinyin": "Datong", "level": 3, "area_code": 971, "post_code": 810100, "pid": 630100, "id": 3132, "area_id": 630121 }, { "area_name": "湟中县", "pinyin": "Huangzhong", "level": 3, "area_code": 971, "post_code": 811600, "pid": 630100, "id": 3133, "area_id": 630122 }, { "area_name": "湟源县", "pinyin": "Huangyuan", "level": 3, "area_code": 971, "post_code": 812100, "pid": 630100, "id": 3134, "area_id": 630123 }, { "area_name": "海东市", "pinyin": "Haidong", "level": 2, "area_code": 972, "post_code": 810700, "pid": 630000, "id": 3135, "area_id": 630200 }, { "area_name": "乐都区", "pinyin": "Ledu", "level": 3, "area_code": 972, "post_code": 810700, "pid": 630200, "id": 3136, "area_id": 630202 }, { "area_name": "平安县", "pinyin": "Ping'an", "level": 3, "area_code": 972, "post_code": 810600, "pid": 630200, "id": 3137, "area_id": 630221 }, { "area_name": "民和回族土族自治县", "pinyin": "Minhe", "level": 3, "area_code": 972, "post_code": 810800, "pid": 630200, "id": 3138, "area_id": 630222 }, { "area_name": "互助土族自治县", "pinyin": "Huzhu", "level": 3, "area_code": 972, "post_code": 810500, "pid": 630200, "id": 3139, "area_id": 630223 }, { "area_name": "化隆回族自治县", "pinyin": "Hualong", "level": 3, "area_code": 972, "post_code": 810900, "pid": 630200, "id": 3140, "area_id": 630224 }, { "area_name": "循化撒拉族自治县", "pinyin": "Xunhua", "level": 3, "area_code": 972, "post_code": 811100, "pid": 630200, "id": 3141, "area_id": 630225 }, { "area_name": "海北藏族自治州", "pinyin": "Haibei", "level": 2, "area_code": 970, "post_code": 812200, "pid": 630000, "id": 3142, "area_id": 632200 }, { "area_name": "门源回族自治县", "pinyin": "Menyuan", "level": 3, "area_code": 970, "post_code": 810300, "pid": 632200, "id": 3143, "area_id": 632221 }, { "area_name": "祁连县", "pinyin": "Qilian", "level": 3, "area_code": 970, "post_code": 810400, "pid": 632200, "id": 3144, "area_id": 632222 }, { "area_name": "海晏县", "pinyin": "Haiyan", "level": 3, "area_code": 970, "post_code": 812200, "pid": 632200, "id": 3145, "area_id": 632223 }, { "area_name": "刚察县", "pinyin": "Gangcha", "level": 3, "area_code": 970, "post_code": 812300, "pid": 632200, "id": 3146, "area_id": 632224 }, { "area_name": "黄南藏族自治州", "pinyin": "Huangnan", "level": 2, "area_code": 973, "post_code": 811300, "pid": 630000, "id": 3147, "area_id": 632300 }, { "area_name": "同仁县", "pinyin": "Tongren", "level": 3, "area_code": 973, "post_code": 811300, "pid": 632300, "id": 3148, "area_id": 632321 }, { "area_name": "尖扎县", "pinyin": "Jianzha", "level": 3, "area_code": 973, "post_code": 811200, "pid": 632300, "id": 3149, "area_id": 632322 }, { "area_name": "泽库县", "pinyin": "Zeku", "level": 3, "area_code": 973, "post_code": 811400, "pid": 632300, "id": 3150, "area_id": 632323 }, { "area_name": "河南蒙古族自治县", "pinyin": "Henan", "level": 3, "area_code": 973, "post_code": 811500, "pid": 632300, "id": 3151, "area_id": 632324 }, { "area_name": "海南藏族自治州", "pinyin": "Hainan", "level": 2, "area_code": 974, "post_code": 813000, "pid": 630000, "id": 3152, "area_id": 632500 }, { "area_name": "共和县", "pinyin": "Gonghe", "level": 3, "area_code": 974, "post_code": 813000, "pid": 632500, "id": 3153, "area_id": 632521 }, { "area_name": "同德县", "pinyin": "Tongde", "level": 3, "area_code": 974, "post_code": 813200, "pid": 632500, "id": 3154, "area_id": 632522 }, { "area_name": "贵德县", "pinyin": "Guide", "level": 3, "area_code": 974, "post_code": 811700, "pid": 632500, "id": 3155, "area_id": 632523 }, { "area_name": "兴海县", "pinyin": "Xinghai", "level": 3, "area_code": 974, "post_code": 813300, "pid": 632500, "id": 3156, "area_id": 632524 }, { "area_name": "贵南县", "pinyin": "Guinan", "level": 3, "area_code": 974, "post_code": 813100, "pid": 632500, "id": 3157, "area_id": 632525 }, { "area_name": "果洛藏族自治州", "pinyin": "Golog", "level": 2, "area_code": 975, "post_code": 814000, "pid": 630000, "id": 3158, "area_id": 632600 }, { "area_name": "玛沁县", "pinyin": "Maqin", "level": 3, "area_code": 975, "post_code": 814000, "pid": 632600, "id": 3159, "area_id": 632621 }, { "area_name": "班玛县", "pinyin": "Banma", "level": 3, "area_code": 975, "post_code": 814300, "pid": 632600, "id": 3160, "area_id": 632622 }, { "area_name": "甘德县", "pinyin": "Gande", "level": 3, "area_code": 975, "post_code": 814100, "pid": 632600, "id": 3161, "area_id": 632623 }, { "area_name": "达日县", "pinyin": "Dari", "level": 3, "area_code": 975, "post_code": 814200, "pid": 632600, "id": 3162, "area_id": 632624 }, { "area_name": "久治县", "pinyin": "Jiuzhi", "level": 3, "area_code": 975, "post_code": 624700, "pid": 632600, "id": 3163, "area_id": 632625 }, { "area_name": "玛多县", "pinyin": "Maduo", "level": 3, "area_code": 975, "post_code": 813500, "pid": 632600, "id": 3164, "area_id": 632626 }, { "area_name": "玉树藏族自治州", "pinyin": "Yushu", "level": 2, "area_code": 976, "post_code": 815000, "pid": 630000, "id": 3165, "area_id": 632700 }, { "area_name": "玉树市", "pinyin": "Yushu", "level": 3, "area_code": 976, "post_code": 815000, "pid": 632700, "id": 3166, "area_id": 632701 }, { "area_name": "杂多县", "pinyin": "Zaduo", "level": 3, "area_code": 976, "post_code": 815300, "pid": 632700, "id": 3167, "area_id": 632722 }, { "area_name": "称多县", "pinyin": "Chenduo", "level": 3, "area_code": 976, "post_code": 815100, "pid": 632700, "id": 3168, "area_id": 632723 }, { "area_name": "治多县", "pinyin": "Zhiduo", "level": 3, "area_code": 976, "post_code": 815400, "pid": 632700, "id": 3169, "area_id": 632724 }, { "area_name": "囊谦县", "pinyin": "Nangqian", "level": 3, "area_code": 976, "post_code": 815200, "pid": 632700, "id": 3170, "area_id": 632725 }, { "area_name": "曲麻莱县", "pinyin": "Qumalai", "level": 3, "area_code": 976, "post_code": 815500, "pid": 632700, "id": 3171, "area_id": 632726 }, { "area_name": "海西蒙古族藏族自治州", "pinyin": "Haixi", "level": 2, "area_code": 977, "post_code": 817000, "pid": 630000, "id": 3172, "area_id": 632800 }, { "area_name": "格尔木市", "pinyin": "Geermu", "level": 3, "area_code": 977, "post_code": 816000, "pid": 632800, "id": 3173, "area_id": 632801 }, { "area_name": "德令哈市", "pinyin": "Delingha", "level": 3, "area_code": 977, "post_code": 817000, "pid": 632800, "id": 3174, "area_id": 632802 }, { "area_name": "乌兰县", "pinyin": "Wulan", "level": 3, "area_code": 977, "post_code": 817100, "pid": 632800, "id": 3175, "area_id": 632821 }, { "area_name": "都兰县", "pinyin": "Dulan", "level": 3, "area_code": 977, "post_code": 816100, "pid": 632800, "id": 3176, "area_id": 632822 }, { "area_name": "天峻县", "pinyin": "Tianjun", "level": 3, "area_code": 977, "post_code": 817200, "pid": 632800, "id": 3177, "area_id": 632823 }, { "area_name": "宁夏回族自治区", "pinyin": "Ningxia", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3178, "area_id": 640000 }, { "area_name": "银川市", "pinyin": "Yinchuan", "level": 2, "area_code": 951, "post_code": 750004, "pid": 640000, "id": 3179, "area_id": 640100 }, { "area_name": "兴庆区", "pinyin": "Xingqing", "level": 3, "area_code": 951, "post_code": 750001, "pid": 640100, "id": 3180, "area_id": 640104 }, { "area_name": "西夏区", "pinyin": "Xixia", "level": 3, "area_code": 951, "post_code": 750021, "pid": 640100, "id": 3181, "area_id": 640105 }, { "area_name": "金凤区", "pinyin": "Jinfeng", "level": 3, "area_code": 951, "post_code": 750011, "pid": 640100, "id": 3182, "area_id": 640106 }, { "area_name": "永宁县", "pinyin": "Yongning", "level": 3, "area_code": 951, "post_code": 750100, "pid": 640100, "id": 3183, "area_id": 640121 }, { "area_name": "贺兰县", "pinyin": "Helan", "level": 3, "area_code": 951, "post_code": 750200, "pid": 640100, "id": 3184, "area_id": 640122 }, { "area_name": "灵武市", "pinyin": "Lingwu", "level": 3, "area_code": 951, "post_code": 750004, "pid": 640100, "id": 3185, "area_id": 640181 }, { "area_name": "石嘴山市", "pinyin": "Shizuishan", "level": 2, "area_code": 952, "post_code": 753000, "pid": 640000, "id": 3186, "area_id": 640200 }, { "area_name": "大武口区", "pinyin": "Dawukou", "level": 3, "area_code": 952, "post_code": 753000, "pid": 640200, "id": 3187, "area_id": 640202 }, { "area_name": "惠农区", "pinyin": "Huinong", "level": 3, "area_code": 952, "post_code": 753600, "pid": 640200, "id": 3188, "area_id": 640205 }, { "area_name": "平罗县", "pinyin": "Pingluo", "level": 3, "area_code": 952, "post_code": 753400, "pid": 640200, "id": 3189, "area_id": 640221 }, { "area_name": "吴忠市", "pinyin": "Wuzhong", "level": 2, "area_code": 953, "post_code": 751100, "pid": 640000, "id": 3190, "area_id": 640300 }, { "area_name": "利通区", "pinyin": "Litong", "level": 3, "area_code": 953, "post_code": 751100, "pid": 640300, "id": 3191, "area_id": 640302 }, { "area_name": "红寺堡区", "pinyin": "Hongsibao", "level": 3, "area_code": 953, "post_code": 751900, "pid": 640300, "id": 3192, "area_id": 640303 }, { "area_name": "盐池县", "pinyin": "Yanchi", "level": 3, "area_code": 953, "post_code": 751500, "pid": 640300, "id": 3193, "area_id": 640323 }, { "area_name": "同心县", "pinyin": "Tongxin", "level": 3, "area_code": 953, "post_code": 751300, "pid": 640300, "id": 3194, "area_id": 640324 }, { "area_name": "青铜峡市", "pinyin": "Qingtongxia", "level": 3, "area_code": 953, "post_code": 751600, "pid": 640300, "id": 3195, "area_id": 640381 }, { "area_name": "固原市", "pinyin": "Guyuan", "level": 2, "area_code": 954, "post_code": 756000, "pid": 640000, "id": 3196, "area_id": 640400 }, { "area_name": "原州区", "pinyin": "Yuanzhou", "level": 3, "area_code": 954, "post_code": 756000, "pid": 640400, "id": 3197, "area_id": 640402 }, { "area_name": "西吉县", "pinyin": "Xiji", "level": 3, "area_code": 954, "post_code": 756200, "pid": 640400, "id": 3198, "area_id": 640422 }, { "area_name": "隆德县", "pinyin": "Longde", "level": 3, "area_code": 954, "post_code": 756300, "pid": 640400, "id": 3199, "area_id": 640423 }, { "area_name": "泾源县", "pinyin": "Jingyuan", "level": 3, "area_code": 954, "post_code": 756400, "pid": 640400, "id": 3200, "area_id": 640424 }, { "area_name": "彭阳县", "pinyin": "Pengyang", "level": 3, "area_code": 954, "post_code": 756500, "pid": 640400, "id": 3201, "area_id": 640425 }, { "area_name": "中卫市", "pinyin": "Zhongwei", "level": 2, "area_code": 955, "post_code": 751700, "pid": 640000, "id": 3202, "area_id": 640500 }, { "area_name": "沙坡头区", "pinyin": "Shapotou", "level": 3, "area_code": 955, "post_code": 755000, "pid": 640500, "id": 3203, "area_id": 640502 }, { "area_name": "中宁县", "pinyin": "Zhongning", "level": 3, "area_code": 955, "post_code": 751200, "pid": 640500, "id": 3204, "area_id": 640521 }, { "area_name": "海原县", "pinyin": "Haiyuan", "level": 3, "area_code": 955, "post_code": 751800, "pid": 640500, "id": 3205, "area_id": 640522 }, { "area_name": "新疆维吾尔自治区", "pinyin": "Xinjiang", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3206, "area_id": 650000 }, { "area_name": "乌鲁木齐市", "pinyin": "Urumqi", "level": 2, "area_code": 991, "post_code": 830002, "pid": 650000, "id": 3207, "area_id": 650100 }, { "area_name": "天山区", "pinyin": "Tianshan", "level": 3, "area_code": 991, "post_code": 830002, "pid": 650100, "id": 3208, "area_id": 650102 }, { "area_name": "沙依巴克区", "pinyin": "Shayibake", "level": 3, "area_code": 991, "post_code": 830000, "pid": 650100, "id": 3209, "area_id": 650103 }, { "area_name": "新市区", "pinyin": "Xinshi", "level": 3, "area_code": 991, "post_code": 830011, "pid": 650100, "id": 3210, "area_id": 650104 }, { "area_name": "水磨沟区", "pinyin": "Shuimogou", "level": 3, "area_code": 991, "post_code": 830017, "pid": 650100, "id": 3211, "area_id": 650105 }, { "area_name": "头屯河区", "pinyin": "Toutunhe", "level": 3, "area_code": 991, "post_code": 830022, "pid": 650100, "id": 3212, "area_id": 650106 }, { "area_name": "达坂城区", "pinyin": "Dabancheng", "level": 3, "area_code": 991, "post_code": 830039, "pid": 650100, "id": 3213, "area_id": 650107 }, { "area_name": "米东区", "pinyin": "Midong", "level": 3, "area_code": 991, "post_code": 830019, "pid": 650100, "id": 3214, "area_id": 650109 }, { "area_name": "乌鲁木齐县", "pinyin": "Wulumuqi", "level": 3, "area_code": 991, "post_code": 830063, "pid": 650100, "id": 3215, "area_id": 650121 }, { "area_name": "克拉玛依市", "pinyin": "Karamay", "level": 2, "area_code": 990, "post_code": 834000, "pid": 650000, "id": 3216, "area_id": 650200 }, { "area_name": "独山子区", "pinyin": "Dushanzi", "level": 3, "area_code": 992, "post_code": 834021, "pid": 650200, "id": 3217, "area_id": 650202 }, { "area_name": "克拉玛依区", "pinyin": "Kelamayi", "level": 3, "area_code": 990, "post_code": 834000, "pid": 650200, "id": 3218, "area_id": 650203 }, { "area_name": "白碱滩区", "pinyin": "Baijiantan", "level": 3, "area_code": 990, "post_code": 834008, "pid": 650200, "id": 3219, "area_id": 650204 }, { "area_name": "乌尔禾区", "pinyin": "Wuerhe", "level": 3, "area_code": 990, "post_code": 834012, "pid": 650200, "id": 3220, "area_id": 650205 }, { "area_name": "吐鲁番地区", "pinyin": "Turpan", "level": 2, "area_code": 995, "post_code": 838000, "pid": 650000, "id": 3221, "area_id": 652100 }, { "area_name": "吐鲁番市", "pinyin": "Tulufan", "level": 3, "area_code": 995, "post_code": 838000, "pid": 652100, "id": 3222, "area_id": 652101 }, { "area_name": "鄯善县", "pinyin": "Shanshan", "level": 3, "area_code": 995, "post_code": 838200, "pid": 652100, "id": 3223, "area_id": 652122 }, { "area_name": "托克逊县", "pinyin": "Tuokexun", "level": 3, "area_code": 995, "post_code": 838100, "pid": 652100, "id": 3224, "area_id": 652123 }, { "area_name": "哈密地区", "pinyin": "Hami", "level": 2, "area_code": 902, "post_code": 839000, "pid": 650000, "id": 3225, "area_id": 652200 }, { "area_name": "哈密市", "pinyin": "Hami", "level": 3, "area_code": 902, "post_code": 839000, "pid": 652200, "id": 3226, "area_id": 652201 }, { "area_name": "巴里坤哈萨克自治县", "pinyin": "Balikun", "level": 3, "area_code": 902, "post_code": 839200, "pid": 652200, "id": 3227, "area_id": 652222 }, { "area_name": "伊吾县", "pinyin": "Yiwu", "level": 3, "area_code": 902, "post_code": 839300, "pid": 652200, "id": 3228, "area_id": 652223 }, { "area_name": "昌吉回族自治州", "pinyin": "Changji", "level": 2, "area_code": 994, "post_code": 831100, "pid": 650000, "id": 3229, "area_id": 652300 }, { "area_name": "昌吉市", "pinyin": "Changji", "level": 3, "area_code": 994, "post_code": 831100, "pid": 652300, "id": 3230, "area_id": 652301 }, { "area_name": "阜康市", "pinyin": "Fukang", "level": 3, "area_code": 994, "post_code": 831500, "pid": 652300, "id": 3231, "area_id": 652302 }, { "area_name": "呼图壁县", "pinyin": "Hutubi", "level": 3, "area_code": 994, "post_code": 831200, "pid": 652300, "id": 3232, "area_id": 652323 }, { "area_name": "玛纳斯县", "pinyin": "Manasi", "level": 3, "area_code": 994, "post_code": 832200, "pid": 652300, "id": 3233, "area_id": 652324 }, { "area_name": "奇台县", "pinyin": "Qitai", "level": 3, "area_code": 994, "post_code": 831800, "pid": 652300, "id": 3234, "area_id": 652325 }, { "area_name": "吉木萨尔县", "pinyin": "Jimusaer", "level": 3, "area_code": 994, "post_code": 831700, "pid": 652300, "id": 3235, "area_id": 652327 }, { "area_name": "木垒哈萨克自治县", "pinyin": "Mulei", "level": 3, "area_code": 994, "post_code": 831900, "pid": 652300, "id": 3236, "area_id": 652328 }, { "area_name": "博尔塔拉蒙古自治州", "pinyin": "Bortala", "level": 2, "area_code": 909, "post_code": 833400, "pid": 650000, "id": 3237, "area_id": 652700 }, { "area_name": "博乐市", "pinyin": "Bole", "level": 3, "area_code": 909, "post_code": 833400, "pid": 652700, "id": 3238, "area_id": 652701 }, { "area_name": "阿拉山口市", "pinyin": "Alashankou", "level": 3, "area_code": 909, "post_code": 833400, "pid": 652700, "id": 3239, "area_id": 652702 }, { "area_name": "精河县", "pinyin": "Jinghe", "level": 3, "area_code": 909, "post_code": 833300, "pid": 652700, "id": 3240, "area_id": 652722 }, { "area_name": "温泉县", "pinyin": "Wenquan", "level": 3, "area_code": 909, "post_code": 833500, "pid": 652700, "id": 3241, "area_id": 652723 }, { "area_name": "巴音郭楞蒙古自治州", "pinyin": "Bayingol", "level": 2, "area_code": 996, "post_code": 841000, "pid": 650000, "id": 3242, "area_id": 652800 }, { "area_name": "库尔勒市", "pinyin": "Kuerle", "level": 3, "area_code": 996, "post_code": 841000, "pid": 652800, "id": 3243, "area_id": 652801 }, { "area_name": "轮台县", "pinyin": "Luntai", "level": 3, "area_code": 996, "post_code": 841600, "pid": 652800, "id": 3244, "area_id": 652822 }, { "area_name": "尉犁县", "pinyin": "Yuli", "level": 3, "area_code": 996, "post_code": 841500, "pid": 652800, "id": 3245, "area_id": 652823 }, { "area_name": "若羌县", "pinyin": "Ruoqiang", "level": 3, "area_code": 996, "post_code": 841800, "pid": 652800, "id": 3246, "area_id": 652824 }, { "area_name": "且末县", "pinyin": "Qiemo", "level": 3, "area_code": 996, "post_code": 841900, "pid": 652800, "id": 3247, "area_id": 652825 }, { "area_name": "焉耆回族自治县", "pinyin": "Yanqi", "level": 3, "area_code": 996, "post_code": 841100, "pid": 652800, "id": 3248, "area_id": 652826 }, { "area_name": "和静县", "pinyin": "Hejing", "level": 3, "area_code": 996, "post_code": 841300, "pid": 652800, "id": 3249, "area_id": 652827 }, { "area_name": "和硕县", "pinyin": "Heshuo", "level": 3, "area_code": 996, "post_code": 841200, "pid": 652800, "id": 3250, "area_id": 652828 }, { "area_name": "博湖县", "pinyin": "Bohu", "level": 3, "area_code": 996, "post_code": 841400, "pid": 652800, "id": 3251, "area_id": 652829 }, { "area_name": "阿克苏地区", "pinyin": "Aksu", "level": 2, "area_code": 997, "post_code": 843000, "pid": 650000, "id": 3252, "area_id": 652900 }, { "area_name": "阿克苏市", "pinyin": "Akesu", "level": 3, "area_code": 997, "post_code": 843000, "pid": 652900, "id": 3253, "area_id": 652901 }, { "area_name": "温宿县", "pinyin": "Wensu", "level": 3, "area_code": 997, "post_code": 843100, "pid": 652900, "id": 3254, "area_id": 652922 }, { "area_name": "库车县", "pinyin": "Kuche", "level": 3, "area_code": 997, "post_code": 842000, "pid": 652900, "id": 3255, "area_id": 652923 }, { "area_name": "沙雅县", "pinyin": "Shaya", "level": 3, "area_code": 997, "post_code": 842200, "pid": 652900, "id": 3256, "area_id": 652924 }, { "area_name": "新和县", "pinyin": "Xinhe", "level": 3, "area_code": 997, "post_code": 842100, "pid": 652900, "id": 3257, "area_id": 652925 }, { "area_name": "拜城县", "pinyin": "Baicheng", "level": 3, "area_code": 997, "post_code": 842300, "pid": 652900, "id": 3258, "area_id": 652926 }, { "area_name": "乌什县", "pinyin": "Wushi", "level": 3, "area_code": 997, "post_code": 843400, "pid": 652900, "id": 3259, "area_id": 652927 }, { "area_name": "阿瓦提县", "pinyin": "Awati", "level": 3, "area_code": 997, "post_code": 843200, "pid": 652900, "id": 3260, "area_id": 652928 }, { "area_name": "柯坪县", "pinyin": "Keping", "level": 3, "area_code": 997, "post_code": 843600, "pid": 652900, "id": 3261, "area_id": 652929 }, { "area_name": "克孜勒苏柯尔克孜自治州", "pinyin": "Kizilsu", "level": 2, "area_code": 908, "post_code": 845350, "pid": 650000, "id": 3262, "area_id": 653000 }, { "area_name": "阿图什市", "pinyin": "Atushi", "level": 3, "area_code": 908, "post_code": 845350, "pid": 653000, "id": 3263, "area_id": 653001 }, { "area_name": "阿克陶县", "pinyin": "Aketao", "level": 3, "area_code": 908, "post_code": 845550, "pid": 653000, "id": 3264, "area_id": 653022 }, { "area_name": "阿合奇县", "pinyin": "Aheqi", "level": 3, "area_code": 997, "post_code": 843500, "pid": 653000, "id": 3265, "area_id": 653023 }, { "area_name": "乌恰县", "pinyin": "Wuqia", "level": 3, "area_code": 908, "post_code": 845450, "pid": 653000, "id": 3266, "area_id": 653024 }, { "area_name": "喀什地区", "pinyin": "Kashgar", "level": 2, "area_code": 998, "post_code": 844000, "pid": 650000, "id": 3267, "area_id": 653100 }, { "area_name": "喀什市", "pinyin": "Kashi", "level": 3, "area_code": 998, "post_code": 844000, "pid": 653100, "id": 3268, "area_id": 653101 }, { "area_name": "疏附县", "pinyin": "Shufu", "level": 3, "area_code": 998, "post_code": 844100, "pid": 653100, "id": 3269, "area_id": 653121 }, { "area_name": "疏勒县", "pinyin": "Shule", "level": 3, "area_code": 998, "post_code": 844200, "pid": 653100, "id": 3270, "area_id": 653122 }, { "area_name": "英吉沙县", "pinyin": "Yingjisha", "level": 3, "area_code": 998, "post_code": 844500, "pid": 653100, "id": 3271, "area_id": 653123 }, { "area_name": "泽普县", "pinyin": "Zepu", "level": 3, "area_code": 998, "post_code": 844800, "pid": 653100, "id": 3272, "area_id": 653124 }, { "area_name": "莎车县", "pinyin": "Shache", "level": 3, "area_code": 998, "post_code": 844700, "pid": 653100, "id": 3273, "area_id": 653125 }, { "area_name": "叶城县", "pinyin": "Yecheng", "level": 3, "area_code": 998, "post_code": 844900, "pid": 653100, "id": 3274, "area_id": 653126 }, { "area_name": "麦盖提县", "pinyin": "Maigaiti", "level": 3, "area_code": 998, "post_code": 844600, "pid": 653100, "id": 3275, "area_id": 653127 }, { "area_name": "岳普湖县", "pinyin": "Yuepuhu", "level": 3, "area_code": 998, "post_code": 844400, "pid": 653100, "id": 3276, "area_id": 653128 }, { "area_name": "伽师县", "pinyin": "Jiashi", "level": 3, "area_code": 998, "post_code": 844300, "pid": 653100, "id": 3277, "area_id": 653129 }, { "area_name": "巴楚县", "pinyin": "Bachu", "level": 3, "area_code": 998, "post_code": 843800, "pid": 653100, "id": 3278, "area_id": 653130 }, { "area_name": "塔什库尔干塔吉克自治县", "pinyin": "Tashikuergantajike", "level": 3, "area_code": 998, "post_code": 845250, "pid": 653100, "id": 3279, "area_id": 653131 }, { "area_name": "和田地区", "pinyin": "Hotan", "level": 2, "area_code": 903, "post_code": 848000, "pid": 650000, "id": 3280, "area_id": 653200 }, { "area_name": "和田市", "pinyin": "Hetianshi", "level": 3, "area_code": 903, "post_code": 848000, "pid": 653200, "id": 3281, "area_id": 653201 }, { "area_name": "和田县", "pinyin": "Hetianxian", "level": 3, "area_code": 903, "post_code": 848000, "pid": 653200, "id": 3282, "area_id": 653221 }, { "area_name": "墨玉县", "pinyin": "Moyu", "level": 3, "area_code": 903, "post_code": 848100, "pid": 653200, "id": 3283, "area_id": 653222 }, { "area_name": "皮山县", "pinyin": "Pishan", "level": 3, "area_code": 903, "post_code": 845150, "pid": 653200, "id": 3284, "area_id": 653223 }, { "area_name": "洛浦县", "pinyin": "Luopu", "level": 3, "area_code": 903, "post_code": 848200, "pid": 653200, "id": 3285, "area_id": 653224 }, { "area_name": "策勒县", "pinyin": "Cele", "level": 3, "area_code": 903, "post_code": 848300, "pid": 653200, "id": 3286, "area_id": 653225 }, { "area_name": "于田县", "pinyin": "Yutian", "level": 3, "area_code": 903, "post_code": 848400, "pid": 653200, "id": 3287, "area_id": 653226 }, { "area_name": "民丰县", "pinyin": "Minfeng", "level": 3, "area_code": 903, "post_code": 848500, "pid": 653200, "id": 3288, "area_id": 653227 }, { "area_name": "伊犁哈萨克自治州", "pinyin": "Ili", "level": 2, "area_code": 999, "post_code": 835100, "pid": 650000, "id": 3289, "area_id": 654000 }, { "area_name": "伊宁市", "pinyin": "Yining", "level": 3, "area_code": 999, "post_code": 835000, "pid": 654000, "id": 3290, "area_id": 654002 }, { "area_name": "奎屯市", "pinyin": "Kuitun", "level": 3, "area_code": 992, "post_code": 833200, "pid": 654000, "id": 3291, "area_id": 654003 }, { "area_name": "霍尔果斯市", "pinyin": "Huoerguosi", "level": 3, "area_code": 999, "post_code": 835221, "pid": 654000, "id": 3292, "area_id": 654004 }, { "area_name": "伊宁县", "pinyin": "Yining", "level": 3, "area_code": 999, "post_code": 835100, "pid": 654000, "id": 3293, "area_id": 654021 }, { "area_name": "察布查尔锡伯自治县", "pinyin": "Chabuchaerxibo", "level": 3, "area_code": 999, "post_code": 835300, "pid": 654000, "id": 3294, "area_id": 654022 }, { "area_name": "霍城县", "pinyin": "Huocheng", "level": 3, "area_code": 999, "post_code": 835200, "pid": 654000, "id": 3295, "area_id": 654023 }, { "area_name": "巩留县", "pinyin": "Gongliu", "level": 3, "area_code": 999, "post_code": 835400, "pid": 654000, "id": 3296, "area_id": 654024 }, { "area_name": "新源县", "pinyin": "Xinyuan", "level": 3, "area_code": 999, "post_code": 835800, "pid": 654000, "id": 3297, "area_id": 654025 }, { "area_name": "昭苏县", "pinyin": "Zhaosu", "level": 3, "area_code": 999, "post_code": 835600, "pid": 654000, "id": 3298, "area_id": 654026 }, { "area_name": "特克斯县", "pinyin": "Tekesi", "level": 3, "area_code": 999, "post_code": 835500, "pid": 654000, "id": 3299, "area_id": 654027 }, { "area_name": "尼勒克县", "pinyin": "Nileke", "level": 3, "area_code": 999, "post_code": 835700, "pid": 654000, "id": 3300, "area_id": 654028 }, { "area_name": "塔城地区", "pinyin": "Qoqek", "level": 2, "area_code": 901, "post_code": 834700, "pid": 650000, "id": 3301, "area_id": 654200 }, { "area_name": "塔城市", "pinyin": "Tacheng", "level": 3, "area_code": 901, "post_code": 834700, "pid": 654200, "id": 3302, "area_id": 654201 }, { "area_name": "乌苏市", "pinyin": "Wusu", "level": 3, "area_code": 992, "post_code": 833000, "pid": 654200, "id": 3303, "area_id": 654202 }, { "area_name": "额敏县", "pinyin": "Emin", "level": 3, "area_code": 901, "post_code": 834600, "pid": 654200, "id": 3304, "area_id": 654221 }, { "area_name": "沙湾县", "pinyin": "Shawan", "level": 3, "area_code": 993, "post_code": 832100, "pid": 654200, "id": 3305, "area_id": 654223 }, { "area_name": "托里县", "pinyin": "Tuoli", "level": 3, "area_code": 901, "post_code": 834500, "pid": 654200, "id": 3306, "area_id": 654224 }, { "area_name": "裕民县", "pinyin": "Yumin", "level": 3, "area_code": 901, "post_code": 834800, "pid": 654200, "id": 3307, "area_id": 654225 }, { "area_name": "和布克赛尔蒙古自治县", "pinyin": "Hebukesaier", "level": 3, "area_code": 990, "post_code": 834400, "pid": 654200, "id": 3308, "area_id": 654226 }, { "area_name": "阿勒泰地区", "pinyin": "Altay", "level": 2, "area_code": 906, "post_code": 836500, "pid": 650000, "id": 3309, "area_id": 654300 }, { "area_name": "阿勒泰市", "pinyin": "Aletai", "level": 3, "area_code": 906, "post_code": 836500, "pid": 654300, "id": 3310, "area_id": 654301 }, { "area_name": "布尔津县", "pinyin": "Buerjin", "level": 3, "area_code": 906, "post_code": 836600, "pid": 654300, "id": 3311, "area_id": 654321 }, { "area_name": "富蕴县", "pinyin": "Fuyun", "level": 3, "area_code": 906, "post_code": 836100, "pid": 654300, "id": 3312, "area_id": 654322 }, { "area_name": "福海县", "pinyin": "Fuhai", "level": 3, "area_code": 906, "post_code": 836400, "pid": 654300, "id": 3313, "area_id": 654323 }, { "area_name": "哈巴河县", "pinyin": "Habahe", "level": 3, "area_code": 906, "post_code": 836700, "pid": 654300, "id": 3314, "area_id": 654324 }, { "area_name": "青河县", "pinyin": "Qinghe", "level": 3, "area_code": 906, "post_code": 836200, "pid": 654300, "id": 3315, "area_id": 654325 }, { "area_name": "吉木乃县", "pinyin": "Jimunai", "level": 3, "area_code": 906, "post_code": 836800, "pid": 654300, "id": 3316, "area_id": 654326 }, { "area_name": "直辖县级", "pinyin": "", "level": 2, "area_code": null, "post_code": null, "pid": 650000, "id": 3317, "area_id": 659000 }, { "area_name": "石河子市", "pinyin": "Shihezi", "level": 3, "area_code": 993, "post_code": 832000, "pid": 659000, "id": 3318, "area_id": 659001 }, { "area_name": "阿拉尔市", "pinyin": "Aral", "level": 3, "area_code": 997, "post_code": 843300, "pid": 659000, "id": 3319, "area_id": 659002 }, { "area_name": "图木舒克市", "pinyin": "Tumxuk", "level": 3, "area_code": 998, "post_code": 843806, "pid": 659000, "id": 3320, "area_id": 659003 }, { "area_name": "五家渠市", "pinyin": "Wujiaqu", "level": 3, "area_code": 994, "post_code": 831300, "pid": 659000, "id": 3321, "area_id": 659004 }, { "area_name": "北屯市", "pinyin": "Beitun", "level": 3, "area_code": 906, "post_code": 836000, "pid": 659000, "id": 3322, "area_id": 659005 }, { "area_name": "铁门关市", "pinyin": "Tiemenguan", "level": 3, "area_code": 906, "post_code": 836000, "pid": 659000, "id": 3323, "area_id": 659006 }, { "area_name": "双河市", "pinyin": "Shuanghe", "level": 3, "area_code": 909, "post_code": 833408, "pid": 659000, "id": 3324, "area_id": 659007 }, { "area_name": "台湾", "pinyin": "Taiwan", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3325, "area_id": 710000 }, { "area_name": "台北市", "pinyin": "Taipei", "level": 2, "area_code": 2, "post_code": 1, "pid": 710000, "id": 3326, "area_id": 710100 }, { "area_name": "松山区", "pinyin": "Songshan", "level": 3, "area_code": 2, "post_code": 105, "pid": 710100, "id": 3327, "area_id": 710101 }, { "area_name": "信义区", "pinyin": "Xinyi", "level": 3, "area_code": 2, "post_code": 110, "pid": 710100, "id": 3328, "area_id": 710102 }, { "area_name": "大安区", "pinyin": "Da'an", "level": 3, "area_code": 2, "post_code": 106, "pid": 710100, "id": 3329, "area_id": 710103 }, { "area_name": "中山区", "pinyin": "Zhongshan", "level": 3, "area_code": 2, "post_code": 104, "pid": 710100, "id": 3330, "area_id": 710104 }, { "area_name": "中正区", "pinyin": "Zhongzheng", "level": 3, "area_code": 2, "post_code": 100, "pid": 710100, "id": 3331, "area_id": 710105 }, { "area_name": "大同区", "pinyin": "Datong", "level": 3, "area_code": 2, "post_code": 103, "pid": 710100, "id": 3332, "area_id": 710106 }, { "area_name": "万华区", "pinyin": "Wanhua", "level": 3, "area_code": 2, "post_code": 108, "pid": 710100, "id": 3333, "area_id": 710107 }, { "area_name": "文山区", "pinyin": "Wenshan", "level": 3, "area_code": 2, "post_code": 116, "pid": 710100, "id": 3334, "area_id": 710108 }, { "area_name": "南港区", "pinyin": "Nangang", "level": 3, "area_code": 2, "post_code": 115, "pid": 710100, "id": 3335, "area_id": 710109 }, { "area_name": "内湖区", "pinyin": "Nahu", "level": 3, "area_code": 2, "post_code": 114, "pid": 710100, "id": 3336, "area_id": 710110 }, { "area_name": "士林区", "pinyin": "Shilin", "level": 3, "area_code": 2, "post_code": 111, "pid": 710100, "id": 3337, "area_id": 710111 }, { "area_name": "北投区", "pinyin": "Beitou", "level": 3, "area_code": 2, "post_code": 112, "pid": 710100, "id": 3338, "area_id": 710112 }, { "area_name": "高雄市", "pinyin": "Kaohsiung", "level": 2, "area_code": 7, "post_code": 8, "pid": 710000, "id": 3339, "area_id": 710200 }, { "area_name": "盐埕区", "pinyin": "Yancheng", "level": 3, "area_code": 7, "post_code": 803, "pid": 710200, "id": 3340, "area_id": 710201 }, { "area_name": "鼓山区", "pinyin": "Gushan", "level": 3, "area_code": 7, "post_code": 804, "pid": 710200, "id": 3341, "area_id": 710202 }, { "area_name": "左营区", "pinyin": "Zuoying", "level": 3, "area_code": 7, "post_code": 813, "pid": 710200, "id": 3342, "area_id": 710203 }, { "area_name": "楠梓区", "pinyin": "Nanzi", "level": 3, "area_code": 7, "post_code": 811, "pid": 710200, "id": 3343, "area_id": 710204 }, { "area_name": "三民区", "pinyin": "Sanmin", "level": 3, "area_code": 7, "post_code": 807, "pid": 710200, "id": 3344, "area_id": 710205 }, { "area_name": "新兴区", "pinyin": "Xinxing", "level": 3, "area_code": 7, "post_code": 800, "pid": 710200, "id": 3345, "area_id": 710206 }, { "area_name": "前金区", "pinyin": "Qianjin", "level": 3, "area_code": 7, "post_code": 801, "pid": 710200, "id": 3346, "area_id": 710207 }, { "area_name": "苓雅区", "pinyin": "Lingya", "level": 3, "area_code": 7, "post_code": 802, "pid": 710200, "id": 3347, "area_id": 710208 }, { "area_name": "前镇区", "pinyin": "Qianzhen", "level": 3, "area_code": 7, "post_code": 806, "pid": 710200, "id": 3348, "area_id": 710209 }, { "area_name": "旗津区", "pinyin": "Qijin", "level": 3, "area_code": 7, "post_code": 805, "pid": 710200, "id": 3349, "area_id": 710210 }, { "area_name": "小港区", "pinyin": "Xiaogang", "level": 3, "area_code": 7, "post_code": 812, "pid": 710200, "id": 3350, "area_id": 710211 }, { "area_name": "凤山区", "pinyin": "Fengshan", "level": 3, "area_code": 7, "post_code": 830, "pid": 710200, "id": 3351, "area_id": 710212 }, { "area_name": "林园区", "pinyin": "Linyuan", "level": 3, "area_code": 7, "post_code": 832, "pid": 710200, "id": 3352, "area_id": 710213 }, { "area_name": "大寮区", "pinyin": "Daliao", "level": 3, "area_code": 7, "post_code": 831, "pid": 710200, "id": 3353, "area_id": 710214 }, { "area_name": "大树区", "pinyin": "Dashu", "level": 3, "area_code": 7, "post_code": 840, "pid": 710200, "id": 3354, "area_id": 710215 }, { "area_name": "大社区", "pinyin": "Dashe", "level": 3, "area_code": 7, "post_code": 815, "pid": 710200, "id": 3355, "area_id": 710216 }, { "area_name": "仁武区", "pinyin": "Renwu", "level": 3, "area_code": 7, "post_code": 814, "pid": 710200, "id": 3356, "area_id": 710217 }, { "area_name": "鸟松区", "pinyin": "Niaosong", "level": 3, "area_code": 7, "post_code": 833, "pid": 710200, "id": 3357, "area_id": 710218 }, { "area_name": "冈山区", "pinyin": "Gangshan", "level": 3, "area_code": 7, "post_code": 820, "pid": 710200, "id": 3358, "area_id": 710219 }, { "area_name": "桥头区", "pinyin": "Qiaotou", "level": 3, "area_code": 7, "post_code": 825, "pid": 710200, "id": 3359, "area_id": 710220 }, { "area_name": "燕巢区", "pinyin": "Yanchao", "level": 3, "area_code": 7, "post_code": 824, "pid": 710200, "id": 3360, "area_id": 710221 }, { "area_name": "田寮区", "pinyin": "Tianliao", "level": 3, "area_code": 7, "post_code": 823, "pid": 710200, "id": 3361, "area_id": 710222 }, { "area_name": "阿莲区", "pinyin": "Alian", "level": 3, "area_code": 7, "post_code": 822, "pid": 710200, "id": 3362, "area_id": 710223 }, { "area_name": "路竹区", "pinyin": "Luzhu", "level": 3, "area_code": 7, "post_code": 821, "pid": 710200, "id": 3363, "area_id": 710224 }, { "area_name": "湖内区", "pinyin": "Huna", "level": 3, "area_code": 7, "post_code": 829, "pid": 710200, "id": 3364, "area_id": 710225 }, { "area_name": "茄萣区", "pinyin": "Qieding", "level": 3, "area_code": 7, "post_code": 852, "pid": 710200, "id": 3365, "area_id": 710226 }, { "area_name": "永安区", "pinyin": "Yong'an", "level": 3, "area_code": 7, "post_code": 828, "pid": 710200, "id": 3366, "area_id": 710227 }, { "area_name": "弥陀区", "pinyin": "Mituo", "level": 3, "area_code": 7, "post_code": 827, "pid": 710200, "id": 3367, "area_id": 710228 }, { "area_name": "梓官区", "pinyin": "Ziguan", "level": 3, "area_code": 7, "post_code": 826, "pid": 710200, "id": 3368, "area_id": 710229 }, { "area_name": "旗山区", "pinyin": "Qishan", "level": 3, "area_code": 7, "post_code": 842, "pid": 710200, "id": 3369, "area_id": 710230 }, { "area_name": "美浓区", "pinyin": "Meinong", "level": 3, "area_code": 7, "post_code": 843, "pid": 710200, "id": 3370, "area_id": 710231 }, { "area_name": "六龟区", "pinyin": "Liugui", "level": 3, "area_code": 7, "post_code": 844, "pid": 710200, "id": 3371, "area_id": 710232 }, { "area_name": "甲仙区", "pinyin": "Jiaxian", "level": 3, "area_code": 7, "post_code": 847, "pid": 710200, "id": 3372, "area_id": 710233 }, { "area_name": "杉林区", "pinyin": "Shanlin", "level": 3, "area_code": 7, "post_code": 846, "pid": 710200, "id": 3373, "area_id": 710234 }, { "area_name": "内门区", "pinyin": "Namen", "level": 3, "area_code": 7, "post_code": 845, "pid": 710200, "id": 3374, "area_id": 710235 }, { "area_name": "茂林区", "pinyin": "Maolin", "level": 3, "area_code": 7, "post_code": 851, "pid": 710200, "id": 3375, "area_id": 710236 }, { "area_name": "桃源区", "pinyin": "Taoyuan", "level": 3, "area_code": 7, "post_code": 848, "pid": 710200, "id": 3376, "area_id": 710237 }, { "area_name": "那玛夏区", "pinyin": "Namaxia", "level": 3, "area_code": 7, "post_code": 849, "pid": 710200, "id": 3377, "area_id": 710238 }, { "area_name": "基隆市", "pinyin": "Keelung", "level": 2, "area_code": 2, "post_code": 2, "pid": 710000, "id": 3378, "area_id": 710300 }, { "area_name": "中正区", "pinyin": "Zhongzheng", "level": 3, "area_code": 2, "post_code": 202, "pid": 710300, "id": 3379, "area_id": 710301 }, { "area_name": "七堵区", "pinyin": "Qidu", "level": 3, "area_code": 2, "post_code": 206, "pid": 710300, "id": 3380, "area_id": 710302 }, { "area_name": "暖暖区", "pinyin": "Nuannuan", "level": 3, "area_code": 2, "post_code": 205, "pid": 710300, "id": 3381, "area_id": 710303 }, { "area_name": "仁爱区", "pinyin": "Renai", "level": 3, "area_code": 2, "post_code": 200, "pid": 710300, "id": 3382, "area_id": 710304 }, { "area_name": "中山区", "pinyin": "Zhongshan", "level": 3, "area_code": 2, "post_code": 203, "pid": 710300, "id": 3383, "area_id": 710305 }, { "area_name": "安乐区", "pinyin": "Anle", "level": 3, "area_code": 2, "post_code": 204, "pid": 710300, "id": 3384, "area_id": 710306 }, { "area_name": "信义区", "pinyin": "Xinyi", "level": 3, "area_code": 2, "post_code": 201, "pid": 710300, "id": 3385, "area_id": 710307 }, { "area_name": "台中市", "pinyin": "Taichung", "level": 2, "area_code": 4, "post_code": 4, "pid": 710000, "id": 3386, "area_id": 710400 }, { "area_name": "中区", "pinyin": "Zhongqu", "level": 3, "area_code": 4, "post_code": 400, "pid": 710400, "id": 3387, "area_id": 710401 }, { "area_name": "东区", "pinyin": "Dongqu", "level": 3, "area_code": 4, "post_code": 401, "pid": 710400, "id": 3388, "area_id": 710402 }, { "area_name": "南区", "pinyin": "Nanqu", "level": 3, "area_code": 4, "post_code": 402, "pid": 710400, "id": 3389, "area_id": 710403 }, { "area_name": "西区", "pinyin": "Xiqu", "level": 3, "area_code": 4, "post_code": 403, "pid": 710400, "id": 3390, "area_id": 710404 }, { "area_name": "北区", "pinyin": "Beiqu", "level": 3, "area_code": 4, "post_code": 404, "pid": 710400, "id": 3391, "area_id": 710405 }, { "area_name": "西屯区", "pinyin": "Xitun", "level": 3, "area_code": 4, "post_code": 407, "pid": 710400, "id": 3392, "area_id": 710406 }, { "area_name": "南屯区", "pinyin": "Nantun", "level": 3, "area_code": 4, "post_code": 408, "pid": 710400, "id": 3393, "area_id": 710407 }, { "area_name": "北屯区", "pinyin": "Beitun", "level": 3, "area_code": 4, "post_code": 406, "pid": 710400, "id": 3394, "area_id": 710408 }, { "area_name": "丰原区", "pinyin": "Fengyuan", "level": 3, "area_code": 4, "post_code": 420, "pid": 710400, "id": 3395, "area_id": 710409 }, { "area_name": "东势区", "pinyin": "Dongshi", "level": 3, "area_code": 4, "post_code": 423, "pid": 710400, "id": 3396, "area_id": 710410 }, { "area_name": "大甲区", "pinyin": "Dajia", "level": 3, "area_code": 4, "post_code": 437, "pid": 710400, "id": 3397, "area_id": 710411 }, { "area_name": "清水区", "pinyin": "Qingshui", "level": 3, "area_code": 4, "post_code": 436, "pid": 710400, "id": 3398, "area_id": 710412 }, { "area_name": "沙鹿区", "pinyin": "Shalu", "level": 3, "area_code": 4, "post_code": 433, "pid": 710400, "id": 3399, "area_id": 710413 }, { "area_name": "梧栖区", "pinyin": "Wuqi", "level": 3, "area_code": 4, "post_code": 435, "pid": 710400, "id": 3400, "area_id": 710414 }, { "area_name": "后里区", "pinyin": "Houli", "level": 3, "area_code": 4, "post_code": 421, "pid": 710400, "id": 3401, "area_id": 710415 }, { "area_name": "神冈区", "pinyin": "Shengang", "level": 3, "area_code": 4, "post_code": 429, "pid": 710400, "id": 3402, "area_id": 710416 }, { "area_name": "潭子区", "pinyin": "Tanzi", "level": 3, "area_code": 4, "post_code": 427, "pid": 710400, "id": 3403, "area_id": 710417 }, { "area_name": "大雅区", "pinyin": "Daya", "level": 3, "area_code": 4, "post_code": 428, "pid": 710400, "id": 3404, "area_id": 710418 }, { "area_name": "新社区", "pinyin": "Xinshe", "level": 3, "area_code": 4, "post_code": 426, "pid": 710400, "id": 3405, "area_id": 710419 }, { "area_name": "石冈区", "pinyin": "Shigang", "level": 3, "area_code": 4, "post_code": 422, "pid": 710400, "id": 3406, "area_id": 710420 }, { "area_name": "外埔区", "pinyin": "Waipu", "level": 3, "area_code": 4, "post_code": 438, "pid": 710400, "id": 3407, "area_id": 710421 }, { "area_name": "大安区", "pinyin": "Da'an", "level": 3, "area_code": 4, "post_code": 439, "pid": 710400, "id": 3408, "area_id": 710422 }, { "area_name": "乌日区", "pinyin": "Wuri", "level": 3, "area_code": 4, "post_code": 414, "pid": 710400, "id": 3409, "area_id": 710423 }, { "area_name": "大肚区", "pinyin": "Dadu", "level": 3, "area_code": 4, "post_code": 432, "pid": 710400, "id": 3410, "area_id": 710424 }, { "area_name": "龙井区", "pinyin": "Longjing", "level": 3, "area_code": 4, "post_code": 434, "pid": 710400, "id": 3411, "area_id": 710425 }, { "area_name": "雾峰区", "pinyin": "Wufeng", "level": 3, "area_code": 4, "post_code": 413, "pid": 710400, "id": 3412, "area_id": 710426 }, { "area_name": "太平区", "pinyin": "Taiping", "level": 3, "area_code": 4, "post_code": 411, "pid": 710400, "id": 3413, "area_id": 710427 }, { "area_name": "大里区", "pinyin": "Dali", "level": 3, "area_code": 4, "post_code": 412, "pid": 710400, "id": 3414, "area_id": 710428 }, { "area_name": "和平区", "pinyin": "Heping", "level": 3, "area_code": 4, "post_code": 424, "pid": 710400, "id": 3415, "area_id": 710429 }, { "area_name": "台南市", "pinyin": "Tainan", "level": 2, "area_code": 6, "post_code": 7, "pid": 710000, "id": 3416, "area_id": 710500 }, { "area_name": "东区", "pinyin": "Dongqu", "level": 3, "area_code": 6, "post_code": 701, "pid": 710500, "id": 3417, "area_id": 710501 }, { "area_name": "南区", "pinyin": "Nanqu", "level": 3, "area_code": 6, "post_code": 702, "pid": 710500, "id": 3418, "area_id": 710502 }, { "area_name": "北区", "pinyin": "Beiqu", "level": 3, "area_code": 6, "post_code": 704, "pid": 710500, "id": 3419, "area_id": 710504 }, { "area_name": "安南区", "pinyin": "Annan", "level": 3, "area_code": 6, "post_code": 709, "pid": 710500, "id": 3420, "area_id": 710506 }, { "area_name": "安平区", "pinyin": "Anping", "level": 3, "area_code": 6, "post_code": 708, "pid": 710500, "id": 3421, "area_id": 710507 }, { "area_name": "中西区", "pinyin": "Zhongxi", "level": 3, "area_code": 6, "post_code": 700, "pid": 710500, "id": 3422, "area_id": 710508 }, { "area_name": "新营区", "pinyin": "Xinying", "level": 3, "area_code": 6, "post_code": 730, "pid": 710500, "id": 3423, "area_id": 710509 }, { "area_name": "盐水区", "pinyin": "Yanshui", "level": 3, "area_code": 6, "post_code": 737, "pid": 710500, "id": 3424, "area_id": 710510 }, { "area_name": "白河区", "pinyin": "Baihe", "level": 3, "area_code": 6, "post_code": 732, "pid": 710500, "id": 3425, "area_id": 710511 }, { "area_name": "柳营区", "pinyin": "Liuying", "level": 3, "area_code": 6, "post_code": 736, "pid": 710500, "id": 3426, "area_id": 710512 }, { "area_name": "后壁区", "pinyin": "Houbi", "level": 3, "area_code": 6, "post_code": 731, "pid": 710500, "id": 3427, "area_id": 710513 }, { "area_name": "东山区", "pinyin": "Dongshan", "level": 3, "area_code": 6, "post_code": 733, "pid": 710500, "id": 3428, "area_id": 710514 }, { "area_name": "麻豆区", "pinyin": "Madou", "level": 3, "area_code": 6, "post_code": 721, "pid": 710500, "id": 3429, "area_id": 710515 }, { "area_name": "下营区", "pinyin": "Xiaying", "level": 3, "area_code": 6, "post_code": 735, "pid": 710500, "id": 3430, "area_id": 710516 }, { "area_name": "六甲区", "pinyin": "Liujia", "level": 3, "area_code": 6, "post_code": 734, "pid": 710500, "id": 3431, "area_id": 710517 }, { "area_name": "官田区", "pinyin": "Guantian", "level": 3, "area_code": 6, "post_code": 720, "pid": 710500, "id": 3432, "area_id": 710518 }, { "area_name": "大内区", "pinyin": "Dana", "level": 3, "area_code": 6, "post_code": 742, "pid": 710500, "id": 3433, "area_id": 710519 }, { "area_name": "佳里区", "pinyin": "Jiali", "level": 3, "area_code": 6, "post_code": 722, "pid": 710500, "id": 3434, "area_id": 710520 }, { "area_name": "学甲区", "pinyin": "Xuejia", "level": 3, "area_code": 6, "post_code": 726, "pid": 710500, "id": 3435, "area_id": 710521 }, { "area_name": "西港区", "pinyin": "Xigang", "level": 3, "area_code": 6, "post_code": 723, "pid": 710500, "id": 3436, "area_id": 710522 }, { "area_name": "七股区", "pinyin": "Qigu", "level": 3, "area_code": 6, "post_code": 724, "pid": 710500, "id": 3437, "area_id": 710523 }, { "area_name": "将军区", "pinyin": "Jiangjun", "level": 3, "area_code": 6, "post_code": 725, "pid": 710500, "id": 3438, "area_id": 710524 }, { "area_name": "北门区", "pinyin": "Beimen", "level": 3, "area_code": 6, "post_code": 727, "pid": 710500, "id": 3439, "area_id": 710525 }, { "area_name": "新化区", "pinyin": "Xinhua", "level": 3, "area_code": 6, "post_code": 712, "pid": 710500, "id": 3440, "area_id": 710526 }, { "area_name": "善化区", "pinyin": "Shanhua", "level": 3, "area_code": 6, "post_code": 741, "pid": 710500, "id": 3441, "area_id": 710527 }, { "area_name": "新市区", "pinyin": "Xinshi", "level": 3, "area_code": 6, "post_code": 744, "pid": 710500, "id": 3442, "area_id": 710528 }, { "area_name": "安定区", "pinyin": "Anding", "level": 3, "area_code": 6, "post_code": 745, "pid": 710500, "id": 3443, "area_id": 710529 }, { "area_name": "山上区", "pinyin": "Shanshang", "level": 3, "area_code": 6, "post_code": 743, "pid": 710500, "id": 3444, "area_id": 710530 }, { "area_name": "玉井区", "pinyin": "Yujing", "level": 3, "area_code": 6, "post_code": 714, "pid": 710500, "id": 3445, "area_id": 710531 }, { "area_name": "楠西区", "pinyin": "Nanxi", "level": 3, "area_code": 6, "post_code": 715, "pid": 710500, "id": 3446, "area_id": 710532 }, { "area_name": "南化区", "pinyin": "Nanhua", "level": 3, "area_code": 6, "post_code": 716, "pid": 710500, "id": 3447, "area_id": 710533 }, { "area_name": "左镇区", "pinyin": "Zuozhen", "level": 3, "area_code": 6, "post_code": 713, "pid": 710500, "id": 3448, "area_id": 710534 }, { "area_name": "仁德区", "pinyin": "Rende", "level": 3, "area_code": 6, "post_code": 717, "pid": 710500, "id": 3449, "area_id": 710535 }, { "area_name": "归仁区", "pinyin": "Guiren", "level": 3, "area_code": 6, "post_code": 711, "pid": 710500, "id": 3450, "area_id": 710536 }, { "area_name": "关庙区", "pinyin": "Guanmiao", "level": 3, "area_code": 6, "post_code": 718, "pid": 710500, "id": 3451, "area_id": 710537 }, { "area_name": "龙崎区", "pinyin": "Longqi", "level": 3, "area_code": 6, "post_code": 719, "pid": 710500, "id": 3452, "area_id": 710538 }, { "area_name": "永康区", "pinyin": "Yongkang", "level": 3, "area_code": 6, "post_code": 710, "pid": 710500, "id": 3453, "area_id": 710539 }, { "area_name": "新竹市", "pinyin": "Hsinchu", "level": 2, "area_code": 3, "post_code": 3, "pid": 710000, "id": 3454, "area_id": 710600 }, { "area_name": "东区", "pinyin": "Dongqu", "level": 3, "area_code": 3, "post_code": 300, "pid": 710600, "id": 3455, "area_id": 710601 }, { "area_name": "北区", "pinyin": "Beiqu", "level": 3, "area_code": 3, "post_code": null, "pid": 710600, "id": 3456, "area_id": 710602 }, { "area_name": "香山区", "pinyin": "Xiangshan", "level": 3, "area_code": 3, "post_code": null, "pid": 710600, "id": 3457, "area_id": 710603 }, { "area_name": "嘉义市", "pinyin": "Chiayi", "level": 2, "area_code": 5, "post_code": 6, "pid": 710000, "id": 3458, "area_id": 710700 }, { "area_name": "东区", "pinyin": "Dongqu", "level": 3, "area_code": 5, "post_code": 600, "pid": 710700, "id": 3459, "area_id": 710701 }, { "area_name": "西区", "pinyin": "Xiqu", "level": 3, "area_code": 5, "post_code": 600, "pid": 710700, "id": 3460, "area_id": 710702 }, { "area_name": "新北市", "pinyin": "New Taipei", "level": 2, "area_code": 2, "post_code": 2, "pid": 710000, "id": 3461, "area_id": 710800 }, { "area_name": "板桥区", "pinyin": "Banqiao", "level": 3, "area_code": 2, "post_code": 220, "pid": 710800, "id": 3462, "area_id": 710801 }, { "area_name": "三重区", "pinyin": "Sanzhong", "level": 3, "area_code": 2, "post_code": 241, "pid": 710800, "id": 3463, "area_id": 710802 }, { "area_name": "中和区", "pinyin": "Zhonghe", "level": 3, "area_code": 2, "post_code": 235, "pid": 710800, "id": 3464, "area_id": 710803 }, { "area_name": "永和区", "pinyin": "Yonghe", "level": 3, "area_code": 2, "post_code": 234, "pid": 710800, "id": 3465, "area_id": 710804 }, { "area_name": "新庄区", "pinyin": "Xinzhuang", "level": 3, "area_code": 2, "post_code": 242, "pid": 710800, "id": 3466, "area_id": 710805 }, { "area_name": "新店区", "pinyin": "Xindian", "level": 3, "area_code": 2, "post_code": 231, "pid": 710800, "id": 3467, "area_id": 710806 }, { "area_name": "树林区", "pinyin": "Shulin", "level": 3, "area_code": 2, "post_code": 238, "pid": 710800, "id": 3468, "area_id": 710807 }, { "area_name": "莺歌区", "pinyin": "Yingge", "level": 3, "area_code": 2, "post_code": 239, "pid": 710800, "id": 3469, "area_id": 710808 }, { "area_name": "三峡区", "pinyin": "Sanxia", "level": 3, "area_code": 2, "post_code": 237, "pid": 710800, "id": 3470, "area_id": 710809 }, { "area_name": "淡水区", "pinyin": "Danshui", "level": 3, "area_code": 2, "post_code": 251, "pid": 710800, "id": 3471, "area_id": 710810 }, { "area_name": "汐止区", "pinyin": "Xizhi", "level": 3, "area_code": 2, "post_code": 221, "pid": 710800, "id": 3472, "area_id": 710811 }, { "area_name": "瑞芳区", "pinyin": "Ruifang", "level": 3, "area_code": 2, "post_code": 224, "pid": 710800, "id": 3473, "area_id": 710812 }, { "area_name": "土城区", "pinyin": "Tucheng", "level": 3, "area_code": 2, "post_code": 236, "pid": 710800, "id": 3474, "area_id": 710813 }, { "area_name": "芦洲区", "pinyin": "Luzhou", "level": 3, "area_code": 2, "post_code": 247, "pid": 710800, "id": 3475, "area_id": 710814 }, { "area_name": "五股区", "pinyin": "Wugu", "level": 3, "area_code": 2, "post_code": 248, "pid": 710800, "id": 3476, "area_id": 710815 }, { "area_name": "泰山区", "pinyin": "Taishan", "level": 3, "area_code": 2, "post_code": 243, "pid": 710800, "id": 3477, "area_id": 710816 }, { "area_name": "林口区", "pinyin": "Linkou", "level": 3, "area_code": 2, "post_code": 244, "pid": 710800, "id": 3478, "area_id": 710817 }, { "area_name": "深坑区", "pinyin": "Shenkeng", "level": 3, "area_code": 2, "post_code": 222, "pid": 710800, "id": 3479, "area_id": 710818 }, { "area_name": "石碇区", "pinyin": "Shiding", "level": 3, "area_code": 2, "post_code": 223, "pid": 710800, "id": 3480, "area_id": 710819 }, { "area_name": "坪林区", "pinyin": "Pinglin", "level": 3, "area_code": 2, "post_code": 232, "pid": 710800, "id": 3481, "area_id": 710820 }, { "area_name": "三芝区", "pinyin": "Sanzhi", "level": 3, "area_code": 2, "post_code": 252, "pid": 710800, "id": 3482, "area_id": 710821 }, { "area_name": "石门区", "pinyin": "Shimen", "level": 3, "area_code": 2, "post_code": 253, "pid": 710800, "id": 3483, "area_id": 710822 }, { "area_name": "八里区", "pinyin": "Bali", "level": 3, "area_code": 2, "post_code": 249, "pid": 710800, "id": 3484, "area_id": 710823 }, { "area_name": "平溪区", "pinyin": "Pingxi", "level": 3, "area_code": 2, "post_code": 226, "pid": 710800, "id": 3485, "area_id": 710824 }, { "area_name": "双溪区", "pinyin": "Shuangxi", "level": 3, "area_code": 2, "post_code": 227, "pid": 710800, "id": 3486, "area_id": 710825 }, { "area_name": "贡寮区", "pinyin": "Gongliao", "level": 3, "area_code": 2, "post_code": 228, "pid": 710800, "id": 3487, "area_id": 710826 }, { "area_name": "金山区", "pinyin": "Jinshan", "level": 3, "area_code": 2, "post_code": 208, "pid": 710800, "id": 3488, "area_id": 710827 }, { "area_name": "万里区", "pinyin": "Wanli", "level": 3, "area_code": 2, "post_code": 207, "pid": 710800, "id": 3489, "area_id": 710828 }, { "area_name": "乌来区", "pinyin": "Wulai", "level": 3, "area_code": 2, "post_code": 233, "pid": 710800, "id": 3490, "area_id": 710829 }, { "area_name": "宜兰县", "pinyin": "Yilan", "level": 2, "area_code": 3, "post_code": 2, "pid": 710000, "id": 3491, "area_id": 712200 }, { "area_name": "宜兰市", "pinyin": "Yilan", "level": 3, "area_code": 3, "post_code": 260, "pid": 712200, "id": 3492, "area_id": 712201 }, { "area_name": "罗东镇", "pinyin": "Luodong", "level": 3, "area_code": 3, "post_code": 265, "pid": 712200, "id": 3493, "area_id": 712221 }, { "area_name": "苏澳镇", "pinyin": "Suao", "level": 3, "area_code": 3, "post_code": 270, "pid": 712200, "id": 3494, "area_id": 712222 }, { "area_name": "头城镇", "pinyin": "Toucheng", "level": 3, "area_code": 3, "post_code": 261, "pid": 712200, "id": 3495, "area_id": 712223 }, { "area_name": "礁溪乡", "pinyin": "Jiaoxi", "level": 3, "area_code": 3, "post_code": 262, "pid": 712200, "id": 3496, "area_id": 712224 }, { "area_name": "壮围乡", "pinyin": "Zhuangwei", "level": 3, "area_code": 3, "post_code": 263, "pid": 712200, "id": 3497, "area_id": 712225 }, { "area_name": "员山乡", "pinyin": "Yuanshan", "level": 3, "area_code": 3, "post_code": 264, "pid": 712200, "id": 3498, "area_id": 712226 }, { "area_name": "冬山乡", "pinyin": "Dongshan", "level": 3, "area_code": 3, "post_code": 269, "pid": 712200, "id": 3499, "area_id": 712227 }, { "area_name": "五结乡", "pinyin": "Wujie", "level": 3, "area_code": 3, "post_code": 268, "pid": 712200, "id": 3500, "area_id": 712228 }, { "area_name": "三星乡", "pinyin": "Sanxing", "level": 3, "area_code": 3, "post_code": 266, "pid": 712200, "id": 3501, "area_id": 712229 }, { "area_name": "大同乡", "pinyin": "Datong", "level": 3, "area_code": 3, "post_code": 267, "pid": 712200, "id": 3502, "area_id": 712230 }, { "area_name": "南澳乡", "pinyin": "Nanao", "level": 3, "area_code": 3, "post_code": 272, "pid": 712200, "id": 3503, "area_id": 712231 }, { "area_name": "桃园县", "pinyin": "Taoyuan", "level": 2, "area_code": 3, "post_code": 3, "pid": 710000, "id": 3504, "area_id": 712300 }, { "area_name": "桃园市", "pinyin": "Taoyuan", "level": 3, "area_code": 3, "post_code": 330, "pid": 712300, "id": 3505, "area_id": 712301 }, { "area_name": "中坜市", "pinyin": "Zhongli", "level": 3, "area_code": 3, "post_code": 320, "pid": 712300, "id": 3506, "area_id": 712302 }, { "area_name": "平镇市", "pinyin": "Pingzhen", "level": 3, "area_code": 3, "post_code": 324, "pid": 712300, "id": 3507, "area_id": 712303 }, { "area_name": "八德市", "pinyin": "Bade", "level": 3, "area_code": 3, "post_code": 334, "pid": 712300, "id": 3508, "area_id": 712304 }, { "area_name": "杨梅市", "pinyin": "Yangmei", "level": 3, "area_code": 3, "post_code": 326, "pid": 712300, "id": 3509, "area_id": 712305 }, { "area_name": "芦竹市", "pinyin": "Luzhu", "level": 3, "area_code": 3, "post_code": 338, "pid": 712300, "id": 3510, "area_id": 712306 }, { "area_name": "大溪镇", "pinyin": "Daxi", "level": 3, "area_code": 3, "post_code": 335, "pid": 712300, "id": 3511, "area_id": 712321 }, { "area_name": "大园乡", "pinyin": "Dayuan", "level": 3, "area_code": 3, "post_code": 337, "pid": 712300, "id": 3512, "area_id": 712324 }, { "area_name": "龟山乡", "pinyin": "Guishan", "level": 3, "area_code": 3, "post_code": 333, "pid": 712300, "id": 3513, "area_id": 712325 }, { "area_name": "龙潭乡", "pinyin": "Longtan", "level": 3, "area_code": 3, "post_code": 325, "pid": 712300, "id": 3514, "area_id": 712327 }, { "area_name": "新屋乡", "pinyin": "Xinwu", "level": 3, "area_code": 3, "post_code": 327, "pid": 712300, "id": 3515, "area_id": 712329 }, { "area_name": "观音乡", "pinyin": "Guanyin", "level": 3, "area_code": 3, "post_code": 328, "pid": 712300, "id": 3516, "area_id": 712330 }, { "area_name": "复兴乡", "pinyin": "Fuxing", "level": 3, "area_code": 3, "post_code": 336, "pid": 712300, "id": 3517, "area_id": 712331 }, { "area_name": "新竹县", "pinyin": "Hsinchu", "level": 2, "area_code": 3, "post_code": 3, "pid": 710000, "id": 3518, "area_id": 712400 }, { "area_name": "竹北市", "pinyin": "Zhubei", "level": 3, "area_code": 3, "post_code": 302, "pid": 712400, "id": 3519, "area_id": 712401 }, { "area_name": "竹东镇", "pinyin": "Zhudong", "level": 3, "area_code": 3, "post_code": 310, "pid": 712400, "id": 3520, "area_id": 712421 }, { "area_name": "新埔镇", "pinyin": "Xinpu", "level": 3, "area_code": 3, "post_code": 305, "pid": 712400, "id": 3521, "area_id": 712422 }, { "area_name": "关西镇", "pinyin": "Guanxi", "level": 3, "area_code": 3, "post_code": 306, "pid": 712400, "id": 3522, "area_id": 712423 }, { "area_name": "湖口乡", "pinyin": "Hukou", "level": 3, "area_code": 3, "post_code": 303, "pid": 712400, "id": 3523, "area_id": 712424 }, { "area_name": "新丰乡", "pinyin": "Xinfeng", "level": 3, "area_code": 3, "post_code": 304, "pid": 712400, "id": 3524, "area_id": 712425 }, { "area_name": "芎林乡", "pinyin": "Xionglin", "level": 3, "area_code": 3, "post_code": 307, "pid": 712400, "id": 3525, "area_id": 712426 }, { "area_name": "横山乡", "pinyin": "Hengshan", "level": 3, "area_code": 3, "post_code": 312, "pid": 712400, "id": 3526, "area_id": 712427 }, { "area_name": "北埔乡", "pinyin": "Beipu", "level": 3, "area_code": 3, "post_code": 314, "pid": 712400, "id": 3527, "area_id": 712428 }, { "area_name": "宝山乡", "pinyin": "Baoshan", "level": 3, "area_code": 3, "post_code": 308, "pid": 712400, "id": 3528, "area_id": 712429 }, { "area_name": "峨眉乡", "pinyin": "Emei", "level": 3, "area_code": 3, "post_code": 315, "pid": 712400, "id": 3529, "area_id": 712430 }, { "area_name": "尖石乡", "pinyin": "Jianshi", "level": 3, "area_code": 3, "post_code": 313, "pid": 712400, "id": 3530, "area_id": 712431 }, { "area_name": "五峰乡", "pinyin": "Wufeng", "level": 3, "area_code": 3, "post_code": 311, "pid": 712400, "id": 3531, "area_id": 712432 }, { "area_name": "苗栗县", "pinyin": "Miaoli", "level": 2, "area_code": 37, "post_code": 3, "pid": 710000, "id": 3532, "area_id": 712500 }, { "area_name": "苗栗市", "pinyin": "Miaoli", "level": 3, "area_code": 37, "post_code": 360, "pid": 712500, "id": 3533, "area_id": 712501 }, { "area_name": "苑里镇", "pinyin": "Yuanli", "level": 3, "area_code": 37, "post_code": 358, "pid": 712500, "id": 3534, "area_id": 712521 }, { "area_name": "通霄镇", "pinyin": "Tongxiao", "level": 3, "area_code": 37, "post_code": 357, "pid": 712500, "id": 3535, "area_id": 712522 }, { "area_name": "竹南镇", "pinyin": "Zhunan", "level": 3, "area_code": 37, "post_code": 350, "pid": 712500, "id": 3536, "area_id": 712523 }, { "area_name": "头份镇", "pinyin": "Toufen", "level": 3, "area_code": 37, "post_code": 351, "pid": 712500, "id": 3537, "area_id": 712524 }, { "area_name": "后龙镇", "pinyin": "Houlong", "level": 3, "area_code": 37, "post_code": 356, "pid": 712500, "id": 3538, "area_id": 712525 }, { "area_name": "卓兰镇", "pinyin": "Zhuolan", "level": 3, "area_code": 37, "post_code": 369, "pid": 712500, "id": 3539, "area_id": 712526 }, { "area_name": "大湖乡", "pinyin": "Dahu", "level": 3, "area_code": 37, "post_code": 364, "pid": 712500, "id": 3540, "area_id": 712527 }, { "area_name": "公馆乡", "pinyin": "Gongguan", "level": 3, "area_code": 37, "post_code": 363, "pid": 712500, "id": 3541, "area_id": 712528 }, { "area_name": "铜锣乡", "pinyin": "Tongluo", "level": 3, "area_code": 37, "post_code": 366, "pid": 712500, "id": 3542, "area_id": 712529 }, { "area_name": "南庄乡", "pinyin": "Nanzhuang", "level": 3, "area_code": 37, "post_code": 353, "pid": 712500, "id": 3543, "area_id": 712530 }, { "area_name": "头屋乡", "pinyin": "Touwu", "level": 3, "area_code": 37, "post_code": 362, "pid": 712500, "id": 3544, "area_id": 712531 }, { "area_name": "三义乡", "pinyin": "Sanyi", "level": 3, "area_code": 37, "post_code": 367, "pid": 712500, "id": 3545, "area_id": 712532 }, { "area_name": "西湖乡", "pinyin": "Xihu", "level": 3, "area_code": 37, "post_code": 368, "pid": 712500, "id": 3546, "area_id": 712533 }, { "area_name": "造桥乡", "pinyin": "Zaoqiao", "level": 3, "area_code": 37, "post_code": 361, "pid": 712500, "id": 3547, "area_id": 712534 }, { "area_name": "三湾乡", "pinyin": "Sanwan", "level": 3, "area_code": 37, "post_code": 352, "pid": 712500, "id": 3548, "area_id": 712535 }, { "area_name": "狮潭乡", "pinyin": "Shitan", "level": 3, "area_code": 37, "post_code": 354, "pid": 712500, "id": 3549, "area_id": 712536 }, { "area_name": "泰安乡", "pinyin": "Tai'an", "level": 3, "area_code": 37, "post_code": 365, "pid": 712500, "id": 3550, "area_id": 712537 }, { "area_name": "彰化县", "pinyin": "Changhua", "level": 2, "area_code": 4, "post_code": 5, "pid": 710000, "id": 3551, "area_id": 712700 }, { "area_name": "彰化市", "pinyin": "Zhanghuashi", "level": 3, "area_code": 4, "post_code": 500, "pid": 712700, "id": 3552, "area_id": 712701 }, { "area_name": "鹿港镇", "pinyin": "Lugang", "level": 3, "area_code": 4, "post_code": 505, "pid": 712700, "id": 3553, "area_id": 712721 }, { "area_name": "和美镇", "pinyin": "Hemei", "level": 3, "area_code": 4, "post_code": 508, "pid": 712700, "id": 3554, "area_id": 712722 }, { "area_name": "线西乡", "pinyin": "Xianxi", "level": 3, "area_code": 4, "post_code": 507, "pid": 712700, "id": 3555, "area_id": 712723 }, { "area_name": "伸港乡", "pinyin": "Shengang", "level": 3, "area_code": 4, "post_code": 509, "pid": 712700, "id": 3556, "area_id": 712724 }, { "area_name": "福兴乡", "pinyin": "Fuxing", "level": 3, "area_code": 4, "post_code": 506, "pid": 712700, "id": 3557, "area_id": 712725 }, { "area_name": "秀水乡", "pinyin": "Xiushui", "level": 3, "area_code": 4, "post_code": 504, "pid": 712700, "id": 3558, "area_id": 712726 }, { "area_name": "花坛乡", "pinyin": "Huatan", "level": 3, "area_code": 4, "post_code": 503, "pid": 712700, "id": 3559, "area_id": 712727 }, { "area_name": "芬园乡", "pinyin": "Fenyuan", "level": 3, "area_code": 4, "post_code": 502, "pid": 712700, "id": 3560, "area_id": 712728 }, { "area_name": "员林镇", "pinyin": "Yuanlin", "level": 3, "area_code": 4, "post_code": 510, "pid": 712700, "id": 3561, "area_id": 712729 }, { "area_name": "溪湖镇", "pinyin": "Xihu", "level": 3, "area_code": 4, "post_code": 514, "pid": 712700, "id": 3562, "area_id": 712730 }, { "area_name": "田中镇", "pinyin": "Tianzhong", "level": 3, "area_code": 4, "post_code": 520, "pid": 712700, "id": 3563, "area_id": 712731 }, { "area_name": "大村乡", "pinyin": "Dacun", "level": 3, "area_code": 4, "post_code": 515, "pid": 712700, "id": 3564, "area_id": 712732 }, { "area_name": "埔盐乡", "pinyin": "Puyan", "level": 3, "area_code": 4, "post_code": 516, "pid": 712700, "id": 3565, "area_id": 712733 }, { "area_name": "埔心乡", "pinyin": "Puxin", "level": 3, "area_code": 4, "post_code": 513, "pid": 712700, "id": 3566, "area_id": 712734 }, { "area_name": "永靖乡", "pinyin": "Yongjing", "level": 3, "area_code": 4, "post_code": 512, "pid": 712700, "id": 3567, "area_id": 712735 }, { "area_name": "社头乡", "pinyin": "Shetou", "level": 3, "area_code": 4, "post_code": 511, "pid": 712700, "id": 3568, "area_id": 712736 }, { "area_name": "二水乡", "pinyin": "Ershui", "level": 3, "area_code": 4, "post_code": 530, "pid": 712700, "id": 3569, "area_id": 712737 }, { "area_name": "北斗镇", "pinyin": "Beidou", "level": 3, "area_code": 4, "post_code": 521, "pid": 712700, "id": 3570, "area_id": 712738 }, { "area_name": "二林镇", "pinyin": "Erlin", "level": 3, "area_code": 4, "post_code": 526, "pid": 712700, "id": 3571, "area_id": 712739 }, { "area_name": "田尾乡", "pinyin": "Tianwei", "level": 3, "area_code": 4, "post_code": 522, "pid": 712700, "id": 3572, "area_id": 712740 }, { "area_name": "埤头乡", "pinyin": "Pitou", "level": 3, "area_code": 4, "post_code": 523, "pid": 712700, "id": 3573, "area_id": 712741 }, { "area_name": "芳苑乡", "pinyin": "Fangyuan", "level": 3, "area_code": 4, "post_code": 528, "pid": 712700, "id": 3574, "area_id": 712742 }, { "area_name": "大城乡", "pinyin": "Dacheng", "level": 3, "area_code": 4, "post_code": 527, "pid": 712700, "id": 3575, "area_id": 712743 }, { "area_name": "竹塘乡", "pinyin": "Zhutang", "level": 3, "area_code": 4, "post_code": 525, "pid": 712700, "id": 3576, "area_id": 712744 }, { "area_name": "溪州乡", "pinyin": "Xizhou", "level": 3, "area_code": 4, "post_code": 524, "pid": 712700, "id": 3577, "area_id": 712745 }, { "area_name": "南投县", "pinyin": "Nantou", "level": 2, "area_code": 49, "post_code": 5, "pid": 710000, "id": 3578, "area_id": 712800 }, { "area_name": "南投市", "pinyin": "Nantoushi", "level": 3, "area_code": 49, "post_code": 540, "pid": 712800, "id": 3579, "area_id": 712801 }, { "area_name": "埔里镇", "pinyin": "Puli", "level": 3, "area_code": 49, "post_code": 545, "pid": 712800, "id": 3580, "area_id": 712821 }, { "area_name": "草屯镇", "pinyin": "Caotun", "level": 3, "area_code": 49, "post_code": 542, "pid": 712800, "id": 3581, "area_id": 712822 }, { "area_name": "竹山镇", "pinyin": "Zhushan", "level": 3, "area_code": 49, "post_code": 557, "pid": 712800, "id": 3582, "area_id": 712823 }, { "area_name": "集集镇", "pinyin": "Jiji", "level": 3, "area_code": 49, "post_code": 552, "pid": 712800, "id": 3583, "area_id": 712824 }, { "area_name": "名间乡", "pinyin": "Mingjian", "level": 3, "area_code": 49, "post_code": 551, "pid": 712800, "id": 3584, "area_id": 712825 }, { "area_name": "鹿谷乡", "pinyin": "Lugu", "level": 3, "area_code": 49, "post_code": 558, "pid": 712800, "id": 3585, "area_id": 712826 }, { "area_name": "中寮乡", "pinyin": "Zhongliao", "level": 3, "area_code": 49, "post_code": 541, "pid": 712800, "id": 3586, "area_id": 712827 }, { "area_name": "鱼池乡", "pinyin": "Yuchi", "level": 3, "area_code": 49, "post_code": 555, "pid": 712800, "id": 3587, "area_id": 712828 }, { "area_name": "国姓乡", "pinyin": "Guoxing", "level": 3, "area_code": 49, "post_code": 544, "pid": 712800, "id": 3588, "area_id": 712829 }, { "area_name": "水里乡", "pinyin": "Shuili", "level": 3, "area_code": 49, "post_code": 553, "pid": 712800, "id": 3589, "area_id": 712830 }, { "area_name": "信义乡", "pinyin": "Xinyi", "level": 3, "area_code": 49, "post_code": 556, "pid": 712800, "id": 3590, "area_id": 712831 }, { "area_name": "仁爱乡", "pinyin": "Renai", "level": 3, "area_code": 49, "post_code": 546, "pid": 712800, "id": 3591, "area_id": 712832 }, { "area_name": "云林县", "pinyin": "Yunlin", "level": 2, "area_code": 5, "post_code": 6, "pid": 710000, "id": 3592, "area_id": 712900 }, { "area_name": "斗六市", "pinyin": "Douliu", "level": 3, "area_code": 5, "post_code": 640, "pid": 712900, "id": 3593, "area_id": 712901 }, { "area_name": "斗南镇", "pinyin": "Dounan", "level": 3, "area_code": 5, "post_code": 630, "pid": 712900, "id": 3594, "area_id": 712921 }, { "area_name": "虎尾镇", "pinyin": "Huwei", "level": 3, "area_code": 5, "post_code": 632, "pid": 712900, "id": 3595, "area_id": 712922 }, { "area_name": "西螺镇", "pinyin": "Xiluo", "level": 3, "area_code": 5, "post_code": 648, "pid": 712900, "id": 3596, "area_id": 712923 }, { "area_name": "土库镇", "pinyin": "Tuku", "level": 3, "area_code": 5, "post_code": 633, "pid": 712900, "id": 3597, "area_id": 712924 }, { "area_name": "北港镇", "pinyin": "Beigang", "level": 3, "area_code": 5, "post_code": 651, "pid": 712900, "id": 3598, "area_id": 712925 }, { "area_name": "古坑乡", "pinyin": "Gukeng", "level": 3, "area_code": 5, "post_code": 646, "pid": 712900, "id": 3599, "area_id": 712926 }, { "area_name": "大埤乡", "pinyin": "Dapi", "level": 3, "area_code": 5, "post_code": 631, "pid": 712900, "id": 3600, "area_id": 712927 }, { "area_name": "莿桐乡", "pinyin": "Citong", "level": 3, "area_code": 5, "post_code": 647, "pid": 712900, "id": 3601, "area_id": 712928 }, { "area_name": "林内乡", "pinyin": "Linna", "level": 3, "area_code": 5, "post_code": 643, "pid": 712900, "id": 3602, "area_id": 712929 }, { "area_name": "二仑乡", "pinyin": "Erlun", "level": 3, "area_code": 5, "post_code": 649, "pid": 712900, "id": 3603, "area_id": 712930 }, { "area_name": "仑背乡", "pinyin": "Lunbei", "level": 3, "area_code": 5, "post_code": 637, "pid": 712900, "id": 3604, "area_id": 712931 }, { "area_name": "麦寮乡", "pinyin": "Mailiao", "level": 3, "area_code": 5, "post_code": 638, "pid": 712900, "id": 3605, "area_id": 712932 }, { "area_name": "东势乡", "pinyin": "Dongshi", "level": 3, "area_code": 5, "post_code": 635, "pid": 712900, "id": 3606, "area_id": 712933 }, { "area_name": "褒忠乡", "pinyin": "Baozhong", "level": 3, "area_code": 5, "post_code": 634, "pid": 712900, "id": 3607, "area_id": 712934 }, { "area_name": "台西乡", "pinyin": "Taixi", "level": 3, "area_code": 5, "post_code": 636, "pid": 712900, "id": 3608, "area_id": 712935 }, { "area_name": "元长乡", "pinyin": "Yuanchang", "level": 3, "area_code": 5, "post_code": 655, "pid": 712900, "id": 3609, "area_id": 712936 }, { "area_name": "四湖乡", "pinyin": "Sihu", "level": 3, "area_code": 5, "post_code": 654, "pid": 712900, "id": 3610, "area_id": 712937 }, { "area_name": "口湖乡", "pinyin": "Kouhu", "level": 3, "area_code": 5, "post_code": 653, "pid": 712900, "id": 3611, "area_id": 712938 }, { "area_name": "水林乡", "pinyin": "Shuilin", "level": 3, "area_code": 5, "post_code": 652, "pid": 712900, "id": 3612, "area_id": 712939 }, { "area_name": "嘉义县", "pinyin": "Chiayi", "level": 2, "area_code": 5, "post_code": 6, "pid": 710000, "id": 3613, "area_id": 713000 }, { "area_name": "太保市", "pinyin": "Taibao", "level": 3, "area_code": 5, "post_code": 612, "pid": 713000, "id": 3614, "area_id": 713001 }, { "area_name": "朴子市", "pinyin": "Puzi", "level": 3, "area_code": 5, "post_code": 613, "pid": 713000, "id": 3615, "area_id": 713002 }, { "area_name": "布袋镇", "pinyin": "Budai", "level": 3, "area_code": 5, "post_code": 625, "pid": 713000, "id": 3616, "area_id": 713023 }, { "area_name": "大林镇", "pinyin": "Dalin", "level": 3, "area_code": 5, "post_code": 622, "pid": 713000, "id": 3617, "area_id": 713024 }, { "area_name": "民雄乡", "pinyin": "Minxiong", "level": 3, "area_code": 5, "post_code": 621, "pid": 713000, "id": 3618, "area_id": 713025 }, { "area_name": "溪口乡", "pinyin": "Xikou", "level": 3, "area_code": 5, "post_code": 623, "pid": 713000, "id": 3619, "area_id": 713026 }, { "area_name": "新港乡", "pinyin": "Xingang", "level": 3, "area_code": 5, "post_code": 616, "pid": 713000, "id": 3620, "area_id": 713027 }, { "area_name": "六脚乡", "pinyin": "Liujiao", "level": 3, "area_code": 5, "post_code": 615, "pid": 713000, "id": 3621, "area_id": 713028 }, { "area_name": "东石乡", "pinyin": "Dongshi", "level": 3, "area_code": 5, "post_code": 614, "pid": 713000, "id": 3622, "area_id": 713029 }, { "area_name": "义竹乡", "pinyin": "Yizhu", "level": 3, "area_code": 5, "post_code": 624, "pid": 713000, "id": 3623, "area_id": 713030 }, { "area_name": "鹿草乡", "pinyin": "Lucao", "level": 3, "area_code": 5, "post_code": 611, "pid": 713000, "id": 3624, "area_id": 713031 }, { "area_name": "水上乡", "pinyin": "Shuishang", "level": 3, "area_code": 5, "post_code": 608, "pid": 713000, "id": 3625, "area_id": 713032 }, { "area_name": "中埔乡", "pinyin": "Zhongpu", "level": 3, "area_code": 5, "post_code": 606, "pid": 713000, "id": 3626, "area_id": 713033 }, { "area_name": "竹崎乡", "pinyin": "Zhuqi", "level": 3, "area_code": 5, "post_code": 604, "pid": 713000, "id": 3627, "area_id": 713034 }, { "area_name": "梅山乡", "pinyin": "Meishan", "level": 3, "area_code": 5, "post_code": 603, "pid": 713000, "id": 3628, "area_id": 713035 }, { "area_name": "番路乡", "pinyin": "Fanlu", "level": 3, "area_code": 5, "post_code": 602, "pid": 713000, "id": 3629, "area_id": 713036 }, { "area_name": "大埔乡", "pinyin": "Dapu", "level": 3, "area_code": 5, "post_code": 607, "pid": 713000, "id": 3630, "area_id": 713037 }, { "area_name": "阿里山乡", "pinyin": "Alishan", "level": 3, "area_code": 5, "post_code": 605, "pid": 713000, "id": 3631, "area_id": 713038 }, { "area_name": "屏东县", "pinyin": "Pingtung", "level": 2, "area_code": 8, "post_code": 9, "pid": 710000, "id": 3632, "area_id": 713300 }, { "area_name": "屏东市", "pinyin": "Pingdong", "level": 3, "area_code": 8, "post_code": 900, "pid": 713300, "id": 3633, "area_id": 713301 }, { "area_name": "潮州镇", "pinyin": "Chaozhou", "level": 3, "area_code": 8, "post_code": 920, "pid": 713300, "id": 3634, "area_id": 713321 }, { "area_name": "东港镇", "pinyin": "Donggang", "level": 3, "area_code": 8, "post_code": 928, "pid": 713300, "id": 3635, "area_id": 713322 }, { "area_name": "恒春镇", "pinyin": "Hengchun", "level": 3, "area_code": 8, "post_code": 946, "pid": 713300, "id": 3636, "area_id": 713323 }, { "area_name": "万丹乡", "pinyin": "Wandan", "level": 3, "area_code": 8, "post_code": 913, "pid": 713300, "id": 3637, "area_id": 713324 }, { "area_name": "长治乡", "pinyin": "Changzhi", "level": 3, "area_code": 8, "post_code": 908, "pid": 713300, "id": 3638, "area_id": 713325 }, { "area_name": "麟洛乡", "pinyin": "Linluo", "level": 3, "area_code": 8, "post_code": 909, "pid": 713300, "id": 3639, "area_id": 713326 }, { "area_name": "九如乡", "pinyin": "Jiuru", "level": 3, "area_code": 8, "post_code": 904, "pid": 713300, "id": 3640, "area_id": 713327 }, { "area_name": "里港乡", "pinyin": "Ligang", "level": 3, "area_code": 8, "post_code": 905, "pid": 713300, "id": 3641, "area_id": 713328 }, { "area_name": "盐埔乡", "pinyin": "Yanpu", "level": 3, "area_code": 8, "post_code": 907, "pid": 713300, "id": 3642, "area_id": 713329 }, { "area_name": "高树乡", "pinyin": "Gaoshu", "level": 3, "area_code": 8, "post_code": 906, "pid": 713300, "id": 3643, "area_id": 713330 }, { "area_name": "万峦乡", "pinyin": "Wanluan", "level": 3, "area_code": 8, "post_code": 923, "pid": 713300, "id": 3644, "area_id": 713331 }, { "area_name": "内埔乡", "pinyin": "Napu", "level": 3, "area_code": 8, "post_code": 912, "pid": 713300, "id": 3645, "area_id": 713332 }, { "area_name": "竹田乡", "pinyin": "Zhutian", "level": 3, "area_code": 8, "post_code": 911, "pid": 713300, "id": 3646, "area_id": 713333 }, { "area_name": "新埤乡", "pinyin": "Xinpi", "level": 3, "area_code": 8, "post_code": 925, "pid": 713300, "id": 3647, "area_id": 713334 }, { "area_name": "枋寮乡", "pinyin": "Fangliao", "level": 3, "area_code": 8, "post_code": 940, "pid": 713300, "id": 3648, "area_id": 713335 }, { "area_name": "新园乡", "pinyin": "Xinyuan", "level": 3, "area_code": 8, "post_code": 932, "pid": 713300, "id": 3649, "area_id": 713336 }, { "area_name": "崁顶乡", "pinyin": "Kanding", "level": 3, "area_code": 8, "post_code": 924, "pid": 713300, "id": 3650, "area_id": 713337 }, { "area_name": "林边乡", "pinyin": "Linbian", "level": 3, "area_code": 8, "post_code": 927, "pid": 713300, "id": 3651, "area_id": 713338 }, { "area_name": "南州乡", "pinyin": "Nanzhou", "level": 3, "area_code": 8, "post_code": 926, "pid": 713300, "id": 3652, "area_id": 713339 }, { "area_name": "佳冬乡", "pinyin": "Jiadong", "level": 3, "area_code": 8, "post_code": 931, "pid": 713300, "id": 3653, "area_id": 713340 }, { "area_name": "琉球乡", "pinyin": "Liuqiu", "level": 3, "area_code": 8, "post_code": 929, "pid": 713300, "id": 3654, "area_id": 713341 }, { "area_name": "车城乡", "pinyin": "Checheng", "level": 3, "area_code": 8, "post_code": 944, "pid": 713300, "id": 3655, "area_id": 713342 }, { "area_name": "满州乡", "pinyin": "Manzhou", "level": 3, "area_code": 8, "post_code": 947, "pid": 713300, "id": 3656, "area_id": 713343 }, { "area_name": "枋山乡", "pinyin": "Fangshan", "level": 3, "area_code": 8, "post_code": 941, "pid": 713300, "id": 3657, "area_id": 713344 }, { "area_name": "三地门乡", "pinyin": "Sandimen", "level": 3, "area_code": 8, "post_code": 901, "pid": 713300, "id": 3658, "area_id": 713345 }, { "area_name": "雾台乡", "pinyin": "Wutai", "level": 3, "area_code": 8, "post_code": 902, "pid": 713300, "id": 3659, "area_id": 713346 }, { "area_name": "玛家乡", "pinyin": "Majia", "level": 3, "area_code": 8, "post_code": 903, "pid": 713300, "id": 3660, "area_id": 713347 }, { "area_name": "泰武乡", "pinyin": "Taiwu", "level": 3, "area_code": 8, "post_code": 921, "pid": 713300, "id": 3661, "area_id": 713348 }, { "area_name": "来义乡", "pinyin": "Laiyi", "level": 3, "area_code": 8, "post_code": 922, "pid": 713300, "id": 3662, "area_id": 713349 }, { "area_name": "春日乡", "pinyin": "Chunri", "level": 3, "area_code": 8, "post_code": 942, "pid": 713300, "id": 3663, "area_id": 713350 }, { "area_name": "狮子乡", "pinyin": "Shizi", "level": 3, "area_code": 8, "post_code": 943, "pid": 713300, "id": 3664, "area_id": 713351 }, { "area_name": "牡丹乡", "pinyin": "Mudan", "level": 3, "area_code": 8, "post_code": 945, "pid": 713300, "id": 3665, "area_id": 713352 }, { "area_name": "台东县", "pinyin": "Taitung", "level": 2, "area_code": 89, "post_code": 9, "pid": 710000, "id": 3666, "area_id": 713400 }, { "area_name": "台东市", "pinyin": "Taidong", "level": 3, "area_code": 89, "post_code": 950, "pid": 713400, "id": 3667, "area_id": 713401 }, { "area_name": "成功镇", "pinyin": "Chenggong", "level": 3, "area_code": 89, "post_code": 961, "pid": 713400, "id": 3668, "area_id": 713421 }, { "area_name": "关山镇", "pinyin": "Guanshan", "level": 3, "area_code": 89, "post_code": 956, "pid": 713400, "id": 3669, "area_id": 713422 }, { "area_name": "卑南乡", "pinyin": "Beinan", "level": 3, "area_code": 89, "post_code": 954, "pid": 713400, "id": 3670, "area_id": 713423 }, { "area_name": "鹿野乡", "pinyin": "Luye", "level": 3, "area_code": 89, "post_code": 955, "pid": 713400, "id": 3671, "area_id": 713424 }, { "area_name": "池上乡", "pinyin": "Chishang", "level": 3, "area_code": 89, "post_code": 958, "pid": 713400, "id": 3672, "area_id": 713425 }, { "area_name": "东河乡", "pinyin": "Donghe", "level": 3, "area_code": 89, "post_code": 959, "pid": 713400, "id": 3673, "area_id": 713426 }, { "area_name": "长滨乡", "pinyin": "Changbin", "level": 3, "area_code": 89, "post_code": 962, "pid": 713400, "id": 3674, "area_id": 713427 }, { "area_name": "太麻里乡", "pinyin": "Taimali", "level": 3, "area_code": 89, "post_code": 963, "pid": 713400, "id": 3675, "area_id": 713428 }, { "area_name": "大武乡", "pinyin": "Dawu", "level": 3, "area_code": 89, "post_code": 965, "pid": 713400, "id": 3676, "area_id": 713429 }, { "area_name": "绿岛乡", "pinyin": "Lvdao", "level": 3, "area_code": 89, "post_code": 951, "pid": 713400, "id": 3677, "area_id": 713430 }, { "area_name": "海端乡", "pinyin": "Haiduan", "level": 3, "area_code": 89, "post_code": 957, "pid": 713400, "id": 3678, "area_id": 713431 }, { "area_name": "延平乡", "pinyin": "Yanping", "level": 3, "area_code": 89, "post_code": 953, "pid": 713400, "id": 3679, "area_id": 713432 }, { "area_name": "金峰乡", "pinyin": "Jinfeng", "level": 3, "area_code": 89, "post_code": 964, "pid": 713400, "id": 3680, "area_id": 713433 }, { "area_name": "达仁乡", "pinyin": "Daren", "level": 3, "area_code": 89, "post_code": 966, "pid": 713400, "id": 3681, "area_id": 713434 }, { "area_name": "兰屿乡", "pinyin": "Lanyu", "level": 3, "area_code": 89, "post_code": 952, "pid": 713400, "id": 3682, "area_id": 713435 }, { "area_name": "花莲县", "pinyin": "Hualien", "level": 2, "area_code": 3, "post_code": 9, "pid": 710000, "id": 3683, "area_id": 713500 }, { "area_name": "花莲市", "pinyin": "Hualian", "level": 3, "area_code": 3, "post_code": 970, "pid": 713500, "id": 3684, "area_id": 713501 }, { "area_name": "凤林镇", "pinyin": "Fenglin", "level": 3, "area_code": 3, "post_code": 975, "pid": 713500, "id": 3685, "area_id": 713521 }, { "area_name": "玉里镇", "pinyin": "Yuli", "level": 3, "area_code": 3, "post_code": 981, "pid": 713500, "id": 3686, "area_id": 713522 }, { "area_name": "新城乡", "pinyin": "Xincheng", "level": 3, "area_code": 3, "post_code": 971, "pid": 713500, "id": 3687, "area_id": 713523 }, { "area_name": "吉安乡", "pinyin": "Ji'an", "level": 3, "area_code": 3, "post_code": 973, "pid": 713500, "id": 3688, "area_id": 713524 }, { "area_name": "寿丰乡", "pinyin": "Shoufeng", "level": 3, "area_code": 3, "post_code": 974, "pid": 713500, "id": 3689, "area_id": 713525 }, { "area_name": "光复乡", "pinyin": "Guangfu", "level": 3, "area_code": 3, "post_code": 976, "pid": 713500, "id": 3690, "area_id": 713526 }, { "area_name": "丰滨乡", "pinyin": "Fengbin", "level": 3, "area_code": 3, "post_code": 977, "pid": 713500, "id": 3691, "area_id": 713527 }, { "area_name": "瑞穗乡", "pinyin": "Ruisui", "level": 3, "area_code": 3, "post_code": 978, "pid": 713500, "id": 3692, "area_id": 713528 }, { "area_name": "富里乡", "pinyin": "Fuli", "level": 3, "area_code": 3, "post_code": 983, "pid": 713500, "id": 3693, "area_id": 713529 }, { "area_name": "秀林乡", "pinyin": "Xiulin", "level": 3, "area_code": 3, "post_code": 972, "pid": 713500, "id": 3694, "area_id": 713530 }, { "area_name": "万荣乡", "pinyin": "Wanrong", "level": 3, "area_code": 3, "post_code": 979, "pid": 713500, "id": 3695, "area_id": 713531 }, { "area_name": "卓溪乡", "pinyin": "Zhuoxi", "level": 3, "area_code": 3, "post_code": 982, "pid": 713500, "id": 3696, "area_id": 713532 }, { "area_name": "澎湖县", "pinyin": "Penghu", "level": 2, "area_code": 6, "post_code": 8, "pid": 710000, "id": 3697, "area_id": 713600 }, { "area_name": "马公市", "pinyin": "Magong", "level": 3, "area_code": 6, "post_code": 880, "pid": 713600, "id": 3698, "area_id": 713601 }, { "area_name": "湖西乡", "pinyin": "Huxi", "level": 3, "area_code": 6, "post_code": 885, "pid": 713600, "id": 3699, "area_id": 713621 }, { "area_name": "白沙乡", "pinyin": "Baisha", "level": 3, "area_code": 6, "post_code": 884, "pid": 713600, "id": 3700, "area_id": 713622 }, { "area_name": "西屿乡", "pinyin": "Xiyu", "level": 3, "area_code": 6, "post_code": 881, "pid": 713600, "id": 3701, "area_id": 713623 }, { "area_name": "望安乡", "pinyin": "Wang'an", "level": 3, "area_code": 6, "post_code": 882, "pid": 713600, "id": 3702, "area_id": 713624 }, { "area_name": "七美乡", "pinyin": "Qimei", "level": 3, "area_code": 6, "post_code": 883, "pid": 713600, "id": 3703, "area_id": 713625 }, { "area_name": "金门县", "pinyin": "Jinmen", "level": 2, "area_code": 82, "post_code": 8, "pid": 710000, "id": 3704, "area_id": 713700 }, { "area_name": "金城镇", "pinyin": "Jincheng", "level": 3, "area_code": 82, "post_code": 893, "pid": 713700, "id": 3705, "area_id": 713701 }, { "area_name": "金湖镇", "pinyin": "Jinhu", "level": 3, "area_code": 82, "post_code": 891, "pid": 713700, "id": 3706, "area_id": 713702 }, { "area_name": "金沙镇", "pinyin": "Jinsha", "level": 3, "area_code": 82, "post_code": 890, "pid": 713700, "id": 3707, "area_id": 713703 }, { "area_name": "金宁乡", "pinyin": "Jinning", "level": 3, "area_code": 82, "post_code": 892, "pid": 713700, "id": 3708, "area_id": 713704 }, { "area_name": "烈屿乡", "pinyin": "Lieyu", "level": 3, "area_code": 82, "post_code": 894, "pid": 713700, "id": 3709, "area_id": 713705 }, { "area_name": "乌丘乡", "pinyin": "Wuqiu", "level": 3, "area_code": 82, "post_code": 896, "pid": 713700, "id": 3710, "area_id": 713706 }, { "area_name": "连江县", "pinyin": "Lienchiang", "level": 2, "area_code": 836, "post_code": 2, "pid": 710000, "id": 3711, "area_id": 713800 }, { "area_name": "南竿乡", "pinyin": "Nangan", "level": 3, "area_code": 836, "post_code": 209, "pid": 713800, "id": 3712, "area_id": 713801 }, { "area_name": "北竿乡", "pinyin": "Beigan", "level": 3, "area_code": 836, "post_code": 210, "pid": 713800, "id": 3713, "area_id": 713802 }, { "area_name": "莒光乡", "pinyin": "Juguang", "level": 3, "area_code": 836, "post_code": 211, "pid": 713800, "id": 3714, "area_id": 713803 }, { "area_name": "东引乡", "pinyin": "Dongyin", "level": 3, "area_code": 836, "post_code": 212, "pid": 713800, "id": 3715, "area_id": 713804 }, { "area_name": "香港特别行政区", "pinyin": "Hong Kong", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3716, "area_id": 810000 }, { "area_name": "香港岛", "pinyin": "Hong Kong Island", "level": 2, "area_code": 852, "post_code": 999077, "pid": 810000, "id": 3717, "area_id": 810100 }, { "area_name": "中西区", "pinyin": "Central and Western District", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810100, "id": 3718, "area_id": 810101 }, { "area_name": "湾仔区", "pinyin": "Wan Chai District", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810100, "id": 3719, "area_id": 810102 }, { "area_name": "东区", "pinyin": "Eastern District", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810100, "id": 3720, "area_id": 810103 }, { "area_name": "南区", "pinyin": "Southern District", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810100, "id": 3721, "area_id": 810104 }, { "area_name": "九龙", "pinyin": "Kowloon", "level": 2, "area_code": 852, "post_code": 999077, "pid": 810000, "id": 3722, "area_id": 810200 }, { "area_name": "油尖旺区", "pinyin": "Yau Tsim Mong", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810200, "id": 3723, "area_id": 810201 }, { "area_name": "深水埗区", "pinyin": "Sham Shui Po", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810200, "id": 3724, "area_id": 810202 }, { "area_name": "九龙城区", "pinyin": "Jiulongcheng", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810200, "id": 3725, "area_id": 810203 }, { "area_name": "黄大仙区", "pinyin": "Wong Tai Sin", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810200, "id": 3726, "area_id": 810204 }, { "area_name": "观塘区", "pinyin": "Kwun Tong", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810200, "id": 3727, "area_id": 810205 }, { "area_name": "新界", "pinyin": "New Territories", "level": 2, "area_code": 852, "post_code": 999077, "pid": 810000, "id": 3728, "area_id": 810300 }, { "area_name": "荃湾区", "pinyin": "Tsuen Wan", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3729, "area_id": 810301 }, { "area_name": "屯门区", "pinyin": "Tuen Mun", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3730, "area_id": 810302 }, { "area_name": "元朗区", "pinyin": "Yuen Long", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3731, "area_id": 810303 }, { "area_name": "北区", "pinyin": "North District", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3732, "area_id": 810304 }, { "area_name": "大埔区", "pinyin": "Tai Po", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3733, "area_id": 810305 }, { "area_name": "西贡区", "pinyin": "Sai Kung", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3734, "area_id": 810306 }, { "area_name": "沙田区", "pinyin": "Sha Tin", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3735, "area_id": 810307 }, { "area_name": "葵青区", "pinyin": "Kwai Tsing", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3736, "area_id": 810308 }, { "area_name": "离岛区", "pinyin": "Outlying Islands", "level": 3, "area_code": 852, "post_code": 999077, "pid": 810300, "id": 3737, "area_id": 810309 }, { "area_name": "澳门特别行政区", "pinyin": "Macau", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3738, "area_id": 820000 }, { "area_name": "澳门半岛", "pinyin": "MacauPeninsula", "level": 2, "area_code": 853, "post_code": 999078, "pid": 820000, "id": 3739, "area_id": 820100 }, { "area_name": "花地玛堂区", "pinyin": "Nossa Senhora de Fatima", "level": 3, "area_code": 853, "post_code": 999078, "pid": 820100, "id": 3740, "area_id": 820101 }, { "area_name": "圣安多尼堂区", "pinyin": "Santo Antonio", "level": 3, "area_code": 853, "post_code": 999078, "pid": 820100, "id": 3741, "area_id": 820102 }, { "area_name": "大堂区", "pinyin": "S�", "level": 3, "area_code": 853, "post_code": 999078, "pid": 820100, "id": 3742, "area_id": 820103 }, { "area_name": "望德堂区", "pinyin": "Sao Lazaro", "level": 3, "area_code": 853, "post_code": 999078, "pid": 820100, "id": 3743, "area_id": 820104 }, { "area_name": "风顺堂区", "pinyin": "Sao Lourenco", "level": 3, "area_code": 853, "post_code": 999078, "pid": 820100, "id": 3744, "area_id": 820105 }, { "area_name": "氹仔岛", "pinyin": "Taipa", "level": 2, "area_code": 853, "post_code": 999078, "pid": 820000, "id": 3745, "area_id": 820200 }, { "area_name": "嘉模堂区", "pinyin": "Our Lady Of Carmel's Parish", "level": 3, "area_code": 853, "post_code": 999078, "pid": 820200, "id": 3746, "area_id": 820201 }, { "area_name": "路环岛", "pinyin": "Coloane", "level": 2, "area_code": 853, "post_code": 999078, "pid": 820000, "id": 3747, "area_id": 820300 }, { "area_name": "圣方济各堂区", "pinyin": "St Francis Xavier's Parish", "level": 3, "area_code": 853, "post_code": 999078, "pid": 820300, "id": 3748, "area_id": 820301 }, { "area_name": "钓鱼岛", "pinyin": "DiaoyuDao", "level": 1, "area_code": null, "post_code": null, "pid": null, "id": 3749, "area_id": 900000 } ] let cityDataTree = setTreeDataUtil(cityAllData, 'pid', 'area_id') let provinceData = {} let cityData = {} let districtData = {} let province = [] let city = {} let district = {} cityDataTree.forEach((item) => { let provinceObj = { area_name: item.area_name, pinyin: item.pinyin, level: item.level, area_code: item.area_code, post_code: item.post_code, pid: item.pid, id: item.id, area_id: item.area_id, leaf: false, } city[item.area_id] = [] if (item.children) { item.children.forEach((cityItem) => { let cityObj = { area_name: cityItem.area_name, pinyin: cityItem.pinyin, level: cityItem.level, area_code: cityItem.area_code, post_code: cityItem.post_code, pid: cityItem.pid, id: cityItem.id, area_id: cityItem.area_id, leaf: false, } district[cityItem.area_id] = [] if (cityItem.children) { cityItem.children.forEach((districtItem) => { let districtObj = { area_name: districtItem.area_name, pinyin: districtItem.pinyin, level: districtItem.level, area_code: districtItem.area_code, post_code: districtItem.post_code, pid: districtItem.pid, id: districtItem.id, area_id: districtItem.area_id, leaf: true, } districtData[districtObj.area_id] = districtObj district[cityItem.area_id].push(districtObj) }) } else { cityObj.leaf = true } cityData[cityObj.area_id] = cityObj city[item.area_id].push(cityObj) }) } else { provinceObj.leaf = true } provinceData[provinceObj.area_id] = provinceObj province.push(provinceObj) }) export const cityObj = { all: cityDataTree, provinceData, cityData, districtData, province, city, district, nullTreeData:cityAllData, }
274056675/springboot-openai-chatgpt
1,415
mng_web/src/research/util/rules.js
export const codeListRules = { 'only': { pattern: 'only', msg: '', type: 'all' }, 'n6-16': { pattern: '^\\d{6,18}$', msg: '请输入6-16位的数字', type: ['int', 'Double', 'BigInt', 'BigDecimal'] }, '*6-16': { pattern: '^.{6,16}$', msg: '请输入6-16位任意字符', type: ['String', 'Text', 'Blob'] }, 's6-18': { pattern: '^[a-z|A-Z]{6,18}$', msg: '请输入6-18位字母', type: ['String', 'Text'] }, 'url': { pattern: '^((ht|f)tps?):\\/\\/[\\w\\-]+(\\.[\\w\\-]+)+([\\w\\-.,@?^=%&:\\/~+#]*[\\w\\-@?^=%&\\/~+#])?$', msg: '请输入正规的网址', type: ['String', 'Text'] }, 'm': { pattern: '^1[3456789]\\d{9}$', msg: '请输入正规的手机号码', type: ['String', 'Text'] }, 'p': { pattern: '^[1-9]\\d{5}$', msg: '请输入正规的邮政编码', type: ['int', 'BigInt', 'String', 'Text'] }, 's': { pattern: '[A-Z|a-z]+$', msg: '请输入字母', type: ['String', 'Text'] }, 'n': { pattern: '^-?\\d+(\\.?\\d+|\\d?)$', msg: '请输入数字', type: ['int', 'Double', 'BigInt', 'BigDecimal'] }, // 'z': { // pattern: 'z', // msg: '请输入整数', // type: ['String', 'Text'] // }, // '*': { // pattern: '^.+$', // msg: '该字段不能为空', // }, 'e': { pattern: '^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$', msg: '请输入正确格式的邮箱地址', }, 'money': { pattern: '^(([1-9][0-9]*)|([0]\\.\\d{0,2}|[1-9][0-9]*\\.\\d{0,5}))$', msg: '请输入正确的金额', }, }
233zzh/TitanDataOperationSystem
3,329
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/zooming/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Selection and zooming</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.selection.js"></script> <script type="text/javascript"> $(function() { // setup plot function getData(x1, x2) { var d = []; for (var i = 0; i <= 100; ++i) { var x = x1 + i * (x2 - x1) / 100; d.push([x, Math.sin(x * Math.sin(x))]); } return [ { label: "sin(x sin(x))", data: d } ]; } var options = { legend: { show: false }, series: { lines: { show: true }, points: { show: true } }, yaxis: { ticks: 10 }, selection: { mode: "xy" } }; var startData = getData(0, 3 * Math.PI); var plot = $.plot("#placeholder", startData, options); // Create the overview plot var overview = $.plot("#overview", startData, { legend: { show: false }, series: { lines: { show: true, lineWidth: 1 }, shadowSize: 0 }, xaxis: { ticks: 4 }, yaxis: { ticks: 3, min: -2, max: 2 }, grid: { color: "#999" }, selection: { mode: "xy" } }); // now connect the two $("#placeholder").bind("plotselected", function (event, ranges) { // clamp the zooming to prevent eternal zoom if (ranges.xaxis.to - ranges.xaxis.from < 0.00001) { ranges.xaxis.to = ranges.xaxis.from + 0.00001; } if (ranges.yaxis.to - ranges.yaxis.from < 0.00001) { ranges.yaxis.to = ranges.yaxis.from + 0.00001; } // do the zooming plot = $.plot("#placeholder", getData(ranges.xaxis.from, ranges.xaxis.to), $.extend(true, {}, options, { xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to }, yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to } }) ); // don't fire event on the overview to prevent eternal loop overview.setSelection(ranges, true); }); $("#overview").bind("plotselected", function (event, ranges) { plot.setSelection(ranges); }); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Selection and zooming</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder" style="float:left; width:650px;"></div> <div id="overview" class="demo-placeholder" style="float:right;width:160px; height:125px;"></div> </div> <p>Selection support makes it easy to construct flexible zooming schemes. With a few lines of code, the small overview plot to the right has been connected to the large plot. Try selecting a rectangle on either of them.</p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
27182812/ChatGLM-LLaMA-chinese-insturct
18,952
src/transformers/hf_argparser.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. import dataclasses import json import sys from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, NewType, Optional, Tuple, Union, get_type_hints import yaml try: # For Python versions <3.8, Literal is not in typing: https://peps.python.org/pep-0586/ from typing import Literal except ImportError: # For Python 3.7 from typing_extensions import Literal DataClass = NewType("DataClass", Any) DataClassType = NewType("DataClassType", Any) # From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse def string_to_bool(v): if isinstance(v, bool): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( f"Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)." ) def make_choice_type_function(choices: list) -> Callable[[str], Any]: """ Creates a mapping function from each choices string representation to the actual value. Used to support multiple value types for a single argument. Args: choices (list): List of choices. Returns: Callable[[str], Any]: Mapping function from string representation to actual value for each choice. """ str_to_choice = {str(choice): choice for choice in choices} return lambda arg: str_to_choice.get(arg, arg) def HfArg( *, aliases: Union[str, List[str]] = None, help: str = None, default: Any = dataclasses.MISSING, default_factory: Callable[[], Any] = dataclasses.MISSING, metadata: dict = None, **kwargs, ) -> dataclasses.Field: """Argument helper enabling a concise syntax to create dataclass fields for parsing with `HfArgumentParser`. Example comparing the use of `HfArg` and `dataclasses.field`: ``` @dataclass class Args: regular_arg: str = dataclasses.field(default="Huggingface", metadata={"aliases": ["--example", "-e"], "help": "This syntax could be better!"}) hf_arg: str = HfArg(default="Huggingface", aliases=["--example", "-e"], help="What a nice syntax!") ``` Args: aliases (Union[str, List[str]], optional): Single string or list of strings of aliases to pass on to argparse, e.g. `aliases=["--example", "-e"]`. Defaults to None. help (str, optional): Help string to pass on to argparse that can be displayed with --help. Defaults to None. default (Any, optional): Default value for the argument. If not default or default_factory is specified, the argument is required. Defaults to dataclasses.MISSING. default_factory (Callable[[], Any], optional): The default_factory is a 0-argument function called to initialize a field's value. It is useful to provide default values for mutable types, e.g. lists: `default_factory=list`. Mutually exclusive with `default=`. Defaults to dataclasses.MISSING. metadata (dict, optional): Further metadata to pass on to `dataclasses.field`. Defaults to None. Returns: Field: A `dataclasses.Field` with the desired properties. """ if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls metadata = {} if aliases is not None: metadata["aliases"] = aliases if help is not None: metadata["help"] = help return dataclasses.field(metadata=metadata, default=default, default_factory=default_factory, **kwargs) class HfArgumentParser(ArgumentParser): """ This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments. The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed) arguments to the parser after initialization and you'll get the output back after parsing as an additional namespace. Optional: To create sub argument groups use the `_argument_group_name` attribute in the dataclass. """ dataclass_types: Iterable[DataClassType] def __init__(self, dataclass_types: Union[DataClassType, Iterable[DataClassType]], **kwargs): """ Args: dataclass_types: Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args. kwargs: (Optional) Passed to `argparse.ArgumentParser()` in the regular way. """ # To make the default appear when using --help if "formatter_class" not in kwargs: kwargs["formatter_class"] = ArgumentDefaultsHelpFormatter super().__init__(**kwargs) if dataclasses.is_dataclass(dataclass_types): dataclass_types = [dataclass_types] self.dataclass_types = list(dataclass_types) for dtype in self.dataclass_types: self._add_dataclass_arguments(dtype) @staticmethod def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field): field_name = f"--{field.name}" kwargs = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type, str): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) aliases = kwargs.pop("aliases", []) if isinstance(aliases, str): aliases = [aliases] origin_type = getattr(field.type, "__origin__", field.type) if origin_type is Union: if str not in field.type.__args__ and ( len(field.type.__args__) != 2 or type(None) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f" Problem encountered in field '{field.name}'." ) if type(None) not in field.type.__args__: # filter `str` in Union field.type = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] origin_type = getattr(field.type, "__origin__", field.type) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) field.type = ( field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1] ) origin_type = getattr(field.type, "__origin__", field.type) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) bool_kwargs = {} if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)): if origin_type is Literal: kwargs["choices"] = field.type.__args__ else: kwargs["choices"] = [x.value for x in field.type] kwargs["type"] = make_choice_type_function(kwargs["choices"]) if field.default is not dataclasses.MISSING: kwargs["default"] = field.default else: kwargs["required"] = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument bool_kwargs = copy(kwargs) # Hack because type=bool in argparse does not behave as we want. kwargs["type"] = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. default = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way kwargs["default"] = default # This tells argparse we accept 0 or 1 value after --field_name kwargs["nargs"] = "?" # This is the value that will get picked if we do --field_name (without value) kwargs["const"] = True elif isclass(origin_type) and issubclass(origin_type, list): kwargs["type"] = field.type.__args__[0] kwargs["nargs"] = "+" if field.default_factory is not dataclasses.MISSING: kwargs["default"] = field.default_factory() elif field.default is dataclasses.MISSING: kwargs["required"] = True else: kwargs["type"] = field.type if field.default is not dataclasses.MISSING: kwargs["default"] = field.default elif field.default_factory is not dataclasses.MISSING: kwargs["default"] = field.default_factory() else: kwargs["required"] = True parser.add_argument(field_name, *aliases, **kwargs) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): bool_kwargs["default"] = False parser.add_argument(f"--no_{field.name}", action="store_false", dest=field.name, **bool_kwargs) def _add_dataclass_arguments(self, dtype: DataClassType): if hasattr(dtype, "_argument_group_name"): parser = self.add_argument_group(dtype._argument_group_name) else: parser = self try: type_hints: Dict[str, type] = get_type_hints(dtype) except NameError: raise RuntimeError( f"Type resolution failed for f{dtype}. Try declaring the class in global scope or " "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) for field in dataclasses.fields(dtype): if not field.init: continue field.type = type_hints[field.name] self._parse_dataclass_field(parser, field) def parse_args_into_dataclasses( self, args=None, return_remaining_strings=False, look_for_args_file=True, args_filename=None, args_file_flag=None, ) -> Tuple[DataClass, ...]: """ Parse command-line args into instances of the specified dataclass types. This relies on argparse's `ArgumentParser.parse_known_args`. See the doc at: docs.python.org/3.7/library/argparse.html#argparse.ArgumentParser.parse_args Args: args: List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser) return_remaining_strings: If true, also return a list of remaining argument strings. look_for_args_file: If true, will look for a ".args" file with the same base name as the entry point script for this process, and will append its potential content to the command line args. args_filename: If not None, will uses this file instead of the ".args" file specified in the previous argument. args_file_flag: If not None, will look for a file in the command-line args specified with this flag. The flag can be specified multiple times and precedence is determined by the order (last one wins). Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer.abspath - if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser after initialization. - The potential list of remaining argument strings. (same as argparse.ArgumentParser.parse_known_args) """ if args_file_flag or args_filename or (look_for_args_file and len(sys.argv)): args_files = [] if args_filename: args_files.append(Path(args_filename)) elif look_for_args_file and len(sys.argv): args_files.append(Path(sys.argv[0]).with_suffix(".args")) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values args_file_parser = ArgumentParser() args_file_parser.add_argument(args_file_flag, type=str, action="append") # Use only remaining args for further parsing (remove the args_file_flag) cfg, args = args_file_parser.parse_known_args(args=args) cmd_args_file_paths = vars(cfg).get(args_file_flag.lstrip("-"), None) if cmd_args_file_paths: args_files.extend([Path(p) for p in cmd_args_file_paths]) file_args = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last args = file_args + args if args is not None else file_args + sys.argv[1:] namespace, remaining_args = self.parse_known_args(args=args) outputs = [] for dtype in self.dataclass_types: keys = {f.name for f in dataclasses.fields(dtype) if f.init} inputs = {k: v for k, v in vars(namespace).items() if k in keys} for k in keys: delattr(namespace, k) obj = dtype(**inputs) outputs.append(obj) if len(namespace.__dict__) > 0: # additional namespace. outputs.append(namespace) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}") return (*outputs,) def parse_dict(self, args: Dict[str, Any], allow_extra_keys: bool = False) -> Tuple[DataClass, ...]: """ Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass types. Args: args (`dict`): dict containing config values allow_extra_keys (`bool`, *optional*, defaults to `False`): Defaults to False. If False, will raise an exception if the dict contains keys that are not parsed. Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer. """ unused_keys = set(args.keys()) outputs = [] for dtype in self.dataclass_types: keys = {f.name for f in dataclasses.fields(dtype) if f.init} inputs = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys()) obj = dtype(**inputs) outputs.append(obj) if not allow_extra_keys and unused_keys: raise ValueError(f"Some keys are not used by the HfArgumentParser: {sorted(unused_keys)}") return tuple(outputs) def parse_json_file(self, json_file: str, allow_extra_keys: bool = False) -> Tuple[DataClass, ...]: """ Alternative helper method that does not use `argparse` at all, instead loading a json file and populating the dataclass types. Args: json_file (`str` or `os.PathLike`): File name of the json file to parse allow_extra_keys (`bool`, *optional*, defaults to `False`): Defaults to False. If False, will raise an exception if the json file contains keys that are not parsed. Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer. """ open_json_file = open(Path(json_file)) data = json.loads(open_json_file.read()) outputs = self.parse_dict(data, allow_extra_keys=allow_extra_keys) return tuple(outputs) def parse_yaml_file(self, yaml_file: str, allow_extra_keys: bool = False) -> Tuple[DataClass, ...]: """ Alternative helper method that does not use `argparse` at all, instead loading a yaml file and populating the dataclass types. Args: yaml_file (`str` or `os.PathLike`): File name of the yaml file to parse allow_extra_keys (`bool`, *optional*, defaults to `False`): Defaults to False. If False, will raise an exception if the json file contains keys that are not parsed. Returns: Tuple consisting of: - the dataclass instances in the same order as they were passed to the initializer. """ outputs = self.parse_dict(yaml.safe_load(Path(yaml_file).read_text()), allow_extra_keys=allow_extra_keys) return tuple(outputs)
27182812/ChatGLM-LLaMA-chinese-insturct
1,126
src/transformers/generation_utils.py
# coding=utf-8 # Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team. # Copyright (c) 2020, 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. import warnings from .generation import GenerationMixin class GenerationMixin(GenerationMixin): # warning at import time warnings.warn( "Importing `GenerationMixin` from `src/transformers/generation_utils.py` is deprecated and will " "be removed in Transformers v5. Import as `from transformers import GenerationMixin` instead.", FutureWarning, )
27182812/ChatGLM-LLaMA-chinese-insturct
25,303
src/transformers/image_processing_utils.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. import copy import json import os from typing import Any, Dict, Iterable, Optional, Tuple, Union import numpy as np from .dynamic_module_utils import custom_object_save from .feature_extraction_utils import BatchFeature as BaseBatchFeature from .utils import ( IMAGE_PROCESSOR_NAME, PushToHubMixin, cached_file, copy_func, download_url, is_offline_mode, is_remote_url, logging, ) logger = logging.get_logger(__name__) # TODO: Move BatchFeature to be imported by both image_processing_utils and image_processing_utils # We override the class string here, but logic is the same. class BatchFeature(BaseBatchFeature): r""" Holds the output of the image processor specific `__call__` methods. This class is derived from a python dictionary and can be used as a dictionary. Args: data (`dict`): Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.). tensor_type (`Union[None, str, TensorType]`, *optional*): You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at initialization. """ # TODO: (Amy) - factor out the common parts of this and the feature extractor class ImageProcessingMixin(PushToHubMixin): """ This is an image processor mixin used to provide saving/loading functionality for sequential and image feature extractors. """ _auto_class = None def __init__(self, **kwargs): """Set elements of `kwargs` as attributes.""" # Pop "processor_class" as it should be saved as private attribute self._processor_class = kwargs.pop("processor_class", None) # Additional attributes without default values for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err def _set_processor_class(self, processor_class: str): """Sets processor class as an attribute.""" self._processor_class = processor_class @classmethod def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs): r""" Instantiate a type of [`~image_processing_utils.ImageProcessingMixin`] from an image processor. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained image_processor hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a image processor file saved using the [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved image processor JSON *file*, e.g., `./my_model_directory/preprocessor_config.json`. cache_dir (`str` or `os.PathLike`, *optional*): Path to a directory in which a downloaded pretrained model image processor should be cached if the standard cache should not be used. force_download (`bool`, *optional*, defaults to `False`): Whether or not to force to (re-)download the image processor files and override the cached versions if they exist. resume_download (`bool`, *optional*, defaults to `False`): Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request. use_auth_token (`str` or `bool`, *optional*): The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). revision (`str`, *optional*, defaults to `"main"`): The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git. <Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>". </Tip> return_unused_kwargs (`bool`, *optional*, defaults to `False`): If `False`, then this function returns just the final image processor object. If `True`, then this functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not image processor attributes: i.e., the part of `kwargs` which has not been used to update `image_processor` and is otherwise ignored. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. kwargs (`Dict[str, Any]`, *optional*): The values in kwargs of any keys which are image processor attributes will be used to override the loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is controlled by the `return_unused_kwargs` keyword parameter. Returns: A image processor of type [`~image_processing_utils.ImageProcessingMixin`]. Examples: ```python # We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a # derived class: *CLIPImageProcessor* image_processor = CLIPImageProcessor.from_pretrained( "openai/clip-vit-base-patch32" ) # Download image_processing_config from huggingface.co and cache. image_processor = CLIPImageProcessor.from_pretrained( "./test/saved_model/" ) # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')* image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json") image_processor = CLIPImageProcessor.from_pretrained( "openai/clip-vit-base-patch32", do_normalize=False, foo=False ) assert image_processor.do_normalize is False image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained( "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True ) assert image_processor.do_normalize is False assert unused_kwargs == {"foo": False} ```""" image_processor_dict, kwargs = cls.get_image_processor_dict(pretrained_model_name_or_path, **kwargs) return cls.from_dict(image_processor_dict, **kwargs) def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): """ Save an image processor object to the directory `save_directory`, so that it can be re-loaded using the [`~image_processing_utils.ImageProcessingMixin.from_pretrained`] class method. Args: save_directory (`str` or `os.PathLike`): Directory where the image processor JSON file will be saved (will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to with `repo_id` (will default to the name of `save_directory` in your namespace). kwargs: Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method. """ if os.path.isfile(save_directory): raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") os.makedirs(save_directory, exist_ok=True) if push_to_hub: commit_message = kwargs.pop("commit_message", None) repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1]) repo_id = self._create_repo(repo_id, **kwargs) files_timestamps = self._get_files_timestamps(save_directory) # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self) # If we save using the predefined names, we can load using `from_pretrained` output_image_processor_file = os.path.join(save_directory, IMAGE_PROCESSOR_NAME) self.to_json_file(output_image_processor_file) logger.info(f"Image processor saved in {output_image_processor_file}") if push_to_hub: self._upload_modified_files( save_directory, repo_id, files_timestamps, commit_message=commit_message, token=kwargs.get("use_auth_token"), ) return [output_image_processor_file] @classmethod def get_image_processor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a image processor of type [`~image_processor_utils.ImageProcessingMixin`] using `from_dict`. Parameters: pretrained_model_name_or_path (`str` or `os.PathLike`): The identifier of the pre-trained checkpoint from which we want the dictionary of parameters. subfolder (`str`, *optional*, defaults to `""`): In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can specify the folder name here. Returns: `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the image processor object. """ cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) resume_download = kwargs.pop("resume_download", False) proxies = kwargs.pop("proxies", None) use_auth_token = kwargs.pop("use_auth_token", None) local_files_only = kwargs.pop("local_files_only", False) revision = kwargs.pop("revision", None) subfolder = kwargs.pop("subfolder", "") from_pipeline = kwargs.pop("_from_pipeline", None) from_auto_class = kwargs.pop("_from_auto", False) user_agent = {"file_type": "image processor", "from_auto_class": from_auto_class} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline if is_offline_mode() and not local_files_only: logger.info("Offline mode: forcing local_files_only=True") local_files_only = True pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isdir(pretrained_model_name_or_path): image_processor_file = os.path.join(pretrained_model_name_or_path, IMAGE_PROCESSOR_NAME) if os.path.isfile(pretrained_model_name_or_path): resolved_image_processor_file = pretrained_model_name_or_path is_local = True elif is_remote_url(pretrained_model_name_or_path): image_processor_file = pretrained_model_name_or_path resolved_image_processor_file = download_url(pretrained_model_name_or_path) else: image_processor_file = IMAGE_PROCESSOR_NAME try: # Load from local folder or from cache or download from model Hub and cache resolved_image_processor_file = cached_file( pretrained_model_name_or_path, image_processor_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, local_files_only=local_files_only, use_auth_token=use_auth_token, user_agent=user_agent, revision=revision, subfolder=subfolder, ) except EnvironmentError: # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to # the original exception. raise except Exception: # For any other exception, we throw a generic error. raise EnvironmentError( f"Can't load image processor for '{pretrained_model_name_or_path}'. If you were trying to load" " it from 'https://huggingface.co/models', make sure you don't have a local directory with the" f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {IMAGE_PROCESSOR_NAME} file" ) try: # Load image_processor dict with open(resolved_image_processor_file, "r", encoding="utf-8") as reader: text = reader.read() image_processor_dict = json.loads(text) except json.JSONDecodeError: raise EnvironmentError( f"It looks like the config file at '{resolved_image_processor_file}' is not a valid JSON file." ) if is_local: logger.info(f"loading configuration file {resolved_image_processor_file}") else: logger.info( f"loading configuration file {image_processor_file} from cache at {resolved_image_processor_file}" ) return image_processor_dict, kwargs @classmethod def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs): """ Instantiates a type of [`~image_processing_utils.ImageProcessingMixin`] from a Python dictionary of parameters. Args: image_processor_dict (`Dict[str, Any]`): Dictionary that will be used to instantiate the image processor object. Such a dictionary can be retrieved from a pretrained checkpoint by leveraging the [`~image_processing_utils.ImageProcessingMixin.to_dict`] method. kwargs (`Dict[str, Any]`): Additional parameters from which to initialize the image processor object. Returns: [`~image_processing_utils.ImageProcessingMixin`]: The image processor object instantiated from those parameters. """ image_processor_dict = image_processor_dict.copy() return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) # The `size` parameter is a dict and was previously an int or tuple in feature extractors. # We set `size` here directly to the `image_processor_dict` so that it is converted to the appropriate # dict within the image processor and isn't overwritten if `size` is passed in as a kwarg. if "size" in kwargs and "size" in image_processor_dict: image_processor_dict["size"] = kwargs.pop("size") if "crop_size" in kwargs and "crop_size" in image_processor_dict: image_processor_dict["crop_size"] = kwargs.pop("crop_size") image_processor = cls(**image_processor_dict) # Update image_processor with kwargs if needed to_remove = [] for key, value in kwargs.items(): if hasattr(image_processor, key): setattr(image_processor, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) logger.info(f"Image processor {image_processor}") if return_unused_kwargs: return image_processor, kwargs else: return image_processor def to_dict(self) -> Dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `Dict[str, Any]`: Dictionary of all the attributes that make up this image processor instance. """ output = copy.deepcopy(self.__dict__) output["image_processor_type"] = self.__class__.__name__ return output @classmethod def from_json_file(cls, json_file: Union[str, os.PathLike]): """ Instantiates a image processor of type [`~image_processing_utils.ImageProcessingMixin`] from the path to a JSON file of parameters. Args: json_file (`str` or `os.PathLike`): Path to the JSON file containing the parameters. Returns: A image processor of type [`~image_processing_utils.ImageProcessingMixin`]: The image_processor object instantiated from that JSON file. """ with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() image_processor_dict = json.loads(text) return cls(**image_processor_dict) def to_json_string(self) -> str: """ Serializes this instance to a JSON string. Returns: `str`: String containing all the attributes that make up this feature_extractor instance in JSON format. """ dictionary = self.to_dict() for key, value in dictionary.items(): if isinstance(value, np.ndarray): dictionary[key] = value.tolist() # make sure private name "_processor_class" is correctly # saved as "processor_class" _processor_class = dictionary.pop("_processor_class", None) if _processor_class is not None: dictionary["processor_class"] = _processor_class return json.dumps(dictionary, indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path: Union[str, os.PathLike]): """ Save this instance to a JSON file. Args: json_file_path (`str` or `os.PathLike`): Path to the JSON file in which this image_processor instance's parameters will be saved. """ with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) def __repr__(self): return f"{self.__class__.__name__} {self.to_json_string()}" @classmethod def register_for_auto_class(cls, auto_class="AutoImageProcessor"): """ Register this class with a given auto class. This should only be used for custom image processors as the ones in the library are already mapped with `AutoImageProcessor `. <Tip warning={true}> This API is experimental and may have some slight breaking changes in the next releases. </Tip> Args: auto_class (`str` or `type`, *optional*, defaults to `"AutoImageProcessor "`): The auto class to register this new image processor with. """ if not isinstance(auto_class, str): auto_class = auto_class.__name__ import transformers.models.auto as auto_module if not hasattr(auto_module, auto_class): raise ValueError(f"{auto_class} is not a valid auto class.") cls._auto_class = auto_class class BaseImageProcessor(ImageProcessingMixin): def __init__(self, **kwargs): super().__init__(**kwargs) def __call__(self, images, **kwargs) -> BatchFeature: """Preprocess an image or a batch of images.""" return self.preprocess(images, **kwargs) def preprocess(self, images, **kwargs) -> BatchFeature: raise NotImplementedError("Each image processor must implement its own preprocess method") VALID_SIZE_DICT_KEYS = ({"height", "width"}, {"shortest_edge"}, {"shortest_edge", "longest_edge"}) def is_valid_size_dict(size_dict): if not isinstance(size_dict, dict): return False size_dict_keys = set(size_dict.keys()) for allowed_keys in VALID_SIZE_DICT_KEYS: if size_dict_keys == allowed_keys: return True return False def convert_to_size_dict( size, max_size: Optional[int] = None, default_to_square: bool = True, height_width_order: bool = True ): # By default, if size is an int we assume it represents a tuple of (size, size). if isinstance(size, int) and default_to_square: if max_size is not None: raise ValueError("Cannot specify both size as an int, with default_to_square=True and max_size") return {"height": size, "width": size} # In other configs, if size is an int and default_to_square is False, size represents the length of # the shortest edge after resizing. elif isinstance(size, int) and not default_to_square: size_dict = {"shortest_edge": size} if max_size is not None: size_dict["longest_edge"] = max_size return size_dict # Otherwise, if size is a tuple it's either (height, width) or (width, height) elif isinstance(size, (tuple, list)) and height_width_order: return {"height": size[0], "width": size[1]} elif isinstance(size, (tuple, list)) and not height_width_order: return {"height": size[1], "width": size[0]} raise ValueError(f"Could not convert size input to size dict: {size}") def get_size_dict( size: Union[int, Iterable[int], Dict[str, int]] = None, max_size: Optional[int] = None, height_width_order: bool = True, default_to_square: bool = True, param_name="size", ) -> dict: """ Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height, width) or (width, height) format. - If `size` is tuple, it is converted to `{"height": size[0], "width": size[1]}` or `{"height": size[1], "width": size[0]}` if `height_width_order` is `False`. - If `size` is an int, and `default_to_square` is `True`, it is converted to `{"height": size, "width": size}`. - If `size` is an int and `default_to_square` is False, it is converted to `{"shortest_edge": size}`. If `max_size` is set, it is added to the dict as `{"longest_edge": max_size}`. Args: size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*): The `size` parameter to be cast into a size dictionary. max_size (`Optional[int]`, *optional*): The `max_size` parameter to be cast into a size dictionary. height_width_order (`bool`, *optional*, defaults to `True`): If `size` is a tuple, whether it's in (height, width) or (width, height) order. default_to_square (`bool`, *optional*, defaults to `True`): If `size` is an int, whether to default to a square image or not. """ if not isinstance(size, dict): size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order) logger.info( f"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}." f" Converted to {size_dict}.", ) else: size_dict = size if not is_valid_size_dict(size_dict): raise ValueError( f"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}" ) return size_dict ImageProcessingMixin.push_to_hub = copy_func(ImageProcessingMixin.push_to_hub) if ImageProcessingMixin.push_to_hub.__doc__ is not None: ImageProcessingMixin.push_to_hub.__doc__ = ImageProcessingMixin.push_to_hub.__doc__.format( object="image processor", object_class="AutoImageProcessor", object_files="image processor file" )
233zzh/TitanDataOperationSystem
3,547
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/series-errorbars/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Error Bars</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.errorbars.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.navigate.js"></script> <script type="text/javascript"> $(function() { function drawArrow(ctx, x, y, radius){ ctx.beginPath(); ctx.moveTo(x + radius, y + radius); ctx.lineTo(x, y); ctx.lineTo(x - radius, y + radius); ctx.stroke(); } function drawSemiCircle(ctx, x, y, radius){ ctx.beginPath(); ctx.arc(x, y, radius, 0, Math.PI, false); ctx.moveTo(x - radius, y); ctx.lineTo(x + radius, y); ctx.stroke(); } var data1 = [ [1,1,.5,.1,.3], [2,2,.3,.5,.2], [3,3,.9,.5,.2], [1.5,-.05,.5,.1,.3], [3.15,1.,.5,.1,.3], [2.5,-1.,.5,.1,.3] ]; var data1_points = { show: true, radius: 5, fillColor: "blue", errorbars: "xy", xerr: {show: true, asymmetric: true, upperCap: "-", lowerCap: "-"}, yerr: {show: true, color: "red", upperCap: "-"} }; var data2 = [ [.7,3,.2,.4], [1.5,2.2,.3,.4], [2.3,1,.5,.2] ]; var data2_points = { show: true, radius: 5, errorbars: "y", yerr: {show:true, asymmetric:true, upperCap: drawArrow, lowerCap: drawSemiCircle} }; var data3 = [ [1,2,.4], [2,0.5,.3], [2.7,2,.5] ]; var data3_points = { //do not show points radius: 0, errorbars: "y", yerr: {show:true, upperCap: "-", lowerCap: "-", radius: 5} }; var data4 = [ [1.3, 1], [1.75, 2.5], [2.5, 0.5] ]; var data4_errors = [0.1, 0.4, 0.2]; for (var i = 0; i < data4.length; i++) { data4_errors[i] = data4[i].concat(data4_errors[i]) } var data = [ {color: "blue", points: data1_points, data: data1, label: "data1"}, {color: "red", points: data2_points, data: data2, label: "data2"}, {color: "green", lines: {show: true}, points: data3_points, data: data3, label: "data3"}, // bars with errors {color: "orange", bars: {show: true, align: "center", barWidth: 0.25}, data: data4, label: "data4"}, {color: "orange", points: data3_points, data: data4_errors} ]; $.plot($("#placeholder"), data , { legend: { position: "sw", show: true }, series: { lines: { show: false } }, xaxis: { min: 0.6, max: 3.1 }, yaxis: { min: 0, max: 3.5 }, zoom: { interactive: true }, pan: { interactive: true } }); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Error Bars</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder"></div> </div> <p>With the errorbars plugin you can plot error bars to show standard deviation and other useful statistical properties.</p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
274056675/springboot-openai-chatgpt
12,399
mng_web/src/research/util/Validation.js
//******************************** Input框 正则表达式验证 ********************************** //inpu框,只能输入数字和小数点,【两位小数,正数】 export const clearNum = (obj) => { obj.value = obj.value.replace(/[^\d.]/g, '').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); } //inpu框,只能输入数字和小数点,【三位小数,正数】 export const clearNumThreeDecimal = (obj) => { obj.value = obj.value.replace(/[^\d.]/g, '').replace(/^(\-)*(\d+)\.(\d\d\d).*$/, '$1$2.$3'); } //inpu框,只能输入数字和小数点,【两位小数,正、负数】 export const clearNumMin = (obj) => { obj.value = obj.value.replace(/[^-*\d.]/g, '').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); } //inpu框,只能输入数字和小数点,【两位小数,正、负数】 export const clearNumMinNoPer = (obj) => { obj.value = obj.value.replace(/[^-*\d.]/g, '').replace(/^(\-)*(\d+)\.(\d+).*$/, '$1$2.$3'); } //inpu框,只能输入数字,【正整数和零】 export const clearNumIntegar = (obj) => { obj.value = obj.value.replace(/\D/g, ''); } //inpu框,只能输入数字,【正整数(大于零)】 export const clearNumPosIntegar = (obj) => { if (obj.value.length == 1) { obj.value = obj.value.replace(/[^1-9]/g, ''); } else { obj.value = obj.value.replace(/\D/g, ''); } } //inpu框,只能输入数字,【正整数(大于零)】 export const clearNumPosIntegarOne = (obj) => { if (obj.value.length == 1) { obj.value = obj.value.replace(/[^1-9]/g, '1'); } else { obj.value = obj.value.replace(/\D/g, '1'); } } //inpu框,只能输入数字英文 export const clearNumCap = (obj) => { obj.value = obj.value.replace(/[^A-Z0-9]/g, ''); } export const clearNumCap2 = (obj) => { obj.value = obj.value.replace(/[^a-zA-Z0-9]/g, ''); } //只能输入数字英文中文 export const clearSpecialAll = (obj) => { obj.value = obj.value.replace(/[^\u4E00-\u9FA5A-Za-z0-9]/g, ''); } //inpu框,不能输入特殊字符 export const clearSpecial = (obj) => { obj.value = obj.value.replace(/[\。\,\、\’\;\:\“\”\_\‘\’\!\,\.\!\|\~\`\(\)\#\@\%\+\=\/\'\$\%\^\&\*\{\}\:\;\"\<\>\?\\]/g, ''); } //不能输入英文双引号 export const CheckContent = (obj) => { obj.value = obj.value.replace(/[\"]/g, ''); } export const clearInputAll = (obj) => { obj.value = ''; } //********************************** 为空和NULL的处理 **************************** //为空数值处理 export const IsNullEmptyNum = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "null" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return 0; } return str; } //为空文字处理 export const IsNullEmpty = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "null" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str; } //时间为空处理(精确到:分) export const IsNullEmptyDataTime = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.replace('T', ' ').substring(0, 16); } //时间为空处理(精确到:秒) export const IsNullEmptyDataTimeSecond = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.replace('T', ' ').substring(0, 19); } //时间为空处理(精确到:天) export const IsNullEmptyDataTimeDay = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.replace('T', ' ').substring(0, 10); } //时间为空处理(精确到:天 空格) export const IsNullEmptyDataTimeDayKg = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } var aa = str.replace('T', ' ').substring(0, 10); aa = aa.replace(/-/g, ' '); return aa; } //时间为空处理(精确到:天 空格1) export const IsNullEmptyDataTimeDayKg1 = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.replace('T', ' ').substring(0, 10).replace(/-/g, ' '); } //时间为空处理(精确到:月) export const IsNullEmptyDataTimeMonth = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.replace('T', ' ').substring(0, 7); } //时间为空处理(精确到:年) export const IsNullEmptyDataTimeYear = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.substring(0, 4); } //时间为空处理(精确到:月-日-小时-分,格式:MM-dd HH:mm) export const IsNullEmptyDataTimeMonthMinute = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.replace('T', ' ').substring(5, 16); } //时间为空处理(精确到:小时-分,格式:HH:mm) export const IsNullEmptyDataTimeHoureMinute = (str, nullRtnStr, isRtnStr) => { if (str == null || str == "" || str == "undefined" || str == undefined) { if (isRtnStr) { return nullRtnStr; } return ""; } return str.replace('T', ' ').substring(11, 16); } export const timeSplictYMD = (startDate) => { var times = IsNullEmptyDataTimeDay(startDate); if (times != "") { var startTimeList = times.split("-"); if (startTimeList.length == 3) { times = startTimeList[0] + "年" + startTimeList[1] + "月" + startTimeList[2] + "日"; } } return times; } //创建唯一字符串 export const newGuid = () => { //var guid = ""; //var n = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); //for (var i = 1; i <= 8; i++) { // guid += n; //} //return guid; var guid = ""; for (var i = 1; i <= 32; i++) { var n = Math.floor(Math.random() * 16.0).toString(16); guid += n; //if (isMiddline && (i == 8 || i == 12 || i == 16 || i == 20)) { // guid += "-"; //} } return guid; } //邮箱验证 export const fChkMail = (szMail) => { var szReg = /^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/; //var szReg = /^[A-Za-zd]+([-_.][A-Za-zd]+)*@([A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/; //var szReg = /w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; var bChk = szReg.test(szMail); return bChk; } //去除字符串两端空格 export const StrTirm = (Str) => { //.replace(/^\s+|\s+$/g, "") if (Str.length > 0) { return Str.replace(/^\s+|\s+$/g, ""); } return Str; } /******************* 身份证号验证 Start ***********************/ //身份证号码验证 export const isIdCardNo = (num) => { num = num.toUpperCase(); var factorArr = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); var parityBit = new Array("1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"); var varArray = new Array(); var intValue; var lngProduct = 0; var intCheckDigit; var intStrLen = num.length; var idNumber = num; // initialize if ((intStrLen != 15) && (intStrLen != 18)) { return false; } // check and set value for (i = 0; i < intStrLen; i++) { varArray[i] = idNumber.charAt(i); if ((varArray[i] < '0' || varArray[i] > '9') && (i != 17)) { return false; } else if (i < 17) { varArray[i] = varArray[i] * factorArr[i]; } } if (intStrLen == 18) { //check date var date8 = idNumber.substring(6, 14); if (isDate8(date8) == false) { return false; } // calculate the sum of the products for (i = 0; i < 17; i++) { lngProduct = lngProduct + varArray[i]; } // calculate the check digit intCheckDigit = parityBit[lngProduct % 11]; // check last digit if (varArray[17] != intCheckDigit) { return false; } } else { //length is 15 //check date var date6 = idNumber.substring(6, 12); if (isDate6(date6) == false) { return false; } } return true; } export const isDate6 = (sDate) => { if (!/^[0-9]{6}$/.test(sDate)) { return false; } var year, month, day; year = sDate.substring(0, 4); month = sDate.substring(4, 6); if (year < 1700 || year > 2500) return false if (month < 1 || month > 12) return false return true } export const isDate8 = (sDate) => { if (!/^[0-9]{8}$/.test(sDate)) { return false; } var year, month, day; year = sDate.substring(0, 4); month = sDate.substring(4, 6); day = sDate.substring(6, 8); var iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if (year < 1700 || year > 2500) return false if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) iaMonthDays[1] = 29; if (month < 1 || month > 12) return false if (day < 1 || day > iaMonthDays[month - 1]) return false return true } /******************** 身份证号验证 END ******************************/ /**---------金额大写转换(转化为中文)------------**/ export const ToCapitalized = (n) => { //金额大写转换函数 if (n <= 0) { return ""; } var unit = "仟佰拾亿仟佰拾万仟佰拾元角分", str = ""; n += "00"; var p = n.indexOf('.'); if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2); unit = unit.substr(unit.length - n.length); for (var i = 0; i < n.length; i++) { str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i); } return str.replace(/零(仟|佰|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整"); } export const ToCapitalizedDe = (n) => { //金额大写转换函数 if (n <= 0) { return ""; } var str = ""; n += "00"; var p = n.indexOf('.'); if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2); for (var i = 0; i < (9 - n.length); i++) { str += '零 '; } for (var i = 0; i < n.length; i++) { str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + ' '; } return str; } export const ToCapitalizedCb = (n) => { //金额大写转换函数 if (n <= 0) { return ""; } var dxMongy = ""; var str = ""; n += "00"; var p = n.indexOf('.'); if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2); for (var i = 0; i < (8 - n.length); i++) { dxMongy += '零'; } for (var i = 0; i < n.length; i++) { dxMongy += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i));// + ' '; } for (var i = 0; i < dxMongy.length; i++) { if (i < 5) { str += dxMongy[i] + ' '; } else { str += dxMongy[i] + ' '; } } return str; } //手机和电话验证 export const IsTelPhone = (str) => { var mobile = /^1[3-9]+\d{9}$/; var phone = /^(0\d{2,3})?-?\d{7,8}$/; if (mobile.test(str) || phone.test(str)) { return true; } else { return false; } } //表号验证 (数字英文横杠) export const IsMeterNo = (str) => { var regx = /^[A-Za-z0-9/-]+$/; if (regx.test(str)) { return true; } else { return false; } } export const IsNumber = (val) => { var regPos = /^\d+(\.\d+)?$/; //非负浮点数 if (regPos.test(val)) { return true; } else { return false; } } //开始时间 stime //结束时间 etime export const CheckTimeOneYear = (stime, etime) => { var timemils = Date.parse(delimiterConvert(etime)) - Date.parse(delimiterConvert(stime)); //开始时间到结束时间的时间差。 if (timemils < 0) { return false; } var yearmils = (1000 * 60 * 60 * 24 * 366);//一年的时间差 if (timemils > yearmils) { return false; } return true; } export const delimiterConvert = (val) => { //格式话数据 return val.replace('-', '/').replace('-', '/') } //获取时间 //时间 PassTime 无值时,去当前时间 //时间格式 FormatType 0 yyyy-MM-dd,1 yyyy-MM-dd HH:mm:ss //差距年份 YearNum 0是当前年 1是加1年 -1 是减1年 ///getFormatDate("",0,-1);//前面一年的时间 ///getFormatDate("", 0, 0);//当前时间 export const getFormatDate = (PassTime, FormatType, YearNum) => { var nowDate = new Date(); if (IsNullEmpty(PassTime) != "") { nowDate = new Date(PassTime); } var year = nowDate.getFullYear() + parseInt(IsNullEmptyNum(YearNum)); var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1; var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate(); var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours(); var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes(); var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds(); var retime = year + "-" + month + "-" + date; if (FormatType == 1) { retime = year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;; } return retime; }
233zzh/TitanDataOperationSystem
3,015
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/interacting/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Interactivity</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script type="text/javascript"> $(function() { var sin = [], cos = []; for (var i = 0; i < 14; i += 0.5) { sin.push([i, Math.sin(i)]); cos.push([i, Math.cos(i)]); } var plot = $.plot("#placeholder", [ { data: sin, label: "sin(x)"}, { data: cos, label: "cos(x)"} ], { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true, clickable: true }, yaxis: { min: -1.2, max: 1.2 } }); $("<div id='tooltip'></div>").css({ position: "absolute", display: "none", border: "1px solid #fdd", padding: "2px", "background-color": "#fee", opacity: 0.80 }).appendTo("body"); $("#placeholder").bind("plothover", function (event, pos, item) { if ($("#enablePosition:checked").length > 0) { var str = "(" + pos.x.toFixed(2) + ", " + pos.y.toFixed(2) + ")"; $("#hoverdata").text(str); } if ($("#enableTooltip:checked").length > 0) { if (item) { var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); $("#tooltip").html(item.series.label + " of " + x + " = " + y) .css({top: item.pageY+5, left: item.pageX+5}) .fadeIn(200); } else { $("#tooltip").hide(); } } }); $("#placeholder").bind("plotclick", function (event, pos, item) { if (item) { $("#clickdata").text(" - click point " + item.dataIndex + " in " + item.series.label); plot.highlight(item.series, item.datapoint); } }); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Interactivity</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder"></div> </div> <p>One of the goals of Flot is to support user interactions. Try pointing and clicking on the points.</p> <p> <label><input id="enablePosition" type="checkbox" checked="checked"></input>Show mouse position</label> <span id="hoverdata"></span> <span id="clickdata"></span> </p> <p>A tooltip is easy to build with a bit of jQuery code and the data returned from the plot.</p> <p><label><input id="enableTooltip" type="checkbox" checked="checked"></input>Enable tooltip</label></p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
27182812/ChatGLM-LLaMA-chinese-insturct
14,190
src/transformers/training_args_tf.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. import warnings from dataclasses import dataclass, field from typing import Optional, Tuple from .training_args import TrainingArguments from .utils import cached_property, is_tf_available, logging, requires_backends logger = logging.get_logger(__name__) if is_tf_available(): import tensorflow as tf @dataclass class TFTrainingArguments(TrainingArguments): """ TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop itself**. Using [`HfArgumentParser`] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line. Parameters: output_dir (`str`): The output directory where the model predictions and checkpoints will be written. overwrite_output_dir (`bool`, *optional*, defaults to `False`): If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir` points to a checkpoint directory. do_train (`bool`, *optional*, defaults to `False`): Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_eval (`bool`, *optional*): Whether to run evaluation on the validation set or not. Will be set to `True` if `evaluation_strategy` is different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_predict (`bool`, *optional*, defaults to `False`): Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. evaluation_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`): The evaluation strategy to adopt during training. Possible values are: - `"no"`: No evaluation is done during training. - `"steps"`: Evaluation is done (and logged) every `eval_steps`. - `"epoch"`: Evaluation is done at the end of each epoch. per_device_train_batch_size (`int`, *optional*, defaults to 8): The batch size per GPU/TPU core/CPU for training. per_device_eval_batch_size (`int`, *optional*, defaults to 8): The batch size per GPU/TPU core/CPU for evaluation. gradient_accumulation_steps: (`int`, *optional*, defaults to 1): Number of updates steps to accumulate the gradients for, before performing a backward/update pass. <Tip warning={true}> When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples. </Tip> learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate for Adam. weight_decay (`float`, *optional*, defaults to 0): The weight decay to apply (if not zero). adam_beta1 (`float`, *optional*, defaults to 0.9): The beta1 hyperparameter for the Adam optimizer. adam_beta2 (`float`, *optional*, defaults to 0.999): The beta2 hyperparameter for the Adam optimizer. adam_epsilon (`float`, *optional*, defaults to 1e-8): The epsilon hyperparameter for the Adam optimizer. max_grad_norm (`float`, *optional*, defaults to 1.0): Maximum gradient norm (for gradient clipping). num_train_epochs(`float`, *optional*, defaults to 3.0): Total number of training epochs to perform. max_steps (`int`, *optional*, defaults to -1): If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. warmup_ratio (`float`, *optional*, defaults to 0.0): Ratio of total training steps used for a linear warmup from 0 to `learning_rate`. warmup_steps (`int`, *optional*, defaults to 0): Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`. logging_dir (`str`, *optional*): [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to *runs/**CURRENT_DATETIME_HOSTNAME***. logging_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The logging strategy to adopt during training. Possible values are: - `"no"`: No logging is done during training. - `"epoch"`: Logging is done at the end of each epoch. - `"steps"`: Logging is done every `logging_steps`. logging_first_step (`bool`, *optional*, defaults to `False`): Whether to log and evaluate the first `global_step` or not. logging_steps (`int`, *optional*, defaults to 500): Number of update steps between two logs if `logging_strategy="steps"`. save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The checkpoint save strategy to adopt during training. Possible values are: - `"no"`: No save is done during training. - `"epoch"`: Save is done at the end of each epoch. - `"steps"`: Save is done every `save_steps`. save_steps (`int`, *optional*, defaults to 500): Number of updates steps before two checkpoint saves if `save_strategy="steps"`. save_total_limit (`int`, *optional*): If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_dir`. no_cuda (`bool`, *optional*, defaults to `False`): Whether to not use CUDA even when it is available or not. seed (`int`, *optional*, defaults to 42): Random seed that will be set at the beginning of training. fp16 (`bool`, *optional*, defaults to `False`): Whether to use 16-bit (mixed) precision training (through NVIDIA Apex) instead of 32-bit training. fp16_opt_level (`str`, *optional*, defaults to 'O1'): For `fp16` training, Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. See details on the [Apex documentation](https://nvidia.github.io/apex/amp). local_rank (`int`, *optional*, defaults to -1): During distributed training, the rank of the process. tpu_num_cores (`int`, *optional*): When training on TPU, the number of TPU cores (automatically passed by launcher script). debug (`bool`, *optional*, defaults to `False`): Whether to activate the trace to record computation graphs and profiling information or not. dataloader_drop_last (`bool`, *optional*, defaults to `False`): Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. eval_steps (`int`, *optional*, defaults to 1000): Number of update steps before two evaluations. past_index (`int`, *optional*, defaults to -1): Some models like [TransformerXL](../model_doc/transformerxl) or :doc*XLNet <../model_doc/xlnet>* can make use of the past hidden states for their predictions. If this argument is set to a positive int, the `Trainer` will use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argument `mems`. tpu_name (`str`, *optional*): The name of the TPU the process is running on. tpu_zone (`str`, *optional*): The zone of the TPU the process is running on. If not specified, we will attempt to automatically detect from metadata. gcp_project (`str`, *optional*): Google Cloud Project name for the Cloud TPU-enabled project. If not specified, we will attempt to automatically detect from metadata. run_name (`str`, *optional*): A descriptor for the run. Notably used for wandb logging. xla (`bool`, *optional*): Whether to activate the XLA compilation or not. """ framework = "tf" tpu_name: Optional[str] = field( default=None, metadata={"help": "Name of TPU"}, ) tpu_zone: Optional[str] = field( default=None, metadata={"help": "Zone of TPU"}, ) gcp_project: Optional[str] = field( default=None, metadata={"help": "Name of Cloud TPU-enabled project"}, ) poly_power: float = field( default=1.0, metadata={"help": "Power for the Polynomial decay LR scheduler."}, ) xla: bool = field(default=False, metadata={"help": "Whether to activate the XLA compilation or not"}) @cached_property def _setup_strategy(self) -> Tuple["tf.distribute.Strategy", int]: requires_backends(self, ["tf"]) logger.info("Tensorflow: setting up strategy") gpus = tf.config.list_physical_devices("GPU") # Set to float16 at first if self.fp16: tf.keras.mixed_precision.set_global_policy("mixed_float16") if self.no_cuda: strategy = tf.distribute.OneDeviceStrategy(device="/cpu:0") else: try: if self.tpu_name: tpu = tf.distribute.cluster_resolver.TPUClusterResolver( self.tpu_name, zone=self.tpu_zone, project=self.gcp_project ) else: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: if self.tpu_name: raise RuntimeError(f"Couldn't connect to TPU {self.tpu_name}!") else: tpu = None if tpu: # Set to bfloat16 in case of TPU if self.fp16: tf.keras.mixed_precision.set_global_policy("mixed_bfloat16") tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.TPUStrategy(tpu) elif len(gpus) == 0: strategy = tf.distribute.OneDeviceStrategy(device="/cpu:0") elif len(gpus) == 1: strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0") elif len(gpus) > 1: # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` strategy = tf.distribute.MirroredStrategy() else: raise ValueError("Cannot find the proper strategy, please check your environment properties.") return strategy @property def strategy(self) -> "tf.distribute.Strategy": """ The strategy used for distributed training. """ requires_backends(self, ["tf"]) return self._setup_strategy @property def n_replicas(self) -> int: """ The number of replicas (CPUs, GPUs or TPU cores) used in this training. """ requires_backends(self, ["tf"]) return self._setup_strategy.num_replicas_in_sync @property def train_batch_size(self) -> int: """ The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training). """ if self.per_gpu_train_batch_size: logger.warning( "Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future " "version. Using `--per_device_train_batch_size` is preferred." ) per_device_batch_size = self.per_gpu_train_batch_size or self.per_device_train_batch_size return per_device_batch_size * self.n_replicas @property def eval_batch_size(self) -> int: """ The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training). """ if self.per_gpu_eval_batch_size: logger.warning( "Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future " "version. Using `--per_device_eval_batch_size` is preferred." ) per_device_batch_size = self.per_gpu_eval_batch_size or self.per_device_eval_batch_size return per_device_batch_size * self.n_replicas @property def n_gpu(self) -> int: """ The number of replicas (CPUs, GPUs or TPU cores) used in this training. """ requires_backends(self, ["tf"]) warnings.warn( "The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead.", FutureWarning, ) return self._setup_strategy.num_replicas_in_sync
27182812/ChatGLM-LLaMA-chinese-insturct
12,243
src/transformers/trainer_seq2seq.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 Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import Dataset from .deepspeed import is_deepspeed_zero3_enabled from .trainer import Trainer from .trainer_utils import PredictionOutput from .utils import logging logger = logging.get_logger(__name__) class Seq2SeqTrainer(Trainer): def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", **gen_kwargs, ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: eval_dataset (`Dataset`, *optional*): Pass a dataset if you wish to override `self.eval_dataset`. If it is an [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. It must implement the `__len__` method. ignore_keys (`List[str]`, *optional*): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (`str`, *optional*, defaults to `"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is `"eval"` (default) max_length (`int`, *optional*): The maximum target length to use when predicting with the generate method. num_beams (`int`, *optional*): Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search. gen_kwargs: Additional `generate` specific kwargs. Returns: A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The dictionary also contains the epoch number which comes from the training state. """ gen_kwargs = gen_kwargs.copy() if gen_kwargs.get("max_length") is None and gen_kwargs.get("max_new_tokens") is None: gen_kwargs["max_length"] = self.args.generation_max_length gen_kwargs["num_beams"] = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams") is not None else self.args.generation_num_beams ) self._gen_kwargs = gen_kwargs return super().evaluate(eval_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix) def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test", **gen_kwargs, ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset (`Dataset`): Dataset to run the predictions on. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. Has to implement the method `__len__` ignore_keys (`List[str]`, *optional*): A list of keys in the output of your model (if it is a dictionary) that should be ignored when gathering predictions. metric_key_prefix (`str`, *optional*, defaults to `"eval"`): An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named "eval_bleu" if the prefix is `"eval"` (default) max_length (`int`, *optional*): The maximum target length to use when predicting with the generate method. num_beams (`int`, *optional*): Number of beams for beam search that will be used when predicting with the generate method. 1 means no beam search. gen_kwargs: Additional `generate` specific kwargs. <Tip> If your predictions or labels have different sequence lengths (for instance because you're doing dynamic padding in a token classification task) the predictions will be padded (on the right) to allow for concatenation into one array. The padding index is -100. </Tip> Returns: *NamedTuple* A namedtuple with the following keys: - predictions (`np.ndarray`): The predictions on `test_dataset`. - label_ids (`np.ndarray`, *optional*): The labels (if the dataset contained some). - metrics (`Dict[str, float]`, *optional*): The potential dictionary of metrics (if the dataset contained labels). """ gen_kwargs = gen_kwargs.copy() if gen_kwargs.get("max_length") is None and gen_kwargs.get("max_new_tokens") is None: gen_kwargs["max_length"] = self.args.generation_max_length gen_kwargs["num_beams"] = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams") is not None else self.args.generation_num_beams ) self._gen_kwargs = gen_kwargs return super().predict(test_dataset, ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix) def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: """ Perform an evaluation step on `model` using `inputs`. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to evaluate. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. The dictionary will be unpacked before being fed to the model. Most models expect the targets under the argument `labels`. Check your model's documentation for all accepted arguments. prediction_loss_only (`bool`): Whether or not to return the loss only. Return: Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and labels (each being optional). """ if not self.args.predict_with_generate or prediction_loss_only: return super().prediction_step( model, inputs, prediction_loss_only=prediction_loss_only, ignore_keys=ignore_keys ) has_labels = "labels" in inputs inputs = self._prepare_inputs(inputs) # XXX: adapt synced_gpus for fairscale as well gen_kwargs = self._gen_kwargs.copy() if gen_kwargs.get("max_length") is None and gen_kwargs.get("max_new_tokens") is None: gen_kwargs["max_length"] = self.model.config.max_length gen_kwargs["num_beams"] = ( gen_kwargs["num_beams"] if gen_kwargs.get("num_beams") is not None else self.model.config.num_beams ) default_synced_gpus = True if is_deepspeed_zero3_enabled() else False gen_kwargs["synced_gpus"] = ( gen_kwargs["synced_gpus"] if gen_kwargs.get("synced_gpus") is not None else default_synced_gpus ) if "attention_mask" in inputs: gen_kwargs["attention_mask"] = inputs.get("attention_mask", None) if "global_attention_mask" in inputs: gen_kwargs["global_attention_mask"] = inputs.get("global_attention_mask", None) # prepare generation inputs # some encoder-decoder models can have varying encoder's and thus # varying model input names if hasattr(self.model, "encoder") and self.model.encoder.main_input_name != self.model.main_input_name: generation_inputs = inputs[self.model.encoder.main_input_name] else: generation_inputs = inputs[self.model.main_input_name] generated_tokens = self.model.generate( generation_inputs, **gen_kwargs, ) # Temporary hack to ensure the generation config is not initialized for each iteration of the evaluation loop # TODO: remove this hack when the legacy code that initializes generation_config from a model config is # removed in https://github.com/huggingface/transformers/blob/98d88b23f54e5a23e741833f1e973fdf600cc2c5/src/transformers/generation/utils.py#L1183 if self.model.generation_config._from_model_config: self.model.generation_config._from_model_config = False # in case the batch is shorter than max length, the output should be padded if gen_kwargs.get("max_length") is not None and generated_tokens.shape[-1] < gen_kwargs["max_length"]: generated_tokens = self._pad_tensors_to_max_len(generated_tokens, gen_kwargs["max_length"]) elif gen_kwargs.get("max_new_tokens") is not None and generated_tokens.shape[-1] < ( gen_kwargs["max_new_tokens"] + 1 ): generated_tokens = self._pad_tensors_to_max_len(generated_tokens, gen_kwargs["max_new_tokens"] + 1) with torch.no_grad(): if has_labels: with self.compute_loss_context_manager(): outputs = model(**inputs) if self.label_smoother is not None: loss = self.label_smoother(outputs, inputs["labels"]).mean().detach() else: loss = (outputs["loss"] if isinstance(outputs, dict) else outputs[0]).mean().detach() else: loss = None if self.args.prediction_loss_only: return (loss, None, None) if has_labels: labels = inputs["labels"] if gen_kwargs.get("max_length") is not None and labels.shape[-1] < gen_kwargs["max_length"]: labels = self._pad_tensors_to_max_len(labels, gen_kwargs["max_length"]) elif gen_kwargs.get("max_new_tokens") is not None and labels.shape[-1] < ( gen_kwargs["max_new_tokens"] + 1 ): labels = self._pad_tensors_to_max_len(labels, (gen_kwargs["max_new_tokens"] + 1)) else: labels = None return (loss, generated_tokens, labels) def _pad_tensors_to_max_len(self, tensor, max_length): if self.tokenizer is not None and hasattr(self.tokenizer, "pad_token_id"): # If PAD token is not defined at least EOS token has to be defined pad_token_id = ( self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.tokenizer.eos_token_id ) else: if self.model.config.pad_token_id is not None: pad_token_id = self.model.config.pad_token_id else: raise ValueError("Pad_token_id must be set in the configuration of the model, in order to pad tensors") padded_tensor = pad_token_id * torch.ones( (tensor.shape[0], max_length), dtype=tensor.dtype, device=tensor.device ) padded_tensor[:, : tensor.shape[-1]] = tensor return padded_tensor
27182812/ChatGLM-LLaMA-chinese-insturct
1,109
src/transformers/generation_tf_utils.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. import warnings from .generation import TFGenerationMixin class TFGenerationMixin(TFGenerationMixin): # warning at import time warnings.warn( "Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will " "be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead.", FutureWarning, )
233zzh/TitanDataOperationSystem
5,467
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/visitors/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Visitors</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.selection.js"></script> <script type="text/javascript"> $(function() { var d = [[1196463600000, 0], [1196550000000, 0], [1196636400000, 0], [1196722800000, 77], [1196809200000, 3636], [1196895600000, 3575], [1196982000000, 2736], [1197068400000, 1086], [1197154800000, 676], [1197241200000, 1205], [1197327600000, 906], [1197414000000, 710], [1197500400000, 639], [1197586800000, 540], [1197673200000, 435], [1197759600000, 301], [1197846000000, 575], [1197932400000, 481], [1198018800000, 591], [1198105200000, 608], [1198191600000, 459], [1198278000000, 234], [1198364400000, 1352], [1198450800000, 686], [1198537200000, 279], [1198623600000, 449], [1198710000000, 468], [1198796400000, 392], [1198882800000, 282], [1198969200000, 208], [1199055600000, 229], [1199142000000, 177], [1199228400000, 374], [1199314800000, 436], [1199401200000, 404], [1199487600000, 253], [1199574000000, 218], [1199660400000, 476], [1199746800000, 462], [1199833200000, 448], [1199919600000, 442], [1200006000000, 403], [1200092400000, 204], [1200178800000, 194], [1200265200000, 327], [1200351600000, 374], [1200438000000, 507], [1200524400000, 546], [1200610800000, 482], [1200697200000, 283], [1200783600000, 221], [1200870000000, 483], [1200956400000, 523], [1201042800000, 528], [1201129200000, 483], [1201215600000, 452], [1201302000000, 270], [1201388400000, 222], [1201474800000, 439], [1201561200000, 559], [1201647600000, 521], [1201734000000, 477], [1201820400000, 442], [1201906800000, 252], [1201993200000, 236], [1202079600000, 525], [1202166000000, 477], [1202252400000, 386], [1202338800000, 409], [1202425200000, 408], [1202511600000, 237], [1202598000000, 193], [1202684400000, 357], [1202770800000, 414], [1202857200000, 393], [1202943600000, 353], [1203030000000, 364], [1203116400000, 215], [1203202800000, 214], [1203289200000, 356], [1203375600000, 399], [1203462000000, 334], [1203548400000, 348], [1203634800000, 243], [1203721200000, 126], [1203807600000, 157], [1203894000000, 288]]; // first correct the timestamps - they are recorded as the daily // midnights in UTC+0100, but Flot always displays dates in UTC // so we have to add one hour to hit the midnights in the plot for (var i = 0; i < d.length; ++i) { d[i][0] += 60 * 60 * 1000; } // helper for returning the weekends in a period function weekendAreas(axes) { var markings = [], d = new Date(axes.xaxis.min); // go to the first Saturday d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7)) d.setUTCSeconds(0); d.setUTCMinutes(0); d.setUTCHours(0); var i = d.getTime(); // when we don't set yaxis, the rectangle automatically // extends to infinity upwards and downwards do { markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } }); i += 7 * 24 * 60 * 60 * 1000; } while (i < axes.xaxis.max); return markings; } var options = { xaxis: { mode: "time", tickLength: 5 }, selection: { mode: "x" }, grid: { markings: weekendAreas } }; var plot = $.plot("#placeholder", [d], options); var overview = $.plot("#overview", [d], { series: { lines: { show: true, lineWidth: 1 }, shadowSize: 0 }, xaxis: { ticks: [], mode: "time" }, yaxis: { ticks: [], min: 0, autoscaleMargin: 0.1 }, selection: { mode: "x" } }); // now connect the two $("#placeholder").bind("plotselected", function (event, ranges) { // do the zooming $.each(plot.getXAxes(), function(_, axis) { var opts = axis.options; opts.min = ranges.xaxis.from; opts.max = ranges.xaxis.to; }); plot.setupGrid(); plot.draw(); plot.clearSelection(); // don't fire event on the overview to prevent eternal loop overview.setSelection(ranges, true); }); $("#overview").bind("plotselected", function (event, ranges) { plot.setSelection(ranges); }); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Visitors</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder"></div> </div> <div class="demo-container" style="height:150px;"> <div id="overview" class="demo-placeholder"></div> </div> <p>This plot shows visitors per day to the Flot homepage, with weekends colored.</p> <p>The smaller plot is linked to the main plot, so it acts as an overview. Try dragging a selection on either plot, and watch the behavior of the other.</p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
274056675/springboot-openai-chatgpt
40,782
mng_web/src/research/util/onlyoffice.js
/*! * Copyright (c) Ascensio System SIA 2021. All rights reserved * * http://www.onlyoffice.com * * Version: 6.4.2 (build:6) */ ;(function(DocsAPI, window, document, undefined) { /* # Full # config = { type: 'desktop or mobile or embedded', width: '100% by default', height: '100% by default', documentType: 'word' | 'cell' | 'slide',// deprecate 'text' | 'spreadsheet' | 'presentation', token: <string> encrypted signature document: { title: 'document title', url: 'document url' fileType: 'document file type', options: <advanced options>, key: 'key', vkey: 'vkey', info: { owner: 'owner name', folder: 'path to document', uploaded: '<uploaded date>', sharingSettings: [ { user: 'user name', permissions: '<permissions>', isLink: false }, ... ], favorite: '<file is favorite>' // true/false/undefined (undefined - don't show fav. button) }, permissions: { edit: <can edit>, // default = true download: <can download>, // default = true reader: <can view in readable mode>, review: <can review>, // default = edit print: <can print>, // default = true comment: <can comment in view mode> // default = edit, modifyFilter: <can add, remove and save filter in the spreadsheet> // default = true modifyContentControl: <can modify content controls in documenteditor> // default = true fillForms: <can edit forms in view mode> // default = edit || review, copy: <can copy data> // default = true, editCommentAuthorOnly: <can edit your own comments only> // default = false deleteCommentAuthorOnly: <can delete your own comments only> // default = false, reviewGroups: ["Group1", ""] // current user can accept/reject review changes made by users from Group1 and users without a group. [] - use groups, but can't change any group's changes commentGroups: { // {} - use groups, but can't view/edit/delete any group's comments view: ["Group1", ""] // current user can view comments made by users from Group1 and users without a group. edit: ["Group1", ""] // current user can edit comments made by users from Group1 and users without a group. remove: ["Group1", ""] // current user can remove comments made by users from Group1 and users without a group. } } }, editorConfig: { actionLink: { // open file and scroll to data, used with onMakeActionLink or the onRequestSendNotify event action: { type: "bookmark", // or type="comment" data: <bookmark name> // or comment id } }, mode: 'view or edit', lang: <language code>, location: <location>, canCoAuthoring: <can coauthoring documents>, canBackToFolder: <can return to folder> - deprecated. use "customization.goback" parameter, createUrl: 'create document url', sharingSettingsUrl: 'document sharing settings url', fileChoiceUrl: 'source url', // for mail merge or image from storage callbackUrl: <url for connection between sdk and portal>, mergeFolderUrl: 'folder for saving merged file', // must be deprecated, use saveAsUrl instead saveAsUrl: 'folder for saving files' licenseUrl: <url for license>, customerId: <customer id>, region: <regional settings> // can be 'en-us' or lang code user: { id: 'user id', name: 'user name', group: 'group name' // for customization.reviewPermissions parameter }, recent: [ { title: 'document title', url: 'document url', folder: 'path to document', }, ... ], templates: [ { title: 'template name', // name - is deprecated image: 'template icon url', url: 'http://...' }, ... ], customization: { logo: { image: url, imageEmbedded: url, url: http://... }, customer: { name: 'SuperPuper', address: 'New-York, 125f-25', mail: 'support@gmail.com', www: 'www.superpuper.com', info: 'Some info', logo: '' }, about: true, feedback: { visible: false, url: http://... }, goback: { url: 'http://...', text: 'Go to London', blank: true, requestClose: false // if true - goback send onRequestClose event instead opening url }, reviewPermissions: { "Group1": ["Group2"], // users from Group1 can accept/reject review changes made by users from Group2 "Group2": ["Group1", "Group2"] // users from Group2 can accept/reject review changes made by users from Group1 and Group2 "Group3": [""] // users from Group3 can accept/reject review changes made by users without a group }, anonymous: { // set name for anonymous user request: bool (default: true), // enable set name label: string (default: "Guest") // postfix for user name }, review: { hideReviewDisplay: false, // hide button Review mode hoverMode: false // true - show review balloons on mouse move, not on click on text }, chat: true, comments: true, zoom: 100, compactToolbar: false, leftMenu: true, rightMenu: true, hideRightMenu: false, // hide or show right panel on first loading toolbar: true, statusBar: true, autosave: true, forcesave: false, commentAuthorOnly: false, // must be deprecated. use permissions.editCommentAuthorOnly and permissions.deleteCommentAuthorOnly instead showReviewChanges: false, help: true, compactHeader: false, toolbarNoTabs: false, toolbarHideFileName: false, reviewDisplay: 'original', // original for viewer, markup for editor spellcheck: true, compatibleFeatures: false, unit: 'cm' // cm, pt, inch, mentionShare : true // customize tooltip for mention, macros: true // can run macros in document plugins: true // can run plugins in document macrosMode: 'warn' // warn about automatic macros, 'enable', 'disable', 'warn', trackChanges: undefined // true/false - open editor with track changes mode on/off, hideRulers: false // hide or show rulers on first loading (presentation or document editor) hideNotes: false // hide or show notes panel on first loading (presentation editor) uiTheme: 'theme-dark' // set interface theme: id or default-dark/default-light }, coEditing: { mode: 'fast', // <coauthoring mode>, 'fast' or 'strict'. if 'fast' and 'customization.autosave'=false -> set 'customization.autosave'=true change: true, // can change co-authoring mode }, plugins: { autostart: ['asc.{FFE1F462-1EA2-4391-990D-4CC84940B754}'], pluginsData: [ "helloworld/config.json", "chess/config.json", "speech/config.json", "clipart/config.json", ] }, wopi: { // only for wopi FileNameMaxLength: 250 // max filename length for rename, 250 by default } }, events: { 'onAppReady': <application ready callback>, 'onDocumentStateChange': <document state changed callback> 'onDocumentReady': <document ready callback> 'onRequestEditRights': <request rights for switching from view to edit>, 'onRequestHistory': <request version history>,// must call refreshHistory method 'onRequestHistoryData': <request version data>,// must call setHistoryData method 'onRequestRestore': <try to restore selected version>, 'onRequestHistoryClose': <request closing history>, 'onError': <error callback>, 'onWarning': <warning callback>, 'onInfo': <document open callback>,// send view or edit mode 'onOutdatedVersion': <outdated version callback>,// send when previous version is opened 'onDownloadAs': <download as callback>,// send url of downloaded file as a response for downloadAs method 'onRequestSaveAs': <try to save copy of the document>, 'onCollaborativeChanges': <co-editing changes callback>,// send when other user co-edit document 'onRequestRename': <try to rename document>, 'onMetaChange': // send when meta information changed 'onRequestClose': <request close editor>, 'onMakeActionLink': <request link to document with bookmark, comment...>,// must call setActionLink method 'onRequestUsers': <request users list for mentions>,// must call setUsers method 'onRequestSendNotify': //send when user is mentioned in a comment, 'onRequestInsertImage': <try to insert image>,// must call insertImage method 'onRequestCompareFile': <request file to compare>,// must call setRevisedFile method 'onRequestSharingSettings': <request sharing settings>,// must call setSharingSettings method 'onRequestCreateNew': <try to create document>, } } # Embedded # config = { type: 'embedded', width: '100% by default', height: '100% by default', documentType: 'word' | 'cell' | 'slide',// deprecate 'text' | 'spreadsheet' | 'presentation', document: { title: 'document title', url: 'document url', fileType: 'document file type', key: 'key', vkey: 'vkey' }, editorConfig: { licenseUrl: <url for license>, customerId: <customer id>, autostart: 'document', // action for app's autostart. for presentations default value is 'player' embedded: { embedUrl: 'url', fullscreenUrl: 'url', saveUrl: 'url', shareUrl: 'url', toolbarDocked: 'top or bottom' } }, events: { 'onAppReady': <application ready callback>, 'onBack': <back to folder callback>, 'onError': <error callback>, 'onDocumentReady': <document ready callback>, 'onWarning': <warning callback> } } */ // TODO: allow several instances on one page simultaneously DocsAPI.DocEditor = function(placeholderId, config) { var _self = this, _config = config || {}; extend(_config, DocsAPI.DocEditor.defaultConfig); _config.editorConfig.canUseHistory = _config.events && !!_config.events.onRequestHistory; _config.editorConfig.canHistoryClose = _config.events && !!_config.events.onRequestHistoryClose; _config.editorConfig.canHistoryRestore = _config.events && !!_config.events.onRequestRestore; _config.editorConfig.canSendEmailAddresses = _config.events && !!_config.events.onRequestEmailAddresses; _config.editorConfig.canRequestEditRights = _config.events && !!_config.events.onRequestEditRights; _config.editorConfig.canRequestClose = _config.events && !!_config.events.onRequestClose; _config.editorConfig.canRename = _config.events && !!_config.events.onRequestRename; _config.editorConfig.canMakeActionLink = _config.events && !!_config.events.onMakeActionLink; _config.editorConfig.canRequestUsers = _config.events && !!_config.events.onRequestUsers; _config.editorConfig.canRequestSendNotify = _config.events && !!_config.events.onRequestSendNotify; _config.editorConfig.mergeFolderUrl = _config.editorConfig.mergeFolderUrl || _config.editorConfig.saveAsUrl; _config.editorConfig.canRequestSaveAs = _config.events && !!_config.events.onRequestSaveAs; _config.editorConfig.canRequestInsertImage = _config.events && !!_config.events.onRequestInsertImage; _config.editorConfig.canRequestMailMergeRecipients = _config.events && !!_config.events.onRequestMailMergeRecipients; _config.editorConfig.canRequestCompareFile = _config.events && !!_config.events.onRequestCompareFile; _config.editorConfig.canRequestSharingSettings = _config.events && !!_config.events.onRequestSharingSettings; _config.editorConfig.canRequestCreateNew = _config.events && !!_config.events.onRequestCreateNew; _config.frameEditorId = placeholderId; _config.parentOrigin = window.location.origin; var onMouseUp = function (evt) { _processMouse(evt); }; var _attachMouseEvents = function() { if (window.addEventListener) { window.addEventListener("mouseup", onMouseUp, false) } else if (window.attachEvent) { window.attachEvent("onmouseup", onMouseUp); } }; var _detachMouseEvents = function() { if (window.removeEventListener) { window.removeEventListener("mouseup", onMouseUp, false) } else if (window.detachEvent) { window.detachEvent("onmouseup", onMouseUp); } }; var _onAppReady = function() { if (_config.type === 'mobile') { document.body.onfocus = function(e) { setTimeout(function(){ iframe.contentWindow.focus(); _sendCommand({ command: 'resetFocus', data: {} }) }, 10); }; } _attachMouseEvents(); if (_config.editorConfig) { _init(_config.editorConfig); } if (_config.document) { _openDocument(_config.document); } }; var _callLocalStorage = function(data) { if (data.cmd == 'get') { if (data.keys && data.keys.length) { var af = data.keys.split(','), re = af[0]; for (i = 0; ++i < af.length;) re += '|' + af[i]; re = new RegExp(re); k = {}; for (i in localStorage) if (re.test(i)) k[i] = localStorage[i]; } else { k = localStorage; } _sendCommand({ command: 'internalCommand', data: { type: 'localstorage', keys: k } }); } else if (data.cmd == 'set') { var k = data.keys, i; for (i in k) { localStorage.setItem(i, k[i]); } } }; var _onMessage = function(msg) { if ( msg ) { if ( msg.type === "onExternalPluginMessage" ) { _sendCommand(msg); } else if (msg.type === "onExternalPluginMessageCallback") { postMessage(window.parent, msg); } else if ( msg.frameEditorId == placeholderId ) { var events = _config.events || {}, handler = events[msg.event], res; if (msg.event === 'onRequestEditRights' && !handler) { _applyEditRights(false, 'handler isn\'t defined'); } else if (msg.event === 'onInternalMessage' && msg.data && msg.data.type == 'localstorage') { _callLocalStorage(msg.data.data); } else { if (msg.event === 'onAppReady') { _onAppReady(); } if (handler && typeof handler == "function") { res = handler.call(_self, {target: _self, data: msg.data}); } } } } }; var _checkConfigParams = function() { if (_config.document) { if (!_config.document.url || ((typeof _config.document.fileType !== 'string' || _config.document.fileType=='') && (typeof _config.documentType !== 'string' || _config.documentType==''))) { window.alert("One or more required parameter for the config object is not set"); return false; } var appMap = { 'text': 'docx', 'text-pdf': 'pdf', 'spreadsheet': 'xlsx', 'presentation': 'pptx', 'word': 'docx', 'cell': 'xlsx', 'slide': 'pptx' }, app; if (_config.documentType=='text' || _config.documentType=='spreadsheet' ||_config.documentType=='presentation') console.warn("The \"documentType\" parameter for the config object must take one of the values word/cell/slide."); if (typeof _config.documentType === 'string' && _config.documentType != '') { app = appMap[_config.documentType.toLowerCase()]; if (!app) { window.alert("The \"documentType\" parameter for the config object is invalid. Please correct it."); return false; } else if (typeof _config.document.fileType !== 'string' || _config.document.fileType == '') { _config.document.fileType = app; } } if (typeof _config.document.fileType === 'string' && _config.document.fileType != '') { _config.document.fileType = _config.document.fileType.toLowerCase(); var type = /^(?:(xls|xlsx|ods|csv|xlst|xlsy|gsheet|xlsm|xlt|xltm|xltx|fods|ots)|(pps|ppsx|ppt|pptx|odp|pptt|ppty|gslides|pot|potm|potx|ppsm|pptm|fodp|otp)|(doc|docx|doct|odt|gdoc|txt|rtf|pdf|mht|htm|html|epub|djvu|xps|oxps|docm|dot|dotm|dotx|fodt|ott|fb2|xml))$/ .exec(_config.document.fileType); if (!type) { window.alert("The \"document.fileType\" parameter for the config object is invalid. Please correct it."); return false; } else if (typeof _config.documentType !== 'string' || _config.documentType == ''){ if (typeof type[1] === 'string') _config.documentType = 'cell'; else if (typeof type[2] === 'string') _config.documentType = 'slide'; else if (typeof type[3] === 'string') _config.documentType = 'word'; } } var type = /^(?:(pdf|djvu|xps|oxps))$/.exec(_config.document.fileType); if (type && typeof type[1] === 'string') { _config.editorConfig.canUseHistory = false; } if (!_config.document.title || _config.document.title=='') _config.document.title = 'Unnamed.' + _config.document.fileType; if (!_config.document.key) { _config.document.key = 'xxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, function (c) {var r = Math.random() * 16 | 0; return r.toString(16);}); } else if (typeof _config.document.key !== 'string') { window.alert("The \"document.key\" parameter for the config object must be string. Please correct it."); return false; } if (_config.editorConfig.user && _config.editorConfig.user.id && (typeof _config.editorConfig.user.id == 'number')) { _config.editorConfig.user.id = _config.editorConfig.user.id.toString(); console.warn("The \"id\" parameter for the editorConfig.user object must be a string."); } _config.document.token = _config.token; } return true; }; (function() { var result = /[\?\&]placement=(\w+)&?/.exec(window.location.search); if (!!result && result.length) { if (result[1] == 'desktop') { _config.editorConfig.targetApp = result[1]; // _config.editorConfig.canBackToFolder = false; if (!_config.editorConfig.customization) _config.editorConfig.customization = {}; _config.editorConfig.customization.about = false; _config.editorConfig.customization.compactHeader = false; } } })(); var target = document.getElementById(placeholderId), iframe; if (target && _checkConfigParams()) { iframe = createIframe(_config); if (iframe.src) { var pathArray = iframe.src.split('/'); this.frameOrigin = pathArray[0] + '//' + pathArray[2]; } target.parentNode && target.parentNode.replaceChild(iframe, target); var _msgDispatcher = new MessageDispatcher(_onMessage, this); } /* cmd = { command: 'commandName', data: <command specific data> } */ var _destroyEditor = function(cmd) { var target = document.createElement("div"); target.setAttribute('id', placeholderId); if (iframe) { _msgDispatcher && _msgDispatcher.unbindEvents(); _detachMouseEvents(); iframe.parentNode && iframe.parentNode.replaceChild(target, iframe); } }; var _sendCommand = function(cmd) { if (iframe && iframe.contentWindow) postMessage(iframe.contentWindow, cmd); }; var _init = function(editorConfig) { _sendCommand({ command: 'init', data: { config: editorConfig } }); }; var _openDocument = function(doc) { _sendCommand({ command: 'openDocument', data: { doc: doc } }); }; var _showMessage = function(title, msg) { msg = msg || title; _sendCommand({ command: 'showMessage', data: { msg: msg } }); }; var _applyEditRights = function(allowed, message) { _sendCommand({ command: 'applyEditRights', data: { allowed: allowed, message: message } }); }; var _processSaveResult = function(result, message) { _sendCommand({ command: 'processSaveResult', data: { result: result, message: message } }); }; // TODO: remove processRightsChange, use denyEditingRights var _processRightsChange = function(enabled, message) { _sendCommand({ command: 'processRightsChange', data: { enabled: enabled, message: message } }); }; var _denyEditingRights = function(message) { _sendCommand({ command: 'processRightsChange', data: { enabled: false, message: message } }); }; var _refreshHistory = function(data, message) { _sendCommand({ command: 'refreshHistory', data: { data: data, message: message } }); }; var _setHistoryData = function(data, message) { _sendCommand({ command: 'setHistoryData', data: { data: data, message: message } }); }; var _setEmailAddresses = function(data) { _sendCommand({ command: 'setEmailAddresses', data: { data: data } }); }; var _setActionLink = function (data) { _sendCommand({ command: 'setActionLink', data: { url: data } }); }; var _processMailMerge = function(enabled, message) { _sendCommand({ command: 'processMailMerge', data: { enabled: enabled, message: message } }); }; var _downloadAs = function(data) { _sendCommand({ command: 'downloadAs', data: data }); }; var _setUsers = function(data) { _sendCommand({ command: 'setUsers', data: data }); }; var _showSharingSettings = function(data) { _sendCommand({ command: 'showSharingSettings', data: data }); }; var _setSharingSettings = function(data) { _sendCommand({ command: 'setSharingSettings', data: data }); }; var _insertImage = function(data) { _sendCommand({ command: 'insertImage', data: data }); }; var _setMailMergeRecipients = function(data) { _sendCommand({ command: 'setMailMergeRecipients', data: data }); }; var _setRevisedFile = function(data) { _sendCommand({ command: 'setRevisedFile', data: data }); }; var _setFavorite = function(data) { _sendCommand({ command: 'setFavorite', data: data }); }; var _requestClose = function(data) { _sendCommand({ command: 'requestClose', data: data }); }; var _processMouse = function(evt) { var r = iframe.getBoundingClientRect(); var data = { type: evt.type, x: evt.x - r.left, y: evt.y - r.top, event: evt }; _sendCommand({ command: 'processMouse', data: data }); }; var _grabFocus = function(data) { setTimeout(function(){ _sendCommand({ command: 'grabFocus', data: data }); }, 10); }; var _blurFocus = function(data) { _sendCommand({ command: 'blurFocus', data: data }); }; var _serviceCommand = function(command, data) { _sendCommand({ command: 'internalCommand', data: { command: command, data: data } }); }; return { showMessage : _showMessage, processSaveResult : _processSaveResult, processRightsChange : _processRightsChange, denyEditingRights : _denyEditingRights, refreshHistory : _refreshHistory, setHistoryData : _setHistoryData, setEmailAddresses : _setEmailAddresses, setActionLink : _setActionLink, processMailMerge : _processMailMerge, downloadAs : _downloadAs, serviceCommand : _serviceCommand, attachMouseEvents : _attachMouseEvents, detachMouseEvents : _detachMouseEvents, destroyEditor : _destroyEditor, setUsers : _setUsers, showSharingSettings : _showSharingSettings, setSharingSettings : _setSharingSettings, insertImage : _insertImage, setMailMergeRecipients: _setMailMergeRecipients, setRevisedFile : _setRevisedFile, setFavorite : _setFavorite, requestClose : _requestClose, grabFocus : _grabFocus, blurFocus : _blurFocus } }; DocsAPI.DocEditor.defaultConfig = { type: 'desktop', width: '100%', height: '100%', editorConfig: { lang: 'en', canCoAuthoring: true, customization: { about: true, feedback: false } } }; DocsAPI.DocEditor.version = function() { return '6.4.2'; }; MessageDispatcher = function(fn, scope) { var _fn = fn, _scope = scope || window, eventFn = function(msg) { _onMessage(msg); }; var _bindEvents = function() { if (window.addEventListener) { window.addEventListener("message", eventFn, false) } else if (window.attachEvent) { window.attachEvent("onmessage", eventFn); } }; var _unbindEvents = function() { if (window.removeEventListener) { window.removeEventListener("message", eventFn, false) } else if (window.detachEvent) { window.detachEvent("onmessage", eventFn); } }; var _onMessage = function(msg) { // TODO: check message origin if (msg && window.JSON && _scope.frameOrigin==msg.origin ) { try { var msg = window.JSON.parse(msg.data); if (_fn) { _fn.call(_scope, msg); } } catch(e) {} } }; _bindEvents.call(this); return { unbindEvents: _unbindEvents } }; function getBasePath() { var scripts = document.getElementsByTagName('script'), match; for (var i = scripts.length - 1; i >= 0; i--) { match = scripts[i].src.match(/(.*)api\/documents\/api.js/i); if (match) { return match[1]; } } return ""; } function getExtensionPath() { if ("undefined" == typeof(extensionParams) || null == extensionParams["url"]) return null; return extensionParams["url"] + "apps/"; } function getAppPath(config) { var extensionPath = getExtensionPath(), path = extensionPath ? extensionPath : getBasePath(), appMap = { 'text': 'documenteditor', 'text-pdf': 'documenteditor', 'spreadsheet': 'spreadsheeteditor', 'presentation': 'presentationeditor', 'word': 'documenteditor', 'cell': 'spreadsheeteditor', 'slide': 'presentationeditor' }, app = appMap['word']; if (typeof config.documentType === 'string') { app = appMap[config.documentType.toLowerCase()]; } else if (!!config.document && typeof config.document.fileType === 'string') { var type = /^(?:(xls|xlsx|ods|csv|xlst|xlsy|gsheet|xlsm|xlt|xltm|xltx|fods|ots)|(pps|ppsx|ppt|pptx|odp|pptt|ppty|gslides|pot|potm|potx|ppsm|pptm|fodp|otp))$/ .exec(config.document.fileType); if (type) { if (typeof type[1] === 'string') app = appMap['cell']; else if (typeof type[2] === 'string') app = appMap['slide']; } } var userAgent = navigator.userAgent.toLowerCase(), check = function(regex){ return regex.test(userAgent); }, isIE = !check(/opera/) && (check(/msie/) || check(/trident/) || check(/edge/)), isChrome = !isIE && check(/\bchrome\b/), isSafari_mobile = !isIE && !isChrome && check(/safari/) && (navigator.maxTouchPoints>0); path += app + "/"; path += (config.type === "mobile" || isSafari_mobile) ? "mobile" : (config.type === "embedded") ? "embed" : "main"; var index = "/index.html"; if (config.editorConfig) { var customization = config.editorConfig.customization; if ( typeof(customization) == 'object' && ( customization.toolbarNoTabs || (config.editorConfig.targetApp!=='desktop') && (customization.loaderName || customization.loaderLogo))) { index = "/index_loader.html"; } else if (config.editorConfig.mode == 'editdiagram' || config.editorConfig.mode == 'editmerge') index = "/index_internal.html"; } path += index; return path; } function getAppParameters(config) { var params = "?_dc=6.4.2-6"; if (config.editorConfig && config.editorConfig.lang) params += "&lang=" + config.editorConfig.lang; if (config.editorConfig && config.editorConfig.targetApp!=='desktop') { if ( (typeof(config.editorConfig.customization) == 'object') && config.editorConfig.customization.loaderName) { if (config.editorConfig.customization.loaderName !== 'none') params += "&customer=" + encodeURIComponent(config.editorConfig.customization.loaderName); } else params += "&customer=ONLYOFFICE"; if ( (typeof(config.editorConfig.customization) == 'object') && config.editorConfig.customization.loaderLogo) { if (config.editorConfig.customization.loaderLogo !== '') params += "&logo=" + encodeURIComponent(config.editorConfig.customization.loaderLogo); } else if ( (typeof(config.editorConfig.customization) == 'object') && config.editorConfig.customization.logo) { if (config.type=='embedded' && config.editorConfig.customization.logo.imageEmbedded) params += "&headerlogo=" + encodeURIComponent(config.editorConfig.customization.logo.imageEmbedded); else if (config.type!='embedded' && config.editorConfig.customization.logo.image) params += "&headerlogo=" + encodeURIComponent(config.editorConfig.customization.logo.image); } } if (config.editorConfig && (config.editorConfig.mode == 'editdiagram' || config.editorConfig.mode == 'editmerge')) params += "&internal=true"; if (config.frameEditorId) params += "&frameEditorId=" + config.frameEditorId; if (config.editorConfig && config.editorConfig.mode == 'view' || config.document && config.document.permissions && (config.document.permissions.edit === false && !config.document.permissions.review )) params += "&mode=view"; if (config.editorConfig && config.editorConfig.customization && !!config.editorConfig.customization.compactHeader) params += "&compact=true"; if (config.editorConfig && config.editorConfig.customization && (config.editorConfig.customization.toolbar===false)) params += "&toolbar=false"; else if (config.document && config.document.permissions && (config.document.permissions.edit === false && config.document.permissions.fillForms )) params += "&toolbar=true"; if (config.parentOrigin) params += "&parentOrigin=" + config.parentOrigin; if (config.editorConfig && config.editorConfig.customization && config.editorConfig.customization.uiTheme ) params += "&uitheme=" + config.editorConfig.customization.uiTheme; return params; } function createIframe(config) { var iframe = document.createElement("iframe"); iframe.src = getAppPath(config) + getAppParameters(config); iframe.width = config.width; iframe.height = config.height; iframe.align = "top"; iframe.frameBorder = 0; iframe.name = "frameEditor"; iframe.allowFullscreen = true; iframe.setAttribute("allowfullscreen",""); // for IE11 iframe.setAttribute("onmousewheel",""); // for Safari on Mac iframe.setAttribute("allow", "autoplay; camera; microphone; display-capture"); if (config.type == "mobile") { iframe.style.position = "fixed"; iframe.style.overflow = "hidden"; document.body.style.overscrollBehaviorY = "contain"; } return iframe; } function postMessage(wnd, msg) { if (wnd && wnd.postMessage && window.JSON) { // TODO: specify explicit origin wnd.postMessage(window.JSON.stringify(msg), "*"); } } function extend(dest, src) { for (var prop in src) { if (src.hasOwnProperty(prop)) { if (typeof dest[prop] === 'undefined') { dest[prop] = src[prop]; } else if (typeof dest[prop] === 'object' && typeof src[prop] === 'object') { extend(dest[prop], src[prop]) } } } return dest; } })(window.DocsAPI = window.DocsAPI || {}, window, document);
274056675/springboot-openai-chatgpt
8,919
mng_web/src/research/util/myUtil.js
export const setTreeDataUtil = ( arr, parentidKeyName, idName = 'id', topPidDefault = 0, delHasChild) => { // 处理成树结构数据 //树结构数据处理方法 arr:数据 parentidKeyName:父id的key名 idName:id的key名 topPidDefault最顶级pid的值 if (delHasChild) { arr = arr.map((item) => { delete item[delHasChild] return item }) } let data = arr let menuArr = [] let childrenObj = {} data.forEach((item) => { if ( item[parentidKeyName] != topPidDefault && item[parentidKeyName] != null && item[parentidKeyName] != '' ) { if (childrenObj[item[parentidKeyName]] == undefined) { childrenObj[item[parentidKeyName]] = [] } childrenObj[item[parentidKeyName]] = [ ...childrenObj[item[parentidKeyName]], item, ] } else { menuArr.push(item) } }) menuArr.map((item) => { childrenFun(item) }) function childrenFun (obj) { if (childrenObj[obj[idName]] && !obj.isScope) { obj.children = childrenObj[obj[idName]] obj.children.map((item) => { return childrenFun(item) }) } else { return obj } } return menuArr } export const findFlowStepDataFun = (json, resourceId, option) => { //查找当前流程的下一步 return new Promise(resolve => { let columnKey = [] let column = option.column; let group = option.group; let dataArr = []; if (column) { dataArr = [...dataArr, ...column]; } if (group) { dataArr = [...dataArr, ...group]; } columnKey = dataArr.map((item) => item.prop); columnKey = columnKey.filter(item => item); let step = json.childShapes //当前步骤 let currStep = {} step.forEach((item) => { if (item.resourceId == resourceId) { currStep = item } }) //下一步箭头 let nextId = [] currStep.outgoing.forEach(outItem => { nextId.push(outItem.resourceId) }) let nextArrows = [] step.forEach(item => { if (nextId.includes(item.resourceId)) { nextArrows.push(item) } }) //下一步流程走向 let succeedId = [] let failId = [] nextArrows.forEach(item => { let arrows = item.properties.conditionsequenceflow if (arrows && arrows.expression) { if (arrows.expression.staticValue == "${pass}") { succeedId.push(item.outgoing[0].resourceId) } else if (arrows.expression.staticValue == "${!pass}") { failId.push(item.outgoing[0].resourceId) } else { succeedId.push(item.outgoing[0].resourceId) } } else { succeedId.push(item.outgoing[0].resourceId) } }) let flowArr = [] //获取 审批通过/驳回指向的流程数据 step.forEach((item) => { if (succeedId.length > 0 && item.resourceId == succeedId[0]) { flowArr.push({ succeed: true, data: item }) } if (failId.length > 0 && item.resourceId == failId[0]) { flowArr.push({ succeed: false, data: item }) } }) //获取流程 指定候选组 flowArr = flowArr.map(item => { let task = item.data.properties.usertaskassignment if (task && task.assignment) { //已绑定分配人 忽略候选 if (task.assignment.candidateGroups && task.assignment.candidateGroups.length > 0) { //获取候选组绑定的角色 let groups = [] task.assignment.candidateGroups.forEach(groupItem => { let key = groupItem.value.replace('${', '').replace('}', '') if (!(columnKey.includes(key))) { groups.push(key) } }) item.groups = groups } } return item }) resolve(flowArr) }) } export const findFlowCandRoleDataFun = (json) => { //查找所有流程候选组配置的角色 return new Promise(resolve => { let step = json.childShapes let roleArr = [] step.forEach(item => { let task = item.properties.usertaskassignment if (task && task.assignment) { if (task.assignment.candidateGroups && task.assignment.candidateGroups.length > 0) { task.assignment.candidateGroups.forEach(groupItem => { let key = groupItem.value.replace('${', '').replace('}', '') if (key && key.indexOf('role_') == 0 && (!roleArr.includes(key))) { roleArr.push(key) } }) } } }) resolve(roleArr) }) } export const findFlowCurrTowardsFun = (json, resourceId) => { //查找当前流程走向 return new Promise(resolve => { let step = json.childShapes //当前步骤 let currStep = {} step.forEach((item) => { if (item.resourceId == resourceId) { currStep = item } }) //下一步箭头id let nextId = [] currStep.outgoing.forEach(outItem => { nextId.push(outItem.resourceId) }) let nextArrows = [] let countersign = false //是否会签 step.forEach(item => { if (nextId.includes(item.resourceId)) { nextArrows.push(item) if (item.properties.multiinstance_type != 'None') { countersign = true } } }) //下一步流程走向 let succeedId = [] let failId = [] let obj = { agreeBtn: false, disagreeBtn: false, } nextArrows.forEach(item => { let arrows = item.properties.conditionsequenceflow if (arrows && arrows.expression) { if (arrows.expression.staticValue == "${pass}") { succeedId.push(item.outgoing[0].resourceId) obj.agreeText = item.properties.name } else if (arrows.expression.staticValue == "${!pass}") { failId.push(item.outgoing[0].resourceId) obj.disagreeText = item.properties.name } else { succeedId.push(item.outgoing[0].resourceId) obj.agreeText = item.properties.name } } else if (arrows == '${pass}') { succeedId.push(item.outgoing[0].resourceId) obj.agreeText = item.properties.name } else if (arrows == "${!pass}") { failId.push(item.outgoing[0].resourceId) obj.disagreeText = item.properties.name } else { succeedId.push(item.outgoing[0].resourceId) obj.agreeText = item.properties.name } }) if (succeedId.length > 0) { obj.agreeBtn = true } if (failId.length > 0) { obj.disagreeBtn = true } if (countersign && failId.length <= 0) { obj.disagreeBtn = true obj.disagreeText = '驳回' } resolve(obj) }) } export const analysisFunction = (fun) => { if (fun) { // fun = fun.replace(/↵/g, '\n') fun = fun.replace(/\/\*{1,2}[\s\S]*?\*\//gis, '') // fun = fun.replace(/(?:^|\n|\r)\s*\/\*[\s\S]*?\*\/\s*(?:\r|\n|$)/g, '') fun = fun.replace(/(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/g, '') // fun = fun.replace('&lt;', '<') try { if (eval(`(${fun})`)) { return eval(`(${fun})`) } else { return () => { } } } catch { return false } } } export const getStrDataFunction = (str) => { return analysisFunction( `function getData(){${str}}` )(); } export const findParentNodeFun = (el, findName, topName) => { /* el:dom元素 findName:查找的class名 topName:class顶级 */ let parentNode = el.parentNode let classArr = parentNode.className.split(' ') if (classArr.includes(findName)) { return parentNode } else if (classArr.includes(topName) || parentNode.tagName == 'BODY') { return '' } return findParentNodeFun(el.parentNode, findName, topName) } export const downloadFileFun = (data, name = "文件") => { //文件下载 let blob = new Blob([data], { type: 'application/vnd.ms-excel', name: name, }) let url = window.URL.createObjectURL(blob) var a = document.createElement('a') document.body.appendChild(a) a.style = 'display: none' a.href = url a.download = name a.click() window.URL.revokeObjectURL(url) } export const getCurrentDateFun = (type) => { let now = new Date(); let year = now.getFullYear(); //获取完整的年份(4位,1970-????) let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月) let today = now.getDate(); //获取当前日(1-31) let hour = now.getHours(); //获取当前小时数(0-23) let minute = now.getMinutes(); //获取当前分钟数(0-59) let second = now.getSeconds(); //获取当前秒数(0-59) let nowTime = '' if (type == 'data') { nowTime = year + '-' + fillZero(month) + '-' + fillZero(today) } else if (type == 'time') { nowTime = fillZero(hour) + ':' + fillZero(minute) + ':' + fillZero(second) } else if (type == 'SplicingTime') { //用于根据时间生成编号 nowTime = year + fillZero(month) + fillZero(today) + fillZero(hour) + fillZero(minute) + fillZero(second) } else { nowTime = year + '-' + fillZero(month) + '-' + fillZero(today) + ' ' + fillZero(hour) + ':' + fillZero(minute) + ':' + fillZero(second) } return nowTime } function fillZero (str) { var realNum; if (str < 10) { realNum = '0' + str; } else { realNum = str; } return realNum; }
274056675/springboot-openai-chatgpt
4,309
mng_web/src/research/mixins/form.js
/* 当前mixins使用于表单设计器 */ // import request from '@/router/axios'; import { getRemoteValuesApi, executeRuleByApi, getSelectRemoteDataApi, getJsOrCssStrApi, getActionApi, postActionApi, putActionApi, deleteActionApi, requestActionApi } from "@/api/research/form"; export default { data() { return { } }, mounted() { }, methods: { //远程接口取值 column:所有的字段配置 mixinGetApiData(column) { return new Promise(async (resolve) => { let formObj = {} let specialObj = {} //特殊的 let formKey = [] let promiseArr = [] column.forEach(item => { if (item.getValueApiName) { let url = item.getValueApiName if (url.indexOf('/') == 0) { url = '/api' + url } formKey.push({ prop: item.prop, type: item.type }) promiseArr.push( getRemoteValuesApi(url) ) } }); let resArr = await Promise.all(promiseArr) resArr.forEach((item, index) => { if (!['title'].includes(formKey[index].type)) { formObj[formKey[index].prop] = item.data } else { specialObj[formKey[index].prop] = { data: item.data, type: formKey[index].type } } }) resolve({ formObj, specialObj }) }) }, //填值规则 column:所有的字段配置 commonFormData:表单的所有值 mixinGetExecuteRule(column, commonFormData) { return new Promise(async (resolve) => { let rules = [] column.forEach(item => { if (item.fillRuleCode) { rules.push({ ruleCode: item.fillRuleCode, }) } }) if (rules.length == 0) { resolve(false) return false } let res = await executeRuleByApi({ rules, commonFormData }) let ruleResObj = {} res.data.data.forEach(item => { ruleResObj[item.ruleCode] = item.result }) if (res.data.success) { resolve(ruleResObj) } else { resolve(false) } }) }, //选择字段远端数据 mixinGetSelectRemoteData(url, format) { return new Promise(async (resolve) => { if (url.indexOf('/') == 0) { url = '/api' + url } let res = await getSelectRemoteDataApi(url) let data = res.data try { if (format) { format = format.split('.') format.forEach(item => { data = data[item] }) } } catch (error) { console.warn('字段远端数据值格式配置异常,url:', url) } resolve(data) }) }, //js增强 接口请求api mixinRequestData(url, parameter, method, type, config) { return new Promise(async (resolve, reject) => { if (url.indexOf('/') == 0) { url = '/api' + url } if (type == 'request') { requestActionApi(url, parameter, method).then(res => { resolve(res.data) }).catch(err => { reject(err) }) } if (method == 'get' && !type) { getActionApi(url, parameter, config).then(res => { resolve(res.data) }).catch(err => { reject(err) }) } if (method == 'post' && !type) { postActionApi(url, parameter, config).then(res => { resolve(res.data) }).catch(err => { reject(err) }) } if (method == 'put' && !type) { putActionApi(url, parameter, config).then(res => { resolve(res.data) }).catch(err => { reject(err) }) } if (method == 'delete' && !type) { deleteActionApi(url, parameter, config).then(res => { resolve(res.data) }).catch(err => { reject(err) }) } }) }, //js/css外部增强 mixinExternalEnhance(url) { return new Promise(async (resolve) => { let res = {} if (url.indexOf('/') == 0) { url = '/api' + url } res = await getJsOrCssStrApi(url) resolve(res.data) }) }, }, }
233zzh/TitanDataOperationSystem
2,146
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/image/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Image Plots</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.image.js"></script> <script type="text/javascript"> $(function() { var data = [[["hs-2004-27-a-large-web.jpg", -10, -10, 10, 10]]]; var options = { series: { images: { show: true } }, xaxis: { min: -8, max: 4 }, yaxis: { min: -8, max: 4 } }; $.plot.image.loadDataImages(data, options, function () { $.plot("#placeholder", data, options); }); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Image Plots</h2> </div> <div id="content"> <div class="demo-container" style="width:600px;height:600px;"> <div id="placeholder" class="demo-placeholder"></div> </div> <p>The Cat's Eye Nebula (<a href="http://hubblesite.org/gallery/album/nebula/pr2004027a/">picture from Hubble</a>).</p> <p>With the image plugin, you can plot static images against a set of axes. This is for useful for adding ticks to complex prerendered visualizations. Instead of inputting data points, you specify the images and where their two opposite corners are supposed to be in plot space.</p> <p>Images represent a little further complication because you need to make sure they are loaded before you can use them (Flot skips incomplete images). The plugin comes with a couple of helpers for doing that.</p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
27182812/ChatGLM-LLaMA-chinese-insturct
34,975
src/transformers/modelcard.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. """ Configuration base class and utilities.""" import copy import json import os import warnings from dataclasses import dataclass from pathlib import Path from typing import Any, Dict, List, Optional, Union import requests import yaml from huggingface_hub import model_info from huggingface_hub.utils import HFValidationError from . import __version__ from .models.auto.modeling_auto import ( MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_FOR_CTC_MAPPING_NAMES, MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, ) from .training_args import ParallelMode from .utils import ( MODEL_CARD_NAME, cached_file, is_datasets_available, is_offline_mode, is_tf_available, is_tokenizers_available, is_torch_available, logging, ) TASK_MAPPING = { "text-generation": MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, "image-classification": MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, "image-segmentation": MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, "fill-mask": MODEL_FOR_MASKED_LM_MAPPING_NAMES, "object-detection": MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, "question-answering": MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, "text2text-generation": MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, "text-classification": MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, "table-question-answering": MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES, "token-classification": MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, "audio-classification": MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, "automatic-speech-recognition": {**MODEL_FOR_CTC_MAPPING_NAMES, **MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES}, } logger = logging.get_logger(__name__) class ModelCard: r""" Structured Model Card class. Store model card as well as methods for loading/downloading/saving model cards. Please read the following paper for details and explanation on the sections: "Model Cards for Model Reporting" by Margaret Mitchell, Simone Wu, Andrew Zaldivar, Parker Barnes, Lucy Vasserman, Ben Hutchinson, Elena Spitzer, Inioluwa Deborah Raji and Timnit Gebru for the proposal behind model cards. Link: https://arxiv.org/abs/1810.03993 Note: A model card can be loaded and saved to disk. """ def __init__(self, **kwargs): warnings.warn( "The class `ModelCard` is deprecated and will be removed in version 5 of Transformers", FutureWarning ) # Recommended attributes from https://arxiv.org/abs/1810.03993 (see papers) self.model_details = kwargs.pop("model_details", {}) self.intended_use = kwargs.pop("intended_use", {}) self.factors = kwargs.pop("factors", {}) self.metrics = kwargs.pop("metrics", {}) self.evaluation_data = kwargs.pop("evaluation_data", {}) self.training_data = kwargs.pop("training_data", {}) self.quantitative_analyses = kwargs.pop("quantitative_analyses", {}) self.ethical_considerations = kwargs.pop("ethical_considerations", {}) self.caveats_and_recommendations = kwargs.pop("caveats_and_recommendations", {}) # Open additional attributes for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err def save_pretrained(self, save_directory_or_file): """Save a model card object to the directory or file `save_directory_or_file`.""" if os.path.isdir(save_directory_or_file): # If we save using the predefined names, we can load using `from_pretrained` output_model_card_file = os.path.join(save_directory_or_file, MODEL_CARD_NAME) else: output_model_card_file = save_directory_or_file self.to_json_file(output_model_card_file) logger.info(f"Model card saved in {output_model_card_file}") @classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a [`ModelCard`] from a pre-trained model model card. Parameters: pretrained_model_name_or_path: either: - a string, the *model id* of a pretrained model card hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a model card file saved using the [`~ModelCard.save_pretrained`] method, e.g.: `./my_model_directory/`. - a path or url to a saved model card JSON *file*, e.g.: `./my_model_directory/modelcard.json`. cache_dir: (*optional*) string: Path to a directory in which a downloaded pre-trained model card should be cached if the standard cache should not be used. kwargs: (*optional*) dict: key/value pairs with which to update the ModelCard object after loading. - The values in kwargs of any keys which are model card attributes will be used to override the loaded values. - Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the *return_unused_kwargs* keyword parameter. proxies: (*optional*) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. return_unused_kwargs: (*optional*) bool: - If False, then this function returns just the final model card object. - If True, then this functions returns a tuple *(model card, unused_kwargs)* where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of kwargs which has not been used to update *ModelCard* and is otherwise ignored. Examples: ```python # Download model card from huggingface.co and cache. modelcard = ModelCard.from_pretrained("bert-base-uncased") # Model card was saved using *save_pretrained('./test/saved_model/')* modelcard = ModelCard.from_pretrained("./test/saved_model/") modelcard = ModelCard.from_pretrained("./test/saved_model/modelcard.json") modelcard = ModelCard.from_pretrained("bert-base-uncased", output_attentions=True, foo=False) ```""" cache_dir = kwargs.pop("cache_dir", None) proxies = kwargs.pop("proxies", None) return_unused_kwargs = kwargs.pop("return_unused_kwargs", False) from_pipeline = kwargs.pop("_from_pipeline", None) user_agent = {"file_type": "model_card"} if from_pipeline is not None: user_agent["using_pipeline"] = from_pipeline is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isfile(pretrained_model_name_or_path): resolved_model_card_file = pretrained_model_name_or_path is_local = True else: try: # Load from URL or cache if already cached resolved_model_card_file = cached_file( pretrained_model_name_or_path, filename=MODEL_CARD_NAME, cache_dir=cache_dir, proxies=proxies, user_agent=user_agent, ) if is_local: logger.info(f"loading model card file {resolved_model_card_file}") else: logger.info(f"loading model card file {MODEL_CARD_NAME} from cache at {resolved_model_card_file}") # Load model card modelcard = cls.from_json_file(resolved_model_card_file) except (EnvironmentError, json.JSONDecodeError): # We fall back on creating an empty model card modelcard = cls() # Update model card with kwargs if needed to_remove = [] for key, value in kwargs.items(): if hasattr(modelcard, key): setattr(modelcard, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) logger.info(f"Model card: {modelcard}") if return_unused_kwargs: return modelcard, kwargs else: return modelcard @classmethod def from_dict(cls, json_object): """Constructs a `ModelCard` from a Python dictionary of parameters.""" return cls(**json_object) @classmethod def from_json_file(cls, json_file): """Constructs a `ModelCard` from a json file of parameters.""" with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() dict_obj = json.loads(text) return cls(**dict_obj) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return str(self.to_json_string()) def to_dict(self): """Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path): """Save this instance to a json file.""" with open(json_file_path, "w", encoding="utf-8") as writer: writer.write(self.to_json_string()) AUTOGENERATED_TRAINER_COMMENT = """ <!-- This model card has been generated automatically according to the information the Trainer had access to. You should probably proofread and complete it, then remove this comment. --> """ AUTOGENERATED_KERAS_COMMENT = """ <!-- This model card has been generated automatically according to the information Keras had access to. You should probably proofread and complete it, then remove this comment. --> """ TASK_TAG_TO_NAME_MAPPING = { "fill-mask": "Masked Language Modeling", "image-classification": "Image Classification", "image-segmentation": "Image Segmentation", "multiple-choice": "Multiple Choice", "object-detection": "Object Detection", "question-answering": "Question Answering", "summarization": "Summarization", "table-question-answering": "Table Question Answering", "text-classification": "Text Classification", "text-generation": "Causal Language Modeling", "text2text-generation": "Sequence-to-sequence Language Modeling", "token-classification": "Token Classification", "translation": "Translation", "zero-shot-classification": "Zero Shot Classification", "automatic-speech-recognition": "Automatic Speech Recognition", } METRIC_TAGS = [ "accuracy", "bleu", "f1", "matthews_correlation", "pearsonr", "precision", "recall", "rouge", "sacrebleu", "spearmanr", "wer", ] def _listify(obj): if obj is None: return [] elif isinstance(obj, str): return [obj] else: return obj def _insert_values_as_list(metadata, name, values): if values is None: return metadata if isinstance(values, str): values = [values] values = [v for v in values if v is not None] if len(values) == 0: return metadata metadata[name] = values return metadata def infer_metric_tags_from_eval_results(eval_results): if eval_results is None: return {} result = {} for key in eval_results.keys(): if key.lower().replace(" ", "_") in METRIC_TAGS: result[key.lower().replace(" ", "_")] = key elif key.lower() == "rouge1": result["rouge"] = key return result def _insert_value(metadata, name, value): if value is None: return metadata metadata[name] = value return metadata def is_hf_dataset(dataset): if not is_datasets_available(): return False from datasets import Dataset, IterableDataset return isinstance(dataset, (Dataset, IterableDataset)) def _get_mapping_values(mapping): result = [] for v in mapping.values(): if isinstance(v, (tuple, list)): result += list(v) else: result.append(v) return result @dataclass class TrainingSummary: model_name: str language: Optional[Union[str, List[str]]] = None license: Optional[str] = None tags: Optional[Union[str, List[str]]] = None finetuned_from: Optional[str] = None tasks: Optional[Union[str, List[str]]] = None dataset: Optional[Union[str, List[str]]] = None dataset_tags: Optional[Union[str, List[str]]] = None dataset_args: Optional[Union[str, List[str]]] = None dataset_metadata: Optional[Dict[str, Any]] = None eval_results: Optional[Dict[str, float]] = None eval_lines: Optional[List[str]] = None hyperparameters: Optional[Dict[str, Any]] = None source: Optional[str] = "trainer" def __post_init__(self): # Infer default license from the checkpoint used, if possible. if ( self.license is None and not is_offline_mode() and self.finetuned_from is not None and len(self.finetuned_from) > 0 ): try: info = model_info(self.finetuned_from) for tag in info.tags: if tag.startswith("license:"): self.license = tag[8:] except (requests.exceptions.HTTPError, HFValidationError): pass def create_model_index(self, metric_mapping): model_index = {"name": self.model_name} # Dataset mapping tag -> name dataset_names = _listify(self.dataset) dataset_tags = _listify(self.dataset_tags) dataset_args = _listify(self.dataset_args) dataset_metadata = _listify(self.dataset_metadata) if len(dataset_args) < len(dataset_tags): dataset_args = dataset_args + [None] * (len(dataset_tags) - len(dataset_args)) dataset_mapping = {tag: name for tag, name in zip(dataset_tags, dataset_names)} dataset_arg_mapping = {tag: arg for tag, arg in zip(dataset_tags, dataset_args)} dataset_metadata_mapping = {tag: metadata for tag, metadata in zip(dataset_tags, dataset_metadata)} task_mapping = { task: TASK_TAG_TO_NAME_MAPPING[task] for task in _listify(self.tasks) if task in TASK_TAG_TO_NAME_MAPPING } model_index["results"] = [] if len(task_mapping) == 0 and len(dataset_mapping) == 0: return [model_index] if len(task_mapping) == 0: task_mapping = {None: None} if len(dataset_mapping) == 0: dataset_mapping = {None: None} # One entry per dataset and per task all_possibilities = [(task_tag, ds_tag) for task_tag in task_mapping for ds_tag in dataset_mapping] for task_tag, ds_tag in all_possibilities: result = {} if task_tag is not None: result["task"] = {"name": task_mapping[task_tag], "type": task_tag} if ds_tag is not None: metadata = dataset_metadata_mapping.get(ds_tag, {}) result["dataset"] = { "name": dataset_mapping[ds_tag], "type": ds_tag, **metadata, } if dataset_arg_mapping[ds_tag] is not None: result["dataset"]["args"] = dataset_arg_mapping[ds_tag] if len(metric_mapping) > 0: result["metrics"] = [] for metric_tag, metric_name in metric_mapping.items(): result["metrics"].append( { "name": metric_name, "type": metric_tag, "value": self.eval_results[metric_name], } ) # Remove partial results to avoid the model card being rejected. if "task" in result and "dataset" in result and "metrics" in result: model_index["results"].append(result) else: logger.info(f"Dropping the following result as it does not have all the necessary fields:\n{result}") return [model_index] def create_metadata(self): metric_mapping = infer_metric_tags_from_eval_results(self.eval_results) metadata = {} metadata = _insert_values_as_list(metadata, "language", self.language) metadata = _insert_value(metadata, "license", self.license) metadata = _insert_values_as_list(metadata, "tags", self.tags) metadata = _insert_values_as_list(metadata, "datasets", self.dataset_tags) metadata = _insert_values_as_list(metadata, "metrics", list(metric_mapping.keys())) metadata["model-index"] = self.create_model_index(metric_mapping) return metadata def to_model_card(self): model_card = "" metadata = yaml.dump(self.create_metadata(), sort_keys=False) if len(metadata) > 0: model_card = f"---\n{metadata}---\n" # Now the model card for realsies. if self.source == "trainer": model_card += AUTOGENERATED_TRAINER_COMMENT else: model_card += AUTOGENERATED_KERAS_COMMENT model_card += f"\n# {self.model_name}\n\n" if self.finetuned_from is None: model_card += "This model was trained from scratch on " else: model_card += ( "This model is a fine-tuned version of" f" [{self.finetuned_from}](https://huggingface.co/{self.finetuned_from}) on " ) if self.dataset is None: model_card += "an unknown dataset." else: if isinstance(self.dataset, str): model_card += f"the {self.dataset} dataset." elif isinstance(self.dataset, (tuple, list)) and len(self.dataset) == 1: model_card += f"the {self.dataset[0]} dataset." else: model_card += ( ", ".join([f"the {ds}" for ds in self.dataset[:-1]]) + f" and the {self.dataset[-1]} datasets." ) if self.eval_results is not None: model_card += "\nIt achieves the following results on the evaluation set:\n" model_card += "\n".join([f"- {name}: {_maybe_round(value)}" for name, value in self.eval_results.items()]) model_card += "\n" model_card += "\n## Model description\n\nMore information needed\n" model_card += "\n## Intended uses & limitations\n\nMore information needed\n" model_card += "\n## Training and evaluation data\n\nMore information needed\n" model_card += "\n## Training procedure\n" model_card += "\n### Training hyperparameters\n" if self.hyperparameters is not None: model_card += "\nThe following hyperparameters were used during training:\n" model_card += "\n".join([f"- {name}: {value}" for name, value in self.hyperparameters.items()]) model_card += "\n" else: model_card += "\nMore information needed\n" if self.eval_lines is not None: model_card += "\n### Training results\n\n" model_card += make_markdown_table(self.eval_lines) model_card += "\n" model_card += "\n### Framework versions\n\n" model_card += f"- Transformers {__version__}\n" if self.source == "trainer" and is_torch_available(): import torch model_card += f"- Pytorch {torch.__version__}\n" elif self.source == "keras" and is_tf_available(): import tensorflow as tf model_card += f"- TensorFlow {tf.__version__}\n" if is_datasets_available(): import datasets model_card += f"- Datasets {datasets.__version__}\n" if is_tokenizers_available(): import tokenizers model_card += f"- Tokenizers {tokenizers.__version__}\n" return model_card @classmethod def from_trainer( cls, trainer, language=None, license=None, tags=None, model_name=None, finetuned_from=None, tasks=None, dataset_tags=None, dataset_metadata=None, dataset=None, dataset_args=None, ): # Infer default from dataset one_dataset = trainer.eval_dataset if trainer.eval_dataset is not None else trainer.train_dataset if is_hf_dataset(one_dataset) and (dataset_tags is None or dataset_args is None or dataset_metadata is None): default_tag = one_dataset.builder_name # Those are not real datasets from the Hub so we exclude them. if default_tag not in ["csv", "json", "pandas", "parquet", "text"]: if dataset_metadata is None: dataset_metadata = [{"config": one_dataset.config_name, "split": str(one_dataset.split)}] if dataset_tags is None: dataset_tags = [default_tag] if dataset_args is None: dataset_args = [one_dataset.config_name] if dataset is None and dataset_tags is not None: dataset = dataset_tags # Infer default finetuned_from if ( finetuned_from is None and hasattr(trainer.model.config, "_name_or_path") and not os.path.isdir(trainer.model.config._name_or_path) ): finetuned_from = trainer.model.config._name_or_path # Infer default task tag: if tasks is None: model_class_name = trainer.model.__class__.__name__ for task, mapping in TASK_MAPPING.items(): if model_class_name in _get_mapping_values(mapping): tasks = task if model_name is None: model_name = Path(trainer.args.output_dir).name if len(model_name) == 0: model_name = finetuned_from # Add `generated_from_trainer` to the tags if tags is None: tags = ["generated_from_trainer"] elif isinstance(tags, str) and tags != "generated_from_trainer": tags = [tags, "generated_from_trainer"] elif "generated_from_trainer" not in tags: tags.append("generated_from_trainer") _, eval_lines, eval_results = parse_log_history(trainer.state.log_history) hyperparameters = extract_hyperparameters_from_trainer(trainer) return cls( language=language, license=license, tags=tags, model_name=model_name, finetuned_from=finetuned_from, tasks=tasks, dataset=dataset, dataset_tags=dataset_tags, dataset_args=dataset_args, dataset_metadata=dataset_metadata, eval_results=eval_results, eval_lines=eval_lines, hyperparameters=hyperparameters, ) @classmethod def from_keras( cls, model, model_name, keras_history=None, language=None, license=None, tags=None, finetuned_from=None, tasks=None, dataset_tags=None, dataset=None, dataset_args=None, ): # Infer default from dataset if dataset is not None: if is_hf_dataset(dataset) and (dataset_tags is None or dataset_args is None): default_tag = dataset.builder_name # Those are not real datasets from the Hub so we exclude them. if default_tag not in ["csv", "json", "pandas", "parquet", "text"]: if dataset_tags is None: dataset_tags = [default_tag] if dataset_args is None: dataset_args = [dataset.config_name] if dataset is None and dataset_tags is not None: dataset = dataset_tags # Infer default finetuned_from if ( finetuned_from is None and hasattr(model.config, "_name_or_path") and not os.path.isdir(model.config._name_or_path) ): finetuned_from = model.config._name_or_path # Infer default task tag: if tasks is None: model_class_name = model.__class__.__name__ for task, mapping in TASK_MAPPING.items(): if model_class_name in _get_mapping_values(mapping): tasks = task # Add `generated_from_keras_callback` to the tags if tags is None: tags = ["generated_from_keras_callback"] elif isinstance(tags, str) and tags != "generated_from_keras_callback": tags = [tags, "generated_from_keras_callback"] elif "generated_from_keras_callback" not in tags: tags.append("generated_from_keras_callback") if keras_history is not None: _, eval_lines, eval_results = parse_keras_history(keras_history) else: eval_lines = [] eval_results = {} hyperparameters = extract_hyperparameters_from_keras(model) return cls( language=language, license=license, tags=tags, model_name=model_name, finetuned_from=finetuned_from, tasks=tasks, dataset_tags=dataset_tags, dataset=dataset, dataset_args=dataset_args, eval_results=eval_results, eval_lines=eval_lines, hyperparameters=hyperparameters, source="keras", ) def parse_keras_history(logs): """ Parse the `logs` of either a `tf.keras.History` object returned by `model.fit()` or an accumulated logs `dict` passed to the `PushToHubCallback`. Returns lines and logs compatible with those returned by `parse_log_history`. """ if hasattr(logs, "history"): # This looks like a `History` object if not hasattr(logs, "epoch"): # This history looks empty, return empty results return None, [], {} logs.history["epoch"] = logs.epoch logs = logs.history else: # Training logs is a list of dicts, let's invert it to a dict of lists to match a History object logs = {log_key: [single_dict[log_key] for single_dict in logs] for log_key in logs[0]} lines = [] for i in range(len(logs["epoch"])): epoch_dict = {log_key: log_value_list[i] for log_key, log_value_list in logs.items()} values = {} for k, v in epoch_dict.items(): if k.startswith("val_"): k = "validation_" + k[4:] elif k != "epoch": k = "train_" + k splits = k.split("_") name = " ".join([part.capitalize() for part in splits]) values[name] = v lines.append(values) eval_results = lines[-1] return logs, lines, eval_results def parse_log_history(log_history): """ Parse the `log_history` of a Trainer to get the intermediate and final evaluation results. """ idx = 0 while idx < len(log_history) and "train_runtime" not in log_history[idx]: idx += 1 # If there are no training logs if idx == len(log_history): idx -= 1 while idx >= 0 and "eval_loss" not in log_history[idx]: idx -= 1 if idx >= 0: return None, None, log_history[idx] else: return None, None, None # From now one we can assume we have training logs: train_log = log_history[idx] lines = [] training_loss = "No log" for i in range(idx): if "loss" in log_history[i]: training_loss = log_history[i]["loss"] if "eval_loss" in log_history[i]: metrics = log_history[i].copy() _ = metrics.pop("total_flos", None) epoch = metrics.pop("epoch", None) step = metrics.pop("step", None) _ = metrics.pop("eval_runtime", None) _ = metrics.pop("eval_samples_per_second", None) _ = metrics.pop("eval_steps_per_second", None) _ = metrics.pop("eval_jit_compilation_time", None) values = {"Training Loss": training_loss, "Epoch": epoch, "Step": step} for k, v in metrics.items(): if k == "eval_loss": values["Validation Loss"] = v else: splits = k.split("_") name = " ".join([part.capitalize() for part in splits[1:]]) values[name] = v lines.append(values) idx = len(log_history) - 1 while idx >= 0 and "eval_loss" not in log_history[idx]: idx -= 1 if idx > 0: eval_results = {} for key, value in log_history[idx].items(): if key.startswith("eval_"): key = key[5:] if key not in ["runtime", "samples_per_second", "steps_per_second", "epoch", "step"]: camel_cased_key = " ".join([part.capitalize() for part in key.split("_")]) eval_results[camel_cased_key] = value return train_log, lines, eval_results else: return train_log, lines, None def extract_hyperparameters_from_keras(model): import tensorflow as tf hyperparameters = {} if hasattr(model, "optimizer") and model.optimizer is not None: hyperparameters["optimizer"] = model.optimizer.get_config() else: hyperparameters["optimizer"] = None hyperparameters["training_precision"] = tf.keras.mixed_precision.global_policy().name return hyperparameters def _maybe_round(v, decimals=4): if isinstance(v, float) and len(str(v).split(".")) > 1 and len(str(v).split(".")[1]) > decimals: return f"{v:.{decimals}f}" return str(v) def _regular_table_line(values, col_widths): values_with_space = [f"| {v}" + " " * (w - len(v) + 1) for v, w in zip(values, col_widths)] return "".join(values_with_space) + "|\n" def _second_table_line(col_widths): values = ["|:" + "-" * w + ":" for w in col_widths] return "".join(values) + "|\n" def make_markdown_table(lines): """ Create a nice Markdown table from the results in `lines`. """ if lines is None or len(lines) == 0: return "" col_widths = {key: len(str(key)) for key in lines[0].keys()} for line in lines: for key, value in line.items(): if col_widths[key] < len(_maybe_round(value)): col_widths[key] = len(_maybe_round(value)) table = _regular_table_line(list(lines[0].keys()), list(col_widths.values())) table += _second_table_line(list(col_widths.values())) for line in lines: table += _regular_table_line([_maybe_round(v) for v in line.values()], list(col_widths.values())) return table _TRAINING_ARGS_KEYS = [ "learning_rate", "train_batch_size", "eval_batch_size", "seed", ] def extract_hyperparameters_from_trainer(trainer): hyperparameters = {k: getattr(trainer.args, k) for k in _TRAINING_ARGS_KEYS} if trainer.args.parallel_mode not in [ParallelMode.NOT_PARALLEL, ParallelMode.NOT_DISTRIBUTED]: hyperparameters["distributed_type"] = ( "multi-GPU" if trainer.args.parallel_mode == ParallelMode.DISTRIBUTED else trainer.args.parallel_mode.value ) if trainer.args.world_size > 1: hyperparameters["num_devices"] = trainer.args.world_size if trainer.args.gradient_accumulation_steps > 1: hyperparameters["gradient_accumulation_steps"] = trainer.args.gradient_accumulation_steps total_train_batch_size = ( trainer.args.train_batch_size * trainer.args.world_size * trainer.args.gradient_accumulation_steps ) if total_train_batch_size != hyperparameters["train_batch_size"]: hyperparameters["total_train_batch_size"] = total_train_batch_size total_eval_batch_size = trainer.args.eval_batch_size * trainer.args.world_size if total_eval_batch_size != hyperparameters["eval_batch_size"]: hyperparameters["total_eval_batch_size"] = total_eval_batch_size if trainer.args.adafactor: hyperparameters["optimizer"] = "Adafactor" else: hyperparameters["optimizer"] = ( f"Adam with betas=({trainer.args.adam_beta1},{trainer.args.adam_beta2}) and" f" epsilon={trainer.args.adam_epsilon}" ) hyperparameters["lr_scheduler_type"] = trainer.args.lr_scheduler_type.value if trainer.args.warmup_ratio != 0.0: hyperparameters["lr_scheduler_warmup_ratio"] = trainer.args.warmup_ratio if trainer.args.warmup_steps != 0.0: hyperparameters["lr_scheduler_warmup_steps"] = trainer.args.warmup_steps if trainer.args.max_steps != -1: hyperparameters["training_steps"] = trainer.args.max_steps else: hyperparameters["num_epochs"] = trainer.args.num_train_epochs if trainer.args.fp16: if trainer.use_cuda_amp: hyperparameters["mixed_precision_training"] = "Native AMP" elif trainer.use_apex: hyperparameters["mixed_precision_training"] = f"Apex, opt level {trainer.args.fp16_opt_level}" if trainer.args.label_smoothing_factor != 0.0: hyperparameters["label_smoothing_factor"] = trainer.args.label_smoothing_factor return hyperparameters
233zzh/TitanDataOperationSystem
2,788
代码/web代码/titanApp/src/main/resources/static/src/assets/extra-libs/flot/examples/realtime/index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples: Real-time updates</title> <link href="../examples.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../../jquery.js"></script> <script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script> <script type="text/javascript"> $(function() { // We use an inline data source in the example, usually data would // be fetched from a server var data = [], totalPoints = 300; function getRandomData() { if (data.length > 0) data = data.slice(1); // Do a random walk while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50, y = prev + Math.random() * 10 - 5; if (y < 0) { y = 0; } else if (y > 100) { y = 100; } data.push(y); } // Zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) { res.push([i, data[i]]) } return res; } // Set up the control widget var updateInterval = 30; $("#updateInterval").val(updateInterval).change(function () { var v = $(this).val(); if (v && !isNaN(+v)) { updateInterval = +v; if (updateInterval < 1) { updateInterval = 1; } else if (updateInterval > 2000) { updateInterval = 2000; } $(this).val("" + updateInterval); } }); var plot = $.plot("#placeholder", [ getRandomData() ], { series: { shadowSize: 0 // Drawing is faster without shadows }, yaxis: { min: 0, max: 100 }, xaxis: { show: false } }); function update() { plot.setData([getRandomData()]); // Since the axes don't change, we don't need to call plot.setupGrid() plot.draw(); setTimeout(update, updateInterval); } update(); // Add the Flot version string to the footer $("#footer").prepend("Flot " + $.plot.version + " &ndash; "); }); </script> </head> <body> <div id="header"> <h2>Real-time updates</h2> </div> <div id="content"> <div class="demo-container"> <div id="placeholder" class="demo-placeholder"></div> </div> <p>You can update a chart periodically to get a real-time effect by using a timer to insert the new data in the plot and redraw it.</p> <p>Time between updates: <input id="updateInterval" type="text" value="" style="text-align: right; width:5em"> milliseconds</p> </div> <div id="footer"> Copyright &copy; 2007 - 2014 IOLA and Ole Laursen </div> </body> </html>
274056675/springboot-openai-chatgpt
14,259
mng_web/src/research/mixins/codetestlist.js
import { apiRequestHead } from '@/config/url.js' // 表单设计基础控件 import MenuLeftBtns from '@/research/components/code-list/menu-left-btns.vue' import MenuFormBtns from '@/research/components/code-list/menu-form-btns.vue' import MenuLinkBtns from '@/research/components/code-list/menu-link-btns.vue' // 其他控件 import CodeSublistForm from '@/research/components/code-list/code-sublist-form' import CodeSublistTable from '@/research/components/code-list/code-sublist-table' import DepartControl from '@/research/components/general-control/depart-control' import UserControl from '@/research/components/general-control/user-control' import TableSelectControl from '@/research/components/general-control/table-select-control' import tableView from "@/research/components/general-control/table-view.vue" import TableTree from '@/research/components/general-control/table-tree.vue' import FormView from '@/research/components/general-control/form-view.vue' import TableSelect from '@/research/components/general-control/table-select.vue' import ControlView from '@/research/components/general-control/control-view.vue' import TabsView from '@/research/components/general-control/tabs-view.vue' // 代码编辑器 import MonacoEditor from '@/packages/utils/monaco-editor' export default { components: { // 基础 MenuLeftBtns, MenuFormBtns, MenuLinkBtns, // 其他 CodeSublistForm, CodeSublistTable, DepartControl, UserControl, TableSelectControl, tableView, TableTree, FormView, TableSelect, ControlView, TabsView, MonacoEditor, }, data () { return { random: `${Math.random()}`.substring(3), isAvueTableLoading: '',//avue表格loading currDateTime: '',//当前时间 isAuthBtn: false, //是否开启系统按钮权限 控制按钮显隐 isOneGetData: true, //是否第一次获取数据 selectionTime: null, apiRequestHead: apiRequestHead, isLinkPullDown: true, //自定义按钮 link是否下拉显示 isTableGetData: true, //是否一开始加载数据 subDataIdKey: 'id', //字表的需要的数据id字段名 tableSearchType: '', tablePermission: { addBtn: false, allDelBtn: false, editBtn: false, exportBtn: false, inportBtn: false, moreDelBtn: false, moreViewBtn: false, moreChildBtn: false, }, //权限控制 maps: new Map(), //存储树表格用于数据回显 themeTemplate: '', //当前主题 timerInte: [], //定时器 tableDescribe: '', //表描述 that: null, drawer: true, isTableLoading: false, //操作button加载 tableCrudType: '', currCodeId: '', //当前表单id currCodeType: '', //当前表单其他参数 tableName: '', //数据库表名 tableIsPage: false, //是否分页 isOpentForm: false, //是否打开了表单弹窗 tableInportDialog: false, //导入弹窗 tableQueryData: {}, //搜索实时条件 tableQueryClickData: {}, //点击查询后的搜索条件 tableOtherQueryData: {},//其他搜索条件(清除搜索不会清空) tableAdvancedQueryData: {}, //高级查询条件 isTableCrud: false, //一开始隐藏表格 subShowMenu: '', //子表是否显示操作按钮和操作列 sortData: { column: 'id', order: 'desc', }, // 表格table配置 tableOption: { align: 'center', dialogDrag: true, dialogTop: '0%', dialogClickModal: false, delBtn: false, editBtn: false, dialogWidth: '80%', menuWidth: '200', border: true, //开启边框 columnBtn: true, //隐藏列显示隐藏按钮 saveBtn: false, cancelBtn: false, updateBtn: false, addBtn: true, header: true, search: false, searchMenuSpan: 6, searchMenuPosition: 'left', searchIndex: 3, searchIcon: true, searchShowBtn: false, expandRowKeys: [], column: [], lazy: true, //暂时只能先设置 avue selectable: (row, index) => { //通过增强配置是否可以选择 if ( this.customOnlineEnhanceJsName && this.customOnlineEnhanceJsName.list.includes('selectable') ) { try { return this.customOnlineEnhanceJsList.selectable(row, index) } catch (error) { console.warn(error) } } else { return true } }, }, tableForm: {}, tableColumnMoreButton: [ { type: 'view', text: '详情', permissionName: 'moreViewBtn', }, { type: 'del', text: '删除', permissionName: 'moreDelBtn', }, ], //默认操作列按钮 tableSelectData: [], //表格选中的数据 tableSelectId: [], //表格选中的数据Id tableData: [], //表格数据 tablePage: {}, //表格分页 tableDataIsTree: false, //是否使用 树结构数据处理方式 tableTreeParentIdName: '', //树结构数据 父id的key名 tableTreeUnfoldName: '', //树结构数据展开列 tableTreeChildern: '', //树结构数据是否有子集 tableColumnDic: {}, tableColumnItemForm: {}, tableAllColumnRules: [], //所有校验规则 columHeaderArr: [],//自定义表头搜索 tableNeetRules: ['text', 'password', 'textarea', 'umeditor', 'markdown'], //可以校验的控件 // 需要字典数据的控件 viewListSelect: [ 'list', 'radio', 'checkbox', 'switch', 'list_multi', 'pca', ], //需要字典数据的控件,并且以树形式展示 viewListTree: ['sel_tree', 'cat_tree'], viewAllTreeKey: [], //是否有省市区控件 isProvinces: false, //表单 单独占一行的控件 fieldSpanOneLine: ['textarea', 'markdown', 'umeditor', 'image', 'file', 'monaco-editor'], //所有的省市区联动控件 viewPcaArr: [], //所有markdown控件 viewMarkdownArr: [], //所有文件控件 viewFileArr: [], //所有联动控件 viewLinkDownArr: [], // 所有联动控件关联字段 viewLinkDownFieldArr: [], //联表查询字段 uniteFormKeyObj: {}, //所有联动控件字典 viewLinkDownDicObj: {}, viewFileNameObj: {}, //存储所有文件名 viewPcaNameObj: {}, //存储所有省市区id对应的文本 //需要自定义搜索的字典处理 customSearchArr: [], //当前操作的列的数据 currentRowDataObj: {}, // 部门 allDepartData: {}, //所有部门数据 viewDepartControlArr: [], //所有部门控件 // 用户 viewUserControlArr: [], //所有用户控件 //所有表格选择控件 viewTableSelectArr: [], //所有的代码编辑器控件 viewMonacoEditor: [], initSelfDefinedArr: [], viewMapArr: [], //所有地图控件 allUserData: {}, //所有用户数据 allUserObj: {}, isTableInfo: false, //是否存在主附表 // 父子表tabs切换配置 tabsOption: { column: [], }, tabsType: {}, //当前tabs listTabsOption: { column: [], }, //自定义按钮 customButtonTop: [], //表格顶部操作栏按钮 customButtonLink: [], //表格操作列按钮 customButtonFormEnd: [], //表单操作菜单 底部 customButtonFormSide: [], //表单操作菜单 侧面 dicAllData: {}, //end 高级查询 customOnlineEnhanceJsList: {}, //js增强list所有方法 customOnlineEnhanceJsForm: {}, //js增强form所有方法 //js增强方法名 customOnlineEnhanceJsName: { list: [], form: [], }, form: { getSelectOptions: null, changeOptions: null, triggleChangeValues: null, getAllFieldValue: null, getFieldValue: null, }, otherPortId:false,//其他导入 导出 下载模板表id // 导入 inportOption: { column: [ { label: '', prop: 'inportexcel', type: 'upload', accept: ' application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', span: 24, labelWidth: 0, labelslot: true, multiple: false, limit: 1, propsHttp: { res: 'data', }, tip: '只能上传 xls / xlsx 文件', }, ], }, inportForm: { inportexcel: [], inportList: [], }, //表单设计 配置值 widgetFormPreview: {}, isDialogFormDesign: false, isFormFullscreenDesign: false, formOpenType: 'add', formActionData: { type: 'formlist', }, formBtnPermissions: {}, allFormListData: {}, dialogFormTitle: '新增', //erp tableErpRadioId: '', //当前erp主题选择数据的id tableErpRadioObj: {}, //当前erp主题选择数据 erpControlsArr: [ 'text', 'radio', 'switch', 'date', 'datetime', 'file', 'image', 'list_multi', 'sel_search', 'list', 'popup', 'sel_depart', 'sel_user', ], //innerTable expandObj: {}, listTabsType: {}, //列表tabs //树选择控件配置 isTableTreeControl: false, tableTreeControlOption: { tableId: '', defaultTree: [], stopTree: [], isDialog: false, defaultProps: {}, defaulKey: '', title: '', addType: { type: '', tableId: '', }, asyncTableName: '', }, //其他表单控件配置 isFormViewControl: false, FormViewControlOption: { viewObj: {}, formId: '', formOpenType: '', actionData: {}, btnPermissions: {}, customFun: () => { } }, //组件配置 isControlView: false, controlViewOption: { type: '', viewObj: {}, params: {}, defaultData: {}, customFun: () => { } }, // 资源审核 isZyscControl: false, //表格选择控件配置 isTableSelectControl: false, tableSelectControlOption: { title: '', isDialog: false, width: '', tableId: '', option: {}, multiple: '', isPage: '', addType: { type: '', tableId: '', isCell: '', }, submitFun: () => { }, }, //tabs显示控件 isTabsView: false, tabsOptionData: { viewObj: { title: '', type: 'dialog', isShow: false, width: '90%', }, tabsParams: {}, openIndex: 0, tabsData: [], }, //其他表格弹窗控件配置 isTableView: false, tableViewOptionData: { viewObj: {}, tableId: '', searchObj: {}, }, //子表是否需要js增强和自定义按钮 subOpentJsEnhance: '', isInitEnhance: false, //判断增强是否初始化完毕 // 大数据展示方式 displayModeType: 'normal', currentStartIndex: 0, currentEndIndex: 50, isOpentAuthFocus: false, //是否开启自动聚焦 authFocusObj: { //自动聚焦配置 currBigDataTrEl: '', inputAttr: '', }, } }, filters: { // 时间格式化 dateFilter (date, format) { date = new Date(date) format = format || 'yyyy-MM-dd hh:mm:ss' if (date != 'Invalid Date') { let o = { 'M+': date.getMonth() + 1, //month 'd+': date.getDate(), //day 'h+': date.getHours(), //hour 'H+': date.getHours(), //hour 'm+': date.getMinutes(), //minute 's+': date.getSeconds(), //second 'q+': Math.floor((date.getMonth() + 3) / 3), //quarter S: date.getMilliseconds(), //millisecond } if (/(y+)/.test(format)) format = format.replace( RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length) ) for (let k in o) if (new RegExp('(' + k + ')').test(format)) format = format.replace( RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length) ) return format } return '' }, }, watch: { subShowMenu (val) { let arr = val.split('/') this.tabsOption.column = this.tabsOption.column.map((item) => { if (item.key == arr[0]) { item.showMenu = arr[1] == 'true' ? true : false } return item }) }, subOpentJsEnhance (val) { let arr = val.split('/') this.tabsOption.column = this.tabsOption.column.map((item) => { if (item.key == arr[0]) { item.opentJsEnhance = arr[1] == 'true' ? true : false } return item }) }, currMainDataId (val) { if (this.tableId) { if (val) { this.tableOption.header = true } else { this.tableOption.header = false } setTimeout(() => { this.initTableData() }, 300) } }, }, computed: { filteredData () { let list = this.tableData.filter((item, index) => { if (index < this.currentStartIndex) { return false } else if (index > this.currentEndIndex) { return false } else { return true } }) return list }, }, props: { //erp附表id tableId: { type: String, default: '', }, //不通过路由传递的表id tranTableId: { type: String, default: '', }, currMainDataId: { type: String, default: '', }, currMainDataObj: { type: Object, default: () => { }, }, foreignKeys: { type: Array, default: () => [], }, tableType: { type: String, default: '', }, //默认搜索值(表格初始化后只执行一次) defaultSearchObj: { //对象里面的值为空则不获取表格数据:{key:''} type: Object, default: () => { }, }, //默认搜索值(每次都执行) searchObj: { type: Object, default: () => { }, }, tableView: { type: Boolean, default: false, }, hideHeader: { type: Boolean, default: true, }, //其他页面或控件传递的方法方法 transmitFun: { type: Function, }, //其他参数 otherParams: { type: Object, default: () => { }, }, //开启懒加载 isLazy: { type: Boolean, default: false, } }, methods: { //创建dom方法 createDomFun (domName, htmlText, type = 'end', nextDom) { let timer = setInterval(() => { let dom = document.querySelector(domName) if (dom) { clearInterval(timer) let div = document.createElement('div') if (type == 'end') { dom.appendChild(div) } else { if (nextDom) { dom.insertBefore(div, nextDom) } dom.insertBefore(div, dom.childNodes[0]) } div.style.width = "100%" div.innerHTML = htmlText } }, 300); } }, }
27182812/ChatGLM-LLaMA-chinese-insturct
95,871
src/transformers/training_args.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. import contextlib import io import json import math import os import warnings from dataclasses import asdict, dataclass, field, fields from datetime import timedelta from enum import Enum from pathlib import Path from typing import Any, Dict, List, Optional, Union from packaging import version from .debug_utils import DebugOption from .trainer_utils import ( EvaluationStrategy, FSDPOption, HubStrategy, IntervalStrategy, SchedulerType, ShardedDDPOption, ) from .utils import ( ExplicitEnum, cached_property, ccl_version, get_full_repo_name, is_accelerate_available, is_psutil_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_torch_available, is_torch_bf16_cpu_available, is_torch_bf16_gpu_available, is_torch_neuroncore_available, is_torch_tf32_available, is_torch_tpu_available, logging, requires_backends, ) if is_torch_available(): import torch import torch.distributed as dist if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm if is_torch_neuroncore_available(check_device=False): # torchrun support # https://github.com/pytorch/xla/pull/3609 if os.environ.get("TORCHELASTIC_RUN_ID"): import torch_xla.distributed.xla_backend as xbn if not isinstance(torch.distributed.group.WORLD, xbn.ProcessGroupXla): torch.distributed.init_process_group(backend="xla") if not isinstance(torch.distributed.group.WORLD, xbn.ProcessGroupXla): raise AssertionError("Failed to initialize torch.distributed process group using XLA backend.") if is_sagemaker_mp_enabled(): import smdistributed.modelparallel.torch as smp smp.init() logger = logging.get_logger(__name__) log_levels = logging.get_log_levels_dict().copy() trainer_log_levels = dict(**log_levels, passive=-1) TORCH_COMPILE_BACKENDS = [ "eager", "aot_eager", "inductor", "nvfuser", "aot_nvfuser", "aot_cudagraphs", "ofi", "fx2trt", "onnxrt", "ipex", ] def default_logdir() -> str: """ Same default as PyTorch """ import socket from datetime import datetime current_time = datetime.now().strftime("%b%d_%H-%M-%S") return os.path.join("runs", current_time + "_" + socket.gethostname()) def get_int_from_env(env_keys, default): """Returns the first positive env value found in the `env_keys` list or the default.""" for e in env_keys: val = int(os.environ.get(e, -1)) if val >= 0: return val return default def get_xla_device_type(device: "torch.device") -> Optional[str]: """ Returns the xla device type (CPU|GPU|TPU) or None if the device is a non-xla device. """ if is_torch_tpu_available(): return xm.xla_real_devices([device])[0].split(":")[0] return None class OptimizerNames(ExplicitEnum): """ Stores the acceptable string identifiers for optimizers. """ ADAMW_HF = "adamw_hf" ADAMW_TORCH = "adamw_torch" ADAMW_TORCH_XLA = "adamw_torch_xla" ADAMW_APEX_FUSED = "adamw_apex_fused" ADAFACTOR = "adafactor" ADAMW_BNB = "adamw_bnb_8bit" ADAMW_ANYPRECISION = "adamw_anyprecision" SGD = "sgd" ADAGRAD = "adagrad" @dataclass class TrainingArguments: """ TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop itself**. Using [`HfArgumentParser`] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line. Parameters: output_dir (`str`): The output directory where the model predictions and checkpoints will be written. overwrite_output_dir (`bool`, *optional*, defaults to `False`): If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir` points to a checkpoint directory. do_train (`bool`, *optional*, defaults to `False`): Whether to run training or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_eval (`bool`, *optional*): Whether to run evaluation on the validation set or not. Will be set to `True` if `evaluation_strategy` is different from `"no"`. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_predict (`bool`, *optional*, defaults to `False`): Whether to run predictions on the test set or not. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. evaluation_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"no"`): The evaluation strategy to adopt during training. Possible values are: - `"no"`: No evaluation is done during training. - `"steps"`: Evaluation is done (and logged) every `eval_steps`. - `"epoch"`: Evaluation is done at the end of each epoch. prediction_loss_only (`bool`, *optional*, defaults to `False`): When performing evaluation and generating predictions, only returns the loss. per_device_train_batch_size (`int`, *optional*, defaults to 8): The batch size per GPU/TPU core/CPU for training. per_device_eval_batch_size (`int`, *optional*, defaults to 8): The batch size per GPU/TPU core/CPU for evaluation. gradient_accumulation_steps (`int`, *optional*, defaults to 1): Number of updates steps to accumulate the gradients for, before performing a backward/update pass. <Tip warning={true}> When using gradient accumulation, one step is counted as one step with backward pass. Therefore, logging, evaluation, save will be conducted every `gradient_accumulation_steps * xxx_step` training examples. </Tip> eval_accumulation_steps (`int`, *optional*): Number of predictions steps to accumulate the output tensors for, before moving the results to the CPU. If left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but requires more memory). eval_delay (`float`, *optional*): Number of epochs or steps to wait for before the first evaluation can be performed, depending on the evaluation_strategy. learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate for [`AdamW`] optimizer. weight_decay (`float`, *optional*, defaults to 0): The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [`AdamW`] optimizer. adam_beta1 (`float`, *optional*, defaults to 0.9): The beta1 hyperparameter for the [`AdamW`] optimizer. adam_beta2 (`float`, *optional*, defaults to 0.999): The beta2 hyperparameter for the [`AdamW`] optimizer. adam_epsilon (`float`, *optional*, defaults to 1e-8): The epsilon hyperparameter for the [`AdamW`] optimizer. max_grad_norm (`float`, *optional*, defaults to 1.0): Maximum gradient norm (for gradient clipping). num_train_epochs(`float`, *optional*, defaults to 3.0): Total number of training epochs to perform (if not an integer, will perform the decimal part percents of the last epoch before stopping training). max_steps (`int`, *optional*, defaults to -1): If set to a positive number, the total number of training steps to perform. Overrides `num_train_epochs`. In case of using a finite iterable dataset the training may stop before reaching the set number of steps when all data is exhausted lr_scheduler_type (`str` or [`SchedulerType`], *optional*, defaults to `"linear"`): The scheduler type to use. See the documentation of [`SchedulerType`] for all possible values. warmup_ratio (`float`, *optional*, defaults to 0.0): Ratio of total training steps used for a linear warmup from 0 to `learning_rate`. warmup_steps (`int`, *optional*, defaults to 0): Number of steps used for a linear warmup from 0 to `learning_rate`. Overrides any effect of `warmup_ratio`. log_level (`str`, *optional*, defaults to `passive`): Logger log level to use on the main process. Possible choices are the log levels as strings: 'debug', 'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and keeps the current log level for the Transformers library (which will be `"warning"` by default). log_level_replica (`str`, *optional*, defaults to `"warning"`): Logger log level to use on replicas. Same choices as `log_level`" log_on_each_node (`bool`, *optional*, defaults to `True`): In multinode distributed training, whether to log using `log_level` once per node, or only on the main node. logging_dir (`str`, *optional*): [TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***. logging_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The logging strategy to adopt during training. Possible values are: - `"no"`: No logging is done during training. - `"epoch"`: Logging is done at the end of each epoch. - `"steps"`: Logging is done every `logging_steps`. logging_first_step (`bool`, *optional*, defaults to `False`): Whether to log and evaluate the first `global_step` or not. logging_steps (`int`, *optional*, defaults to 500): Number of update steps between two logs if `logging_strategy="steps"`. logging_nan_inf_filter (`bool`, *optional*, defaults to `True`): Whether to filter `nan` and `inf` losses for logging. If set to `True` the loss of every step that is `nan` or `inf` is filtered and the average loss of the current logging window is taken instead. <Tip> `logging_nan_inf_filter` only influences the logging of loss values, it does not change the behavior the gradient is computed or applied to the model. </Tip> save_strategy (`str` or [`~trainer_utils.IntervalStrategy`], *optional*, defaults to `"steps"`): The checkpoint save strategy to adopt during training. Possible values are: - `"no"`: No save is done during training. - `"epoch"`: Save is done at the end of each epoch. - `"steps"`: Save is done every `save_steps`. save_steps (`int`, *optional*, defaults to 500): Number of updates steps before two checkpoint saves if `save_strategy="steps"`. save_total_limit (`int`, *optional*): If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_dir`. save_on_each_node (`bool`, *optional*, defaults to `False`): When doing multi-node distributed training, whether to save models and checkpoints on each node, or only on the main one. This should not be activated when the different nodes use the same storage as the files will be saved with the same names for each node. no_cuda (`bool`, *optional*, defaults to `False`): Whether to not use CUDA even when it is available or not. seed (`int`, *optional*, defaults to 42): Random seed that will be set at the beginning of training. To ensure reproducibility across runs, use the [`~Trainer.model_init`] function to instantiate the model if it has some randomly initialized parameters. data_seed (`int`, *optional*): Random seed to be used with data samplers. If not set, random generators for data sampling will use the same seed as `seed`. This can be used to ensure reproducibility of data sampling, independent of the model seed. jit_mode_eval (`bool`, *optional*, defaults to `False`): Whether or not to use PyTorch jit trace for inference. use_ipex (`bool`, *optional*, defaults to `False`): Use Intel extension for PyTorch when it is available. [IPEX installation](https://github.com/intel/intel-extension-for-pytorch). bf16 (`bool`, *optional*, defaults to `False`): Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training. Requires Ampere or higher NVIDIA architecture or using CPU (no_cuda). This is an experimental API and it may change. fp16 (`bool`, *optional*, defaults to `False`): Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training. fp16_opt_level (`str`, *optional*, defaults to 'O1'): For `fp16` training, Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. See details on the [Apex documentation](https://nvidia.github.io/apex/amp). fp16_backend (`str`, *optional*, defaults to `"auto"`): This argument is deprecated. Use `half_precision_backend` instead. half_precision_backend (`str`, *optional*, defaults to `"auto"`): The backend to use for mixed precision training. Must be one of `"auto", "cuda_amp", "apex", "cpu_amp"`. `"auto"` will use CPU/CUDA AMP or APEX depending on the PyTorch version detected, while the other choices will force the requested backend. bf16_full_eval (`bool`, *optional*, defaults to `False`): Whether to use full bfloat16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. This is an experimental API and it may change. fp16_full_eval (`bool`, *optional*, defaults to `False`): Whether to use full float16 evaluation instead of 32-bit. This will be faster and save memory but can harm metric values. tf32 (`bool`, *optional*): Whether to enable the TF32 mode, available in Ampere and newer GPU architectures. The default value depends on PyTorch's version default of `torch.backends.cuda.matmul.allow_tf32`. For more details please refer to the [TF32](https://huggingface.co/docs/transformers/performance#tf32) documentation. This is an experimental API and it may change. local_rank (`int`, *optional*, defaults to -1): Rank of the process during distributed training. xpu_backend (`str`, *optional*): The backend to use for xpu distributed training. Must be one of `"mpi"` or `"ccl"` or `"gloo"`. tpu_num_cores (`int`, *optional*): When training on TPU, the number of TPU cores (automatically passed by launcher script). dataloader_drop_last (`bool`, *optional*, defaults to `False`): Whether to drop the last incomplete batch (if the length of the dataset is not divisible by the batch size) or not. eval_steps (`int`, *optional*): Number of update steps between two evaluations if `evaluation_strategy="steps"`. Will default to the same value as `logging_steps` if not set. dataloader_num_workers (`int`, *optional*, defaults to 0): Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded in the main process. past_index (`int`, *optional*, defaults to -1): Some models like [TransformerXL](../model_doc/transformerxl) or [XLNet](../model_doc/xlnet) can make use of the past hidden states for their predictions. If this argument is set to a positive int, the `Trainer` will use the corresponding output (usually index 2) as the past state and feed it to the model at the next training step under the keyword argument `mems`. run_name (`str`, *optional*): A descriptor for the run. Typically used for [wandb](https://www.wandb.com/) and [mlflow](https://www.mlflow.org/) logging. disable_tqdm (`bool`, *optional*): Whether or not to disable the tqdm progress bars and table of metrics produced by [`~notebook.NotebookTrainingTracker`] in Jupyter Notebooks. Will default to `True` if the logging level is set to warn or lower (default), `False` otherwise. remove_unused_columns (`bool`, *optional*, defaults to `True`): Whether or not to automatically remove the columns unused by the model forward method. (Note that this behavior is not implemented for [`TFTrainer`] yet.) label_names (`List[str]`, *optional*): The list of keys in your dictionary of inputs that correspond to the labels. Will eventually default to the list of argument names accepted by the model that contain the word "label", except if the model used is one of the `XxxForQuestionAnswering` in which case it will also include the `["start_positions", "end_positions"]` keys. load_best_model_at_end (`bool`, *optional*, defaults to `False`): Whether or not to load the best model found during training at the end of training. <Tip> When set to `True`, the parameters `save_strategy` needs to be the same as `evaluation_strategy`, and in the case it is "steps", `save_steps` must be a round multiple of `eval_steps`. </Tip> metric_for_best_model (`str`, *optional*): Use in conjunction with `load_best_model_at_end` to specify the metric to use to compare two different models. Must be the name of a metric returned by the evaluation with or without the prefix `"eval_"`. Will default to `"loss"` if unspecified and `load_best_model_at_end=True` (to use the evaluation loss). If you set this value, `greater_is_better` will default to `True`. Don't forget to set it to `False` if your metric is better when lower. greater_is_better (`bool`, *optional*): Use in conjunction with `load_best_model_at_end` and `metric_for_best_model` to specify if better models should have a greater metric or not. Will default to: - `True` if `metric_for_best_model` is set to a value that isn't `"loss"` or `"eval_loss"`. - `False` if `metric_for_best_model` is not set, or set to `"loss"` or `"eval_loss"`. ignore_data_skip (`bool`, *optional*, defaults to `False`): When resuming training, whether or not to skip the epochs and batches to get the data loading at the same stage as in the previous training. If set to `True`, the training will begin faster (as that skipping step can take a long time) but will not yield the same results as the interrupted training would have. sharded_ddp (`bool`, `str` or list of [`~trainer_utils.ShardedDDPOption`], *optional*, defaults to `False`): Use Sharded DDP training from [FairScale](https://github.com/facebookresearch/fairscale) (in distributed training only). This is an experimental feature. A list of options along the following: - `"simple"`: to use first instance of sharded DDP released by fairscale (`ShardedDDP`) similar to ZeRO-2. - `"zero_dp_2"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in Zero-2 mode (with `reshard_after_forward=False`). - `"zero_dp_3"`: to use the second instance of sharded DPP released by fairscale (`FullyShardedDDP`) in Zero-3 mode (with `reshard_after_forward=True`). - `"offload"`: to add ZeRO-offload (only compatible with `"zero_dp_2"` and `"zero_dp_3"`). If a string is passed, it will be split on space. If a bool is passed, it will be converted to an empty list for `False` and `["simple"]` for `True`. fsdp (`bool`, `str` or list of [`~trainer_utils.FSDPOption`], *optional*, defaults to `False`): Use PyTorch Distributed Parallel Training (in distributed training only). A list of options along the following: - `"full_shard"`: Shard parameters, gradients and optimizer states. - `"shard_grad_op"`: Shard optimizer states and gradients. - `"offload"`: Offload parameters and gradients to CPUs (only compatible with `"full_shard"` and `"shard_grad_op"`). - `"auto_wrap"`: Automatically recursively wrap layers with FSDP using `default_auto_wrap_policy`. fsdp_config (`str` or `dict`, *optional*): Config to be used with fsdp (Pytorch Distributed Parallel Training). The value is either a location of deepspeed json config file (e.g., `ds_config.json`) or an already loaded json file as `dict`. A List of config and its options: - fsdp_min_num_params (`int`, *optional*, defaults to `0`): FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `fsdp` field is passed). - fsdp_transformer_layer_cls_to_wrap (`List[str]`, *optional*): List of transformer layer class names (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... (useful only when `fsdp` flag is passed). - fsdp_backward_prefetch (`str`, *optional*) FSDP's backward prefetch mode. Controls when to prefetch next set of parameters (useful only when `fsdp` field is passed). A list of options along the following: - `"backward_pre"` : Prefetches the next set of parameters before the current set of parameter's gradient computation. - `"backward_pos"` : This prefetches the next set of parameters after the current set of parameter’s gradient computation. - fsdp_forward_prefetch (`bool`, *optional*, defaults to `False`) FSDP's forward prefetch mode (useful only when `fsdp` field is passed). If `"True"`, then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. - limit_all_gathers (`bool`, *optional*, defaults to `False`) FSDP's limit_all_gathers (useful only when `fsdp` field is passed). If `"True"`, FSDP explicitly synchronizes the CPU thread to prevent too many in-flight all-gathers. - xla (`bool`, *optional*, defaults to `False`): Whether to use PyTorch/XLA Fully Sharded Data Parallel Training. This is an experimental feature and its API may evolve in the future. - xla_fsdp_settings (`dict`, *optional*) The value is a dictionary which stores the XLA FSDP wrapping parameters. For a complete list of options, please see [here]( https://github.com/pytorch/xla/blob/master/torch_xla/distributed/fsdp/xla_fully_sharded_data_parallel.py). - xla_fsdp_grad_ckpt (`bool`, *optional*, defaults to `False`): Will use gradient checkpointing over each nested XLA FSDP wrapped layer. This setting can only be used when the xla flag is set to true, and an auto wrapping policy is specified through fsdp_min_num_params or fsdp_transformer_layer_cls_to_wrap. deepspeed (`str` or `dict`, *optional*): Use [Deepspeed](https://github.com/microsoft/deepspeed). This is an experimental feature and its API may evolve in the future. The value is either the location of DeepSpeed json config file (e.g., `ds_config.json`) or an already loaded json file as a `dict`" label_smoothing_factor (`float`, *optional*, defaults to 0.0): The label smoothing factor to use. Zero means no label smoothing, otherwise the underlying onehot-encoded labels are changed from 0s and 1s to `label_smoothing_factor/num_labels` and `1 - label_smoothing_factor + label_smoothing_factor/num_labels` respectively. debug (`str` or list of [`~debug_utils.DebugOption`], *optional*, defaults to `""`): Enable one or more debug features. This is an experimental feature. Possible options are: - `"underflow_overflow"`: detects overflow in model's input/outputs and reports the last frames that led to the event - `"tpu_metrics_debug"`: print debug metrics on TPU The options should be separated by whitespaces. optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_hf"`): The optimizer to use: adamw_hf, adamw_torch, adamw_apex_fused, adamw_anyprecision or adafactor. optim_args (`str`, *optional*): Optional arguments that are supplied to AnyPrecisionAdamW. adafactor (`bool`, *optional*, defaults to `False`): This argument is deprecated. Use `--optim adafactor` instead. group_by_length (`bool`, *optional*, defaults to `False`): Whether or not to group together samples of roughly the same length in the training dataset (to minimize padding applied and be more efficient). Only useful if applying dynamic padding. length_column_name (`str`, *optional*, defaults to `"length"`): Column name for precomputed lengths. If the column exists, grouping by length will use these values rather than computing them on train startup. Ignored unless `group_by_length` is `True` and the dataset is an instance of `Dataset`. report_to (`str` or `List[str]`, *optional*, defaults to `"all"`): The list of integrations to report the results and logs to. Supported platforms are `"azure_ml"`, `"comet_ml"`, `"mlflow"`, `"neptune"`, `"tensorboard"`,`"clearml"` and `"wandb"`. Use `"all"` to report to all integrations installed, `"none"` for no integrations. ddp_find_unused_parameters (`bool`, *optional*): When using distributed training, the value of the flag `find_unused_parameters` passed to `DistributedDataParallel`. Will default to `False` if gradient checkpointing is used, `True` otherwise. ddp_bucket_cap_mb (`int`, *optional*): When using distributed training, the value of the flag `bucket_cap_mb` passed to `DistributedDataParallel`. dataloader_pin_memory (`bool`, *optional*, defaults to `True`): Whether you want to pin memory in data loaders or not. Will default to `True`. skip_memory_metrics (`bool`, *optional*, defaults to `True`): Whether to skip adding of memory profiler reports to metrics. This is skipped by default because it slows down the training and evaluation speed. push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push the model to the Hub every time the model is saved. If this is activated, `output_dir` will begin a git directory synced with the repo (determined by `hub_model_id`) and the content will be pushed each time a save is triggered (depending on your `save_strategy`). Calling [`~Trainer.save_model`] will also trigger a push. <Tip warning={true}> If `output_dir` exists, it needs to be a local clone of the repository to which the [`Trainer`] will be pushed. </Tip> resume_from_checkpoint (`str`, *optional*): The path to a folder with a valid checkpoint for your model. This argument is not directly used by [`Trainer`], it's intended to be used by your training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. hub_model_id (`str`, *optional*): The name of the repository to keep in sync with the local *output_dir*. It can be a simple model ID in which case the model will be pushed in your namespace. Otherwise it should be the whole repository name, for instance `"user_name/model"`, which allows you to push to an organization you are a member of with `"organization_name/model"`. Will default to `user_name/output_dir_name` with *output_dir_name* being the name of `output_dir`. Will default to the name of `output_dir`. hub_strategy (`str` or [`~trainer_utils.HubStrategy`], *optional*, defaults to `"every_save"`): Defines the scope of what is pushed to the Hub and when. Possible values are: - `"end"`: push the model, its configuration, the tokenizer (if passed along to the [`Trainer`]) and a draft of a model card when the [`~Trainer.save_model`] method is called. - `"every_save"`: push the model, its configuration, the tokenizer (if passed along to the [`Trainer`]) and a draft of a model card each time there is a model save. The pushes are asynchronous to not block training, and in case the save are very frequent, a new push is only attempted if the previous one is finished. A last push is made with the final model at the end of training. - `"checkpoint"`: like `"every_save"` but the latest checkpoint is also pushed in a subfolder named last-checkpoint, allowing you to resume training easily with `trainer.train(resume_from_checkpoint="last-checkpoint")`. - `"all_checkpoints"`: like `"checkpoint"` but all checkpoints are pushed like they appear in the output folder (so you will get one checkpoint folder per folder in your final repository) hub_token (`str`, *optional*): The token to use to push the model to the Hub. Will default to the token in the cache folder obtained with `huggingface-cli login`. hub_private_repo (`bool`, *optional*, defaults to `False`): If True, the Hub repo will be set to private. gradient_checkpointing (`bool`, *optional*, defaults to `False`): If True, use gradient checkpointing to save memory at the expense of slower backward pass. include_inputs_for_metrics (`bool`, *optional*, defaults to `False`): Whether or not the inputs will be passed to the `compute_metrics` function. This is intended for metrics that need inputs, predictions and references for scoring calculation in Metric class. auto_find_batch_size (`bool`, *optional*, defaults to `False`) Whether to find a batch size that will fit into memory automatically through exponential decay, avoiding CUDA Out-of-Memory errors. Requires accelerate to be installed (`pip install accelerate`) full_determinism (`bool`, *optional*, defaults to `False`) If `True`, [`enable_full_determinism`] is called instead of [`set_seed`] to ensure reproducible results in distributed training torchdynamo (`str`, *optional*): If set, the backend compiler for TorchDynamo. Possible choices are `"eager"`, `"aot_eager"`, `"inductor"`, `"nvfuser"`, `"aot_nvfuser"`, `"aot_cudagraphs"`, `"ofi"`, `"fx2trt"`, `"onnxrt"` and `"ipex"`. ray_scope (`str`, *optional*, defaults to `"last"`): The scope to use when doing hyperparameter search with Ray. By default, `"last"` will be used. Ray will then use the last checkpoint of all trials, compare those, and select the best one. However, other options are also available. See the [Ray documentation]( https://docs.ray.io/en/latest/tune/api_docs/analysis.html#ray.tune.ExperimentAnalysis.get_best_trial) for more options. ddp_timeout (`int`, *optional*, defaults to 1800): The timeout for `torch.distributed.init_process_group` calls, used to avoid GPU socket timeouts when performing slow operations in distributed runnings. Please refer the [PyTorch documentation] (https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more information. use_mps_device (`bool`, *optional*, defaults to `False`): Whether to use Apple Silicon chip based `mps` device. torch_compile (`bool`, *optional*, defaults to `False`): Whether or not to compile the model using PyTorch 2.0 [`torch.compile`](https://pytorch.org/get-started/pytorch-2.0/) (requires a nighlty install of PyTorch). If set, the backend will default to `"inductor"` (can be customized with `torch_compile_backend`) and the mode will default to `"default"` (can be customized with `torch_compile_mode`). torch_compile_backend (`str`, *optional*): The backend to use in `torch.compile`. If set to any value, `torch_compile` will be set to `True`. Possible choices are `"eager"`, `"aot_eager"`, `"inductor"`, `"nvfuser"`, `"aot_nvfuser"`, `"aot_cudagraphs"`, `"ofi"`, `"fx2trt"`, `"onnxrt"` and `"ipex"`. torch_compile_mode (`str`, *optional*): The mode to use in `torch.compile`. If set to any value, `torch_compile` will be set to `True`. Possible choices are `"default"`, `"reduce-overhead"` and `"max-autotune"`. """ framework = "pt" output_dir: str = field( metadata={"help": "The output directory where the model predictions and checkpoints will be written."}, ) overwrite_output_dir: bool = field( default=False, metadata={ "help": ( "Overwrite the content of the output directory. " "Use this to continue training if output_dir points to a checkpoint directory." ) }, ) do_train: bool = field(default=False, metadata={"help": "Whether to run training."}) do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."}) do_predict: bool = field(default=False, metadata={"help": "Whether to run predictions on the test set."}) evaluation_strategy: Union[IntervalStrategy, str] = field( default="no", metadata={"help": "The evaluation strategy to use."}, ) prediction_loss_only: bool = field( default=False, metadata={"help": "When performing evaluation and predictions, only returns the loss."}, ) per_device_train_batch_size: int = field( default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for training."} ) per_device_eval_batch_size: int = field( default=8, metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."} ) per_gpu_train_batch_size: Optional[int] = field( default=None, metadata={ "help": ( "Deprecated, the use of `--per_device_train_batch_size` is preferred. " "Batch size per GPU/TPU core/CPU for training." ) }, ) per_gpu_eval_batch_size: Optional[int] = field( default=None, metadata={ "help": ( "Deprecated, the use of `--per_device_eval_batch_size` is preferred. " "Batch size per GPU/TPU core/CPU for evaluation." ) }, ) gradient_accumulation_steps: int = field( default=1, metadata={"help": "Number of updates steps to accumulate before performing a backward/update pass."}, ) eval_accumulation_steps: Optional[int] = field( default=None, metadata={"help": "Number of predictions steps to accumulate before moving the tensors to the CPU."}, ) eval_delay: Optional[float] = field( default=0, metadata={ "help": ( "Number of epochs or steps to wait for before the first evaluation can be performed, depending on the" " evaluation_strategy." ) }, ) learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."}) weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."}) adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"}) adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"}) adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."}) max_grad_norm: float = field(default=1.0, metadata={"help": "Max gradient norm."}) num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."}) max_steps: int = field( default=-1, metadata={"help": "If > 0: set total number of training steps to perform. Override num_train_epochs."}, ) lr_scheduler_type: Union[SchedulerType, str] = field( default="linear", metadata={"help": "The scheduler type to use."}, ) warmup_ratio: float = field( default=0.0, metadata={"help": "Linear warmup over warmup_ratio fraction of total steps."} ) warmup_steps: int = field(default=0, metadata={"help": "Linear warmup over warmup_steps."}) log_level: Optional[str] = field( default="passive", metadata={ "help": ( "Logger log level to use on the main node. Possible choices are the log levels as strings: 'debug'," " 'info', 'warning', 'error' and 'critical', plus a 'passive' level which doesn't set anything and" " lets the application set the level. Defaults to 'passive'." ), "choices": trainer_log_levels.keys(), }, ) log_level_replica: Optional[str] = field( default="warning", metadata={ "help": "Logger log level to use on replica nodes. Same choices and defaults as ``log_level``", "choices": trainer_log_levels.keys(), }, ) log_on_each_node: bool = field( default=True, metadata={ "help": ( "When doing a multinode distributed training, whether to log once per node or just once on the main" " node." ) }, ) logging_dir: Optional[str] = field(default=None, metadata={"help": "Tensorboard log dir."}) logging_strategy: Union[IntervalStrategy, str] = field( default="steps", metadata={"help": "The logging strategy to use."}, ) logging_first_step: bool = field(default=False, metadata={"help": "Log the first global_step"}) logging_steps: int = field(default=500, metadata={"help": "Log every X updates steps."}) logging_nan_inf_filter: bool = field(default=True, metadata={"help": "Filter nan and inf losses for logging."}) save_strategy: Union[IntervalStrategy, str] = field( default="steps", metadata={"help": "The checkpoint save strategy to use."}, ) save_steps: int = field(default=500, metadata={"help": "Save checkpoint every X updates steps."}) save_total_limit: Optional[int] = field( default=None, metadata={ "help": ( "Limit the total amount of checkpoints. " "Deletes the older checkpoints in the output_dir. Default is unlimited checkpoints" ) }, ) save_on_each_node: bool = field( default=False, metadata={ "help": ( "When doing multi-node distributed training, whether to save models and checkpoints on each node, or" " only on the main one" ) }, ) no_cuda: bool = field(default=False, metadata={"help": "Do not use CUDA even when it is available"}) use_mps_device: bool = field( default=False, metadata={"help": "Whether to use Apple Silicon chip based `mps` device."} ) seed: int = field(default=42, metadata={"help": "Random seed that will be set at the beginning of training."}) data_seed: Optional[int] = field(default=None, metadata={"help": "Random seed to be used with data samplers."}) jit_mode_eval: bool = field( default=False, metadata={"help": "Whether or not to use PyTorch jit trace for inference"} ) use_ipex: bool = field( default=False, metadata={ "help": ( "Use Intel extension for PyTorch when it is available, installation:" " 'https://github.com/intel/intel-extension-for-pytorch'" ) }, ) bf16: bool = field( default=False, metadata={ "help": ( "Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA" " architecture or using CPU (no_cuda). This is an experimental API and it may change." ) }, ) fp16: bool = field( default=False, metadata={"help": "Whether to use fp16 (mixed) precision instead of 32-bit"}, ) fp16_opt_level: str = field( default="O1", metadata={ "help": ( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. " "See details at https://nvidia.github.io/apex/amp.html" ) }, ) half_precision_backend: str = field( default="auto", metadata={ "help": "The backend to be used for half precision.", "choices": ["auto", "cuda_amp", "apex", "cpu_amp"], }, ) bf16_full_eval: bool = field( default=False, metadata={ "help": ( "Whether to use full bfloat16 evaluation instead of 32-bit. This is an experimental API and it may" " change." ) }, ) fp16_full_eval: bool = field( default=False, metadata={"help": "Whether to use full float16 evaluation instead of 32-bit"}, ) tf32: Optional[bool] = field( default=None, metadata={ "help": ( "Whether to enable tf32 mode, available in Ampere and newer GPU architectures. This is an experimental" " API and it may change." ) }, ) local_rank: int = field(default=-1, metadata={"help": "For distributed training: local_rank"}) xpu_backend: Optional[str] = field( default=None, metadata={ "help": "The backend to be used for distributed training on Intel XPU.", "choices": ["mpi", "ccl", "gloo"], }, ) tpu_num_cores: Optional[int] = field( default=None, metadata={"help": "TPU: Number of TPU cores (automatically passed by launcher script)"} ) tpu_metrics_debug: bool = field( default=False, metadata={ "help": ( "Deprecated, the use of `--debug tpu_metrics_debug` is preferred. TPU: Whether to print debug metrics" ) }, ) debug: str = field( default="", metadata={ "help": ( "Whether or not to enable debug mode. Current options: " "`underflow_overflow` (Detect underflow and overflow in activations and weights), " "`tpu_metrics_debug` (print debug metrics on TPU)." ) }, ) dataloader_drop_last: bool = field( default=False, metadata={"help": "Drop the last incomplete batch if it is not divisible by the batch size."} ) eval_steps: Optional[int] = field(default=None, metadata={"help": "Run an evaluation every X steps."}) dataloader_num_workers: int = field( default=0, metadata={ "help": ( "Number of subprocesses to use for data loading (PyTorch only). 0 means that the data will be loaded" " in the main process." ) }, ) past_index: int = field( default=-1, metadata={"help": "If >=0, uses the corresponding part of the output as the past state for next step."}, ) run_name: Optional[str] = field( default=None, metadata={"help": "An optional descriptor for the run. Notably used for wandb logging."} ) disable_tqdm: Optional[bool] = field( default=None, metadata={"help": "Whether or not to disable the tqdm progress bars."} ) remove_unused_columns: Optional[bool] = field( default=True, metadata={"help": "Remove columns not required by the model when using an nlp.Dataset."} ) label_names: Optional[List[str]] = field( default=None, metadata={"help": "The list of keys in your dictionary of inputs that correspond to the labels."} ) load_best_model_at_end: Optional[bool] = field( default=False, metadata={"help": "Whether or not to load the best model found during training at the end of training."}, ) metric_for_best_model: Optional[str] = field( default=None, metadata={"help": "The metric to use to compare two different models."} ) greater_is_better: Optional[bool] = field( default=None, metadata={"help": "Whether the `metric_for_best_model` should be maximized or not."} ) ignore_data_skip: bool = field( default=False, metadata={ "help": ( "When resuming training, whether or not to skip the first epochs and batches to get to the same" " training data." ) }, ) sharded_ddp: str = field( default="", metadata={ "help": ( "Whether or not to use sharded DDP training (in distributed training only). The base option should be" " `simple`, `zero_dp_2` or `zero_dp_3` and you can add CPU-offload to `zero_dp_2` or `zero_dp_3` like" " this: zero_dp_2 offload` or `zero_dp_3 offload`. You can add auto-wrap to `zero_dp_2` or `zero_dp_3`" " with the same syntax: zero_dp_2 auto_wrap` or `zero_dp_3 auto_wrap`." ), }, ) fsdp: str = field( default="", metadata={ "help": ( "Whether or not to use PyTorch Fully Sharded Data Parallel (FSDP) training (in distributed training" " only). The base option should be `full_shard`, `shard_grad_op` or `no_shard` and you can add" " CPU-offload to `full_shard` or `shard_grad_op` like this: full_shard offload` or `shard_grad_op" " offload`. You can add auto-wrap to `full_shard` or `shard_grad_op` with the same syntax: full_shard" " auto_wrap` or `shard_grad_op auto_wrap`." ), }, ) fsdp_min_num_params: int = field( default=0, metadata={ "help": ( "This parameter is deprecated. FSDP's minimum number of parameters for Default Auto Wrapping. (useful" " only when `fsdp` field is passed)." ) }, ) fsdp_config: Optional[str] = field( default=None, metadata={ "help": ( "Config to be used with FSDP (Pytorch Fully Sharded Data Parallel). The value is either a" "fsdp json config file (e.g., `fsdp_config.json`) or an already loaded json file as `dict`." ) }, ) fsdp_transformer_layer_cls_to_wrap: Optional[str] = field( default=None, metadata={ "help": ( "This parameter is deprecated. Transformer layer class name (case-sensitive) to wrap, e.g," " `BertLayer`, `GPTJBlock`, `T5Block` .... (useful only when `fsdp` flag is passed)." ) }, ) deepspeed: Optional[str] = field( default=None, metadata={ "help": ( "Enable deepspeed and pass the path to deepspeed json config file (e.g. ds_config.json) or an already" " loaded json file as a dict" ) }, ) label_smoothing_factor: float = field( default=0.0, metadata={"help": "The label smoothing epsilon to apply (zero means no label smoothing)."} ) optim: Union[OptimizerNames, str] = field( default="adamw_hf", metadata={"help": "The optimizer to use."}, ) optim_args: Optional[str] = field(default=None, metadata={"help": "Optional arguments to supply to optimizer."}) adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."}) group_by_length: bool = field( default=False, metadata={"help": "Whether or not to group samples of roughly the same length together when batching."}, ) length_column_name: Optional[str] = field( default="length", metadata={"help": "Column name with precomputed lengths to use when grouping by length."}, ) report_to: Optional[List[str]] = field( default=None, metadata={"help": "The list of integrations to report the results and logs to."} ) ddp_find_unused_parameters: Optional[bool] = field( default=None, metadata={ "help": ( "When using distributed training, the value of the flag `find_unused_parameters` passed to " "`DistributedDataParallel`." ) }, ) ddp_bucket_cap_mb: Optional[int] = field( default=None, metadata={ "help": ( "When using distributed training, the value of the flag `bucket_cap_mb` passed to " "`DistributedDataParallel`." ) }, ) dataloader_pin_memory: bool = field( default=True, metadata={"help": "Whether or not to pin memory for DataLoader."} ) skip_memory_metrics: bool = field( default=True, metadata={"help": "Whether or not to skip adding of memory profiler reports to metrics."} ) use_legacy_prediction_loop: bool = field( default=False, metadata={"help": "Whether or not to use the legacy prediction_loop in the Trainer."} ) push_to_hub: bool = field( default=False, metadata={"help": "Whether or not to upload the trained model to the model hub after training."} ) resume_from_checkpoint: Optional[str] = field( default=None, metadata={"help": "The path to a folder with a valid checkpoint for your model."}, ) hub_model_id: Optional[str] = field( default=None, metadata={"help": "The name of the repository to keep in sync with the local `output_dir`."} ) hub_strategy: Union[HubStrategy, str] = field( default="every_save", metadata={"help": "The hub strategy to use when `--push_to_hub` is activated."}, ) hub_token: Optional[str] = field(default=None, metadata={"help": "The token to use to push to the Model Hub."}) hub_private_repo: bool = field(default=False, metadata={"help": "Whether the model repository is private or not."}) gradient_checkpointing: bool = field( default=False, metadata={ "help": "If True, use gradient checkpointing to save memory at the expense of slower backward pass." }, ) include_inputs_for_metrics: bool = field( default=False, metadata={"help": "Whether or not the inputs will be passed to the `compute_metrics` function."} ) # Deprecated arguments fp16_backend: str = field( default="auto", metadata={ "help": "Deprecated. Use half_precision_backend instead", "choices": ["auto", "cuda_amp", "apex", "cpu_amp"], }, ) push_to_hub_model_id: Optional[str] = field( default=None, metadata={"help": "The name of the repository to which push the `Trainer`."} ) push_to_hub_organization: Optional[str] = field( default=None, metadata={"help": "The name of the organization in with to which push the `Trainer`."} ) push_to_hub_token: Optional[str] = field( default=None, metadata={"help": "The token to use to push to the Model Hub."} ) _n_gpu: int = field(init=False, repr=False, default=-1) mp_parameters: str = field( default="", metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in Trainer"}, ) auto_find_batch_size: bool = field( default=False, metadata={ "help": ( "Whether to automatically decrease the batch size in half and rerun the training loop again each time" " a CUDA Out-of-Memory was reached" ) }, ) full_determinism: bool = field( default=False, metadata={ "help": ( "Whether to call enable_full_determinism instead of set_seed for reproducibility in distributed" " training" ) }, ) torchdynamo: Optional[str] = field( default=None, metadata={ "help": "This argument is deprecated, use `--torch_compile_backend` instead.", "choices": TORCH_COMPILE_BACKENDS, }, ) ray_scope: Optional[str] = field( default="last", metadata={ "help": ( 'The scope to use when doing hyperparameter search with Ray. By default, `"last"` will be used. Ray' " will then use the last checkpoint of all trials, compare those, and select the best one. However," " other options are also available. See the Ray documentation" " (https://docs.ray.io/en/latest/tune/api_docs/analysis.html" "#ray.tune.ExperimentAnalysis.get_best_trial)" " for more options." ) }, ) ddp_timeout: Optional[int] = field( default=1800, metadata={ "help": "Overrides the default timeout for distributed training (value should be given in seconds)." }, ) torch_compile: bool = field( default=False, metadata={"help": "If set to `True`, the model will be wrapped in `torch.compile`."} ) torch_compile_backend: Optional[str] = field( default=None, metadata={ "help": "Which backend to use with `torch.compile`, passing one will trigger a model compilation.", "choices": TORCH_COMPILE_BACKENDS, }, ) torch_compile_mode: Optional[str] = field( default=None, metadata={ "help": "Which mode to use with `torch.compile`, passing one will trigger a model compilation.", "choices": ["default", "reduce-overhead", "max-autotune"], }, ) def __post_init__(self): # Handle --use_env option in torch.distributed.launch (local_rank not passed as an arg then). # This needs to happen before any call to self.device or self.n_gpu. env_local_rank = int(os.environ.get("LOCAL_RANK", -1)) if env_local_rank != -1 and env_local_rank != self.local_rank: self.local_rank = env_local_rank # expand paths, if not os.makedirs("~/bar") will make directory # in the current directory instead of the actual home # see https://github.com/huggingface/transformers/issues/10628 if self.output_dir is not None: self.output_dir = os.path.expanduser(self.output_dir) if self.logging_dir is None and self.output_dir is not None: self.logging_dir = os.path.join(self.output_dir, default_logdir()) if self.logging_dir is not None: self.logging_dir = os.path.expanduser(self.logging_dir) if self.disable_tqdm is None: self.disable_tqdm = logger.getEffectiveLevel() > logging.WARN if isinstance(self.evaluation_strategy, EvaluationStrategy): warnings.warn( "using `EvaluationStrategy` for `evaluation_strategy` is deprecated and will be removed in version 5" " of 🤗 Transformers. Use `IntervalStrategy` instead", FutureWarning, ) # Go back to the underlying string or we won't be able to instantiate `IntervalStrategy` on it. self.evaluation_strategy = self.evaluation_strategy.value self.evaluation_strategy = IntervalStrategy(self.evaluation_strategy) self.logging_strategy = IntervalStrategy(self.logging_strategy) self.save_strategy = IntervalStrategy(self.save_strategy) self.hub_strategy = HubStrategy(self.hub_strategy) self.lr_scheduler_type = SchedulerType(self.lr_scheduler_type) if self.do_eval is False and self.evaluation_strategy != IntervalStrategy.NO: self.do_eval = True # eval_steps has to be defined and non-zero, fallbacks to logging_steps if the latter is non-zero if self.evaluation_strategy == IntervalStrategy.STEPS and (self.eval_steps is None or self.eval_steps == 0): if self.logging_steps > 0: logger.info(f"using `logging_steps` to initialize `eval_steps` to {self.logging_steps}") self.eval_steps = self.logging_steps else: raise ValueError( f"evaluation strategy {self.evaluation_strategy} requires either non-zero --eval_steps or" " --logging_steps" ) # logging_steps must be non-zero for logging_strategy that is other than 'no' if self.logging_strategy == IntervalStrategy.STEPS and self.logging_steps == 0: raise ValueError(f"logging strategy {self.logging_strategy} requires non-zero --logging_steps") # Sanity checks for load_best_model_at_end: we require save and eval strategies to be compatible. if self.load_best_model_at_end: if self.evaluation_strategy != self.save_strategy: raise ValueError( "--load_best_model_at_end requires the save and eval strategy to match, but found\n- Evaluation " f"strategy: {self.evaluation_strategy}\n- Save strategy: {self.save_strategy}" ) if self.evaluation_strategy == IntervalStrategy.STEPS and self.save_steps % self.eval_steps != 0: raise ValueError( "--load_best_model_at_end requires the saving steps to be a round multiple of the evaluation " f"steps, but found {self.save_steps}, which is not a round multiple of {self.eval_steps}." ) if self.load_best_model_at_end and self.metric_for_best_model is None: self.metric_for_best_model = "loss" if self.greater_is_better is None and self.metric_for_best_model is not None: self.greater_is_better = self.metric_for_best_model not in ["loss", "eval_loss"] if self.run_name is None: self.run_name = self.output_dir if self.framework == "pt" and is_torch_available(): if self.fp16_backend and self.fp16_backend != "auto": warnings.warn( "`fp16_backend` is deprecated and will be removed in version 5 of 🤗 Transformers. Use" " `half_precision_backend` instead", FutureWarning, ) self.half_precision_backend = self.fp16_backend if self.bf16 or self.bf16_full_eval: if self.no_cuda and not is_torch_bf16_cpu_available() and not is_torch_tpu_available(): # cpu raise ValueError("Your setup doesn't support bf16/(cpu, tpu, neuroncore). You need torch>=1.10") elif not self.no_cuda and torch.cuda.is_available() and not is_torch_bf16_gpu_available(): # gpu raise ValueError( "Your setup doesn't support bf16/gpu. You need torch>=1.10, using Ampere GPU with cuda>=11.0" ) if self.fp16 and self.bf16: raise ValueError("At most one of fp16 and bf16 can be True, but not both") if self.fp16_full_eval and self.bf16_full_eval: raise ValueError("At most one of fp16 and bf16 can be True for full eval, but not both") if self.bf16: if self.half_precision_backend == "apex": raise ValueError( " `--half_precision_backend apex`: GPU bf16 is not supported by apex. Use" " `--half_precision_backend cuda_amp` instead" ) if not (self.sharded_ddp == "" or not self.sharded_ddp): raise ValueError("sharded_ddp is not supported with bf16") self.optim = OptimizerNames(self.optim) if self.adafactor: warnings.warn( "`--adafactor` is deprecated and will be removed in version 5 of 🤗 Transformers. Use `--optim" " adafactor` instead", FutureWarning, ) self.optim = OptimizerNames.ADAFACTOR if ( self.framework == "pt" and is_torch_available() and (self.device.type != "cuda") and (get_xla_device_type(self.device) != "GPU") and (self.fp16 or self.fp16_full_eval) ): raise ValueError( "FP16 Mixed precision training with AMP or APEX (`--fp16`) and FP16 half precision evaluation" " (`--fp16_full_eval`) can only be used on CUDA devices." ) if ( self.framework == "pt" and is_torch_available() and (self.device.type != "cuda") and (get_xla_device_type(self.device) != "GPU") and (get_xla_device_type(self.device) != "TPU") and (self.device.type != "cpu") and (self.bf16 or self.bf16_full_eval) ): raise ValueError( "BF16 Mixed precision training with AMP (`--bf16`) and BF16 half precision evaluation" " (`--bf16_full_eval`) can only be used on CUDA or CPU/TPU/NeuronCore devices." ) if self.torchdynamo is not None: warnings.warn( "`torchdynamo` is deprecated and will be removed in version 5 of 🤗 Transformers. Use" " `torch_compile_backend` instead", FutureWarning, ) self.torch_compile_backend = self.torchdynamo if (self.torch_compile_mode is not None or self.torch_compile_backend is not None) and not self.torch_compile: self.torch_compile = True if self.torch_compile and self.torch_compile_backend is None: self.torch_compile_backend = "inductor" if self.framework == "pt" and is_torch_available() and self.torch_compile: if is_torch_tf32_available(): if self.tf32 is None and not self.fp16 or self.bf16: logger.info( "Setting TF32 in CUDA backends to speedup torch compile, you won't see any improvement" " otherwise." ) torch.backends.cuda.matmul.allow_tf32 = True else: logger.warning( "The speedups for torchdynamo mostly come wih GPU Ampere or higher and which is not detected here." ) if self.framework == "pt" and is_torch_available() and self.tf32 is not None: if self.tf32: if is_torch_tf32_available(): torch.backends.cuda.matmul.allow_tf32 = True else: raise ValueError("--tf32 requires Ampere or a newer GPU arch, cuda>=11 and torch>=1.7") else: if is_torch_tf32_available(): torch.backends.cuda.matmul.allow_tf32 = False # no need to assert on else if self.report_to is None: logger.info( "The default value for the training argument `--report_to` will change in v5 (from all installed " "integrations to none). In v5, you will need to use `--report_to all` to get the same behavior as " "now. You should start updating your code and make this info disappear :-)." ) self.report_to = "all" if self.report_to == "all" or self.report_to == ["all"]: # Import at runtime to avoid a circular import. from .integrations import get_available_reporting_integrations self.report_to = get_available_reporting_integrations() elif self.report_to == "none" or self.report_to == ["none"]: self.report_to = [] elif not isinstance(self.report_to, list): self.report_to = [self.report_to] if self.warmup_ratio < 0 or self.warmup_ratio > 1: raise ValueError("warmup_ratio must lie in range [0,1]") elif self.warmup_ratio > 0 and self.warmup_steps > 0: logger.info( "Both warmup_ratio and warmup_steps given, warmup_steps will override any effect of warmup_ratio" " during training" ) if isinstance(self.sharded_ddp, bool): self.sharded_ddp = "simple" if self.sharded_ddp else "" if isinstance(self.sharded_ddp, str): self.sharded_ddp = [ShardedDDPOption(s) for s in self.sharded_ddp.split()] if self.sharded_ddp == [ShardedDDPOption.OFFLOAD]: raise ValueError( "`--sharded_ddp offload` can't work on its own. It needs to be added to `--sharded_ddp zero_dp_2` or " '`--sharded_ddp zero_dp_3`. For example, `--sharded_ddp "zero_dp_2 offload"`.' ) elif len(self.sharded_ddp) > 1 and ShardedDDPOption.SIMPLE in self.sharded_ddp: raise ValueError("`--sharded_ddp simple` is not compatible with any other option.") elif ShardedDDPOption.ZERO_DP_2 in self.sharded_ddp and ShardedDDPOption.ZERO_DP_3 in self.sharded_ddp: raise ValueError("`--sharded_ddp zero_dp_2` is not compatible with `--sharded_ddp zero_dp_3`.") if isinstance(self.fsdp, bool): self.fsdp = "full_shard" if self.fsdp else "" if isinstance(self.fsdp, str): self.fsdp = [FSDPOption(s) for s in self.fsdp.split()] if self.fsdp == [FSDPOption.OFFLOAD]: raise ValueError( "`--fsdp offload` can't work on its own. It needs to be added to `--fsdp full_shard` or " '`--fsdp shard_grad_op`. For example, `--fsdp "full_shard offload"`.' ) elif FSDPOption.FULL_SHARD in self.fsdp and FSDPOption.SHARD_GRAD_OP in self.fsdp: raise ValueError("`--fsdp full_shard` is not compatible with `--fsdp shard_grad_op`.") if self.fsdp_config is None: self.fsdp_config = {} if isinstance(self.fsdp_config, str): with io.open(self.fsdp_config, "r", encoding="utf-8") as f: self.fsdp_config = json.load(f) if self.fsdp_min_num_params > 0: warnings.warn("using `--fsdp_min_num_params` is deprecated. Use fsdp_config instead ", FutureWarning) self.fsdp_config["fsdp_min_num_params"] = max( self.fsdp_config.get("fsdp_min_num_params", 0), self.fsdp_min_num_params ) # if fsdp_config["fsdp_transformer_layer_cls_to_wrap"] is specified as a string, convert it to a list with a single object if isinstance(self.fsdp_config.get("fsdp_transformer_layer_cls_to_wrap", None), str): self.fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = [ self.fsdp_config["fsdp_transformer_layer_cls_to_wrap"] ] if self.fsdp_transformer_layer_cls_to_wrap is not None: warnings.warn( "using `--fsdp_transformer_layer_cls_to_wrap` is deprecated. Use fsdp_config instead ", FutureWarning ) self.fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = self.fsdp_config.get( "fsdp_transformer_layer_cls_to_wrap", [] ) + [self.fsdp_transformer_layer_cls_to_wrap] if len(self.fsdp) == 0 and self.fsdp_config["fsdp_min_num_params"] > 0: warnings.warn("`--fsdp_min_num_params` is useful only when `--fsdp` is specified.") if len(self.fsdp) == 0 and self.fsdp_config.get("fsdp_transformer_layer_cls_to_wrap", None) is not None: warnings.warn("`--fsdp_transformer_layer_cls_to_wrap` is useful only when `--fsdp` is specified.") if ( len(self.fsdp) > 0 and self.fsdp_config["fsdp_min_num_params"] > 0 and self.fsdp_config.get("fsdp_transformer_layer_cls_to_wrap", None) is not None ): raise ValueError( "`--fsdp_min_num_params` and `--fsdp_transformer_layer_cls_to_wrap` are mutually exclusive." ) self.fsdp_config["xla"] = self.fsdp_config.get("xla", False) self.fsdp_config["xla_fsdp_grad_ckpt"] = self.fsdp_config.get("xla_fsdp_grad_ckpt", False) if self.fsdp_config["xla"]: if len(self.fsdp) > 0: # store XLA fsdp configuration parameters into a dictionary self.xla_fsdp_config = self.fsdp_config.get("xla_fsdp_settings", {}) # apply appropriate string to torch.dtype conversions for parameters if "compute_dtype" in self.xla_fsdp_config: self.xla_fsdp_config["compute_dtype"] = getattr(torch, self.xla_fsdp_config["compute_dtype"]) if "buffer_dtype" in self.xla_fsdp_config: self.xla_fsdp_config["buffer_dtype"] = getattr(torch, self.xla_fsdp_config["buffer_dtype"]) else: warnings.warn("XLA FSDP can be used only when `--fsdp` is specified.") else: if self.fsdp_config["xla_fsdp_grad_ckpt"]: warnings.warn("`--xla_fsdp_grad_ckpt` is useful only when `--xla` is set to true.") if self.tpu_metrics_debug: warnings.warn( "using `--tpu_metrics_debug` is deprecated and will be removed in version 5 of 🤗 Transformers. Use" " `--debug tpu_metrics_debug` instead", FutureWarning, ) self.debug += " tpu_metrics_debug" self.tpu_metrics_debug = False if isinstance(self.debug, str): self.debug = [DebugOption(s) for s in self.debug.split()] if self.deepspeed: # - must be run very last in arg parsing, since it will use a lot of these settings. # - must be run before the model is created. if not is_accelerate_available(): raise ValueError("--deepspeed requires Accelerate to be installed: `pip install accelerate`.") from transformers.deepspeed import HfTrainerDeepSpeedConfig # will be used later by the Trainer # note: leave self.deepspeed unmodified in case a user relies on it not to be modified) self.hf_deepspeed_config = HfTrainerDeepSpeedConfig(self.deepspeed) self.hf_deepspeed_config.trainer_config_process(self) if self.push_to_hub_token is not None: warnings.warn( "`--push_to_hub_token` is deprecated and will be removed in version 5 of 🤗 Transformers. Use " "`--hub_token` instead.", FutureWarning, ) self.hub_token = self.push_to_hub_token if self.push_to_hub_model_id is not None: self.hub_model_id = get_full_repo_name( self.push_to_hub_model_id, organization=self.push_to_hub_organization, token=self.hub_token ) if self.push_to_hub_organization is not None: warnings.warn( "`--push_to_hub_model_id` and `--push_to_hub_organization` are deprecated and will be removed in " "version 5 of 🤗 Transformers. Use `--hub_model_id` instead and pass the full repo name to this " f"argument (in this case {self.hub_model_id}).", FutureWarning, ) else: warnings.warn( "`--push_to_hub_model_id` is deprecated and will be removed in version 5 of 🤗 Transformers. Use " "`--hub_model_id` instead and pass the full repo name to this argument (in this case " f"{self.hub_model_id}).", FutureWarning, ) elif self.push_to_hub_organization is not None: self.hub_model_id = f"{self.push_to_hub_organization}/{Path(self.output_dir).name}" warnings.warn( "`--push_to_hub_organization` is deprecated and will be removed in version 5 of 🤗 Transformers. Use " "`--hub_model_id` instead and pass the full repo name to this argument (in this case " f"{self.hub_model_id}).", FutureWarning, ) def __str__(self): self_as_dict = asdict(self) # Remove deprecated arguments. That code should be removed once # those deprecated arguments are removed from TrainingArguments. (TODO: v5) del self_as_dict["per_gpu_train_batch_size"] del self_as_dict["per_gpu_eval_batch_size"] self_as_dict = {k: f"<{k.upper()}>" if k.endswith("_token") else v for k, v in self_as_dict.items()} attrs_as_str = [f"{k}={v},\n" for k, v in sorted(self_as_dict.items())] return f"{self.__class__.__name__}(\n{''.join(attrs_as_str)})" __repr__ = __str__ @property def train_batch_size(self) -> int: """ The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training). """ if self.per_gpu_train_batch_size: logger.warning( "Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future " "version. Using `--per_device_train_batch_size` is preferred." ) per_device_batch_size = self.per_gpu_train_batch_size or self.per_device_train_batch_size train_batch_size = per_device_batch_size * max(1, self.n_gpu) return train_batch_size @property def eval_batch_size(self) -> int: """ The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training). """ if self.per_gpu_eval_batch_size: logger.warning( "Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future " "version. Using `--per_device_eval_batch_size` is preferred." ) per_device_batch_size = self.per_gpu_eval_batch_size or self.per_device_eval_batch_size eval_batch_size = per_device_batch_size * max(1, self.n_gpu) return eval_batch_size @property def ddp_timeout_delta(self) -> timedelta: """ The actual timeout for torch.distributed.init_process_group since it expects a timedelta variable. """ return timedelta(seconds=self.ddp_timeout) @cached_property def _setup_devices(self) -> "torch.device": requires_backends(self, ["torch"]) logger.info("PyTorch: setting up devices") if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: device = torch.device("cpu") self._n_gpu = 0 self.local_rank = get_int_from_env( ["LOCAL_RANK", "MPI_LOCALRANKID", "OMPI_COMM_WORLD_LOCAL_RANK", "MV2_COMM_WORLD_LOCAL_RANK"], self.local_rank, ) if self.local_rank != -1 and not torch.distributed.is_initialized(): # Initializes distributed backend for cpu if self.xpu_backend not in ("mpi", "ccl", "gloo"): raise ValueError( "CPU distributed training backend is not properly set. " "Please set '--xpu_backend' to either 'mpi' or 'ccl' or 'gloo'." ) if self.xpu_backend == "ccl": requires_backends(self, "oneccl_bind_pt") if ccl_version >= "1.12": import oneccl_bindings_for_pytorch # noqa: F401 else: import torch_ccl # noqa: F401 if int(os.environ.get("CCL_WORKER_COUNT", 0)) < 1: raise ValueError( "CPU distributed training backend is ccl. but CCL_WORKER_COUNT is not correctly set. " "Please use like 'export CCL_WORKER_COUNT = 1' to set." ) # Try to get launch configuration from environment variables set by MPI launcher - works for Intel MPI, OpenMPI and MVAPICH rank = get_int_from_env(["RANK", "PMI_RANK", "OMPI_COMM_WORLD_RANK", "MV2_COMM_WORLD_RANK"], 0) size = get_int_from_env(["WORLD_SIZE", "PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE"], 1) local_size = get_int_from_env( ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"], 1 ) os.environ["RANK"] = str(rank) os.environ["WORLD_SIZE"] = str(size) os.environ["LOCAL_RANK"] = str(self.local_rank) if not os.environ.get("MASTER_PORT", None): os.environ["MASTER_PORT"] = "29500" if not os.environ.get("MASTER_ADDR", None): if local_size != size or self.xpu_backend != "mpi": raise ValueError( "Looks like distributed multinode run but MASTER_ADDR env not set, " "please try exporting rank 0's hostname as MASTER_ADDR" ) if ( torch.get_num_threads() == 1 and get_int_from_env(["OMP_NUM_THREADS", "MKL_NUM_THREADS"], 0) == 0 and is_psutil_available() ): import psutil num_cpu_threads_per_process = int(psutil.cpu_count(logical=False) / local_size) if num_cpu_threads_per_process == 0: num_cpu_threads_per_process = 1 torch.set_num_threads(num_cpu_threads_per_process) logger.info( f"num_cpu_threads_per_process unset, we set it at {num_cpu_threads_per_process} to improve oob" " performance." ) torch.distributed.init_process_group( backend=self.xpu_backend, rank=rank, world_size=size, timeout=self.ddp_timeout_delta ) elif is_torch_tpu_available(): device = xm.xla_device() self._n_gpu = 0 elif is_sagemaker_mp_enabled(): local_rank = smp.local_rank() device = torch.device("cuda", local_rank) self._n_gpu = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 dist.init_process_group(backend="smddp", timeout=self.ddp_timeout_delta) self.local_rank = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK")) device = torch.device("cuda", self.local_rank) self._n_gpu = 1 elif self.deepspeed: # deepspeed inits torch.distributed internally from .deepspeed import is_deepspeed_available if not is_deepspeed_available(): raise ImportError("--deepspeed requires deepspeed: `pip install deepspeed`.") import deepspeed deepspeed.init_distributed(timeout=timedelta(seconds=self.ddp_timeout)) # workaround for setups like notebooks where the launcher can't be used, # but deepspeed requires a dist env. # env LOCAL_RANK could be set manually by the user, or via init_distributed if mpi4py is installed self.local_rank = int(os.environ.get("LOCAL_RANK", "-1")) device = torch.device("cuda", self.local_rank) self._n_gpu = 1 elif self.local_rank == -1: if self.use_mps_device: if not torch.backends.mps.is_available(): if not torch.backends.mps.is_built(): raise AssertionError( "MPS not available because the current PyTorch install was not " "built with MPS enabled. Please install torch version >=1.12.0 on " "your Apple silicon Mac running macOS 12.3 or later with a native " "version (arm64) of Python" ) else: raise AssertionError( "MPS not available because the current MacOS version is not 12.3+ " "and/or you do not have an MPS-enabled device on this machine." ) else: if not version.parse(version.parse(torch.__version__).base_version) > version.parse("1.12.0"): warnings.warn( "We strongly recommend to install PyTorch >= 1.13 (nightly version at the time of writing)" " on your MacOS machine. It has major fixes related to model correctness and performance" " improvements for transformer based models. Please refer to" " https://github.com/pytorch/pytorch/issues/82707 for more details." ) device = torch.device("mps") self._n_gpu = 1 else: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. self._n_gpu = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl", timeout=self.ddp_timeout_delta) device = torch.device("cuda", self.local_rank) self._n_gpu = 1 if device.type == "cuda": torch.cuda.set_device(device) return device @property def device(self) -> "torch.device": """ The device used by this process. """ requires_backends(self, ["torch"]) return self._setup_devices @property def n_gpu(self): """ The number of GPUs used by this process. Note: This will only be greater than one when you have multiple GPUs available but are not using distributed training. For distributed training, it will always be 1. """ requires_backends(self, ["torch"]) # Make sure `self._n_gpu` is properly setup. _ = self._setup_devices return self._n_gpu @property def parallel_mode(self): """ The current mode used for parallelism if multiple GPUs/TPU cores are available. One of: - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU). - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`). - `ParallelMode.DISTRIBUTED`: several GPUs, each having its own process (uses `torch.nn.DistributedDataParallel`). - `ParallelMode.TPU`: several TPU cores. """ requires_backends(self, ["torch"]) if is_torch_tpu_available(): return ParallelMode.TPU elif is_sagemaker_mp_enabled(): return ParallelMode.SAGEMAKER_MODEL_PARALLEL elif is_sagemaker_dp_enabled(): return ParallelMode.SAGEMAKER_DATA_PARALLEL elif self.local_rank != -1: return ParallelMode.DISTRIBUTED elif self.n_gpu > 1: return ParallelMode.NOT_DISTRIBUTED else: return ParallelMode.NOT_PARALLEL @property def world_size(self): """ The number of processes used in parallel. """ requires_backends(self, ["torch"]) if is_torch_tpu_available(): return xm.xrt_world_size() elif is_sagemaker_mp_enabled(): return smp.dp_size() if not smp.state.cfg.prescaled_batch else smp.rdp_size() elif is_sagemaker_dp_enabled(): return dist.get_world_size() elif self.local_rank != -1: return torch.distributed.get_world_size() return 1 @property def process_index(self): """ The index of the current process used. """ requires_backends(self, ["torch"]) if is_torch_tpu_available(): return xm.get_ordinal() elif is_sagemaker_mp_enabled(): return smp.dp_rank() if not smp.state.cfg.prescaled_batch else smp.rdp_rank() elif is_sagemaker_dp_enabled(): return dist.get_rank() elif self.local_rank != -1: return torch.distributed.get_rank() return 0 @property def local_process_index(self): """ The index of the local process used. """ requires_backends(self, ["torch"]) if is_torch_tpu_available(): return xm.get_local_ordinal() elif is_sagemaker_mp_enabled(): return smp.local_rank() elif is_sagemaker_dp_enabled(): return dist.get_rank() elif self.local_rank != -1: return self.local_rank return 0 @property def should_log(self): """ Whether or not the current process should produce log. """ if self.log_on_each_node: return self.local_process_index == 0 else: if is_sagemaker_mp_enabled(): return smp.rank() == 0 else: return self.process_index == 0 @property def should_save(self): """ Whether or not the current process should write to disk, e.g., to save models and checkpoints. """ if self.save_on_each_node: return self.local_process_index == 0 else: if is_sagemaker_mp_enabled(): return smp.rank() == 0 else: return self.process_index == 0 def get_process_log_level(self): """ Returns the log level to be used depending on whether this process is the main process of node 0, main process of node non-0, or a non-main process. For the main process the log level defaults to the logging level set (`logging.WARNING` if you didn't do anything) unless overridden by `log_level` argument. For the replica processes the log level defaults to `logging.WARNING` unless overridden by `log_level_replica` argument. The choice between the main and replica process settings is made according to the return value of `should_log`. """ # convert to int log_level = trainer_log_levels[self.log_level] log_level_replica = trainer_log_levels[self.log_level_replica] log_level_main_node = logging.get_verbosity() if log_level == -1 else log_level log_level_replica_node = logging.get_verbosity() if log_level_replica == -1 else log_level_replica return log_level_main_node if self.should_log else log_level_replica_node @property def place_model_on_device(self): """ Can be subclassed and overridden for some specific integrations. """ return not is_sagemaker_mp_enabled() @property def _no_sync_in_gradient_accumulation(self): """ Whether or not to use no_sync for the gradients when doing gradient accumulation. """ return not (self.deepspeed or is_sagemaker_dp_enabled() or is_sagemaker_mp_enabled()) @contextlib.contextmanager def main_process_first(self, local=True, desc="work"): """ A context manager for torch distributed environment where on needs to do something on the main process, while blocking replicas, and when it's finished releasing the replicas. One such use is for `datasets`'s `map` feature which to be efficient should be run once on the main process, which upon completion saves a cached version of results and which then automatically gets loaded by the replicas. Args: local (`bool`, *optional*, defaults to `True`): if `True` first means process of rank 0 of each node if `False` first means process of rank 0 of node rank 0 In multi-node environment with a shared filesystem you most likely will want to use `local=False` so that only the main process of the first node will do the processing. If however, the filesystem is not shared, then the main process of each node will need to do the processing, which is the default behavior. desc (`str`, *optional*, defaults to `"work"`): a work description to be used in debug logs """ if is_torch_available() and self.world_size > 1: main_process_desc = "main process" if local: is_main_process = self.local_process_index == 0 main_process_desc = "main local process" elif is_sagemaker_mp_enabled(): is_main_process = smp.rank() == 0 else: is_main_process = self.process_index == 0 try: if not is_main_process: # tell all replicas to wait logger.debug(f"{self.process_index}: waiting for the {main_process_desc} to perform {desc}") if is_torch_tpu_available(): xm.rendezvous(desc) elif is_sagemaker_dp_enabled(): dist.barrier() else: torch.distributed.barrier() yield finally: if is_main_process: # the wait is over logger.debug(f"{self.process_index}: {main_process_desc} completed {desc}, releasing all replicas") if is_torch_tpu_available(): xm.rendezvous(desc) elif is_sagemaker_dp_enabled(): dist.barrier() else: torch.distributed.barrier() else: yield def get_warmup_steps(self, num_training_steps: int): """ Get number of steps used for a linear warmup. """ warmup_steps = ( self.warmup_steps if self.warmup_steps > 0 else math.ceil(num_training_steps * self.warmup_ratio) ) return warmup_steps def to_dict(self): """ Serializes this instance while replace `Enum` by their values (for JSON serialization support). It obfuscates the token values by removing their value. """ # filter out fields that are defined as field(init=False) d = {field.name: getattr(self, field.name) for field in fields(self) if field.init} for k, v in d.items(): if isinstance(v, Enum): d[k] = v.value if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum): d[k] = [x.value for x in v] if k.endswith("_token"): d[k] = f"<{k.upper()}>" return d def to_json_string(self): """ Serializes this instance to a JSON string. """ return json.dumps(self.to_dict(), indent=2) def to_sanitized_dict(self) -> Dict[str, Any]: """ Sanitized serialization to use with TensorBoard’s hparams """ d = self.to_dict() d = {**d, **{"train_batch_size": self.train_batch_size, "eval_batch_size": self.eval_batch_size}} valid_types = [bool, int, float, str] if is_torch_available(): valid_types.append(torch.Tensor) return {k: v if type(v) in valid_types else str(v) for k, v in d.items()} class ParallelMode(Enum): NOT_PARALLEL = "not_parallel" NOT_DISTRIBUTED = "not_distributed" DISTRIBUTED = "distributed" SAGEMAKER_MODEL_PARALLEL = "sagemaker_model_parallel" SAGEMAKER_DATA_PARALLEL = "sagemaker_data_parallel" TPU = "tpu"
27182812/ChatGLM-LLaMA-chinese-insturct
11,214
src/transformers/pytorch_utils.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. import inspect from typing import Callable, List, Optional, Set, Tuple, Union import torch from packaging import version from torch import nn from .utils import logging ALL_LAYERNORM_LAYERS = [nn.LayerNorm] logger = logging.get_logger(__name__) parsed_torch_version_base = version.parse(version.parse(torch.__version__).base_version) is_torch_less_than_1_8 = parsed_torch_version_base < version.parse("1.8.0") is_torch_less_than_1_9 = parsed_torch_version_base < version.parse("1.9.0") is_torch_greater_or_equal_than_1_10 = parsed_torch_version_base >= version.parse("1.10") is_torch_less_than_1_11 = parsed_torch_version_base < version.parse("1.11") def torch_int_div(tensor1, tensor2): """ A function that performs integer division across different versions of PyTorch. """ if is_torch_less_than_1_8: return tensor1 // tensor2 else: return torch.div(tensor1, tensor2, rounding_mode="floor") def softmax_backward_data(parent, grad_output, output, dim, self): """ A function that calls the internal `_softmax_backward_data` PyTorch method and that adjusts the arguments according to the torch version detected. """ from torch import _softmax_backward_data if is_torch_less_than_1_11: return _softmax_backward_data(grad_output, output, parent.dim, self) else: return _softmax_backward_data(grad_output, output, parent.dim, self.dtype) def prune_linear_layer(layer: nn.Linear, index: torch.LongTensor, dim: int = 0) -> nn.Linear: """ Prune a linear layer to keep only entries in index. Used to remove heads. Args: layer (`torch.nn.Linear`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*, defaults to 0): The dimension on which to keep the indices. Returns: `torch.nn.Linear`: The pruned layer as a new layer with `requires_grad=True`. """ index = index.to(layer.weight.device) W = layer.weight.index_select(dim, index).clone().detach() if layer.bias is not None: if dim == 1: b = layer.bias.clone().detach() else: b = layer.bias[index].clone().detach() new_size = list(layer.weight.size()) new_size[dim] = len(index) new_layer = nn.Linear(new_size[1], new_size[0], bias=layer.bias is not None).to(layer.weight.device) new_layer.weight.requires_grad = False new_layer.weight.copy_(W.contiguous()) new_layer.weight.requires_grad = True if layer.bias is not None: new_layer.bias.requires_grad = False new_layer.bias.copy_(b.contiguous()) new_layer.bias.requires_grad = True return new_layer class Conv1D(nn.Module): """ 1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Args: nf (`int`): The number of output features. nx (`int`): The number of input features. """ def __init__(self, nf, nx): super().__init__() self.nf = nf self.weight = nn.Parameter(torch.empty(nx, nf)) self.bias = nn.Parameter(torch.zeros(nf)) nn.init.normal_(self.weight, std=0.02) def forward(self, x): size_out = x.size()[:-1] + (self.nf,) x = torch.addmm(self.bias, x.view(-1, x.size(-1)), self.weight) x = x.view(size_out) return x def prune_conv1d_layer(layer: Conv1D, index: torch.LongTensor, dim: int = 1) -> Conv1D: """ Prune a Conv1D layer to keep only entries in index. A Conv1D work as a Linear layer (see e.g. BERT) but the weights are transposed. Used to remove heads. Args: layer ([`~pytorch_utils.Conv1D`]): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*, defaults to 1): The dimension on which to keep the indices. Returns: [`~pytorch_utils.Conv1D`]: The pruned layer as a new layer with `requires_grad=True`. """ index = index.to(layer.weight.device) W = layer.weight.index_select(dim, index).clone().detach() if dim == 0: b = layer.bias.clone().detach() else: b = layer.bias[index].clone().detach() new_size = list(layer.weight.size()) new_size[dim] = len(index) new_layer = Conv1D(new_size[1], new_size[0]).to(layer.weight.device) new_layer.weight.requires_grad = False new_layer.weight.copy_(W.contiguous()) new_layer.weight.requires_grad = True new_layer.bias.requires_grad = False new_layer.bias.copy_(b.contiguous()) new_layer.bias.requires_grad = True return new_layer def prune_layer( layer: Union[nn.Linear, Conv1D], index: torch.LongTensor, dim: Optional[int] = None ) -> Union[nn.Linear, Conv1D]: """ Prune a Conv1D or linear layer to keep only entries in index. Used to remove heads. Args: layer (`Union[torch.nn.Linear, Conv1D]`): The layer to prune. index (`torch.LongTensor`): The indices to keep in the layer. dim (`int`, *optional*): The dimension on which to keep the indices. Returns: `torch.nn.Linear` or [`~pytorch_utils.Conv1D`]: The pruned layer as a new layer with `requires_grad=True`. """ if isinstance(layer, nn.Linear): return prune_linear_layer(layer, index, dim=0 if dim is None else dim) elif isinstance(layer, Conv1D): return prune_conv1d_layer(layer, index, dim=1 if dim is None else dim) else: raise ValueError(f"Can't prune layer of class {layer.__class__}") def apply_chunking_to_forward( forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors ) -> torch.Tensor: """ This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory. If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly applying `forward_fn` to `input_tensors`. Args: forward_fn (`Callable[..., torch.Tensor]`): The forward function of the model. chunk_size (`int`): The chunk size of a chunked tensor: `num_chunks = len(input_tensors[0]) / chunk_size`. chunk_dim (`int`): The dimension over which the `input_tensors` should be chunked. input_tensors (`Tuple[torch.Tensor]`): The input tensors of `forward_fn` which will be chunked Returns: `torch.Tensor`: A tensor with the same shape as the `forward_fn` would have given if applied`. Examples: ```python # rename the usual forward() fn to forward_chunk() def forward_chunk(self, hidden_states): hidden_states = self.decoder(hidden_states) return hidden_states # implement a chunked forward function def forward(self, hidden_states): return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states) ```""" assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors" # inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters) if num_args_in_forward_chunk_fn != len(input_tensors): raise ValueError( f"forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(input_tensors)} input " "tensors are given" ) if chunk_size > 0: tensor_shape = input_tensors[0].shape[chunk_dim] for input_tensor in input_tensors: if input_tensor.shape[chunk_dim] != tensor_shape: raise ValueError( f"All input tenors have to be of the same shape: {tensor_shape}, " f"found shape {input_tensor.shape[chunk_dim]}" ) if input_tensors[0].shape[chunk_dim] % chunk_size != 0: raise ValueError( f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk " f"size {chunk_size}" ) num_chunks = input_tensors[0].shape[chunk_dim] // chunk_size # chunk input tensor into tuples input_tensors_chunks = tuple(input_tensor.chunk(num_chunks, dim=chunk_dim) for input_tensor in input_tensors) # apply forward fn to every tuple output_chunks = tuple(forward_fn(*input_tensors_chunk) for input_tensors_chunk in zip(*input_tensors_chunks)) # concatenate output at same dimension return torch.cat(output_chunks, dim=chunk_dim) return forward_fn(*input_tensors) def find_pruneable_heads_and_indices( heads: List[int], n_heads: int, head_size: int, already_pruned_heads: Set[int] ) -> Tuple[Set[int], torch.LongTensor]: """ Finds the heads and their indices taking `already_pruned_heads` into account. Args: heads (`List[int]`): List of the indices of heads to prune. n_heads (`int`): The number of heads in the model. head_size (`int`): The size of each head. already_pruned_heads (`Set[int]`): A set of already pruned heads. Returns: `Tuple[Set[int], torch.LongTensor]`: A tuple with the remaining heads and their corresponding indices. """ mask = torch.ones(n_heads, head_size) heads = set(heads) - already_pruned_heads # Convert to set and remove already pruned heads for head in heads: # Compute how many pruned heads are before the head and move the index accordingly head = head - sum(1 if h < head else 0 for h in already_pruned_heads) mask[head] = 0 mask = mask.view(-1).contiguous().eq(1) index: torch.LongTensor = torch.arange(len(mask))[mask].long() return heads, index def meshgrid( *tensors: Union[torch.Tensor, List[torch.Tensor]], indexing: Optional[str] = None ) -> Tuple[torch.Tensor, ...]: """ Wrapper around torch.meshgrid to avoid warning messages about the introduced `indexing` argument. Reference: https://pytorch.org/docs/1.13/generated/torch.meshgrid.html """ if is_torch_greater_or_equal_than_1_10: return torch.meshgrid(*tensors, indexing=indexing) else: if indexing != "ij": raise ValueError('torch.meshgrid only supports `indexing="ij"` for torch<1.10.') return torch.meshgrid(*tensors)