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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import warnings
|
4 |
+
|
5 |
+
os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'
|
6 |
+
os.environ['BITSANDBYTES_NOWELCOME'] = '1'
|
7 |
+
warnings.filterwarnings('ignore', category=UserWarning, message='TypedStorage is deprecated')
|
8 |
+
|
9 |
+
# This is a hack to prevent Gradio from phoning home when it gets imported
|
10 |
+
def my_get(url, **kwargs):
|
11 |
+
print('Gradio HTTP request redirected to localhost :)')
|
12 |
+
kwargs.setdefault('allow_redirects', True)
|
13 |
+
return requests.api.request('get', 'http://127.0.0.1/', **kwargs)
|
14 |
+
|
15 |
+
original_get = requests.get
|
16 |
+
requests.get = my_get
|
17 |
+
import gradio as gr
|
18 |
+
requests.get = original_get
|
19 |
+
|
20 |
+
# This fixes LaTeX rendering on some systems
|
21 |
+
import matplotlib
|
22 |
+
matplotlib.use('Agg')
|
23 |
+
|
24 |
+
import importlib
|
25 |
+
import io
|
26 |
+
import json
|
27 |
+
import math
|
28 |
+
import os
|
29 |
+
import re
|
30 |
+
import sys
|
31 |
+
import time
|
32 |
+
import traceback
|
33 |
+
import zipfile
|
34 |
+
from datetime import datetime
|
35 |
+
from functools import partial
|
36 |
+
from pathlib import Path
|
37 |
+
|
38 |
+
import psutil
|
39 |
+
import torch
|
40 |
+
import yaml
|
41 |
+
from PIL import Image
|
42 |
+
|
43 |
+
import modules.extensions as extensions_module
|
44 |
+
from modules import chat, shared, training, ui
|
45 |
+
from modules.html_generator import chat_html_wrapper
|
46 |
+
from modules.LoRA import add_lora_to_model
|
47 |
+
from modules.models import load_model, load_soft_prompt, unload_model
|
48 |
+
from modules.text_generation import (encode, generate_reply,
|
49 |
+
stop_everything_event)
|
50 |
+
|
51 |
+
|
52 |
+
def get_available_models():
|
53 |
+
if shared.args.flexgen:
|
54 |
+
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)
|
55 |
+
else:
|
56 |
+
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', '.yaml'))], key=str.lower)
|
57 |
+
|
58 |
+
|
59 |
+
def get_available_presets():
|
60 |
+
return sorted(set((k.stem for k in Path('presets').glob('*.txt'))), key=str.lower)
|
61 |
+
|
62 |
+
|
63 |
+
def get_available_prompts():
|
64 |
+
prompts = []
|
65 |
+
prompts += sorted(set((k.stem for k in Path('prompts').glob('[0-9]*.txt'))), key=str.lower, reverse=True)
|
66 |
+
prompts += sorted(set((k.stem for k in Path('prompts').glob('*.txt'))), key=str.lower)
|
67 |
+
prompts += ['None']
|
68 |
+
return prompts
|
69 |
+
|
70 |
+
|
71 |
+
def get_available_characters():
|
72 |
+
paths = (x for x in Path('characters').iterdir() if x.suffix in ('.json', '.yaml', '.yml'))
|
73 |
+
return ['None'] + sorted(set((k.stem for k in paths if k.stem != "instruction-following")), key=str.lower)
|
74 |
+
|
75 |
+
|
76 |
+
def get_available_instruction_templates():
|
77 |
+
path = "characters/instruction-following"
|
78 |
+
paths = []
|
79 |
+
if os.path.exists(path):
|
80 |
+
paths = (x for x in Path(path).iterdir() if x.suffix in ('.json', '.yaml', '.yml'))
|
81 |
+
return ['None'] + sorted(set((k.stem for k in paths)), key=str.lower)
|
82 |
+
|
83 |
+
|
84 |
+
def get_available_extensions():
|
85 |
+
return sorted(set(map(lambda x: x.parts[1], Path('extensions').glob('*/script.py'))), key=str.lower)
|
86 |
+
|
87 |
+
|
88 |
+
def get_available_softprompts():
|
89 |
+
return ['None'] + sorted(set((k.stem for k in Path('softprompts').glob('*.zip'))), key=str.lower)
|
90 |
+
|
91 |
+
|
92 |
+
def get_available_loras():
|
93 |
+
return 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)
|
94 |
+
|
95 |
+
|
96 |
+
def load_model_wrapper(selected_model):
|
97 |
+
try:
|
98 |
+
yield f"Loading {selected_model}..."
|
99 |
+
shared.model_name = selected_model
|
100 |
+
unload_model()
|
101 |
+
if selected_model != '':
|
102 |
+
shared.model, shared.tokenizer = load_model(shared.model_name)
|
103 |
+
|
104 |
+
yield f"Successfully loaded {selected_model}"
|
105 |
+
except:
|
106 |
+
yield traceback.format_exc()
|
107 |
+
|
108 |
+
|
109 |
+
def load_lora_wrapper(selected_loras):
|
110 |
+
yield ("Applying the following LoRAs to {}:\n\n{}".format(shared.model_name, '\n'.join(selected_loras)))
|
111 |
+
add_lora_to_model(selected_loras)
|
112 |
+
yield ("Successfuly applied the LoRAs")
|
113 |
+
|
114 |
+
|
115 |
+
def load_preset_values(preset_menu, state, return_dict=False):
|
116 |
+
generate_params = {
|
117 |
+
'do_sample': True,
|
118 |
+
'temperature': 1,
|
119 |
+
'top_p': 1,
|
120 |
+
'typical_p': 1,
|
121 |
+
'repetition_penalty': 1,
|
122 |
+
'encoder_repetition_penalty': 1,
|
123 |
+
'top_k': 50,
|
124 |
+
'num_beams': 1,
|
125 |
+
'penalty_alpha': 0,
|
126 |
+
'min_length': 0,
|
127 |
+
'length_penalty': 1,
|
128 |
+
'no_repeat_ngram_size': 0,
|
129 |
+
'early_stopping': False,
|
130 |
+
}
|
131 |
+
with open(Path(f'presets/{preset_menu}.txt'), 'r') as infile:
|
132 |
+
preset = infile.read()
|
133 |
+
for i in preset.splitlines():
|
134 |
+
i = i.rstrip(',').strip().split('=')
|
135 |
+
if len(i) == 2 and i[0].strip() != 'tokens':
|
136 |
+
generate_params[i[0].strip()] = eval(i[1].strip())
|
137 |
+
generate_params['temperature'] = min(1.99, generate_params['temperature'])
|
138 |
+
|
139 |
+
if return_dict:
|
140 |
+
return generate_params
|
141 |
+
else:
|
142 |
+
state.update(generate_params)
|
143 |
+
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']]
|
144 |
+
|
145 |
+
|
146 |
+
def upload_soft_prompt(file):
|
147 |
+
with zipfile.ZipFile(io.BytesIO(file)) as zf:
|
148 |
+
zf.extract('meta.json')
|
149 |
+
j = json.loads(open('meta.json', 'r').read())
|
150 |
+
name = j['name']
|
151 |
+
Path('meta.json').unlink()
|
152 |
+
|
153 |
+
with open(Path(f'softprompts/{name}.zip'), 'wb') as f:
|
154 |
+
f.write(file)
|
155 |
+
|
156 |
+
return name
|
157 |
+
|
158 |
+
|
159 |
+
def save_prompt(text):
|
160 |
+
fname = f"{datetime.now().strftime('%Y-%m-%d-%H%M%S')}.txt"
|
161 |
+
with open(Path(f'prompts/{fname}'), 'w', encoding='utf-8') as f:
|
162 |
+
f.write(text)
|
163 |
+
return f"Saved to prompts/{fname}"
|
164 |
+
|
165 |
+
|
166 |
+
def load_prompt(fname):
|
167 |
+
if fname in ['None', '']:
|
168 |
+
return ''
|
169 |
+
else:
|
170 |
+
with open(Path(f'prompts/{fname}.txt'), 'r', encoding='utf-8') as f:
|
171 |
+
text = f.read()
|
172 |
+
if text[-1] == '\n':
|
173 |
+
text = text[:-1]
|
174 |
+
return text
|
175 |
+
|
176 |
+
|
177 |
+
def count_tokens(text):
|
178 |
+
tokens = len(encode(text)[0])
|
179 |
+
return f'{tokens} tokens in the input.'
|
180 |
+
|
181 |
+
|
182 |
+
def download_model_wrapper(repo_id):
|
183 |
+
try:
|
184 |
+
downloader = importlib.import_module("download-model")
|
185 |
+
|
186 |
+
model = repo_id
|
187 |
+
branch = "main"
|
188 |
+
check = False
|
189 |
+
|
190 |
+
yield ("Cleaning up the model/branch names")
|
191 |
+
model, branch = downloader.sanitize_model_and_branch_names(model, branch)
|
192 |
+
|
193 |
+
yield ("Getting the download links from Hugging Face")
|
194 |
+
links, sha256, is_lora = downloader.get_download_links_from_huggingface(model, branch, text_only=False)
|
195 |
+
|
196 |
+
yield ("Getting the output folder")
|
197 |
+
output_folder = downloader.get_output_folder(model, branch, is_lora)
|
198 |
+
|
199 |
+
if check:
|
200 |
+
yield ("Checking previously downloaded files")
|
201 |
+
downloader.check_model_files(model, branch, links, sha256, output_folder)
|
202 |
+
else:
|
203 |
+
yield (f"Downloading files to {output_folder}")
|
204 |
+
downloader.download_model_files(model, branch, links, sha256, output_folder, threads=1)
|
205 |
+
yield ("Done!")
|
206 |
+
except:
|
207 |
+
yield traceback.format_exc()
|
208 |
+
|
209 |
+
|
210 |
+
# Update the command-line arguments based on the interface values
|
211 |
+
def update_model_parameters(state, initial=False):
|
212 |
+
elements = ui.list_model_elements() # the names of the parameters
|
213 |
+
gpu_memories = []
|
214 |
+
|
215 |
+
for i, element in enumerate(elements):
|
216 |
+
if element not in state:
|
217 |
+
continue
|
218 |
+
|
219 |
+
value = state[element]
|
220 |
+
if element.startswith('gpu_memory'):
|
221 |
+
gpu_memories.append(value)
|
222 |
+
continue
|
223 |
+
|
224 |
+
if initial and vars(shared.args)[element] != vars(shared.args_defaults)[element]:
|
225 |
+
continue
|
226 |
+
|
227 |
+
# Setting null defaults
|
228 |
+
if element in ['wbits', 'groupsize', 'model_type'] and value == 'None':
|
229 |
+
value = vars(shared.args_defaults)[element]
|
230 |
+
elif element in ['cpu_memory'] and value == 0:
|
231 |
+
value = vars(shared.args_defaults)[element]
|
232 |
+
|
233 |
+
# Making some simple conversions
|
234 |
+
if element in ['wbits', 'groupsize', 'pre_layer']:
|
235 |
+
value = int(value)
|
236 |
+
elif element == 'cpu_memory' and value is not None:
|
237 |
+
value = f"{value}MiB"
|
238 |
+
|
239 |
+
setattr(shared.args, element, value)
|
240 |
+
|
241 |
+
found_positive = False
|
242 |
+
for i in gpu_memories:
|
243 |
+
if i > 0:
|
244 |
+
found_positive = True
|
245 |
+
break
|
246 |
+
|
247 |
+
if not (initial and vars(shared.args)['gpu_memory'] != vars(shared.args_defaults)['gpu_memory']):
|
248 |
+
if found_positive:
|
249 |
+
shared.args.gpu_memory = [f"{i}MiB" for i in gpu_memories]
|
250 |
+
else:
|
251 |
+
shared.args.gpu_memory = None
|
252 |
+
|
253 |
+
|
254 |
+
def get_model_specific_settings(model):
|
255 |
+
settings = shared.model_config
|
256 |
+
model_settings = {}
|
257 |
+
|
258 |
+
for pat in settings:
|
259 |
+
if re.match(pat.lower(), model.lower()):
|
260 |
+
for k in settings[pat]:
|
261 |
+
model_settings[k] = settings[pat][k]
|
262 |
+
|
263 |
+
return model_settings
|
264 |
+
|
265 |
+
|
266 |
+
def load_model_specific_settings(model, state, return_dict=False):
|
267 |
+
model_settings = get_model_specific_settings(model)
|
268 |
+
for k in model_settings:
|
269 |
+
if k in state:
|
270 |
+
state[k] = model_settings[k]
|
271 |
+
|
272 |
+
return state
|
273 |
+
|
274 |
+
|
275 |
+
def save_model_settings(model, state):
|
276 |
+
if model == 'None':
|
277 |
+
yield ("Not saving the settings because no model is loaded.")
|
278 |
+
return
|
279 |
+
|
280 |
+
with Path(f'{shared.args.model_dir}/config-user.yaml') as p:
|
281 |
+
if p.exists():
|
282 |
+
user_config = yaml.safe_load(open(p, 'r').read())
|
283 |
+
else:
|
284 |
+
user_config = {}
|
285 |
+
|
286 |
+
if model not in user_config:
|
287 |
+
user_config[model] = {}
|
288 |
+
|
289 |
+
for k in ui.list_model_elements():
|
290 |
+
user_config[model][k] = state[k]
|
291 |
+
|
292 |
+
with open(p, 'w') as f:
|
293 |
+
f.write(yaml.dump(user_config))
|
294 |
+
|
295 |
+
yield (f"Settings for {model} saved to {p}")
|
296 |
+
|
297 |
+
|
298 |
+
def create_model_menus():
|
299 |
+
# Finding the default values for the GPU and CPU memories
|
300 |
+
total_mem = []
|
301 |
+
for i in range(torch.cuda.device_count()):
|
302 |
+
total_mem.append(math.floor(torch.cuda.get_device_properties(i).total_memory / (1024 * 1024)))
|
303 |
+
|
304 |
+
default_gpu_mem = []
|
305 |
+
if shared.args.gpu_memory is not None and len(shared.args.gpu_memory) > 0:
|
306 |
+
for i in shared.args.gpu_memory:
|
307 |
+
if 'mib' in i.lower():
|
308 |
+
default_gpu_mem.append(int(re.sub('[a-zA-Z ]', '', i)))
|
309 |
+
else:
|
310 |
+
default_gpu_mem.append(int(re.sub('[a-zA-Z ]', '', i)) * 1000)
|
311 |
+
while len(default_gpu_mem) < len(total_mem):
|
312 |
+
default_gpu_mem.append(0)
|
313 |
+
|
314 |
+
total_cpu_mem = math.floor(psutil.virtual_memory().total / (1024 * 1024))
|
315 |
+
if shared.args.cpu_memory is not None:
|
316 |
+
default_cpu_mem = re.sub('[a-zA-Z ]', '', shared.args.cpu_memory)
|
317 |
+
else:
|
318 |
+
default_cpu_mem = 0
|
319 |
+
|
320 |
+
with gr.Row():
|
321 |
+
with gr.Column():
|
322 |
+
with gr.Row():
|
323 |
+
with gr.Column():
|
324 |
+
with gr.Row():
|
325 |
+
shared.gradio['model_menu'] = gr.Dropdown(choices=get_available_models(), value=shared.model_name, label='Model')
|
326 |
+
ui.create_refresh_button(shared.gradio['model_menu'], lambda: None, lambda: {'choices': get_available_models()}, 'refresh-button')
|
327 |
+
|
328 |
+
with gr.Column():
|
329 |
+
with gr.Row():
|
330 |
+
shared.gradio['lora_menu'] = gr.Dropdown(multiselect=True, choices=get_available_loras(), value=shared.lora_names, label='LoRA(s)')
|
331 |
+
ui.create_refresh_button(shared.gradio['lora_menu'], lambda: None, lambda: {'choices': get_available_loras(), 'value': shared.lora_names}, 'refresh-button')
|
332 |
+
|
333 |
+
with gr.Column():
|
334 |
+
with gr.Row():
|
335 |
+
shared.gradio['lora_menu_apply'] = gr.Button(value='Apply the selected LoRAs')
|
336 |
+
with gr.Row():
|
337 |
+
unload = gr.Button("Unload the model")
|
338 |
+
reload = gr.Button("Reload the model")
|
339 |
+
save_settings = gr.Button("Save settings for this model")
|
340 |
+
|
341 |
+
with gr.Row():
|
342 |
+
with gr.Column():
|
343 |
+
with gr.Box():
|
344 |
+
gr.Markdown('Transformers parameters')
|
345 |
+
with gr.Row():
|
346 |
+
with gr.Column():
|
347 |
+
for i in range(len(total_mem)):
|
348 |
+
shared.gradio[f'gpu_memory_{i}'] = gr.Slider(label=f"gpu-memory in MiB for device :{i}", maximum=total_mem[i], value=default_gpu_mem[i])
|
349 |
+
shared.gradio['cpu_memory'] = gr.Slider(label="cpu-memory in MiB", maximum=total_cpu_mem, value=default_cpu_mem)
|
350 |
+
|
351 |
+
with gr.Column():
|
352 |
+
shared.gradio['auto_devices'] = gr.Checkbox(label="auto-devices", value=shared.args.auto_devices)
|
353 |
+
shared.gradio['disk'] = gr.Checkbox(label="disk", value=shared.args.disk)
|
354 |
+
shared.gradio['cpu'] = gr.Checkbox(label="cpu", value=shared.args.cpu)
|
355 |
+
shared.gradio['bf16'] = gr.Checkbox(label="bf16", value=shared.args.bf16)
|
356 |
+
shared.gradio['load_in_8bit'] = gr.Checkbox(label="load-in-8bit", value=shared.args.load_in_8bit)
|
357 |
+
|
358 |
+
with gr.Column():
|
359 |
+
with gr.Box():
|
360 |
+
gr.Markdown('GPTQ parameters')
|
361 |
+
with gr.Row():
|
362 |
+
with gr.Column():
|
363 |
+
shared.gradio['wbits'] = gr.Dropdown(label="wbits", choices=["None", 1, 2, 3, 4, 8], value=shared.args.wbits if shared.args.wbits > 0 else "None")
|
364 |
+
shared.gradio['groupsize'] = gr.Dropdown(label="groupsize", choices=["None", 32, 64, 128], value=shared.args.groupsize if shared.args.groupsize > 0 else "None")
|
365 |
+
|
366 |
+
with gr.Column():
|
367 |
+
shared.gradio['model_type'] = gr.Dropdown(label="model_type", choices=["None", "llama", "opt", "gptj"], value=shared.args.model_type or "None")
|
368 |
+
shared.gradio['pre_layer'] = gr.Slider(label="pre_layer", minimum=0, maximum=100, value=shared.args.pre_layer)
|
369 |
+
|
370 |
+
with gr.Row():
|
371 |
+
with gr.Column():
|
372 |
+
shared.gradio['custom_model_menu'] = gr.Textbox(label="Download custom model or LoRA", info="Enter Hugging Face username/model path, e.g: facebook/galactica-125m")
|
373 |
+
shared.gradio['download_model_button'] = gr.Button("Download")
|
374 |
+
|
375 |
+
with gr.Column():
|
376 |
+
shared.gradio['model_status'] = gr.Markdown('No model is loaded' if shared.model_name == 'None' else 'Ready')
|
377 |
+
|
378 |
+
# In this event handler, the interface state is read and updated
|
379 |
+
# with the model defaults (if any), and then the model is loaded
|
380 |
+
shared.gradio['model_menu'].change(
|
381 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
382 |
+
load_model_specific_settings, [shared.gradio[k] for k in ['model_menu', 'interface_state']], shared.gradio['interface_state']).then(
|
383 |
+
ui.apply_interface_values, shared.gradio['interface_state'], [shared.gradio[k] for k in ui.list_interface_input_elements(chat=shared.is_chat())], show_progress=False).then(
|
384 |
+
update_model_parameters, shared.gradio['interface_state'], None).then(
|
385 |
+
load_model_wrapper, shared.gradio['model_menu'], shared.gradio['model_status'], show_progress=True)
|
386 |
+
|
387 |
+
unload.click(
|
388 |
+
unload_model, None, None).then(
|
389 |
+
lambda: "Model unloaded", None, shared.gradio['model_status'])
|
390 |
+
|
391 |
+
reload.click(
|
392 |
+
unload_model, None, None).then(
|
393 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
394 |
+
update_model_parameters, shared.gradio['interface_state'], None).then(
|
395 |
+
load_model_wrapper, shared.gradio['model_menu'], shared.gradio['model_status'], show_progress=False)
|
396 |
+
|
397 |
+
save_settings.click(
|
398 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
399 |
+
save_model_settings, [shared.gradio[k] for k in ['model_menu', 'interface_state']], shared.gradio['model_status'], show_progress=False)
|
400 |
+
|
401 |
+
shared.gradio['lora_menu_apply'].click(load_lora_wrapper, shared.gradio['lora_menu'], shared.gradio['model_status'], show_progress=False)
|
402 |
+
shared.gradio['download_model_button'].click(download_model_wrapper, shared.gradio['custom_model_menu'], shared.gradio['model_status'], show_progress=False)
|
403 |
+
|
404 |
+
|
405 |
+
def create_settings_menus(default_preset):
|
406 |
+
|
407 |
+
generate_params = load_preset_values(default_preset if not shared.args.flexgen else 'Naive', {}, return_dict=True)
|
408 |
+
|
409 |
+
with gr.Row():
|
410 |
+
with gr.Column():
|
411 |
+
with gr.Row():
|
412 |
+
shared.gradio['preset_menu'] = gr.Dropdown(choices=get_available_presets(), value=default_preset if not shared.args.flexgen else 'Naive', label='Generation parameters preset')
|
413 |
+
ui.create_refresh_button(shared.gradio['preset_menu'], lambda: None, lambda: {'choices': get_available_presets()}, 'refresh-button')
|
414 |
+
with gr.Column():
|
415 |
+
shared.gradio['seed'] = gr.Number(value=shared.settings['seed'], label='Seed (-1 for random)')
|
416 |
+
|
417 |
+
with gr.Row():
|
418 |
+
with gr.Column():
|
419 |
+
with gr.Box():
|
420 |
+
gr.Markdown('Custom generation parameters ([click here to view technical documentation](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig))')
|
421 |
+
with gr.Row():
|
422 |
+
with gr.Column():
|
423 |
+
shared.gradio['temperature'] = gr.Slider(0.01, 1.99, value=generate_params['temperature'], step=0.01, label='temperature', info='Primary factor to control randomness of outputs. 0 = deterministic (only the most likely token is used). Higher value = more randomness.')
|
424 |
+
shared.gradio['top_p'] = gr.Slider(0.0, 1.0, value=generate_params['top_p'], step=0.01, label='top_p', info='If not set to 1, select tokens with probabilities adding up to less than this number. Higher value = higher range of possible random results.')
|
425 |
+
shared.gradio['top_k'] = gr.Slider(0, 200, value=generate_params['top_k'], step=1, label='top_k', info='Similar to top_p, but select instead only the top_k most likely tokens. Higher value = higher range of possible random results.')
|
426 |
+
shared.gradio['typical_p'] = gr.Slider(0.0, 1.0, value=generate_params['typical_p'], step=0.01, label='typical_p', info='If not set to 1, select only tokens that are at least this much more likely to appear than random tokens, given the prior text.')
|
427 |
+
with gr.Column():
|
428 |
+
shared.gradio['repetition_penalty'] = gr.Slider(1.0, 1.5, value=generate_params['repetition_penalty'], step=0.01, label='repetition_penalty', info='Exponential penalty factor for repeating prior tokens. 1 means no penalty, higher value = less repetition, lower value = more repetition.')
|
429 |
+
shared.gradio['encoder_repetition_penalty'] = gr.Slider(0.8, 1.5, value=generate_params['encoder_repetition_penalty'], step=0.01, label='encoder_repetition_penalty', info='Also known as the "Hallucinations filter". Used to penalize tokens that are *not* in the prior text. Higher value = more likely to stay in context, lower value = more likely to diverge.')
|
430 |
+
shared.gradio['no_repeat_ngram_size'] = gr.Slider(0, 20, step=1, value=generate_params['no_repeat_ngram_size'], label='no_repeat_ngram_size', info='If not set to 0, specifies the length of token sets that are completely blocked from repeating at all. Higher values = blocks larger phrases, lower values = blocks words or letters from repeating. Only 0 or high values are a good idea in most cases.')
|
431 |
+
shared.gradio['min_length'] = gr.Slider(0, 2000, step=1, value=generate_params['min_length'], label='min_length', info='Minimum generation length in tokens.')
|
432 |
+
shared.gradio['do_sample'] = gr.Checkbox(value=generate_params['do_sample'], label='do_sample')
|
433 |
+
with gr.Column():
|
434 |
+
with gr.Box():
|
435 |
+
gr.Markdown('Contrastive search')
|
436 |
+
shared.gradio['penalty_alpha'] = gr.Slider(0, 5, value=generate_params['penalty_alpha'], label='penalty_alpha')
|
437 |
+
|
438 |
+
gr.Markdown('Beam search (uses a lot of VRAM)')
|
439 |
+
with gr.Row():
|
440 |
+
with gr.Column():
|
441 |
+
shared.gradio['num_beams'] = gr.Slider(1, 20, step=1, value=generate_params['num_beams'], label='num_beams')
|
442 |
+
shared.gradio['length_penalty'] = gr.Slider(-5, 5, value=generate_params['length_penalty'], label='length_penalty')
|
443 |
+
with gr.Column():
|
444 |
+
shared.gradio['early_stopping'] = gr.Checkbox(value=generate_params['early_stopping'], label='early_stopping')
|
445 |
+
|
446 |
+
with gr.Box():
|
447 |
+
with gr.Row():
|
448 |
+
with gr.Column():
|
449 |
+
shared.gradio['truncation_length'] = gr.Slider(value=shared.settings['truncation_length'], minimum=shared.settings['truncation_length_min'], maximum=shared.settings['truncation_length_max'], step=1, label='Truncate the prompt up to this length', info='The leftmost tokens are removed if the prompt exceeds this length. Most models require this to be at most 2048.')
|
450 |
+
shared.gradio['custom_stopping_strings'] = gr.Textbox(lines=1, value=shared.settings["custom_stopping_strings"] or None, label='Custom stopping strings', info='In addition to the defaults. Written between "" and separated by commas. For instance: "\\nYour Assistant:", "\\nThe assistant:"')
|
451 |
+
with gr.Column():
|
452 |
+
shared.gradio['add_bos_token'] = gr.Checkbox(value=shared.settings['add_bos_token'], label='Add the bos_token to the beginning of prompts', info='Disabling this can make the replies more creative.')
|
453 |
+
shared.gradio['ban_eos_token'] = gr.Checkbox(value=shared.settings['ban_eos_token'], label='Ban the eos_token', info='Forces the model to never end the generation prematurely.')
|
454 |
+
|
455 |
+
shared.gradio['skip_special_tokens'] = gr.Checkbox(value=shared.settings['skip_special_tokens'], label='Skip special tokens', info='Some specific models need this unset.')
|
456 |
+
|
457 |
+
with gr.Accordion('Soft prompt', open=False):
|
458 |
+
with gr.Row():
|
459 |
+
shared.gradio['softprompts_menu'] = gr.Dropdown(choices=get_available_softprompts(), value='None', label='Soft prompt')
|
460 |
+
ui.create_refresh_button(shared.gradio['softprompts_menu'], lambda: None, lambda: {'choices': get_available_softprompts()}, 'refresh-button')
|
461 |
+
|
462 |
+
gr.Markdown('Upload a soft prompt (.zip format):')
|
463 |
+
with gr.Row():
|
464 |
+
shared.gradio['upload_softprompt'] = gr.File(type='binary', file_types=['.zip'])
|
465 |
+
|
466 |
+
shared.gradio['preset_menu'].change(load_preset_values, [shared.gradio[k] for k in ['preset_menu', 'interface_state']], [shared.gradio[k] for k in ['interface_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']])
|
467 |
+
shared.gradio['softprompts_menu'].change(load_soft_prompt, shared.gradio['softprompts_menu'], shared.gradio['softprompts_menu'], show_progress=True)
|
468 |
+
shared.gradio['upload_softprompt'].upload(upload_soft_prompt, shared.gradio['upload_softprompt'], shared.gradio['softprompts_menu'])
|
469 |
+
|
470 |
+
|
471 |
+
def set_interface_arguments(interface_mode, extensions, bool_active):
|
472 |
+
modes = ["default", "notebook", "chat", "cai_chat"]
|
473 |
+
cmd_list = vars(shared.args)
|
474 |
+
bool_list = [k for k in cmd_list if type(cmd_list[k]) is bool and k not in modes]
|
475 |
+
|
476 |
+
shared.args.extensions = extensions
|
477 |
+
for k in modes[1:]:
|
478 |
+
setattr(shared.args, k, False)
|
479 |
+
if interface_mode != "default":
|
480 |
+
setattr(shared.args, interface_mode, True)
|
481 |
+
|
482 |
+
for k in bool_list:
|
483 |
+
setattr(shared.args, k, False)
|
484 |
+
for k in bool_active:
|
485 |
+
setattr(shared.args, k, True)
|
486 |
+
|
487 |
+
shared.need_restart = True
|
488 |
+
|
489 |
+
|
490 |
+
def create_interface():
|
491 |
+
|
492 |
+
# Defining some variables
|
493 |
+
gen_events = []
|
494 |
+
default_preset = shared.settings['presets'][next((k for k in shared.settings['presets'] if re.match(k.lower(), shared.model_name.lower())), 'default')]
|
495 |
+
if len(shared.lora_names) == 1:
|
496 |
+
default_text = load_prompt(shared.settings['lora_prompts'][next((k for k in shared.settings['lora_prompts'] if re.match(k.lower(), shared.lora_names[0].lower())), 'default')])
|
497 |
+
else:
|
498 |
+
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')])
|
499 |
+
title = 'Text generation web UI'
|
500 |
+
|
501 |
+
# Authentication variables
|
502 |
+
auth = None
|
503 |
+
if shared.args.gradio_auth_path is not None:
|
504 |
+
gradio_auth_creds = []
|
505 |
+
with open(shared.args.gradio_auth_path, 'r', encoding="utf8") as file:
|
506 |
+
for line in file.readlines():
|
507 |
+
gradio_auth_creds += [x.strip() for x in line.split(',') if x.strip()]
|
508 |
+
auth = [tuple(cred.split(':')) for cred in gradio_auth_creds]
|
509 |
+
|
510 |
+
# Importing the extension files and executing their setup() functions
|
511 |
+
if shared.args.extensions is not None and len(shared.args.extensions) > 0:
|
512 |
+
extensions_module.load_extensions()
|
513 |
+
|
514 |
+
with gr.Blocks(css=ui.css if not shared.is_chat() else ui.css + ui.chat_css, analytics_enabled=False, title=title, theme=ui.theme) as shared.gradio['interface']:
|
515 |
+
|
516 |
+
# Create chat mode interface
|
517 |
+
if shared.is_chat():
|
518 |
+
shared.input_elements = ui.list_interface_input_elements(chat=True)
|
519 |
+
shared.gradio['interface_state'] = gr.State({k: None for k in shared.input_elements})
|
520 |
+
shared.gradio['Chat input'] = gr.State()
|
521 |
+
|
522 |
+
with gr.Tab('Text generation', elem_id='main'):
|
523 |
+
shared.gradio['display'] = gr.HTML(value=chat_html_wrapper(shared.history['visible'], shared.settings['name1'], shared.settings['name2'], 'cai-chat'))
|
524 |
+
shared.gradio['textbox'] = gr.Textbox(label='Input')
|
525 |
+
with gr.Row():
|
526 |
+
shared.gradio['Stop'] = gr.Button('Stop', elem_id='stop')
|
527 |
+
shared.gradio['Generate'] = gr.Button('Generate', elem_id='Generate', variant='primary')
|
528 |
+
shared.gradio['Continue'] = gr.Button('Continue')
|
529 |
+
|
530 |
+
with gr.Row():
|
531 |
+
shared.gradio['Copy last reply'] = gr.Button('Copy last reply')
|
532 |
+
shared.gradio['Regenerate'] = gr.Button('Regenerate')
|
533 |
+
shared.gradio['Replace last reply'] = gr.Button('Replace last reply')
|
534 |
+
|
535 |
+
with gr.Row():
|
536 |
+
shared.gradio['Impersonate'] = gr.Button('Impersonate')
|
537 |
+
shared.gradio['Send dummy message'] = gr.Button('Send dummy message')
|
538 |
+
shared.gradio['Send dummy reply'] = gr.Button('Send dummy reply')
|
539 |
+
|
540 |
+
with gr.Row():
|
541 |
+
shared.gradio['Remove last'] = gr.Button('Remove last')
|
542 |
+
shared.gradio['Clear history'] = gr.Button('Clear history')
|
543 |
+
shared.gradio['Clear history-confirm'] = gr.Button('Confirm', variant='stop', visible=False)
|
544 |
+
shared.gradio['Clear history-cancel'] = gr.Button('Cancel', visible=False)
|
545 |
+
|
546 |
+
shared.gradio['mode'] = gr.Radio(choices=['cai-chat', 'chat', 'instruct'], value=shared.settings['mode'], label='Mode')
|
547 |
+
shared.gradio['instruction_template'] = gr.Dropdown(choices=get_available_instruction_templates(), label='Instruction template', value='None', visible=shared.settings['mode'] == 'instruct', info='Change this according to the model/LoRA that you are using.')
|
548 |
+
|
549 |
+
with gr.Tab('Character', elem_id='chat-settings'):
|
550 |
+
with gr.Row():
|
551 |
+
with gr.Column(scale=8):
|
552 |
+
shared.gradio['name1'] = gr.Textbox(value=shared.settings['name1'], lines=1, label='Your name')
|
553 |
+
shared.gradio['name2'] = gr.Textbox(value=shared.settings['name2'], lines=1, label='Character\'s name')
|
554 |
+
shared.gradio['greeting'] = gr.Textbox(value=shared.settings['greeting'], lines=4, label='Greeting')
|
555 |
+
shared.gradio['context'] = gr.Textbox(value=shared.settings['context'], lines=4, label='Context')
|
556 |
+
shared.gradio['turn_template'] = gr.Textbox(value=shared.settings['turn_template'], lines=1, label='Turn template', info='Used to precisely define the placement of spaces and new line characters in instruction prompts.')
|
557 |
+
|
558 |
+
with gr.Column(scale=1):
|
559 |
+
shared.gradio['character_picture'] = gr.Image(label='Character picture', type='pil')
|
560 |
+
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)
|
561 |
+
|
562 |
+
with gr.Row():
|
563 |
+
shared.gradio['character_menu'] = gr.Dropdown(choices=get_available_characters(), label='Character', elem_id='character-menu')
|
564 |
+
ui.create_refresh_button(shared.gradio['character_menu'], lambda: None, lambda: {'choices': get_available_characters()}, 'refresh-button')
|
565 |
+
|
566 |
+
with gr.Row():
|
567 |
+
with gr.Tab('Chat history'):
|
568 |
+
with gr.Row():
|
569 |
+
with gr.Column():
|
570 |
+
gr.Markdown('Upload')
|
571 |
+
shared.gradio['upload_chat_history'] = gr.File(type='binary', file_types=['.json', '.txt'])
|
572 |
+
|
573 |
+
with gr.Column():
|
574 |
+
gr.Markdown('Download')
|
575 |
+
shared.gradio['download'] = gr.File()
|
576 |
+
shared.gradio['download_button'] = gr.Button(value='Click me')
|
577 |
+
|
578 |
+
with gr.Tab('Upload character'):
|
579 |
+
gr.Markdown('# JSON format')
|
580 |
+
with gr.Row():
|
581 |
+
with gr.Column():
|
582 |
+
gr.Markdown('1. Select the JSON file')
|
583 |
+
shared.gradio['upload_json'] = gr.File(type='binary', file_types=['.json'])
|
584 |
+
|
585 |
+
with gr.Column():
|
586 |
+
gr.Markdown('2. Select your character\'s profile picture (optional)')
|
587 |
+
shared.gradio['upload_img_bot'] = gr.File(type='binary', file_types=['image'])
|
588 |
+
|
589 |
+
shared.gradio['Upload character'] = gr.Button(value='Submit')
|
590 |
+
gr.Markdown('# TavernAI PNG format')
|
591 |
+
shared.gradio['upload_img_tavern'] = gr.File(type='binary', file_types=['image'])
|
592 |
+
|
593 |
+
with gr.Tab("Parameters", elem_id="parameters"):
|
594 |
+
with gr.Box():
|
595 |
+
gr.Markdown("Chat parameters")
|
596 |
+
with gr.Row():
|
597 |
+
with gr.Column():
|
598 |
+
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'])
|
599 |
+
shared.gradio['chat_prompt_size'] = 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'])
|
600 |
+
|
601 |
+
with gr.Column():
|
602 |
+
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)')
|
603 |
+
shared.gradio['stop_at_newline'] = gr.Checkbox(value=shared.settings['stop_at_newline'], label='Stop generating at new line character')
|
604 |
+
|
605 |
+
create_settings_menus(default_preset)
|
606 |
+
|
607 |
+
# Create notebook mode interface
|
608 |
+
elif shared.args.notebook:
|
609 |
+
shared.input_elements = ui.list_interface_input_elements(chat=False)
|
610 |
+
shared.gradio['interface_state'] = gr.State({k: None for k in shared.input_elements})
|
611 |
+
shared.gradio['last_input'] = gr.State('')
|
612 |
+
with gr.Tab("Text generation", elem_id="main"):
|
613 |
+
with gr.Row():
|
614 |
+
with gr.Column(scale=4):
|
615 |
+
with gr.Tab('Raw'):
|
616 |
+
shared.gradio['textbox'] = gr.Textbox(value=default_text, elem_classes="textbox", lines=27)
|
617 |
+
|
618 |
+
with gr.Tab('Markdown'):
|
619 |
+
shared.gradio['markdown'] = gr.Markdown()
|
620 |
+
|
621 |
+
with gr.Tab('HTML'):
|
622 |
+
shared.gradio['html'] = gr.HTML()
|
623 |
+
|
624 |
+
with gr.Row():
|
625 |
+
shared.gradio['Generate'] = gr.Button('Generate', variant='primary', elem_classes="small-button")
|
626 |
+
shared.gradio['Stop'] = gr.Button('Stop', elem_classes="small-button")
|
627 |
+
shared.gradio['Undo'] = gr.Button('Undo', elem_classes="small-button")
|
628 |
+
shared.gradio['Regenerate'] = gr.Button('Regenerate', elem_classes="small-button")
|
629 |
+
|
630 |
+
with gr.Column(scale=1):
|
631 |
+
gr.HTML('<div style="padding-bottom: 13px"></div>')
|
632 |
+
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'])
|
633 |
+
with gr.Row():
|
634 |
+
shared.gradio['prompt_menu'] = gr.Dropdown(choices=get_available_prompts(), value='None', label='Prompt')
|
635 |
+
ui.create_refresh_button(shared.gradio['prompt_menu'], lambda: None, lambda: {'choices': get_available_prompts()}, 'refresh-button')
|
636 |
+
|
637 |
+
shared.gradio['save_prompt'] = gr.Button('Save prompt')
|
638 |
+
shared.gradio['count_tokens'] = gr.Button('Count tokens')
|
639 |
+
shared.gradio['status'] = gr.Markdown('')
|
640 |
+
|
641 |
+
with gr.Tab("Parameters", elem_id="parameters"):
|
642 |
+
create_settings_menus(default_preset)
|
643 |
+
|
644 |
+
# Create default mode interface
|
645 |
+
else:
|
646 |
+
shared.input_elements = ui.list_interface_input_elements(chat=False)
|
647 |
+
shared.gradio['interface_state'] = gr.State({k: None for k in shared.input_elements})
|
648 |
+
shared.gradio['last_input'] = gr.State('')
|
649 |
+
with gr.Tab("Text generation", elem_id="main"):
|
650 |
+
with gr.Row():
|
651 |
+
with gr.Column():
|
652 |
+
shared.gradio['textbox'] = gr.Textbox(value=default_text, elem_classes="textbox_default", lines=27, label='Input')
|
653 |
+
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'])
|
654 |
+
with gr.Row():
|
655 |
+
shared.gradio['Generate'] = gr.Button('Generate', variant='primary', elem_classes="small-button")
|
656 |
+
shared.gradio['Stop'] = gr.Button('Stop', elem_classes="small-button")
|
657 |
+
shared.gradio['Continue'] = gr.Button('Continue', elem_classes="small-button")
|
658 |
+
shared.gradio['save_prompt'] = gr.Button('Save prompt', elem_classes="small-button")
|
659 |
+
shared.gradio['count_tokens'] = gr.Button('Count tokens', elem_classes="small-button")
|
660 |
+
|
661 |
+
with gr.Row():
|
662 |
+
with gr.Column():
|
663 |
+
with gr.Row():
|
664 |
+
shared.gradio['prompt_menu'] = gr.Dropdown(choices=get_available_prompts(), value='None', label='Prompt')
|
665 |
+
ui.create_refresh_button(shared.gradio['prompt_menu'], lambda: None, lambda: {'choices': get_available_prompts()}, 'refresh-button')
|
666 |
+
|
667 |
+
with gr.Column():
|
668 |
+
shared.gradio['status'] = gr.Markdown('')
|
669 |
+
|
670 |
+
with gr.Column():
|
671 |
+
with gr.Tab('Raw'):
|
672 |
+
shared.gradio['output_textbox'] = gr.Textbox(elem_classes="textbox_default_output", lines=27, label='Output')
|
673 |
+
|
674 |
+
with gr.Tab('Markdown'):
|
675 |
+
shared.gradio['markdown'] = gr.Markdown()
|
676 |
+
|
677 |
+
with gr.Tab('HTML'):
|
678 |
+
shared.gradio['html'] = gr.HTML()
|
679 |
+
|
680 |
+
with gr.Tab("Parameters", elem_id="parameters"):
|
681 |
+
create_settings_menus(default_preset)
|
682 |
+
|
683 |
+
# Model tab
|
684 |
+
with gr.Tab("Model", elem_id="model-tab"):
|
685 |
+
create_model_menus()
|
686 |
+
|
687 |
+
# Training tab
|
688 |
+
with gr.Tab("Training", elem_id="training-tab"):
|
689 |
+
training.create_train_interface()
|
690 |
+
|
691 |
+
# Interface mode tab
|
692 |
+
with gr.Tab("Interface mode", elem_id="interface-mode"):
|
693 |
+
modes = ["default", "notebook", "chat", "cai_chat"]
|
694 |
+
current_mode = "default"
|
695 |
+
for mode in modes[1:]:
|
696 |
+
if getattr(shared.args, mode):
|
697 |
+
current_mode = mode
|
698 |
+
break
|
699 |
+
cmd_list = vars(shared.args)
|
700 |
+
bool_list = [k for k in cmd_list if type(cmd_list[k]) is bool and k not in modes + ui.list_model_elements()]
|
701 |
+
bool_active = [k for k in bool_list if vars(shared.args)[k]]
|
702 |
+
|
703 |
+
gr.Markdown("*Experimental*")
|
704 |
+
shared.gradio['interface_modes_menu'] = gr.Dropdown(choices=modes, value=current_mode, label="Mode")
|
705 |
+
shared.gradio['extensions_menu'] = gr.CheckboxGroup(choices=get_available_extensions(), value=shared.args.extensions, label="Available extensions")
|
706 |
+
shared.gradio['bool_menu'] = gr.CheckboxGroup(choices=bool_list, value=bool_active, label="Boolean command-line flags")
|
707 |
+
shared.gradio['reset_interface'] = gr.Button("Apply and restart the interface")
|
708 |
+
|
709 |
+
# Reset interface event
|
710 |
+
shared.gradio['reset_interface'].click(
|
711 |
+
set_interface_arguments, [shared.gradio[k] for k in ['interface_modes_menu', 'extensions_menu', 'bool_menu']], None).then(
|
712 |
+
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 []}')
|
713 |
+
|
714 |
+
# chat mode event handlers
|
715 |
+
if shared.is_chat():
|
716 |
+
shared.input_params = [shared.gradio[k] for k in ['Chat input', 'interface_state']]
|
717 |
+
clear_arr = [shared.gradio[k] for k in ['Clear history-confirm', 'Clear history', 'Clear history-cancel']]
|
718 |
+
reload_inputs = [shared.gradio[k] for k in ['name1', 'name2', 'mode']]
|
719 |
+
|
720 |
+
gen_events.append(shared.gradio['Generate'].click(
|
721 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
722 |
+
lambda x: (x, ''), shared.gradio['textbox'], [shared.gradio['Chat input'], shared.gradio['textbox']], show_progress=False).then(
|
723 |
+
chat.cai_chatbot_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream).then(
|
724 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
725 |
+
)
|
726 |
+
|
727 |
+
gen_events.append(shared.gradio['textbox'].submit(
|
728 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
729 |
+
lambda x: (x, ''), shared.gradio['textbox'], [shared.gradio['Chat input'], shared.gradio['textbox']], show_progress=False).then(
|
730 |
+
chat.cai_chatbot_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream).then(
|
731 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
732 |
+
)
|
733 |
+
|
734 |
+
gen_events.append(shared.gradio['Regenerate'].click(
|
735 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
736 |
+
chat.regenerate_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream).then(
|
737 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
738 |
+
)
|
739 |
+
|
740 |
+
gen_events.append(shared.gradio['Continue'].click(
|
741 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
742 |
+
chat.continue_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream).then(
|
743 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
744 |
+
)
|
745 |
+
|
746 |
+
gen_events.append(shared.gradio['Impersonate'].click(
|
747 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
748 |
+
chat.impersonate_wrapper, shared.input_params, shared.gradio['textbox'], show_progress=shared.args.no_stream)
|
749 |
+
)
|
750 |
+
|
751 |
+
shared.gradio['Replace last reply'].click(
|
752 |
+
chat.replace_last_reply, [shared.gradio[k] for k in ['textbox', 'name1', 'name2', 'mode']], shared.gradio['display'], show_progress=shared.args.no_stream).then(
|
753 |
+
lambda x: '', shared.gradio['textbox'], shared.gradio['textbox'], show_progress=False).then(
|
754 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
755 |
+
|
756 |
+
shared.gradio['Send dummy message'].click(
|
757 |
+
chat.send_dummy_message, [shared.gradio[k] for k in ['textbox', 'name1', 'name2', 'mode']], shared.gradio['display'], show_progress=shared.args.no_stream).then(
|
758 |
+
lambda x: '', shared.gradio['textbox'], shared.gradio['textbox'], show_progress=False).then(
|
759 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
760 |
+
|
761 |
+
shared.gradio['Send dummy reply'].click(
|
762 |
+
chat.send_dummy_reply, [shared.gradio[k] for k in ['textbox', 'name1', 'name2', 'mode']], shared.gradio['display'], show_progress=shared.args.no_stream).then(
|
763 |
+
lambda x: '', shared.gradio['textbox'], shared.gradio['textbox'], show_progress=False).then(
|
764 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
765 |
+
|
766 |
+
shared.gradio['Clear history-confirm'].click(
|
767 |
+
lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, clear_arr).then(
|
768 |
+
chat.clear_chat_log, [shared.gradio[k] for k in ['name1', 'name2', 'greeting', 'mode']], shared.gradio['display']).then(
|
769 |
+
chat.save_history, shared.gradio['mode'], None, show_progress=False)
|
770 |
+
|
771 |
+
shared.gradio['Stop'].click(
|
772 |
+
stop_everything_event, None, None, queue=False, cancels=gen_events if shared.args.no_stream else None).then(
|
773 |
+
chat.redraw_html, reload_inputs, shared.gradio['display'])
|
774 |
+
|
775 |
+
shared.gradio['mode'].change(
|
776 |
+
lambda x: gr.update(visible=x == 'instruct'), shared.gradio['mode'], shared.gradio['instruction_template']).then(
|
777 |
+
lambda x: gr.update(interactive=x != 'instruct'), shared.gradio['mode'], shared.gradio['character_menu']).then(
|
778 |
+
chat.redraw_html, reload_inputs, shared.gradio['display'])
|
779 |
+
|
780 |
+
shared.gradio['instruction_template'].change(
|
781 |
+
chat.load_character, [shared.gradio[k] for k in ['instruction_template', 'name1', 'name2', 'mode']], [shared.gradio[k] for k in ['name1', 'name2', 'character_picture', 'greeting', 'context', 'turn_template', 'display']]).then(
|
782 |
+
chat.redraw_html, reload_inputs, shared.gradio['display'])
|
783 |
+
|
784 |
+
shared.gradio['upload_chat_history'].upload(
|
785 |
+
chat.load_history, [shared.gradio[k] for k in ['upload_chat_history', 'name1', 'name2']], None).then(
|
786 |
+
chat.redraw_html, reload_inputs, shared.gradio['display'])
|
787 |
+
|
788 |
+
shared.gradio['Copy last reply'].click(chat.send_last_reply_to_input, None, shared.gradio['textbox'], show_progress=shared.args.no_stream)
|
789 |
+
shared.gradio['Clear history'].click(lambda: [gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)], None, clear_arr)
|
790 |
+
shared.gradio['Clear history-cancel'].click(lambda: [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, clear_arr)
|
791 |
+
shared.gradio['Remove last'].click(chat.remove_last_message, [shared.gradio[k] for k in ['name1', 'name2', 'mode']], [shared.gradio['display'], shared.gradio['textbox']], show_progress=False)
|
792 |
+
shared.gradio['download_button'].click(lambda x: chat.save_history(x, timestamp=True), shared.gradio['mode'], shared.gradio['download'])
|
793 |
+
shared.gradio['Upload character'].click(chat.upload_character, [shared.gradio['upload_json'], shared.gradio['upload_img_bot']], [shared.gradio['character_menu']])
|
794 |
+
shared.gradio['character_menu'].change(chat.load_character, [shared.gradio[k] for k in ['character_menu', 'name1', 'name2', 'mode']], [shared.gradio[k] for k in ['name1', 'name2', 'character_picture', 'greeting', 'context', 'turn_template', 'display']])
|
795 |
+
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']])
|
796 |
+
shared.gradio['your_picture'].change(chat.upload_your_profile_picture, [shared.gradio[k] for k in ['your_picture', 'name1', 'name2', 'mode']], shared.gradio['display'])
|
797 |
+
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js+ui.chat_js}}}")
|
798 |
+
|
799 |
+
# notebook/default modes event handlers
|
800 |
+
else:
|
801 |
+
shared.input_params = [shared.gradio[k] for k in ['textbox', 'interface_state']]
|
802 |
+
if shared.args.notebook:
|
803 |
+
output_params = [shared.gradio[k] for k in ['textbox', 'markdown', 'html']]
|
804 |
+
else:
|
805 |
+
output_params = [shared.gradio[k] for k in ['output_textbox', 'markdown', 'html']]
|
806 |
+
|
807 |
+
gen_events.append(shared.gradio['Generate'].click(
|
808 |
+
lambda x: x, shared.gradio['textbox'], shared.gradio['last_input']).then(
|
809 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
810 |
+
generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream) # .then(
|
811 |
+
# None, None, None, _js="() => {element = document.getElementsByTagName('textarea')[0]; element.scrollTop = element.scrollHeight}")
|
812 |
+
)
|
813 |
+
|
814 |
+
gen_events.append(shared.gradio['textbox'].submit(
|
815 |
+
lambda x: x, shared.gradio['textbox'], shared.gradio['last_input']).then(
|
816 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
817 |
+
generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream) # .then(
|
818 |
+
# None, None, None, _js="() => {element = document.getElementsByTagName('textarea')[0]; element.scrollTop = element.scrollHeight}")
|
819 |
+
)
|
820 |
+
|
821 |
+
if shared.args.notebook:
|
822 |
+
shared.gradio['Undo'].click(lambda x: x, shared.gradio['last_input'], shared.gradio['textbox'], show_progress=False)
|
823 |
+
gen_events.append(shared.gradio['Regenerate'].click(
|
824 |
+
lambda x: x, shared.gradio['last_input'], shared.gradio['textbox'], show_progress=False).then(
|
825 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
826 |
+
generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream) # .then(
|
827 |
+
# None, None, None, _js="() => {element = document.getElementsByTagName('textarea')[0]; element.scrollTop = element.scrollHeight}")
|
828 |
+
)
|
829 |
+
else:
|
830 |
+
gen_events.append(shared.gradio['Continue'].click(
|
831 |
+
ui.gather_interface_values, [shared.gradio[k] for k in shared.input_elements], shared.gradio['interface_state']).then(
|
832 |
+
generate_reply, [shared.gradio['output_textbox']] + shared.input_params[1:], output_params, show_progress=shared.args.no_stream) # .then(
|
833 |
+
# None, None, None, _js="() => {element = document.getElementsByTagName('textarea')[1]; element.scrollTop = element.scrollHeight}")
|
834 |
+
)
|
835 |
+
|
836 |
+
shared.gradio['Stop'].click(stop_everything_event, None, None, queue=False, cancels=gen_events if shared.args.no_stream else None)
|
837 |
+
shared.gradio['prompt_menu'].change(load_prompt, shared.gradio['prompt_menu'], shared.gradio['textbox'], show_progress=False)
|
838 |
+
shared.gradio['save_prompt'].click(save_prompt, shared.gradio['textbox'], shared.gradio['status'], show_progress=False)
|
839 |
+
shared.gradio['count_tokens'].click(count_tokens, shared.gradio['textbox'], shared.gradio['status'], show_progress=False)
|
840 |
+
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js}}}")
|
841 |
+
|
842 |
+
shared.gradio['interface'].load(partial(ui.apply_interface_values, {}, use_persistent=True), None, [shared.gradio[k] for k in ui.list_interface_input_elements(chat=shared.is_chat())], show_progress=False)
|
843 |
+
# Extensions block
|
844 |
+
if shared.args.extensions is not None:
|
845 |
+
extensions_module.create_extensions_block()
|
846 |
+
|
847 |
+
# Launch the interface
|
848 |
+
shared.gradio['interface'].queue()
|
849 |
+
if shared.args.listen:
|
850 |
+
shared.gradio['interface'].launch(prevent_thread_lock=True, share=shared.args.share, server_name=shared.args.listen_host or '0.0.0.0', server_port=shared.args.listen_port, inbrowser=shared.args.auto_launch, auth=auth)
|
851 |
+
else:
|
852 |
+
shared.gradio['interface'].launch(prevent_thread_lock=True, share=shared.args.share, server_port=shared.args.listen_port, inbrowser=shared.args.auto_launch, auth=auth)
|
853 |
+
|
854 |
+
|
855 |
+
if __name__ == "__main__":
|
856 |
+
# Loading custom settings
|
857 |
+
settings_file = None
|
858 |
+
if shared.args.settings is not None and Path(shared.args.settings).exists():
|
859 |
+
settings_file = Path(shared.args.settings)
|
860 |
+
elif Path('settings.json').exists():
|
861 |
+
settings_file = Path('settings.json')
|
862 |
+
if settings_file is not None:
|
863 |
+
print(f"Loading settings from {settings_file}...")
|
864 |
+
new_settings = json.loads(open(settings_file, 'r').read())
|
865 |
+
for item in new_settings:
|
866 |
+
shared.settings[item] = new_settings[item]
|
867 |
+
|
868 |
+
# Default extensions
|
869 |
+
extensions_module.available_extensions = get_available_extensions()
|
870 |
+
if shared.is_chat():
|
871 |
+
for extension in shared.settings['chat_default_extensions']:
|
872 |
+
shared.args.extensions = shared.args.extensions or []
|
873 |
+
if extension not in shared.args.extensions:
|
874 |
+
shared.args.extensions.append(extension)
|
875 |
+
else:
|
876 |
+
for extension in shared.settings['default_extensions']:
|
877 |
+
shared.args.extensions = shared.args.extensions or []
|
878 |
+
if extension not in shared.args.extensions:
|
879 |
+
shared.args.extensions.append(extension)
|
880 |
+
|
881 |
+
available_models = get_available_models()
|
882 |
+
|
883 |
+
# Model defined through --model
|
884 |
+
if shared.args.model is not None:
|
885 |
+
shared.model_name = shared.args.model
|
886 |
+
|
887 |
+
# Only one model is available
|
888 |
+
elif len(available_models) == 1:
|
889 |
+
shared.model_name = available_models[0]
|
890 |
+
|
891 |
+
# Select the model from a command-line menu
|
892 |
+
elif shared.args.model_menu:
|
893 |
+
if len(available_models) == 0:
|
894 |
+
print('No models are available! Please download at least one.')
|
895 |
+
sys.exit(0)
|
896 |
+
else:
|
897 |
+
print('The following models are available:\n')
|
898 |
+
for i, model in enumerate(available_models):
|
899 |
+
print(f'{i+1}. {model}')
|
900 |
+
|
901 |
+
print(f'\nWhich one do you want to load? 1-{len(available_models)}\n')
|
902 |
+
i = int(input()) - 1
|
903 |
+
print()
|
904 |
+
|
905 |
+
shared.model_name = available_models[i]
|
906 |
+
|
907 |
+
# If any model has been selected, load it
|
908 |
+
if shared.model_name != 'None':
|
909 |
+
model_settings = get_model_specific_settings(shared.model_name)
|
910 |
+
shared.settings.update(model_settings) # hijacking the interface defaults
|
911 |
+
update_model_parameters(model_settings, initial=True) # hijacking the command-line arguments
|
912 |
+
|
913 |
+
# Load the model
|
914 |
+
shared.model, shared.tokenizer = load_model(shared.model_name)
|
915 |
+
if shared.args.lora:
|
916 |
+
add_lora_to_model(shared.args.lora)
|
917 |
+
|
918 |
+
# Force a character to be loaded
|
919 |
+
if shared.is_chat():
|
920 |
+
shared.persistent_interface_state.update({
|
921 |
+
'mode': shared.settings['mode'],
|
922 |
+
'character_menu': shared.args.character or shared.settings['character'],
|
923 |
+
'instruction_template': shared.settings['instruction_template']
|
924 |
+
})
|
925 |
+
|
926 |
+
# Launch the web UI
|
927 |
+
create_interface()
|
928 |
+
while True:
|
929 |
+
time.sleep(0.5)
|
930 |
+
if shared.need_restart:
|
931 |
+
shared.need_restart = False
|
932 |
+
shared.gradio['interface'].close()
|
933 |
+
create_interface()
|