diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..545fb400e12008a93b854ea0264c253578a9ba86 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,32 @@ +default_language_version: + python: python3 +exclude: 'dotnet' +ci: + autofix_prs: true + autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions' + autoupdate_schedule: 'quarterly' + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-ast + # - id: check-yaml + - id: check-toml + - id: check-json + - id: check-byte-order-marker + exclude: .gitignore + - id: check-merge-conflict + - id: detect-private-key + - id: trailing-whitespace + - id: end-of-file-fixer + - id: no-commit-to-branch + - repo: https://github.com/psf/black + rev: 23.3.0 + hooks: + - id: black + # - repo: https://github.com/charliermarsh/ruff-pre-commit + # rev: v0.0.261 + # hooks: + # - id: ruff + # args: ["--fix"] diff --git a/Dockerfile b/Dockerfile index f51befa12461627e9141c581262f842a19b0011d..97dba6f114fd0db32bc14d123e699e341ca9c02c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,7 +18,6 @@ WORKDIR /gpt # 安装大部分依赖,利用Docker缓存加速以后的构建 (以下三行,可以删除) COPY requirements.txt ./ -COPY ./docs/gradio-3.32.6-py3-none-any.whl ./docs/gradio-3.32.6-py3-none-any.whl RUN pip3 install -r requirements.txt diff --git a/README.md b/README.md index 922cb229eddf0c08116accd1194a606aa7919cae..49fa0683dd3d1ac2826be4c2d43a879a5aa705f1 100644 --- a/README.md +++ b/README.md @@ -54,13 +54,11 @@ If you like this project, please give it a Star. Read this in [English](docs/README.English.md) | [日本語](docs/README.Japanese.md) | [한국어](docs/README.Korean.md) | [Русский](docs/README.Russian.md) | [Français](docs/README.French.md). All translations have been provided by the project itself. To translate this project to arbitrary language with GPT, read and run [`multi_language.py`](multi_language.py) (experimental).
- -> 1.请注意只有 **高亮** 标识的插件(按钮)才支持读取文件,部分插件位于插件区的**下拉菜单**中。另外我们以**最高优先级**欢迎和处理任何新插件的PR。 -> -> 2.本项目中每个文件的功能都在[自译解报告](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告)`self_analysis.md`详细说明。随着版本的迭代,您也可以随时自行点击相关函数插件,调用GPT重新生成项目的自我解析报告。常见问题请查阅wiki。 +> [!NOTE] +> 1.本项目中每个文件的功能都在[自译解报告](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告)`self_analysis.md`详细说明。随着版本的迭代,您也可以随时自行点击相关函数插件,调用GPT重新生成项目的自我解析报告。常见问题请查阅wiki。 > [![常规安装方法](https://img.shields.io/static/v1?label=&message=常规安装方法&color=gray)](#installation) [![一键安装脚本](https://img.shields.io/static/v1?label=&message=一键安装脚本&color=gray)](https://github.com/binary-husky/gpt_academic/releases) [![配置说明](https://img.shields.io/static/v1?label=&message=配置说明&color=gray)](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明) [![wiki](https://img.shields.io/static/v1?label=&message=wiki&color=gray)]([https://github.com/binary-husky/gpt_academic/wiki/项目配置说明](https://github.com/binary-husky/gpt_academic/wiki)) -> -> 3.本项目兼容并鼓励尝试国产大语言模型ChatGLM等。支持多个api-key共存,可在配置文件中填写如`API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`。需要临时更换`API_KEY`时,在输入区输入临时的`API_KEY`然后回车键提交即可生效。 +> +> 2.本项目兼容并鼓励尝试国内中文大语言基座模型如通义千问,智谱GLM等。支持多个api-key共存,可在配置文件中填写如`API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`。需要临时更换`API_KEY`时,在输入区输入临时的`API_KEY`然后回车键提交即可生效。

@@ -68,7 +66,12 @@ Read this in [English](docs/README.English.md) | [日本語](docs/README.Japanes 功能(⭐= 近期新增功能) | 描述 --- | --- -⭐[接入新模型](https://github.com/binary-husky/gpt_academic/wiki/%E5%A6%82%E4%BD%95%E5%88%87%E6%8D%A2%E6%A8%A1%E5%9E%8B) | 百度[千帆](https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu)与文心一言, 通义千问[Qwen](https://modelscope.cn/models/qwen/Qwen-7B-Chat/summary),上海AI-Lab[书生](https://github.com/InternLM/InternLM),讯飞[星火](https://xinghuo.xfyun.cn/),[LLaMa2](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf),[智谱API](https://open.bigmodel.cn/),DALLE3, [DeepseekCoder](https://coder.deepseek.com/) +⭐[接入新模型](https://github.com/binary-husky/gpt_academic/wiki/%E5%A6%82%E4%BD%95%E5%88%87%E6%8D%A2%E6%A8%A1%E5%9E%8B) | 百度[千帆](https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Nlks5zkzu)与文心一言, 通义千问[Qwen](https://modelscope.cn/models/qwen/Qwen-7B-Chat/summary),上海AI-Lab[书生](https://github.com/InternLM/InternLM),讯飞[星火](https://xinghuo.xfyun.cn/),[LLaMa2](https://huggingface.co/meta-llama/Llama-2-7b-chat-hf),[智谱GLM4](https://open.bigmodel.cn/),DALLE3, [DeepseekCoder](https://coder.deepseek.com/) +⭐支持mermaid图像渲染 | 支持让GPT生成[流程图](https://www.bilibili.com/video/BV18c41147H9/)、状态转移图、甘特图、饼状图、GitGraph等等(3.7版本) +⭐Arxiv论文精细翻译 ([Docker](https://github.com/binary-husky/gpt_academic/pkgs/container/gpt_academic_with_latex)) | [插件] 一键[以超高质量翻译arxiv论文](https://www.bilibili.com/video/BV1dz4y1v77A/),目前最好的论文翻译工具 +⭐[实时语音对话输入](https://github.com/binary-husky/gpt_academic/blob/master/docs/use_audio.md) | [插件] 异步[监听音频](https://www.bilibili.com/video/BV1AV4y187Uy/),自动断句,自动寻找回答时机 +⭐AutoGen多智能体插件 | [插件] 借助微软AutoGen,探索多Agent的智能涌现可能! +⭐虚空终端插件 | [插件] 能够使用自然语言直接调度本项目其他插件 润色、翻译、代码解释 | 一键润色、翻译、查找论文语法错误、解释代码 [自定义快捷键](https://www.bilibili.com/video/BV14s4y1E7jN) | 支持自定义快捷键 模块化设计 | 支持自定义强大的[插件](https://github.com/binary-husky/gpt_academic/tree/master/crazy_functions),插件支持[热更新](https://github.com/binary-husky/gpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97) @@ -77,22 +80,16 @@ Read this in [English](docs/README.English.md) | [日本語](docs/README.Japanes Latex全文[翻译](https://www.bilibili.com/video/BV1nk4y1Y7Js/)、[润色](https://www.bilibili.com/video/BV1FT411H7c5/) | [插件] 一键翻译或润色latex论文 批量注释生成 | [插件] 一键批量生成函数注释 Markdown[中英互译](https://www.bilibili.com/video/BV1yo4y157jV/) | [插件] 看到上面5种语言的[README](https://github.com/binary-husky/gpt_academic/blob/master/docs/README_EN.md)了吗?就是出自他的手笔 -chat分析报告生成 | [插件] 运行后自动生成总结汇报 [PDF论文全文翻译功能](https://www.bilibili.com/video/BV1KT411x7Wn) | [插件] PDF论文提取题目&摘要+翻译全文(多线程) [Arxiv小助手](https://www.bilibili.com/video/BV1LM4y1279X) | [插件] 输入arxiv文章url即可一键翻译摘要+下载PDF Latex论文一键校对 | [插件] 仿Grammarly对Latex文章进行语法、拼写纠错+输出对照PDF [谷歌学术统合小助手](https://www.bilibili.com/video/BV19L411U7ia) | [插件] 给定任意谷歌学术搜索页面URL,让gpt帮你[写relatedworks](https://www.bilibili.com/video/BV1GP411U7Az/) 互联网信息聚合+GPT | [插件] 一键[让GPT从互联网获取信息](https://www.bilibili.com/video/BV1om4y127ck)回答问题,让信息永不过时 -⭐Arxiv论文精细翻译 ([Docker](https://github.com/binary-husky/gpt_academic/pkgs/container/gpt_academic_with_latex)) | [插件] 一键[以超高质量翻译arxiv论文](https://www.bilibili.com/video/BV1dz4y1v77A/),目前最好的论文翻译工具 -⭐[实时语音对话输入](https://github.com/binary-husky/gpt_academic/blob/master/docs/use_audio.md) | [插件] 异步[监听音频](https://www.bilibili.com/video/BV1AV4y187Uy/),自动断句,自动寻找回答时机 公式/图片/表格显示 | 可以同时显示公式的[tex形式和渲染形式](https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png),支持公式、代码高亮 -⭐AutoGen多智能体插件 | [插件] 借助微软AutoGen,探索多Agent的智能涌现可能! 启动暗色[主题](https://github.com/binary-husky/gpt_academic/issues/173) | 在浏览器url后面添加```/?__theme=dark```可以切换dark主题 [多LLM模型](https://www.bilibili.com/video/BV1wT411p7yf)支持 | 同时被GPT3.5、GPT4、[清华ChatGLM2](https://github.com/THUDM/ChatGLM2-6B)、[复旦MOSS](https://github.com/OpenLMLab/MOSS)伺候的感觉一定会很不错吧? -⭐ChatGLM2微调模型 | 支持加载ChatGLM2微调模型,提供ChatGLM2微调辅助插件 更多LLM模型接入,支持[huggingface部署](https://huggingface.co/spaces/qingxu98/gpt-academic) | 加入Newbing接口(新必应),引入清华[Jittorllms](https://github.com/Jittor/JittorLLMs)支持[LLaMA](https://github.com/facebookresearch/llama)和[盘古α](https://openi.org.cn/pangu/) ⭐[void-terminal](https://github.com/binary-husky/void-terminal) pip包 | 脱离GUI,在Python中直接调用本项目的所有函数插件(开发中) -⭐虚空终端插件 | [插件] 能够使用自然语言直接调度本项目其他插件 更多新功能展示 (图像生成等) …… | 见本文档结尾处 …… @@ -131,7 +128,26 @@ Latex论文一键校对 | [插件] 仿Grammarly对Latex文章进行语法、拼

# Installation -### 安装方法I:直接运行 (Windows, Linux or MacOS) + +```mermaid +flowchart TD + A{"安装方法"} --> W1("I. 🔑直接运行 (Windows, Linux or MacOS)") + W1 --> W11["1. Python pip包管理依赖"] + W1 --> W12["2. Anaconda包管理依赖(推荐⭐)"] + + A --> W2["II. 🐳使用Docker (Windows, Linux or MacOS)"] + + W2 --> k1["1. 部署项目全部能力的大镜像(推荐⭐)"] + W2 --> k2["2. 仅在线模型(GPT, GLM4等)镜像"] + W2 --> k3["3. 在线模型 + Latex的大镜像"] + + A --> W4["IV. 🚀其他部署方法"] + W4 --> C1["1. Windows/MacOS 一键安装运行脚本(推荐⭐)"] + W4 --> C2["2. Huggingface, Sealos远程部署"] + W4 --> C4["3. ... 其他 ..."] +``` + +### 安装方法I:直接运行 (Windows, Linux or MacOS) 1. 下载项目 @@ -144,7 +160,7 @@ Latex论文一键校对 | [插件] 仿Grammarly对Latex文章进行语法、拼 在`config.py`中,配置API KEY等变量。[特殊网络环境设置方法](https://github.com/binary-husky/gpt_academic/issues/1)、[Wiki-项目配置说明](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明)。 - 「 程序会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。如您能理解以上读取逻辑,我们强烈建议您在`config.py`同路径下创建一个名为`config_private.py`的新配置文件,并使用`config_private.py`配置项目,以确保更新或其他用户无法轻易查看您的私有配置 」。 + 「 程序会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。如您能理解以上读取逻辑,我们强烈建议您在`config.py`同路径下创建一个名为`config_private.py`的新配置文件,并使用`config_private.py`配置项目,从而确保自动更新时不会丢失配置 」。 「 支持通过`环境变量`配置项目,环境变量的书写格式参考`docker-compose.yml`文件或者我们的[Wiki页面](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明)。配置读取优先级: `环境变量` > `config_private.py` > `config.py` 」。 @@ -164,11 +180,11 @@ Latex论文一键校对 | [插件] 仿Grammarly对Latex文章进行语法、拼
如果需要支持清华ChatGLM2/复旦MOSS/RWKV作为后端,请点击展开此处

-【可选步骤】如果需要支持清华ChatGLM2/复旦MOSS作为后端,需要额外安装更多依赖(前提条件:熟悉Python + 用过Pytorch + 电脑配置够强): +【可选步骤】如果需要支持清华ChatGLM3/复旦MOSS作为后端,需要额外安装更多依赖(前提条件:熟悉Python + 用过Pytorch + 电脑配置够强): ```sh -# 【可选步骤I】支持清华ChatGLM2。清华ChatGLM备注:如果遇到"Call ChatGLM fail 不能正常加载ChatGLM的参数" 错误,参考如下: 1:以上默认安装的为torch+cpu版,使用cuda需要卸载torch重新安装torch+cuda; 2:如因本机配置不够无法加载模型,可以修改request_llm/bridge_chatglm.py中的模型精度, 将 AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 都修改为 AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llms/requirements_chatglm.txt +# 【可选步骤I】支持清华ChatGLM3。清华ChatGLM备注:如果遇到"Call ChatGLM fail 不能正常加载ChatGLM的参数" 错误,参考如下: 1:以上默认安装的为torch+cpu版,使用cuda需要卸载torch重新安装torch+cuda; 2:如因本机配置不够无法加载模型,可以修改request_llm/bridge_chatglm.py中的模型精度, 将 AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) 都修改为 AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) +python -m pip install -r request_llms/requirements_chatglm.txt # 【可选步骤II】支持复旦MOSS python -m pip install -r request_llms/requirements_moss.txt @@ -209,7 +225,7 @@ pip install peft docker-compose up ``` -1. 仅ChatGPT+文心一言+spark等在线模型(推荐大多数人选择) +1. 仅ChatGPT + GLM4 + 文心一言+spark等在线模型(推荐大多数人选择) [![basic](https://github.com/binary-husky/gpt_academic/actions/workflows/build-without-local-llms.yml/badge.svg?branch=master)](https://github.com/binary-husky/gpt_academic/actions/workflows/build-without-local-llms.yml) [![basiclatex](https://github.com/binary-husky/gpt_academic/actions/workflows/build-with-latex.yml/badge.svg?branch=master)](https://github.com/binary-husky/gpt_academic/actions/workflows/build-with-latex.yml) [![basicaudio](https://github.com/binary-husky/gpt_academic/actions/workflows/build-with-audio-assistant.yml/badge.svg?branch=master)](https://github.com/binary-husky/gpt_academic/actions/workflows/build-with-audio-assistant.yml) @@ -221,7 +237,7 @@ pip install peft P.S. 如果需要依赖Latex的插件功能,请见Wiki。另外,您也可以直接使用方案4或者方案0获取Latex功能。 -2. ChatGPT + ChatGLM2 + MOSS + LLAMA2 + 通义千问(需要熟悉[Nvidia Docker](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#installing-on-ubuntu-and-debian)运行时) +2. ChatGPT + GLM3 + MOSS + LLAMA2 + 通义千问(需要熟悉[Nvidia Docker](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#installing-on-ubuntu-and-debian)运行时) [![chatglm](https://github.com/binary-husky/gpt_academic/actions/workflows/build-with-chatglm.yml/badge.svg?branch=master)](https://github.com/binary-husky/gpt_academic/actions/workflows/build-with-chatglm.yml) ``` sh @@ -255,8 +271,8 @@ P.S. 如果需要依赖Latex的插件功能,请见Wiki。另外,您也可以 ```python "超级英译中": { # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等 - "Prefix": "请翻译把下面一段内容成中文,然后用一个markdown表格逐一解释文中出现的专有名词:\n\n", - + "Prefix": "请翻译把下面一段内容成中文,然后用一个markdown表格逐一解释文中出现的专有名词:\n\n", + # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。 "Suffix": "", }, @@ -320,9 +336,9 @@ Tip:不指定文件直接点击 `载入对话历史存档` 可以查看历史h -8. OpenAI音频解析与总结 +8. 基于mermaid的流图、脑图绘制

- +
9. Latex全文校对纠错 @@ -339,8 +355,8 @@ Tip:不指定文件直接点击 `载入对话历史存档` 可以查看历史h ### II:版本: - -- version 3.70(todo): 优化AutoGen插件主题并设计一系列衍生插件 +- version 3.80(TODO): 优化AutoGen插件主题并设计一系列衍生插件 +- version 3.70: 引入Mermaid绘图,实现GPT画脑图等功能 - version 3.60: 引入AutoGen作为新一代插件的基石 - version 3.57: 支持GLM3,星火v3,文心一言v4,修复本地模型的并发BUG - version 3.56: 支持动态追加基础功能按钮,新汇报PDF汇总页面 @@ -373,6 +389,32 @@ GPT Academic开发者QQ群:`610599535` - 某些浏览器翻译插件干扰此软件前端的运行 - 官方Gradio目前有很多兼容性问题,请**务必使用`requirement.txt`安装Gradio** +```mermaid +timeline LR + title GPT-Academic项目发展历程 + section 2.x + 1.0~2.2: 基础功能: 引入模块化函数插件: 可折叠式布局: 函数插件支持热重载 + 2.3~2.5: 增强多线程交互性: 新增PDF全文翻译功能: 新增输入区切换位置的功能: 自更新 + 2.6: 重构了插件结构: 提高了交互性: 加入更多插件 + section 3.x + 3.0~3.1: 对chatglm支持: 对其他小型llm支持: 支持同时问询多个gpt模型: 支持多个apikey负载均衡 + 3.2~3.3: 函数插件支持更多参数接口: 保存对话功能: 解读任意语言代码: 同时询问任意的LLM组合: 互联网信息综合功能 + 3.4: 加入arxiv论文翻译: 加入latex论文批改功能 + 3.44: 正式支持Azure: 优化界面易用性 + 3.46: 自定义ChatGLM2微调模型: 实时语音对话 + 3.49: 支持阿里达摩院通义千问: 上海AI-Lab书生: 讯飞星火: 支持百度千帆平台 & 文心一言 + 3.50: 虚空终端: 支持插件分类: 改进UI: 设计新主题 + 3.53: 动态选择不同界面主题: 提高稳定性: 解决多用户冲突问题 + 3.55: 动态代码解释器: 重构前端界面: 引入悬浮窗口与菜单栏 + 3.56: 动态追加基础功能按钮: 新汇报PDF汇总页面 + 3.57: GLM3, 星火v3: 支持文心一言v4: 修复本地模型的并发BUG + 3.60: 引入AutoGen + 3.70: 引入Mermaid绘图: 实现GPT画脑图等功能 + 3.80(TODO): 优化AutoGen插件主题: 设计衍生插件 + +``` + + ### III:主题 可以通过修改`THEME`选项(config.py)变更主题 1. `Chuanhu-Small-and-Beautiful` [网址](https://github.com/GaiZhenbiao/ChuanhuChatGPT/) diff --git a/app.py b/app.py index 4a15e07e6578f78f3c067cc02b3fadae61518d0a..e0b461b5ee34ef57fad93fc7014febfada2cd09f 100644 --- a/app.py +++ b/app.py @@ -15,9 +15,9 @@ help_menu_description = \ def main(): import subprocess, sys - subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'https://github.com/binary-husky/gpt_academic/raw/master/docs/gradio-3.32.6-py3-none-any.whl']) + subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'https://fastly.jsdelivr.net/gh/binary-husky/gradio-fix@gpt-academic/release/gradio-3.32.7-py3-none-any.whl']) import gradio as gr - if gr.__version__ not in ['3.32.6']: + if gr.__version__ not in ['3.32.6', '3.32.7']: raise ModuleNotFoundError("使用项目内置Gradio获取最优体验! 请运行 `pip install -r requirements.txt` 指令安装内置Gradio及其他依赖, 详情信息见requirements.txt.") from request_llms.bridge_all import predict from toolbox import format_io, find_free_port, on_file_uploaded, on_report_generated, get_conf, ArgsGeneralWrapper, load_chat_cookies, DummyWith @@ -142,17 +142,17 @@ def main(): with gr.Row(): switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary").style(size="sm") with gr.Row(): - with gr.Accordion("点击展开“文件上传区”。上传本地文件/压缩包供函数插件调用。", open=False) as area_file_up: + with gr.Accordion("点击展开“文件下载区”。", open=False) as area_file_up: file_upload = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple", elem_id="elem_upload") - with gr.Floating(init_x="0%", init_y="0%", visible=True, width=None, drag="forbidden"): + with gr.Floating(init_x="0%", init_y="0%", visible=True, width=None, drag="forbidden", elem_id="tooltip"): with gr.Row(): with gr.Tab("上传文件", elem_id="interact-panel"): gr.Markdown("请上传本地文件/压缩包供“函数插件区”功能调用。请注意: 上传文件后会自动把输入区修改为相应路径。") file_upload_2 = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple", elem_id="elem_upload_float") - with gr.Tab("更换模型 & Prompt", elem_id="interact-panel"): + with gr.Tab("更换模型", elem_id="interact-panel"): md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False) top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",) temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",) @@ -164,10 +164,9 @@ def main(): checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "浮动输入区", "输入清除键", "插件参数区"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区", elem_id='cbs').style(container=False) checkboxes_2 = gr.CheckboxGroup(["自定义菜单"], - value=[], label="显示/隐藏自定义菜单", elem_id='cbs').style(container=False) + value=[], label="显示/隐藏自定义菜单", elem_id='cbsc').style(container=False) dark_mode_btn = gr.Button("切换界面明暗 ☀", variant="secondary").style(size="sm") - dark_mode_btn.click(None, None, None, _js=js_code_for_toggle_darkmode, - ) + dark_mode_btn.click(None, None, None, _js=js_code_for_toggle_darkmode) with gr.Tab("帮助", elem_id="interact-panel"): gr.Markdown(help_menu_description) diff --git a/config.py b/config.py index 6560d3e01546d5dbebe1841b8c83e7dcbc75a4ff..c9d3ec5d0bf66f9d6e9f5984f19f17a72f75a8ef 100644 --- a/config.py +++ b/config.py @@ -96,12 +96,14 @@ DEFAULT_FN_GROUPS = ['对话', '编程', '学术', '智能体'] LLM_MODEL = "gpt-3.5-turbo" # 可选 ↓↓↓ AVAIL_LLM_MODELS = ["gpt-3.5-turbo-1106","gpt-4-1106-preview","gpt-4-vision-preview", "gpt-3.5-turbo-16k", "gpt-3.5-turbo", "azure-gpt-3.5", - "api2d-gpt-3.5-turbo", 'api2d-gpt-3.5-turbo-16k', "gpt-4", "gpt-4-32k", "azure-gpt-4", "api2d-gpt-4", - "chatglm3", "moss", "claude-2"] -# P.S. 其他可用的模型还包括 ["zhipuai", "qianfan", "deepseekcoder", "llama2", "qwen-local", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-16k-0613", "gpt-3.5-random" + "gemini-pro", "chatglm3", "claude-2", "zhipuai"] +# P.S. 其他可用的模型还包括 [ +# "moss", "qwen-turbo", "qwen-plus", "qwen-max" +# "zhipuai", "qianfan", "deepseekcoder", "llama2", "qwen-local", "gpt-3.5-turbo-0613", +# "gpt-3.5-turbo-16k-0613", "gpt-3.5-random", "api2d-gpt-3.5-turbo", 'api2d-gpt-3.5-turbo-16k', # "spark", "sparkv2", "sparkv3", "chatglm_onnx", "claude-1-100k", "claude-2", "internlm", "jittorllms_pangualpha", "jittorllms_llama" -# “qwen-turbo", "qwen-plus", "qwen-max"] +# ] # 定义界面上“询问多个GPT模型”插件应该使用哪些模型,请从AVAIL_LLM_MODELS中选择,并在不同模型之间用`&`间隔,例如"gpt-3.5-turbo&chatglm3&azure-gpt-4" @@ -200,7 +202,13 @@ XFYUN_API_KEY = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # 接入智谱大模型 ZHIPUAI_API_KEY = "" -ZHIPUAI_MODEL = "chatglm_turbo" +ZHIPUAI_MODEL = "glm-4" # 可选 "glm-3-turbo" "glm-4" + + +# # 火山引擎YUNQUE大模型 +# YUNQUE_SECRET_KEY = "" +# YUNQUE_ACCESS_KEY = "" +# YUNQUE_MODEL = "" # Claude API KEY @@ -211,6 +219,10 @@ ANTHROPIC_API_KEY = "" CUSTOM_API_KEY_PATTERN = "" +# Google Gemini API-Key +GEMINI_API_KEY = '' + + # HUGGINGFACE的TOKEN,下载LLAMA时起作用 https://huggingface.co/docs/hub/security-tokens HUGGINGFACE_ACCESS_TOKEN = "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" @@ -299,6 +311,9 @@ NUM_CUSTOM_BASIC_BTN = 4 ├── "qwen-turbo" 等通义千问大模型 │ └── DASHSCOPE_API_KEY │ +├── "Gemini" +│ └── GEMINI_API_KEY +│ └── "newbing" Newbing接口不再稳定,不推荐使用 ├── NEWBING_STYLE └── NEWBING_COOKIES diff --git a/core_functional.py b/core_functional.py index e19e82e7a5059a8a019156de3ce4dfb90ab088d8..0b283a8970f5e35627f68889a381653f796ff26f 100644 --- a/core_functional.py +++ b/core_functional.py @@ -3,30 +3,58 @@ # 'stop' 颜色对应 theme.py 中的 color_er import importlib from toolbox import clear_line_break - +from textwrap import dedent def get_core_functions(): return { + "英语学术润色": { - # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等 - "Prefix": r"Below is a paragraph from an academic paper. Polish the writing to meet the academic style, " + - r"improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. " + + # [1*] 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等 + "Prefix": r"Below is a paragraph from an academic paper. Polish the writing to meet the academic style, " + r"improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. " r"Firstly, you should provide the polished paragraph. " r"Secondly, you should list all your modification and explain the reasons to do so in markdown table." + "\n\n", - # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来 + # [2*] 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来 "Suffix": r"", - # 按钮颜色 (默认 secondary) + # [3] 按钮颜色 (可选参数,默认 secondary) "Color": r"secondary", - # 按钮是否可见 (默认 True,即可见) + # [4] 按钮是否可见 (可选参数,默认 True,即可见) "Visible": True, - # 是否在触发时清除历史 (默认 False,即不处理之前的对话历史) - "AutoClearHistory": False + # [5] 是否在触发时清除历史 (可选参数,默认 False,即不处理之前的对话历史) + "AutoClearHistory": False, + # [6] 文本预处理 (可选参数,默认 None,举例:写个函数移除所有的换行符) + "PreProcess": None, }, - "中文学术润色": { - "Prefix": r"作为一名中文学术论文写作改进助理,你的任务是改进所提供文本的拼写、语法、清晰、简洁和整体可读性," + - r"同时分解长句,减少重复,并提供改进建议。请只提供文本的更正版本,避免包括解释。请编辑以下文本" + "\n\n", - "Suffix": r"", + + + "总结绘制脑图": { + # 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等 + "Prefix": r"", + # 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来 + "Suffix": + dedent("\n"+r''' + ============================== + 使用mermaid flowchart对以上文本进行总结,概括上述段落的内容以及内在逻辑关系,例如: + + 以下是对以上文本的总结,以mermaid flowchart的形式展示: + ```mermaid + flowchart LR + A["节点名1"] --> B("节点名2") + B --> C{"节点名3"} + C --> D["节点名4"] + C --> |"箭头名1"| E["节点名5"] + C --> |"箭头名2"| F["节点名6"] + ``` + + 警告: + (1)使用中文 + (2)节点名字使用引号包裹,如["Laptop"] + (3)`|` 和 `"`之间不要存在空格 + (4)根据情况选择flowchart LR(从左到右)或者flowchart TD(从上到下) + '''), }, + + "查找语法错误": { "Prefix": r"Help me ensure that the grammar and the spelling is correct. " r"Do not try to polish the text, if no mistake is found, tell me that this paragraph is good. " @@ -46,11 +74,15 @@ def get_core_functions(): "Suffix": r"", "PreProcess": clear_line_break, # 预处理:清除换行符 }, + + "中译英": { "Prefix": r"Please translate following sentence to English:" + "\n\n", "Suffix": r"", }, - "学术中英互译": { + + + "学术英中互译": { "Prefix": r"I want you to act as a scientific English-Chinese translator, " + r"I will provide you with some paragraphs in one language " + r"and your task is to accurately and academically translate the paragraphs only into the other language. " + @@ -59,29 +91,36 @@ def get_core_functions(): r"such as natural language processing, and rhetorical knowledge " + r"and experience about effective writing techniques to reply. " + r"I'll give you my paragraphs as follows, tell me what language it is written in, and then translate:" + "\n\n", - "Suffix": "", - "Color": "secondary", + "Suffix": r"", }, + + "英译中": { "Prefix": r"翻译成地道的中文:" + "\n\n", "Suffix": r"", - "Visible": False, + "Visible": False, }, + + "找图片": { - "Prefix": r"我需要你找一张网络图片。使用Unsplash API(https://source.unsplash.com/960x640/?<英语关键词>)获取图片URL," + + "Prefix": r"我需要你找一张网络图片。使用Unsplash API(https://source.unsplash.com/960x640/?<英语关键词>)获取图片URL," r"然后请使用Markdown格式封装,并且不要有反斜线,不要用代码块。现在,请按以下描述给我发送图片:" + "\n\n", "Suffix": r"", - "Visible": False, + "Visible": False, }, + + "解释代码": { "Prefix": r"请解释以下代码:" + "\n```\n", "Suffix": "\n```\n", }, + + "参考文献转Bib": { - "Prefix": r"Here are some bibliography items, please transform them into bibtex style." + - r"Note that, reference styles maybe more than one kind, you should transform each item correctly." + - r"Items need to be transformed:", - "Visible": False, + "Prefix": r"Here are some bibliography items, please transform them into bibtex style." + r"Note that, reference styles maybe more than one kind, you should transform each item correctly." + r"Items need to be transformed:" + "\n\n", + "Visible": False, "Suffix": r"", } } @@ -98,8 +137,14 @@ def handle_core_functionality(additional_fn, inputs, history, chatbot): return inputs, history else: # 预制功能 - if "PreProcess" in core_functional[additional_fn]: inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话) + if "PreProcess" in core_functional[additional_fn]: + if core_functional[additional_fn]["PreProcess"] is not None: + inputs = core_functional[additional_fn]["PreProcess"](inputs) # 获取预处理函数(如果有的话) inputs = core_functional[additional_fn]["Prefix"] + inputs + core_functional[additional_fn]["Suffix"] if core_functional[additional_fn].get("AutoClearHistory", False): history = [] return inputs, history + +if __name__ == "__main__": + t = get_core_functions()["总结绘制脑图"] + print(t["Prefix"] + t["Suffix"]) \ No newline at end of file diff --git a/crazy_functional.py b/crazy_functional.py index c323dc3204ae709def53e9c9fcfa53893ee98142..45400731c519d5f82570fd2449c20961cc20d2d3 100644 --- a/crazy_functional.py +++ b/crazy_functional.py @@ -37,110 +37,109 @@ def get_crazy_functions(): from crazy_functions.批量Markdown翻译 import Markdown中译英 from crazy_functions.虚空终端 import 虚空终端 - function_plugins = { "虚空终端": { "Group": "对话|编程|学术|智能体", "Color": "stop", "AsButton": True, - "Function": HotReload(虚空终端) + "Function": HotReload(虚空终端), }, "解析整个Python项目": { "Group": "编程", "Color": "stop", "AsButton": True, "Info": "解析一个Python项目的所有源文件(.py) | 输入参数为路径", - "Function": HotReload(解析一个Python项目) + "Function": HotReload(解析一个Python项目), }, "载入对话历史存档(先上传存档或输入路径)": { "Group": "对话", "Color": "stop", "AsButton": False, "Info": "载入对话历史存档 | 输入参数为路径", - "Function": HotReload(载入对话历史存档) + "Function": HotReload(载入对话历史存档), }, "删除所有本地对话历史记录(谨慎操作)": { "Group": "对话", "AsButton": False, "Info": "删除所有本地对话历史记录,谨慎操作 | 不需要输入参数", - "Function": HotReload(删除所有本地对话历史记录) + "Function": HotReload(删除所有本地对话历史记录), }, "清除所有缓存文件(谨慎操作)": { "Group": "对话", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "清除所有缓存文件,谨慎操作 | 不需要输入参数", - "Function": HotReload(清除缓存) + "Function": HotReload(清除缓存), }, "批量总结Word文档": { "Group": "学术", "Color": "stop", "AsButton": True, "Info": "批量总结word文档 | 输入参数为路径", - "Function": HotReload(总结word文档) + "Function": HotReload(总结word文档), }, "解析整个Matlab项目": { "Group": "编程", "Color": "stop", "AsButton": False, "Info": "解析一个Matlab项目的所有源文件(.m) | 输入参数为路径", - "Function": HotReload(解析一个Matlab项目) + "Function": HotReload(解析一个Matlab项目), }, "解析整个C++项目头文件": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个C++项目的所有头文件(.h/.hpp) | 输入参数为路径", - "Function": HotReload(解析一个C项目的头文件) + "Function": HotReload(解析一个C项目的头文件), }, "解析整个C++项目(.cpp/.hpp/.c/.h)": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个C++项目的所有源文件(.cpp/.hpp/.c/.h)| 输入参数为路径", - "Function": HotReload(解析一个C项目) + "Function": HotReload(解析一个C项目), }, "解析整个Go项目": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个Go项目的所有源文件 | 输入参数为路径", - "Function": HotReload(解析一个Golang项目) + "Function": HotReload(解析一个Golang项目), }, "解析整个Rust项目": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个Rust项目的所有源文件 | 输入参数为路径", - "Function": HotReload(解析一个Rust项目) + "Function": HotReload(解析一个Rust项目), }, "解析整个Java项目": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个Java项目的所有源文件 | 输入参数为路径", - "Function": HotReload(解析一个Java项目) + "Function": HotReload(解析一个Java项目), }, "解析整个前端项目(js,ts,css等)": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个前端项目的所有源文件(js,ts,css等) | 输入参数为路径", - "Function": HotReload(解析一个前端项目) + "Function": HotReload(解析一个前端项目), }, "解析整个Lua项目": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个Lua项目的所有源文件 | 输入参数为路径", - "Function": HotReload(解析一个Lua项目) + "Function": HotReload(解析一个Lua项目), }, "解析整个CSharp项目": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "解析一个CSharp项目的所有源文件 | 输入参数为路径", - "Function": HotReload(解析一个CSharp项目) + "Function": HotReload(解析一个CSharp项目), }, "解析Jupyter Notebook文件": { "Group": "编程", @@ -156,103 +155,102 @@ def get_crazy_functions(): "Color": "stop", "AsButton": False, "Info": "读取Tex论文并写摘要 | 输入参数为路径", - "Function": HotReload(读文章写摘要) + "Function": HotReload(读文章写摘要), }, "翻译README或MD": { "Group": "编程", "Color": "stop", "AsButton": True, "Info": "将Markdown翻译为中文 | 输入参数为路径或URL", - "Function": HotReload(Markdown英译中) + "Function": HotReload(Markdown英译中), }, "翻译Markdown或README(支持Github链接)": { "Group": "编程", "Color": "stop", "AsButton": False, "Info": "将Markdown或README翻译为中文 | 输入参数为路径或URL", - "Function": HotReload(Markdown英译中) + "Function": HotReload(Markdown英译中), }, "批量生成函数注释": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "批量生成函数的注释 | 输入参数为路径", - "Function": HotReload(批量生成函数注释) + "Function": HotReload(批量生成函数注释), }, "保存当前的对话": { "Group": "对话", "AsButton": True, "Info": "保存当前的对话 | 不需要输入参数", - "Function": HotReload(对话历史存档) + "Function": HotReload(对话历史存档), }, "[多线程Demo]解析此项目本身(源码自译解)": { "Group": "对话|编程", "AsButton": False, # 加入下拉菜单中 "Info": "多线程解析并翻译此项目的源码 | 不需要输入参数", - "Function": HotReload(解析项目本身) + "Function": HotReload(解析项目本身), }, "历史上的今天": { "Group": "对话", "AsButton": True, "Info": "查看历史上的今天事件 (这是一个面向开发者的插件Demo) | 不需要输入参数", - "Function": HotReload(高阶功能模板函数) + "Function": HotReload(高阶功能模板函数), }, "精准翻译PDF论文": { "Group": "学术", "Color": "stop", - "AsButton": True, + "AsButton": True, "Info": "精准翻译PDF论文为中文 | 输入参数为路径", - "Function": HotReload(批量翻译PDF文档) + "Function": HotReload(批量翻译PDF文档), }, "询问多个GPT模型": { "Group": "对话", "Color": "stop", "AsButton": True, - "Function": HotReload(同时问询) + "Function": HotReload(同时问询), }, "批量总结PDF文档": { "Group": "学术", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "批量总结PDF文档的内容 | 输入参数为路径", - "Function": HotReload(批量总结PDF文档) + "Function": HotReload(批量总结PDF文档), }, "谷歌学术检索助手(输入谷歌学术搜索页url)": { "Group": "学术", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "使用谷歌学术检索助手搜索指定URL的结果 | 输入参数为谷歌学术搜索页的URL", - "Function": HotReload(谷歌检索小助手) + "Function": HotReload(谷歌检索小助手), }, "理解PDF文档内容 (模仿ChatPDF)": { "Group": "学术", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "理解PDF文档的内容并进行回答 | 输入参数为路径", - "Function": HotReload(理解PDF文档内容标准文件输入) + "Function": HotReload(理解PDF文档内容标准文件输入), }, "英文Latex项目全文润色(输入路径或上传压缩包)": { "Group": "学术", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "对英文Latex项目全文进行润色处理 | 输入参数为路径或上传压缩包", - "Function": HotReload(Latex英文润色) + "Function": HotReload(Latex英文润色), }, "英文Latex项目全文纠错(输入路径或上传压缩包)": { "Group": "学术", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "对英文Latex项目全文进行纠错处理 | 输入参数为路径或上传压缩包", - "Function": HotReload(Latex英文纠错) + "Function": HotReload(Latex英文纠错), }, "中文Latex项目全文润色(输入路径或上传压缩包)": { "Group": "学术", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "对中文Latex项目全文进行润色处理 | 输入参数为路径或上传压缩包", - "Function": HotReload(Latex中文润色) + "Function": HotReload(Latex中文润色), }, - # 已经被新插件取代 # "Latex项目全文中译英(输入路径或上传压缩包)": { # "Group": "学术", @@ -261,7 +259,6 @@ def get_crazy_functions(): # "Info": "对Latex项目全文进行中译英处理 | 输入参数为路径或上传压缩包", # "Function": HotReload(Latex中译英) # }, - # 已经被新插件取代 # "Latex项目全文英译中(输入路径或上传压缩包)": { # "Group": "学术", @@ -270,339 +267,414 @@ def get_crazy_functions(): # "Info": "对Latex项目全文进行英译中处理 | 输入参数为路径或上传压缩包", # "Function": HotReload(Latex英译中) # }, - "批量Markdown中译英(输入路径或上传压缩包)": { "Group": "编程", "Color": "stop", "AsButton": False, # 加入下拉菜单中 "Info": "批量将Markdown文件中文翻译为英文 | 输入参数为路径或上传压缩包", - "Function": HotReload(Markdown中译英) + "Function": HotReload(Markdown中译英), }, } # -=--=- 尚未充分测试的实验性插件 & 需要额外依赖的插件 -=--=- try: from crazy_functions.下载arxiv论文翻译摘要 import 下载arxiv论文并翻译摘要 - function_plugins.update({ - "一键下载arxiv论文并翻译摘要(先在input输入编号,如1812.10695)": { - "Group": "学术", - "Color": "stop", - "AsButton": False, # 加入下拉菜单中 - # "Info": "下载arxiv论文并翻译摘要 | 输入参数为arxiv编号如1812.10695", - "Function": HotReload(下载arxiv论文并翻译摘要) + + function_plugins.update( + { + "一键下载arxiv论文并翻译摘要(先在input输入编号,如1812.10695)": { + "Group": "学术", + "Color": "stop", + "AsButton": False, # 加入下拉菜单中 + # "Info": "下载arxiv论文并翻译摘要 | 输入参数为arxiv编号如1812.10695", + "Function": HotReload(下载arxiv论文并翻译摘要), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.联网的ChatGPT import 连接网络回答问题 - function_plugins.update({ - "连接网络回答问题(输入问题后点击该插件,需要访问谷歌)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, # 加入下拉菜单中 - # "Info": "连接网络回答问题(需要访问谷歌)| 输入参数是一个问题", - "Function": HotReload(连接网络回答问题) + + function_plugins.update( + { + "连接网络回答问题(输入问题后点击该插件,需要访问谷歌)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, # 加入下拉菜单中 + # "Info": "连接网络回答问题(需要访问谷歌)| 输入参数是一个问题", + "Function": HotReload(连接网络回答问题), + } } - }) + ) from crazy_functions.联网的ChatGPT_bing版 import 连接bing搜索回答问题 - function_plugins.update({ - "连接网络回答问题(中文Bing版,输入问题后点击该插件)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, # 加入下拉菜单中 - "Info": "连接网络回答问题(需要访问中文Bing)| 输入参数是一个问题", - "Function": HotReload(连接bing搜索回答问题) + + function_plugins.update( + { + "连接网络回答问题(中文Bing版,输入问题后点击该插件)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, # 加入下拉菜单中 + "Info": "连接网络回答问题(需要访问中文Bing)| 输入参数是一个问题", + "Function": HotReload(连接bing搜索回答问题), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.解析项目源代码 import 解析任意code项目 - function_plugins.update({ - "解析项目源代码(手动指定和筛选源代码文件类型)": { - "Group": "编程", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) - "ArgsReminder": "输入时用逗号隔开, *代表通配符, 加了^代表不匹配; 不输入代表全部匹配。例如: \"*.c, ^*.cpp, config.toml, ^*.toml\"", # 高级参数输入区的显示提示 - "Function": HotReload(解析任意code项目) - }, - }) + + function_plugins.update( + { + "解析项目源代码(手动指定和筛选源代码文件类型)": { + "Group": "编程", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) + "ArgsReminder": '输入时用逗号隔开, *代表通配符, 加了^代表不匹配; 不输入代表全部匹配。例如: "*.c, ^*.cpp, config.toml, ^*.toml"', # 高级参数输入区的显示提示 + "Function": HotReload(解析任意code项目), + }, + } + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.询问多个大语言模型 import 同时问询_指定模型 - function_plugins.update({ - "询问多个GPT模型(手动指定询问哪些模型)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) - "ArgsReminder": "支持任意数量的llm接口,用&符号分隔。例如chatglm&gpt-3.5-turbo&gpt-4", # 高级参数输入区的显示提示 - "Function": HotReload(同时问询_指定模型) - }, - }) + + function_plugins.update( + { + "询问多个GPT模型(手动指定询问哪些模型)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) + "ArgsReminder": "支持任意数量的llm接口,用&符号分隔。例如chatglm&gpt-3.5-turbo&gpt-4", # 高级参数输入区的显示提示 + "Function": HotReload(同时问询_指定模型), + }, + } + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.图片生成 import 图片生成_DALLE2, 图片生成_DALLE3, 图片修改_DALLE2 - function_plugins.update({ - "图片生成_DALLE2 (先切换模型到gpt-*)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) - "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 256x256, 512x512, 1024x1024", # 高级参数输入区的显示提示 - "Info": "使用DALLE2生成图片 | 输入参数字符串,提供图像的内容", - "Function": HotReload(图片生成_DALLE2) - }, - }) - function_plugins.update({ - "图片生成_DALLE3 (先切换模型到gpt-*)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) - "ArgsReminder": "在这里输入自定义参数「分辨率-质量(可选)-风格(可选)」, 参数示例「1024x1024-hd-vivid」 || 分辨率支持 「1024x1024」(默认) /「1792x1024」/「1024x1792」 || 质量支持 「-standard」(默认) /「-hd」 || 风格支持 「-vivid」(默认) /「-natural」", # 高级参数输入区的显示提示 - "Info": "使用DALLE3生成图片 | 输入参数字符串,提供图像的内容", - "Function": HotReload(图片生成_DALLE3) - }, - }) - function_plugins.update({ - "图片修改_DALLE2 (先切换模型到gpt-*)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": False, # 调用时,唤起高级参数输入区(默认False) - # "Info": "使用DALLE2修改图片 | 输入参数字符串,提供图像的内容", - "Function": HotReload(图片修改_DALLE2) - }, - }) + + function_plugins.update( + { + "图片生成_DALLE2 (先切换模型到gpt-*)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) + "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 256x256, 512x512, 1024x1024", # 高级参数输入区的显示提示 + "Info": "使用DALLE2生成图片 | 输入参数字符串,提供图像的内容", + "Function": HotReload(图片生成_DALLE2), + }, + } + ) + function_plugins.update( + { + "图片生成_DALLE3 (先切换模型到gpt-*)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) + "ArgsReminder": "在这里输入自定义参数「分辨率-质量(可选)-风格(可选)」, 参数示例「1024x1024-hd-vivid」 || 分辨率支持 「1024x1024」(默认) /「1792x1024」/「1024x1792」 || 质量支持 「-standard」(默认) /「-hd」 || 风格支持 「-vivid」(默认) /「-natural」", # 高级参数输入区的显示提示 + "Info": "使用DALLE3生成图片 | 输入参数字符串,提供图像的内容", + "Function": HotReload(图片生成_DALLE3), + }, + } + ) + function_plugins.update( + { + "图片修改_DALLE2 (先切换模型到gpt-*)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": False, # 调用时,唤起高级参数输入区(默认False) + # "Info": "使用DALLE2修改图片 | 输入参数字符串,提供图像的内容", + "Function": HotReload(图片修改_DALLE2), + }, + } + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.总结音视频 import 总结音视频 - function_plugins.update({ - "批量总结音视频(输入路径或上传压缩包)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, - "ArgsReminder": "调用openai api 使用whisper-1模型, 目前支持的格式:mp4, m4a, wav, mpga, mpeg, mp3。此处可以输入解析提示,例如:解析为简体中文(默认)。", - "Info": "批量总结音频或视频 | 输入参数为路径", - "Function": HotReload(总结音视频) + + function_plugins.update( + { + "批量总结音视频(输入路径或上传压缩包)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, + "ArgsReminder": "调用openai api 使用whisper-1模型, 目前支持的格式:mp4, m4a, wav, mpga, mpeg, mp3。此处可以输入解析提示,例如:解析为简体中文(默认)。", + "Info": "批量总结音频或视频 | 输入参数为路径", + "Function": HotReload(总结音视频), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.数学动画生成manim import 动画生成 - function_plugins.update({ - "数学动画生成(Manim)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "Info": "按照自然语言描述生成一个动画 | 输入参数是一段话", - "Function": HotReload(动画生成) + + function_plugins.update( + { + "数学动画生成(Manim)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "Info": "按照自然语言描述生成一个动画 | 输入参数是一段话", + "Function": HotReload(动画生成), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.批量Markdown翻译 import Markdown翻译指定语言 - function_plugins.update({ - "Markdown翻译(指定翻译成何种语言)": { - "Group": "编程", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, - "ArgsReminder": "请输入要翻译成哪种语言,默认为Chinese。", - "Function": HotReload(Markdown翻译指定语言) + + function_plugins.update( + { + "Markdown翻译(指定翻译成何种语言)": { + "Group": "编程", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, + "ArgsReminder": "请输入要翻译成哪种语言,默认为Chinese。", + "Function": HotReload(Markdown翻译指定语言), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.知识库问答 import 知识库文件注入 - function_plugins.update({ - "构建知识库(先上传文件素材,再运行此插件)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, - "ArgsReminder": "此处待注入的知识库名称id, 默认为default。文件进入知识库后可长期保存。可以通过再次调用本插件的方式,向知识库追加更多文档。", - "Function": HotReload(知识库文件注入) + + function_plugins.update( + { + "构建知识库(先上传文件素材,再运行此插件)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, + "ArgsReminder": "此处待注入的知识库名称id, 默认为default。文件进入知识库后可长期保存。可以通过再次调用本插件的方式,向知识库追加更多文档。", + "Function": HotReload(知识库文件注入), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.知识库问答 import 读取知识库作答 - function_plugins.update({ - "知识库文件注入(构建知识库后,再运行此插件)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, - "ArgsReminder": "待提取的知识库名称id, 默认为default, 您需要构建知识库后再运行此插件。", - "Function": HotReload(读取知识库作答) + + function_plugins.update( + { + "知识库文件注入(构建知识库后,再运行此插件)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, + "ArgsReminder": "待提取的知识库名称id, 默认为default, 您需要构建知识库后再运行此插件。", + "Function": HotReload(读取知识库作答), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.交互功能函数模板 import 交互功能模板函数 - function_plugins.update({ - "交互功能模板Demo函数(查找wallhaven.cc的壁纸)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "Function": HotReload(交互功能模板函数) + + function_plugins.update( + { + "交互功能模板Demo函数(查找wallhaven.cc的壁纸)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "Function": HotReload(交互功能模板函数), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.Latex输出PDF结果 import Latex英文纠错加PDF对比 - function_plugins.update({ - "Latex英文纠错+高亮修正位置 [需Latex]": { - "Group": "学术", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, - "ArgsReminder": "如果有必要, 请在此处追加更细致的矫错指令(使用英文)。", - "Function": HotReload(Latex英文纠错加PDF对比) + + function_plugins.update( + { + "Latex英文纠错+高亮修正位置 [需Latex]": { + "Group": "学术", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, + "ArgsReminder": "如果有必要, 请在此处追加更细致的矫错指令(使用英文)。", + "Function": HotReload(Latex英文纠错加PDF对比), + } } - }) + ) from crazy_functions.Latex输出PDF结果 import Latex翻译中文并重新编译PDF - function_plugins.update({ - "Arxiv论文精细翻译(输入arxivID)[需Latex]": { - "Group": "学术", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, - "ArgsReminder": - "如果有必要, 请在此处给出自定义翻译命令, 解决部分词汇翻译不准确的问题。 " + - "例如当单词'agent'翻译不准确时, 请尝试把以下指令复制到高级参数区: " + - 'If the term "agent" is used in this section, it should be translated to "智能体". ', - "Info": "Arixv论文精细翻译 | 输入参数arxiv论文的ID,比如1812.10695", - "Function": HotReload(Latex翻译中文并重新编译PDF) + + function_plugins.update( + { + "Arxiv论文精细翻译(输入arxivID)[需Latex]": { + "Group": "学术", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, + "ArgsReminder": "如果有必要, 请在此处给出自定义翻译命令, 解决部分词汇翻译不准确的问题。 " + + "例如当单词'agent'翻译不准确时, 请尝试把以下指令复制到高级参数区: " + + 'If the term "agent" is used in this section, it should be translated to "智能体". ', + "Info": "Arixv论文精细翻译 | 输入参数arxiv论文的ID,比如1812.10695", + "Function": HotReload(Latex翻译中文并重新编译PDF), + } } - }) - function_plugins.update({ - "本地Latex论文精细翻译(上传Latex项目)[需Latex]": { - "Group": "学术", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, - "ArgsReminder": - "如果有必要, 请在此处给出自定义翻译命令, 解决部分词汇翻译不准确的问题。 " + - "例如当单词'agent'翻译不准确时, 请尝试把以下指令复制到高级参数区: " + - 'If the term "agent" is used in this section, it should be translated to "智能体". ', - "Info": "本地Latex论文精细翻译 | 输入参数是路径", - "Function": HotReload(Latex翻译中文并重新编译PDF) + ) + function_plugins.update( + { + "本地Latex论文精细翻译(上传Latex项目)[需Latex]": { + "Group": "学术", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, + "ArgsReminder": "如果有必要, 请在此处给出自定义翻译命令, 解决部分词汇翻译不准确的问题。 " + + "例如当单词'agent'翻译不准确时, 请尝试把以下指令复制到高级参数区: " + + 'If the term "agent" is used in this section, it should be translated to "智能体". ', + "Info": "本地Latex论文精细翻译 | 输入参数是路径", + "Function": HotReload(Latex翻译中文并重新编译PDF), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from toolbox import get_conf - ENABLE_AUDIO = get_conf('ENABLE_AUDIO') + + ENABLE_AUDIO = get_conf("ENABLE_AUDIO") if ENABLE_AUDIO: from crazy_functions.语音助手 import 语音助手 - function_plugins.update({ - "实时语音对话": { - "Group": "对话", - "Color": "stop", - "AsButton": True, - "Info": "这是一个时刻聆听着的语音对话助手 | 没有输入参数", - "Function": HotReload(语音助手) + + function_plugins.update( + { + "实时语音对话": { + "Group": "对话", + "Color": "stop", + "AsButton": True, + "Info": "这是一个时刻聆听着的语音对话助手 | 没有输入参数", + "Function": HotReload(语音助手), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.批量翻译PDF文档_NOUGAT import 批量翻译PDF文档 - function_plugins.update({ - "精准翻译PDF文档(NOUGAT)": { - "Group": "学术", - "Color": "stop", - "AsButton": False, - "Function": HotReload(批量翻译PDF文档) + + function_plugins.update( + { + "精准翻译PDF文档(NOUGAT)": { + "Group": "学术", + "Color": "stop", + "AsButton": False, + "Function": HotReload(批量翻译PDF文档), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.函数动态生成 import 函数动态生成 - function_plugins.update({ - "动态代码解释器(CodeInterpreter)": { - "Group": "智能体", - "Color": "stop", - "AsButton": False, - "Function": HotReload(函数动态生成) + + function_plugins.update( + { + "动态代码解释器(CodeInterpreter)": { + "Group": "智能体", + "Color": "stop", + "AsButton": False, + "Function": HotReload(函数动态生成), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.多智能体 import 多智能体终端 - function_plugins.update({ - "AutoGen多智能体终端(仅供测试)": { - "Group": "智能体", - "Color": "stop", - "AsButton": False, - "Function": HotReload(多智能体终端) + + function_plugins.update( + { + "AutoGen多智能体终端(仅供测试)": { + "Group": "智能体", + "Color": "stop", + "AsButton": False, + "Function": HotReload(多智能体终端), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") try: from crazy_functions.互动小游戏 import 随机小游戏 - function_plugins.update({ - "随机互动小游戏(仅供测试)": { - "Group": "智能体", - "Color": "stop", - "AsButton": False, - "Function": HotReload(随机小游戏) + + function_plugins.update( + { + "随机互动小游戏(仅供测试)": { + "Group": "智能体", + "Color": "stop", + "AsButton": False, + "Function": HotReload(随机小游戏), + } } - }) + ) except: print(trimmed_format_exc()) - print('Load function plugin failed') + print("Load function plugin failed") + + # try: + # from crazy_functions.高级功能函数模板 import 测试图表渲染 + # function_plugins.update({ + # "绘制逻辑关系(测试图表渲染)": { + # "Group": "智能体", + # "Color": "stop", + # "AsButton": True, + # "Function": HotReload(测试图表渲染) + # } + # }) + # except: + # print(trimmed_format_exc()) + # print('Load function plugin failed') # try: # from crazy_functions.chatglm微调工具 import 微调数据集生成 @@ -618,8 +690,6 @@ def get_crazy_functions(): # except: # print('Load function plugin failed') - - """ 设置默认值: - 默认 Group = 对话 @@ -629,12 +699,12 @@ def get_crazy_functions(): """ for name, function_meta in function_plugins.items(): if "Group" not in function_meta: - function_plugins[name]["Group"] = '对话' + function_plugins[name]["Group"] = "对话" if "AsButton" not in function_meta: function_plugins[name]["AsButton"] = True if "AdvancedArgs" not in function_meta: function_plugins[name]["AdvancedArgs"] = False if "Color" not in function_meta: - function_plugins[name]["Color"] = 'secondary' + function_plugins[name]["Color"] = "secondary" return function_plugins diff --git "a/crazy_functions/Latex\350\276\223\345\207\272PDF\347\273\223\346\236\234.py" "b/crazy_functions/Latex\350\276\223\345\207\272PDF\347\273\223\346\236\234.py" index 18a8d1bab26af31e7ac0671b95c91660d6d7f02d..36c99e71cf7ad81dcf1b721b1f98f59ef694c7fa 100644 --- "a/crazy_functions/Latex\350\276\223\345\207\272PDF\347\273\223\346\236\234.py" +++ "b/crazy_functions/Latex\350\276\223\345\207\272PDF\347\273\223\346\236\234.py" @@ -5,7 +5,7 @@ import glob, os, requests, time pj = os.path.join ARXIV_CACHE_DIR = os.path.expanduser(f"~/arxiv_cache/") -# =================================== 工具函数 =============================================== +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 工具函数 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # 专业词汇声明 = 'If the term "agent" is used in this section, it should be translated to "智能体". ' def switch_prompt(pfg, mode, more_requirement): """ @@ -142,7 +142,7 @@ def arxiv_download(chatbot, history, txt, allow_cache=True): from toolbox import extract_archive extract_archive(file_path=dst, dest_dir=extract_dst) return extract_dst, arxiv_id -# ========================================= 插件主程序1 ===================================================== +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 插件主程序1 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= @CatchException @@ -218,7 +218,7 @@ def Latex英文纠错加PDF对比(txt, llm_kwargs, plugin_kwargs, chatbot, histo # <-------------- we are done -------------> return success -# ========================================= 插件主程序2 ===================================================== +# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 插件主程序2 =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= @CatchException def Latex翻译中文并重新编译PDF(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): diff --git a/crazy_functions/agent_fns/general.py b/crazy_functions/agent_fns/general.py index 49bc4dc89e9e1244891c15ff73bb0ae065d51821..327a613b36b456220ac85d42a6a536f4fce42ea6 100644 --- a/crazy_functions/agent_fns/general.py +++ b/crazy_functions/agent_fns/general.py @@ -35,7 +35,11 @@ def gpt_academic_generate_oai_reply( class AutoGenGeneral(PluginMultiprocessManager): def gpt_academic_print_override(self, user_proxy, message, sender): # ⭐⭐ run in subprocess - self.child_conn.send(PipeCom("show", sender.name + "\n\n---\n\n" + message["content"])) + try: + print_msg = sender.name + "\n\n---\n\n" + message["content"] + except: + print_msg = sender.name + "\n\n---\n\n" + message + self.child_conn.send(PipeCom("show", print_msg)) def gpt_academic_get_human_input(self, user_proxy, message): # ⭐⭐ run in subprocess @@ -62,33 +66,33 @@ class AutoGenGeneral(PluginMultiprocessManager): def exe_autogen(self, input): # ⭐⭐ run in subprocess input = input.content - with ProxyNetworkActivate("AutoGen"): - code_execution_config = {"work_dir": self.autogen_work_dir, "use_docker": self.use_docker} - agents = self.define_agents() - user_proxy = None - assistant = None - for agent_kwargs in agents: - agent_cls = agent_kwargs.pop('cls') - kwargs = { - 'llm_config':self.llm_kwargs, - 'code_execution_config':code_execution_config - } - kwargs.update(agent_kwargs) - agent_handle = agent_cls(**kwargs) - agent_handle._print_received_message = lambda a,b: self.gpt_academic_print_override(agent_kwargs, a, b) - for d in agent_handle._reply_func_list: - if hasattr(d['reply_func'],'__name__') and d['reply_func'].__name__ == 'generate_oai_reply': - d['reply_func'] = gpt_academic_generate_oai_reply - if agent_kwargs['name'] == 'user_proxy': - agent_handle.get_human_input = lambda a: self.gpt_academic_get_human_input(user_proxy, a) - user_proxy = agent_handle - if agent_kwargs['name'] == 'assistant': assistant = agent_handle - try: - if user_proxy is None or assistant is None: raise Exception("用户代理或助理代理未定义") + code_execution_config = {"work_dir": self.autogen_work_dir, "use_docker": self.use_docker} + agents = self.define_agents() + user_proxy = None + assistant = None + for agent_kwargs in agents: + agent_cls = agent_kwargs.pop('cls') + kwargs = { + 'llm_config':self.llm_kwargs, + 'code_execution_config':code_execution_config + } + kwargs.update(agent_kwargs) + agent_handle = agent_cls(**kwargs) + agent_handle._print_received_message = lambda a,b: self.gpt_academic_print_override(agent_kwargs, a, b) + for d in agent_handle._reply_func_list: + if hasattr(d['reply_func'],'__name__') and d['reply_func'].__name__ == 'generate_oai_reply': + d['reply_func'] = gpt_academic_generate_oai_reply + if agent_kwargs['name'] == 'user_proxy': + agent_handle.get_human_input = lambda a: self.gpt_academic_get_human_input(user_proxy, a) + user_proxy = agent_handle + if agent_kwargs['name'] == 'assistant': assistant = agent_handle + try: + if user_proxy is None or assistant is None: raise Exception("用户代理或助理代理未定义") + with ProxyNetworkActivate("AutoGen"): user_proxy.initiate_chat(assistant, message=input) - except Exception as e: - tb_str = '```\n' + trimmed_format_exc() + '```' - self.child_conn.send(PipeCom("done", "AutoGen 执行失败: \n\n" + tb_str)) + except Exception as e: + tb_str = '```\n' + trimmed_format_exc() + '```' + self.child_conn.send(PipeCom("done", "AutoGen 执行失败: \n\n" + tb_str)) def subprocess_worker(self, child_conn): # ⭐⭐ run in subprocess diff --git a/crazy_functions/crazy_utils.py b/crazy_functions/crazy_utils.py index 4d3b1953d424c8d0c9ba01882b55c2fe0ee18941..e7e625b9c505827fde3a7fd1341ac19273c7d147 100644 --- a/crazy_functions/crazy_utils.py +++ b/crazy_functions/crazy_utils.py @@ -466,6 +466,9 @@ def read_and_clean_pdf_text(fp): return True else: return False + # 对于某些PDF会有第一个段落就以小写字母开头,为了避免索引错误将其更改为大写 + if starts_with_lowercase_word(meta_txt[0]): + meta_txt[0] = meta_txt[0].capitalize() for _ in range(100): for index, block_txt in enumerate(meta_txt): if starts_with_lowercase_word(block_txt): diff --git a/crazy_functions/latex_fns/latex_toolbox.py b/crazy_functions/latex_fns/latex_toolbox.py index 0a6a873b50b8299fa28bc41e27cf7a27a16637ae..bbd1bb3c6b85a9731912388f187b248a626ffd52 100644 --- a/crazy_functions/latex_fns/latex_toolbox.py +++ b/crazy_functions/latex_fns/latex_toolbox.py @@ -1,15 +1,18 @@ import os, shutil import re import numpy as np + PRESERVE = 0 TRANSFORM = 1 pj = os.path.join -class LinkedListNode(): + +class LinkedListNode: """ Linked List Node """ + def __init__(self, string, preserve=True) -> None: self.string = string self.preserve = preserve @@ -18,41 +21,47 @@ class LinkedListNode(): # self.begin_line = 0 # self.begin_char = 0 + def convert_to_linklist(text, mask): root = LinkedListNode("", preserve=True) current_node = root for c, m, i in zip(text, mask, range(len(text))): - if (m==PRESERVE and current_node.preserve) \ - or (m==TRANSFORM and not current_node.preserve): + if (m == PRESERVE and current_node.preserve) or ( + m == TRANSFORM and not current_node.preserve + ): # add current_node.string += c else: - current_node.next = LinkedListNode(c, preserve=(m==PRESERVE)) + current_node.next = LinkedListNode(c, preserve=(m == PRESERVE)) current_node = current_node.next return root + def post_process(root): # 修复括号 node = root while True: string = node.string - if node.preserve: + if node.preserve: node = node.next - if node is None: break + if node is None: + break continue + def break_check(string): - str_stack = [""] # (lv, index) + str_stack = [""] # (lv, index) for i, c in enumerate(string): - if c == '{': - str_stack.append('{') - elif c == '}': + if c == "{": + str_stack.append("{") + elif c == "}": if len(str_stack) == 1: - print('stack fix') + print("stack fix") return i str_stack.pop(-1) else: str_stack[-1] += c return -1 + bp = break_check(string) if bp == -1: @@ -69,51 +78,66 @@ def post_process(root): node.next = q node = node.next - if node is None: break + if node is None: + break # 屏蔽空行和太短的句子 node = root while True: - if len(node.string.strip('\n').strip(''))==0: node.preserve = True - if len(node.string.strip('\n').strip(''))<42: node.preserve = True + if len(node.string.strip("\n").strip("")) == 0: + node.preserve = True + if len(node.string.strip("\n").strip("")) < 42: + node.preserve = True node = node.next - if node is None: break + if node is None: + break node = root while True: if node.next and node.preserve and node.next.preserve: node.string += node.next.string node.next = node.next.next node = node.next - if node is None: break + if node is None: + break # 将前后断行符脱离 node = root prev_node = None while True: if not node.preserve: - lstriped_ = node.string.lstrip().lstrip('\n') - if (prev_node is not None) and (prev_node.preserve) and (len(lstriped_)!=len(node.string)): - prev_node.string += node.string[:-len(lstriped_)] + lstriped_ = node.string.lstrip().lstrip("\n") + if ( + (prev_node is not None) + and (prev_node.preserve) + and (len(lstriped_) != len(node.string)) + ): + prev_node.string += node.string[: -len(lstriped_)] node.string = lstriped_ - rstriped_ = node.string.rstrip().rstrip('\n') - if (node.next is not None) and (node.next.preserve) and (len(rstriped_)!=len(node.string)): - node.next.string = node.string[len(rstriped_):] + node.next.string + rstriped_ = node.string.rstrip().rstrip("\n") + if ( + (node.next is not None) + and (node.next.preserve) + and (len(rstriped_) != len(node.string)) + ): + node.next.string = node.string[len(rstriped_) :] + node.next.string node.string = rstriped_ - # ===== + # =-=-= prev_node = node node = node.next - if node is None: break + if node is None: + break # 标注节点的行数范围 node = root n_line = 0 expansion = 2 while True: - n_l = node.string.count('\n') - node.range = [n_line-expansion, n_line+n_l+expansion] # 失败时,扭转的范围 - n_line = n_line+n_l + n_l = node.string.count("\n") + node.range = [n_line - expansion, n_line + n_l + expansion] # 失败时,扭转的范围 + n_line = n_line + n_l node = node.next - if node is None: break + if node is None: + break return root @@ -128,97 +152,125 @@ def set_forbidden_text(text, mask, pattern, flags=0): """ Add a preserve text area in this paper e.g. with pattern = r"\\begin\{algorithm\}(.*?)\\end\{algorithm\}" - you can mask out (mask = PRESERVE so that text become untouchable for GPT) + you can mask out (mask = PRESERVE so that text become untouchable for GPT) everything between "\begin{equation}" and "\end{equation}" """ - if isinstance(pattern, list): pattern = '|'.join(pattern) + if isinstance(pattern, list): + pattern = "|".join(pattern) pattern_compile = re.compile(pattern, flags) for res in pattern_compile.finditer(text): - mask[res.span()[0]:res.span()[1]] = PRESERVE + mask[res.span()[0] : res.span()[1]] = PRESERVE return text, mask + def reverse_forbidden_text(text, mask, pattern, flags=0, forbid_wrapper=True): """ Move area out of preserve area (make text editable for GPT) - count the number of the braces so as to catch compelete text area. + count the number of the braces so as to catch compelete text area. e.g. - \begin{abstract} blablablablablabla. \end{abstract} + \begin{abstract} blablablablablabla. \end{abstract} """ - if isinstance(pattern, list): pattern = '|'.join(pattern) + if isinstance(pattern, list): + pattern = "|".join(pattern) pattern_compile = re.compile(pattern, flags) for res in pattern_compile.finditer(text): if not forbid_wrapper: - mask[res.span()[0]:res.span()[1]] = TRANSFORM + mask[res.span()[0] : res.span()[1]] = TRANSFORM else: - mask[res.regs[0][0]: res.regs[1][0]] = PRESERVE # '\\begin{abstract}' - mask[res.regs[1][0]: res.regs[1][1]] = TRANSFORM # abstract - mask[res.regs[1][1]: res.regs[0][1]] = PRESERVE # abstract + mask[res.regs[0][0] : res.regs[1][0]] = PRESERVE # '\\begin{abstract}' + mask[res.regs[1][0] : res.regs[1][1]] = TRANSFORM # abstract + mask[res.regs[1][1] : res.regs[0][1]] = PRESERVE # abstract return text, mask + def set_forbidden_text_careful_brace(text, mask, pattern, flags=0): """ Add a preserve text area in this paper (text become untouchable for GPT). - count the number of the braces so as to catch compelete text area. + count the number of the braces so as to catch compelete text area. e.g. - \caption{blablablablabla\texbf{blablabla}blablabla.} + \caption{blablablablabla\texbf{blablabla}blablabla.} """ pattern_compile = re.compile(pattern, flags) for res in pattern_compile.finditer(text): brace_level = -1 p = begin = end = res.regs[0][0] - for _ in range(1024*16): - if text[p] == '}' and brace_level == 0: break - elif text[p] == '}': brace_level -= 1 - elif text[p] == '{': brace_level += 1 + for _ in range(1024 * 16): + if text[p] == "}" and brace_level == 0: + break + elif text[p] == "}": + brace_level -= 1 + elif text[p] == "{": + brace_level += 1 p += 1 - end = p+1 + end = p + 1 mask[begin:end] = PRESERVE return text, mask -def reverse_forbidden_text_careful_brace(text, mask, pattern, flags=0, forbid_wrapper=True): + +def reverse_forbidden_text_careful_brace( + text, mask, pattern, flags=0, forbid_wrapper=True +): """ Move area out of preserve area (make text editable for GPT) - count the number of the braces so as to catch compelete text area. + count the number of the braces so as to catch compelete text area. e.g. - \caption{blablablablabla\texbf{blablabla}blablabla.} + \caption{blablablablabla\texbf{blablabla}blablabla.} """ pattern_compile = re.compile(pattern, flags) for res in pattern_compile.finditer(text): brace_level = 0 p = begin = end = res.regs[1][0] - for _ in range(1024*16): - if text[p] == '}' and brace_level == 0: break - elif text[p] == '}': brace_level -= 1 - elif text[p] == '{': brace_level += 1 + for _ in range(1024 * 16): + if text[p] == "}" and brace_level == 0: + break + elif text[p] == "}": + brace_level -= 1 + elif text[p] == "{": + brace_level += 1 p += 1 end = p mask[begin:end] = TRANSFORM if forbid_wrapper: - mask[res.regs[0][0]:begin] = PRESERVE - mask[end:res.regs[0][1]] = PRESERVE + mask[res.regs[0][0] : begin] = PRESERVE + mask[end : res.regs[0][1]] = PRESERVE return text, mask + def set_forbidden_text_begin_end(text, mask, pattern, flags=0, limit_n_lines=42): """ Find all \begin{} ... \end{} text block that with less than limit_n_lines lines. Add it to preserve area """ pattern_compile = re.compile(pattern, flags) + def search_with_line_limit(text, mask): for res in pattern_compile.finditer(text): cmd = res.group(1) # begin{what} - this = res.group(2) # content between begin and end - this_mask = mask[res.regs[2][0]:res.regs[2][1]] - white_list = ['document', 'abstract', 'lemma', 'definition', 'sproof', - 'em', 'emph', 'textit', 'textbf', 'itemize', 'enumerate'] - if (cmd in white_list) or this.count('\n') >= limit_n_lines: # use a magical number 42 + this = res.group(2) # content between begin and end + this_mask = mask[res.regs[2][0] : res.regs[2][1]] + white_list = [ + "document", + "abstract", + "lemma", + "definition", + "sproof", + "em", + "emph", + "textit", + "textbf", + "itemize", + "enumerate", + ] + if (cmd in white_list) or this.count( + "\n" + ) >= limit_n_lines: # use a magical number 42 this, this_mask = search_with_line_limit(this, this_mask) - mask[res.regs[2][0]:res.regs[2][1]] = this_mask + mask[res.regs[2][0] : res.regs[2][1]] = this_mask else: - mask[res.regs[0][0]:res.regs[0][1]] = PRESERVE + mask[res.regs[0][0] : res.regs[0][1]] = PRESERVE return text, mask - return search_with_line_limit(text, mask) + return search_with_line_limit(text, mask) """ @@ -227,6 +279,7 @@ Latex Merge File =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= """ + def find_main_tex_file(file_manifest, mode): """ 在多Tex文档中,寻找主文件,必须包含documentclass,返回找到的第一个。 @@ -234,27 +287,36 @@ def find_main_tex_file(file_manifest, mode): """ canidates = [] for texf in file_manifest: - if os.path.basename(texf).startswith('merge'): + if os.path.basename(texf).startswith("merge"): continue - with open(texf, 'r', encoding='utf8', errors='ignore') as f: + with open(texf, "r", encoding="utf8", errors="ignore") as f: file_content = f.read() - if r'\documentclass' in file_content: + if r"\documentclass" in file_content: canidates.append(texf) else: continue if len(canidates) == 0: - raise RuntimeError('无法找到一个主Tex文件(包含documentclass关键字)') + raise RuntimeError("无法找到一个主Tex文件(包含documentclass关键字)") elif len(canidates) == 1: return canidates[0] - else: # if len(canidates) >= 2 通过一些Latex模板中常见(但通常不会出现在正文)的单词,对不同latex源文件扣分,取评分最高者返回 + else: # if len(canidates) >= 2 通过一些Latex模板中常见(但通常不会出现在正文)的单词,对不同latex源文件扣分,取评分最高者返回 canidates_score = [] # 给出一些判定模板文档的词作为扣分项 - unexpected_words = ['\LaTeX', 'manuscript', 'Guidelines', 'font', 'citations', 'rejected', 'blind review', 'reviewers'] - expected_words = ['\input', '\ref', '\cite'] + unexpected_words = [ + "\\LaTeX", + "manuscript", + "Guidelines", + "font", + "citations", + "rejected", + "blind review", + "reviewers", + ] + expected_words = ["\\input", "\\ref", "\\cite"] for texf in canidates: canidates_score.append(0) - with open(texf, 'r', encoding='utf8', errors='ignore') as f: + with open(texf, "r", encoding="utf8", errors="ignore") as f: file_content = f.read() file_content = rm_comments(file_content) for uw in unexpected_words: @@ -263,9 +325,10 @@ def find_main_tex_file(file_manifest, mode): for uw in expected_words: if uw in file_content: canidates_score[-1] += 1 - select = np.argmax(canidates_score) # 取评分最高者返回 + select = np.argmax(canidates_score) # 取评分最高者返回 return canidates[select] - + + def rm_comments(main_file): new_file_remove_comment_lines = [] for l in main_file.splitlines(): @@ -274,30 +337,39 @@ def rm_comments(main_file): pass else: new_file_remove_comment_lines.append(l) - main_file = '\n'.join(new_file_remove_comment_lines) + main_file = "\n".join(new_file_remove_comment_lines) # main_file = re.sub(r"\\include{(.*?)}", r"\\input{\1}", main_file) # 将 \include 命令转换为 \input 命令 - main_file = re.sub(r'(? 0 and node_string.count('\_') > final_tex.count('\_'): + final_tex = node_string # 出问题了,还原原文 + if node_string.count("\\begin") != final_tex.count("\\begin"): + final_tex = node_string # 出问题了,还原原文 + if node_string.count("\_") > 0 and node_string.count("\_") > final_tex.count("\_"): # walk and replace any _ without \ final_tex = re.sub(r"(? 0: - chatbot.append([f"处理任务: {txt}", f"暂不支持中转."]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 - return - + # 尝试导入依赖,如果缺少依赖,则给出安装建议 try: import autogen diff --git "a/crazy_functions/\346\225\260\345\255\246\345\212\250\347\224\273\347\224\237\346\210\220manim.py" "b/crazy_functions/\346\225\260\345\255\246\345\212\250\347\224\273\347\224\237\346\210\220manim.py" index 26e61b1b3032c180b4cb59625eba00d5f7b7c441..0acf5592c15096d46666b3ffbb41115a1db34429 100644 --- "a/crazy_functions/\346\225\260\345\255\246\345\212\250\347\224\273\347\224\237\346\210\220manim.py" +++ "b/crazy_functions/\346\225\260\345\255\246\345\212\250\347\224\273\347\224\237\346\210\220manim.py" @@ -1,6 +1,7 @@ -from toolbox import CatchException, update_ui, gen_time_str -from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive -from .crazy_utils import input_clipping +import os +from toolbox import CatchException, update_ui, gen_time_str, promote_file_to_downloadzone +from crazy_functions.crazy_utils import request_gpt_model_in_new_thread_with_ui_alive +from crazy_functions.crazy_utils import input_clipping def inspect_dependency(chatbot, history): # 尝试导入依赖,如果缺少依赖,则给出安装建议 @@ -27,9 +28,10 @@ def eval_manim(code): class_name = get_class_name(code) try: + time_str = gen_time_str() subprocess.check_output([sys.executable, '-c', f"from gpt_log.MyAnimation import {class_name}; {class_name}().render()"]) - shutil.move('media/videos/1080p60/{class_name}.mp4', f'gpt_log/{class_name}-{gen_time_str()}.mp4') - return f'gpt_log/{gen_time_str()}.mp4' + shutil.move(f'media/videos/1080p60/{class_name}.mp4', f'gpt_log/{class_name}-{time_str}.mp4') + return f'gpt_log/{time_str}.mp4' except subprocess.CalledProcessError as e: output = e.output.decode() print(f"Command returned non-zero exit status {e.returncode}: {output}.") @@ -94,6 +96,8 @@ def 动画生成(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt res = eval_manim(code) chatbot.append(("生成的视频文件路径", res)) + if os.path.exists(res): + promote_file_to_downloadzone(res, chatbot=chatbot) yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 # 在这里放一些网上搜集的demo,辅助gpt生成代码 diff --git "a/crazy_functions/\351\253\230\347\272\247\345\212\237\350\203\275\345\207\275\346\225\260\346\250\241\346\235\277.py" "b/crazy_functions/\351\253\230\347\272\247\345\212\237\350\203\275\345\207\275\346\225\260\346\250\241\346\235\277.py" index abcbbc6631fa4abdd0577c5a06bd12c5c2504b09..0a9ac0e7f344804f0fd796a1da1a441c3cff68f4 100644 --- "a/crazy_functions/\351\253\230\347\272\247\345\212\237\350\203\275\345\207\275\346\225\260\346\250\241\346\235\277.py" +++ "b/crazy_functions/\351\253\230\347\272\247\345\212\237\350\203\275\345\207\275\346\225\260\346\250\241\346\235\277.py" @@ -26,4 +26,46 @@ def 高阶功能模板函数(txt, llm_kwargs, plugin_kwargs, chatbot, history, s ) chatbot[-1] = (i_say, gpt_say) history.append(i_say);history.append(gpt_say) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 \ No newline at end of file + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 + + + + +PROMPT = """ +请你给出围绕“{subject}”的逻辑关系图,使用mermaid语法,mermaid语法举例: +```mermaid +graph TD + P(编程) --> L1(Python) + P(编程) --> L2(C) + P(编程) --> L3(C++) + P(编程) --> L4(Javascipt) + P(编程) --> L5(PHP) +``` +""" +@CatchException +def 测试图表渲染(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): + """ + txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径 + llm_kwargs gpt模型参数,如温度和top_p等,一般原样传递下去就行 + plugin_kwargs 插件模型的参数,用于灵活调整复杂功能的各种参数 + chatbot 聊天显示框的句柄,用于显示给用户 + history 聊天历史,前情提要 + system_prompt 给gpt的静默提醒 + web_port 当前软件运行的端口号 + """ + history = [] # 清空历史,以免输入溢出 + chatbot.append(("这是什么功能?", "一个测试mermaid绘制图表的功能,您可以在输入框中输入一些关键词,然后使用mermaid+llm绘制图表。")) + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 + + if txt == "": txt = "空白的输入栏" # 调皮一下 + + i_say_show_user = f'请绘制有关“{txt}”的逻辑关系图。' + i_say = PROMPT.format(subject=txt) + gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive( + inputs=i_say, + inputs_show_user=i_say_show_user, + llm_kwargs=llm_kwargs, chatbot=chatbot, history=[], + sys_prompt="" + ) + history.append(i_say); history.append(gpt_say) + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 9472a0f9411a7cfcb9640d3db2e2962145bc49f1..2090c5aa90f728e16d1d0254feb03cddefff12a1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -129,7 +129,7 @@ services: runtime: nvidia devices: - /dev/nvidia0:/dev/nvidia0 - + # 与宿主的网络融合 network_mode: "host" command: > @@ -163,7 +163,7 @@ services: runtime: nvidia devices: - /dev/nvidia0:/dev/nvidia0 - + # 与宿主的网络融合 network_mode: "host" @@ -229,4 +229,3 @@ services: # 不使用代理网络拉取最新代码 command: > bash -c "python3 -u main.py" - diff --git a/docs/Dockerfile+ChatGLM b/docs/Dockerfile+ChatGLM index f0d7c7586f14f3a77557684d62609dba8d5a83a5..7777bf26716e9206de62a51da2d47eadaff0ed15 100644 --- a/docs/Dockerfile+ChatGLM +++ b/docs/Dockerfile+ChatGLM @@ -1,2 +1 @@ # 此Dockerfile不再维护,请前往docs/GithubAction+ChatGLM+Moss - diff --git a/docs/Dockerfile+JittorLLM b/docs/Dockerfile+JittorLLM index 2bd1237b9386545ed681a9540af968872bddd140..b10be8075b3212c6231e6574af29932de6d35aa6 100644 --- a/docs/Dockerfile+JittorLLM +++ b/docs/Dockerfile+JittorLLM @@ -1 +1 @@ -# 此Dockerfile不再维护,请前往docs/GithubAction+JittorLLMs \ No newline at end of file +# 此Dockerfile不再维护,请前往docs/GithubAction+JittorLLMs diff --git a/docs/GithubAction+NoLocal+Latex b/docs/GithubAction+NoLocal+Latex index 6335ee72d4ede9e6f57164ec6fc56baa204bcdcb..95dd4b82729da1cc611c1c245c9ed2c54ba0cde3 100644 --- a/docs/GithubAction+NoLocal+Latex +++ b/docs/GithubAction+NoLocal+Latex @@ -18,7 +18,7 @@ WORKDIR /gpt RUN pip3 install openai numpy arxiv rich RUN pip3 install colorama Markdown pygments pymupdf -RUN pip3 install python-docx pdfminer +RUN pip3 install python-docx pdfminer RUN pip3 install nougat-ocr # 装载项目文件 diff --git a/docs/README.Arabic.md b/docs/README.Arabic.md index 791fb69a03cd6502d01f72cdae0a61c23502442d..5d8bf3cc31d118fab8d8523bebffce77593abb5c 100644 --- a/docs/README.Arabic.md +++ b/docs/README.Arabic.md @@ -2,9 +2,9 @@ > **ملحوظة** -> +> > تمت ترجمة هذا الملف README باستخدام GPT (بواسطة المكون الإضافي لهذا المشروع) وقد لا تكون الترجمة 100٪ موثوقة، يُرجى التمييز بعناية بنتائج الترجمة. -> +> > 2023.11.7: عند تثبيت التبعيات، يُرجى اختيار الإصدار المُحدد في `requirements.txt`. الأمر للتثبيت: `pip install -r requirements.txt`. #
GPT الأكاديمي
@@ -12,14 +12,14 @@ **إذا كنت تحب هذا المشروع، فيُرجى إعطاؤه Star. لترجمة هذا المشروع إلى لغة عشوائية باستخدام GPT، قم بقراءة وتشغيل [`multi_language.py`](multi_language.py) (تجريبي). > **ملحوظة** -> +> > 1. يُرجى ملاحظة أنها الإضافات (الأزرار) المميزة فقط التي تدعم قراءة الملفات، وبعض الإضافات توجد في قائمة منسدلة في منطقة الإضافات. بالإضافة إلى ذلك، نرحب بأي Pull Request جديد بأعلى أولوية لأي إضافة جديدة. -> +> > 2. تُوضّح كل من الملفات في هذا المشروع وظيفتها بالتفصيل في [تقرير الفهم الذاتي `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告). يمكنك في أي وقت أن تنقر على إضافة وظيفة ذات صلة لاستدعاء GPT وإعادة إنشاء تقرير الفهم الذاتي للمشروع. للأسئلة الشائعة [`الويكي`](https://github.com/binary-husky/gpt_academic/wiki). [طرق التثبيت العادية](#installation) | [نصب بنقرة واحدة](https://github.com/binary-husky/gpt_academic/releases) | [تعليمات التكوين](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明). -> +> > 3. يتم توافق هذا المشروع مع ودعم توصيات اللغة البيجائية الأكبر شمولًا وشجاعة لمثل ChatGLM. يمكنك توفير العديد من مفاتيح Api المشتركة في تكوين الملف، مثل `API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`. عند تبديل مؤقت لـ `API_KEY`، قم بإدخال `API_KEY` المؤقت في منطقة الإدخال ثم اضغط على زر "إدخال" لجعله ساري المفعول. - +
@@ -46,7 +46,7 @@ ⭐إضغط على وكيل "شارلوت الذكي" | [وظائف] استكمال الذكاء للكأس الأول للذكاء المكتسب من مايكروسوفت، اكتشاف وتطوير عالمي العميل تبديل الواجهة المُظلمة | يمكنك التبديل إلى الواجهة المظلمة بإضافة ```/?__theme=dark``` إلى نهاية عنوان URL في المتصفح دعم المزيد من نماذج LLM | دعم لجميع GPT3.5 وGPT4 و[ChatGLM2 في جامعة ثوه في لين](https://github.com/THUDM/ChatGLM2-6B) و[MOSS في جامعة فودان](https://github.com/OpenLMLab/MOSS) -⭐تحوي انطباعة "ChatGLM2" | يدعم استيراد "ChatGLM2" ويوفر إضافة المساعدة في تعديله +⭐تحوي انطباعة "ChatGLM2" | يدعم استيراد "ChatGLM2" ويوفر إضافة المساعدة في تعديله دعم المزيد من نماذج "LLM"، دعم [نشر الحديس](https://huggingface.co/spaces/qingxu98/gpt-academic) | انضم إلى واجهة "Newbing" (Bing الجديدة)،نقدم نماذج Jittorllms الجديدة تؤيدهم [LLaMA](https://github.com/facebookresearch/llama) و [盘古α](https://openi.org.cn/pangu/) ⭐حزمة "void-terminal" للشبكة (pip) | قم بطلب كافة وظائف إضافة هذا المشروع في python بدون واجهة رسومية (قيد التطوير) ⭐PCI-Express لإعلام (PCI) | [وظائف] باللغة الطبيعية، قم بتنفيذ المِهام الأخرى في المشروع @@ -200,8 +200,8 @@ docker-compose up ``` "ترجمة سوبر الإنجليزية إلى العربية": { # البادئة، ستتم إضافتها قبل إدخالاتك. مثلاً، لوصف ما تريده مثل ترجمة أو شرح كود أو تلوين وهلم جرا - "بادئة": "يرجى ترجمة النص التالي إلى العربية ثم استخدم جدول Markdown لشرح المصطلحات المختصة المذكورة في النص:\n\n", - + "بادئة": "يرجى ترجمة النص التالي إلى العربية ثم استخدم جدول Markdown لشرح المصطلحات المختصة المذكورة في النص:\n\n", + # اللاحقة، سيتم إضافتها بعد إدخالاتك. يمكن استخدامها لوضع علامات اقتباس حول إدخالك. "لاحقة": "", }, @@ -341,4 +341,3 @@ https://github.com/oobabooga/one-click-installers # المزيد: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.English.md b/docs/README.English.md index f5632f35da32a422aee618c73163e7a9771d3429..48afdf4549f8f1a83927da857cd535a18e3e6f97 100644 --- a/docs/README.English.md +++ b/docs/README.English.md @@ -18,11 +18,11 @@ To translate this project to arbitrary language with GPT, read and run [`multi_l > 1.Please note that only plugins (buttons) highlighted in **bold** support reading files, and some plugins are located in the **dropdown menu** in the plugin area. Additionally, we welcome and process any new plugins with the **highest priority** through PRs. > > 2.The functionalities of each file in this project are described in detail in the [self-analysis report `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告). As the version iterates, you can also click on the relevant function plugin at any time to call GPT to regenerate the project's self-analysis report. Common questions are in the [`wiki`](https://github.com/binary-husky/gpt_academic/wiki). [Regular installation method](#installation) | [One-click installation script](https://github.com/binary-husky/gpt_academic/releases) | [Configuration instructions](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明). -> +> > 3.This project is compatible with and encourages the use of domestic large-scale language models such as ChatGLM. Multiple api-keys can be used together. You can fill in the configuration file with `API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"` to temporarily switch `API_KEY` during input, enter the temporary `API_KEY`, and then press enter to apply it. - +
@@ -126,7 +126,7 @@ python -m pip install -r requirements.txt # This step is the same as the pip ins 【Optional Step】If you need to support THU ChatGLM2 or Fudan MOSS as backends, you need to install additional dependencies (Prerequisites: Familiar with Python + Familiar with Pytorch + Sufficient computer configuration): ```sh # 【Optional Step I】Support THU ChatGLM2. Note: If you encounter the "Call ChatGLM fail unable to load ChatGLM parameters" error, refer to the following: 1. The default installation above is for torch+cpu version. To use cuda, uninstall torch and reinstall torch+cuda; 2. If the model cannot be loaded due to insufficient local configuration, you can modify the model accuracy in request_llm/bridge_chatglm.py. Change AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) to AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llms/requirements_chatglm.txt +python -m pip install -r request_llms/requirements_chatglm.txt # 【Optional Step II】Support Fudan MOSS python -m pip install -r request_llms/requirements_moss.txt @@ -204,8 +204,8 @@ For example: ``` "Super Translation": { # Prefix: will be added before your input. For example, used to describe your request, such as translation, code explanation, proofreading, etc. - "Prefix": "Please translate the following paragraph into Chinese and then explain each proprietary term in the text using a markdown table:\n\n", - + "Prefix": "Please translate the following paragraph into Chinese and then explain each proprietary term in the text using a markdown table:\n\n", + # Suffix: will be added after your input. For example, used to wrap your input in quotation marks along with the prefix. "Suffix": "", }, @@ -355,4 +355,3 @@ https://github.com/oobabooga/one-click-installers # More: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.French.md b/docs/README.French.md index dbd64caac4bde0ec7fa55bf541b5ccf0ec638542..bf136e59dc42f88b7303efc2cd98c12f55e4bced 100644 --- a/docs/README.French.md +++ b/docs/README.French.md @@ -2,9 +2,9 @@ > **Remarque** -> +> > Ce README a été traduit par GPT (implémenté par le plugin de ce projet) et n'est pas fiable à 100 %. Veuillez examiner attentivement les résultats de la traduction. -> +> > 7 novembre 2023 : Lors de l'installation des dépendances, veuillez choisir les versions **spécifiées** dans le fichier `requirements.txt`. Commande d'installation : `pip install -r requirements.txt`. @@ -12,7 +12,7 @@ **Si vous aimez ce projet, merci de lui donner une étoile ; si vous avez inventé des raccourcis ou des plugins utiles, n'hésitez pas à envoyer des demandes d'extraction !** -Si vous aimez ce projet, veuillez lui donner une étoile. +Si vous aimez ce projet, veuillez lui donner une étoile. Pour traduire ce projet dans une langue arbitraire avec GPT, lisez et exécutez [`multi_language.py`](multi_language.py) (expérimental). > **Remarque** @@ -22,7 +22,7 @@ Pour traduire ce projet dans une langue arbitraire avec GPT, lisez et exécutez > 2. Les fonctionnalités de chaque fichier de ce projet sont spécifiées en détail dans [le rapport d'auto-analyse `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic个项目自译解报告). Vous pouvez également cliquer à tout moment sur les plugins de fonctions correspondants pour appeler GPT et générer un rapport d'auto-analyse du projet. Questions fréquemment posées [wiki](https://github.com/binary-husky/gpt_academic/wiki). [Méthode d'installation standard](#installation) | [Script d'installation en un clic](https://github.com/binary-husky/gpt_academic/releases) | [Instructions de configuration](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明).. > > 3. Ce projet est compatible avec et recommande l'expérimentation de grands modèles de langage chinois tels que ChatGLM, etc. Prend en charge plusieurs clés API, vous pouvez les remplir dans le fichier de configuration comme `API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`. Pour changer temporairement la clé API, entrez la clé API temporaire dans la zone de saisie, puis appuyez sur Entrée pour soumettre et activer celle-ci. - +
@@ -128,7 +128,7 @@ python -m pip install -r requirements.txt # This step is the same as the pip ins [Optional Steps] If you need to support Tsinghua ChatGLM2/Fudan MOSS as backends, you need to install additional dependencies (Prerequisites: Familiar with Python + Have used PyTorch + Sufficient computer configuration): ```sh # [Optional Step I] Support Tsinghua ChatGLM2. Comment on this note: If you encounter the error "Call ChatGLM generated an error and cannot load the parameters of ChatGLM", refer to the following: 1: The default installation is the torch+cpu version. To use cuda, you need to uninstall torch and reinstall torch+cuda; 2: If the model cannot be loaded due to insufficient computer configuration, you can modify the model precision in request_llm/bridge_chatglm.py. Change AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) to AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True). -python -m pip install -r request_llms/requirements_chatglm.txt +python -m pip install -r request_llms/requirements_chatglm.txt # [Optional Step II] Support Fudan MOSS python -m pip install -r request_llms/requirements_moss.txt @@ -201,7 +201,7 @@ Par exemple: "Traduction avancée de l'anglais vers le français": { # Préfixe, ajouté avant votre saisie. Par exemple, utilisez-le pour décrire votre demande, telle que la traduction, l'explication du code, l'amélioration, etc. "Prefix": "Veuillez traduire le contenu suivant en français, puis expliquer chaque terme propre à la langue anglaise utilisé dans le texte à l'aide d'un tableau markdown : \n\n", - + # Suffixe, ajouté après votre saisie. Par exemple, en utilisant le préfixe, vous pouvez entourer votre contenu par des guillemets. "Suffix": "", }, @@ -354,4 +354,3 @@ https://github.com/oobabooga/one-click-installers # Plus: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.German.md b/docs/README.German.md index ffbcaacd17e3ddda35f6b3e919fd3ab274ebb8d2..87f7db5903d3bccabae8dbee97bfe274a1864946 100644 --- a/docs/README.German.md +++ b/docs/README.German.md @@ -2,9 +2,9 @@ > **Hinweis** -> -> Dieses README wurde mithilfe der GPT-Übersetzung (durch das Plugin dieses Projekts) erstellt und ist nicht zu 100 % zuverlässig. Bitte überprüfen Sie die Übersetzungsergebnisse sorgfältig. -> +> +> Dieses README wurde mithilfe der GPT-Übersetzung (durch das Plugin dieses Projekts) erstellt und ist nicht zu 100 % zuverlässig. Bitte überprüfen Sie die Übersetzungsergebnisse sorgfältig. +> > 7. November 2023: Beim Installieren der Abhängigkeiten bitte nur die in der `requirements.txt` **angegebenen Versionen** auswählen. Installationsbefehl: `pip install -r requirements.txt`. @@ -12,19 +12,19 @@ **Wenn Ihnen dieses Projekt gefällt, geben Sie ihm bitte einen Star. Wenn Sie praktische Tastenkombinationen oder Plugins entwickelt haben, sind Pull-Anfragen willkommen!** -Wenn Ihnen dieses Projekt gefällt, geben Sie ihm bitte einen Star. +Wenn Ihnen dieses Projekt gefällt, geben Sie ihm bitte einen Star. Um dieses Projekt mit GPT in eine beliebige Sprache zu übersetzen, lesen Sie [`multi_language.py`](multi_language.py) (experimentell). > **Hinweis** > > 1. Beachten Sie bitte, dass nur die mit **hervorgehobenen** Plugins (Schaltflächen) Dateien lesen können. Einige Plugins befinden sich im **Drop-down-Menü** des Plugin-Bereichs. Außerdem freuen wir uns über jede neue Plugin-PR mit **höchster Priorität**. -> +> > 2. Die Funktionen jeder Datei in diesem Projekt sind im [Selbstanalysebericht `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT-Academic-Selbstanalysebericht) ausführlich erläutert. Sie können jederzeit auf die relevanten Funktions-Plugins klicken und GPT aufrufen, um den Selbstanalysebericht des Projekts neu zu generieren. Häufig gestellte Fragen finden Sie im [`Wiki`](https://github.com/binary-husky/gpt_academic/wiki). [Standardinstallationsmethode](#installation) | [Ein-Klick-Installationsskript](https://github.com/binary-husky/gpt_academic/releases) | [Konfigurationsanleitung](https://github.com/binary-husky/gpt_academic/wiki/Projekt-Konfigurationsanleitung). -> +> > 3. Dieses Projekt ist kompatibel mit und unterstützt auch die Verwendung von inländischen Sprachmodellen wie ChatGLM. Die gleichzeitige Verwendung mehrerer API-Schlüssel ist möglich, indem Sie sie in der Konfigurationsdatei wie folgt angeben: `API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`. Wenn Sie den `API_KEY` vorübergehend ändern möchten, geben Sie vorübergehend den temporären `API_KEY` im Eingabebereich ein und drücken Sie die Eingabetaste, um die Änderung wirksam werden zu lassen. - +
@@ -93,7 +93,7 @@ Weitere Funktionen anzeigen (z. B. Bildgenerierung) …… | Siehe das Ende dies
# Installation -### Installation Method I: Run directly (Windows, Linux or MacOS) +### Installation Method I: Run directly (Windows, Linux or MacOS) 1. Download the project ```sh @@ -128,7 +128,7 @@ python -m pip install -r requirements.txt # This step is the same as installing [Optional] If you need to support Tsinghua ChatGLM2/Fudan MOSS as the backend, you need to install additional dependencies (Prerequisites: Familiar with Python + Have used PyTorch + Strong computer configuration): ```sh # [Optional Step I] Support Tsinghua ChatGLM2. Tsinghua ChatGLM note: If you encounter the error "Call ChatGLM fail cannot load ChatGLM parameters normally", refer to the following: 1: The default installation above is torch+cpu version. To use cuda, you need to uninstall torch and reinstall torch+cuda; 2: If you cannot load the model due to insufficient computer configuration, you can modify the model accuracy in request_llm/bridge_chatglm.py. Change AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) to AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llms/requirements_chatglm.txt +python -m pip install -r request_llms/requirements_chatglm.txt # [Optional Step II] Support Fudan MOSS python -m pip install -r request_llms/requirements_moss.txt @@ -207,8 +207,8 @@ Beispiel: ``` "Übersetzung von Englisch nach Chinesisch": { # Präfix, wird vor Ihrer Eingabe hinzugefügt. Zum Beispiel, um Ihre Anforderungen zu beschreiben, z.B. Übersetzen, Code erklären, verbessern usw. - "Präfix": "Bitte übersetzen Sie den folgenden Abschnitt ins Chinesische und erklären Sie dann jedes Fachwort in einer Markdown-Tabelle:\n\n", - + "Präfix": "Bitte übersetzen Sie den folgenden Abschnitt ins Chinesische und erklären Sie dann jedes Fachwort in einer Markdown-Tabelle:\n\n", + # Suffix, wird nach Ihrer Eingabe hinzugefügt. Zum Beispiel, um Ihre Eingabe in Anführungszeichen zu setzen. "Suffix": "", }, @@ -361,4 +361,3 @@ https://github.com/oobabooga/one-click-installers # Weitere: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.Italian.md b/docs/README.Italian.md index e5179f2d064e4248eef08f2b4226336bd8fede33..f231e49ff792cd9510a3115f2a9415b9400efd5d 100644 --- a/docs/README.Italian.md +++ b/docs/README.Italian.md @@ -12,7 +12,7 @@ **Se ti piace questo progetto, per favore dagli una stella; se hai idee o plugin utili, fai una pull request!** -Se ti piace questo progetto, dagli una stella. +Se ti piace questo progetto, dagli una stella. Per tradurre questo progetto in qualsiasi lingua con GPT, leggi ed esegui [`multi_language.py`](multi_language.py) (sperimentale). > **Nota** @@ -20,11 +20,11 @@ Per tradurre questo progetto in qualsiasi lingua con GPT, leggi ed esegui [`mult > 1. Fai attenzione che solo i plugin (pulsanti) **evidenziati** supportano la lettura dei file, alcuni plugin si trovano nel **menu a tendina** nell'area dei plugin. Inoltre, accogliamo e gestiamo con **massima priorità** qualsiasi nuovo plugin attraverso pull request. > > 2. Le funzioni di ogni file in questo progetto sono descritte in dettaglio nel [rapporto di traduzione automatica del progetto `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告). Con l'iterazione della versione, puoi anche fare clic sui plugin delle funzioni rilevanti in qualsiasi momento per richiamare GPT e rigenerare il rapporto di auto-analisi del progetto. Domande frequenti [`wiki`](https://github.com/binary-husky/gpt_academic/wiki) | [Metodo di installazione standard](#installazione) | [Script di installazione one-click](https://github.com/binary-husky/gpt_academic/releases) | [Configurazione](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明)。 -> +> > 3. Questo progetto è compatibile e incoraggia l'uso di modelli di linguaggio di grandi dimensioni nazionali, come ChatGLM. Supporto per la coesistenza di più chiavi API, puoi compilare nel file di configurazione come `API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`. Quando è necessario sostituire temporaneamente `API_KEY`, inserisci temporaneamente `API_KEY` nell'area di input e premi Invio per confermare. - +
@@ -128,7 +128,7 @@ python -m pip install -r requirements.txt # Questo passaggio è identico alla pr [Optional] Se desideri utilizzare ChatGLM2 di Tsinghua/Fudan MOSS come backend, è necessario installare ulteriori dipendenze (Requisiti: conoscenza di Python + esperienza con Pytorch + hardware potente): ```sh # [Optional Step I] Supporto per ChatGLM2 di Tsinghua. Note di ChatGLM di Tsinghua: Se si verifica l'errore "Call ChatGLM fail non può caricare i parametri di ChatGLM", fare riferimento a quanto segue: 1: L'installazione predefinita è la versione torch+cpu, per usare cuda è necessario disinstallare torch ed installare nuovamente la versione con torch+cuda; 2: Se il modello non può essere caricato a causa di una configurazione insufficiente, è possibile modificare la precisione del modello in request_llm/bridge_chatglm.py, sostituendo AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) con AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llms/requirements_chatglm.txt +python -m pip install -r request_llms/requirements_chatglm.txt # [Optional Step II] Supporto per Fudan MOSS python -m pip install -r request_llms/requirements_moss.txt @@ -206,8 +206,8 @@ Ad esempio, ``` "Traduzione avanzata Cinese-Inglese": { # Prefisso, sarà aggiunto prima del tuo input. Ad esempio, utilizzato per descrivere la tua richiesta, come traduzione, spiegazione del codice, rifinitura, ecc. - "Prefisso": "Si prega di tradurre il seguente testo in cinese e fornire spiegazione per i termini tecnici utilizzati, utilizzando una tabella in markdown uno per uno:\n\n", - + "Prefisso": "Si prega di tradurre il seguente testo in cinese e fornire spiegazione per i termini tecnici utilizzati, utilizzando una tabella in markdown uno per uno:\n\n", + # Suffisso, sarà aggiunto dopo il tuo input. Ad esempio, in combinazione con il prefisso, puoi circondare il tuo input con virgolette. "Suffisso": "", }, @@ -224,7 +224,7 @@ La scrittura di plugin per questo progetto è facile e richiede solo conoscenze # Aggiornamenti ### I: Aggiornamenti -1. Funzionalità di salvataggio della conversazione. Chiamare `Salva la conversazione corrente` nell'area del plugin per salvare la conversazione corrente come un file html leggibile e ripristinabile. +1. Funzionalità di salvataggio della conversazione. Chiamare `Salva la conversazione corrente` nell'area del plugin per salvare la conversazione corrente come un file html leggibile e ripristinabile. Inoltre, nella stessa area del plugin (menu a tendina) chiamare `Carica la cronologia della conversazione` per ripristinare una conversazione precedente. Suggerimento: fare clic su `Carica la cronologia della conversazione` senza specificare un file per visualizzare la tua cronologia di archiviazione HTML.
@@ -358,4 +358,3 @@ https://github.com/oobabooga/one-click-installers # Altre risorse: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.Japanese.md b/docs/README.Japanese.md index 983395b55639429ee66927440ba6e3912e835ec8..13cbdede24b3c716a0961b72331259ed081aab2b 100644 --- a/docs/README.Japanese.md +++ b/docs/README.Japanese.md @@ -2,9 +2,9 @@ > **注意** -> +> > 此READMEはGPTによる翻訳で生成されました(このプロジェクトのプラグインによって実装されています)、翻訳結果は100%正確ではないため、注意してください。 -> +> > 2023年11月7日: 依存関係をインストールする際は、`requirements.txt`で**指定されたバージョン**を選択してください。 インストールコマンド: `pip install -r requirements.txt`。 @@ -18,11 +18,11 @@ GPTを使用してこのプロジェクトを任意の言語に翻訳するに > 1. **強調された** プラグイン(ボタン)のみがファイルを読み込むことができることに注意してください。一部のプラグインは、プラグインエリアのドロップダウンメニューにあります。また、新しいプラグインのPRを歓迎し、最優先で対応します。 > > 2. このプロジェクトの各ファイルの機能は、[自己分析レポート`self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E5%A0%82)で詳しく説明されています。バージョンが進化するにつれて、関連する関数プラグインをクリックして、プロジェクトの自己分析レポートをGPTで再生成することもできます。よくある質問については、[`wiki`](https://github.com/binary-husky/gpt_academic/wiki)をご覧ください。[標準的なインストール方法](#installation) | [ワンクリックインストールスクリプト](https://github.com/binary-husky/gpt_academic/releases) | [構成の説明](https://github.com/binary-husky/gpt_academic/wiki/Project-Configuration-Explain)。 -> +> > 3. このプロジェクトは、[ChatGLM](https://www.chatglm.dev/)などの中国製の大規模言語モデルも互換性があり、試してみることを推奨しています。複数のAPIキーを共存させることができ、設定ファイルに`API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`のように記入できます。`API_KEY`を一時的に変更する必要がある場合は、入力エリアに一時的な`API_KEY`を入力し、Enterキーを押して提出すると有効になります。 - +
@@ -189,7 +189,7 @@ Python環境に詳しくないWindowsユーザーは、[リリース](https://gi "超级英译中": { # プレフィックス、入力の前に追加されます。例えば、要求を記述するために使用されます。翻訳、コードの解説、校正など "プレフィックス": "下記の内容を中国語に翻訳し、専門用語を一つずつマークダウンテーブルで解説してください:\n\n"、 - + # サフィックス、入力の後に追加されます。プレフィックスと一緒に使用して、入力内容を引用符で囲むことができます。 "サフィックス": ""、 }、 @@ -342,4 +342,3 @@ https://github.com/oobabooga/one-click-installers # その他: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.Korean.md b/docs/README.Korean.md index ebf8d4b9c4fa5eb8ff1a63c6ec067124ae3a5589..2bd1f577cfa10888016873a9befc64d63a23b287 100644 --- a/docs/README.Korean.md +++ b/docs/README.Korean.md @@ -27,7 +27,7 @@ GPT를 사용하여 이 프로젝트를 임의의 언어로 번역하려면 [`mu - +
@@ -130,7 +130,7 @@ python -m pip install -r requirements.txt # This step is the same as the pip ins [Optional Step] If you need support for Tsinghua ChatGLM2/Fudan MOSS as the backend, you need to install additional dependencies (Prerequisites: Familiar with Python + Have used Pytorch + Sufficient computer configuration): ```sh # [Optional Step I] Support for Tsinghua ChatGLM2. Note for Tsinghua ChatGLM: If you encounter the error "Call ChatGLM fail cannot load ChatGLM parameters", refer to the following: 1: The default installation above is torch+cpu version. To use cuda, uninstall torch and reinstall torch+cuda; 2: If you cannot load the model due to insufficient computer configuration, you can modify the model precision in request_llm/bridge_chatglm.py, change AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) to AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llms/requirements_chatglm.txt +python -m pip install -r request_llms/requirements_chatglm.txt # [Optional Step II] Support for Fudan MOSS python -m pip install -r request_llms/requirements_moss.txt @@ -208,8 +208,8 @@ Please visit the [cloud server remote deployment wiki](https://github.com/binary ``` "초급영문 번역": { # 접두사, 입력 내용 앞에 추가됩니다. 예를 들어 요구 사항을 설명하는 데 사용됩니다. 예를 들어 번역, 코드 설명, 교정 등 - "Prefix": "다음 내용을 한국어로 번역하고 전문 용어에 대한 설명을 적용한 마크다운 표를 사용하세요:\n\n", - + "Prefix": "다음 내용을 한국어로 번역하고 전문 용어에 대한 설명을 적용한 마크다운 표를 사용하세요:\n\n", + # 접미사, 입력 내용 뒤에 추가됩니다. 예를 들어 접두사와 함께 입력 내용을 따옴표로 감쌀 수 있습니다. "Suffix": "", }, @@ -361,4 +361,3 @@ https://github.com/oobabooga/one-click-installers # 더보기: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.Portuguese.md b/docs/README.Portuguese.md index 089465a6908db818e65a70f1a7af6535ddf11926..4cc02c19ebbb900c4424d60d680d654d4bc3fe8d 100644 --- a/docs/README.Portuguese.md +++ b/docs/README.Portuguese.md @@ -2,9 +2,9 @@ > **Nota** -> +> > Este README foi traduzido pelo GPT (implementado por um plugin deste projeto) e não é 100% confiável. Por favor, verifique cuidadosamente o resultado da tradução. -> +> > 7 de novembro de 2023: Ao instalar as dependências, favor selecionar as **versões especificadas** no `requirements.txt`. Comando de instalação: `pip install -r requirements.txt`. #
GPT Acadêmico
@@ -15,12 +15,12 @@ Para traduzir este projeto para qualquer idioma utilizando o GPT, leia e execute > **Nota** > > 1. Observe que apenas os plugins (botões) marcados em **destaque** são capazes de ler arquivos, alguns plugins estão localizados no **menu suspenso** do plugin area. Também damos boas-vindas e prioridade máxima a qualquer novo plugin via PR. -> +> > 2. As funcionalidades de cada arquivo deste projeto estão detalhadamente explicadas em [autoanálise `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告). Com a iteração das versões, você também pode clicar nos plugins de funções relevantes a qualquer momento para chamar o GPT para regerar o relatório de autonálise do projeto. Perguntas frequentes [`wiki`](https://github.com/binary-husky/gpt_academic/wiki) | [Método de instalação convencional](#installation) | [Script de instalação em um clique](https://github.com/binary-husky/gpt_academic/releases) | [Explicação de configuração](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明)。 > > 3. Este projeto é compatível e encoraja o uso de modelos de linguagem chineses, como ChatGLM. Vários api-keys podem ser usados simultaneamente, podendo ser especificados no arquivo de configuração como `API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`. Quando precisar alterar temporariamente o `API_KEY`, insira o `API_KEY` temporário na área de entrada e pressione Enter para que ele seja efetivo. - +
Funcionalidades (⭐= funcionalidade recentemente adicionada) | Descrição @@ -89,7 +89,7 @@ Apresentação de mais novas funcionalidades (geração de imagens, etc.) ... |
# Instalação -### Método de instalação I: Executar diretamente (Windows, Linux ou MacOS) +### Método de instalação I: Executar diretamente (Windows, Linux ou MacOS) 1. Baixe o projeto ```sh @@ -124,7 +124,7 @@ python -m pip install -r requirements.txt # Este passo é igual ao da instalaç [Opcional] Se você quiser suporte para o ChatGLM2 do THU/ MOSS do Fudan, precisará instalar dependências extras (pré-requisitos: familiarizado com o Python + já usou o PyTorch + o computador tem configuração suficiente): ```sh # [Opcional Passo I] Suporte para ChatGLM2 do THU. Observações sobre o ChatGLM2 do THU: Se você encontrar o erro "Call ChatGLM fail 不能正常加载ChatGLM的参数" (Falha ao chamar o ChatGLM, não é possível carregar os parâmetros do ChatGLM), consulte o seguinte: 1: A versão instalada por padrão é a versão torch+cpu. Se você quiser usar a versão cuda, desinstale o torch e reinstale uma versão com torch+cuda; 2: Se a sua configuração não for suficiente para carregar o modelo, você pode modificar a precisão do modelo em request_llm/bridge_chatglm.py, alterando todas as ocorrências de AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True) para AutoTokenizer.from_pretrained("THUDM/chatglm-6b-int4", trust_remote_code=True) -python -m pip install -r request_llms/requirements_chatglm.txt +python -m pip install -r request_llms/requirements_chatglm.txt # [Opcional Passo II] Suporte para MOSS do Fudan python -m pip install -r request_llms/requirements_moss.txt @@ -202,8 +202,8 @@ Por exemplo: ``` "超级英译中": { # Prefixo, adicionado antes do seu input. Por exemplo, usado para descrever sua solicitação, como traduzir, explicar o código, revisar, etc. - "Prefix": "Por favor, traduza o parágrafo abaixo para o chinês e explique cada termo técnico dentro de uma tabela markdown:\n\n", - + "Prefix": "Por favor, traduza o parágrafo abaixo para o chinês e explique cada termo técnico dentro de uma tabela markdown:\n\n", + # Sufixo, adicionado após o seu input. Por exemplo, em conjunto com o prefixo, pode-se colocar seu input entre aspas. "Suffix": "", }, @@ -355,4 +355,3 @@ https://github.com/oobabooga/instaladores-de-um-clique # Mais: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/README.Russian.md b/docs/README.Russian.md index 07ba098b0adafc603a396ba2acc55a85b8f39b1c..471f17449884c06a63bcd20905fd263c574bf869 100644 --- a/docs/README.Russian.md +++ b/docs/README.Russian.md @@ -2,9 +2,9 @@ > **Примечание** -> +> > Этот README был переведен с помощью GPT (реализовано с помощью плагина этого проекта) и не может быть полностью надежным, пожалуйста, внимательно проверьте результаты перевода. -> +> > 7 ноября 2023 года: При установке зависимостей, пожалуйста, выберите **указанные версии** из `requirements.txt`. Команда установки: `pip install -r requirements.txt`. @@ -17,12 +17,12 @@ > > 1. Пожалуйста, обратите внимание, что только плагины (кнопки), выделенные **жирным шрифтом**, поддерживают чтение файлов, некоторые плагины находятся в выпадающем меню **плагинов**. Кроме того, мы с радостью приветствуем и обрабатываем PR для любых новых плагинов с **наивысшим приоритетом**. > -> 2. Функции каждого файла в этом проекте подробно описаны в [отчете о самостоятельном анализе проекта `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告). С каждым новым релизом вы также можете в любое время нажать на соответствующий функциональный плагин, вызвать GPT для повторной генерации сводного отчета о самоанализе проекта. Часто задаваемые вопросы [`wiki`](https://github.com/binary-husky/gpt_academic/wiki) | [обычные методы установки](#installation) | [скрипт одношаговой установки](https://github.com/binary-husky/gpt_academic/releases) | [инструкции по настройке](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明). +> 2. Функции каждого файла в этом проекте подробно описаны в [отчете о самостоятельном анализе проекта `self_analysis.md`](https://github.com/binary-husky/gpt_academic/wiki/GPT‐Academic项目自译解报告). С каждым новым релизом вы также можете в любое время нажать на соответствующий функциональный плагин, вызвать GPT для повторной генерации сводного отчета о самоанализе проекта. Часто задаваемые вопросы [`wiki`](https://github.com/binary-husky/gpt_academic/wiki) | [обычные методы установки](#installation) | [скрипт одношаговой установки](https://github.com/binary-husky/gpt_academic/releases) | [инструкции по настройке](https://github.com/binary-husky/gpt_academic/wiki/项目配置说明). > > 3. Этот проект совместим и настоятельно рекомендуется использование китайской NLP-модели ChatGLM и других моделей больших языков производства Китая. Поддерживает одновременное использование нескольких ключей API, которые можно указать в конфигурационном файле, например, `API_KEY="openai-key1,openai-key2,azure-key3,api2d-key4"`. Если нужно временно заменить `API_KEY`, введите временный `API_KEY` в окне ввода и нажмите Enter для его подтверждения. - +
@@ -204,8 +204,8 @@ docker-compose up ``` "Супер-англо-русский перевод": { # Префикс, который будет добавлен перед вашим вводом. Например, используется для описания вашего запроса, например, перевода, объяснения кода, редактирования и т.д. - "Префикс": "Пожалуйста, переведите следующий абзац на русский язык, а затем покажите каждый термин на экране с помощью таблицы Markdown:\n\n", - + "Префикс": "Пожалуйста, переведите следующий абзац на русский язык, а затем покажите каждый термин на экране с помощью таблицы Markdown:\n\n", + # Суффикс, который будет добавлен после вашего ввода. Например, можно использовать с префиксом, чтобы заключить ваш ввод в кавычки. "Суффикс": "", }, @@ -335,7 +335,7 @@ GPT Academic Группа QQ разработчиков: `610599535` ``` В коде использовались многие функции, представленные в других отличных проектах, поэтому их порядок не имеет значения: -# ChatGLM2-6B от Тиньхуа: +# ChatGLM2-6B от Тиньхуа: https://github.com/THUDM/ChatGLM2-6B # Линейные модели с ограниченной памятью от Тиньхуа: @@ -358,4 +358,3 @@ https://github.com/oobabooga/one-click-installers # Больше: https://github.com/gradio-app/gradio https://github.com/fghrsh/live2d_demo - diff --git a/docs/WithFastapi.md b/docs/WithFastapi.md index bbbb386e8ad280c5037ffcf2feb4d0280e69d225..270375076a6d0cdae568180c48a619a40f3c0ccd 100644 --- a/docs/WithFastapi.md +++ b/docs/WithFastapi.md @@ -17,18 +17,18 @@ nano config.py - # 如果需要在二级路径下运行 - # CUSTOM_PATH = get_conf('CUSTOM_PATH') - - # if CUSTOM_PATH != "/": + - # if CUSTOM_PATH != "/": - # from toolbox import run_gradio_in_subpath - # run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH) - - # else: + - # else: - # demo.launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png") + 如果需要在二级路径下运行 + CUSTOM_PATH = get_conf('CUSTOM_PATH') - + if CUSTOM_PATH != "/": + + if CUSTOM_PATH != "/": + from toolbox import run_gradio_in_subpath + run_gradio_in_subpath(demo, auth=AUTHENTICATION, port=PORT, custom_path=CUSTOM_PATH) - + else: + + else: + demo.launch(server_name="0.0.0.0", server_port=PORT, auth=AUTHENTICATION, favicon_path="docs/logo.png") if __name__ == "__main__": diff --git a/docs/test_markdown_format.py b/docs/test_markdown_format.py index 896f6f130c69f8a94d6f49feadf7091f0f23c2c9..8255478474a379fafd43a40278e6a8e802aae4f0 100644 --- a/docs/test_markdown_format.py +++ b/docs/test_markdown_format.py @@ -7,13 +7,27 @@ sample = """ """ import re + def preprocess_newbing_out(s): - pattern = r'\^(\d+)\^' # 匹配^数字^ - pattern2 = r'\[(\d+)\]' # 匹配^数字^ - sub = lambda m: '\['+m.group(1)+'\]' # 将匹配到的数字作为替换值 - result = re.sub(pattern, sub, s) # 替换操作 - if '[1]' in result: - result += '


' + "
".join([re.sub(pattern2, sub, r) for r in result.split('\n') if r.startswith('[')]) + '
' + pattern = r"\^(\d+)\^" # 匹配^数字^ + pattern2 = r"\[(\d+)\]" # 匹配^数字^ + + def sub(m): + return "\\[" + m.group(1) + "\\]" # 将匹配到的数字作为替换值 + + result = re.sub(pattern, sub, s) # 替换操作 + if "[1]" in result: + result += ( + '


' + + "
".join( + [ + re.sub(pattern2, sub, r) + for r in result.split("\n") + if r.startswith("[") + ] + ) + + "
" + ) return result @@ -28,37 +42,39 @@ def close_up_code_segment_during_stream(gpt_reply): str: 返回一个新的字符串,将输出代码片段的“后面的```”补上。 """ - if '```' not in gpt_reply: + if "```" not in gpt_reply: return gpt_reply - if gpt_reply.endswith('```'): + if gpt_reply.endswith("```"): return gpt_reply # 排除了以上两个情况,我们 - segments = gpt_reply.split('```') + segments = gpt_reply.split("```") n_mark = len(segments) - 1 if n_mark % 2 == 1: # print('输出代码片段中!') - return gpt_reply+'\n```' + return gpt_reply + "\n```" else: return gpt_reply - + + import markdown from latex2mathml.converter import convert as tex2mathml -from functools import wraps, lru_cache + + def markdown_convertion(txt): """ 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。 """ pre = '
' - suf = '
' + suf = "
" if txt.startswith(pre) and txt.endswith(suf): # print('警告,输入了已经经过转化的字符串,二次转化可能出问题') - return txt # 已经被转化过,不需要再次转化 - + return txt # 已经被转化过,不需要再次转化 + markdown_extension_configs = { - 'mdx_math': { - 'enable_dollar_delimiter': True, - 'use_gitlab_delimiters': False, + "mdx_math": { + "enable_dollar_delimiter": True, + "use_gitlab_delimiters": False, }, } find_equation_pattern = r'\n', '') + content = content.replace( + '\n", "") return content - - if ('$' in txt) and ('```' not in txt): # 有$标识的公式符号,且没有代码段```的标识 + if ("$" in txt) and ("```" not in txt): # 有$标识的公式符号,且没有代码段```的标识 # convert everything to html format - split = markdown.markdown(text='---') - convert_stage_1 = markdown.markdown(text=txt, extensions=['mdx_math', 'fenced_code', 'tables', 'sane_lists'], extension_configs=markdown_extension_configs) + split = markdown.markdown(text="---") + convert_stage_1 = markdown.markdown( + text=txt, + extensions=["mdx_math", "fenced_code", "tables", "sane_lists"], + extension_configs=markdown_extension_configs, + ) convert_stage_1 = markdown_bug_hunt(convert_stage_1) # re.DOTALL: Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Corresponds to the inline flag (?s). # 1. convert to easy-to-copy tex (do not render math) - convert_stage_2_1, n = re.subn(find_equation_pattern, replace_math_no_render, convert_stage_1, flags=re.DOTALL) + convert_stage_2_1, n = re.subn( + find_equation_pattern, + replace_math_no_render, + convert_stage_1, + flags=re.DOTALL, + ) # 2. convert to rendered equation - convert_stage_2_2, n = re.subn(find_equation_pattern, replace_math_render, convert_stage_1, flags=re.DOTALL) + convert_stage_2_2, n = re.subn( + find_equation_pattern, replace_math_render, convert_stage_1, flags=re.DOTALL + ) # cat them together - return pre + convert_stage_2_1 + f'{split}' + convert_stage_2_2 + suf + return pre + convert_stage_2_1 + f"{split}" + convert_stage_2_2 + suf else: - return pre + markdown.markdown(txt, extensions=['fenced_code', 'codehilite', 'tables', 'sane_lists']) + suf + return ( + pre + + markdown.markdown( + txt, extensions=["fenced_code", "codehilite", "tables", "sane_lists"] + ) + + suf + ) sample = preprocess_newbing_out(sample) sample = close_up_code_segment_during_stream(sample) sample = markdown_convertion(sample) -with open('tmp.html', 'w', encoding='utf8') as f: - f.write(""" +with open("tmp.html", "w", encoding="utf8") as f: + f.write( + """ My Website - """) + """ + ) f.write(sample) diff --git a/docs/translate_japanese.json b/docs/translate_japanese.json index 2f80792c4eecbaf60d3a2c4c12c8b378dd891a90..142e4a69e0e245348cee359e0d5b309ca0d0cc5b 100644 --- a/docs/translate_japanese.json +++ b/docs/translate_japanese.json @@ -2106,4 +2106,4 @@ "改变输入参数的顺序与结构": "入力パラメータの順序と構造を変更する", "正在精细切分latex文件": "LaTeXファイルを細かく分割しています", "读取文件": "ファイルを読み込んでいます" -} \ No newline at end of file +} diff --git a/docs/translate_std.json b/docs/translate_std.json index ee8b2c69a312d275e34b4bc137d8f653079303c0..961e595bc4a979737d7acd93a0b3788133481e77 100644 --- a/docs/translate_std.json +++ b/docs/translate_std.json @@ -98,4 +98,4 @@ "图片生成_DALLE2": "ImageGeneration_DALLE2", "图片生成_DALLE3": "ImageGeneration_DALLE3", "图片修改_DALLE2": "ImageModification_DALLE2" -} \ No newline at end of file +} diff --git a/docs/use_audio.md b/docs/use_audio.md index b461f58ac78ae27b94ec8ad4ccacb81ed760b55b..337c786820d3c02bfe4cae4911cac34615d8f006 100644 --- a/docs/use_audio.md +++ b/docs/use_audio.md @@ -61,4 +61,3 @@ VI 两种音频监听模式切换时,需要刷新页面才有效。 VII 非localhost运行+非https情况下无法打开录音功能的坑:https://blog.csdn.net/weixin_39461487/article/details/109594434 ## 5.点击函数插件区“实时音频采集” 或者其他音频交互功能 - diff --git a/docs/waifu_plugin/autoload.js b/docs/waifu_plugin/autoload.js index 3464a5cd44b0d4e1b0f2528bd01fc1793275b964..d0648770b6d18512bfa4310508445e76cf72c11a 100644 --- a/docs/waifu_plugin/autoload.js +++ b/docs/waifu_plugin/autoload.js @@ -8,8 +8,8 @@ try { live2d_settings['modelId'] = 5; // 默认模型 ID live2d_settings['modelTexturesId'] = 1; // 默认材质 ID live2d_settings['modelStorage'] = false; // 不储存模型 ID - live2d_settings['waifuSize'] = '210x187'; - live2d_settings['waifuTipsSize'] = '187x52'; + live2d_settings['waifuSize'] = '210x187'; + live2d_settings['waifuTipsSize'] = '187x52'; live2d_settings['canSwitchModel'] = true; live2d_settings['canSwitchTextures'] = true; live2d_settings['canSwitchHitokoto'] = false; diff --git a/docs/waifu_plugin/flat-ui-icons-regular.svg b/docs/waifu_plugin/flat-ui-icons-regular.svg index cb2727cac3c0f52b7370e851a1e2f3092ad76d1a..e05f3a0d31e417b72be11d5935cbb201729085dc 100644 --- a/docs/waifu_plugin/flat-ui-icons-regular.svg +++ b/docs/waifu_plugin/flat-ui-icons-regular.svg @@ -123,4 +123,4 @@ - \ No newline at end of file + diff --git a/docs/waifu_plugin/jquery-ui.min.js b/docs/waifu_plugin/jquery-ui.min.js index 25398a167415050ae8bfb0bfebac6aa3ab790909..862a649869db80cb6c8cd6d48f63ee0b56169a2c 100644 --- a/docs/waifu_plugin/jquery-ui.min.js +++ b/docs/waifu_plugin/jquery-ui.min.js @@ -10,4 +10,4 @@ this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=t },_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.lefti[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=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("
").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("
"),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.maxWidtht.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("
"),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("
").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("
"),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({label:t("").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("").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(" ")},_createButtonPane:function(){this.uiDialogButtonPane=t("
"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("
").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("",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("").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("
").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("
").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("
").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("
").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("
"),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:"",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("").parent().append("")},_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""},_buttonHtml:function(){return""}}),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("
").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("").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("
").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("
").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("
").attr("role","tooltip"),s=t("
").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}); \ No newline at end of file +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:"",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("").parent().append("")},_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""},_buttonHtml:function(){return""}}),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("
").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("").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("
").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("
").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("
").attr("role","tooltip"),s=t("
").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}); diff --git a/docs/waifu_plugin/source b/docs/waifu_plugin/source index 7201fd631355230715b825c8046718da50c2c75c..82d2ed01245d9ab6a6d70576398b96286b24790d 100644 --- a/docs/waifu_plugin/source +++ b/docs/waifu_plugin/source @@ -1 +1 @@ -https://github.com/fghrsh/live2d_demo \ No newline at end of file +https://github.com/fghrsh/live2d_demo diff --git a/docs/waifu_plugin/waifu-tips.js b/docs/waifu_plugin/waifu-tips.js index d1b214d7e26bd2ea429f35af2ff87f6f3d74f526..6ae98395a14239861fbc8250d190971e34590434 100644 --- a/docs/waifu_plugin/waifu-tips.js +++ b/docs/waifu_plugin/waifu-tips.js @@ -5,11 +5,11 @@ window.live2d_settings = Array(); /*       /`ー'    L//`ヽ、 Live2D 看板娘 参数设置      /  /,  /|  ,  ,    ', Version 1.4.2    イ  / /-‐/ i L_ ハ ヽ!  i Update 2018.11.12 -     レ ヘ 7イ`ト  レ'ァ-ト、!ハ|  | +     レ ヘ 7イ`ト  レ'ァ-ト、!ハ|  |      !,/7 '0'   ´0iソ|   |         |.从"  _   ,,,, / |./   | 网页添加 Live2D 看板娘      レ'| i>.、,,__ _,.イ /  .i  | https://www.fghrsh.net/post/123.html -       レ'| | / k_7_/レ'ヽ, ハ. | +       レ'| | / k_7_/レ'ヽ, ハ. |        | |/i 〈|/  i ,.ヘ | i | Thanks       .|/ / i:   ヘ!  \ | journey-ad / https://github.com/journey-ad/live2d_src         kヽ>、ハ   _,.ヘ、   /、! xiazeyu / https://github.com/xiazeyu/live2d-widget.js @@ -77,11 +77,11 @@ String.prototype.render = function(context) { return this.replace(tokenReg, function (word, slash1, token, slash2) { if (slash1 || slash2) { return word.replace('\\', ''); } - + var variables = token.replace(/\s/g, '').split('.'); var currentObject = context; var i, length, variable; - + for (i = 0, length = variables.length; i < length; ++i) { variable = variables[i]; currentObject = currentObject[variable]; @@ -101,9 +101,9 @@ function showMessage(text, timeout, flag) { if(flag || sessionStorage.getItem('waifu-text') === '' || sessionStorage.getItem('waifu-text') === null){ if(Array.isArray(text)) text = text[Math.floor(Math.random() * text.length + 1)-1]; if (live2d_settings.showF12Message) console.log('[Message]', text.replace(/<[^<>]+>/g,'')); - + if(flag) sessionStorage.setItem('waifu-text', text); - + $('.waifu-tips').stop(); $('.waifu-tips').html(text).fadeTo(200, 1); if (timeout === undefined) timeout = 5000; @@ -121,15 +121,15 @@ function hideMessage(timeout) { function initModel(waifuPath, type) { /* console welcome message */ eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('8.d(" ");8.d("\\U,.\\y\\5.\\1\\1\\1\\1/\\1,\\u\\2 \\H\\n\\1\\1\\1\\1\\1\\b \', !-\\r\\j-i\\1/\\1/\\g\\n\\1\\1\\1 \\1 \\a\\4\\f\'\\1\\1\\1 L/\\a\\4\\5\\2\\n\\1\\1 \\1 /\\1 \\a,\\1 /|\\1 ,\\1 ,\\1\\1\\1 \',\\n\\1\\1\\1\\q \\1/ /-\\j/\\1\\h\\E \\9 \\5!\\1 i\\n\\1\\1\\1 \\3 \\6 7\\q\\4\\c\\1 \\3\'\\s-\\c\\2!\\t|\\1 |\\n\\1\\1\\1\\1 !,/7 \'0\'\\1\\1 \\X\\w| \\1 |\\1\\1\\1\\n\\1\\1\\1\\1 |.\\x\\"\\1\\l\\1\\1 ,,,, / |./ \\1 |\\n\\1\\1\\1\\1 \\3\'| i\\z.\\2,,A\\l,.\\B / \\1.i \\1|\\n\\1\\1\\1\\1\\1 \\3\'| | / C\\D/\\3\'\\5,\\1\\9.\\1|\\n\\1\\1\\1\\1\\1\\1 | |/i \\m|/\\1 i\\1,.\\6 |\\F\\1|\\n\\1\\1\\1\\1\\1\\1.|/ /\\1\\h\\G \\1 \\6!\\1\\1\\b\\1|\\n\\1\\1\\1 \\1 \\1 k\\5>\\2\\9 \\1 o,.\\6\\2 \\1 /\\2!\\n\\1\\1\\1\\1\\1\\1 !\'\\m//\\4\\I\\g\', \\b \\4\'7\'\\J\'\\n\\1\\1\\1\\1\\1\\1 \\3\'\\K|M,p,\\O\\3|\\P\\n\\1\\1\\1\\1\\1 \\1\\1\\1\\c-,/\\1|p./\\n\\1\\1\\1\\1\\1 \\1\\1\\1\'\\f\'\\1\\1!o,.:\\Q \\R\\S\\T v"+e.V+" / W "+e.N);8.d(" ");',60,60,'|u3000|uff64|uff9a|uff40|u30fd|uff8d||console|uff8a|uff0f|uff3c|uff84|log|live2d_settings|uff70|u00b4|uff49||u2010||u3000_|u3008||_|___|uff72|u2500|uff67|u30cf|u30fc||u30bd|u4ece|u30d8|uff1e|__|u30a4|k_|uff17_|u3000L_|u3000i|uff1a|u3009|uff34|uff70r|u30fdL__||___i|l2dVerDate|u30f3|u30ce|nLive2D|u770b|u677f|u5a18|u304f__|l2dVersion|FGHRSH|u00b40i'.split('|'),0,{})); - + /* 判断 JQuery */ if (typeof($.ajax) != 'function') typeof(jQuery.ajax) == 'function' ? window.$ = jQuery : console.log('[Error] JQuery is not defined.'); - + /* 加载看板娘样式 */ live2d_settings.waifuSize = live2d_settings.waifuSize.split('x'); live2d_settings.waifuTipsSize = live2d_settings.waifuTipsSize.split('x'); live2d_settings.waifuEdgeSide = live2d_settings.waifuEdgeSide.split(':'); - + $("#live2d").attr("width",live2d_settings.waifuSize[0]); $("#live2d").attr("height",live2d_settings.waifuSize[1]); $(".waifu-tips").width(live2d_settings.waifuTipsSize[0]); @@ -138,32 +138,32 @@ function initModel(waifuPath, type) { $(".waifu-tips").css("font-size",live2d_settings.waifuFontSize); $(".waifu-tool").css("font-size",live2d_settings.waifuToolFont); $(".waifu-tool span").css("line-height",live2d_settings.waifuToolLine); - + if (live2d_settings.waifuEdgeSide[0] == 'left') $(".waifu").css("left",live2d_settings.waifuEdgeSide[1]+'px'); else if (live2d_settings.waifuEdgeSide[0] == 'right') $(".waifu").css("right",live2d_settings.waifuEdgeSide[1]+'px'); - + window.waifuResize = function() { $(window).width() <= Number(live2d_settings.waifuMinWidth.replace('px','')) ? $(".waifu").hide() : $(".waifu").show(); }; if (live2d_settings.waifuMinWidth != 'disable') { waifuResize(); $(window).resize(function() {waifuResize()}); } - + try { if (live2d_settings.waifuDraggable == 'axis-x') $(".waifu").draggable({ axis: "x", revert: live2d_settings.waifuDraggableRevert }); else if (live2d_settings.waifuDraggable == 'unlimited') $(".waifu").draggable({ revert: live2d_settings.waifuDraggableRevert }); else $(".waifu").css("transition", 'all .3s ease-in-out'); } catch(err) { console.log('[Error] JQuery UI is not defined.') } - + live2d_settings.homePageUrl = live2d_settings.homePageUrl == 'auto' ? window.location.protocol+'//'+window.location.hostname+'/' : live2d_settings.homePageUrl; if (window.location.protocol == 'file:' && live2d_settings.modelAPI.substr(0,2) == '//') live2d_settings.modelAPI = 'http:'+live2d_settings.modelAPI; - + $('.waifu-tool .fui-home').click(function (){ //window.location = 'https://www.fghrsh.net/'; window.location = live2d_settings.homePageUrl; }); - + $('.waifu-tool .fui-info-circle').click(function (){ //window.open('https://imjad.cn/archives/lab/add-dynamic-poster-girl-with-live2d-to-your-blog-02'); window.open(live2d_settings.aboutPageUrl); }); - + if (typeof(waifuPath) == "object") loadTipsMessage(waifuPath); else { $.ajax({ cache: true, @@ -172,7 +172,7 @@ function initModel(waifuPath, type) { success: function (result){ loadTipsMessage(result); } }); } - + if (!live2d_settings.showToolMenu) $('.waifu-tool').hide(); if (!live2d_settings.canCloseLive2d) $('.waifu-tool .fui-cross').hide(); if (!live2d_settings.canSwitchModel) $('.waifu-tool .fui-eye').hide(); @@ -185,7 +185,7 @@ function initModel(waifuPath, type) { if (waifuPath === undefined) waifuPath = ''; var modelId = localStorage.getItem('modelId'); var modelTexturesId = localStorage.getItem('modelTexturesId'); - + if (!live2d_settings.modelStorage || modelId == null) { var modelId = live2d_settings.modelId; var modelTexturesId = live2d_settings.modelTexturesId; @@ -204,7 +204,7 @@ function loadModel(modelId, modelTexturesId=0) { function loadTipsMessage(result) { window.waifu_tips = result; - + $.each(result.mouseover, function (index, tips){ $(document).on("mouseover", tips.selector, function (){ var text = getRandText(tips.text); @@ -223,50 +223,50 @@ function loadTipsMessage(result) { var now = new Date(); var after = tips.date.split('-')[0]; var before = tips.date.split('-')[1] || after; - - if((after.split('/')[0] <= now.getMonth()+1 && now.getMonth()+1 <= before.split('/')[0]) && + + if((after.split('/')[0] <= now.getMonth()+1 && now.getMonth()+1 <= before.split('/')[0]) && (after.split('/')[1] <= now.getDate() && now.getDate() <= before.split('/')[1])){ var text = getRandText(tips.text); text = text.render({year: now.getFullYear()}); showMessage(text, 6000, true); } }); - + if (live2d_settings.showF12OpenMsg) { re.toString = function() { showMessage(getRandText(result.waifu.console_open_msg), 5000, true); return ''; }; } - + if (live2d_settings.showCopyMessage) { $(document).on('copy', function() { showMessage(getRandText(result.waifu.copy_message), 5000, true); }); } - + $('.waifu-tool .fui-photo').click(function(){ showMessage(getRandText(result.waifu.screenshot_message), 5000, true); window.Live2D.captureName = live2d_settings.screenshotCaptureName; window.Live2D.captureFrame = true; }); - + $('.waifu-tool .fui-cross').click(function(){ sessionStorage.setItem('waifu-dsiplay', 'none'); showMessage(getRandText(result.waifu.hidden_message), 1300, true); window.setTimeout(function() {$('.waifu').hide();}, 1300); }); - + window.showWelcomeMessage = function(result) { showMessage('欢迎使用GPT-Academic', 6000); }; if (live2d_settings.showWelcomeMessage) showWelcomeMessage(result); - + var waifu_tips = result.waifu; - + function loadOtherModel() { var modelId = modelStorageGetItem('modelId'); var modelRandMode = live2d_settings.modelRandMode; - + $.ajax({ cache: modelRandMode == 'switch' ? true : false, url: live2d_settings.modelAPI+modelRandMode+'/?id='+modelId, @@ -279,12 +279,12 @@ function loadTipsMessage(result) { } }); } - + function loadRandTextures() { var modelId = modelStorageGetItem('modelId'); var modelTexturesId = modelStorageGetItem('modelTexturesId'); var modelTexturesRandMode = live2d_settings.modelTexturesRandMode; - + $.ajax({ cache: modelTexturesRandMode == 'switch' ? true : false, url: live2d_settings.modelAPI+modelTexturesRandMode+'_textures/?id='+modelId+'-'+modelTexturesId, @@ -297,32 +297,32 @@ function loadTipsMessage(result) { } }); } - + function modelStorageGetItem(key) { return live2d_settings.modelStorage ? localStorage.getItem(key) : sessionStorage.getItem(key); } - + /* 检测用户活动状态,并在空闲时显示一言 */ if (live2d_settings.showHitokoto) { window.getActed = false; window.hitokotoTimer = 0; window.hitokotoInterval = false; $(document).mousemove(function(e){getActed = true;}).keydown(function(){getActed = true;}); setInterval(function(){ if (!getActed) ifActed(); else elseActed(); }, 1000); } - + function ifActed() { if (!hitokotoInterval) { hitokotoInterval = true; hitokotoTimer = window.setInterval(showHitokotoActed, 30000); } } - + function elseActed() { getActed = hitokotoInterval = false; window.clearInterval(hitokotoTimer); } - + function showHitokotoActed() { if ($(document)[0].visibilityState == 'visible') showHitokoto(); } - + function showHitokoto() { switch(live2d_settings.hitokotoAPI) { case 'lwl12.com': @@ -366,7 +366,7 @@ function loadTipsMessage(result) { }); } } - + $('.waifu-tool .fui-eye').click(function (){loadOtherModel()}); $('.waifu-tool .fui-user').click(function (){loadRandTextures()}); $('.waifu-tool .fui-chat').click(function (){showHitokoto()}); diff --git a/docs/waifu_plugin/waifu-tips.json b/docs/waifu_plugin/waifu-tips.json index 30f263153f3c20e10a1a28b35490fd4307f9595d..c7d84e3e6835a3d0926c3a4539bd223affd0265c 100644 --- a/docs/waifu_plugin/waifu-tips.json +++ b/docs/waifu_plugin/waifu-tips.json @@ -31,7 +31,7 @@ }, "model_message": { "1": ["来自 Potion Maker 的 Pio 酱 ~"], - "2": ["来自 Potion Maker 的 Tia 酱 ~"] + "2": ["来自 Potion Maker 的 Tia 酱 ~"] }, "hitokoto_api_message": { "lwl12.com": ["这句一言来自 『{source}』", ",是 {creator} 投稿的", "。"], @@ -111,4 +111,4 @@ { "date": "11/05-11/12", "text": ["今年的双十一是和谁一起过的呢~"] }, { "date": "12/20-12/31", "text": ["这几天是圣诞节,主人肯定又去剁手买买买了~"] } ] -} \ No newline at end of file +} diff --git a/docs/waifu_plugin/waifu.css b/docs/waifu_plugin/waifu.css index 42639df0794e46fc58f66e2c772e2bf9ba605eed..0a50344d79a66972067476f308a1544968e00a40 100644 --- a/docs/waifu_plugin/waifu.css +++ b/docs/waifu_plugin/waifu.css @@ -287,4 +287,4 @@ } .fui-user:before { content: "\e631"; -} \ No newline at end of file +} diff --git a/multi_language.py b/multi_language.py index a807dbd09feaab4601ee0050b97bf3359a58dd79..c65872aa08a0b0088d94467054594c422978ca38 100644 --- a/multi_language.py +++ b/multi_language.py @@ -352,9 +352,9 @@ def step_1_core_key_translate(): chinese_core_keys_norepeat_mapping.update({k:cached_translation[k]}) chinese_core_keys_norepeat_mapping = dict(sorted(chinese_core_keys_norepeat_mapping.items(), key=lambda x: -len(x[0]))) - # =============================================== + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # copy - # =============================================== + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- def copy_source_code(): from toolbox import get_conf @@ -367,9 +367,9 @@ def step_1_core_key_translate(): shutil.copytree('./', backup_dir, ignore=lambda x, y: blacklist) copy_source_code() - # =============================================== + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # primary key replace - # =============================================== + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- directory_path = f'./multi-language/{LANG}/' for root, dirs, files in os.walk(directory_path): for file in files: @@ -389,9 +389,9 @@ def step_1_core_key_translate(): def step_2_core_key_translate(): - # ================================================================================================= + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # step2 - # ================================================================================================= + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= def load_string(strings, string_input): string_ = string_input.strip().strip(',').strip().strip('.').strip() @@ -492,9 +492,9 @@ def step_2_core_key_translate(): cached_translation.update(read_map_from_json(language=LANG_STD)) cached_translation = dict(sorted(cached_translation.items(), key=lambda x: -len(x[0]))) - # =============================================== + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # literal key replace - # =============================================== + # =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- directory_path = f'./multi-language/{LANG}/' for root, dirs, files in os.walk(directory_path): for file in files: diff --git a/request_llms/README.md b/request_llms/README.md index 288bc1352e0e85ce56f569f3a5e6685d279e1565..5a51592ab8751bed5583532c8d552ba492c54c86 100644 --- a/request_llms/README.md +++ b/request_llms/README.md @@ -32,4 +32,4 @@ P.S. 如果您按照以下步骤成功接入了新的大模型,欢迎发Pull R 5. 测试通过后,在`request_llms/bridge_all.py`中做最后的修改,把你的模型完全接入到框架中(聪慧如您,只需要看一眼该文件就明白怎么修改了) -6. 修改`LLM_MODEL`配置,然后运行`python main.py`,测试最后的效果 \ No newline at end of file +6. 修改`LLM_MODEL`配置,然后运行`python main.py`,测试最后的效果 diff --git a/request_llms/bridge_all.py b/request_llms/bridge_all.py index 689b1f97c64731a95637f17e9a0e2090e86484ce..c19691e8744249d4bef28eceb72dc07b4f2a97fe 100644 --- a/request_llms/bridge_all.py +++ b/request_llms/bridge_all.py @@ -28,6 +28,9 @@ from .bridge_chatglm3 import predict as chatglm3_ui from .bridge_qianfan import predict_no_ui_long_connection as qianfan_noui from .bridge_qianfan import predict as qianfan_ui +from .bridge_google_gemini import predict as genai_ui +from .bridge_google_gemini import predict_no_ui_long_connection as genai_noui + colors = ['#FF00FF', '#00FFFF', '#FF0000', '#990099', '#009999', '#990044'] class LazyloadTiktoken(object): @@ -246,6 +249,22 @@ model_info = { "tokenizer": tokenizer_gpt35, "token_cnt": get_token_num_gpt35, }, + "gemini-pro": { + "fn_with_ui": genai_ui, + "fn_without_ui": genai_noui, + "endpoint": None, + "max_token": 1024 * 32, + "tokenizer": tokenizer_gpt35, + "token_cnt": get_token_num_gpt35, + }, + "gemini-pro-vision": { + "fn_with_ui": genai_ui, + "fn_without_ui": genai_noui, + "endpoint": None, + "max_token": 1024 * 32, + "tokenizer": tokenizer_gpt35, + "token_cnt": get_token_num_gpt35, + }, } # -=-=-=-=-=-=- api2d 对齐支持 -=-=-=-=-=-=- @@ -479,22 +498,6 @@ if "qwen-turbo" in AVAIL_LLM_MODELS or "qwen-plus" in AVAIL_LLM_MODELS or "qwen- }) except: print(trimmed_format_exc()) -if "chatgpt_website" in AVAIL_LLM_MODELS: # 接入一些逆向工程https://github.com/acheong08/ChatGPT-to-API/ - try: - from .bridge_chatgpt_website import predict_no_ui_long_connection as chatgpt_website_noui - from .bridge_chatgpt_website import predict as chatgpt_website_ui - model_info.update({ - "chatgpt_website": { - "fn_with_ui": chatgpt_website_ui, - "fn_without_ui": chatgpt_website_noui, - "endpoint": openai_endpoint, - "max_token": 4096, - "tokenizer": tokenizer_gpt35, - "token_cnt": get_token_num_gpt35, - } - }) - except: - print(trimmed_format_exc()) if "spark" in AVAIL_LLM_MODELS: # 讯飞星火认知大模型 try: from .bridge_spark import predict_no_ui_long_connection as spark_noui @@ -591,6 +594,23 @@ if "deepseekcoder" in AVAIL_LLM_MODELS: # deepseekcoder }) except: print(trimmed_format_exc()) +# if "skylark" in AVAIL_LLM_MODELS: +# try: +# from .bridge_skylark2 import predict_no_ui_long_connection as skylark_noui +# from .bridge_skylark2 import predict as skylark_ui +# model_info.update({ +# "skylark": { +# "fn_with_ui": skylark_ui, +# "fn_without_ui": skylark_noui, +# "endpoint": None, +# "max_token": 4096, +# "tokenizer": tokenizer_gpt35, +# "token_cnt": get_token_num_gpt35, +# } +# }) +# except: +# print(trimmed_format_exc()) + # <-- 用于定义和切换多个azure模型 --> AZURE_CFG_ARRAY = get_conf("AZURE_CFG_ARRAY") diff --git a/request_llms/bridge_chatgpt.py b/request_llms/bridge_chatgpt.py index faad6cfdce00fcc5b8e219736e1c97282a0cac63..660d5ddf1abb0aea10c036a09d42cbc1ac332f04 100644 --- a/request_llms/bridge_chatgpt.py +++ b/request_llms/bridge_chatgpt.py @@ -244,6 +244,9 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp if has_choices and not choice_valid: # 一些垃圾第三方接口的出现这样的错误 continue + if ('data: [DONE]' not in chunk_decoded) and len(chunk_decoded) > 0 and (chunkjson is None): + # 传递进来一些奇怪的东西 + raise ValueError(f'无法读取以下数据,请检查配置。\n\n{chunk_decoded}') # 前者是API2D的结束条件,后者是OPENAI的结束条件 if ('data: [DONE]' in chunk_decoded) or (len(chunkjson['choices'][0]["delta"]) == 0): # 判定为数据流的结束,gpt_replying_buffer也写完了 diff --git a/request_llms/bridge_google_gemini.py b/request_llms/bridge_google_gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..48e54190b0488c525eee1466be8deb03440d0081 --- /dev/null +++ b/request_llms/bridge_google_gemini.py @@ -0,0 +1,114 @@ +# encoding: utf-8 +# @Time : 2023/12/21 +# @Author : Spike +# @Descr : +import json +import re +import os +import time +from request_llms.com_google import GoogleChatInit +from toolbox import get_conf, update_ui, update_ui_lastest_msg, have_any_recent_upload_image_files, trimmed_format_exc + +proxies, TIMEOUT_SECONDS, MAX_RETRY = get_conf('proxies', 'TIMEOUT_SECONDS', 'MAX_RETRY') +timeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings in config.py.' + \ + '网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。' + + +def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, + console_slience=False): + # 检查API_KEY + if get_conf("GEMINI_API_KEY") == "": + raise ValueError(f"请配置 GEMINI_API_KEY。") + + genai = GoogleChatInit() + watch_dog_patience = 5 # 看门狗的耐心, 设置5秒即可 + gpt_replying_buffer = '' + stream_response = genai.generate_chat(inputs, llm_kwargs, history, sys_prompt) + for response in stream_response: + results = response.decode() + match = re.search(r'"text":\s*"((?:[^"\\]|\\.)*)"', results, flags=re.DOTALL) + error_match = re.search(r'\"message\":\s*\"(.*?)\"', results, flags=re.DOTALL) + if match: + try: + paraphrase = json.loads('{"text": "%s"}' % match.group(1)) + except: + raise ValueError(f"解析GEMINI消息出错。") + buffer = paraphrase['text'] + gpt_replying_buffer += buffer + if len(observe_window) >= 1: + observe_window[0] = gpt_replying_buffer + if len(observe_window) >= 2: + if (time.time() - observe_window[1]) > watch_dog_patience: raise RuntimeError("程序终止。") + if error_match: + raise RuntimeError(f'{gpt_replying_buffer} 对话错误') + return gpt_replying_buffer + + +def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream=True, additional_fn=None): + # 检查API_KEY + if get_conf("GEMINI_API_KEY") == "": + yield from update_ui_lastest_msg(f"请配置 GEMINI_API_KEY。", chatbot=chatbot, history=history, delay=0) + return + + # 适配润色区域 + if additional_fn is not None: + from core_functional import handle_core_functionality + inputs, history = handle_core_functionality(additional_fn, inputs, history, chatbot) + + if "vision" in llm_kwargs["llm_model"]: + have_recent_file, image_paths = have_any_recent_upload_image_files(chatbot) + def make_media_input(inputs, image_paths): + for image_path in image_paths: + inputs = inputs + f'

' + return inputs + if have_recent_file: + inputs = make_media_input(inputs, image_paths) + + chatbot.append((inputs, "")) + yield from update_ui(chatbot=chatbot, history=history) + genai = GoogleChatInit() + retry = 0 + while True: + try: + stream_response = genai.generate_chat(inputs, llm_kwargs, history, system_prompt) + break + except Exception as e: + retry += 1 + chatbot[-1] = ((chatbot[-1][0], trimmed_format_exc())) + yield from update_ui(chatbot=chatbot, history=history, msg="请求失败") # 刷新界面 + return + gpt_replying_buffer = "" + gpt_security_policy = "" + history.extend([inputs, '']) + for response in stream_response: + results = response.decode("utf-8") # 被这个解码给耍了。。 + gpt_security_policy += results + match = re.search(r'"text":\s*"((?:[^"\\]|\\.)*)"', results, flags=re.DOTALL) + error_match = re.search(r'\"message\":\s*\"(.*)\"', results, flags=re.DOTALL) + if match: + try: + paraphrase = json.loads('{"text": "%s"}' % match.group(1)) + except: + raise ValueError(f"解析GEMINI消息出错。") + gpt_replying_buffer += paraphrase['text'] # 使用 json 解析库进行处理 + chatbot[-1] = (inputs, gpt_replying_buffer) + history[-1] = gpt_replying_buffer + yield from update_ui(chatbot=chatbot, history=history) + if error_match: + history = history[-2] # 错误的不纳入对话 + chatbot[-1] = (inputs, gpt_replying_buffer + f"对话错误,请查看message\n\n```\n{error_match.group(1)}\n```") + yield from update_ui(chatbot=chatbot, history=history) + raise RuntimeError('对话错误') + if not gpt_replying_buffer: + history = history[-2] # 错误的不纳入对话 + chatbot[-1] = (inputs, gpt_replying_buffer + f"触发了Google的安全访问策略,没有回答\n\n```\n{gpt_security_policy}\n```") + yield from update_ui(chatbot=chatbot, history=history) + + + +if __name__ == '__main__': + import sys + llm_kwargs = {'llm_model': 'gemini-pro'} + result = predict('Write long a story about a magic backpack.', llm_kwargs, llm_kwargs, []) + for i in result: + print(i) diff --git a/request_llms/bridge_newbingfree.py b/request_llms/bridge_newbingfree.py index cb83a0fb0cedcd7ab3aa98f9d0e907231d9b0388..13573ede0977880c04547c37ca334a29d5e272fa 100644 --- a/request_llms/bridge_newbingfree.py +++ b/request_llms/bridge_newbingfree.py @@ -1,16 +1,17 @@ """ -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 第一部分:来自EdgeGPT.py https://github.com/acheong08/EdgeGPT -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- """ from .edge_gpt_free import Chatbot as NewbingChatbot + load_message = "等待NewBing响应。" """ -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 第二部分:子进程Worker(调用主体) -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- """ import time import json @@ -22,19 +23,30 @@ import threading from toolbox import update_ui, get_conf, trimmed_format_exc from multiprocessing import Process, Pipe + def preprocess_newbing_out(s): - pattern = r'\^(\d+)\^' # 匹配^数字^ - sub = lambda m: '('+m.group(1)+')' # 将匹配到的数字作为替换值 - result = re.sub(pattern, sub, s) # 替换操作 - if '[1]' in result: - result += '\n\n```reference\n' + "\n".join([r for r in result.split('\n') if r.startswith('[')]) + '\n```\n' + pattern = r"\^(\d+)\^" # 匹配^数字^ + sub = lambda m: "(" + m.group(1) + ")" # 将匹配到的数字作为替换值 + result = re.sub(pattern, sub, s) # 替换操作 + if "[1]" in result: + result += ( + "\n\n```reference\n" + + "\n".join([r for r in result.split("\n") if r.startswith("[")]) + + "\n```\n" + ) return result + def preprocess_newbing_out_simple(result): - if '[1]' in result: - result += '\n\n```reference\n' + "\n".join([r for r in result.split('\n') if r.startswith('[')]) + '\n```\n' + if "[1]" in result: + result += ( + "\n\n```reference\n" + + "\n".join([r for r in result.split("\n") if r.startswith("[")]) + + "\n```\n" + ) return result + class NewBingHandle(Process): def __init__(self): super().__init__(daemon=True) @@ -46,11 +58,12 @@ class NewBingHandle(Process): self.check_dependency() self.start() self.threadLock = threading.Lock() - + def check_dependency(self): try: self.success = False import certifi, httpx, rich + self.info = "依赖检测通过,等待NewBing响应。注意目前不能多人同时调用NewBing接口(有线程锁),否则将导致每个人的NewBing问询历史互相渗透。调用NewBing时,会自动使用已配置的代理。" self.success = True except: @@ -62,18 +75,19 @@ class NewBingHandle(Process): async def async_run(self): # 读取配置 - NEWBING_STYLE = get_conf('NEWBING_STYLE') + NEWBING_STYLE = get_conf("NEWBING_STYLE") from request_llms.bridge_all import model_info - endpoint = model_info['newbing']['endpoint'] + + endpoint = model_info["newbing"]["endpoint"] while True: # 等待 kwargs = self.child.recv() - question=kwargs['query'] - history=kwargs['history'] - system_prompt=kwargs['system_prompt'] + question = kwargs["query"] + history = kwargs["history"] + system_prompt = kwargs["system_prompt"] # 是否重置 - if len(self.local_history) > 0 and len(history)==0: + if len(self.local_history) > 0 and len(history) == 0: await self.newbing_model.reset() self.local_history = [] @@ -81,34 +95,33 @@ class NewBingHandle(Process): prompt = "" if system_prompt not in self.local_history: self.local_history.append(system_prompt) - prompt += system_prompt + '\n' + prompt += system_prompt + "\n" # 追加历史 for ab in history: a, b = ab if a not in self.local_history: self.local_history.append(a) - prompt += a + '\n' + prompt += a + "\n" # 问题 prompt += question self.local_history.append(question) - print('question:', prompt) + print("question:", prompt) # 提交 async for final, response in self.newbing_model.ask_stream( prompt=question, - conversation_style=NEWBING_STYLE, # ["creative", "balanced", "precise"] - wss_link=endpoint, # "wss://sydney.bing.com/sydney/ChatHub" + conversation_style=NEWBING_STYLE, # ["creative", "balanced", "precise"] + wss_link=endpoint, # "wss://sydney.bing.com/sydney/ChatHub" ): if not final: print(response) self.child.send(str(response)) else: - print('-------- receive final ---------') - self.child.send('[Finish]') + print("-------- receive final ---------") + self.child.send("[Finish]") # self.local_history.append(response) - def run(self): """ 这个函数运行在子进程 @@ -118,32 +131,37 @@ class NewBingHandle(Process): self.local_history = [] if (self.newbing_model is None) or (not self.success): # 代理设置 - proxies, NEWBING_COOKIES = get_conf('proxies', 'NEWBING_COOKIES') - if proxies is None: + proxies, NEWBING_COOKIES = get_conf("proxies", "NEWBING_COOKIES") + if proxies is None: self.proxies_https = None - else: - self.proxies_https = proxies['https'] + else: + self.proxies_https = proxies["https"] if (NEWBING_COOKIES is not None) and len(NEWBING_COOKIES) > 100: try: cookies = json.loads(NEWBING_COOKIES) except: self.success = False - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] NEWBING_COOKIES未填写或有格式错误。') - self.child.send('[Fail]'); self.child.send('[Finish]') + tb_str = "\n```\n" + trimmed_format_exc() + "\n```\n" + self.child.send(f"[Local Message] NEWBING_COOKIES未填写或有格式错误。") + self.child.send("[Fail]") + self.child.send("[Finish]") raise RuntimeError(f"NEWBING_COOKIES未填写或有格式错误。") else: cookies = None try: - self.newbing_model = NewbingChatbot(proxy=self.proxies_https, cookies=cookies) + self.newbing_model = NewbingChatbot( + proxy=self.proxies_https, cookies=cookies + ) except: self.success = False - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] 不能加载Newbing组件,请注意Newbing组件已不再维护。{tb_str}') - self.child.send('[Fail]') - self.child.send('[Finish]') + tb_str = "\n```\n" + trimmed_format_exc() + "\n```\n" + self.child.send( + f"[Local Message] 不能加载Newbing组件,请注意Newbing组件已不再维护。{tb_str}" + ) + self.child.send("[Fail]") + self.child.send("[Finish]") raise RuntimeError(f"不能加载Newbing组件,请注意Newbing组件已不再维护。") self.success = True @@ -151,66 +169,100 @@ class NewBingHandle(Process): # 进入任务等待状态 asyncio.run(self.async_run()) except Exception: - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] Newbing 请求失败,报错信息如下. 如果是与网络相关的问题,建议更换代理协议(推荐http)或代理节点 {tb_str}.') - self.child.send('[Fail]') - self.child.send('[Finish]') - + tb_str = "\n```\n" + trimmed_format_exc() + "\n```\n" + self.child.send( + f"[Local Message] Newbing 请求失败,报错信息如下. 如果是与网络相关的问题,建议更换代理协议(推荐http)或代理节点 {tb_str}." + ) + self.child.send("[Fail]") + self.child.send("[Finish]") + def stream_chat(self, **kwargs): """ 这个函数运行在主进程 """ - self.threadLock.acquire() # 获取线程锁 - self.parent.send(kwargs) # 请求子进程 + self.threadLock.acquire() # 获取线程锁 + self.parent.send(kwargs) # 请求子进程 while True: - res = self.parent.recv() # 等待newbing回复的片段 - if res == '[Finish]': break # 结束 - elif res == '[Fail]': self.success = False; break # 失败 - else: yield res # newbing回复的片段 - self.threadLock.release() # 释放线程锁 + res = self.parent.recv() # 等待newbing回复的片段 + if res == "[Finish]": + break # 结束 + elif res == "[Fail]": + self.success = False + break # 失败 + else: + yield res # newbing回复的片段 + self.threadLock.release() # 释放线程锁 """ -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 第三部分:主进程统一调用函数接口 -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- """ global newbingfree_handle newbingfree_handle = None -def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=[], console_slience=False): + +def predict_no_ui_long_connection( + inputs, + llm_kwargs, + history=[], + sys_prompt="", + observe_window=[], + console_slience=False, +): """ - 多线程方法 - 函数的说明请见 request_llms/bridge_all.py + 多线程方法 + 函数的说明请见 request_llms/bridge_all.py """ global newbingfree_handle if (newbingfree_handle is None) or (not newbingfree_handle.success): newbingfree_handle = NewBingHandle() - if len(observe_window) >= 1: observe_window[0] = load_message + "\n\n" + newbingfree_handle.info - if not newbingfree_handle.success: + if len(observe_window) >= 1: + observe_window[0] = load_message + "\n\n" + newbingfree_handle.info + if not newbingfree_handle.success: error = newbingfree_handle.info newbingfree_handle = None raise RuntimeError(error) # 没有 sys_prompt 接口,因此把prompt加入 history history_feedin = [] - for i in range(len(history)//2): - history_feedin.append([history[2*i], history[2*i+1]] ) + for i in range(len(history) // 2): + history_feedin.append([history[2 * i], history[2 * i + 1]]) - watch_dog_patience = 5 # 看门狗 (watchdog) 的耐心, 设置5秒即可 + watch_dog_patience = 5 # 看门狗 (watchdog) 的耐心, 设置5秒即可 response = "" - if len(observe_window) >= 1: observe_window[0] = "[Local Message] 等待NewBing响应中 ..." - for response in newbingfree_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=sys_prompt, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']): - if len(observe_window) >= 1: observe_window[0] = preprocess_newbing_out_simple(response) - if len(observe_window) >= 2: - if (time.time()-observe_window[1]) > watch_dog_patience: + if len(observe_window) >= 1: + observe_window[0] = "[Local Message] 等待NewBing响应中 ..." + for response in newbingfree_handle.stream_chat( + query=inputs, + history=history_feedin, + system_prompt=sys_prompt, + max_length=llm_kwargs["max_length"], + top_p=llm_kwargs["top_p"], + temperature=llm_kwargs["temperature"], + ): + if len(observe_window) >= 1: + observe_window[0] = preprocess_newbing_out_simple(response) + if len(observe_window) >= 2: + if (time.time() - observe_window[1]) > watch_dog_patience: raise RuntimeError("程序终止。") return preprocess_newbing_out_simple(response) -def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None): + +def predict( + inputs, + llm_kwargs, + plugin_kwargs, + chatbot, + history=[], + system_prompt="", + stream=True, + additional_fn=None, +): """ - 单线程方法 - 函数的说明请见 request_llms/bridge_all.py + 单线程方法 + 函数的说明请见 request_llms/bridge_all.py """ chatbot.append((inputs, "[Local Message] 等待NewBing响应中 ...")) @@ -219,27 +271,41 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp newbingfree_handle = NewBingHandle() chatbot[-1] = (inputs, load_message + "\n\n" + newbingfree_handle.info) yield from update_ui(chatbot=chatbot, history=[]) - if not newbingfree_handle.success: + if not newbingfree_handle.success: newbingfree_handle = None return if additional_fn is not None: from core_functional import handle_core_functionality - inputs, history = handle_core_functionality(additional_fn, inputs, history, chatbot) + + inputs, history = handle_core_functionality( + additional_fn, inputs, history, chatbot + ) history_feedin = [] - for i in range(len(history)//2): - history_feedin.append([history[2*i], history[2*i+1]] ) + for i in range(len(history) // 2): + history_feedin.append([history[2 * i], history[2 * i + 1]]) chatbot[-1] = (inputs, "[Local Message] 等待NewBing响应中 ...") response = "[Local Message] 等待NewBing响应中 ..." - yield from update_ui(chatbot=chatbot, history=history, msg="NewBing响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") - for response in newbingfree_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=system_prompt, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']): + yield from update_ui( + chatbot=chatbot, history=history, msg="NewBing响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。" + ) + for response in newbingfree_handle.stream_chat( + query=inputs, + history=history_feedin, + system_prompt=system_prompt, + max_length=llm_kwargs["max_length"], + top_p=llm_kwargs["top_p"], + temperature=llm_kwargs["temperature"], + ): chatbot[-1] = (inputs, preprocess_newbing_out(response)) - yield from update_ui(chatbot=chatbot, history=history, msg="NewBing响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") - if response == "[Local Message] 等待NewBing响应中 ...": response = "[Local Message] NewBing响应异常,请刷新界面重试 ..." + yield from update_ui( + chatbot=chatbot, history=history, msg="NewBing响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。" + ) + if response == "[Local Message] 等待NewBing响应中 ...": + response = "[Local Message] NewBing响应异常,请刷新界面重试 ..." history.extend([inputs, response]) - logging.info(f'[raw_input] {inputs}') - logging.info(f'[response] {response}') + logging.info(f"[raw_input] {inputs}") + logging.info(f"[response] {response}") yield from update_ui(chatbot=chatbot, history=history, msg="完成全部响应,请提交新问题。") - diff --git a/request_llms/bridge_skylark2.py b/request_llms/bridge_skylark2.py new file mode 100644 index 0000000000000000000000000000000000000000..8f10b839355cb95922a2499d85ff598e17c44352 --- /dev/null +++ b/request_llms/bridge_skylark2.py @@ -0,0 +1,67 @@ +import time +from toolbox import update_ui, get_conf, update_ui_lastest_msg +from toolbox import check_packages, report_exception + +model_name = '云雀大模型' + +def validate_key(): + YUNQUE_SECRET_KEY = get_conf("YUNQUE_SECRET_KEY") + if YUNQUE_SECRET_KEY == '': return False + return True + +def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=[], console_slience=False): + """ + ⭐ 多线程方法 + 函数的说明请见 request_llms/bridge_all.py + """ + watch_dog_patience = 5 + response = "" + + if validate_key() is False: + raise RuntimeError('请配置YUNQUE_SECRET_KEY') + + from .com_skylark2api import YUNQUERequestInstance + sri = YUNQUERequestInstance() + for response in sri.generate(inputs, llm_kwargs, history, sys_prompt): + if len(observe_window) >= 1: + observe_window[0] = response + if len(observe_window) >= 2: + if (time.time()-observe_window[1]) > watch_dog_patience: raise RuntimeError("程序终止。") + return response + +def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None): + """ + ⭐ 单线程方法 + 函数的说明请见 request_llms/bridge_all.py + """ + chatbot.append((inputs, "")) + yield from update_ui(chatbot=chatbot, history=history) + + # 尝试导入依赖,如果缺少依赖,则给出安装建议 + try: + check_packages(["zhipuai"]) + except: + yield from update_ui_lastest_msg(f"导入软件依赖失败。使用该模型需要额外依赖,安装方法```pip install --upgrade zhipuai```。", + chatbot=chatbot, history=history, delay=0) + return + + if validate_key() is False: + yield from update_ui_lastest_msg(lastmsg="[Local Message] 请配置HUOSHAN_API_KEY", chatbot=chatbot, history=history, delay=0) + return + + if additional_fn is not None: + from core_functional import handle_core_functionality + inputs, history = handle_core_functionality(additional_fn, inputs, history, chatbot) + + # 开始接收回复 + from .com_skylark2api import YUNQUERequestInstance + sri = YUNQUERequestInstance() + for response in sri.generate(inputs, llm_kwargs, history, system_prompt): + chatbot[-1] = (inputs, response) + yield from update_ui(chatbot=chatbot, history=history) + + # 总结输出 + if response == f"[Local Message] 等待{model_name}响应中 ...": + response = f"[Local Message] {model_name}响应异常 ..." + history.extend([inputs, response]) + yield from update_ui(chatbot=chatbot, history=history) \ No newline at end of file diff --git a/request_llms/bridge_stackclaude.py b/request_llms/bridge_stackclaude.py index 0b42a17c0c5abdf0a04b68bde558e6790617661f..21590b8a0853e169d4f9bcf2397d6bb487f19558 100644 --- a/request_llms/bridge_stackclaude.py +++ b/request_llms/bridge_stackclaude.py @@ -7,14 +7,15 @@ import logging import time from toolbox import get_conf import asyncio + load_message = "正在加载Claude组件,请稍候..." try: """ - ======================================================================== + =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 第一部分:Slack API Client https://github.com/yokonsan/claude-in-slack-api - ======================================================================== + =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- """ from slack_sdk.errors import SlackApiError @@ -23,20 +24,23 @@ try: class SlackClient(AsyncWebClient): """SlackClient类用于与Slack API进行交互,实现消息发送、接收等功能。 - 属性: - - CHANNEL_ID:str类型,表示频道ID。 + 属性: + - CHANNEL_ID:str类型,表示频道ID。 - 方法: - - open_channel():异步方法。通过调用conversations_open方法打开一个频道,并将返回的频道ID保存在属性CHANNEL_ID中。 - - chat(text: str):异步方法。向已打开的频道发送一条文本消息。 - - get_slack_messages():异步方法。获取已打开频道的最新消息并返回消息列表,目前不支持历史消息查询。 - - get_reply():异步方法。循环监听已打开频道的消息,如果收到"Typing…_"结尾的消息说明Claude还在继续输出,否则结束循环。 + 方法: + - open_channel():异步方法。通过调用conversations_open方法打开一个频道,并将返回的频道ID保存在属性CHANNEL_ID中。 + - chat(text: str):异步方法。向已打开的频道发送一条文本消息。 + - get_slack_messages():异步方法。获取已打开频道的最新消息并返回消息列表,目前不支持历史消息查询。 + - get_reply():异步方法。循环监听已打开频道的消息,如果收到"Typing…_"结尾的消息说明Claude还在继续输出,否则结束循环。 """ + CHANNEL_ID = None async def open_channel(self): - response = await self.conversations_open(users=get_conf('SLACK_CLAUDE_BOT_ID')) + response = await self.conversations_open( + users=get_conf("SLACK_CLAUDE_BOT_ID") + ) self.CHANNEL_ID = response["channel"]["id"] async def chat(self, text): @@ -49,33 +53,39 @@ try: async def get_slack_messages(self): try: # TODO:暂时不支持历史消息,因为在同一个频道里存在多人使用时历史消息渗透问题 - resp = await self.conversations_history(channel=self.CHANNEL_ID, oldest=self.LAST_TS, limit=1) - msg = [msg for msg in resp["messages"] - if msg.get("user") == get_conf('SLACK_CLAUDE_BOT_ID')] + resp = await self.conversations_history( + channel=self.CHANNEL_ID, oldest=self.LAST_TS, limit=1 + ) + msg = [ + msg + for msg in resp["messages"] + if msg.get("user") == get_conf("SLACK_CLAUDE_BOT_ID") + ] return msg except (SlackApiError, KeyError) as e: raise RuntimeError(f"获取Slack消息失败。") - + async def get_reply(self): while True: slack_msgs = await self.get_slack_messages() if len(slack_msgs) == 0: await asyncio.sleep(0.5) continue - + msg = slack_msgs[-1] if msg["text"].endswith("Typing…_"): yield False, msg["text"] else: yield True, msg["text"] break + except: pass """ -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 第二部分:子进程Worker(调用主体) -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- """ @@ -88,7 +98,7 @@ class ClaudeHandle(Process): self.success = True self.local_history = [] self.check_dependency() - if self.success: + if self.success: self.start() self.threadLock = threading.Lock() @@ -96,6 +106,7 @@ class ClaudeHandle(Process): try: self.success = False import slack_sdk + self.info = "依赖检测通过,等待Claude响应。注意目前不能多人同时调用Claude接口(有线程锁),否则将导致每个人的Claude问询历史互相渗透。调用Claude时,会自动使用已配置的代理。" self.success = True except: @@ -103,40 +114,44 @@ class ClaudeHandle(Process): self.success = False def ready(self): - return self.claude_model is not None - + return self.claude_model is not None + async def async_run(self): await self.claude_model.open_channel() while True: # 等待 kwargs = self.child.recv() - question = kwargs['query'] - history = kwargs['history'] + question = kwargs["query"] + history = kwargs["history"] # 开始问问题 prompt = "" # 问题 prompt += question - print('question:', prompt) + print("question:", prompt) # 提交 await self.claude_model.chat(prompt) - + # 获取回复 - async for final, response in self.claude_model.get_reply(): + async for final, response in self.claude_model.get_reply(): if not final: print(response) self.child.send(str(response)) else: # 防止丢失最后一条消息 slack_msgs = await self.claude_model.get_slack_messages() - last_msg = slack_msgs[-1]["text"] if slack_msgs and len(slack_msgs) > 0 else "" + last_msg = ( + slack_msgs[-1]["text"] + if slack_msgs and len(slack_msgs) > 0 + else "" + ) if last_msg: self.child.send(last_msg) - print('-------- receive final ---------') - self.child.send('[Finish]') - + print("-------- receive final ---------") + self.child.send("[Finish]") + def run(self): """ 这个函数运行在子进程 @@ -146,22 +161,24 @@ class ClaudeHandle(Process): self.local_history = [] if (self.claude_model is None) or (not self.success): # 代理设置 - proxies = get_conf('proxies') + proxies = get_conf("proxies") if proxies is None: self.proxies_https = None else: - self.proxies_https = proxies['https'] + self.proxies_https = proxies["https"] try: - SLACK_CLAUDE_USER_TOKEN = get_conf('SLACK_CLAUDE_USER_TOKEN') - self.claude_model = SlackClient(token=SLACK_CLAUDE_USER_TOKEN, proxy=self.proxies_https) - print('Claude组件初始化成功。') + SLACK_CLAUDE_USER_TOKEN = get_conf("SLACK_CLAUDE_USER_TOKEN") + self.claude_model = SlackClient( + token=SLACK_CLAUDE_USER_TOKEN, proxy=self.proxies_https + ) + print("Claude组件初始化成功。") except: self.success = False - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] 不能加载Claude组件。{tb_str}') - self.child.send('[Fail]') - self.child.send('[Finish]') + tb_str = "\n```\n" + trimmed_format_exc() + "\n```\n" + self.child.send(f"[Local Message] 不能加载Claude组件。{tb_str}") + self.child.send("[Fail]") + self.child.send("[Finish]") raise RuntimeError(f"不能加载Claude组件。") self.success = True @@ -169,42 +186,49 @@ class ClaudeHandle(Process): # 进入任务等待状态 asyncio.run(self.async_run()) except Exception: - tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n' - self.child.send(f'[Local Message] Claude失败 {tb_str}.') - self.child.send('[Fail]') - self.child.send('[Finish]') + tb_str = "\n```\n" + trimmed_format_exc() + "\n```\n" + self.child.send(f"[Local Message] Claude失败 {tb_str}.") + self.child.send("[Fail]") + self.child.send("[Finish]") def stream_chat(self, **kwargs): """ 这个函数运行在主进程 """ self.threadLock.acquire() - self.parent.send(kwargs) # 发送请求到子进程 + self.parent.send(kwargs) # 发送请求到子进程 while True: - res = self.parent.recv() # 等待Claude回复的片段 - if res == '[Finish]': - break # 结束 - elif res == '[Fail]': + res = self.parent.recv() # 等待Claude回复的片段 + if res == "[Finish]": + break # 结束 + elif res == "[Fail]": self.success = False break else: - yield res # Claude回复的片段 + yield res # Claude回复的片段 self.threadLock.release() """ -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 第三部分:主进程统一调用函数接口 -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- """ global claude_handle claude_handle = None -def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False): +def predict_no_ui_long_connection( + inputs, + llm_kwargs, + history=[], + sys_prompt="", + observe_window=None, + console_slience=False, +): """ - 多线程方法 - 函数的说明请见 request_llms/bridge_all.py + 多线程方法 + 函数的说明请见 request_llms/bridge_all.py """ global claude_handle if (claude_handle is None) or (not claude_handle.success): @@ -217,24 +241,40 @@ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", # 没有 sys_prompt 接口,因此把prompt加入 history history_feedin = [] - for i in range(len(history)//2): - history_feedin.append([history[2*i], history[2*i+1]]) + for i in range(len(history) // 2): + history_feedin.append([history[2 * i], history[2 * i + 1]]) watch_dog_patience = 5 # 看门狗 (watchdog) 的耐心, 设置5秒即可 response = "" observe_window[0] = "[Local Message] 等待Claude响应中 ..." - for response in claude_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=sys_prompt, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']): + for response in claude_handle.stream_chat( + query=inputs, + history=history_feedin, + system_prompt=sys_prompt, + max_length=llm_kwargs["max_length"], + top_p=llm_kwargs["top_p"], + temperature=llm_kwargs["temperature"], + ): observe_window[0] = preprocess_newbing_out_simple(response) if len(observe_window) >= 2: - if (time.time()-observe_window[1]) > watch_dog_patience: + if (time.time() - observe_window[1]) > watch_dog_patience: raise RuntimeError("程序终止。") return preprocess_newbing_out_simple(response) -def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream=True, additional_fn=None): +def predict( + inputs, + llm_kwargs, + plugin_kwargs, + chatbot, + history=[], + system_prompt="", + stream=True, + additional_fn=None, +): """ - 单线程方法 - 函数的说明请见 request_llms/bridge_all.py + 单线程方法 + 函数的说明请见 request_llms/bridge_all.py """ chatbot.append((inputs, "[Local Message] 等待Claude响应中 ...")) @@ -249,21 +289,30 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp if additional_fn is not None: from core_functional import handle_core_functionality - inputs, history = handle_core_functionality(additional_fn, inputs, history, chatbot) + + inputs, history = handle_core_functionality( + additional_fn, inputs, history, chatbot + ) history_feedin = [] - for i in range(len(history)//2): - history_feedin.append([history[2*i], history[2*i+1]]) + for i in range(len(history) // 2): + history_feedin.append([history[2 * i], history[2 * i + 1]]) chatbot[-1] = (inputs, "[Local Message] 等待Claude响应中 ...") response = "[Local Message] 等待Claude响应中 ..." - yield from update_ui(chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") - for response in claude_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=system_prompt): + yield from update_ui( + chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。" + ) + for response in claude_handle.stream_chat( + query=inputs, history=history_feedin, system_prompt=system_prompt + ): chatbot[-1] = (inputs, preprocess_newbing_out(response)) - yield from update_ui(chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。") + yield from update_ui( + chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。" + ) if response == "[Local Message] 等待Claude响应中 ...": response = "[Local Message] Claude响应异常,请刷新界面重试 ..." history.extend([inputs, response]) - logging.info(f'[raw_input] {inputs}') - logging.info(f'[response] {response}') + logging.info(f"[raw_input] {inputs}") + logging.info(f"[response] {response}") yield from update_ui(chatbot=chatbot, history=history, msg="完成全部响应,请提交新问题。") diff --git a/request_llms/bridge_zhipu.py b/request_llms/bridge_zhipu.py index 915a13efbaf6411ea7c2a66500f09f57237b87d0..91903ad37b379e02a6642b93109db5d01a7ea07c 100644 --- a/request_llms/bridge_zhipu.py +++ b/request_llms/bridge_zhipu.py @@ -42,7 +42,7 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp try: check_packages(["zhipuai"]) except: - yield from update_ui_lastest_msg(f"导入软件依赖失败。使用该模型需要额外依赖,安装方法```pip install --upgrade zhipuai```。", + yield from update_ui_lastest_msg(f"导入软件依赖失败。使用该模型需要额外依赖,安装方法```pip install zhipuai==1.0.7```。", chatbot=chatbot, history=history, delay=0) return diff --git a/request_llms/com_google.py b/request_llms/com_google.py new file mode 100644 index 0000000000000000000000000000000000000000..211581af5aea81aee1b5d74e28f80e7e371bedda --- /dev/null +++ b/request_llms/com_google.py @@ -0,0 +1,229 @@ +# encoding: utf-8 +# @Time : 2023/12/25 +# @Author : Spike +# @Descr : +import json +import os +import re +import requests +from typing import List, Dict, Tuple +from toolbox import get_conf, encode_image, get_pictures_list + +proxies, TIMEOUT_SECONDS = get_conf("proxies", "TIMEOUT_SECONDS") + +""" +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +第五部分 一些文件处理方法 +files_filter_handler 根据type过滤文件 +input_encode_handler 提取input中的文件,并解析 +file_manifest_filter_html 根据type过滤文件, 并解析为html or md 文本 +link_mtime_to_md 文件增加本地时间参数,避免下载到缓存文件 +html_view_blank 超链接 +html_local_file 本地文件取相对路径 +to_markdown_tabs 文件list 转换为 md tab +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- +""" + + +def files_filter_handler(file_list): + new_list = [] + filter_ = [ + "png", + "jpg", + "jpeg", + "bmp", + "svg", + "webp", + "ico", + "tif", + "tiff", + "raw", + "eps", + ] + for file in file_list: + file = str(file).replace("file=", "") + if os.path.exists(file): + if str(os.path.basename(file)).split(".")[-1] in filter_: + new_list.append(file) + return new_list + + +def input_encode_handler(inputs, llm_kwargs): + if llm_kwargs["most_recent_uploaded"].get("path"): + image_paths = get_pictures_list(llm_kwargs["most_recent_uploaded"]["path"]) + md_encode = [] + for md_path in image_paths: + type_ = os.path.splitext(md_path)[1].replace(".", "") + type_ = "jpeg" if type_ == "jpg" else type_ + md_encode.append({"data": encode_image(md_path), "type": type_}) + return inputs, md_encode + + +def file_manifest_filter_html(file_list, filter_: list = None, md_type=False): + new_list = [] + if not filter_: + filter_ = [ + "png", + "jpg", + "jpeg", + "bmp", + "svg", + "webp", + "ico", + "tif", + "tiff", + "raw", + "eps", + ] + for file in file_list: + if str(os.path.basename(file)).split(".")[-1] in filter_: + new_list.append(html_local_img(file, md=md_type)) + elif os.path.exists(file): + new_list.append(link_mtime_to_md(file)) + else: + new_list.append(file) + return new_list + + +def link_mtime_to_md(file): + link_local = html_local_file(file) + link_name = os.path.basename(file) + a = f"[{link_name}]({link_local}?{os.path.getmtime(file)})" + return a + + +def html_local_file(file): + base_path = os.path.dirname(__file__) # 项目目录 + if os.path.exists(str(file)): + file = f'file={file.replace(base_path, ".")}' + return file + + +def html_local_img(__file, layout="left", max_width=None, max_height=None, md=True): + style = "" + if max_width is not None: + style += f"max-width: {max_width};" + if max_height is not None: + style += f"max-height: {max_height};" + __file = html_local_file(__file) + a = f'
' + if md: + a = f"![{__file}]({__file})" + return a + + +def to_markdown_tabs(head: list, tabs: list, alignment=":---:", column=False): + """ + Args: + head: 表头:[] + tabs: 表值:[[列1], [列2], [列3], [列4]] + alignment: :--- 左对齐, :---: 居中对齐, ---: 右对齐 + column: True to keep data in columns, False to keep data in rows (default). + Returns: + A string representation of the markdown table. + """ + if column: + transposed_tabs = list(map(list, zip(*tabs))) + else: + transposed_tabs = tabs + # Find the maximum length among the columns + max_len = max(len(column) for column in transposed_tabs) + + tab_format = "| %s " + tabs_list = "".join([tab_format % i for i in head]) + "|\n" + tabs_list += "".join([tab_format % alignment for i in head]) + "|\n" + + for i in range(max_len): + row_data = [tab[i] if i < len(tab) else "" for tab in transposed_tabs] + row_data = file_manifest_filter_html(row_data, filter_=None) + tabs_list += "".join([tab_format % i for i in row_data]) + "|\n" + + return tabs_list + + +class GoogleChatInit: + def __init__(self): + self.url_gemini = "https://generativelanguage.googleapis.com/v1beta/models/%m:streamGenerateContent?key=%k" + + def generate_chat(self, inputs, llm_kwargs, history, system_prompt): + headers, payload = self.generate_message_payload( + inputs, llm_kwargs, history, system_prompt + ) + response = requests.post( + url=self.url_gemini, + headers=headers, + data=json.dumps(payload), + stream=True, + proxies=proxies, + timeout=TIMEOUT_SECONDS, + ) + return response.iter_lines() + + def __conversation_user(self, user_input, llm_kwargs): + what_i_have_asked = {"role": "user", "parts": []} + if "vision" not in self.url_gemini: + input_ = user_input + encode_img = [] + else: + input_, encode_img = input_encode_handler(user_input, llm_kwargs=llm_kwargs) + what_i_have_asked["parts"].append({"text": input_}) + if encode_img: + for data in encode_img: + what_i_have_asked["parts"].append( + { + "inline_data": { + "mime_type": f"image/{data['type']}", + "data": data["data"], + } + } + ) + return what_i_have_asked + + def __conversation_history(self, history, llm_kwargs): + messages = [] + conversation_cnt = len(history) // 2 + if conversation_cnt: + for index in range(0, 2 * conversation_cnt, 2): + what_i_have_asked = self.__conversation_user(history[index], llm_kwargs) + what_gpt_answer = { + "role": "model", + "parts": [{"text": history[index + 1]}], + } + messages.append(what_i_have_asked) + messages.append(what_gpt_answer) + return messages + + def generate_message_payload( + self, inputs, llm_kwargs, history, system_prompt + ) -> Tuple[Dict, Dict]: + messages = [ + # {"role": "system", "parts": [{"text": system_prompt}]}, # gemini 不允许对话轮次为偶数,所以这个没有用,看后续支持吧。。。 + # {"role": "user", "parts": [{"text": ""}]}, + # {"role": "model", "parts": [{"text": ""}]} + ] + self.url_gemini = self.url_gemini.replace( + "%m", llm_kwargs["llm_model"] + ).replace("%k", get_conf("GEMINI_API_KEY")) + header = {"Content-Type": "application/json"} + if "vision" not in self.url_gemini: # 不是vision 才处理history + messages.extend( + self.__conversation_history(history, llm_kwargs) + ) # 处理 history + messages.append(self.__conversation_user(inputs, llm_kwargs)) # 处理用户对话 + payload = { + "contents": messages, + "generationConfig": { + # "maxOutputTokens": 800, + "stopSequences": str(llm_kwargs.get("stop", "")).split(" "), + "temperature": llm_kwargs.get("temperature", 1), + "topP": llm_kwargs.get("top_p", 0.8), + "topK": 10, + }, + } + return header, payload + + +if __name__ == "__main__": + google = GoogleChatInit() + # print(gootle.generate_message_payload('你好呀', {}, ['123123', '3123123'], '')) + # gootle.input_encode_handle('123123[123123](./123123), ![53425](./asfafa/fff.jpg)') diff --git a/request_llms/com_skylark2api.py b/request_llms/com_skylark2api.py new file mode 100644 index 0000000000000000000000000000000000000000..2530eccaab9e05f10f16fabe3293103b52058f0e --- /dev/null +++ b/request_llms/com_skylark2api.py @@ -0,0 +1,95 @@ +from toolbox import get_conf +import threading +import logging +import os + +timeout_bot_msg = '[Local Message] Request timeout. Network error.' +#os.environ['VOLC_ACCESSKEY'] = '' +#os.environ['VOLC_SECRETKEY'] = '' + +class YUNQUERequestInstance(): + def __init__(self): + + self.time_to_yield_event = threading.Event() + self.time_to_exit_event = threading.Event() + + self.result_buf = "" + + def generate(self, inputs, llm_kwargs, history, system_prompt): + # import _thread as thread + from volcengine.maas import MaasService, MaasException + + maas = MaasService('maas-api.ml-platform-cn-beijing.volces.com', 'cn-beijing') + + YUNQUE_SECRET_KEY, YUNQUE_ACCESS_KEY,YUNQUE_MODEL = get_conf("YUNQUE_SECRET_KEY", "YUNQUE_ACCESS_KEY","YUNQUE_MODEL") + maas.set_ak(YUNQUE_ACCESS_KEY) #填写 VOLC_ACCESSKEY + maas.set_sk(YUNQUE_SECRET_KEY) #填写 'VOLC_SECRETKEY' + + self.result_buf = "" + + req = { + "model": { + "name": YUNQUE_MODEL, + "version": "1.0", # use default version if not specified. + }, + "parameters": { + "max_new_tokens": 4000, # 输出文本的最大tokens限制 + "min_new_tokens": 1, # 输出文本的最小tokens限制 + "temperature": llm_kwargs['temperature'], # 用于控制生成文本的随机性和创造性,Temperature值越大随机性越大,取值范围0~1 + "top_p": llm_kwargs['top_p'], # 用于控制输出tokens的多样性,TopP值越大输出的tokens类型越丰富,取值范围0~1 + "top_k": 0, # 选择预测值最大的k个token进行采样,取值范围0-1000,0表示不生效 + "max_prompt_tokens": 4000, # 最大输入 token 数,如果给出的 prompt 的 token 长度超过此限制,取最后 max_prompt_tokens 个 token 输入模型。 + }, + "messages": self.generate_message_payload(inputs, llm_kwargs, history, system_prompt) + } + + response = maas.stream_chat(req) + + for resp in response: + self.result_buf += resp.choice.message.content + yield self.result_buf + ''' + for event in response.events(): + if event.event == "add": + self.result_buf += event.data + yield self.result_buf + elif event.event == "error" or event.event == "interrupted": + raise RuntimeError("Unknown error:" + event.data) + elif event.event == "finish": + yield self.result_buf + break + else: + raise RuntimeError("Unknown error:" + str(event)) + + logging.info(f'[raw_input] {inputs}') + logging.info(f'[response] {self.result_buf}') + ''' + return self.result_buf + + def generate_message_payload(inputs, llm_kwargs, history, system_prompt): + from volcengine.maas import ChatRole + conversation_cnt = len(history) // 2 + messages = [{"role": ChatRole.USER, "content": system_prompt}, + {"role": ChatRole.ASSISTANT, "content": "Certainly!"}] + if conversation_cnt: + for index in range(0, 2 * conversation_cnt, 2): + what_i_have_asked = {} + what_i_have_asked["role"] = ChatRole.USER + what_i_have_asked["content"] = history[index] + what_gpt_answer = {} + what_gpt_answer["role"] = ChatRole.ASSISTANT + what_gpt_answer["content"] = history[index + 1] + if what_i_have_asked["content"] != "": + if what_gpt_answer["content"] == "": + continue + if what_gpt_answer["content"] == timeout_bot_msg: + continue + messages.append(what_i_have_asked) + messages.append(what_gpt_answer) + else: + messages[-1]['content'] = what_gpt_answer['content'] + what_i_ask_now = {} + what_i_ask_now["role"] = ChatRole.USER + what_i_ask_now["content"] = inputs + messages.append(what_i_ask_now) + return messages \ No newline at end of file diff --git a/request_llms/com_zhipuapi.py b/request_llms/com_zhipuapi.py index 445720d88172ff86b639c1ea60eb90889d6089a5..d8b763c9087d4b505c2a75f277ec4e1c49de3edd 100644 --- a/request_llms/com_zhipuapi.py +++ b/request_llms/com_zhipuapi.py @@ -21,11 +21,13 @@ class ZhipuRequestInstance(): response = zhipuai.model_api.sse_invoke( model=ZHIPUAI_MODEL, prompt=generate_message_payload(inputs, llm_kwargs, history, system_prompt), - top_p=llm_kwargs['top_p'], - temperature=llm_kwargs['temperature'], + top_p=llm_kwargs['top_p']*0.7, # 智谱的API抽风,手动*0.7给做个线性变换 + temperature=llm_kwargs['temperature']*0.95, # 智谱的API抽风,手动*0.7给做个线性变换 ) for event in response.events(): if event.event == "add": + # if self.result_buf == "" and event.data.startswith(" "): + # event.data = event.data.lstrip(" ") # 每次智谱为啥都要带个空格开头呢? self.result_buf += event.data yield self.result_buf elif event.event == "error" or event.event == "interrupted": @@ -35,7 +37,8 @@ class ZhipuRequestInstance(): break else: raise RuntimeError("Unknown error:" + str(event)) - + if self.result_buf == "": + yield "智谱没有返回任何数据, 请检查ZHIPUAI_API_KEY和ZHIPUAI_MODEL是否填写正确." logging.info(f'[raw_input] {inputs}') logging.info(f'[response] {self.result_buf}') return self.result_buf diff --git a/request_llms/edge_gpt_free.py b/request_llms/edge_gpt_free.py index 22ff05272b634e8557ceb83501248cc238074366..d0122a52852fcb0f369d2269410569d8cad7c73b 100644 --- a/request_llms/edge_gpt_free.py +++ b/request_llms/edge_gpt_free.py @@ -1,8 +1,8 @@ """ -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 第一部分:来自EdgeGPT.py https://github.com/acheong08/EdgeGPT -======================================================================== +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- """ """ Main.py @@ -196,9 +196,9 @@ class _ChatHubRequest: self, prompt: str, conversation_style: CONVERSATION_STYLE_TYPE, - options = None, - webpage_context = None, - search_result = False, + options=None, + webpage_context=None, + search_result=False, ) -> None: """ Updates request object @@ -294,9 +294,9 @@ class _Conversation: def __init__( self, - proxy = None, - async_mode = False, - cookies = None, + proxy=None, + async_mode=False, + cookies=None, ) -> None: if async_mode: return @@ -350,8 +350,8 @@ class _Conversation: @staticmethod async def create( - proxy = None, - cookies = None, + proxy=None, + cookies=None, ): self = _Conversation(async_mode=True) self.struct = { @@ -418,8 +418,8 @@ class _ChatHub: def __init__( self, conversation: _Conversation, - proxy = None, - cookies = None, + proxy=None, + cookies=None, ) -> None: self.session = None self.wss = None @@ -441,7 +441,7 @@ class _ChatHub: conversation_style: CONVERSATION_STYLE_TYPE = None, raw: bool = False, options: dict = None, - webpage_context = None, + webpage_context=None, search_result: bool = False, ) -> Generator[str, None, None]: """ @@ -452,10 +452,12 @@ class _ChatHub: ws_cookies = [] for cookie in self.cookies: ws_cookies.append(f"{cookie['name']}={cookie['value']}") - req_header.update({ - 'Cookie': ';'.join(ws_cookies), - }) - + req_header.update( + { + "Cookie": ";".join(ws_cookies), + } + ) + timeout = aiohttp.ClientTimeout(total=30) self.session = aiohttp.ClientSession(timeout=timeout) @@ -521,9 +523,9 @@ class _ChatHub: msg = await self.wss.receive() try: objects = msg.data.split(DELIMITER) - except : + except: continue - + for obj in objects: if obj is None or not obj: continue @@ -624,8 +626,8 @@ class Chatbot: def __init__( self, - proxy = None, - cookies = None, + proxy=None, + cookies=None, ) -> None: self.proxy = proxy self.chat_hub: _ChatHub = _ChatHub( @@ -636,8 +638,8 @@ class Chatbot: @staticmethod async def create( - proxy = None, - cookies = None, + proxy=None, + cookies=None, ): self = Chatbot.__new__(Chatbot) self.proxy = proxy @@ -654,7 +656,7 @@ class Chatbot: wss_link: str = "wss://sydney.bing.com/sydney/ChatHub", conversation_style: CONVERSATION_STYLE_TYPE = None, options: dict = None, - webpage_context = None, + webpage_context=None, search_result: bool = False, ) -> dict: """ @@ -680,7 +682,7 @@ class Chatbot: conversation_style: CONVERSATION_STYLE_TYPE = None, raw: bool = False, options: dict = None, - webpage_context = None, + webpage_context=None, search_result: bool = False, ) -> Generator[str, None, None]: """ diff --git a/request_llms/requirements_chatglm.txt b/request_llms/requirements_chatglm.txt index cd53cd736fe0c46121f60f41848a42d3a7a10ff3..dabdd8ea519c3f9e59031bb6b73d55502c89f99a 100644 --- a/request_llms/requirements_chatglm.txt +++ b/request_llms/requirements_chatglm.txt @@ -2,4 +2,4 @@ protobuf cpm_kernels torch>=1.10 mdtex2html -sentencepiece \ No newline at end of file +sentencepiece diff --git a/request_llms/requirements_jittorllms.txt b/request_llms/requirements_jittorllms.txt index ddb61955243a16cffe95c8b0dec3a7681fb4da7e..2bd2da8bb2b8cc3624758c52e1bd429d95df607c 100644 --- a/request_llms/requirements_jittorllms.txt +++ b/request_llms/requirements_jittorllms.txt @@ -3,4 +3,4 @@ jtorch >= 0.1.3 torch torchvision pandas -jieba \ No newline at end of file +jieba diff --git a/request_llms/requirements_moss.txt b/request_llms/requirements_moss.txt index 544b25f0688c605f0910fbb3ae69c15f4fac0e98..a1f84f0415d98a848a412d6bce77d90792de633f 100644 --- a/request_llms/requirements_moss.txt +++ b/request_llms/requirements_moss.txt @@ -5,4 +5,3 @@ accelerate matplotlib huggingface_hub triton - diff --git a/request_llms/requirements_qwen.txt b/request_llms/requirements_qwen.txt index 5899464f479117dceab904f0dbe7a4f7459cf02e..e9617907be68516ff85ab10097a5e52423664c8e 100644 --- a/request_llms/requirements_qwen.txt +++ b/request_llms/requirements_qwen.txt @@ -1 +1 @@ -dashscope \ No newline at end of file +dashscope diff --git a/request_llms/requirements_qwen_local.txt b/request_llms/requirements_qwen_local.txt index de6bf3c9d9becb7bf7771894e07db228bafe2a5d..c4715f3f5e48ff41e828a86b69c2fa90c039fe14 100644 --- a/request_llms/requirements_qwen_local.txt +++ b/request_llms/requirements_qwen_local.txt @@ -2,4 +2,4 @@ modelscope transformers_stream_generator auto-gptq optimum -urllib3<2 \ No newline at end of file +urllib3<2 diff --git a/request_llms/requirements_slackclaude.txt b/request_llms/requirements_slackclaude.txt index 472d58c2844b20e171720c873d794959c24fdce7..7c8563efb570325a9145f1e9af972ee34b394904 100644 --- a/request_llms/requirements_slackclaude.txt +++ b/request_llms/requirements_slackclaude.txt @@ -1 +1 @@ -slack-sdk==3.21.3 \ No newline at end of file +slack-sdk==3.21.3 diff --git a/requirements.txt b/requirements.txt index 52e851de5d5163a42f2e8dab709b1db597cd1933..f13dcc5b857a71cdb1d1d895724f472a5c69d9d6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,11 +1,13 @@ pydantic==1.10.11 pypdf2==2.12.1 +zhipuai<2 tiktoken>=0.3.3 requests[socks] protobuf==3.18 transformers>=4.27.1 scipdf_parser>=0.52 python-markdown-math +pymdown-extensions websocket-client beautifulsoup4 prompt_toolkit diff --git a/shared_utils/advanced_markdown_format.py b/shared_utils/advanced_markdown_format.py new file mode 100644 index 0000000000000000000000000000000000000000..9eed4f09bffaa90fe28ae08ea31353508d7c8f8f --- /dev/null +++ b/shared_utils/advanced_markdown_format.py @@ -0,0 +1,287 @@ +import markdown +import re +import os +import math +from textwrap import dedent +from functools import lru_cache +from pymdownx.superfences import fence_div_format, fence_code_format +from latex2mathml.converter import convert as tex2mathml +from shared_utils.config_loader import get_conf as get_conf + +pj = os.path.join +default_user_name = 'default_user' + +markdown_extension_configs = { + 'mdx_math': { + 'enable_dollar_delimiter': True, + 'use_gitlab_delimiters': False, + }, +} + +code_highlight_configs = { + "pymdownx.superfences": { + 'css_class': 'codehilite', + "custom_fences": [ + { + 'name': 'mermaid', + 'class': 'mermaid', + 'format': fence_code_format + } + ] + }, + "pymdownx.highlight": { + 'css_class': 'codehilite', + 'guess_lang': True, + # 'auto_title': True, + # 'linenums': True + } +} + +def text_divide_paragraph(text): + """ + 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。 + """ + pre = '
' + suf = '
' + if text.startswith(pre) and text.endswith(suf): + return text + + if '```' in text: + # careful input + return text + elif '
' in text: + # careful input + return text + else: + # whatever input + lines = text.split("\n") + for i, line in enumerate(lines): + lines[i] = lines[i].replace(" ", " ") + text = "
".join(lines) + return pre + text + suf + + +def tex2mathml_catch_exception(content, *args, **kwargs): + try: + content = tex2mathml(content, *args, **kwargs) + except: + content = content + return content + + +def replace_math_no_render(match): + content = match.group(1) + if 'mode=display' in match.group(0): + content = content.replace('\n', '
') + return f"$${content}$$" + else: + return f"${content}$" + + +def replace_math_render(match): + content = match.group(1) + if 'mode=display' in match.group(0): + if '\\begin{aligned}' in content: + content = content.replace('\\begin{aligned}', '\\begin{array}') + content = content.replace('\\end{aligned}', '\\end{array}') + content = content.replace('&', ' ') + content = tex2mathml_catch_exception(content, display="block") + return content + else: + return tex2mathml_catch_exception(content) + + +def markdown_bug_hunt(content): + """ + 解决一个mdx_math的bug(单$包裹begin命令时多余\n', '') + return content + + +def is_equation(txt): + """ + 判定是否为公式 | 测试1 写出洛伦兹定律,使用tex格式公式 测试2 给出柯西不等式,使用latex格式 测试3 写出麦克斯韦方程组 + """ + if '```' in txt and '```reference' not in txt: return False + if '$' not in txt and '\\[' not in txt: return False + mathpatterns = { + r'(?^[ \t]*(?:~{3,}|`{3,}))[ ]* # opening fence + ((\{(?P[^\}\n]*)\})| # (optional {attrs} or + (\.?(?P[\w#.+-]*)[ ]*)? # optional (.)lang + (hl_lines=(?P"|')(?P.*?)(?P=quot)[ ]*)?) # optional hl_lines) + \n # newline (end of opening fence) + (?P.*?)(?<=\n) # the code block + (?P=fence)[ ]*$ # closing fence + '''), + re.MULTILINE | re.DOTALL | re.VERBOSE +) + + +def get_line_range(re_match_obj, txt): + start_pos, end_pos = re_match_obj.regs[0] + num_newlines_before = txt[:start_pos+1].count('\n') + line_start = num_newlines_before + line_end = num_newlines_before + txt[start_pos:end_pos].count('\n')+1 + return line_start, line_end + + +def fix_code_segment_indent(txt): + lines = [] + change_any = False + txt_tmp = txt + while True: + re_match_obj = FENCED_BLOCK_RE.search(txt_tmp) + if not re_match_obj: break + if len(lines) == 0: lines = txt.split("\n") + + # 清空 txt_tmp 对应的位置方便下次搜索 + start_pos, end_pos = re_match_obj.regs[0] + txt_tmp = txt_tmp[:start_pos] + ' '*(end_pos-start_pos) + txt_tmp[end_pos:] + line_start, line_end = get_line_range(re_match_obj, txt) + + # 获取公共缩进 + shared_indent_cnt = 1e5 + for i in range(line_start, line_end): + stripped_string = lines[i].lstrip() + num_spaces = len(lines[i]) - len(stripped_string) + if num_spaces < shared_indent_cnt: + shared_indent_cnt = num_spaces + + # 修复缩进 + if (shared_indent_cnt < 1e5) and (shared_indent_cnt % 4) == 3: + num_spaces_should_be = math.ceil(shared_indent_cnt / 4) * 4 + for i in range(line_start, line_end): + add_n = num_spaces_should_be - shared_indent_cnt + lines[i] = ' ' * add_n + lines[i] + if not change_any: # 遇到第一个 + change_any = True + + if change_any: + return '\n'.join(lines) + else: + return txt + + +@lru_cache(maxsize=128) # 使用 lru缓存 加快转换速度 +def markdown_convertion(txt): + """ + 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。 + """ + pre = '
' + suf = '
' + if txt.startswith(pre) and txt.endswith(suf): + # print('警告,输入了已经经过转化的字符串,二次转化可能出问题') + return txt # 已经被转化过,不需要再次转化 + + find_equation_pattern = r'" - + js = "" + for jsf in [ + os.path.join(theme_dir, "common.js"), + os.path.join(theme_dir, "mermaid.min.js"), + os.path.join(theme_dir, "mermaid_loader.js"), + ]: + with open(jsf, "r", encoding="utf8") as f: + js += f"" + # 添加一个萌萌的看板娘 if ADD_WAIFU: js += """ @@ -69,21 +83,26 @@ def adjust_theme(): """ - if not hasattr(gr, 'RawTemplateResponse'): + if not hasattr(gr, "RawTemplateResponse"): gr.RawTemplateResponse = gr.routes.templates.TemplateResponse gradio_original_template_fn = gr.RawTemplateResponse + def gradio_new_template_fn(*args, **kwargs): res = gradio_original_template_fn(*args, **kwargs) - res.body = res.body.replace(b'', f'{js}'.encode("utf8")) + res.body = res.body.replace(b"", f"{js}".encode("utf8")) res.init_headers() return res - gr.routes.templates.TemplateResponse = gradio_new_template_fn # override gradio template + + gr.routes.templates.TemplateResponse = ( + gradio_new_template_fn # override gradio template + ) except: set_theme = None - print('gradio版本较旧, 不能自定义字体和颜色') + print("gradio版本较旧, 不能自定义字体和颜色") return set_theme -with open(os.path.join(theme_dir, 'contrast.css'), "r", encoding="utf-8") as f: + +with open(os.path.join(theme_dir, "contrast.css"), "r", encoding="utf-8") as f: advanced_css = f.read() -with open(os.path.join(theme_dir, 'common.css'), "r", encoding="utf-8") as f: +with open(os.path.join(theme_dir, "common.css"), "r", encoding="utf-8") as f: advanced_css += f.read() diff --git a/themes/default.css b/themes/default.css index 7c1d400f2d92b320a0bffc411367eb216596e8a0..5a9e3ea7a2f1c213cb2a4035e1eba5c1a70643e4 100644 --- a/themes/default.css +++ b/themes/default.css @@ -303,4 +303,3 @@ .dark .codehilite .vi { color: #89DDFF } /* Name.Variable.Instance */ .dark .codehilite .vm { color: #82AAFF } /* Name.Variable.Magic */ .dark .codehilite .il { color: #F78C6C } /* Literal.Number.Integer.Long */ - diff --git a/themes/default.py b/themes/default.py index 64b6720943522a4a41192cfa4fa506ce39bb14fa..b8e943197033c29d6df8b45fd61fc55eda2ebb00 100644 --- a/themes/default.py +++ b/themes/default.py @@ -1,17 +1,26 @@ import os import gradio as gr from toolbox import get_conf -CODE_HIGHLIGHT, ADD_WAIFU, LAYOUT = get_conf('CODE_HIGHLIGHT', 'ADD_WAIFU', 'LAYOUT') + +CODE_HIGHLIGHT, ADD_WAIFU, LAYOUT = get_conf("CODE_HIGHLIGHT", "ADD_WAIFU", "LAYOUT") theme_dir = os.path.dirname(__file__) -def adjust_theme(): + +def adjust_theme(): try: color_er = gr.themes.utils.colors.fuchsia set_theme = gr.themes.Default( primary_hue=gr.themes.utils.colors.orange, neutral_hue=gr.themes.utils.colors.gray, - font=["Helvetica", "Microsoft YaHei", "ui-sans-serif", "sans-serif", "system-ui"], - font_mono=["ui-monospace", "Consolas", "monospace"]) + font=[ + "Helvetica", + "Microsoft YaHei", + "ui-sans-serif", + "sans-serif", + "system-ui", + ], + font_mono=["ui-monospace", "Consolas", "monospace"], + ) set_theme.set( # Colors input_background_fill_dark="*neutral_800", @@ -58,8 +67,14 @@ def adjust_theme(): button_cancel_text_color_dark="white", ) - with open(os.path.join(theme_dir, 'common.js'), 'r', encoding='utf8') as f: - js = f"" + js = "" + for jsf in [ + os.path.join(theme_dir, "common.js"), + os.path.join(theme_dir, "mermaid.min.js"), + os.path.join(theme_dir, "mermaid_loader.js"), + ]: + with open(jsf, "r", encoding="utf8") as f: + js += f"" # 添加一个萌萌的看板娘 if ADD_WAIFU: @@ -68,21 +83,26 @@ def adjust_theme(): """ - if not hasattr(gr, 'RawTemplateResponse'): + if not hasattr(gr, "RawTemplateResponse"): gr.RawTemplateResponse = gr.routes.templates.TemplateResponse gradio_original_template_fn = gr.RawTemplateResponse + def gradio_new_template_fn(*args, **kwargs): res = gradio_original_template_fn(*args, **kwargs) - res.body = res.body.replace(b'', f'{js}'.encode("utf8")) + res.body = res.body.replace(b"", f"{js}".encode("utf8")) res.init_headers() return res - gr.routes.templates.TemplateResponse = gradio_new_template_fn # override gradio template + + gr.routes.templates.TemplateResponse = ( + gradio_new_template_fn # override gradio template + ) except: set_theme = None - print('gradio版本较旧, 不能自定义字体和颜色') + print("gradio版本较旧, 不能自定义字体和颜色") return set_theme -with open(os.path.join(theme_dir, 'default.css'), "r", encoding="utf-8") as f: + +with open(os.path.join(theme_dir, "default.css"), "r", encoding="utf-8") as f: advanced_css = f.read() -with open(os.path.join(theme_dir, 'common.css'), "r", encoding="utf-8") as f: +with open(os.path.join(theme_dir, "common.css"), "r", encoding="utf-8") as f: advanced_css += f.read() diff --git a/themes/gradios.py b/themes/gradios.py index 9db134159c3a596bf9057b83e27cacefdd053426..68f15df88dbd98f84251b7117316b51a50740f78 100644 --- a/themes/gradios.py +++ b/themes/gradios.py @@ -2,30 +2,44 @@ import logging import os import gradio as gr from toolbox import get_conf, ProxyNetworkActivate -CODE_HIGHLIGHT, ADD_WAIFU, LAYOUT = get_conf('CODE_HIGHLIGHT', 'ADD_WAIFU', 'LAYOUT') + +CODE_HIGHLIGHT, ADD_WAIFU, LAYOUT = get_conf("CODE_HIGHLIGHT", "ADD_WAIFU", "LAYOUT") theme_dir = os.path.dirname(__file__) + def dynamic_set_theme(THEME): set_theme = gr.themes.ThemeClass() - with ProxyNetworkActivate('Download_Gradio_Theme'): - logging.info('正在下载Gradio主题,请稍等。') - if THEME.startswith('Huggingface-'): THEME = THEME.lstrip('Huggingface-') - if THEME.startswith('huggingface-'): THEME = THEME.lstrip('huggingface-') + with ProxyNetworkActivate("Download_Gradio_Theme"): + logging.info("正在下载Gradio主题,请稍等。") + if THEME.startswith("Huggingface-"): + THEME = THEME.lstrip("Huggingface-") + if THEME.startswith("huggingface-"): + THEME = THEME.lstrip("huggingface-") set_theme = set_theme.from_hub(THEME.lower()) return set_theme + def adjust_theme(): try: set_theme = gr.themes.ThemeClass() - with ProxyNetworkActivate('Download_Gradio_Theme'): - logging.info('正在下载Gradio主题,请稍等。') - THEME = get_conf('THEME') - if THEME.startswith('Huggingface-'): THEME = THEME.lstrip('Huggingface-') - if THEME.startswith('huggingface-'): THEME = THEME.lstrip('huggingface-') + with ProxyNetworkActivate("Download_Gradio_Theme"): + logging.info("正在下载Gradio主题,请稍等。") + THEME = get_conf("THEME") + if THEME.startswith("Huggingface-"): + THEME = THEME.lstrip("Huggingface-") + if THEME.startswith("huggingface-"): + THEME = THEME.lstrip("huggingface-") set_theme = set_theme.from_hub(THEME.lower()) - with open(os.path.join(theme_dir, 'common.js'), 'r', encoding='utf8') as f: - js = f"" + js = "" + for jsf in [ + os.path.join(theme_dir, "common.js"), + os.path.join(theme_dir, "mermaid.min.js"), + os.path.join(theme_dir, "mermaid_loader.js"), + ]: + with open(jsf, "r", encoding="utf8") as f: + js += f"" + # 添加一个萌萌的看板娘 if ADD_WAIFU: @@ -34,20 +48,26 @@ def adjust_theme(): """ - if not hasattr(gr, 'RawTemplateResponse'): + if not hasattr(gr, "RawTemplateResponse"): gr.RawTemplateResponse = gr.routes.templates.TemplateResponse gradio_original_template_fn = gr.RawTemplateResponse + def gradio_new_template_fn(*args, **kwargs): res = gradio_original_template_fn(*args, **kwargs) - res.body = res.body.replace(b'', f'{js}'.encode("utf8")) + res.body = res.body.replace(b"", f"{js}".encode("utf8")) res.init_headers() return res - gr.routes.templates.TemplateResponse = gradio_new_template_fn # override gradio template - except Exception as e: + + gr.routes.templates.TemplateResponse = ( + gradio_new_template_fn # override gradio template + ) + except Exception: set_theme = None from toolbox import trimmed_format_exc - logging.error('gradio版本较旧, 不能自定义字体和颜色:', trimmed_format_exc()) + + logging.error("gradio版本较旧, 不能自定义字体和颜色:", trimmed_format_exc()) return set_theme -with open(os.path.join(theme_dir, 'common.css'), "r", encoding="utf-8") as f: + +with open(os.path.join(theme_dir, "common.css"), "r", encoding="utf-8") as f: advanced_css = f.read() diff --git a/themes/green.css b/themes/green.css index 870af4825c1b69af99ede253b1669b5dabdcd044..85dd80139fb25a11b33ab1e67729b9297b73baa7 100644 --- a/themes/green.css +++ b/themes/green.css @@ -197,12 +197,12 @@ footer { } textarea.svelte-1pie7s6 { background: #e7e6e6 !important; - width: 96% !important; + width: 100% !important; } .dark textarea.svelte-1pie7s6 { background: var(--input-background-fill) !important; - width: 96% !important; + width: 100% !important; } .dark input[type=number].svelte-1cl284s { @@ -508,12 +508,14 @@ ol:not(.options), ul:not(.options) { [data-testid = "bot"] { max-width: 85%; border-bottom-left-radius: 0 !important; + box-shadow: 2px 2px 0px 1px rgba(0, 0, 0, 0.06); background-color: var(--message-bot-background-color-light) !important; } [data-testid = "user"] { max-width: 85%; width: auto !important; border-bottom-right-radius: 0 !important; + box-shadow: 2px 2px 0px 1px rgba(0, 0, 0, 0.06); background-color: var(--message-user-background-color-light) !important; } .dark [data-testid = "bot"] { diff --git a/themes/green.js b/themes/green.js index 65948c0344e85c098a7f96e176fa8388575ca07a..7801b970d253b2372456ab0b25804189a3434bf5 100644 --- a/themes/green.js +++ b/themes/green.js @@ -38,4 +38,4 @@ function setSlider() { window.addEventListener("DOMContentLoaded", () => { set_elements(); -}); \ No newline at end of file +}); diff --git a/themes/green.py b/themes/green.py index 326981e3d835fd52b07ac4b587ecf3725dd3c06f..84287417436274b83a09caeb6dc2c9c72b30badc 100644 --- a/themes/green.py +++ b/themes/green.py @@ -1,9 +1,11 @@ import os import gradio as gr from toolbox import get_conf -CODE_HIGHLIGHT, ADD_WAIFU, LAYOUT = get_conf('CODE_HIGHLIGHT', 'ADD_WAIFU', 'LAYOUT') + +CODE_HIGHLIGHT, ADD_WAIFU, LAYOUT = get_conf("CODE_HIGHLIGHT", "ADD_WAIFU", "LAYOUT") theme_dir = os.path.dirname(__file__) + def adjust_theme(): try: set_theme = gr.themes.Soft( @@ -50,7 +52,6 @@ def adjust_theme(): c900="#2B2B2B", c950="#171717", ), - radius_size=gr.themes.sizes.radius_sm, ).set( button_primary_background_fill="*primary_500", @@ -75,8 +76,14 @@ def adjust_theme(): chatbot_code_background_color_dark="*neutral_950", ) - with open(os.path.join(theme_dir, 'common.js'), 'r', encoding='utf8') as f: - js = f"" + js = "" + for jsf in [ + os.path.join(theme_dir, "common.js"), + os.path.join(theme_dir, "mermaid.min.js"), + os.path.join(theme_dir, "mermaid_loader.js"), + ]: + with open(jsf, "r", encoding="utf8") as f: + js += f"" # 添加一个萌萌的看板娘 if ADD_WAIFU: @@ -86,24 +93,29 @@ def adjust_theme(): """ - with open(os.path.join(theme_dir, 'green.js'), 'r', encoding='utf8') as f: + with open(os.path.join(theme_dir, "green.js"), "r", encoding="utf8") as f: js += f"" - if not hasattr(gr, 'RawTemplateResponse'): + if not hasattr(gr, "RawTemplateResponse"): gr.RawTemplateResponse = gr.routes.templates.TemplateResponse gradio_original_template_fn = gr.RawTemplateResponse + def gradio_new_template_fn(*args, **kwargs): res = gradio_original_template_fn(*args, **kwargs) - res.body = res.body.replace(b'', f'{js}'.encode("utf8")) + res.body = res.body.replace(b"", f"{js}".encode("utf8")) res.init_headers() return res - gr.routes.templates.TemplateResponse = gradio_new_template_fn # override gradio template + + gr.routes.templates.TemplateResponse = ( + gradio_new_template_fn # override gradio template + ) except: set_theme = None - print('gradio版本较旧, 不能自定义字体和颜色') + print("gradio版本较旧, 不能自定义字体和颜色") return set_theme -with open(os.path.join(theme_dir, 'green.css'), "r", encoding="utf-8") as f: + +with open(os.path.join(theme_dir, "green.css"), "r", encoding="utf-8") as f: advanced_css = f.read() -with open(os.path.join(theme_dir, 'common.css'), "r", encoding="utf-8") as f: +with open(os.path.join(theme_dir, "common.css"), "r", encoding="utf-8") as f: advanced_css += f.read() diff --git a/themes/mermaid.min.js b/themes/mermaid.min.js new file mode 100644 index 0000000000000000000000000000000000000000..87df8091797d85c18867a1e49be8dd0860c0553a --- /dev/null +++ b/themes/mermaid.min.js @@ -0,0 +1,1589 @@ +(function(T2,G0){typeof exports=="object"&&typeof module<"u"?module.exports=G0():typeof define=="function"&&define.amd?define(G0):(T2=typeof globalThis<"u"?globalThis:T2||self,T2.mermaid=G0())})(this,function(){"use strict";var VPn=Object.defineProperty;var UPn=(T2,G0,Ar)=>G0 in T2?VPn(T2,G0,{enumerable:!0,configurable:!0,writable:!0,value:Ar}):T2[G0]=Ar;var CL=(T2,G0,Ar)=>(UPn(T2,typeof G0!="symbol"?G0+"":G0,Ar),Ar);function T2(r){for(var i=[],o=1;o>>0,l;for(l=0;l0)for(o=0;o=0;return(b?o?"+":"":"-")+Math.pow(10,Math.max(0,f)).toString().substr(1)+l}var Tie=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,az=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Cie={},_T={};function Ki(r,i,o,l){var f=l;typeof l=="string"&&(f=function(){return this[l]()}),r&&(_T[r]=f),i&&(_T[i[0]]=function(){return Sm(f.apply(this,arguments),i[1],i[2])}),o&&(_T[o]=function(){return this.localeData().ordinal(f.apply(this,arguments),r)})}function $_t(r){return r.match(/\[[\s\S]/)?r.replace(/^\[|\]$/g,""):r.replace(/\\/g,"")}function H_t(r){var i=r.match(Tie),o,l;for(o=0,l=i.length;o=0&&az.test(r);)r=r.replace(az,l),az.lastIndex=0,o-=1;return r}var z_t={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function G_t(r){var i=this._longDateFormat[r],o=this._longDateFormat[r.toUpperCase()];return i||!o?i:(this._longDateFormat[r]=o.match(Tie).map(function(l){return l==="MMMM"||l==="MM"||l==="DD"||l==="dddd"?l.slice(1):l}).join(""),this._longDateFormat[r])}var V_t="Invalid date";function U_t(){return this._invalidDate}var q_t="%d",Y_t=/\d{1,2}/;function W_t(r){return this._ordinal.replace("%d",r)}var K_t={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function X_t(r,i,o,l){var f=this._relativeTime[o];return Cm(f)?f(r,i,o,l):f.replace(/%d/i,r)}function Q_t(r,i){var o=this._relativeTime[r>0?"future":"past"];return Cm(o)?o(i):o.replace(/%s/i,i)}var ML={};function nd(r,i){var o=r.toLowerCase();ML[o]=ML[o+"s"]=ML[i]=r}function S2(r){return typeof r=="string"?ML[r]||ML[r.toLowerCase()]:void 0}function Sie(r){var i={},o,l;for(l in r)Mo(r,l)&&(o=S2(l),o&&(i[o]=r[l]));return i}var r9e={};function rd(r,i){r9e[r]=i}function Z_t(r){var i=[],o;for(o in r)Mo(r,o)&&i.push({unit:o,priority:r9e[o]});return i.sort(function(l,f){return l.priority-f.priority}),i}function cz(r){return r%4===0&&r%100!==0||r%400===0}function A2(r){return r<0?Math.ceil(r)||0:Math.floor(r)}function Fa(r){var i=+r,o=0;return i!==0&&isFinite(i)&&(o=A2(i)),o}function TT(r,i){return function(o){return o!=null?(i9e(this,r,o),Ar.updateOffset(this,i),this):uz(this,r)}}function uz(r,i){return r.isValid()?r._d["get"+(r._isUTC?"UTC":"")+i]():NaN}function i9e(r,i,o){r.isValid()&&!isNaN(o)&&(i==="FullYear"&&cz(r.year())&&r.month()===1&&r.date()===29?(o=Fa(o),r._d["set"+(r._isUTC?"UTC":"")+i](o,r.month(),bz(o,r.month()))):r._d["set"+(r._isUTC?"UTC":"")+i](o))}function J_t(r){return r=S2(r),Cm(this[r])?this[r]():this}function eTt(r,i){if(typeof r=="object"){r=Sie(r);var o=Z_t(r),l,f=o.length;for(l=0;l68?1900:2e3)};var g9e=TT("FullYear",!0);function mTt(){return cz(this.year())}function yTt(r,i,o,l,f,b,d){var w;return r<100&&r>=0?(w=new Date(r+400,i,o,l,f,b,d),isFinite(w.getFullYear())&&w.setFullYear(r)):w=new Date(r,i,o,l,f,b,d),w}function OL(r){var i,o;return r<100&&r>=0?(o=Array.prototype.slice.call(arguments),o[0]=r+400,i=new Date(Date.UTC.apply(null,o)),isFinite(i.getUTCFullYear())&&i.setUTCFullYear(r)):i=new Date(Date.UTC.apply(null,arguments)),i}function vz(r,i,o){var l=7+i-o,f=(7+OL(r,0,l).getUTCDay()-i)%7;return-f+l-1}function p9e(r,i,o,l,f){var b=(7+o-l)%7,d=vz(r,l,f),w=1+7*(i-1)+b+d,y,k;return w<=0?(y=r-1,k=IL(y)+w):w>IL(r)?(y=r+1,k=w-IL(r)):(y=r,k=w),{year:y,dayOfYear:k}}function NL(r,i,o){var l=vz(r.year(),i,o),f=Math.floor((r.dayOfYear()-l-1)/7)+1,b,d;return f<1?(d=r.year()-1,b=f+N3(d,i,o)):f>N3(r.year(),i,o)?(b=f-N3(r.year(),i,o),d=r.year()+1):(d=r.year(),b=f),{week:b,year:d}}function N3(r,i,o){var l=vz(r,i,o),f=vz(r+1,i,o);return(IL(r)-l+f)/7}Ki("w",["ww",2],"wo","week"),Ki("W",["WW",2],"Wo","isoWeek"),nd("week","w"),nd("isoWeek","W"),rd("week",5),rd("isoWeek",5),ci("w",wu),ci("ww",wu,op),ci("W",wu),ci("WW",wu,op),LL(["w","ww","W","WW"],function(r,i,o,l){i[l.substr(0,1)]=Fa(r)});function kTt(r){return NL(r,this._week.dow,this._week.doy).week}var xTt={dow:0,doy:6};function ETt(){return this._week.dow}function _Tt(){return this._week.doy}function TTt(r){var i=this.localeData().week(this);return r==null?i:this.add((r-i)*7,"d")}function CTt(r){var i=NL(this,1,4).week;return r==null?i:this.add((r-i)*7,"d")}Ki("d",0,"do","day"),Ki("dd",0,0,function(r){return this.localeData().weekdaysMin(this,r)}),Ki("ddd",0,0,function(r){return this.localeData().weekdaysShort(this,r)}),Ki("dddd",0,0,function(r){return this.localeData().weekdays(this,r)}),Ki("e",0,0,"weekday"),Ki("E",0,0,"isoWeekday"),nd("day","d"),nd("weekday","e"),nd("isoWeekday","E"),rd("day",11),rd("weekday",11),rd("isoWeekday",11),ci("d",wu),ci("e",wu),ci("E",wu),ci("dd",function(r,i){return i.weekdaysMinRegex(r)}),ci("ddd",function(r,i){return i.weekdaysShortRegex(r)}),ci("dddd",function(r,i){return i.weekdaysRegex(r)}),LL(["dd","ddd","dddd"],function(r,i,o,l){var f=o._locale.weekdaysParse(r,l,o._strict);f!=null?i.d=f:ba(o).invalidWeekday=r}),LL(["d","e","E"],function(r,i,o,l){i[l]=Fa(r)});function STt(r,i){return typeof r!="string"?r:isNaN(r)?(r=i.weekdaysParse(r),typeof r=="number"?r:null):parseInt(r,10)}function ATt(r,i){return typeof r=="string"?i.weekdaysParse(r)%7||7:isNaN(r)?null:r}function Lie(r,i){return r.slice(i,7).concat(r.slice(0,i))}var MTt="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),b9e="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),DTt="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),LTt=DL,ITt=DL,OTt=DL;function NTt(r,i){var o=mv(this._weekdays)?this._weekdays:this._weekdays[r&&r!==!0&&this._weekdays.isFormat.test(i)?"format":"standalone"];return r===!0?Lie(o,this._week.dow):r?o[r.day()]:o}function PTt(r){return r===!0?Lie(this._weekdaysShort,this._week.dow):r?this._weekdaysShort[r.day()]:this._weekdaysShort}function BTt(r){return r===!0?Lie(this._weekdaysMin,this._week.dow):r?this._weekdaysMin[r.day()]:this._weekdaysMin}function FTt(r,i,o){var l,f,b,d=r.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],l=0;l<7;++l)b=Tm([2e3,1]).day(l),this._minWeekdaysParse[l]=this.weekdaysMin(b,"").toLocaleLowerCase(),this._shortWeekdaysParse[l]=this.weekdaysShort(b,"").toLocaleLowerCase(),this._weekdaysParse[l]=this.weekdays(b,"").toLocaleLowerCase();return o?i==="dddd"?(f=ih.call(this._weekdaysParse,d),f!==-1?f:null):i==="ddd"?(f=ih.call(this._shortWeekdaysParse,d),f!==-1?f:null):(f=ih.call(this._minWeekdaysParse,d),f!==-1?f:null):i==="dddd"?(f=ih.call(this._weekdaysParse,d),f!==-1||(f=ih.call(this._shortWeekdaysParse,d),f!==-1)?f:(f=ih.call(this._minWeekdaysParse,d),f!==-1?f:null)):i==="ddd"?(f=ih.call(this._shortWeekdaysParse,d),f!==-1||(f=ih.call(this._weekdaysParse,d),f!==-1)?f:(f=ih.call(this._minWeekdaysParse,d),f!==-1?f:null)):(f=ih.call(this._minWeekdaysParse,d),f!==-1||(f=ih.call(this._weekdaysParse,d),f!==-1)?f:(f=ih.call(this._shortWeekdaysParse,d),f!==-1?f:null))}function RTt(r,i,o){var l,f,b;if(this._weekdaysParseExact)return FTt.call(this,r,i,o);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),l=0;l<7;l++){if(f=Tm([2e3,1]).day(l),o&&!this._fullWeekdaysParse[l]&&(this._fullWeekdaysParse[l]=new RegExp("^"+this.weekdays(f,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[l]=new RegExp("^"+this.weekdaysShort(f,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[l]=new RegExp("^"+this.weekdaysMin(f,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[l]||(b="^"+this.weekdays(f,"")+"|^"+this.weekdaysShort(f,"")+"|^"+this.weekdaysMin(f,""),this._weekdaysParse[l]=new RegExp(b.replace(".",""),"i")),o&&i==="dddd"&&this._fullWeekdaysParse[l].test(r))return l;if(o&&i==="ddd"&&this._shortWeekdaysParse[l].test(r))return l;if(o&&i==="dd"&&this._minWeekdaysParse[l].test(r))return l;if(!o&&this._weekdaysParse[l].test(r))return l}}function jTt(r){if(!this.isValid())return r!=null?this:NaN;var i=this._isUTC?this._d.getUTCDay():this._d.getDay();return r!=null?(r=STt(r,this.localeData()),this.add(r-i,"d")):i}function $Tt(r){if(!this.isValid())return r!=null?this:NaN;var i=(this.day()+7-this.localeData()._week.dow)%7;return r==null?i:this.add(r-i,"d")}function HTt(r){if(!this.isValid())return r!=null?this:NaN;if(r!=null){var i=ATt(r,this.localeData());return this.day(this.day()%7?i:i-7)}else return this.day()||7}function zTt(r){return this._weekdaysParseExact?(Mo(this,"_weekdaysRegex")||Iie.call(this),r?this._weekdaysStrictRegex:this._weekdaysRegex):(Mo(this,"_weekdaysRegex")||(this._weekdaysRegex=LTt),this._weekdaysStrictRegex&&r?this._weekdaysStrictRegex:this._weekdaysRegex)}function GTt(r){return this._weekdaysParseExact?(Mo(this,"_weekdaysRegex")||Iie.call(this),r?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(Mo(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=ITt),this._weekdaysShortStrictRegex&&r?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function VTt(r){return this._weekdaysParseExact?(Mo(this,"_weekdaysRegex")||Iie.call(this),r?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(Mo(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=OTt),this._weekdaysMinStrictRegex&&r?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function Iie(){function r(E,T){return T.length-E.length}var i=[],o=[],l=[],f=[],b,d,w,y,k;for(b=0;b<7;b++)d=Tm([2e3,1]).day(b),w=cp(this.weekdaysMin(d,"")),y=cp(this.weekdaysShort(d,"")),k=cp(this.weekdays(d,"")),i.push(w),o.push(y),l.push(k),f.push(w),f.push(y),f.push(k);i.sort(r),o.sort(r),l.sort(r),f.sort(r),this._weekdaysRegex=new RegExp("^("+f.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+i.join("|")+")","i")}function Oie(){return this.hours()%12||12}function UTt(){return this.hours()||24}Ki("H",["HH",2],0,"hour"),Ki("h",["hh",2],0,Oie),Ki("k",["kk",2],0,UTt),Ki("hmm",0,0,function(){return""+Oie.apply(this)+Sm(this.minutes(),2)}),Ki("hmmss",0,0,function(){return""+Oie.apply(this)+Sm(this.minutes(),2)+Sm(this.seconds(),2)}),Ki("Hmm",0,0,function(){return""+this.hours()+Sm(this.minutes(),2)}),Ki("Hmmss",0,0,function(){return""+this.hours()+Sm(this.minutes(),2)+Sm(this.seconds(),2)});function v9e(r,i){Ki(r,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),i)})}v9e("a",!0),v9e("A",!1),nd("hour","h"),rd("hour",13);function w9e(r,i){return i._meridiemParse}ci("a",w9e),ci("A",w9e),ci("H",wu),ci("h",wu),ci("k",wu),ci("HH",wu,op),ci("hh",wu,op),ci("kk",wu,op),ci("hmm",o9e),ci("hmmss",c9e),ci("Hmm",o9e),ci("Hmmss",c9e),Mc(["H","HH"],of),Mc(["k","kk"],function(r,i,o){var l=Fa(r);i[of]=l===24?0:l}),Mc(["a","A"],function(r,i,o){o._isPm=o._locale.isPM(r),o._meridiem=r}),Mc(["h","hh"],function(r,i,o){i[of]=Fa(r),ba(o).bigHour=!0}),Mc("hmm",function(r,i,o){var l=r.length-2;i[of]=Fa(r.substr(0,l)),i[kv]=Fa(r.substr(l)),ba(o).bigHour=!0}),Mc("hmmss",function(r,i,o){var l=r.length-4,f=r.length-2;i[of]=Fa(r.substr(0,l)),i[kv]=Fa(r.substr(l,2)),i[O3]=Fa(r.substr(f)),ba(o).bigHour=!0}),Mc("Hmm",function(r,i,o){var l=r.length-2;i[of]=Fa(r.substr(0,l)),i[kv]=Fa(r.substr(l))}),Mc("Hmmss",function(r,i,o){var l=r.length-4,f=r.length-2;i[of]=Fa(r.substr(0,l)),i[kv]=Fa(r.substr(l,2)),i[O3]=Fa(r.substr(f))});function qTt(r){return(r+"").toLowerCase().charAt(0)==="p"}var YTt=/[ap]\.?m?\.?/i,WTt=TT("Hours",!0);function KTt(r,i,o){return r>11?o?"pm":"PM":o?"am":"AM"}var m9e={calendar:R_t,longDateFormat:z_t,invalidDate:V_t,ordinal:q_t,dayOfMonthOrdinalParse:Y_t,relativeTime:K_t,months:uTt,monthsShort:u9e,week:xTt,weekdays:MTt,weekdaysMin:DTt,weekdaysShort:b9e,meridiemParse:YTt},Nu={},PL={},BL;function XTt(r,i){var o,l=Math.min(r.length,i.length);for(o=0;o0;){if(f=wz(b.slice(0,o).join("-")),f)return f;if(l&&l.length>=o&&XTt(b,l)>=o-1)break;o--}i++}return BL}function ZTt(r){return r.match("^[^/\\\\]*$")!=null}function wz(r){var i=null,o;if(Nu[r]===void 0&&typeof module<"u"&&module&&module.exports&&ZTt(r))try{i=BL._abbr,o=require,o("./locale/"+r),r6(i)}catch{Nu[r]=null}return Nu[r]}function r6(r,i){var o;return r&&(V0(i)?o=P3(r):o=Nie(r,i),o?BL=o:typeof console<"u"&&console.warn&&console.warn("Locale "+r+" not found. Did you forget to load it?")),BL._abbr}function Nie(r,i){if(i!==null){var o,l=m9e;if(i.abbr=r,Nu[r]!=null)t9e("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),l=Nu[r]._config;else if(i.parentLocale!=null)if(Nu[i.parentLocale]!=null)l=Nu[i.parentLocale]._config;else if(o=wz(i.parentLocale),o!=null)l=o._config;else return PL[i.parentLocale]||(PL[i.parentLocale]=[]),PL[i.parentLocale].push({name:r,config:i}),null;return Nu[r]=new Eie(xie(l,i)),PL[r]&&PL[r].forEach(function(f){Nie(f.name,f.config)}),r6(r),Nu[r]}else return delete Nu[r],null}function JTt(r,i){if(i!=null){var o,l,f=m9e;Nu[r]!=null&&Nu[r].parentLocale!=null?Nu[r].set(xie(Nu[r]._config,i)):(l=wz(r),l!=null&&(f=l._config),i=xie(f,i),l==null&&(i.abbr=r),o=new Eie(i),o.parentLocale=Nu[r],Nu[r]=o),r6(r)}else Nu[r]!=null&&(Nu[r].parentLocale!=null?(Nu[r]=Nu[r].parentLocale,r===r6()&&r6(r)):Nu[r]!=null&&delete Nu[r]);return Nu[r]}function P3(r){var i;if(r&&r._locale&&r._locale._abbr&&(r=r._locale._abbr),!r)return BL;if(!mv(r)){if(i=wz(r),i)return i;r=[r]}return QTt(r)}function eCt(){return _ie(Nu)}function Pie(r){var i,o=r._a;return o&&ba(r).overflow===-2&&(i=o[I3]<0||o[I3]>11?I3:o[Am]<1||o[Am]>bz(o[id],o[I3])?Am:o[of]<0||o[of]>24||o[of]===24&&(o[kv]!==0||o[O3]!==0||o[D8]!==0)?of:o[kv]<0||o[kv]>59?kv:o[O3]<0||o[O3]>59?O3:o[D8]<0||o[D8]>999?D8:-1,ba(r)._overflowDayOfYear&&(iAm)&&(i=Am),ba(r)._overflowWeeks&&i===-1&&(i=aTt),ba(r)._overflowWeekday&&i===-1&&(i=oTt),ba(r).overflow=i),r}var tCt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,nCt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,rCt=/Z|[+-]\d\d(?::?\d\d)?/,mz=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],Bie=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],iCt=/^\/?Date\((-?\d+)/i,sCt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,aCt={UT:0,GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function k9e(r){var i,o,l=r._i,f=tCt.exec(l)||nCt.exec(l),b,d,w,y,k=mz.length,E=Bie.length;if(f){for(ba(r).iso=!0,i=0,o=k;iIL(d)||r._dayOfYear===0)&&(ba(r)._overflowDayOfYear=!0),o=OL(d,0,r._dayOfYear),r._a[I3]=o.getUTCMonth(),r._a[Am]=o.getUTCDate()),i=0;i<3&&r._a[i]==null;++i)r._a[i]=l[i]=f[i];for(;i<7;i++)r._a[i]=l[i]=r._a[i]==null?i===2?1:0:r._a[i];r._a[of]===24&&r._a[kv]===0&&r._a[O3]===0&&r._a[D8]===0&&(r._nextDay=!0,r._a[of]=0),r._d=(r._useUTC?OL:yTt).apply(null,l),b=r._useUTC?r._d.getUTCDay():r._d.getDay(),r._tzm!=null&&r._d.setUTCMinutes(r._d.getUTCMinutes()-r._tzm),r._nextDay&&(r._a[of]=24),r._w&&typeof r._w.d<"u"&&r._w.d!==b&&(ba(r).weekdayMismatch=!0)}}function gCt(r){var i,o,l,f,b,d,w,y,k;i=r._w,i.GG!=null||i.W!=null||i.E!=null?(b=1,d=4,o=ST(i.GG,r._a[id],NL(mu(),1,4).year),l=ST(i.W,1),f=ST(i.E,1),(f<1||f>7)&&(y=!0)):(b=r._locale._week.dow,d=r._locale._week.doy,k=NL(mu(),b,d),o=ST(i.gg,r._a[id],k.year),l=ST(i.w,k.week),i.d!=null?(f=i.d,(f<0||f>6)&&(y=!0)):i.e!=null?(f=i.e+b,(i.e<0||i.e>6)&&(y=!0)):f=b),l<1||l>N3(o,b,d)?ba(r)._overflowWeeks=!0:y!=null?ba(r)._overflowWeekday=!0:(w=p9e(o,l,f,b,d),r._a[id]=w.year,r._dayOfYear=w.dayOfYear)}Ar.ISO_8601=function(){},Ar.RFC_2822=function(){};function Rie(r){if(r._f===Ar.ISO_8601){k9e(r);return}if(r._f===Ar.RFC_2822){x9e(r);return}r._a=[],ba(r).empty=!0;var i=""+r._i,o,l,f,b,d,w=i.length,y=0,k,E;for(f=n9e(r._f,r._locale).match(Tie)||[],E=f.length,o=0;o0&&ba(r).unusedInput.push(d),i=i.slice(i.indexOf(l)+l.length),y+=l.length),_T[b]?(l?ba(r).empty=!1:ba(r).unusedTokens.push(b),sTt(b,l,r)):r._strict&&!l&&ba(r).unusedTokens.push(b);ba(r).charsLeftOver=w-y,i.length>0&&ba(r).unusedInput.push(i),r._a[of]<=12&&ba(r).bigHour===!0&&r._a[of]>0&&(ba(r).bigHour=void 0),ba(r).parsedDateParts=r._a.slice(0),ba(r).meridiem=r._meridiem,r._a[of]=pCt(r._locale,r._a[of],r._meridiem),k=ba(r).era,k!==null&&(r._a[id]=r._locale.erasConvertYear(k,r._a[id])),Fie(r),Pie(r)}function pCt(r,i,o){var l;return o==null?i:r.meridiemHour!=null?r.meridiemHour(i,o):(r.isPM!=null&&(l=r.isPM(o),l&&i<12&&(i+=12),!l&&i===12&&(i=0)),i)}function bCt(r){var i,o,l,f,b,d,w=!1,y=r._f.length;if(y===0){ba(r).invalidFormat=!0,r._d=new Date(NaN);return}for(f=0;fthis?this:r:sz()});function T9e(r,i){var o,l;if(i.length===1&&mv(i[0])&&(i=i[0]),!i.length)return mu();for(o=i[0],l=1;lthis.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function FCt(){if(!V0(this._isDSTShifted))return this._isDSTShifted;var r={},i;return kie(r,this),r=E9e(r),r._a?(i=r._isUTC?Tm(r._a):mu(r._a),this._isDSTShifted=this.isValid()&&ACt(r._a,i.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function RCt(){return this.isValid()?!this._isUTC:!1}function jCt(){return this.isValid()?this._isUTC:!1}function S9e(){return this.isValid()?this._isUTC&&this._offset===0:!1}var $Ct=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,HCt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function xv(r,i){var o=r,l=null,f,b,d;return kz(r)?o={ms:r._milliseconds,d:r._days,M:r._months}:L3(r)||!isNaN(+r)?(o={},i?o[i]=+r:o.milliseconds=+r):(l=$Ct.exec(r))?(f=l[1]==="-"?-1:1,o={y:0,d:Fa(l[Am])*f,h:Fa(l[of])*f,m:Fa(l[kv])*f,s:Fa(l[O3])*f,ms:Fa(jie(l[D8]*1e3))*f}):(l=HCt.exec(r))?(f=l[1]==="-"?-1:1,o={y:L8(l[2],f),M:L8(l[3],f),w:L8(l[4],f),d:L8(l[5],f),h:L8(l[6],f),m:L8(l[7],f),s:L8(l[8],f)}):o==null?o={}:typeof o=="object"&&("from"in o||"to"in o)&&(d=zCt(mu(o.from),mu(o.to)),o={},o.ms=d.milliseconds,o.M=d.months),b=new yz(o),kz(r)&&Mo(r,"_locale")&&(b._locale=r._locale),kz(r)&&Mo(r,"_isValid")&&(b._isValid=r._isValid),b}xv.fn=yz.prototype,xv.invalid=SCt;function L8(r,i){var o=r&&parseFloat(r.replace(",","."));return(isNaN(o)?0:o)*i}function A9e(r,i){var o={};return o.months=i.month()-r.month()+(i.year()-r.year())*12,r.clone().add(o.months,"M").isAfter(i)&&--o.months,o.milliseconds=+i-+r.clone().add(o.months,"M"),o}function zCt(r,i){var o;return r.isValid()&&i.isValid()?(i=Hie(i,r),r.isBefore(i)?o=A9e(r,i):(o=A9e(i,r),o.milliseconds=-o.milliseconds,o.months=-o.months),o):{milliseconds:0,months:0}}function M9e(r,i){return function(o,l){var f,b;return l!==null&&!isNaN(+l)&&(t9e(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),b=o,o=l,l=b),f=xv(o,l),D9e(this,f,r),this}}function D9e(r,i,o,l){var f=i._milliseconds,b=jie(i._days),d=jie(i._months);!r.isValid()||(l=l==null?!0:l,d&&h9e(r,uz(r,"Month")+d*o),b&&i9e(r,"Date",uz(r,"Date")+b*o),f&&r._d.setTime(r._d.valueOf()+f*o),l&&Ar.updateOffset(r,b||d))}var GCt=M9e(1,"add"),VCt=M9e(-1,"subtract");function L9e(r){return typeof r=="string"||r instanceof String}function UCt(r){return yv(r)||SL(r)||L9e(r)||L3(r)||YCt(r)||qCt(r)||r===null||r===void 0}function qCt(r){var i=M8(r)&&!vie(r),o=!1,l=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],f,b,d=l.length;for(f=0;fo.valueOf():o.valueOf()9999?oz(o,i?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):Cm(Date.prototype.toISOString)?i?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",oz(o,"Z")):oz(o,i?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function oSt(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var r="moment",i="",o,l,f,b;return this.isLocal()||(r=this.utcOffset()===0?"moment.utc":"moment.parseZone",i="Z"),o="["+r+'("]',l=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",f="-MM-DD[T]HH:mm:ss.SSS",b=i+'[")]',this.format(o+l+f+b)}function cSt(r){r||(r=this.isUtc()?Ar.defaultFormatUtc:Ar.defaultFormat);var i=oz(this,r);return this.localeData().postformat(i)}function uSt(r,i){return this.isValid()&&(yv(r)&&r.isValid()||mu(r).isValid())?xv({to:this,from:r}).locale(this.locale()).humanize(!i):this.localeData().invalidDate()}function lSt(r){return this.from(mu(),r)}function hSt(r,i){return this.isValid()&&(yv(r)&&r.isValid()||mu(r).isValid())?xv({from:this,to:r}).locale(this.locale()).humanize(!i):this.localeData().invalidDate()}function fSt(r){return this.to(mu(),r)}function I9e(r){var i;return r===void 0?this._locale._abbr:(i=P3(r),i!=null&&(this._locale=i),this)}var O9e=C2("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(r){return r===void 0?this.localeData():this.locale(r)});function N9e(){return this._locale}var Ez=1e3,AT=60*Ez,_z=60*AT,P9e=(365*400+97)*24*_z;function MT(r,i){return(r%i+i)%i}function B9e(r,i,o){return r<100&&r>=0?new Date(r+400,i,o)-P9e:new Date(r,i,o).valueOf()}function F9e(r,i,o){return r<100&&r>=0?Date.UTC(r+400,i,o)-P9e:Date.UTC(r,i,o)}function dSt(r){var i,o;if(r=S2(r),r===void 0||r==="millisecond"||!this.isValid())return this;switch(o=this._isUTC?F9e:B9e,r){case"year":i=o(this.year(),0,1);break;case"quarter":i=o(this.year(),this.month()-this.month()%3,1);break;case"month":i=o(this.year(),this.month(),1);break;case"week":i=o(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":i=o(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":i=o(this.year(),this.month(),this.date());break;case"hour":i=this._d.valueOf(),i-=MT(i+(this._isUTC?0:this.utcOffset()*AT),_z);break;case"minute":i=this._d.valueOf(),i-=MT(i,AT);break;case"second":i=this._d.valueOf(),i-=MT(i,Ez);break}return this._d.setTime(i),Ar.updateOffset(this,!0),this}function gSt(r){var i,o;if(r=S2(r),r===void 0||r==="millisecond"||!this.isValid())return this;switch(o=this._isUTC?F9e:B9e,r){case"year":i=o(this.year()+1,0,1)-1;break;case"quarter":i=o(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":i=o(this.year(),this.month()+1,1)-1;break;case"week":i=o(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":i=o(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":i=o(this.year(),this.month(),this.date()+1)-1;break;case"hour":i=this._d.valueOf(),i+=_z-MT(i+(this._isUTC?0:this.utcOffset()*AT),_z)-1;break;case"minute":i=this._d.valueOf(),i+=AT-MT(i,AT)-1;break;case"second":i=this._d.valueOf(),i+=Ez-MT(i,Ez)-1;break}return this._d.setTime(i),Ar.updateOffset(this,!0),this}function pSt(){return this._d.valueOf()-(this._offset||0)*6e4}function bSt(){return Math.floor(this.valueOf()/1e3)}function vSt(){return new Date(this.valueOf())}function wSt(){var r=this;return[r.year(),r.month(),r.date(),r.hour(),r.minute(),r.second(),r.millisecond()]}function mSt(){var r=this;return{years:r.year(),months:r.month(),date:r.date(),hours:r.hours(),minutes:r.minutes(),seconds:r.seconds(),milliseconds:r.milliseconds()}}function ySt(){return this.isValid()?this.toISOString():null}function kSt(){return mie(this)}function xSt(){return n6({},ba(this))}function ESt(){return ba(this).overflow}function _St(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}Ki("N",0,0,"eraAbbr"),Ki("NN",0,0,"eraAbbr"),Ki("NNN",0,0,"eraAbbr"),Ki("NNNN",0,0,"eraName"),Ki("NNNNN",0,0,"eraNarrow"),Ki("y",["y",1],"yo","eraYear"),Ki("y",["yy",2],0,"eraYear"),Ki("y",["yyy",3],0,"eraYear"),Ki("y",["yyyy",4],0,"eraYear"),ci("N",Gie),ci("NN",Gie),ci("NNN",Gie),ci("NNNN",PSt),ci("NNNNN",BSt),Mc(["N","NN","NNN","NNNN","NNNNN"],function(r,i,o,l){var f=o._locale.erasParse(r,l,o._strict);f?ba(o).era=f:ba(o).invalidEra=r}),ci("y",CT),ci("yy",CT),ci("yyy",CT),ci("yyyy",CT),ci("yo",FSt),Mc(["y","yy","yyy","yyyy"],id),Mc(["yo"],function(r,i,o,l){var f;o._locale._eraYearOrdinalRegex&&(f=r.match(o._locale._eraYearOrdinalRegex)),o._locale.eraYearOrdinalParse?i[id]=o._locale.eraYearOrdinalParse(r,f):i[id]=parseInt(r,10)});function TSt(r,i){var o,l,f,b=this._eras||P3("en")._eras;for(o=0,l=b.length;o=0)return b[l]}function SSt(r,i){var o=r.since<=r.until?1:-1;return i===void 0?Ar(r.since).year():Ar(r.since).year()+(i-r.offset)*o}function ASt(){var r,i,o,l=this.localeData().eras();for(r=0,i=l.length;rb&&(i=b),VSt.call(this,r,i,o,l,f))}function VSt(r,i,o,l,f){var b=p9e(r,i,o,l,f),d=OL(b.year,0,b.dayOfYear);return this.year(d.getUTCFullYear()),this.month(d.getUTCMonth()),this.date(d.getUTCDate()),this}Ki("Q",0,"Qo","quarter"),nd("quarter","Q"),rd("quarter",7),ci("Q",s9e),Mc("Q",function(r,i){i[I3]=(Fa(r)-1)*3});function USt(r){return r==null?Math.ceil((this.month()+1)/3):this.month((r-1)*3+this.month()%3)}Ki("D",["DD",2],"Do","date"),nd("date","D"),rd("date",9),ci("D",wu),ci("DD",wu,op),ci("Do",function(r,i){return r?i._dayOfMonthOrdinalParse||i._ordinalParse:i._dayOfMonthOrdinalParseLenient}),Mc(["D","DD"],Am),Mc("Do",function(r,i){i[Am]=Fa(r.match(wu)[0])});var j9e=TT("Date",!0);Ki("DDD",["DDDD",3],"DDDo","dayOfYear"),nd("dayOfYear","DDD"),rd("dayOfYear",4),ci("DDD",hz),ci("DDDD",a9e),Mc(["DDD","DDDD"],function(r,i,o){o._dayOfYear=Fa(r)});function qSt(r){var i=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return r==null?i:this.add(r-i,"d")}Ki("m",["mm",2],0,"minute"),nd("minute","m"),rd("minute",14),ci("m",wu),ci("mm",wu,op),Mc(["m","mm"],kv);var YSt=TT("Minutes",!1);Ki("s",["ss",2],0,"second"),nd("second","s"),rd("second",15),ci("s",wu),ci("ss",wu,op),Mc(["s","ss"],O3);var WSt=TT("Seconds",!1);Ki("S",0,0,function(){return~~(this.millisecond()/100)}),Ki(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Ki(0,["SSS",3],0,"millisecond"),Ki(0,["SSSS",4],0,function(){return this.millisecond()*10}),Ki(0,["SSSSS",5],0,function(){return this.millisecond()*100}),Ki(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3}),Ki(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4}),Ki(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5}),Ki(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6}),nd("millisecond","ms"),rd("millisecond",16),ci("S",hz,s9e),ci("SS",hz,op),ci("SSS",hz,a9e);var i6,$9e;for(i6="SSSS";i6.length<=9;i6+="S")ci(i6,CT);function KSt(r,i){i[D8]=Fa(("0."+r)*1e3)}for(i6="S";i6.length<=9;i6+="S")Mc(i6,KSt);$9e=TT("Milliseconds",!1),Ki("z",0,0,"zoneAbbr"),Ki("zz",0,0,"zoneName");function XSt(){return this._isUTC?"UTC":""}function QSt(){return this._isUTC?"Coordinated Universal Time":""}var xr=AL.prototype;xr.add=GCt,xr.calendar=XCt,xr.clone=QCt,xr.diff=iSt,xr.endOf=gSt,xr.format=cSt,xr.from=uSt,xr.fromNow=lSt,xr.to=hSt,xr.toNow=fSt,xr.get=J_t,xr.invalidAt=ESt,xr.isAfter=ZCt,xr.isBefore=JCt,xr.isBetween=eSt,xr.isSame=tSt,xr.isSameOrAfter=nSt,xr.isSameOrBefore=rSt,xr.isValid=kSt,xr.lang=O9e,xr.locale=I9e,xr.localeData=N9e,xr.max=kCt,xr.min=yCt,xr.parsingFlags=xSt,xr.set=eTt,xr.startOf=dSt,xr.subtract=VCt,xr.toArray=wSt,xr.toObject=mSt,xr.toDate=vSt,xr.toISOString=aSt,xr.inspect=oSt,typeof Symbol<"u"&&Symbol.for!=null&&(xr[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),xr.toJSON=ySt,xr.toString=sSt,xr.unix=bSt,xr.valueOf=pSt,xr.creationData=_St,xr.eraName=ASt,xr.eraNarrow=MSt,xr.eraAbbr=DSt,xr.eraYear=LSt,xr.year=g9e,xr.isLeapYear=mTt,xr.weekYear=RSt,xr.isoWeekYear=jSt,xr.quarter=xr.quarters=USt,xr.month=f9e,xr.daysInMonth=bTt,xr.week=xr.weeks=TTt,xr.isoWeek=xr.isoWeeks=CTt,xr.weeksInYear=zSt,xr.weeksInWeekYear=GSt,xr.isoWeeksInYear=$St,xr.isoWeeksInISOWeekYear=HSt,xr.date=j9e,xr.day=xr.days=jTt,xr.weekday=$Tt,xr.isoWeekday=HTt,xr.dayOfYear=qSt,xr.hour=xr.hours=WTt,xr.minute=xr.minutes=YSt,xr.second=xr.seconds=WSt,xr.millisecond=xr.milliseconds=$9e,xr.utcOffset=DCt,xr.utc=ICt,xr.local=OCt,xr.parseZone=NCt,xr.hasAlignedHourOffset=PCt,xr.isDST=BCt,xr.isLocal=RCt,xr.isUtcOffset=jCt,xr.isUtc=S9e,xr.isUTC=S9e,xr.zoneAbbr=XSt,xr.zoneName=QSt,xr.dates=C2("dates accessor is deprecated. Use date instead.",j9e),xr.months=C2("months accessor is deprecated. Use month instead",f9e),xr.years=C2("years accessor is deprecated. Use year instead",g9e),xr.zone=C2("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",LCt),xr.isDSTShifted=C2("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",FCt);function ZSt(r){return mu(r*1e3)}function JSt(){return mu.apply(null,arguments).parseZone()}function H9e(r){return r}var Do=Eie.prototype;Do.calendar=j_t,Do.longDateFormat=G_t,Do.invalidDate=U_t,Do.ordinal=W_t,Do.preparse=H9e,Do.postformat=H9e,Do.relativeTime=X_t,Do.pastFuture=Q_t,Do.set=F_t,Do.eras=TSt,Do.erasParse=CSt,Do.erasConvertYear=SSt,Do.erasAbbrRegex=OSt,Do.erasNameRegex=ISt,Do.erasNarrowRegex=NSt,Do.months=fTt,Do.monthsShort=dTt,Do.monthsParse=pTt,Do.monthsRegex=wTt,Do.monthsShortRegex=vTt,Do.week=kTt,Do.firstDayOfYear=_Tt,Do.firstDayOfWeek=ETt,Do.weekdays=NTt,Do.weekdaysMin=BTt,Do.weekdaysShort=PTt,Do.weekdaysParse=RTt,Do.weekdaysRegex=zTt,Do.weekdaysShortRegex=GTt,Do.weekdaysMinRegex=VTt,Do.isPM=qTt,Do.meridiem=KTt;function Cz(r,i,o,l){var f=P3(),b=Tm().set(l,i);return f[o](b,r)}function z9e(r,i,o){if(L3(r)&&(i=r,r=void 0),r=r||"",i!=null)return Cz(r,i,o,"month");var l,f=[];for(l=0;l<12;l++)f[l]=Cz(r,l,o,"month");return f}function Uie(r,i,o,l){typeof r=="boolean"?(L3(i)&&(o=i,i=void 0),i=i||""):(i=r,o=i,r=!1,L3(i)&&(o=i,i=void 0),i=i||"");var f=P3(),b=r?f._week.dow:0,d,w=[];if(o!=null)return Cz(i,(o+b)%7,l,"day");for(d=0;d<7;d++)w[d]=Cz(i,(d+b)%7,l,"day");return w}function eAt(r,i){return z9e(r,i,"months")}function tAt(r,i){return z9e(r,i,"monthsShort")}function nAt(r,i,o){return Uie(r,i,o,"weekdays")}function rAt(r,i,o){return Uie(r,i,o,"weekdaysShort")}function iAt(r,i,o){return Uie(r,i,o,"weekdaysMin")}r6("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(r){var i=r%10,o=Fa(r%100/10)===1?"th":i===1?"st":i===2?"nd":i===3?"rd":"th";return r+o}}),Ar.lang=C2("moment.lang is deprecated. Use moment.locale instead.",r6),Ar.langData=C2("moment.langData is deprecated. Use moment.localeData instead.",P3);var B3=Math.abs;function sAt(){var r=this._data;return this._milliseconds=B3(this._milliseconds),this._days=B3(this._days),this._months=B3(this._months),r.milliseconds=B3(r.milliseconds),r.seconds=B3(r.seconds),r.minutes=B3(r.minutes),r.hours=B3(r.hours),r.months=B3(r.months),r.years=B3(r.years),this}function G9e(r,i,o,l){var f=xv(i,o);return r._milliseconds+=l*f._milliseconds,r._days+=l*f._days,r._months+=l*f._months,r._bubble()}function aAt(r,i){return G9e(this,r,i,1)}function oAt(r,i){return G9e(this,r,i,-1)}function V9e(r){return r<0?Math.floor(r):Math.ceil(r)}function cAt(){var r=this._milliseconds,i=this._days,o=this._months,l=this._data,f,b,d,w,y;return r>=0&&i>=0&&o>=0||r<=0&&i<=0&&o<=0||(r+=V9e(qie(o)+i)*864e5,i=0,o=0),l.milliseconds=r%1e3,f=A2(r/1e3),l.seconds=f%60,b=A2(f/60),l.minutes=b%60,d=A2(b/60),l.hours=d%24,i+=A2(d/24),y=A2(U9e(i)),o+=y,i-=V9e(qie(y)),w=A2(o/12),o%=12,l.days=i,l.months=o,l.years=w,this}function U9e(r){return r*4800/146097}function qie(r){return r*146097/4800}function uAt(r){if(!this.isValid())return NaN;var i,o,l=this._milliseconds;if(r=S2(r),r==="month"||r==="quarter"||r==="year")switch(i=this._days+l/864e5,o=this._months+U9e(i),r){case"month":return o;case"quarter":return o/3;case"year":return o/12}else switch(i=this._days+Math.round(qie(this._months)),r){case"week":return i/7+l/6048e5;case"day":return i+l/864e5;case"hour":return i*24+l/36e5;case"minute":return i*1440+l/6e4;case"second":return i*86400+l/1e3;case"millisecond":return Math.floor(i*864e5)+l;default:throw new Error("Unknown unit "+r)}}function lAt(){return this.isValid()?this._milliseconds+this._days*864e5+this._months%12*2592e6+Fa(this._months/12)*31536e6:NaN}function F3(r){return function(){return this.as(r)}}var hAt=F3("ms"),fAt=F3("s"),dAt=F3("m"),gAt=F3("h"),pAt=F3("d"),bAt=F3("w"),vAt=F3("M"),wAt=F3("Q"),mAt=F3("y");function yAt(){return xv(this)}function kAt(r){return r=S2(r),this.isValid()?this[r+"s"]():NaN}function I8(r){return function(){return this.isValid()?this._data[r]:NaN}}var xAt=I8("milliseconds"),EAt=I8("seconds"),_At=I8("minutes"),TAt=I8("hours"),CAt=I8("days"),SAt=I8("months"),AAt=I8("years");function MAt(){return A2(this.days()/7)}var R3=Math.round,DT={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function DAt(r,i,o,l,f){return f.relativeTime(i||1,!!o,r,l)}function LAt(r,i,o,l){var f=xv(r).abs(),b=R3(f.as("s")),d=R3(f.as("m")),w=R3(f.as("h")),y=R3(f.as("d")),k=R3(f.as("M")),E=R3(f.as("w")),T=R3(f.as("y")),C=b<=o.ss&&["s",b]||b0,C[4]=l,DAt.apply(null,C)}function IAt(r){return r===void 0?R3:typeof r=="function"?(R3=r,!0):!1}function OAt(r,i){return DT[r]===void 0?!1:i===void 0?DT[r]:(DT[r]=i,r==="s"&&(DT.ss=i-1),!0)}function NAt(r,i){if(!this.isValid())return this.localeData().invalidDate();var o=!1,l=DT,f,b;return typeof r=="object"&&(i=r,r=!1),typeof r=="boolean"&&(o=r),typeof i=="object"&&(l=Object.assign({},DT,i),i.s!=null&&i.ss==null&&(l.ss=i.s-1)),f=this.localeData(),b=LAt(this,!o,l,f),o&&(b=f.pastFuture(+this,b)),f.postformat(b)}var Yie=Math.abs;function LT(r){return(r>0)-(r<0)||+r}function Sz(){if(!this.isValid())return this.localeData().invalidDate();var r=Yie(this._milliseconds)/1e3,i=Yie(this._days),o=Yie(this._months),l,f,b,d,w=this.asSeconds(),y,k,E,T;return w?(l=A2(r/60),f=A2(l/60),r%=60,l%=60,b=A2(o/12),o%=12,d=r?r.toFixed(3).replace(/\.?0+$/,""):"",y=w<0?"-":"",k=LT(this._months)!==LT(w)?"-":"",E=LT(this._days)!==LT(w)?"-":"",T=LT(this._milliseconds)!==LT(w)?"-":"",y+"P"+(b?k+b+"Y":"")+(o?k+o+"M":"")+(i?E+i+"D":"")+(f||l||r?"T":"")+(f?T+f+"H":"")+(l?T+l+"M":"")+(r?T+d+"S":"")):"P0D"}var vo=yz.prototype;vo.isValid=CCt,vo.abs=sAt,vo.add=aAt,vo.subtract=oAt,vo.as=uAt,vo.asMilliseconds=hAt,vo.asSeconds=fAt,vo.asMinutes=dAt,vo.asHours=gAt,vo.asDays=pAt,vo.asWeeks=bAt,vo.asMonths=vAt,vo.asQuarters=wAt,vo.asYears=mAt,vo.valueOf=lAt,vo._bubble=cAt,vo.clone=yAt,vo.get=kAt,vo.milliseconds=xAt,vo.seconds=EAt,vo.minutes=_At,vo.hours=TAt,vo.days=CAt,vo.weeks=MAt,vo.months=SAt,vo.years=AAt,vo.humanize=NAt,vo.toISOString=Sz,vo.toString=Sz,vo.toJSON=Sz,vo.locale=I9e,vo.localeData=N9e,vo.toIsoString=C2("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Sz),vo.lang=O9e,Ki("X",0,0,"unix"),Ki("x",0,0,"valueOf"),ci("x",dz),ci("X",nTt),Mc("X",function(r,i,o){o._d=new Date(parseFloat(r)*1e3)}),Mc("x",function(r,i,o){o._d=new Date(Fa(r))});//! moment.js +Ar.version="2.29.4",P_t(mu),Ar.fn=xr,Ar.min=xCt,Ar.max=ECt,Ar.now=_Ct,Ar.utc=Tm,Ar.unix=ZSt,Ar.months=eAt,Ar.isDate=SL,Ar.locale=r6,Ar.invalid=sz,Ar.duration=xv,Ar.isMoment=yv,Ar.weekdays=nAt,Ar.parseZone=JSt,Ar.localeData=P3,Ar.isDuration=kz,Ar.monthsShort=tAt,Ar.weekdaysMin=iAt,Ar.defineLocale=Nie,Ar.updateLocale=JTt,Ar.locales=eCt,Ar.weekdaysShort=rAt,Ar.normalizeUnits=S2,Ar.relativeTimeRounding=IAt,Ar.relativeTimeThreshold=OAt,Ar.calendarFormat=KCt,Ar.prototype=xr,Ar.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"};const j3={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},Se={trace:(...r)=>{},debug:(...r)=>{},info:(...r)=>{},warn:(...r)=>{},error:(...r)=>{},fatal:(...r)=>{}},Wie=function(r="fatal"){let i=j3.fatal;typeof r=="string"?(r=r.toLowerCase(),r in j3&&(i=j3[r])):typeof r=="number"&&(i=r),Se.trace=()=>{},Se.debug=()=>{},Se.info=()=>{},Se.warn=()=>{},Se.error=()=>{},Se.fatal=()=>{},i<=j3.fatal&&(Se.fatal=console.error?console.error.bind(console,M2("FATAL"),"color: orange"):console.log.bind(console,"\x1B[35m",M2("FATAL"))),i<=j3.error&&(Se.error=console.error?console.error.bind(console,M2("ERROR"),"color: orange"):console.log.bind(console,"\x1B[31m",M2("ERROR"))),i<=j3.warn&&(Se.warn=console.warn?console.warn.bind(console,M2("WARN"),"color: orange"):console.log.bind(console,"\x1B[33m",M2("WARN"))),i<=j3.info&&(Se.info=console.info?console.info.bind(console,M2("INFO"),"color: lightblue"):console.log.bind(console,"\x1B[34m",M2("INFO"))),i<=j3.debug&&(Se.debug=console.debug?console.debug.bind(console,M2("DEBUG"),"color: lightgreen"):console.log.bind(console,"\x1B[32m",M2("DEBUG"))),i<=j3.trace&&(Se.trace=console.debug?console.debug.bind(console,M2("TRACE"),"color: lightgreen"):console.log.bind(console,"\x1B[32m",M2("TRACE")))},M2=r=>`%c${Ar().format("ss.SSS")} : ${r} : `;var Mm=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function q9e(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Kie={};Object.defineProperty(Kie,"__esModule",{value:!0});var $3=Kie.sanitizeUrl=void 0,PAt=/^([^\w]*)(javascript|data|vbscript)/im,BAt=/&#(\w+)(^\w|;)?/g,FAt=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim,RAt=/^([^:]+):/gm,jAt=[".","/"];function $At(r){return jAt.indexOf(r[0])>-1}function HAt(r){return r.replace(BAt,function(i,o){return String.fromCharCode(o)})}function zAt(r){var i=HAt(r||"").replace(FAt,"").trim();if(!i)return"about:blank";if($At(i))return i;var o=i.match(RAt);if(!o)return i;var l=o[0];return PAt.test(l)?"about:blank":i}$3=Kie.sanitizeUrl=zAt;function Az(r,i){return r==null||i==null?NaN:ri?1:r>=i?0:NaN}function GAt(r,i){return r==null||i==null?NaN:ir?1:i>=r?0:NaN}function Xie(r){let i,o,l;r.length!==2?(i=Az,o=(w,y)=>Az(r(w),y),l=(w,y)=>r(w)-y):(i=r===Az||r===GAt?r:VAt,o=r,l=r);function f(w,y,k=0,E=w.length){if(k>>1;o(w[T],y)<0?k=T+1:E=T}while(k>>1;o(w[T],y)<=0?k=T+1:E=T}while(kk&&l(w[T-1],y)>-l(w[T],y)?T-1:T}return{left:f,center:d,right:b}}function VAt(){return 0}function UAt(r){return r===null?NaN:+r}const qAt=Xie(Az).right;Xie(UAt).center;const YAt=qAt;class Y9e extends Map{constructor(i,o=XAt){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:o}}),i!=null)for(const[l,f]of i)this.set(l,f)}get(i){return super.get(W9e(this,i))}has(i){return super.has(W9e(this,i))}set(i,o){return super.set(WAt(this,i),o)}delete(i){return super.delete(KAt(this,i))}}function W9e({_intern:r,_key:i},o){const l=i(o);return r.has(l)?r.get(l):o}function WAt({_intern:r,_key:i},o){const l=i(o);return r.has(l)?r.get(l):(r.set(l,o),o)}function KAt({_intern:r,_key:i},o){const l=i(o);return r.has(l)&&(o=r.get(l),r.delete(l)),o}function XAt(r){return r!==null&&typeof r=="object"?r.valueOf():r}var Qie=Math.sqrt(50),Zie=Math.sqrt(10),Jie=Math.sqrt(2);function QAt(r,i,o){var l,f=-1,b,d,w;if(i=+i,r=+r,o=+o,r===i&&o>0)return[r];if((l=i0){let y=Math.round(r/w),k=Math.round(i/w);for(y*wi&&--k,d=new Array(b=k-y+1);++fi&&--k,d=new Array(b=k-y+1);++f=0?(b>=Qie?10:b>=Zie?5:b>=Jie?2:1)*Math.pow(10,f):-Math.pow(10,-f)/(b>=Qie?10:b>=Zie?5:b>=Jie?2:1)}function ese(r,i,o){var l=Math.abs(i-r)/Math.max(0,o),f=Math.pow(10,Math.floor(Math.log(l)/Math.LN10)),b=l/f;return b>=Qie?f*=10:b>=Zie?f*=5:b>=Jie&&(f*=2),i=l)&&(o=l);else{let l=-1;for(let f of r)(f=i(f,++l,r))!=null&&(o=f)&&(o=f)}return o}function JAt(r,i){let o;if(i===void 0)for(const l of r)l!=null&&(o>l||o===void 0&&l>=l)&&(o=l);else{let l=-1;for(let f of r)(f=i(f,++l,r))!=null&&(o>f||o===void 0&&f>=f)&&(o=f)}return o}function eMt(r){return r}var Mz=1,tse=2,nse=3,Dz=4,X9e=1e-6;function tMt(r){return"translate("+r+",0)"}function nMt(r){return"translate(0,"+r+")"}function rMt(r){return i=>+r(i)}function iMt(r,i){return i=Math.max(0,r.bandwidth()-i*2)/2,r.round()&&(i=Math.round(i)),o=>+r(o)+i}function sMt(){return!this.__axis}function Q9e(r,i){var o=[],l=null,f=null,b=6,d=6,w=3,y=typeof window<"u"&&window.devicePixelRatio>1?0:.5,k=r===Mz||r===Dz?-1:1,E=r===Dz||r===tse?"x":"y",T=r===Mz||r===nse?tMt:nMt;function C(S){var L=l==null?i.ticks?i.ticks.apply(i,o):i.domain():l,O=f==null?i.tickFormat?i.tickFormat.apply(i,o):eMt:f,B=Math.max(b,0)+w,N=i.range(),F=+N[0]+y,R=+N[N.length-1]+y,q=(i.bandwidth?iMt:rMt)(i.copy(),y),X=S.selection?S.selection():S,te=X.selectAll(".domain").data([null]),H=X.selectAll(".tick").data(L,i).order(),Y=H.exit(),z=H.enter().append("g").attr("class","tick"),W=H.select("line"),Z=H.select("text");te=te.merge(te.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),H=H.merge(z),W=W.merge(z.append("line").attr("stroke","currentColor").attr(E+"2",k*b)),Z=Z.merge(z.append("text").attr("fill","currentColor").attr(E,k*B).attr("dy",r===Mz?"0em":r===nse?"0.71em":"0.32em")),S!==X&&(te=te.transition(S),H=H.transition(S),W=W.transition(S),Z=Z.transition(S),Y=Y.transition(S).attr("opacity",X9e).attr("transform",function(G){return isFinite(G=q(G))?T(G+y):this.getAttribute("transform")}),z.attr("opacity",X9e).attr("transform",function(G){var ae=this.parentNode.__axis;return T((ae&&isFinite(ae=ae(G))?ae:q(G))+y)})),Y.remove(),te.attr("d",r===Dz||r===tse?d?"M"+k*d+","+F+"H"+y+"V"+R+"H"+k*d:"M"+y+","+F+"V"+R:d?"M"+F+","+k*d+"V"+y+"H"+R+"V"+k*d:"M"+F+","+y+"H"+R),H.attr("opacity",1).attr("transform",function(G){return T(q(G)+y)}),W.attr(E+"2",k*b),Z.attr(E,k*B).text(O),X.filter(sMt).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",r===tse?"start":r===Dz?"end":"middle"),X.each(function(){this.__axis=q})}return C.scale=function(S){return arguments.length?(i=S,C):i},C.ticks=function(){return o=Array.from(arguments),C},C.tickArguments=function(S){return arguments.length?(o=S==null?[]:Array.from(S),C):o.slice()},C.tickValues=function(S){return arguments.length?(l=S==null?null:Array.from(S),C):l&&l.slice()},C.tickFormat=function(S){return arguments.length?(f=S,C):f},C.tickSize=function(S){return arguments.length?(b=d=+S,C):b},C.tickSizeInner=function(S){return arguments.length?(b=+S,C):b},C.tickSizeOuter=function(S){return arguments.length?(d=+S,C):d},C.tickPadding=function(S){return arguments.length?(w=+S,C):w},C.offset=function(S){return arguments.length?(y=+S,C):y},C}function aMt(r){return Q9e(Mz,r)}function oMt(r){return Q9e(nse,r)}var cMt={value:()=>{}};function Z9e(){for(var r=0,i=arguments.length,o={},l;r=0&&(l=o.slice(f+1),o=o.slice(0,f)),o&&!i.hasOwnProperty(o))throw new Error("unknown type: "+o);return{type:o,name:l}})}Lz.prototype=Z9e.prototype={constructor:Lz,on:function(r,i){var o=this._,l=uMt(r+"",o),f,b=-1,d=l.length;if(arguments.length<2){for(;++b0)for(var o=new Array(f),l=0,f,b;l=0&&(i=r.slice(0,o))!=="xmlns"&&(r=r.slice(o+1)),e_e.hasOwnProperty(i)?{space:e_e[i],local:r}:r}function hMt(r){return function(){var i=this.ownerDocument,o=this.namespaceURI;return o===rse&&i.documentElement.namespaceURI===rse?i.createElement(r):i.createElementNS(o,r)}}function fMt(r){return function(){return this.ownerDocument.createElementNS(r.space,r.local)}}function t_e(r){var i=Iz(r);return(i.local?fMt:hMt)(i)}function dMt(){}function ise(r){return r==null?dMt:function(){return this.querySelector(r)}}function gMt(r){typeof r!="function"&&(r=ise(r));for(var i=this._groups,o=i.length,l=new Array(o),f=0;f=R&&(R=F+1);!(X=B[R])&&++R=0;)(d=l[f])&&(b&&d.compareDocumentPosition(b)^4&&b.parentNode.insertBefore(d,b),b=d);return this}function RMt(r){r||(r=jMt);function i(T,C){return T&&C?r(T.__data__,C.__data__):!T-!C}for(var o=this._groups,l=o.length,f=new Array(l),b=0;bi?1:r>=i?0:NaN}function $Mt(){var r=arguments[0];return arguments[0]=this,r.apply(null,arguments),this}function HMt(){return Array.from(this)}function zMt(){for(var r=this._groups,i=0,o=r.length;i1?this.each((i==null?JMt:typeof i=="function"?tDt:eDt)(r,i,o==null?"":o)):IT(this.node(),r)}function IT(r,i){return r.style.getPropertyValue(i)||o_e(r).getComputedStyle(r,null).getPropertyValue(i)}function rDt(r){return function(){delete this[r]}}function iDt(r,i){return function(){this[r]=i}}function sDt(r,i){return function(){var o=i.apply(this,arguments);o==null?delete this[r]:this[r]=o}}function aDt(r,i){return arguments.length>1?this.each((i==null?rDt:typeof i=="function"?sDt:iDt)(r,i)):this.node()[r]}function c_e(r){return r.trim().split(/^|\s+/)}function sse(r){return r.classList||new u_e(r)}function u_e(r){this._node=r,this._names=c_e(r.getAttribute("class")||"")}u_e.prototype={add:function(r){var i=this._names.indexOf(r);i<0&&(this._names.push(r),this._node.setAttribute("class",this._names.join(" ")))},remove:function(r){var i=this._names.indexOf(r);i>=0&&(this._names.splice(i,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(r){return this._names.indexOf(r)>=0}};function l_e(r,i){for(var o=sse(r),l=-1,f=i.length;++l=0&&(o=i.slice(l+1),i=i.slice(0,l)),{type:i,name:o}})}function NDt(r){return function(){var i=this.__on;if(!!i){for(var o=0,l=-1,f=i.length,b;o>8&15|i>>4&240,i>>4&15|i&240,(i&15)<<4|i&15,1):o===8?Bz(i>>24&255,i>>16&255,i>>8&255,(i&255)/255):o===4?Bz(i>>12&15|i>>8&240,i>>8&15|i>>4&240,i>>4&15|i&240,((i&15)<<4|i&15)/255):null):(i=GDt.exec(r))?new sd(i[1],i[2],i[3],1):(i=VDt.exec(r))?new sd(i[1]*255/100,i[2]*255/100,i[3]*255/100,1):(i=UDt.exec(r))?Bz(i[1],i[2],i[3],i[4]):(i=qDt.exec(r))?Bz(i[1]*255/100,i[2]*255/100,i[3]*255/100,i[4]):(i=YDt.exec(r))?y_e(i[1],i[2]/100,i[3]/100,1):(i=WDt.exec(r))?y_e(i[1],i[2]/100,i[3]/100,i[4]):d_e.hasOwnProperty(r)?b_e(d_e[r]):r==="transparent"?new sd(NaN,NaN,NaN,0):null}function b_e(r){return new sd(r>>16&255,r>>8&255,r&255,1)}function Bz(r,i,o,l){return l<=0&&(r=i=o=NaN),new sd(r,i,o,l)}function v_e(r){return r instanceof O8||(r=N8(r)),r?(r=r.rgb(),new sd(r.r,r.g,r.b,r.opacity)):new sd}function cse(r,i,o,l){return arguments.length===1?v_e(r):new sd(r,i,o,l==null?1:l)}function sd(r,i,o,l){this.r=+r,this.g=+i,this.b=+o,this.opacity=+l}jL(sd,cse,Nz(O8,{brighter(r){return r=r==null?Pz:Math.pow(Pz,r),new sd(this.r*r,this.g*r,this.b*r,this.opacity)},darker(r){return r=r==null?$L:Math.pow($L,r),new sd(this.r*r,this.g*r,this.b*r,this.opacity)},rgb(){return this},clamp(){return new sd(P8(this.r),P8(this.g),P8(this.b),Fz(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:w_e,formatHex:w_e,formatHex8:QDt,formatRgb:m_e,toString:m_e}));function w_e(){return`#${B8(this.r)}${B8(this.g)}${B8(this.b)}`}function QDt(){return`#${B8(this.r)}${B8(this.g)}${B8(this.b)}${B8((isNaN(this.opacity)?1:this.opacity)*255)}`}function m_e(){const r=Fz(this.opacity);return`${r===1?"rgb(":"rgba("}${P8(this.r)}, ${P8(this.g)}, ${P8(this.b)}${r===1?")":`, ${r})`}`}function Fz(r){return isNaN(r)?1:Math.max(0,Math.min(1,r))}function P8(r){return Math.max(0,Math.min(255,Math.round(r)||0))}function B8(r){return r=P8(r),(r<16?"0":"")+r.toString(16)}function y_e(r,i,o,l){return l<=0?r=i=o=NaN:o<=0||o>=1?r=i=NaN:i<=0&&(r=NaN),new Ev(r,i,o,l)}function k_e(r){if(r instanceof Ev)return new Ev(r.h,r.s,r.l,r.opacity);if(r instanceof O8||(r=N8(r)),!r)return new Ev;if(r instanceof Ev)return r;r=r.rgb();var i=r.r/255,o=r.g/255,l=r.b/255,f=Math.min(i,o,l),b=Math.max(i,o,l),d=NaN,w=b-f,y=(b+f)/2;return w?(i===b?d=(o-l)/w+(o0&&y<1?0:d,new Ev(d,w,y,r.opacity)}function ZDt(r,i,o,l){return arguments.length===1?k_e(r):new Ev(r,i,o,l==null?1:l)}function Ev(r,i,o,l){this.h=+r,this.s=+i,this.l=+o,this.opacity=+l}jL(Ev,ZDt,Nz(O8,{brighter(r){return r=r==null?Pz:Math.pow(Pz,r),new Ev(this.h,this.s,this.l*r,this.opacity)},darker(r){return r=r==null?$L:Math.pow($L,r),new Ev(this.h,this.s,this.l*r,this.opacity)},rgb(){var r=this.h%360+(this.h<0)*360,i=isNaN(r)||isNaN(this.s)?0:this.s,o=this.l,l=o+(o<.5?o:1-o)*i,f=2*o-l;return new sd(use(r>=240?r-240:r+120,f,l),use(r,f,l),use(r<120?r+240:r-120,f,l),this.opacity)},clamp(){return new Ev(x_e(this.h),Rz(this.s),Rz(this.l),Fz(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const r=Fz(this.opacity);return`${r===1?"hsl(":"hsla("}${x_e(this.h)}, ${Rz(this.s)*100}%, ${Rz(this.l)*100}%${r===1?")":`, ${r})`}`}}));function x_e(r){return r=(r||0)%360,r<0?r+360:r}function Rz(r){return Math.max(0,Math.min(1,r||0))}function use(r,i,o){return(r<60?i+(o-i)*r/60:r<180?o:r<240?i+(o-i)*(240-r)/60:i)*255}const JDt=Math.PI/180,eLt=180/Math.PI,jz=18,E_e=.96422,__e=1,T_e=.82521,C_e=4/29,NT=6/29,S_e=3*NT*NT,tLt=NT*NT*NT;function A_e(r){if(r instanceof Lm)return new Lm(r.l,r.a,r.b,r.opacity);if(r instanceof H3)return M_e(r);r instanceof sd||(r=v_e(r));var i=dse(r.r),o=dse(r.g),l=dse(r.b),f=lse((.2225045*i+.7168786*o+.0606169*l)/__e),b,d;return i===o&&o===l?b=d=f:(b=lse((.4360747*i+.3850649*o+.1430804*l)/E_e),d=lse((.0139322*i+.0971045*o+.7141733*l)/T_e)),new Lm(116*f-16,500*(b-f),200*(f-d),r.opacity)}function nLt(r,i,o,l){return arguments.length===1?A_e(r):new Lm(r,i,o,l==null?1:l)}function Lm(r,i,o,l){this.l=+r,this.a=+i,this.b=+o,this.opacity=+l}jL(Lm,nLt,Nz(O8,{brighter(r){return new Lm(this.l+jz*(r==null?1:r),this.a,this.b,this.opacity)},darker(r){return new Lm(this.l-jz*(r==null?1:r),this.a,this.b,this.opacity)},rgb(){var r=(this.l+16)/116,i=isNaN(this.a)?r:r+this.a/500,o=isNaN(this.b)?r:r-this.b/200;return i=E_e*hse(i),r=__e*hse(r),o=T_e*hse(o),new sd(fse(3.1338561*i-1.6168667*r-.4906146*o),fse(-.9787684*i+1.9161415*r+.033454*o),fse(.0719453*i-.2289914*r+1.4052427*o),this.opacity)}}));function lse(r){return r>tLt?Math.pow(r,1/3):r/S_e+C_e}function hse(r){return r>NT?r*r*r:S_e*(r-C_e)}function fse(r){return 255*(r<=.0031308?12.92*r:1.055*Math.pow(r,1/2.4)-.055)}function dse(r){return(r/=255)<=.04045?r/12.92:Math.pow((r+.055)/1.055,2.4)}function rLt(r){if(r instanceof H3)return new H3(r.h,r.c,r.l,r.opacity);if(r instanceof Lm||(r=A_e(r)),r.a===0&&r.b===0)return new H3(NaN,0()=>r;function D_e(r,i){return function(o){return r+o*i}}function iLt(r,i,o){return r=Math.pow(r,o),i=Math.pow(i,o)-r,o=1/o,function(l){return Math.pow(r+l*i,o)}}function sLt(r,i){var o=i-r;return o?D_e(r,o>180||o<-180?o-360*Math.round(o/360):o):$z(isNaN(r)?i:r)}function aLt(r){return(r=+r)==1?zL:function(i,o){return o-i?iLt(i,o,r):$z(isNaN(i)?o:i)}}function zL(r,i){var o=i-r;return o?D_e(r,o):$z(isNaN(r)?i:r)}const Hz=function r(i){var o=aLt(i);function l(f,b){var d=o((f=cse(f)).r,(b=cse(b)).r),w=o(f.g,b.g),y=o(f.b,b.b),k=zL(f.opacity,b.opacity);return function(E){return f.r=d(E),f.g=w(E),f.b=y(E),f.opacity=k(E),f+""}}return l.gamma=r,l}(1);function oLt(r,i){i||(i=[]);var o=r?Math.min(i.length,r.length):0,l=i.slice(),f;return function(b){for(f=0;fo&&(b=i.slice(o,b),w[d]?w[d]+=b:w[++d]=b),(l=l[0])===(f=f[0])?w[d]?w[d]+=f:w[++d]=f:(w[++d]=null,y.push({i:d,x:_v(l,f)})),o=bse.lastIndex;return o180?E+=360:E-k>180&&(k+=360),C.push({i:T.push(f(T)+"rotate(",null,l)-2,x:_v(k,E)})):E&&T.push(f(T)+"rotate("+E+l)}function w(k,E,T,C){k!==E?C.push({i:T.push(f(T)+"skewX(",null,l)-2,x:_v(k,E)}):E&&T.push(f(T)+"skewX("+E+l)}function y(k,E,T,C,S,L){if(k!==T||E!==C){var O=S.push(f(S)+"scale(",null,",",null,")");L.push({i:O-4,x:_v(k,T)},{i:O-2,x:_v(E,C)})}else(T!==1||C!==1)&&S.push(f(S)+"scale("+T+","+C+")")}return function(k,E){var T=[],C=[];return k=r(k),E=r(E),b(k.translateX,k.translateY,E.translateX,E.translateY,T,C),d(k.rotate,E.rotate,T,C),w(k.skewX,E.skewX,T,C),y(k.scaleX,k.scaleY,E.scaleX,E.scaleY,T,C),k=E=null,function(S){for(var L=-1,O=C.length,B;++L=0&&r._call.call(void 0,i),r=r._next;--PT}function R_e(){F8=(Vz=qL.now())+Uz,PT=GL=0;try{xLt()}finally{PT=0,_Lt(),F8=0}}function ELt(){var r=qL.now(),i=r-Vz;i>P_e&&(Uz-=i,Vz=r)}function _Lt(){for(var r,i=Gz,o,l=1/0;i;)i._call?(l>i._time&&(l=i._time),r=i,i=i._next):(o=i._next,i._next=null,i=r?r._next=o:Gz=o);UL=r,yse(l)}function yse(r){if(!PT){GL&&(GL=clearTimeout(GL));var i=r-F8;i>24?(r<1/0&&(GL=setTimeout(R_e,r-qL.now()-Uz)),VL&&(VL=clearInterval(VL))):(VL||(Vz=qL.now(),VL=setInterval(ELt,P_e)),PT=1,B_e(R_e))}}function j_e(r,i,o){var l=new qz;return i=i==null?0:+i,l.restart(f=>{l.stop(),r(f+i)},i,o),l}var TLt=Z9e("start","end","cancel","interrupt"),CLt=[],$_e=0,H_e=1,kse=2,Yz=3,z_e=4,xse=5,Wz=6;function Kz(r,i,o,l,f,b){var d=r.__transition;if(!d)r.__transition={};else if(o in d)return;SLt(r,o,{name:i,index:l,group:f,on:TLt,tween:CLt,time:b.time,delay:b.delay,duration:b.duration,ease:b.ease,timer:null,state:$_e})}function Ese(r,i){var o=Tv(r,i);if(o.state>$_e)throw new Error("too late; already scheduled");return o}function Im(r,i){var o=Tv(r,i);if(o.state>Yz)throw new Error("too late; already running");return o}function Tv(r,i){var o=r.__transition;if(!o||!(o=o[i]))throw new Error("transition not found");return o}function SLt(r,i,o){var l=r.__transition,f;l[i]=o,o.timer=F_e(b,0,o.time);function b(k){o.state=H_e,o.timer.restart(d,o.delay,o.time),o.delay<=k&&d(k-o.delay)}function d(k){var E,T,C,S;if(o.state!==H_e)return y();for(E in l)if(S=l[E],S.name===o.name){if(S.state===Yz)return j_e(d);S.state===z_e?(S.state=Wz,S.timer.stop(),S.on.call("interrupt",r,r.__data__,S.index,S.group),delete l[E]):+Ekse&&l.state=0&&(i=i.slice(0,o)),!i||i==="start"})}function iIt(r,i,o){var l,f,b=rIt(i)?Ese:Im;return function(){var d=b(this,r),w=d.on;w!==l&&(f=(l=w).copy()).on(i,o),d.on=f}}function sIt(r,i){var o=this._id;return arguments.length<2?Tv(this.node(),o).on.on(r):this.each(iIt(o,r,i))}function aIt(r){return function(){var i=this.parentNode;for(var o in this.__transition)if(+o!==r)return;i&&i.removeChild(this)}}function oIt(){return this.on("end.remove",aIt(this._id))}function cIt(r){var i=this._name,o=this._id;typeof r!="function"&&(r=ise(r));for(var l=this._groups,f=l.length,b=new Array(f),d=0;dR8)if(!(Math.abs(E*w-y*k)>R8)||!f)this._+="L"+(this._x1=r)+","+(this._y1=i);else{var C=o-b,S=l-d,L=w*w+y*y,O=C*C+S*S,B=Math.sqrt(L),N=Math.sqrt(T),F=f*Math.tan((Tse-Math.acos((L+T-O)/(2*B*N)))/2),R=F/N,q=F/B;Math.abs(R-1)>R8&&(this._+="L"+(r+R*k)+","+(i+R*E)),this._+="A"+f+","+f+",0,0,"+ +(E*C>k*S)+","+(this._x1=r+q*w)+","+(this._y1=i+q*y)}},arc:function(r,i,o,l,f,b){r=+r,i=+i,o=+o,b=!!b;var d=o*Math.cos(l),w=o*Math.sin(l),y=r+d,k=i+w,E=1^b,T=b?l-f:f-l;if(o<0)throw new Error("negative radius: "+o);this._x1===null?this._+="M"+y+","+k:(Math.abs(this._x1-y)>R8||Math.abs(this._y1-k)>R8)&&(this._+="L"+y+","+k),o&&(T<0&&(T=T%Cse+Cse),T>OIt?this._+="A"+o+","+o+",0,1,"+E+","+(r-d)+","+(i-w)+"A"+o+","+o+",0,1,"+E+","+(this._x1=y)+","+(this._y1=k):T>R8&&(this._+="A"+o+","+o+",0,"+ +(T>=Tse)+","+E+","+(this._x1=r+o*Math.cos(f))+","+(this._y1=i+o*Math.sin(f))))},rect:function(r,i,o,l){this._+="M"+(this._x0=this._x1=+r)+","+(this._y0=this._y1=+i)+"h"+ +o+"v"+ +l+"h"+-o+"Z"},toString:function(){return this._}};function NIt(r){if(!r.ok)throw new Error(r.status+" "+r.statusText);return r.text()}function PIt(r,i){return fetch(r,i).then(NIt)}function BIt(r){return(i,o)=>PIt(i,o).then(l=>new DOMParser().parseFromString(l,r))}var FIt=BIt("image/svg+xml");function RIt(r){return Math.abs(r=Math.round(r))>=1e21?r.toLocaleString("en").replace(/,/g,""):r.toString(10)}function Xz(r,i){if((o=(r=i?r.toExponential(i-1):r.toExponential()).indexOf("e"))<0)return null;var o,l=r.slice(0,o);return[l.length>1?l[0]+l.slice(2):l,+r.slice(o+1)]}function BT(r){return r=Xz(Math.abs(r)),r?r[1]:NaN}function jIt(r,i){return function(o,l){for(var f=o.length,b=[],d=0,w=r[0],y=0;f>0&&w>0&&(y+w+1>l&&(w=Math.max(1,l-y)),b.push(o.substring(f-=w,f+w)),!((y+=w+1)>l));)w=r[d=(d+1)%r.length];return b.reverse().join(i)}}function $It(r){return function(i){return i.replace(/[0-9]/g,function(o){return r[+o]})}}var HIt=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Qz(r){if(!(i=HIt.exec(r)))throw new Error("invalid format: "+r);var i;return new Mse({fill:i[1],align:i[2],sign:i[3],symbol:i[4],zero:i[5],width:i[6],comma:i[7],precision:i[8]&&i[8].slice(1),trim:i[9],type:i[10]})}Qz.prototype=Mse.prototype;function Mse(r){this.fill=r.fill===void 0?" ":r.fill+"",this.align=r.align===void 0?">":r.align+"",this.sign=r.sign===void 0?"-":r.sign+"",this.symbol=r.symbol===void 0?"":r.symbol+"",this.zero=!!r.zero,this.width=r.width===void 0?void 0:+r.width,this.comma=!!r.comma,this.precision=r.precision===void 0?void 0:+r.precision,this.trim=!!r.trim,this.type=r.type===void 0?"":r.type+""}Mse.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function zIt(r){e:for(var i=r.length,o=1,l=-1,f;o0&&(l=0);break}return l>0?r.slice(0,l)+r.slice(f+1):r}var q_e;function GIt(r,i){var o=Xz(r,i);if(!o)return r+"";var l=o[0],f=o[1],b=f-(q_e=Math.max(-8,Math.min(8,Math.floor(f/3)))*3)+1,d=l.length;return b===d?l:b>d?l+new Array(b-d+1).join("0"):b>0?l.slice(0,b)+"."+l.slice(b):"0."+new Array(1-b).join("0")+Xz(r,Math.max(0,i+b-1))[0]}function Y_e(r,i){var o=Xz(r,i);if(!o)return r+"";var l=o[0],f=o[1];return f<0?"0."+new Array(-f).join("0")+l:l.length>f+1?l.slice(0,f+1)+"."+l.slice(f+1):l+new Array(f-l.length+2).join("0")}const W_e={"%":(r,i)=>(r*100).toFixed(i),b:r=>Math.round(r).toString(2),c:r=>r+"",d:RIt,e:(r,i)=>r.toExponential(i),f:(r,i)=>r.toFixed(i),g:(r,i)=>r.toPrecision(i),o:r=>Math.round(r).toString(8),p:(r,i)=>Y_e(r*100,i),r:Y_e,s:GIt,X:r=>Math.round(r).toString(16).toUpperCase(),x:r=>Math.round(r).toString(16)};function K_e(r){return r}var X_e=Array.prototype.map,Q_e=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];function VIt(r){var i=r.grouping===void 0||r.thousands===void 0?K_e:jIt(X_e.call(r.grouping,Number),r.thousands+""),o=r.currency===void 0?"":r.currency[0]+"",l=r.currency===void 0?"":r.currency[1]+"",f=r.decimal===void 0?".":r.decimal+"",b=r.numerals===void 0?K_e:$It(X_e.call(r.numerals,String)),d=r.percent===void 0?"%":r.percent+"",w=r.minus===void 0?"\u2212":r.minus+"",y=r.nan===void 0?"NaN":r.nan+"";function k(T){T=Qz(T);var C=T.fill,S=T.align,L=T.sign,O=T.symbol,B=T.zero,N=T.width,F=T.comma,R=T.precision,q=T.trim,X=T.type;X==="n"?(F=!0,X="g"):W_e[X]||(R===void 0&&(R=12),q=!0,X="g"),(B||C==="0"&&S==="=")&&(B=!0,C="0",S="=");var te=O==="$"?o:O==="#"&&/[boxX]/.test(X)?"0"+X.toLowerCase():"",H=O==="$"?l:/[%p]/.test(X)?d:"",Y=W_e[X],z=/[defgprs%]/.test(X);R=R===void 0?6:/[gprs]/.test(X)?Math.max(1,Math.min(21,R)):Math.max(0,Math.min(20,R));function W(Z){var G=te,ae=H,$,ge,ee;if(X==="c")ae=Y(Z)+ae,Z="";else{Z=+Z;var de=Z<0||1/Z<0;if(Z=isNaN(Z)?y:Y(Math.abs(Z),R),q&&(Z=zIt(Z)),de&&+Z==0&&L!=="+"&&(de=!1),G=(de?L==="("?L:w:L==="-"||L==="("?"":L)+G,ae=(X==="s"?Q_e[8+q_e/3]:"")+ae+(de&&L==="("?")":""),z){for($=-1,ge=Z.length;++$ee||ee>57){ae=(ee===46?f+Z.slice($+1):Z.slice($))+ae,Z=Z.slice(0,$);break}}}F&&!B&&(Z=i(Z,1/0));var re=G.length+Z.length+ae.length,ke=re>1)+G+Z+ae+ke.slice(re);break;default:Z=ke+G+Z+ae;break}return b(Z)}return W.toString=function(){return T+""},W}function E(T,C){var S=k((T=Qz(T),T.type="f",T)),L=Math.max(-8,Math.min(8,Math.floor(BT(C)/3)))*3,O=Math.pow(10,-L),B=Q_e[8+L/3];return function(N){return S(O*N)+B}}return{format:k,formatPrefix:E}}var Zz,Z_e,J_e;UIt({thousands:",",grouping:[3],currency:["$",""]});function UIt(r){return Zz=VIt(r),Z_e=Zz.format,J_e=Zz.formatPrefix,Zz}function qIt(r){return Math.max(0,-BT(Math.abs(r)))}function YIt(r,i){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(BT(i)/3)))*3-BT(Math.abs(r)))}function WIt(r,i){return r=Math.abs(r),i=Math.abs(i)-r,Math.max(0,BT(i)-BT(r))+1}function Dse(r,i){switch(arguments.length){case 0:break;case 1:this.range(r);break;default:this.range(i).domain(r);break}return this}const eTe=Symbol("implicit");function tTe(){var r=new Y9e,i=[],o=[],l=eTe;function f(b){let d=r.get(b);if(d===void 0){if(l!==eTe)return l;r.set(b,d=i.push(b)-1)}return o[d%o.length]}return f.domain=function(b){if(!arguments.length)return i.slice();i=[],r=new Y9e;for(const d of b)r.has(d)||r.set(d,i.push(d)-1);return f},f.range=function(b){return arguments.length?(o=Array.from(b),f):o.slice()},f.unknown=function(b){return arguments.length?(l=b,f):l},f.copy=function(){return tTe(i,o).unknown(l)},Dse.apply(f,arguments),f}function KIt(r){return function(){return r}}function XIt(r){return+r}var nTe=[0,1];function FT(r){return r}function Lse(r,i){return(i-=r=+r)?function(o){return(o-r)/i}:KIt(isNaN(i)?NaN:.5)}function QIt(r,i){var o;return r>i&&(o=r,r=i,i=o),function(l){return Math.max(r,Math.min(i,l))}}function ZIt(r,i,o){var l=r[0],f=r[1],b=i[0],d=i[1];return f2?JIt:ZIt,y=k=null,T}function T(C){return C==null||isNaN(C=+C)?b:(y||(y=w(r.map(l),i,o)))(l(d(C)))}return T.invert=function(C){return d(f((k||(k=w(i,r.map(l),_v)))(C)))},T.domain=function(C){return arguments.length?(r=Array.from(C,XIt),E()):r.slice()},T.range=function(C){return arguments.length?(i=Array.from(C),E()):i.slice()},T.rangeRound=function(C){return i=Array.from(C),o=gLt,E()},T.clamp=function(C){return arguments.length?(d=C?!0:FT,E()):d!==FT},T.interpolate=function(C){return arguments.length?(o=C,E()):o},T.unknown=function(C){return arguments.length?(b=C,T):b},function(C,S){return l=C,f=S,E()}}function iTe(){return eOt()(FT,FT)}function tOt(r,i,o,l){var f=ese(r,i,o),b;switch(l=Qz(l==null?",f":l),l.type){case"s":{var d=Math.max(Math.abs(r),Math.abs(i));return l.precision==null&&!isNaN(b=YIt(f,d))&&(l.precision=b),J_e(l,d)}case"":case"e":case"g":case"p":case"r":{l.precision==null&&!isNaN(b=WIt(f,Math.max(Math.abs(r),Math.abs(i))))&&(l.precision=b-(l.type==="e"));break}case"f":case"%":{l.precision==null&&!isNaN(b=qIt(f))&&(l.precision=b-(l.type==="%")*2);break}}return Z_e(l)}function nOt(r){var i=r.domain;return r.ticks=function(o){var l=i();return QAt(l[0],l[l.length-1],o==null?10:o)},r.tickFormat=function(o,l){var f=i();return tOt(f[0],f[f.length-1],o==null?10:o,l)},r.nice=function(o){o==null&&(o=10);var l=i(),f=0,b=l.length-1,d=l[f],w=l[b],y,k,E=10;for(w0;){if(k=K9e(d,w,o),k===y)return l[f]=d,l[b]=w,i(l);if(k>0)d=Math.floor(d/k)*k,w=Math.ceil(w/k)*k;else if(k<0)d=Math.ceil(d*k)/k,w=Math.floor(w*k)/k;else break;y=k}return r},r}function sTe(){var r=iTe();return r.copy=function(){return rTe(r,sTe())},Dse.apply(r,arguments),nOt(r)}function rOt(r,i){r=r.slice();var o=0,l=r.length-1,f=r[o],b=r[l],d;return b0))return y;do y.push(k=new Date(+b)),i(b,w),r(b);while(k=d)for(;r(d),!b(d);)d.setTime(d-1)},function(d,w){if(d>=d)if(w<0)for(;++w<=0;)for(;i(d,-1),!b(d););else for(;--w>=0;)for(;i(d,1),!b(d););})},o&&(f.count=function(b,d){return Ise.setTime(+b),Ose.setTime(+d),r(Ise),r(Ose),Math.floor(o(Ise,Ose))},f.every=function(b){return b=Math.floor(b),!isFinite(b)||!(b>0)?null:b>1?f.filter(l?function(d){return l(d)%b===0}:function(d){return f.count(0,d)%b===0}):f}),f}var Jz=Uf(function(){},function(r,i){r.setTime(+r+i)},function(r,i){return i-r});Jz.every=function(r){return r=Math.floor(r),!isFinite(r)||!(r>0)?null:r>1?Uf(function(i){i.setTime(Math.floor(i/r)*r)},function(i,o){i.setTime(+i+o*r)},function(i,o){return(o-i)/r}):Jz};const iOt=Jz;Jz.range;const V3=1e3,D2=V3*60,U3=D2*60,j8=U3*24,Nse=j8*7,aTe=j8*30,Pse=j8*365;var oTe=Uf(function(r){r.setTime(r-r.getMilliseconds())},function(r,i){r.setTime(+r+i*V3)},function(r,i){return(i-r)/V3},function(r){return r.getUTCSeconds()});const YL=oTe;oTe.range;var cTe=Uf(function(r){r.setTime(r-r.getMilliseconds()-r.getSeconds()*V3)},function(r,i){r.setTime(+r+i*D2)},function(r,i){return(i-r)/D2},function(r){return r.getMinutes()});const eG=cTe;cTe.range;var uTe=Uf(function(r){r.setTime(r-r.getMilliseconds()-r.getSeconds()*V3-r.getMinutes()*D2)},function(r,i){r.setTime(+r+i*U3)},function(r,i){return(i-r)/U3},function(r){return r.getHours()});const tG=uTe;uTe.range;var lTe=Uf(r=>r.setHours(0,0,0,0),(r,i)=>r.setDate(r.getDate()+i),(r,i)=>(i-r-(i.getTimezoneOffset()-r.getTimezoneOffset())*D2)/j8,r=>r.getDate()-1);const RT=lTe;lTe.range;function $8(r){return Uf(function(i){i.setDate(i.getDate()-(i.getDay()+7-r)%7),i.setHours(0,0,0,0)},function(i,o){i.setDate(i.getDate()+o*7)},function(i,o){return(o-i-(o.getTimezoneOffset()-i.getTimezoneOffset())*D2)/Nse})}var jT=$8(0),nG=$8(1),sOt=$8(2),aOt=$8(3),$T=$8(4),oOt=$8(5),cOt=$8(6);jT.range,nG.range,sOt.range,aOt.range,$T.range,oOt.range,cOt.range;var hTe=Uf(function(r){r.setDate(1),r.setHours(0,0,0,0)},function(r,i){r.setMonth(r.getMonth()+i)},function(r,i){return i.getMonth()-r.getMonth()+(i.getFullYear()-r.getFullYear())*12},function(r){return r.getMonth()});const rG=hTe;hTe.range;var Bse=Uf(function(r){r.setMonth(0,1),r.setHours(0,0,0,0)},function(r,i){r.setFullYear(r.getFullYear()+i)},function(r,i){return i.getFullYear()-r.getFullYear()},function(r){return r.getFullYear()});Bse.every=function(r){return!isFinite(r=Math.floor(r))||!(r>0)?null:Uf(function(i){i.setFullYear(Math.floor(i.getFullYear()/r)*r),i.setMonth(0,1),i.setHours(0,0,0,0)},function(i,o){i.setFullYear(i.getFullYear()+o*r)})};const H8=Bse;Bse.range;var fTe=Uf(function(r){r.setUTCSeconds(0,0)},function(r,i){r.setTime(+r+i*D2)},function(r,i){return(i-r)/D2},function(r){return r.getUTCMinutes()});const uOt=fTe;fTe.range;var dTe=Uf(function(r){r.setUTCMinutes(0,0,0)},function(r,i){r.setTime(+r+i*U3)},function(r,i){return(i-r)/U3},function(r){return r.getUTCHours()});const lOt=dTe;dTe.range;var gTe=Uf(function(r){r.setUTCHours(0,0,0,0)},function(r,i){r.setUTCDate(r.getUTCDate()+i)},function(r,i){return(i-r)/j8},function(r){return r.getUTCDate()-1});const Fse=gTe;gTe.range;function z8(r){return Uf(function(i){i.setUTCDate(i.getUTCDate()-(i.getUTCDay()+7-r)%7),i.setUTCHours(0,0,0,0)},function(i,o){i.setUTCDate(i.getUTCDate()+o*7)},function(i,o){return(o-i)/Nse})}var Rse=z8(0),iG=z8(1),hOt=z8(2),fOt=z8(3),HT=z8(4),dOt=z8(5),gOt=z8(6);Rse.range,iG.range,hOt.range,fOt.range,HT.range,dOt.range,gOt.range;var pTe=Uf(function(r){r.setUTCDate(1),r.setUTCHours(0,0,0,0)},function(r,i){r.setUTCMonth(r.getUTCMonth()+i)},function(r,i){return i.getUTCMonth()-r.getUTCMonth()+(i.getUTCFullYear()-r.getUTCFullYear())*12},function(r){return r.getUTCMonth()});const pOt=pTe;pTe.range;var jse=Uf(function(r){r.setUTCMonth(0,1),r.setUTCHours(0,0,0,0)},function(r,i){r.setUTCFullYear(r.getUTCFullYear()+i)},function(r,i){return i.getUTCFullYear()-r.getUTCFullYear()},function(r){return r.getUTCFullYear()});jse.every=function(r){return!isFinite(r=Math.floor(r))||!(r>0)?null:Uf(function(i){i.setUTCFullYear(Math.floor(i.getUTCFullYear()/r)*r),i.setUTCMonth(0,1),i.setUTCHours(0,0,0,0)},function(i,o){i.setUTCFullYear(i.getUTCFullYear()+o*r)})};const zT=jse;jse.range;function bTe(r,i,o,l,f,b){const d=[[YL,1,V3],[YL,5,5*V3],[YL,15,15*V3],[YL,30,30*V3],[b,1,D2],[b,5,5*D2],[b,15,15*D2],[b,30,30*D2],[f,1,U3],[f,3,3*U3],[f,6,6*U3],[f,12,12*U3],[l,1,j8],[l,2,2*j8],[o,1,Nse],[i,1,aTe],[i,3,3*aTe],[r,1,Pse]];function w(k,E,T){const C=EB).right(d,C);if(S===d.length)return r.every(ese(k/Pse,E/Pse,T));if(S===0)return iOt.every(Math.max(ese(k,E,T),1));const[L,O]=d[C/d[S-1][2]53)return null;"w"in xe||(xe.w=1),"Z"in xe?(je=Hse(WL(xe.y,0,1)),me=je.getUTCDay(),je=me>4||me===0?iG.ceil(je):iG(je),je=Fse.offset(je,(xe.V-1)*7),xe.y=je.getUTCFullYear(),xe.m=je.getUTCMonth(),xe.d=je.getUTCDate()+(xe.w+6)%7):(je=$se(WL(xe.y,0,1)),me=je.getDay(),je=me>4||me===0?nG.ceil(je):nG(je),je=RT.offset(je,(xe.V-1)*7),xe.y=je.getFullYear(),xe.m=je.getMonth(),xe.d=je.getDate()+(xe.w+6)%7)}else("W"in xe||"U"in xe)&&("w"in xe||(xe.w="u"in xe?xe.u%7:"W"in xe?1:0),me="Z"in xe?Hse(WL(xe.y,0,1)).getUTCDay():$se(WL(xe.y,0,1)).getDay(),xe.m=0,xe.d="W"in xe?(xe.w+6)%7+xe.W*7-(me+5)%7:xe.w+xe.U*7-(me+6)%7);return"Z"in xe?(xe.H+=xe.Z/100|0,xe.M+=xe.Z%100,Hse(xe)):$se(xe)}}function Y(Oe,Le,$e,xe){for(var Ae=0,je=Le.length,me=$e.length,vt,ve;Ae=me)return-1;if(vt=Le.charCodeAt(Ae++),vt===37){if(vt=Le.charAt(Ae++),ve=X[vt in vTe?Le.charAt(Ae++):vt],!ve||(xe=ve(Oe,$e,xe))<0)return-1}else if(vt!=$e.charCodeAt(xe++))return-1}return xe}function z(Oe,Le,$e){var xe=k.exec(Le.slice($e));return xe?(Oe.p=E.get(xe[0].toLowerCase()),$e+xe[0].length):-1}function W(Oe,Le,$e){var xe=S.exec(Le.slice($e));return xe?(Oe.w=L.get(xe[0].toLowerCase()),$e+xe[0].length):-1}function Z(Oe,Le,$e){var xe=T.exec(Le.slice($e));return xe?(Oe.w=C.get(xe[0].toLowerCase()),$e+xe[0].length):-1}function G(Oe,Le,$e){var xe=N.exec(Le.slice($e));return xe?(Oe.m=F.get(xe[0].toLowerCase()),$e+xe[0].length):-1}function ae(Oe,Le,$e){var xe=O.exec(Le.slice($e));return xe?(Oe.m=B.get(xe[0].toLowerCase()),$e+xe[0].length):-1}function $(Oe,Le,$e){return Y(Oe,i,Le,$e)}function ge(Oe,Le,$e){return Y(Oe,o,Le,$e)}function ee(Oe,Le,$e){return Y(Oe,l,Le,$e)}function de(Oe){return d[Oe.getDay()]}function re(Oe){return b[Oe.getDay()]}function ke(Oe){return y[Oe.getMonth()]}function Ce(Oe){return w[Oe.getMonth()]}function _e(Oe){return f[+(Oe.getHours()>=12)]}function Te(Oe){return 1+~~(Oe.getMonth()/3)}function Be(Oe){return d[Oe.getUTCDay()]}function Ge(Oe){return b[Oe.getUTCDay()]}function Xe(Oe){return y[Oe.getUTCMonth()]}function Ee(Oe){return w[Oe.getUTCMonth()]}function Ze(Oe){return f[+(Oe.getUTCHours()>=12)]}function Ie(Oe){return 1+~~(Oe.getUTCMonth()/3)}return{format:function(Oe){var Le=te(Oe+="",R);return Le.toString=function(){return Oe},Le},parse:function(Oe){var Le=H(Oe+="",!1);return Le.toString=function(){return Oe},Le},utcFormat:function(Oe){var Le=te(Oe+="",q);return Le.toString=function(){return Oe},Le},utcParse:function(Oe){var Le=H(Oe+="",!0);return Le.toString=function(){return Oe},Le}}}var vTe={"-":"",_:" ",0:"0"},qf=/^\s*\d+/,mOt=/^%/,yOt=/[\\^$*+?|[\]().{}]/g;function Lo(r,i,o){var l=r<0?"-":"",f=(l?-r:r)+"",b=f.length;return l+(b[i.toLowerCase(),o]))}function xOt(r,i,o){var l=qf.exec(i.slice(o,o+1));return l?(r.w=+l[0],o+l[0].length):-1}function EOt(r,i,o){var l=qf.exec(i.slice(o,o+1));return l?(r.u=+l[0],o+l[0].length):-1}function _Ot(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.U=+l[0],o+l[0].length):-1}function TOt(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.V=+l[0],o+l[0].length):-1}function COt(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.W=+l[0],o+l[0].length):-1}function wTe(r,i,o){var l=qf.exec(i.slice(o,o+4));return l?(r.y=+l[0],o+l[0].length):-1}function mTe(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.y=+l[0]+(+l[0]>68?1900:2e3),o+l[0].length):-1}function SOt(r,i,o){var l=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(i.slice(o,o+6));return l?(r.Z=l[1]?0:-(l[2]+(l[3]||"00")),o+l[0].length):-1}function AOt(r,i,o){var l=qf.exec(i.slice(o,o+1));return l?(r.q=l[0]*3-3,o+l[0].length):-1}function MOt(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.m=l[0]-1,o+l[0].length):-1}function yTe(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.d=+l[0],o+l[0].length):-1}function DOt(r,i,o){var l=qf.exec(i.slice(o,o+3));return l?(r.m=0,r.d=+l[0],o+l[0].length):-1}function kTe(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.H=+l[0],o+l[0].length):-1}function LOt(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.M=+l[0],o+l[0].length):-1}function IOt(r,i,o){var l=qf.exec(i.slice(o,o+2));return l?(r.S=+l[0],o+l[0].length):-1}function OOt(r,i,o){var l=qf.exec(i.slice(o,o+3));return l?(r.L=+l[0],o+l[0].length):-1}function NOt(r,i,o){var l=qf.exec(i.slice(o,o+6));return l?(r.L=Math.floor(l[0]/1e3),o+l[0].length):-1}function POt(r,i,o){var l=mOt.exec(i.slice(o,o+1));return l?o+l[0].length:-1}function BOt(r,i,o){var l=qf.exec(i.slice(o));return l?(r.Q=+l[0],o+l[0].length):-1}function FOt(r,i,o){var l=qf.exec(i.slice(o));return l?(r.s=+l[0],o+l[0].length):-1}function xTe(r,i){return Lo(r.getDate(),i,2)}function ROt(r,i){return Lo(r.getHours(),i,2)}function jOt(r,i){return Lo(r.getHours()%12||12,i,2)}function $Ot(r,i){return Lo(1+RT.count(H8(r),r),i,3)}function ETe(r,i){return Lo(r.getMilliseconds(),i,3)}function HOt(r,i){return ETe(r,i)+"000"}function zOt(r,i){return Lo(r.getMonth()+1,i,2)}function GOt(r,i){return Lo(r.getMinutes(),i,2)}function VOt(r,i){return Lo(r.getSeconds(),i,2)}function UOt(r){var i=r.getDay();return i===0?7:i}function qOt(r,i){return Lo(jT.count(H8(r)-1,r),i,2)}function _Te(r){var i=r.getDay();return i>=4||i===0?$T(r):$T.ceil(r)}function YOt(r,i){return r=_Te(r),Lo($T.count(H8(r),r)+(H8(r).getDay()===4),i,2)}function WOt(r){return r.getDay()}function KOt(r,i){return Lo(nG.count(H8(r)-1,r),i,2)}function XOt(r,i){return Lo(r.getFullYear()%100,i,2)}function QOt(r,i){return r=_Te(r),Lo(r.getFullYear()%100,i,2)}function ZOt(r,i){return Lo(r.getFullYear()%1e4,i,4)}function JOt(r,i){var o=r.getDay();return r=o>=4||o===0?$T(r):$T.ceil(r),Lo(r.getFullYear()%1e4,i,4)}function eNt(r){var i=r.getTimezoneOffset();return(i>0?"-":(i*=-1,"+"))+Lo(i/60|0,"0",2)+Lo(i%60,"0",2)}function TTe(r,i){return Lo(r.getUTCDate(),i,2)}function tNt(r,i){return Lo(r.getUTCHours(),i,2)}function nNt(r,i){return Lo(r.getUTCHours()%12||12,i,2)}function rNt(r,i){return Lo(1+Fse.count(zT(r),r),i,3)}function CTe(r,i){return Lo(r.getUTCMilliseconds(),i,3)}function iNt(r,i){return CTe(r,i)+"000"}function sNt(r,i){return Lo(r.getUTCMonth()+1,i,2)}function aNt(r,i){return Lo(r.getUTCMinutes(),i,2)}function oNt(r,i){return Lo(r.getUTCSeconds(),i,2)}function cNt(r){var i=r.getUTCDay();return i===0?7:i}function uNt(r,i){return Lo(Rse.count(zT(r)-1,r),i,2)}function STe(r){var i=r.getUTCDay();return i>=4||i===0?HT(r):HT.ceil(r)}function lNt(r,i){return r=STe(r),Lo(HT.count(zT(r),r)+(zT(r).getUTCDay()===4),i,2)}function hNt(r){return r.getUTCDay()}function fNt(r,i){return Lo(iG.count(zT(r)-1,r),i,2)}function dNt(r,i){return Lo(r.getUTCFullYear()%100,i,2)}function gNt(r,i){return r=STe(r),Lo(r.getUTCFullYear()%100,i,2)}function pNt(r,i){return Lo(r.getUTCFullYear()%1e4,i,4)}function bNt(r,i){var o=r.getUTCDay();return r=o>=4||o===0?HT(r):HT.ceil(r),Lo(r.getUTCFullYear()%1e4,i,4)}function vNt(){return"+0000"}function ATe(){return"%"}function MTe(r){return+r}function DTe(r){return Math.floor(+r/1e3)}var GT,sG;wNt({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function wNt(r){return GT=wOt(r),sG=GT.format,GT.parse,GT.utcFormat,GT.utcParse,GT}function mNt(r){return new Date(r)}function yNt(r){return r instanceof Date?+r:+new Date(+r)}function LTe(r,i,o,l,f,b,d,w,y,k){var E=iTe(),T=E.invert,C=E.domain,S=k(".%L"),L=k(":%S"),O=k("%I:%M"),B=k("%I %p"),N=k("%a %d"),F=k("%b %d"),R=k("%B"),q=k("%Y");function X(te){return(y(te)1?0:r<-1?QL:Math.acos(r)}function OTe(r){return r>=1?aG:r<=-1?-aG:Math.asin(r)}function _Nt(r){return r.innerRadius}function TNt(r){return r.outerRadius}function CNt(r){return r.startAngle}function SNt(r){return r.endAngle}function ANt(r){return r&&r.padAngle}function MNt(r,i,o,l,f,b,d,w){var y=o-r,k=l-i,E=d-f,T=w-b,C=T*y-E*k;if(!(C*C$*$+ge*ge&&(Y=W,z=Z),{cx:Y,cy:z,x01:-E,y01:-T,x11:Y*(f/X-1),y11:z*(f/X-1)}}function ZL(){var r=_Nt,i=TNt,o=sh(0),l=null,f=CNt,b=SNt,d=ANt,w=null;function y(){var k,E,T=+r.apply(this,arguments),C=+i.apply(this,arguments),S=f.apply(this,arguments)-aG,L=b.apply(this,arguments)-aG,O=ITe(L-S),B=L>S;if(w||(w=k=Ase()),Cod))w.moveTo(0,0);else if(O>oG-od)w.moveTo(C*G8(S),C*Om(S)),w.arc(0,0,C,S,L,!B),T>od&&(w.moveTo(T*G8(L),T*Om(L)),w.arc(0,0,T,L,S,B));else{var N=S,F=L,R=S,q=L,X=O,te=O,H=d.apply(this,arguments)/2,Y=H>od&&(l?+l.apply(this,arguments):VT(T*T+C*C)),z=zse(ITe(C-T)/2,+o.apply(this,arguments)),W=z,Z=z,G,ae;if(Y>od){var $=OTe(Y/T*Om(H)),ge=OTe(Y/C*Om(H));(X-=$*2)>od?($*=B?1:-1,R+=$,q-=$):(X=0,R=q=(S+L)/2),(te-=ge*2)>od?(ge*=B?1:-1,N+=ge,F-=ge):(te=0,N=F=(S+L)/2)}var ee=C*G8(N),de=C*Om(N),re=T*G8(q),ke=T*Om(q);if(z>od){var Ce=C*G8(F),_e=C*Om(F),Te=T*G8(R),Be=T*Om(R),Ge;if(Ood?Z>od?(G=cG(Te,Be,ee,de,C,Z,B),ae=cG(Ce,_e,re,ke,C,Z,B),w.moveTo(G.cx+G.x01,G.cy+G.y01),Zod)||!(X>od)?w.lineTo(re,ke):W>od?(G=cG(re,ke,Ce,_e,T,-W,B),ae=cG(ee,de,Te,Be,T,-W,B),w.lineTo(G.cx+G.x01,G.cy+G.y01),Wr?1:i>=r?0:NaN}function ONt(r){return r}function NNt(){var r=ONt,i=INt,o=null,l=sh(0),f=sh(oG),b=sh(0);function d(w){var y,k=(w=NTe(w)).length,E,T,C=0,S=new Array(k),L=new Array(k),O=+l.apply(this,arguments),B=Math.min(oG,Math.max(-oG,f.apply(this,arguments)-O)),N,F=Math.min(Math.abs(B)/k,b.apply(this,arguments)),R=F*(B<0?-1:1),q;for(y=0;y0&&(C+=q);for(i!=null?S.sort(function(X,te){return i(L[X],L[te])}):o!=null&&S.sort(function(X,te){return o(w[X],w[te])}),y=0,T=C?(B-k*R)/C:0;y0?q*T:0)+R,L[E]={data:w[E],index:y,value:q,startAngle:O,endAngle:N,padAngle:F};return L}return d.value=function(w){return arguments.length?(r=typeof w=="function"?w:sh(+w),d):r},d.sortValues=function(w){return arguments.length?(i=w,o=null,d):i},d.sort=function(w){return arguments.length?(o=w,i=null,d):o},d.startAngle=function(w){return arguments.length?(l=typeof w=="function"?w:sh(+w),d):l},d.endAngle=function(w){return arguments.length?(f=typeof w=="function"?w:sh(+w),d):f},d.padAngle=function(w){return arguments.length?(b=typeof w=="function"?w:sh(+w),d):b},d}class BTe{constructor(i,o){this._context=i,this._x=o}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(i,o){switch(i=+i,o=+o,this._point){case 0:{this._point=1,this._line?this._context.lineTo(i,o):this._context.moveTo(i,o);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+i)/2,this._y0,this._x0,o,i,o):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+o)/2,i,this._y0,i,o);break}}this._x0=i,this._y0=o}}function PNt(r){return new BTe(r,!0)}function BNt(r){return new BTe(r,!1)}function s6(){}function uG(r,i,o){r._context.bezierCurveTo((2*r._x0+r._x1)/3,(2*r._y0+r._y1)/3,(r._x0+2*r._x1)/3,(r._y0+2*r._y1)/3,(r._x0+4*r._x1+i)/6,(r._y0+4*r._y1+o)/6)}function lG(r){this._context=r}lG.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:uG(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(r,i){switch(r=+r,i=+i,this._point){case 0:this._point=1,this._line?this._context.lineTo(r,i):this._context.moveTo(r,i);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:uG(this,r,i);break}this._x0=this._x1,this._x1=r,this._y0=this._y1,this._y1=i}};function UT(r){return new lG(r)}function FTe(r){this._context=r}FTe.prototype={areaStart:s6,areaEnd:s6,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(r,i){switch(r=+r,i=+i,this._point){case 0:this._point=1,this._x2=r,this._y2=i;break;case 1:this._point=2,this._x3=r,this._y3=i;break;case 2:this._point=3,this._x4=r,this._y4=i,this._context.moveTo((this._x0+4*this._x1+r)/6,(this._y0+4*this._y1+i)/6);break;default:uG(this,r,i);break}this._x0=this._x1,this._x1=r,this._y0=this._y1,this._y1=i}};function FNt(r){return new FTe(r)}function RTe(r){this._context=r}RTe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(r,i){switch(r=+r,i=+i,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var o=(this._x0+4*this._x1+r)/6,l=(this._y0+4*this._y1+i)/6;this._line?this._context.lineTo(o,l):this._context.moveTo(o,l);break;case 3:this._point=4;default:uG(this,r,i);break}this._x0=this._x1,this._x1=r,this._y0=this._y1,this._y1=i}};function RNt(r){return new RTe(r)}function jTe(r,i){this._basis=new lG(r),this._beta=i}jTe.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var r=this._x,i=this._y,o=r.length-1;if(o>0)for(var l=r[0],f=i[0],b=r[o]-l,d=i[o]-f,w=-1,y;++w<=o;)y=w/o,this._basis.point(this._beta*r[w]+(1-this._beta)*(l+y*b),this._beta*i[w]+(1-this._beta)*(f+y*d));this._x=this._y=null,this._basis.lineEnd()},point:function(r,i){this._x.push(+r),this._y.push(+i)}};const jNt=function r(i){function o(l){return i===1?new lG(l):new jTe(l,i)}return o.beta=function(l){return r(+l)},o}(.85);function hG(r,i,o){r._context.bezierCurveTo(r._x1+r._k*(r._x2-r._x0),r._y1+r._k*(r._y2-r._y0),r._x2+r._k*(r._x1-i),r._y2+r._k*(r._y1-o),r._x2,r._y2)}function Gse(r,i){this._context=r,this._k=(1-i)/6}Gse.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:hG(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(r,i){switch(r=+r,i=+i,this._point){case 0:this._point=1,this._line?this._context.lineTo(r,i):this._context.moveTo(r,i);break;case 1:this._point=2,this._x1=r,this._y1=i;break;case 2:this._point=3;default:hG(this,r,i);break}this._x0=this._x1,this._x1=this._x2,this._x2=r,this._y0=this._y1,this._y1=this._y2,this._y2=i}};const $Nt=function r(i){function o(l){return new Gse(l,i)}return o.tension=function(l){return r(+l)},o}(0);function Vse(r,i){this._context=r,this._k=(1-i)/6}Vse.prototype={areaStart:s6,areaEnd:s6,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(r,i){switch(r=+r,i=+i,this._point){case 0:this._point=1,this._x3=r,this._y3=i;break;case 1:this._point=2,this._context.moveTo(this._x4=r,this._y4=i);break;case 2:this._point=3,this._x5=r,this._y5=i;break;default:hG(this,r,i);break}this._x0=this._x1,this._x1=this._x2,this._x2=r,this._y0=this._y1,this._y1=this._y2,this._y2=i}};const HNt=function r(i){function o(l){return new Vse(l,i)}return o.tension=function(l){return r(+l)},o}(0);function Use(r,i){this._context=r,this._k=(1-i)/6}Use.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(r,i){switch(r=+r,i=+i,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:hG(this,r,i);break}this._x0=this._x1,this._x1=this._x2,this._x2=r,this._y0=this._y1,this._y1=this._y2,this._y2=i}};const zNt=function r(i){function o(l){return new Use(l,i)}return o.tension=function(l){return r(+l)},o}(0);function qse(r,i,o){var l=r._x1,f=r._y1,b=r._x2,d=r._y2;if(r._l01_a>od){var w=2*r._l01_2a+3*r._l01_a*r._l12_a+r._l12_2a,y=3*r._l01_a*(r._l01_a+r._l12_a);l=(l*w-r._x0*r._l12_2a+r._x2*r._l01_2a)/y,f=(f*w-r._y0*r._l12_2a+r._y2*r._l01_2a)/y}if(r._l23_a>od){var k=2*r._l23_2a+3*r._l23_a*r._l12_a+r._l12_2a,E=3*r._l23_a*(r._l23_a+r._l12_a);b=(b*k+r._x1*r._l23_2a-i*r._l12_2a)/E,d=(d*k+r._y1*r._l23_2a-o*r._l12_2a)/E}r._context.bezierCurveTo(l,f,b,d,r._x2,r._y2)}function $Te(r,i){this._context=r,this._alpha=i}$Te.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(r,i){if(r=+r,i=+i,this._point){var o=this._x2-r,l=this._y2-i;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(o*o+l*l,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(r,i):this._context.moveTo(r,i);break;case 1:this._point=2;break;case 2:this._point=3;default:qse(this,r,i);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=r,this._y0=this._y1,this._y1=this._y2,this._y2=i}};const GNt=function r(i){function o(l){return i?new $Te(l,i):new Gse(l,0)}return o.alpha=function(l){return r(+l)},o}(.5);function HTe(r,i){this._context=r,this._alpha=i}HTe.prototype={areaStart:s6,areaEnd:s6,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},point:function(r,i){if(r=+r,i=+i,this._point){var o=this._x2-r,l=this._y2-i;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(o*o+l*l,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=r,this._y3=i;break;case 1:this._point=2,this._context.moveTo(this._x4=r,this._y4=i);break;case 2:this._point=3,this._x5=r,this._y5=i;break;default:qse(this,r,i);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=r,this._y0=this._y1,this._y1=this._y2,this._y2=i}};const VNt=function r(i){function o(l){return i?new HTe(l,i):new Vse(l,0)}return o.alpha=function(l){return r(+l)},o}(.5);function zTe(r,i){this._context=r,this._alpha=i}zTe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(r,i){if(r=+r,i=+i,this._point){var o=this._x2-r,l=this._y2-i;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(o*o+l*l,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:qse(this,r,i);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=r,this._y0=this._y1,this._y1=this._y2,this._y2=i}};const UNt=function r(i){function o(l){return i?new zTe(l,i):new Use(l,0)}return o.alpha=function(l){return r(+l)},o}(.5);function GTe(r){this._context=r}GTe.prototype={areaStart:s6,areaEnd:s6,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(r,i){r=+r,i=+i,this._point?this._context.lineTo(r,i):(this._point=1,this._context.moveTo(r,i))}};function qNt(r){return new GTe(r)}function VTe(r){return r<0?-1:1}function UTe(r,i,o){var l=r._x1-r._x0,f=i-r._x1,b=(r._y1-r._y0)/(l||f<0&&-0),d=(o-r._y1)/(f||l<0&&-0),w=(b*f+d*l)/(l+f);return(VTe(b)+VTe(d))*Math.min(Math.abs(b),Math.abs(d),.5*Math.abs(w))||0}function qTe(r,i){var o=r._x1-r._x0;return o?(3*(r._y1-r._y0)/o-i)/2:i}function Yse(r,i,o){var l=r._x0,f=r._y0,b=r._x1,d=r._y1,w=(b-l)/3;r._context.bezierCurveTo(l+w,f+w*i,b-w,d-w*o,b,d)}function fG(r){this._context=r}fG.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Yse(this,this._t0,qTe(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(r,i){var o=NaN;if(r=+r,i=+i,!(r===this._x1&&i===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(r,i):this._context.moveTo(r,i);break;case 1:this._point=2;break;case 2:this._point=3,Yse(this,qTe(this,o=UTe(this,r,i)),o);break;default:Yse(this,this._t0,o=UTe(this,r,i));break}this._x0=this._x1,this._x1=r,this._y0=this._y1,this._y1=i,this._t0=o}}};function YTe(r){this._context=new WTe(r)}(YTe.prototype=Object.create(fG.prototype)).point=function(r,i){fG.prototype.point.call(this,i,r)};function WTe(r){this._context=r}WTe.prototype={moveTo:function(r,i){this._context.moveTo(i,r)},closePath:function(){this._context.closePath()},lineTo:function(r,i){this._context.lineTo(i,r)},bezierCurveTo:function(r,i,o,l,f,b){this._context.bezierCurveTo(i,r,l,o,b,f)}};function YNt(r){return new fG(r)}function WNt(r){return new YTe(r)}function KTe(r){this._context=r}KTe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var r=this._x,i=this._y,o=r.length;if(o)if(this._line?this._context.lineTo(r[0],i[0]):this._context.moveTo(r[0],i[0]),o===2)this._context.lineTo(r[1],i[1]);else for(var l=XTe(r),f=XTe(i),b=0,d=1;d=0;--i)f[i]=(d[i]-f[i+1])/b[i];for(b[o-1]=(r[o]+f[o-1])/2,i=0;i=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(r,i){switch(r=+r,i=+i,this._point){case 0:this._point=1,this._line?this._context.lineTo(r,i):this._context.moveTo(r,i);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,i),this._context.lineTo(r,i);else{var o=this._x*(1-this._t)+r*this._t;this._context.lineTo(o,this._y),this._context.lineTo(o,i)}break}}this._x=r,this._y=i}};function XNt(r){return new dG(r,.5)}function QNt(r){return new dG(r,0)}function ZNt(r){return new dG(r,1)}function qT(r,i,o){this.k=r,this.x=i,this.y=o}qT.prototype={constructor:qT,scale:function(r){return r===1?this:new qT(this.k*r,this.x,this.y)},translate:function(r,i){return r===0&i===0?this:new qT(this.k,this.x+this.k*r,this.y+this.k*i)},apply:function(r){return[r[0]*this.k+this.x,r[1]*this.k+this.y]},applyX:function(r){return r*this.k+this.x},applyY:function(r){return r*this.k+this.y},invert:function(r){return[(r[0]-this.x)/this.k,(r[1]-this.y)/this.k]},invertX:function(r){return(r-this.x)/this.k},invertY:function(r){return(r-this.y)/this.k},rescaleX:function(r){return r.copy().domain(r.range().map(this.invertX,this).map(r.invert,r))},rescaleY:function(r){return r.copy().domain(r.range().map(this.invertY,this).map(r.invert,r))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}},new qT(1,0,0),qT.prototype;/*! @license DOMPurify 2.4.3 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.4.3/LICENSE */function a6(r){return a6=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(i){return typeof i}:function(i){return i&&typeof Symbol=="function"&&i.constructor===Symbol&&i!==Symbol.prototype?"symbol":typeof i},a6(r)}function Wse(r,i){return Wse=Object.setPrototypeOf||function(l,f){return l.__proto__=f,l},Wse(r,i)}function JNt(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function gG(r,i,o){return JNt()?gG=Reflect.construct:gG=function(f,b,d){var w=[null];w.push.apply(w,b);var y=Function.bind.apply(f,w),k=new y;return d&&Wse(k,d.prototype),k},gG.apply(null,arguments)}function Cv(r){return ePt(r)||tPt(r)||nPt(r)||rPt()}function ePt(r){if(Array.isArray(r))return Kse(r)}function tPt(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function nPt(r,i){if(!!r){if(typeof r=="string")return Kse(r,i);var o=Object.prototype.toString.call(r).slice(8,-1);if(o==="Object"&&r.constructor&&(o=r.constructor.name),o==="Map"||o==="Set")return Array.from(r);if(o==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o))return Kse(r,i)}}function Kse(r,i){(i==null||i>r.length)&&(i=r.length);for(var o=0,l=new Array(i);o1?o-1:0),f=1;f/gm),wPt=Sv(/\${[\w\W]*}/gm),mPt=Sv(/^data-[\-\w.\u00B7-\uFFFF]/),yPt=Sv(/^aria-[\-\w]+$/),kPt=Sv(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),xPt=Sv(/^(?:\w+script|data):/i),EPt=Sv(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),_Pt=Sv(/^html$/i),TPt=function(){return typeof window>"u"?null:window},CPt=function(i,o){if(a6(i)!=="object"||typeof i.createPolicy!="function")return null;var l=null,f="data-tt-policy-suffix";o.currentScript&&o.currentScript.hasAttribute(f)&&(l=o.currentScript.getAttribute(f));var b="dompurify"+(l?"#"+l:"");try{return i.createPolicy(b,{createHTML:function(w){return w},createScriptURL:function(w){return w}})}catch{return console.warn("TrustedTypes policy "+b+" could not be created."),null}};function iCe(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:TPt(),i=function(bt){return iCe(bt)};if(i.version="2.4.3",i.removed=[],!r||!r.document||r.document.nodeType!==9)return i.isSupported=!1,i;var o=r.document,l=r.document,f=r.DocumentFragment,b=r.HTMLTemplateElement,d=r.Node,w=r.Element,y=r.NodeFilter,k=r.NamedNodeMap,E=k===void 0?r.NamedNodeMap||r.MozNamedAttrMap:k,T=r.HTMLFormElement,C=r.DOMParser,S=r.trustedTypes,L=w.prototype,O=vG(L,"cloneNode"),B=vG(L,"nextSibling"),N=vG(L,"childNodes"),F=vG(L,"parentNode");if(typeof b=="function"){var R=l.createElement("template");R.content&&R.content.ownerDocument&&(l=R.content.ownerDocument)}var q=CPt(S,o),X=q?q.createHTML(""):"",te=l,H=te.implementation,Y=te.createNodeIterator,z=te.createDocumentFragment,W=te.getElementsByTagName,Z=o.importNode,G={};try{G=U8(l).documentMode?l.documentMode:{}}catch{}var ae={};i.isSupported=typeof F=="function"&&H&&typeof H.createHTMLDocument<"u"&&G!==9;var $=bPt,ge=vPt,ee=wPt,de=mPt,re=yPt,ke=xPt,Ce=EPt,_e=kPt,Te=null,Be=xa({},[].concat(Cv(eCe),Cv(Jse),Cv(eae),Cv(tae),Cv(tCe))),Ge=null,Xe=xa({},[].concat(Cv(nCe),Cv(nae),Cv(rCe),Cv(wG))),Ee=Object.seal(Object.create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ze=null,Ie=null,Oe=!0,Le=!0,$e=!1,xe=!1,Ae=!1,je=!1,me=!1,vt=!1,ve=!1,Zt=!1,nt=!0,xn=!1,cn="user-content-",jt=!0,ot=!1,be={},We=null,ct=xa({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),Yt=null,Ut=xa({},["audio","video","img","source","image","track"]),Wn=null,Gt=xa({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Rn="http://www.w3.org/1998/Math/MathML",si="http://www.w3.org/2000/svg",$r="http://www.w3.org/1999/xhtml",nr=$r,Kn=!1,Jt=null,en=xa({},[Rn,si,$r],Qse),In,hn=["application/xhtml+xml","text/html"],Fr="text/html",Pt,ei=null,nn=l.createElement("form"),hi=function(bt){return bt instanceof RegExp||bt instanceof Function},Hi=function(bt){ei&&ei===bt||((!bt||a6(bt)!=="object")&&(bt={}),bt=U8(bt),In=hn.indexOf(bt.PARSER_MEDIA_TYPE)===-1?In=Fr:In=bt.PARSER_MEDIA_TYPE,Pt=In==="application/xhtml+xml"?Qse:bG,Te="ALLOWED_TAGS"in bt?xa({},bt.ALLOWED_TAGS,Pt):Be,Ge="ALLOWED_ATTR"in bt?xa({},bt.ALLOWED_ATTR,Pt):Xe,Jt="ALLOWED_NAMESPACES"in bt?xa({},bt.ALLOWED_NAMESPACES,Qse):en,Wn="ADD_URI_SAFE_ATTR"in bt?xa(U8(Gt),bt.ADD_URI_SAFE_ATTR,Pt):Gt,Yt="ADD_DATA_URI_TAGS"in bt?xa(U8(Ut),bt.ADD_DATA_URI_TAGS,Pt):Ut,We="FORBID_CONTENTS"in bt?xa({},bt.FORBID_CONTENTS,Pt):ct,Ze="FORBID_TAGS"in bt?xa({},bt.FORBID_TAGS,Pt):{},Ie="FORBID_ATTR"in bt?xa({},bt.FORBID_ATTR,Pt):{},be="USE_PROFILES"in bt?bt.USE_PROFILES:!1,Oe=bt.ALLOW_ARIA_ATTR!==!1,Le=bt.ALLOW_DATA_ATTR!==!1,$e=bt.ALLOW_UNKNOWN_PROTOCOLS||!1,xe=bt.SAFE_FOR_TEMPLATES||!1,Ae=bt.WHOLE_DOCUMENT||!1,vt=bt.RETURN_DOM||!1,ve=bt.RETURN_DOM_FRAGMENT||!1,Zt=bt.RETURN_TRUSTED_TYPE||!1,me=bt.FORCE_BODY||!1,nt=bt.SANITIZE_DOM!==!1,xn=bt.SANITIZE_NAMED_PROPS||!1,jt=bt.KEEP_CONTENT!==!1,ot=bt.IN_PLACE||!1,_e=bt.ALLOWED_URI_REGEXP||_e,nr=bt.NAMESPACE||$r,bt.CUSTOM_ELEMENT_HANDLING&&hi(bt.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(Ee.tagNameCheck=bt.CUSTOM_ELEMENT_HANDLING.tagNameCheck),bt.CUSTOM_ELEMENT_HANDLING&&hi(bt.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(Ee.attributeNameCheck=bt.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),bt.CUSTOM_ELEMENT_HANDLING&&typeof bt.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(Ee.allowCustomizedBuiltInElements=bt.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),xe&&(Le=!1),ve&&(vt=!0),be&&(Te=xa({},Cv(tCe)),Ge=[],be.html===!0&&(xa(Te,eCe),xa(Ge,nCe)),be.svg===!0&&(xa(Te,Jse),xa(Ge,nae),xa(Ge,wG)),be.svgFilters===!0&&(xa(Te,eae),xa(Ge,nae),xa(Ge,wG)),be.mathMl===!0&&(xa(Te,tae),xa(Ge,rCe),xa(Ge,wG))),bt.ADD_TAGS&&(Te===Be&&(Te=U8(Te)),xa(Te,bt.ADD_TAGS,Pt)),bt.ADD_ATTR&&(Ge===Xe&&(Ge=U8(Ge)),xa(Ge,bt.ADD_ATTR,Pt)),bt.ADD_URI_SAFE_ATTR&&xa(Wn,bt.ADD_URI_SAFE_ATTR,Pt),bt.FORBID_CONTENTS&&(We===ct&&(We=U8(We)),xa(We,bt.FORBID_CONTENTS,Pt)),jt&&(Te["#text"]=!0),Ae&&xa(Te,["html","head","body"]),Te.table&&(xa(Te,["tbody"]),delete Ze.tbody),Wd&&Wd(bt),ei=bt)},ss=xa({},["mi","mo","mn","ms","mtext"]),ls=xa({},["foreignobject","desc","title","annotation-xml"]),vs=xa({},["title","style","font","a","script"]),ti=xa({},Jse);xa(ti,eae),xa(ti,gPt);var zi=xa({},tae);xa(zi,pPt);var as=function(bt){var $n=F(bt);(!$n||!$n.tagName)&&($n={namespaceURI:nr,tagName:"template"});var Er=bG(bt.tagName),Ss=bG($n.tagName);return Jt[bt.namespaceURI]?bt.namespaceURI===si?$n.namespaceURI===$r?Er==="svg":$n.namespaceURI===Rn?Er==="svg"&&(Ss==="annotation-xml"||ss[Ss]):Boolean(ti[Er]):bt.namespaceURI===Rn?$n.namespaceURI===$r?Er==="math":$n.namespaceURI===si?Er==="math"&&ls[Ss]:Boolean(zi[Er]):bt.namespaceURI===$r?$n.namespaceURI===si&&!ls[Ss]||$n.namespaceURI===Rn&&!ss[Ss]?!1:!zi[Er]&&(vs[Er]||!ti[Er]):!!(In==="application/xhtml+xml"&&Jt[bt.namespaceURI]):!1},ai=function(bt){JL(i.removed,{element:bt});try{bt.parentNode.removeChild(bt)}catch{try{bt.outerHTML=X}catch{bt.remove()}}},hc=function(bt,$n){try{JL(i.removed,{attribute:$n.getAttributeNode(bt),from:$n})}catch{JL(i.removed,{attribute:null,from:$n})}if($n.removeAttribute(bt),bt==="is"&&!Ge[bt])if(vt||ve)try{ai($n)}catch{}else try{$n.setAttribute(bt,"")}catch{}},xu=function(bt){var $n,Er;if(me)bt=""+bt;else{var Ss=lPt(bt,/^[\r\n\t ]+/);Er=Ss&&Ss[0]}In==="application/xhtml+xml"&&nr===$r&&(bt=''+bt+"");var wo=q?q.createHTML(bt):bt;if(nr===$r)try{$n=new C().parseFromString(wo,In)}catch{}if(!$n||!$n.documentElement){$n=H.createDocument(nr,"template",null);try{$n.documentElement.innerHTML=Kn?X:wo}catch{}}var Po=$n.body||$n.documentElement;return bt&&Er&&Po.insertBefore(l.createTextNode(Er),Po.childNodes[0]||null),nr===$r?W.call($n,Ae?"html":"body")[0]:Ae?$n.documentElement:Po},No=function(bt){return Y.call(bt.ownerDocument||bt,bt,y.SHOW_ELEMENT|y.SHOW_COMMENT|y.SHOW_TEXT,null,!1)},Si=function(bt){return bt instanceof T&&(typeof bt.nodeName!="string"||typeof bt.textContent!="string"||typeof bt.removeChild!="function"||!(bt.attributes instanceof E)||typeof bt.removeAttribute!="function"||typeof bt.setAttribute!="function"||typeof bt.namespaceURI!="string"||typeof bt.insertBefore!="function"||typeof bt.hasChildNodes!="function")},Yc=function(bt){return a6(d)==="object"?bt instanceof d:bt&&a6(bt)==="object"&&typeof bt.nodeType=="number"&&typeof bt.nodeName=="string"},lh=function(bt,$n,Er){!ae[bt]||uPt(ae[bt],function(Ss){Ss.call(i,$n,Er,ei)})},su=function(bt){var $n;if(lh("beforeSanitizeElements",bt,null),Si(bt)||Kd(/[\u0080-\uFFFF]/,bt.nodeName))return ai(bt),!0;var Er=Pt(bt.nodeName);if(lh("uponSanitizeElement",bt,{tagName:Er,allowedTags:Te}),bt.hasChildNodes()&&!Yc(bt.firstElementChild)&&(!Yc(bt.content)||!Yc(bt.content.firstElementChild))&&Kd(/<[/\w]/g,bt.innerHTML)&&Kd(/<[/\w]/g,bt.textContent)||Er==="select"&&Kd(/