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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
return "Hello " + name + "!!"
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import io
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
import sys
|
| 6 |
+
import time
|
| 7 |
+
import zipfile
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
import gradio as gr
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
import modules.extensions as extensions_module
|
| 15 |
+
from modules import api, chat, shared, training, ui
|
| 16 |
+
from modules.html_generator import chat_html_wrapper
|
| 17 |
+
from modules.LoRA import add_lora_to_model
|
| 18 |
+
from modules.models import load_model, load_soft_prompt
|
| 19 |
+
from modules.text_generation import (clear_torch_cache, generate_reply,
|
| 20 |
+
stop_everything_event)
|
| 21 |
+
|
| 22 |
+
# Loading custom settings
|
| 23 |
+
settings_file = None
|
| 24 |
+
if shared.args.settings is not None and Path(shared.args.settings).exists():
|
| 25 |
+
settings_file = Path(shared.args.settings)
|
| 26 |
+
elif Path('settings.json').exists():
|
| 27 |
+
settings_file = Path('settings.json')
|
| 28 |
+
if settings_file is not None:
|
| 29 |
+
print(f"Loading settings from {settings_file}...")
|
| 30 |
+
new_settings = json.loads(open(settings_file, 'r').read())
|
| 31 |
+
for item in new_settings:
|
| 32 |
+
shared.settings[item] = new_settings[item]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_available_models():
|
| 36 |
+
if shared.args.flexgen:
|
| 37 |
+
return sorted([re.sub('-np$', '', item.name) for item in list(Path(f'{shared.args.model_dir}/').glob('*')) if item.name.endswith('-np')], key=str.lower)
|
| 38 |
+
else:
|
| 39 |
+
return sorted([re.sub('.pth$', '', item.name) for item in list(Path(f'{shared.args.model_dir}/').glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=str.lower)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_available_presets():
|
| 43 |
+
return sorted(set((k.stem for k in Path('presets').glob('*.txt'))), key=str.lower)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_available_prompts():
|
| 47 |
+
prompts = []
|
| 48 |
+
prompts += sorted(set((k.stem for k in Path('prompts').glob('[0-9]*.txt'))), key=str.lower, reverse=True)
|
| 49 |
+
prompts += sorted(set((k.stem for k in Path('prompts').glob('*.txt'))), key=str.lower)
|
| 50 |
+
prompts += ['None']
|
| 51 |
+
return prompts
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_available_characters():
|
| 55 |
+
paths = (x for x in Path('characters').iterdir() if x.suffix in ('.json', '.yaml', '.yml'))
|
| 56 |
+
return ['None'] + sorted(set((k.stem for k in paths if k.stem != "instruction-following")), key=str.lower)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_available_instruction_templates():
|
| 60 |
+
path = "characters/instruction-following"
|
| 61 |
+
paths = []
|
| 62 |
+
if os.path.exists(path):
|
| 63 |
+
paths = (x for x in Path(path).iterdir() if x.suffix in ('.json', '.yaml', '.yml'))
|
| 64 |
+
return ['None'] + sorted(set((k.stem for k in paths)), key=str.lower)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_available_extensions():
|
| 68 |
+
return sorted(set(map(lambda x: x.parts[1], Path('extensions').glob('*/script.py'))), key=str.lower)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def get_available_softprompts():
|
| 72 |
+
return ['None'] + sorted(set((k.stem for k in Path('softprompts').glob('*.zip'))), key=str.lower)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def get_available_loras():
|
| 76 |
+
return ['None'] + sorted([item.name for item in list(Path(shared.args.lora_dir).glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=str.lower)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def unload_model():
|
| 80 |
+
shared.model = shared.tokenizer = None
|
| 81 |
+
clear_torch_cache()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def load_model_wrapper(selected_model):
|
| 85 |
+
if selected_model != shared.model_name:
|
| 86 |
+
shared.model_name = selected_model
|
| 87 |
+
|
| 88 |
+
unload_model()
|
| 89 |
+
if selected_model != '':
|
| 90 |
+
shared.model, shared.tokenizer = load_model(shared.model_name)
|
| 91 |
+
|
| 92 |
+
return selected_model
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def load_lora_wrapper(selected_lora):
|
| 96 |
+
add_lora_to_model(selected_lora)
|
| 97 |
+
return selected_lora
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def load_preset_values(preset_menu, state, return_dict=False):
|
| 101 |
+
generate_params = {
|
| 102 |
+
'do_sample': True,
|
| 103 |
+
'temperature': 1,
|
| 104 |
+
'top_p': 1,
|
| 105 |
+
'typical_p': 1,
|
| 106 |
+
'repetition_penalty': 1,
|
| 107 |
+
'encoder_repetition_penalty': 1,
|
| 108 |
+
'top_k': 50,
|
| 109 |
+
'num_beams': 1,
|
| 110 |
+
'penalty_alpha': 0,
|
| 111 |
+
'min_length': 0,
|
| 112 |
+
'length_penalty': 1,
|
| 113 |
+
'no_repeat_ngram_size': 0,
|
| 114 |
+
'early_stopping': False,
|
| 115 |
+
}
|
| 116 |
+
with open(Path(f'presets/{preset_menu}.txt'), 'r') as infile:
|
| 117 |
+
preset = infile.read()
|
| 118 |
+
for i in preset.splitlines():
|
| 119 |
+
i = i.rstrip(',').strip().split('=')
|
| 120 |
+
if len(i) == 2 and i[0].strip() != 'tokens':
|
| 121 |
+
generate_params[i[0].strip()] = eval(i[1].strip())
|
| 122 |
+
generate_params['temperature'] = min(1.99, generate_params['temperature'])
|
| 123 |
+
|
| 124 |
+
if return_dict:
|
| 125 |
+
return generate_params
|
| 126 |
+
else:
|
| 127 |
+
state.update(generate_params)
|
| 128 |
+
return state, *[generate_params[k] for k in ['do_sample', 'temperature', 'top_p', 'typical_p', 'repetition_penalty', 'encoder_repetition_penalty', 'top_k', 'min_length', 'no_repeat_ngram_size', 'num_beams', 'penalty_alpha', 'length_penalty', 'early_stopping']]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def upload_soft_prompt(file):
|
| 132 |
+
with zipfile.ZipFile(io.BytesIO(file)) as zf:
|
| 133 |
+
zf.extract('meta.json')
|
| 134 |
+
j = json.loads(open('meta.json', 'r').read())
|
| 135 |
+
name = j['name']
|
| 136 |
+
Path('meta.json').unlink()
|
| 137 |
+
|
| 138 |
+
with open(Path(f'softprompts/{name}.zip'), 'wb') as f:
|
| 139 |
+
f.write(file)
|
| 140 |
+
|
| 141 |
+
return name
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def save_prompt(text):
|
| 145 |
+
fname = f"{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.txt"
|
| 146 |
+
with open(Path(f'prompts/{fname}'), 'w', encoding='utf-8') as f:
|
| 147 |
+
f.write(text)
|
| 148 |
+
return f"Saved to prompts/{fname}"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def load_prompt(fname):
|
| 152 |
+
if fname in ['None', '']:
|
| 153 |
+
return ''
|
| 154 |
+
else:
|
| 155 |
+
with open(Path(f'prompts/{fname}.txt'), 'r', encoding='utf-8') as f:
|
| 156 |
+
text = f.read()
|
| 157 |
+
if text[-1] == '\n':
|
| 158 |
+
text = text[:-1]
|
| 159 |
+
return text
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def create_prompt_menus():
|
| 163 |
+
with gr.Row():
|
| 164 |
+
with gr.Column():
|
| 165 |
+
with gr.Row():
|
| 166 |
+
shared.gradio['prompt_menu'] = gr.Dropdown(choices=get_available_prompts(), value='None', label='Prompt')
|
| 167 |
+
ui.create_refresh_button(shared.gradio['prompt_menu'], lambda: None, lambda: {'choices': get_available_prompts()}, 'refresh-button')
|
| 168 |
+
|
| 169 |
+
with gr.Column():
|
| 170 |
+
with gr.Column():
|
| 171 |
+
shared.gradio['save_prompt'] = gr.Button('Save prompt')
|
| 172 |
+
shared.gradio['status'] = gr.Markdown('Ready')
|
| 173 |
+
|
| 174 |
+
shared.gradio['prompt_menu'].change(load_prompt, [shared.gradio['prompt_menu']], [shared.gradio['textbox']], show_progress=False)
|
| 175 |
+
shared.gradio['save_prompt'].click(save_prompt, [shared.gradio['textbox']], [shared.gradio['status']], show_progress=False)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def create_model_menus():
|
| 179 |
+
with gr.Row():
|
| 180 |
+
with gr.Column():
|
| 181 |
+
with gr.Row():
|
| 182 |
+
shared.gradio['model_menu'] = gr.Dropdown(choices=available_models, value=shared.model_name, label='Model')
|
| 183 |
+
ui.create_refresh_button(shared.gradio['model_menu'], lambda: None, lambda: {'choices': get_available_models()}, 'refresh-button')
|
| 184 |
+
with gr.Column():
|
| 185 |
+
with gr.Row():
|
| 186 |
+
shared.gradio['lora_menu'] = gr.Dropdown(choices=available_loras, value=shared.lora_name, label='LoRA')
|
| 187 |
+
ui.create_refresh_button(shared.gradio['lora_menu'], lambda: None, lambda: {'choices': get_available_loras()}, 'refresh-button')
|
| 188 |
+
|
| 189 |
+
shared.gradio['model_menu'].change(load_model_wrapper, shared.gradio['model_menu'], shared.gradio['model_menu'], show_progress=True)
|
| 190 |
+
shared.gradio['lora_menu'].change(load_lora_wrapper, shared.gradio['lora_menu'], shared.gradio['lora_menu'], show_progress=True)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def create_settings_menus(default_preset):
|
| 194 |
+
generate_params = load_preset_values(default_preset if not shared.args.flexgen else 'Naive', {}, return_dict=True)
|
| 195 |
+
for k in ['max_new_tokens', 'seed', 'stop_at_newline', 'chat_prompt_size', 'chat_generation_attempts']:
|
| 196 |
+
generate_params[k] = shared.settings[k]
|
| 197 |
+
shared.gradio['generate_state'] = gr.State(generate_params)
|
| 198 |
+
|
| 199 |
+
with gr.Row():
|
| 200 |
+
with gr.Column():
|
| 201 |
+
with gr.Row():
|
| 202 |
+
shared.gradio['preset_menu'] = gr.Dropdown(choices=available_presets, value=default_preset if not shared.args.flexgen else 'Naive', label='Generation parameters preset')
|
| 203 |
+
ui.create_refresh_button(shared.gradio['preset_menu'], lambda: None, lambda: {'choices': get_available_presets()}, 'refresh-button')
|
| 204 |
+
with gr.Column():
|
| 205 |
+
shared.gradio['seed'] = gr.Number(value=shared.settings['seed'], label='Seed (-1 for random)')
|
| 206 |
+
|
| 207 |
+
with gr.Row():
|
| 208 |
+
with gr.Column():
|
| 209 |
+
with gr.Box():
|
| 210 |
+
gr.Markdown('Custom generation parameters ([reference](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig))')
|
| 211 |
+
with gr.Row():
|
| 212 |
+
with gr.Column():
|
| 213 |
+
shared.gradio['temperature'] = gr.Slider(0.01, 1.99, value=generate_params['temperature'], step=0.01, label='temperature')
|
| 214 |
+
shared.gradio['top_p'] = gr.Slider(0.0, 1.0, value=generate_params['top_p'], step=0.01, label='top_p')
|
| 215 |
+
shared.gradio['top_k'] = gr.Slider(0, 200, value=generate_params['top_k'], step=1, label='top_k')
|
| 216 |
+
shared.gradio['typical_p'] = gr.Slider(0.0, 1.0, value=generate_params['typical_p'], step=0.01, label='typical_p')
|
| 217 |
+
with gr.Column():
|
| 218 |
+
shared.gradio['repetition_penalty'] = gr.Slider(1.0, 1.5, value=generate_params['repetition_penalty'], step=0.01, label='repetition_penalty')
|
| 219 |
+
shared.gradio['encoder_repetition_penalty'] = gr.Slider(0.8, 1.5, value=generate_params['encoder_repetition_penalty'], step=0.01, label='encoder_repetition_penalty')
|
| 220 |
+
shared.gradio['no_repeat_ngram_size'] = gr.Slider(0, 20, step=1, value=generate_params['no_repeat_ngram_size'], label='no_repeat_ngram_size')
|
| 221 |
+
shared.gradio['min_length'] = gr.Slider(0, 2000, step=1, value=generate_params['min_length'] if shared.args.no_stream else 0, label='min_length', interactive=shared.args.no_stream)
|
| 222 |
+
shared.gradio['do_sample'] = gr.Checkbox(value=generate_params['do_sample'], label='do_sample')
|
| 223 |
+
with gr.Column():
|
| 224 |
+
with gr.Box():
|
| 225 |
+
gr.Markdown('Contrastive search')
|
| 226 |
+
shared.gradio['penalty_alpha'] = gr.Slider(0, 5, value=generate_params['penalty_alpha'], label='penalty_alpha')
|
| 227 |
+
with gr.Box():
|
| 228 |
+
gr.Markdown('Beam search (uses a lot of VRAM)')
|
| 229 |
+
with gr.Row():
|
| 230 |
+
with gr.Column():
|
| 231 |
+
shared.gradio['num_beams'] = gr.Slider(1, 20, step=1, value=generate_params['num_beams'], label='num_beams')
|
| 232 |
+
with gr.Column():
|
| 233 |
+
shared.gradio['length_penalty'] = gr.Slider(-5, 5, value=generate_params['length_penalty'], label='length_penalty')
|
| 234 |
+
shared.gradio['early_stopping'] = gr.Checkbox(value=generate_params['early_stopping'], label='early_stopping')
|
| 235 |
+
|
| 236 |
+
with gr.Accordion('Soft prompt', open=False):
|
| 237 |
+
with gr.Row():
|
| 238 |
+
shared.gradio['softprompts_menu'] = gr.Dropdown(choices=available_softprompts, value='None', label='Soft prompt')
|
| 239 |
+
ui.create_refresh_button(shared.gradio['softprompts_menu'], lambda: None, lambda: {'choices': get_available_softprompts()}, 'refresh-button')
|
| 240 |
+
|
| 241 |
+
gr.Markdown('Upload a soft prompt (.zip format):')
|
| 242 |
+
with gr.Row():
|
| 243 |
+
shared.gradio['upload_softprompt'] = gr.File(type='binary', file_types=['.zip'])
|
| 244 |
+
|
| 245 |
+
shared.gradio['preset_menu'].change(load_preset_values, [shared.gradio[k] for k in ['preset_menu', 'generate_state']], [shared.gradio[k] for k in ['generate_state', 'do_sample', 'temperature', 'top_p', 'typical_p', 'repetition_penalty', 'encoder_repetition_penalty', 'top_k', 'min_length', 'no_repeat_ngram_size', 'num_beams', 'penalty_alpha', 'length_penalty', 'early_stopping']])
|
| 246 |
+
shared.gradio['softprompts_menu'].change(load_soft_prompt, shared.gradio['softprompts_menu'], shared.gradio['softprompts_menu'], show_progress=True)
|
| 247 |
+
shared.gradio['upload_softprompt'].upload(upload_soft_prompt, shared.gradio['upload_softprompt'], shared.gradio['softprompts_menu'])
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def set_interface_arguments(interface_mode, extensions, bool_active):
|
| 251 |
+
modes = ["default", "notebook", "chat", "cai_chat"]
|
| 252 |
+
cmd_list = vars(shared.args)
|
| 253 |
+
bool_list = [k for k in cmd_list if type(cmd_list[k]) is bool and k not in modes]
|
| 254 |
+
|
| 255 |
+
shared.args.extensions = extensions
|
| 256 |
+
for k in modes[1:]:
|
| 257 |
+
exec(f"shared.args.{k} = False")
|
| 258 |
+
if interface_mode != "default":
|
| 259 |
+
exec(f"shared.args.{interface_mode} = True")
|
| 260 |
+
|
| 261 |
+
for k in bool_list:
|
| 262 |
+
exec(f"shared.args.{k} = False")
|
| 263 |
+
for k in bool_active:
|
| 264 |
+
exec(f"shared.args.{k} = True")
|
| 265 |
+
|
| 266 |
+
shared.need_restart = True
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
available_models = get_available_models()
|
| 270 |
+
available_presets = get_available_presets()
|
| 271 |
+
available_characters = get_available_characters()
|
| 272 |
+
available_softprompts = get_available_softprompts()
|
| 273 |
+
available_loras = get_available_loras()
|
| 274 |
+
|
| 275 |
+
# Default extensions
|
| 276 |
+
extensions_module.available_extensions = get_available_extensions()
|
| 277 |
+
if shared.is_chat():
|
| 278 |
+
for extension in shared.settings['chat_default_extensions']:
|
| 279 |
+
shared.args.extensions = shared.args.extensions or []
|
| 280 |
+
if extension not in shared.args.extensions:
|
| 281 |
+
shared.args.extensions.append(extension)
|
| 282 |
+
else:
|
| 283 |
+
for extension in shared.settings['default_extensions']:
|
| 284 |
+
shared.args.extensions = shared.args.extensions or []
|
| 285 |
+
if extension not in shared.args.extensions:
|
| 286 |
+
shared.args.extensions.append(extension)
|
| 287 |
+
|
| 288 |
+
# Default model
|
| 289 |
+
if shared.args.model is not None:
|
| 290 |
+
shared.model_name = shared.args.model
|
| 291 |
+
else:
|
| 292 |
+
if len(available_models) == 0:
|
| 293 |
+
print('No models are available! Please download at least one.')
|
| 294 |
+
sys.exit(0)
|
| 295 |
+
elif len(available_models) == 1:
|
| 296 |
+
i = 0
|
| 297 |
+
else:
|
| 298 |
+
print('The following models are available:\n')
|
| 299 |
+
for i, model in enumerate(available_models):
|
| 300 |
+
print(f'{i+1}. {model}')
|
| 301 |
+
print(f'\nWhich one do you want to load? 1-{len(available_models)}\n')
|
| 302 |
+
i = int(input()) - 1
|
| 303 |
+
print()
|
| 304 |
+
shared.model_name = available_models[i]
|
| 305 |
+
shared.model, shared.tokenizer = load_model(shared.model_name)
|
| 306 |
+
if shared.args.lora:
|
| 307 |
+
add_lora_to_model(shared.args.lora)
|
| 308 |
+
|
| 309 |
+
# Default UI settings
|
| 310 |
+
default_preset = shared.settings['presets'][next((k for k in shared.settings['presets'] if re.match(k.lower(), shared.model_name.lower())), 'default')]
|
| 311 |
+
if shared.lora_name != "None":
|
| 312 |
+
default_text = load_prompt(shared.settings['lora_prompts'][next((k for k in shared.settings['lora_prompts'] if re.match(k.lower(), shared.lora_name.lower())), 'default')])
|
| 313 |
+
else:
|
| 314 |
+
default_text = load_prompt(shared.settings['prompts'][next((k for k in shared.settings['prompts'] if re.match(k.lower(), shared.model_name.lower())), 'default')])
|
| 315 |
+
title = 'Text generation web UI'
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def create_interface():
|
| 319 |
+
gen_events = []
|
| 320 |
+
if shared.args.extensions is not None and len(shared.args.extensions) > 0:
|
| 321 |
+
extensions_module.load_extensions()
|
| 322 |
+
|
| 323 |
+
with gr.Blocks(css=ui.css if not shared.is_chat() else ui.css + ui.chat_css, analytics_enabled=False, title=title) as shared.gradio['interface']:
|
| 324 |
+
if shared.is_chat():
|
| 325 |
+
shared.gradio['Chat input'] = gr.State()
|
| 326 |
+
with gr.Tab("Text generation", elem_id="main"):
|
| 327 |
+
shared.gradio['display'] = gr.HTML(value=chat_html_wrapper(shared.history['visible'], shared.settings['name1'], shared.settings['name2'], 'cai-chat'))
|
| 328 |
+
shared.gradio['textbox'] = gr.Textbox(label='Input')
|
| 329 |
+
with gr.Row():
|
| 330 |
+
shared.gradio['Generate'] = gr.Button('Generate')
|
| 331 |
+
shared.gradio['Stop'] = gr.Button('Stop', elem_id="stop")
|
| 332 |
+
with gr.Row():
|
| 333 |
+
shared.gradio['Impersonate'] = gr.Button('Impersonate')
|
| 334 |
+
shared.gradio['Regenerate'] = gr.Button('Regenerate')
|
| 335 |
+
with gr.Row():
|
| 336 |
+
shared.gradio['Copy last reply'] = gr.Button('Copy last reply')
|
| 337 |
+
shared.gradio['Replace last reply'] = gr.Button('Replace last reply')
|
| 338 |
+
shared.gradio['Remove last'] = gr.Button('Remove last')
|
| 339 |
+
|
| 340 |
+
shared.gradio['Clear history'] = gr.Button('Clear history')
|
| 341 |
+
shared.gradio['Clear history-confirm'] = gr.Button('Confirm', variant="stop", visible=False)
|
| 342 |
+
shared.gradio['Clear history-cancel'] = gr.Button('Cancel', visible=False)
|
| 343 |
+
|
| 344 |
+
shared.gradio["Chat mode"] = gr.Radio(choices=["cai-chat", "chat", "instruct"], value="cai-chat", label="Mode")
|
| 345 |
+
shared.gradio["Instruction templates"] = gr.Dropdown(choices=get_available_instruction_templates(), label="Instruction template", value="None", visible=False)
|
| 346 |
+
|
| 347 |
+
with gr.Tab("Character", elem_id="chat-settings"):
|
| 348 |
+
with gr.Row():
|
| 349 |
+
with gr.Column(scale=8):
|
| 350 |
+
shared.gradio['name1'] = gr.Textbox(value=shared.settings['name1'], lines=1, label='Your name')
|
| 351 |
+
shared.gradio['name2'] = gr.Textbox(value=shared.settings['name2'], lines=1, label='Character\'s name')
|
| 352 |
+
shared.gradio['greeting'] = gr.Textbox(value=shared.settings['greeting'], lines=4, label='Greeting')
|
| 353 |
+
shared.gradio['context'] = gr.Textbox(value=shared.settings['context'], lines=4, label='Context')
|
| 354 |
+
shared.gradio['end_of_turn'] = gr.Textbox(value=shared.settings["end_of_turn"], lines=1, label='End of turn string')
|
| 355 |
+
with gr.Column(scale=1):
|
| 356 |
+
shared.gradio['character_picture'] = gr.Image(label='Character picture', type="pil")
|
| 357 |
+
shared.gradio['your_picture'] = gr.Image(label='Your picture', type="pil", value=Image.open(Path("cache/pfp_me.png")) if Path("cache/pfp_me.png").exists() else None)
|
| 358 |
+
with gr.Row():
|
| 359 |
+
shared.gradio['character_menu'] = gr.Dropdown(choices=available_characters, value='None', label='Character', elem_id='character-menu')
|
| 360 |
+
ui.create_refresh_button(shared.gradio['character_menu'], lambda: None, lambda: {'choices': get_available_characters()}, 'refresh-button')
|
| 361 |
+
|
| 362 |
+
with gr.Row():
|
| 363 |
+
with gr.Tab('Chat history'):
|
| 364 |
+
with gr.Row():
|
| 365 |
+
with gr.Column():
|
| 366 |
+
gr.Markdown('Upload')
|
| 367 |
+
shared.gradio['upload_chat_history'] = gr.File(type='binary', file_types=['.json', '.txt'])
|
| 368 |
+
with gr.Column():
|
| 369 |
+
gr.Markdown('Download')
|
| 370 |
+
shared.gradio['download'] = gr.File()
|
| 371 |
+
shared.gradio['download_button'] = gr.Button(value='Click me')
|
| 372 |
+
with gr.Tab('Upload character'):
|
| 373 |
+
gr.Markdown("# JSON format")
|
| 374 |
+
with gr.Row():
|
| 375 |
+
with gr.Column():
|
| 376 |
+
gr.Markdown('1. Select the JSON file')
|
| 377 |
+
shared.gradio['upload_json'] = gr.File(type='binary', file_types=['.json'])
|
| 378 |
+
with gr.Column():
|
| 379 |
+
gr.Markdown('2. Select your character\'s profile picture (optional)')
|
| 380 |
+
shared.gradio['upload_img_bot'] = gr.File(type='binary', file_types=['image'])
|
| 381 |
+
shared.gradio['Upload character'] = gr.Button(value='Submit')
|
| 382 |
+
|
| 383 |
+
gr.Markdown("# TavernAI PNG format")
|
| 384 |
+
shared.gradio['upload_img_tavern'] = gr.File(type='binary', file_types=['image'])
|
| 385 |
+
|
| 386 |
+
with gr.Tab("Parameters", elem_id="parameters"):
|
| 387 |
+
with gr.Box():
|
| 388 |
+
gr.Markdown("Chat parameters")
|
| 389 |
+
with gr.Row():
|
| 390 |
+
with gr.Column():
|
| 391 |
+
shared.gradio['max_new_tokens'] = gr.Slider(minimum=shared.settings['max_new_tokens_min'], maximum=shared.settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=shared.settings['max_new_tokens'])
|
| 392 |
+
shared.gradio['chat_prompt_size_slider'] = gr.Slider(minimum=shared.settings['chat_prompt_size_min'], maximum=shared.settings['chat_prompt_size_max'], step=1, label='Maximum prompt size in tokens', value=shared.settings['chat_prompt_size'])
|
| 393 |
+
with gr.Column():
|
| 394 |
+
shared.gradio['chat_generation_attempts'] = gr.Slider(minimum=shared.settings['chat_generation_attempts_min'], maximum=shared.settings['chat_generation_attempts_max'], value=shared.settings['chat_generation_attempts'], step=1, label='Generation attempts (for longer replies)')
|
| 395 |
+
shared.gradio['stop_at_newline'] = gr.Checkbox(value=shared.settings['stop_at_newline'], label='Stop generating at new line character?')
|
| 396 |
+
|
| 397 |
+
create_settings_menus(default_preset)
|
| 398 |
+
|
| 399 |
+
shared.input_params = [shared.gradio[k] for k in ['Chat input', 'generate_state', 'name1', 'name2', 'context', 'Chat mode', 'end_of_turn']]
|
| 400 |
+
|
| 401 |
+
def set_chat_input(textbox):
|
| 402 |
+
return textbox, ""
|
| 403 |
+
|
| 404 |
+
gen_events.append(shared.gradio['Generate'].click(set_chat_input, shared.gradio['textbox'], [shared.gradio['Chat input'], shared.gradio['textbox']], show_progress=False))
|
| 405 |
+
gen_events.append(shared.gradio['Generate'].click(chat.cai_chatbot_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream))
|
| 406 |
+
gen_events.append(shared.gradio['textbox'].submit(set_chat_input, shared.gradio['textbox'], [shared.gradio['Chat input'], shared.gradio['textbox']], show_progress=False))
|
| 407 |
+
gen_events.append(shared.gradio['textbox'].submit(chat.cai_chatbot_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream))
|
| 408 |
+
gen_events.append(shared.gradio['Regenerate'].click(chat.regenerate_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream))
|
| 409 |
+
gen_events.append(shared.gradio['Impersonate'].click(chat.impersonate_wrapper, shared.input_params, shared.gradio['textbox'], show_progress=shared.args.no_stream))
|
| 410 |
+
shared.gradio['Stop'].click(stop_everything_event, [], [], queue=False, cancels=gen_events if shared.args.no_stream else None)
|
| 411 |
+
|
| 412 |
+
shared.gradio['Copy last reply'].click(chat.send_last_reply_to_input, [], shared.gradio['textbox'], show_progress=shared.args.no_stream)
|
| 413 |
+
shared.gradio['Replace last reply'].click(chat.replace_last_reply, [shared.gradio[k] for k in ['textbox', 'name1', 'name2', 'Chat mode']], shared.gradio['display'], show_progress=shared.args.no_stream)
|
| 414 |
+
|
| 415 |
+
# Clear history with confirmation
|
| 416 |
+
clear_arr = [shared.gradio[k] for k in ['Clear history-confirm', 'Clear history', 'Clear history-cancel']]
|
| 417 |
+
shared.gradio['Clear history'].click(lambda: [gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)], None, clear_arr)
|
| 418 |
+
shared.gradio['Clear history-confirm'].click(lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, clear_arr)
|
| 419 |
+
shared.gradio['Clear history-confirm'].click(chat.clear_chat_log, [shared.gradio[k] for k in ['name1', 'name2', 'greeting', 'Chat mode']], shared.gradio['display'])
|
| 420 |
+
shared.gradio['Clear history-cancel'].click(lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, clear_arr)
|
| 421 |
+
shared.gradio['Chat mode'].change(lambda x: gr.update(visible=x == 'instruct'), shared.gradio['Chat mode'], shared.gradio['Instruction templates'])
|
| 422 |
+
|
| 423 |
+
shared.gradio['Remove last'].click(chat.remove_last_message, [shared.gradio[k] for k in ['name1', 'name2', 'Chat mode']], [shared.gradio['display'], shared.gradio['textbox']], show_progress=False)
|
| 424 |
+
shared.gradio['download_button'].click(chat.save_history, inputs=[], outputs=[shared.gradio['download']])
|
| 425 |
+
shared.gradio['Upload character'].click(chat.upload_character, [shared.gradio['upload_json'], shared.gradio['upload_img_bot']], [shared.gradio['character_menu']])
|
| 426 |
+
|
| 427 |
+
# Clearing stuff and saving the history
|
| 428 |
+
for i in ['Generate', 'Regenerate', 'Replace last reply']:
|
| 429 |
+
shared.gradio[i].click(lambda x: '', shared.gradio['textbox'], shared.gradio['textbox'], show_progress=False)
|
| 430 |
+
shared.gradio[i].click(lambda: chat.save_history(timestamp=False), [], [], show_progress=False)
|
| 431 |
+
shared.gradio['Clear history-confirm'].click(lambda: chat.save_history(timestamp=False), [], [], show_progress=False)
|
| 432 |
+
shared.gradio['textbox'].submit(lambda x: '', shared.gradio['textbox'], shared.gradio['textbox'], show_progress=False)
|
| 433 |
+
shared.gradio['textbox'].submit(lambda: chat.save_history(timestamp=False), [], [], show_progress=False)
|
| 434 |
+
|
| 435 |
+
shared.gradio['character_menu'].change(chat.load_character, [shared.gradio[k] for k in ['character_menu', 'name1', 'name2', 'Chat mode']], [shared.gradio[k] for k in ['name1', 'name2', 'character_picture', 'greeting', 'context', 'end_of_turn', 'display']])
|
| 436 |
+
shared.gradio['Instruction templates'].change(lambda character, name1, name2, mode: chat.load_character(character, name1, name2, mode), [shared.gradio[k] for k in ['Instruction templates', 'name1', 'name2', 'Chat mode']], [shared.gradio[k] for k in ['name1', 'name2', 'character_picture', 'greeting', 'context', 'end_of_turn', 'display']])
|
| 437 |
+
shared.gradio['upload_chat_history'].upload(chat.load_history, [shared.gradio[k] for k in ['upload_chat_history', 'name1', 'name2']], [])
|
| 438 |
+
shared.gradio['upload_img_tavern'].upload(chat.upload_tavern_character, [shared.gradio['upload_img_tavern'], shared.gradio['name1'], shared.gradio['name2']], [shared.gradio['character_menu']])
|
| 439 |
+
shared.gradio['your_picture'].change(chat.upload_your_profile_picture, [shared.gradio[k] for k in ['your_picture', 'name1', 'name2', 'Chat mode']], shared.gradio['display'])
|
| 440 |
+
|
| 441 |
+
reload_inputs = [shared.gradio[k] for k in ['name1', 'name2', 'Chat mode']]
|
| 442 |
+
shared.gradio['upload_chat_history'].upload(chat.redraw_html, reload_inputs, [shared.gradio['display']])
|
| 443 |
+
shared.gradio['Stop'].click(chat.redraw_html, reload_inputs, [shared.gradio['display']])
|
| 444 |
+
shared.gradio['Instruction templates'].change(chat.redraw_html, reload_inputs, [shared.gradio['display']])
|
| 445 |
+
shared.gradio['Chat mode'].change(chat.redraw_html, reload_inputs, [shared.gradio['display']])
|
| 446 |
+
|
| 447 |
+
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js+ui.chat_js}}}")
|
| 448 |
+
shared.gradio['interface'].load(lambda: chat.load_default_history(shared.settings['name1'], shared.settings['name2']), None, None)
|
| 449 |
+
shared.gradio['interface'].load(chat.redraw_html, reload_inputs, [shared.gradio['display']], show_progress=True)
|
| 450 |
+
|
| 451 |
+
elif shared.args.notebook:
|
| 452 |
+
with gr.Tab("Text generation", elem_id="main"):
|
| 453 |
+
with gr.Row():
|
| 454 |
+
with gr.Column(scale=4):
|
| 455 |
+
with gr.Tab('Raw'):
|
| 456 |
+
shared.gradio['textbox'] = gr.Textbox(value=default_text, elem_id="textbox", lines=27)
|
| 457 |
+
with gr.Tab('Markdown'):
|
| 458 |
+
shared.gradio['markdown'] = gr.Markdown()
|
| 459 |
+
with gr.Tab('HTML'):
|
| 460 |
+
shared.gradio['html'] = gr.HTML()
|
| 461 |
+
|
| 462 |
+
with gr.Row():
|
| 463 |
+
with gr.Column():
|
| 464 |
+
with gr.Row():
|
| 465 |
+
shared.gradio['Generate'] = gr.Button('Generate')
|
| 466 |
+
shared.gradio['Stop'] = gr.Button('Stop')
|
| 467 |
+
with gr.Column():
|
| 468 |
+
pass
|
| 469 |
+
|
| 470 |
+
with gr.Column(scale=1):
|
| 471 |
+
gr.HTML('<div style="padding-bottom: 13px"></div>')
|
| 472 |
+
shared.gradio['max_new_tokens'] = gr.Slider(minimum=shared.settings['max_new_tokens_min'], maximum=shared.settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=shared.settings['max_new_tokens'])
|
| 473 |
+
|
| 474 |
+
create_prompt_menus()
|
| 475 |
+
|
| 476 |
+
with gr.Tab("Parameters", elem_id="parameters"):
|
| 477 |
+
create_settings_menus(default_preset)
|
| 478 |
+
|
| 479 |
+
shared.input_params = [shared.gradio[k] for k in ['textbox', 'generate_state']]
|
| 480 |
+
output_params = [shared.gradio[k] for k in ['textbox', 'markdown', 'html']]
|
| 481 |
+
gen_events.append(shared.gradio['Generate'].click(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream))
|
| 482 |
+
gen_events.append(shared.gradio['textbox'].submit(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream))
|
| 483 |
+
shared.gradio['Stop'].click(stop_everything_event, [], [], queue=False, cancels=gen_events if shared.args.no_stream else None)
|
| 484 |
+
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js}}}")
|
| 485 |
+
|
| 486 |
+
else:
|
| 487 |
+
with gr.Tab("Text generation", elem_id="main"):
|
| 488 |
+
with gr.Row():
|
| 489 |
+
with gr.Column():
|
| 490 |
+
shared.gradio['textbox'] = gr.Textbox(value=default_text, lines=21, label='Input')
|
| 491 |
+
shared.gradio['max_new_tokens'] = gr.Slider(minimum=shared.settings['max_new_tokens_min'], maximum=shared.settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=shared.settings['max_new_tokens'])
|
| 492 |
+
shared.gradio['Generate'] = gr.Button('Generate')
|
| 493 |
+
with gr.Row():
|
| 494 |
+
with gr.Column():
|
| 495 |
+
shared.gradio['Continue'] = gr.Button('Continue')
|
| 496 |
+
with gr.Column():
|
| 497 |
+
shared.gradio['Stop'] = gr.Button('Stop')
|
| 498 |
+
|
| 499 |
+
create_prompt_menus()
|
| 500 |
+
|
| 501 |
+
with gr.Column():
|
| 502 |
+
with gr.Tab('Raw'):
|
| 503 |
+
shared.gradio['output_textbox'] = gr.Textbox(lines=27, label='Output')
|
| 504 |
+
with gr.Tab('Markdown'):
|
| 505 |
+
shared.gradio['markdown'] = gr.Markdown()
|
| 506 |
+
with gr.Tab('HTML'):
|
| 507 |
+
shared.gradio['html'] = gr.HTML()
|
| 508 |
+
|
| 509 |
+
with gr.Tab("Parameters", elem_id="parameters"):
|
| 510 |
+
create_settings_menus(default_preset)
|
| 511 |
+
|
| 512 |
+
shared.input_params = [shared.gradio[k] for k in ['textbox', 'generate_state']]
|
| 513 |
+
output_params = [shared.gradio[k] for k in ['output_textbox', 'markdown', 'html']]
|
| 514 |
+
gen_events.append(shared.gradio['Generate'].click(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream))
|
| 515 |
+
gen_events.append(shared.gradio['textbox'].submit(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream))
|
| 516 |
+
gen_events.append(shared.gradio['Continue'].click(generate_reply, [shared.gradio['output_textbox']] + shared.input_params[1:], output_params, show_progress=shared.args.no_stream))
|
| 517 |
+
shared.gradio['Stop'].click(stop_everything_event, [], [], queue=False, cancels=gen_events if shared.args.no_stream else None)
|
| 518 |
+
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js}}}")
|
| 519 |
+
|
| 520 |
+
with gr.Tab("Model", elem_id="model-tab"):
|
| 521 |
+
create_model_menus()
|
| 522 |
+
|
| 523 |
+
with gr.Tab("Training", elem_id="training-tab"):
|
| 524 |
+
training.create_train_interface()
|
| 525 |
+
|
| 526 |
+
with gr.Tab("Interface mode", elem_id="interface-mode"):
|
| 527 |
+
modes = ["default", "notebook", "chat", "cai_chat"]
|
| 528 |
+
current_mode = "default"
|
| 529 |
+
for mode in modes[1:]:
|
| 530 |
+
if eval(f"shared.args.{mode}"):
|
| 531 |
+
current_mode = mode
|
| 532 |
+
break
|
| 533 |
+
cmd_list = vars(shared.args)
|
| 534 |
+
bool_list = [k for k in cmd_list if type(cmd_list[k]) is bool and k not in modes]
|
| 535 |
+
bool_active = [k for k in bool_list if vars(shared.args)[k]]
|
| 536 |
+
|
| 537 |
+
gr.Markdown("*Experimental*")
|
| 538 |
+
shared.gradio['interface_modes_menu'] = gr.Dropdown(choices=modes, value=current_mode, label="Mode")
|
| 539 |
+
shared.gradio['extensions_menu'] = gr.CheckboxGroup(choices=get_available_extensions(), value=shared.args.extensions, label="Available extensions")
|
| 540 |
+
shared.gradio['bool_menu'] = gr.CheckboxGroup(choices=bool_list, value=bool_active, label="Boolean command-line flags")
|
| 541 |
+
shared.gradio['reset_interface'] = gr.Button("Apply and restart the interface")
|
| 542 |
+
|
| 543 |
+
shared.gradio['reset_interface'].click(set_interface_arguments, [shared.gradio[k] for k in ['interface_modes_menu', 'extensions_menu', 'bool_menu']], None)
|
| 544 |
+
shared.gradio['reset_interface'].click(lambda: None, None, None, _js='() => {document.body.innerHTML=\'<h1 style="font-family:monospace;margin-top:20%;color:lightgray;text-align:center;">Reloading...</h1>\'; setTimeout(function(){location.reload()},2500); return []}')
|
| 545 |
+
|
| 546 |
+
if shared.args.extensions is not None:
|
| 547 |
+
extensions_module.create_extensions_block()
|
| 548 |
+
|
| 549 |
+
def change_dict_value(d, key, value):
|
| 550 |
+
d[key] = value
|
| 551 |
+
return d
|
| 552 |
+
|
| 553 |
+
for k in ['do_sample', 'temperature', 'top_p', 'typical_p', 'repetition_penalty', 'encoder_repetition_penalty', 'top_k', 'min_length', 'no_repeat_ngram_size', 'num_beams', 'penalty_alpha', 'length_penalty', 'early_stopping', 'max_new_tokens', 'seed', 'stop_at_newline', 'chat_prompt_size_slider', 'chat_generation_attempts']:
|
| 554 |
+
if k not in shared.gradio:
|
| 555 |
+
continue
|
| 556 |
+
if type(shared.gradio[k]) in [gr.Checkbox, gr.Number]:
|
| 557 |
+
shared.gradio[k].change(lambda state, value, copy=k: change_dict_value(state, copy, value), inputs=[shared.gradio['generate_state'], shared.gradio[k]], outputs=shared.gradio['generate_state'])
|
| 558 |
+
else:
|
| 559 |
+
shared.gradio[k].release(lambda state, value, copy=k: change_dict_value(state, copy, value), inputs=[shared.gradio['generate_state'], shared.gradio[k]], outputs=shared.gradio['generate_state'])
|
| 560 |
+
|
| 561 |
+
if not shared.is_chat():
|
| 562 |
+
api.create_apis()
|
| 563 |
+
|
| 564 |
+
# Authentication
|
| 565 |
+
auth = None
|
| 566 |
+
if shared.args.gradio_auth_path is not None:
|
| 567 |
+
gradio_auth_creds = []
|
| 568 |
+
with open(shared.args.gradio_auth_path, 'r', encoding="utf8") as file:
|
| 569 |
+
for line in file.readlines():
|
| 570 |
+
gradio_auth_creds += [x.strip() for x in line.split(',') if x.strip()]
|
| 571 |
+
auth = [tuple(cred.split(':')) for cred in gradio_auth_creds]
|
| 572 |
+
|
| 573 |
+
# Launch the interface
|
| 574 |
+
shared.gradio['interface'].queue()
|
| 575 |
+
if shared.args.listen:
|
| 576 |
+
shared.gradio['interface'].launch(prevent_thread_lock=True, share=True, server_name='0.0.0.0', server_port=shared.args.listen_port, inbrowser=shared.args.auto_launch, auth=auth)
|
| 577 |
+
else:
|
| 578 |
+
shared.gradio['interface'].launch(prevent_thread_lock=True, share=True, server_port=shared.args.listen_port, inbrowser=shared.args.auto_launch, auth=auth)
|
| 579 |
+
|
| 580 |
|
| 581 |
+
create_interface()
|
|
|
|
| 582 |
|
| 583 |
+
while True:
|
| 584 |
+
time.sleep(0.5)
|
| 585 |
+
if shared.need_restart:
|
| 586 |
+
shared.need_restart = False
|
| 587 |
+
shared.gradio['interface'].close()
|
| 588 |
+
create_interface()
|