Spaces:
Runtime error
Runtime error
Commit
·
daac7d9
1
Parent(s):
498787d
Update app.py
Browse files
app.py
CHANGED
@@ -1,473 +1,12 @@
|
|
1 |
-
import gc
|
2 |
-
import io
|
3 |
-
import json
|
4 |
-
import re
|
5 |
-
import sys
|
6 |
-
import time
|
7 |
-
import zipfile
|
8 |
-
from pathlib import Path
|
9 |
-
|
10 |
import gradio as gr
|
11 |
-
import torch as torch
|
12 |
-
|
13 |
-
import modules.chat as chat
|
14 |
-
import modules.extensions as extensions_module
|
15 |
-
import modules.shared as shared
|
16 |
-
import modules.ui as ui
|
17 |
-
from modules.html_generator import generate_chat_html
|
18 |
-
from modules.LoRA import add_lora_to_model
|
19 |
-
from modules.models import load_model, load_soft_prompt
|
20 |
-
from modules.text_generation import generate_reply
|
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 |
-
def get_available_models():
|
35 |
-
if shared.args.flexgen:
|
36 |
-
return sorted([re.sub('-np$', '', item.name) for item in list(Path('models/').glob('*')) if item.name.endswith('-np')], key=str.lower)
|
37 |
-
else:
|
38 |
-
return sorted([re.sub('.pth$', '', item.name) for item in list(Path('models/').glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=str.lower)
|
39 |
-
|
40 |
-
def get_available_presets():
|
41 |
-
return sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('presets').glob('*.txt'))), key=str.lower)
|
42 |
-
|
43 |
-
def get_available_characters():
|
44 |
-
return ['None'] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('characters').glob('*.json'))), key=str.lower)
|
45 |
-
|
46 |
-
def get_available_extensions():
|
47 |
-
return sorted(set(map(lambda x : x.parts[1], Path('extensions').glob('*/script.py'))), key=str.lower)
|
48 |
-
|
49 |
-
def get_available_softprompts():
|
50 |
-
return ['None'] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('softprompts').glob('*.zip'))), key=str.lower)
|
51 |
-
|
52 |
-
def get_available_loras():
|
53 |
-
return ['None'] + sorted([item.name for item in list(Path('loras/').glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=str.lower)
|
54 |
-
|
55 |
-
def load_model_wrapper(selected_model):
|
56 |
-
if selected_model != shared.model_name:
|
57 |
-
shared.model_name = selected_model
|
58 |
-
shared.model = shared.tokenizer = None
|
59 |
-
if not shared.args.cpu:
|
60 |
-
gc.collect()
|
61 |
-
torch.cuda.empty_cache()
|
62 |
-
shared.model, shared.tokenizer = load_model(shared.model_name)
|
63 |
-
|
64 |
-
return selected_model
|
65 |
-
|
66 |
-
def load_lora_wrapper(selected_lora):
|
67 |
-
shared.lora_name = selected_lora
|
68 |
-
default_text = shared.settings['lora_prompts'][next((k for k in shared.settings['lora_prompts'] if re.match(k.lower(), shared.lora_name.lower())), 'default')]
|
69 |
-
|
70 |
-
if not shared.args.cpu:
|
71 |
-
gc.collect()
|
72 |
-
torch.cuda.empty_cache()
|
73 |
-
add_lora_to_model(selected_lora)
|
74 |
-
|
75 |
-
return selected_lora, default_text
|
76 |
-
|
77 |
-
def load_preset_values(preset_menu, return_dict=False):
|
78 |
-
generate_params = {
|
79 |
-
'do_sample': True,
|
80 |
-
'temperature': 1,
|
81 |
-
'top_p': 1,
|
82 |
-
'typical_p': 1,
|
83 |
-
'repetition_penalty': 1,
|
84 |
-
'encoder_repetition_penalty': 1,
|
85 |
-
'top_k': 50,
|
86 |
-
'num_beams': 1,
|
87 |
-
'penalty_alpha': 0,
|
88 |
-
'min_length': 0,
|
89 |
-
'length_penalty': 1,
|
90 |
-
'no_repeat_ngram_size': 0,
|
91 |
-
'early_stopping': False,
|
92 |
-
}
|
93 |
-
with open(Path(f'presets/{preset_menu}.txt'), 'r') as infile:
|
94 |
-
preset = infile.read()
|
95 |
-
for i in preset.splitlines():
|
96 |
-
i = i.rstrip(',').strip().split('=')
|
97 |
-
if len(i) == 2 and i[0].strip() != 'tokens':
|
98 |
-
generate_params[i[0].strip()] = eval(i[1].strip())
|
99 |
-
|
100 |
-
generate_params['temperature'] = min(1.99, generate_params['temperature'])
|
101 |
-
|
102 |
-
if return_dict:
|
103 |
-
return generate_params
|
104 |
-
else:
|
105 |
-
return preset_menu, generate_params['do_sample'], generate_params['temperature'], generate_params['top_p'], generate_params['typical_p'], generate_params['repetition_penalty'], generate_params['encoder_repetition_penalty'], generate_params['top_k'], generate_params['min_length'], generate_params['no_repeat_ngram_size'], generate_params['num_beams'], generate_params['penalty_alpha'], generate_params['length_penalty'], generate_params['early_stopping']
|
106 |
-
|
107 |
-
def upload_soft_prompt(file):
|
108 |
-
with zipfile.ZipFile(io.BytesIO(file)) as zf:
|
109 |
-
zf.extract('meta.json')
|
110 |
-
j = json.loads(open('meta.json', 'r').read())
|
111 |
-
name = j['name']
|
112 |
-
Path('meta.json').unlink()
|
113 |
-
|
114 |
-
with open(Path(f'softprompts/{name}.zip'), 'wb') as f:
|
115 |
-
f.write(file)
|
116 |
-
|
117 |
-
return name
|
118 |
-
|
119 |
-
def create_model_and_preset_menus():
|
120 |
-
with gr.Row():
|
121 |
-
with gr.Column():
|
122 |
-
with gr.Row():
|
123 |
-
shared.gradio['model_menu'] = gr.Dropdown(choices=available_models, value=shared.model_name, label='Model')
|
124 |
-
ui.create_refresh_button(shared.gradio['model_menu'], lambda : None, lambda : {'choices': get_available_models()}, 'refresh-button')
|
125 |
-
with gr.Column():
|
126 |
-
with gr.Row():
|
127 |
-
shared.gradio['preset_menu'] = gr.Dropdown(choices=available_presets, value=default_preset if not shared.args.flexgen else 'Naive', label='Generation parameters preset')
|
128 |
-
ui.create_refresh_button(shared.gradio['preset_menu'], lambda : None, lambda : {'choices': get_available_presets()}, 'refresh-button')
|
129 |
-
|
130 |
-
def create_settings_menus(default_preset):
|
131 |
-
generate_params = load_preset_values(default_preset if not shared.args.flexgen else 'Naive', return_dict=True)
|
132 |
-
|
133 |
-
with gr.Row():
|
134 |
-
shared.gradio['preset_menu_mirror'] = gr.Dropdown(choices=available_presets, value=default_preset if not shared.args.flexgen else 'Naive', label='Generation parameters preset')
|
135 |
-
ui.create_refresh_button(shared.gradio['preset_menu_mirror'], lambda : None, lambda : {'choices': get_available_presets()}, 'refresh-button')
|
136 |
-
|
137 |
-
with gr.Row():
|
138 |
-
with gr.Column():
|
139 |
-
with gr.Box():
|
140 |
-
gr.Markdown('Custom generation parameters ([reference](https://huggingface.co/docs/transformers/main_classes/text_generation#transformers.GenerationConfig))')
|
141 |
-
with gr.Row():
|
142 |
-
with gr.Column():
|
143 |
-
shared.gradio['temperature'] = gr.Slider(0.01, 1.99, value=generate_params['temperature'], step=0.01, label='temperature')
|
144 |
-
shared.gradio['top_p'] = gr.Slider(0.0,1.0,value=generate_params['top_p'],step=0.01,label='top_p')
|
145 |
-
shared.gradio['top_k'] = gr.Slider(0,200,value=generate_params['top_k'],step=1,label='top_k')
|
146 |
-
shared.gradio['typical_p'] = gr.Slider(0.0,1.0,value=generate_params['typical_p'],step=0.01,label='typical_p')
|
147 |
-
with gr.Column():
|
148 |
-
shared.gradio['repetition_penalty'] = gr.Slider(1.0, 1.5, value=generate_params['repetition_penalty'],step=0.01,label='repetition_penalty')
|
149 |
-
shared.gradio['encoder_repetition_penalty'] = gr.Slider(0.8, 1.5, value=generate_params['encoder_repetition_penalty'],step=0.01,label='encoder_repetition_penalty')
|
150 |
-
shared.gradio['no_repeat_ngram_size'] = gr.Slider(0, 20, step=1, value=generate_params['no_repeat_ngram_size'], label='no_repeat_ngram_size')
|
151 |
-
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)
|
152 |
-
shared.gradio['do_sample'] = gr.Checkbox(value=generate_params['do_sample'], label='do_sample')
|
153 |
-
with gr.Column():
|
154 |
-
with gr.Box():
|
155 |
-
gr.Markdown('Contrastive search')
|
156 |
-
shared.gradio['penalty_alpha'] = gr.Slider(0, 5, value=generate_params['penalty_alpha'], label='penalty_alpha')
|
157 |
-
|
158 |
-
with gr.Box():
|
159 |
-
gr.Markdown('Beam search (uses a lot of VRAM)')
|
160 |
-
with gr.Row():
|
161 |
-
with gr.Column():
|
162 |
-
shared.gradio['num_beams'] = gr.Slider(1, 20, step=1, value=generate_params['num_beams'], label='num_beams')
|
163 |
-
with gr.Column():
|
164 |
-
shared.gradio['length_penalty'] = gr.Slider(-5, 5, value=generate_params['length_penalty'], label='length_penalty')
|
165 |
-
shared.gradio['early_stopping'] = gr.Checkbox(value=generate_params['early_stopping'], label='early_stopping')
|
166 |
-
|
167 |
-
with gr.Row():
|
168 |
-
shared.gradio['lora_menu'] = gr.Dropdown(choices=available_loras, value=shared.lora_name, label='LoRA')
|
169 |
-
ui.create_refresh_button(shared.gradio['lora_menu'], lambda : None, lambda : {'choices': get_available_loras()}, 'refresh-button')
|
170 |
-
|
171 |
-
with gr.Accordion('Soft prompt', open=False):
|
172 |
-
with gr.Row():
|
173 |
-
shared.gradio['softprompts_menu'] = gr.Dropdown(choices=available_softprompts, value='None', label='Soft prompt')
|
174 |
-
ui.create_refresh_button(shared.gradio['softprompts_menu'], lambda : None, lambda : {'choices': get_available_softprompts()}, 'refresh-button')
|
175 |
-
|
176 |
-
gr.Markdown('Upload a soft prompt (.zip format):')
|
177 |
-
with gr.Row():
|
178 |
-
shared.gradio['upload_softprompt'] = gr.File(type='binary', file_types=['.zip'])
|
179 |
-
|
180 |
-
shared.gradio['model_menu'].change(load_model_wrapper, [shared.gradio['model_menu']], [shared.gradio['model_menu']], show_progress=True)
|
181 |
-
shared.gradio['preset_menu'].change(load_preset_values, [shared.gradio['preset_menu']], [shared.gradio[k] for k in ['preset_menu_mirror', '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']])
|
182 |
-
shared.gradio['preset_menu_mirror'].change(load_preset_values, [shared.gradio['preset_menu_mirror']], [shared.gradio[k] for k in ['preset_menu', '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']])
|
183 |
-
shared.gradio['lora_menu'].change(load_lora_wrapper, [shared.gradio['lora_menu']], [shared.gradio['lora_menu'], shared.gradio['textbox']], show_progress=True)
|
184 |
-
shared.gradio['softprompts_menu'].change(load_soft_prompt, [shared.gradio['softprompts_menu']], [shared.gradio['softprompts_menu']], show_progress=True)
|
185 |
-
shared.gradio['upload_softprompt'].upload(upload_soft_prompt, [shared.gradio['upload_softprompt']], [shared.gradio['softprompts_menu']])
|
186 |
-
|
187 |
-
def set_interface_arguments(interface_mode, extensions, cmd_active):
|
188 |
-
modes = ["default", "notebook", "chat", "cai_chat"]
|
189 |
-
cmd_list = vars(shared.args)
|
190 |
-
cmd_list = [k for k in cmd_list if type(cmd_list[k]) is bool and k not in modes]
|
191 |
-
|
192 |
-
shared.args.extensions = extensions
|
193 |
-
for k in modes[1:]:
|
194 |
-
exec(f"shared.args.{k} = False")
|
195 |
-
if interface_mode != "default":
|
196 |
-
exec(f"shared.args.{interface_mode} = True")
|
197 |
-
|
198 |
-
for k in cmd_list:
|
199 |
-
exec(f"shared.args.{k} = False")
|
200 |
-
for k in cmd_active:
|
201 |
-
exec(f"shared.args.{k} = True")
|
202 |
-
|
203 |
-
shared.need_restart = True
|
204 |
-
|
205 |
-
available_models = get_available_models()
|
206 |
-
available_presets = get_available_presets()
|
207 |
-
available_characters = get_available_characters()
|
208 |
-
available_softprompts = get_available_softprompts()
|
209 |
-
available_loras = get_available_loras()
|
210 |
-
|
211 |
-
# Default extensions
|
212 |
-
extensions_module.available_extensions = get_available_extensions()
|
213 |
-
if shared.args.chat or shared.args.cai_chat:
|
214 |
-
for extension in shared.settings['chat_default_extensions']:
|
215 |
-
shared.args.extensions = shared.args.extensions or []
|
216 |
-
if extension not in shared.args.extensions:
|
217 |
-
shared.args.extensions.append(extension)
|
218 |
-
else:
|
219 |
-
for extension in shared.settings['default_extensions']:
|
220 |
-
shared.args.extensions = shared.args.extensions or []
|
221 |
-
if extension not in shared.args.extensions:
|
222 |
-
shared.args.extensions.append(extension)
|
223 |
-
|
224 |
-
# Default model
|
225 |
-
if shared.args.model is not None:
|
226 |
-
shared.model_name = shared.args.model
|
227 |
-
else:
|
228 |
-
if len(available_models) == 0:
|
229 |
-
print('No models are available! Please download at least one.')
|
230 |
-
sys.exit(0)
|
231 |
-
elif len(available_models) == 1:
|
232 |
-
i = 0
|
233 |
-
else:
|
234 |
-
print('The following models are available:\n')
|
235 |
-
for i, model in enumerate(available_models):
|
236 |
-
print(f'{i+1}. {model}')
|
237 |
-
print(f'\nWhich one do you want to load? 1-{len(available_models)}\n')
|
238 |
-
i = int(input())-1
|
239 |
-
print()
|
240 |
-
shared.model_name = available_models[i]
|
241 |
-
shared.model, shared.tokenizer = load_model(shared.model_name)
|
242 |
-
if shared.args.lora:
|
243 |
-
print(shared.args.lora)
|
244 |
-
shared.lora_name = shared.args.lora
|
245 |
-
add_lora_to_model(shared.lora_name)
|
246 |
-
|
247 |
-
# Default UI settings
|
248 |
-
default_preset = shared.settings['presets'][next((k for k in shared.settings['presets'] if re.match(k.lower(), shared.model_name.lower())), 'default')]
|
249 |
-
default_text = shared.settings['lora_prompts'][next((k for k in shared.settings['lora_prompts'] if re.match(k.lower(), shared.lora_name.lower())), 'default')]
|
250 |
-
if default_text == '':
|
251 |
-
default_text = shared.settings['prompts'][next((k for k in shared.settings['prompts'] if re.match(k.lower(), shared.model_name.lower())), 'default')]
|
252 |
-
title ='Text generation web UI'
|
253 |
-
description = '\n\n# Text generation lab\nGenerate text using Large Language Models.\n'
|
254 |
-
suffix = '_pygmalion' if 'pygmalion' in shared.model_name.lower() else ''
|
255 |
-
|
256 |
-
def create_interface():
|
257 |
-
|
258 |
-
gen_events = []
|
259 |
-
if shared.args.extensions is not None and len(shared.args.extensions) > 0:
|
260 |
-
extensions_module.load_extensions()
|
261 |
-
|
262 |
-
with gr.Blocks(css=ui.css if not any((shared.args.chat, shared.args.cai_chat)) else ui.css+ui.chat_css, analytics_enabled=False, title=title) as shared.gradio['interface']:
|
263 |
-
if shared.args.chat or shared.args.cai_chat:
|
264 |
-
with gr.Tab("Text generation", elem_id="main"):
|
265 |
-
if shared.args.cai_chat:
|
266 |
-
shared.gradio['display'] = gr.HTML(value=generate_chat_html(shared.history['visible'], shared.settings[f'name1{suffix}'], shared.settings[f'name2{suffix}'], shared.character))
|
267 |
-
else:
|
268 |
-
shared.gradio['display'] = gr.Chatbot(value=shared.history['visible']).style(color_map=("#326efd", "#212528"))
|
269 |
-
shared.gradio['textbox'] = gr.Textbox(label='Input')
|
270 |
-
with gr.Row():
|
271 |
-
shared.gradio['Stop'] = gr.Button('Stop', elem_id="stop")
|
272 |
-
shared.gradio['Generate'] = gr.Button('Generate')
|
273 |
-
with gr.Row():
|
274 |
-
shared.gradio['Impersonate'] = gr.Button('Impersonate')
|
275 |
-
shared.gradio['Regenerate'] = gr.Button('Regenerate')
|
276 |
-
with gr.Row():
|
277 |
-
shared.gradio['Copy last reply'] = gr.Button('Copy last reply')
|
278 |
-
shared.gradio['Replace last reply'] = gr.Button('Replace last reply')
|
279 |
-
shared.gradio['Remove last'] = gr.Button('Remove last')
|
280 |
-
|
281 |
-
shared.gradio['Clear history'] = gr.Button('Clear history')
|
282 |
-
shared.gradio['Clear history-confirm'] = gr.Button('Confirm', variant="stop", visible=False)
|
283 |
-
shared.gradio['Clear history-cancel'] = gr.Button('Cancel', visible=False)
|
284 |
-
|
285 |
-
create_model_and_preset_menus()
|
286 |
-
|
287 |
-
with gr.Tab("Character", elem_id="chat-settings"):
|
288 |
-
shared.gradio['name1'] = gr.Textbox(value=shared.settings[f'name1{suffix}'], lines=1, label='Your name')
|
289 |
-
shared.gradio['name2'] = gr.Textbox(value=shared.settings[f'name2{suffix}'], lines=1, label='Bot\'s name')
|
290 |
-
shared.gradio['context'] = gr.Textbox(value=shared.settings[f'context{suffix}'], lines=5, label='Context')
|
291 |
-
with gr.Row():
|
292 |
-
shared.gradio['character_menu'] = gr.Dropdown(choices=available_characters, value='None', label='Character', elem_id='character-menu')
|
293 |
-
ui.create_refresh_button(shared.gradio['character_menu'], lambda : None, lambda : {'choices': get_available_characters()}, 'refresh-button')
|
294 |
-
|
295 |
-
with gr.Row():
|
296 |
-
with gr.Tab('Chat history'):
|
297 |
-
with gr.Row():
|
298 |
-
with gr.Column():
|
299 |
-
gr.Markdown('Upload')
|
300 |
-
shared.gradio['upload_chat_history'] = gr.File(type='binary', file_types=['.json', '.txt'])
|
301 |
-
with gr.Column():
|
302 |
-
gr.Markdown('Download')
|
303 |
-
shared.gradio['download'] = gr.File()
|
304 |
-
shared.gradio['download_button'] = gr.Button(value='Click me')
|
305 |
-
with gr.Tab('Upload character'):
|
306 |
-
with gr.Row():
|
307 |
-
with gr.Column():
|
308 |
-
gr.Markdown('1. Select the JSON file')
|
309 |
-
shared.gradio['upload_json'] = gr.File(type='binary', file_types=['.json'])
|
310 |
-
with gr.Column():
|
311 |
-
gr.Markdown('2. Select your character\'s profile picture (optional)')
|
312 |
-
shared.gradio['upload_img_bot'] = gr.File(type='binary', file_types=['image'])
|
313 |
-
shared.gradio['Upload character'] = gr.Button(value='Submit')
|
314 |
-
with gr.Tab('Upload your profile picture'):
|
315 |
-
shared.gradio['upload_img_me'] = gr.File(type='binary', file_types=['image'])
|
316 |
-
with gr.Tab('Upload TavernAI Character Card'):
|
317 |
-
shared.gradio['upload_img_tavern'] = gr.File(type='binary', file_types=['image'])
|
318 |
-
|
319 |
-
with gr.Tab("Parameters", elem_id="parameters"):
|
320 |
-
with gr.Box():
|
321 |
-
gr.Markdown("Chat parameters")
|
322 |
-
with gr.Row():
|
323 |
-
with gr.Column():
|
324 |
-
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'])
|
325 |
-
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'])
|
326 |
-
with gr.Column():
|
327 |
-
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)')
|
328 |
-
shared.gradio['check'] = gr.Checkbox(value=shared.settings[f'stop_at_newline{suffix}'], label='Stop generating at new line character?')
|
329 |
-
|
330 |
-
create_settings_menus(default_preset)
|
331 |
-
|
332 |
-
function_call = 'chat.cai_chatbot_wrapper' if shared.args.cai_chat else 'chat.chatbot_wrapper'
|
333 |
-
shared.input_params = [shared.gradio[k] for k in ['textbox', 'max_new_tokens', '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', 'name1', 'name2', 'context', 'check', 'chat_prompt_size_slider', 'chat_generation_attempts']]
|
334 |
-
|
335 |
-
gen_events.append(shared.gradio['Generate'].click(eval(function_call), shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream))
|
336 |
-
gen_events.append(shared.gradio['textbox'].submit(eval(function_call), shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream))
|
337 |
-
gen_events.append(shared.gradio['Regenerate'].click(chat.regenerate_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream))
|
338 |
-
gen_events.append(shared.gradio['Impersonate'].click(chat.impersonate_wrapper, shared.input_params, shared.gradio['textbox'], show_progress=shared.args.no_stream))
|
339 |
-
shared.gradio['Stop'].click(chat.stop_everything_event, [], [], cancels=gen_events)
|
340 |
-
|
341 |
-
shared.gradio['Copy last reply'].click(chat.send_last_reply_to_input, [], shared.gradio['textbox'], show_progress=shared.args.no_stream)
|
342 |
-
shared.gradio['Replace last reply'].click(chat.replace_last_reply, [shared.gradio['textbox'], shared.gradio['name1'], shared.gradio['name2']], shared.gradio['display'], show_progress=shared.args.no_stream)
|
343 |
-
|
344 |
-
# Clear history with confirmation
|
345 |
-
clear_arr = [shared.gradio[k] for k in ['Clear history-confirm', 'Clear history', 'Clear history-cancel']]
|
346 |
-
shared.gradio['Clear history'].click(lambda :[gr.update(visible=True), gr.update(visible=False), gr.update(visible=True)], None, clear_arr)
|
347 |
-
shared.gradio['Clear history-confirm'].click(lambda :[gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, clear_arr)
|
348 |
-
shared.gradio['Clear history-confirm'].click(chat.clear_chat_log, [shared.gradio['name1'], shared.gradio['name2']], shared.gradio['display'])
|
349 |
-
shared.gradio['Clear history-cancel'].click(lambda :[gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)], None, clear_arr)
|
350 |
-
|
351 |
-
shared.gradio['Remove last'].click(chat.remove_last_message, [shared.gradio['name1'], shared.gradio['name2']], [shared.gradio['display'], shared.gradio['textbox']], show_progress=False)
|
352 |
-
shared.gradio['download_button'].click(chat.save_history, inputs=[], outputs=[shared.gradio['download']])
|
353 |
-
shared.gradio['Upload character'].click(chat.upload_character, [shared.gradio['upload_json'], shared.gradio['upload_img_bot']], [shared.gradio['character_menu']])
|
354 |
-
|
355 |
-
# Clearing stuff and saving the history
|
356 |
-
for i in ['Generate', 'Regenerate', 'Replace last reply']:
|
357 |
-
shared.gradio[i].click(lambda x: '', shared.gradio['textbox'], shared.gradio['textbox'], show_progress=False)
|
358 |
-
shared.gradio[i].click(lambda : chat.save_history(timestamp=False), [], [], show_progress=False)
|
359 |
-
shared.gradio['Clear history-confirm'].click(lambda : chat.save_history(timestamp=False), [], [], show_progress=False)
|
360 |
-
shared.gradio['textbox'].submit(lambda x: '', shared.gradio['textbox'], shared.gradio['textbox'], show_progress=False)
|
361 |
-
shared.gradio['textbox'].submit(lambda : chat.save_history(timestamp=False), [], [], show_progress=False)
|
362 |
-
|
363 |
-
shared.gradio['character_menu'].change(chat.load_character, [shared.gradio['character_menu'], shared.gradio['name1'], shared.gradio['name2']], [shared.gradio['name2'], shared.gradio['context'], shared.gradio['display']])
|
364 |
-
shared.gradio['upload_chat_history'].upload(chat.load_history, [shared.gradio['upload_chat_history'], shared.gradio['name1'], shared.gradio['name2']], [])
|
365 |
-
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']])
|
366 |
-
shared.gradio['upload_img_me'].upload(chat.upload_your_profile_picture, [shared.gradio['upload_img_me']], [])
|
367 |
-
|
368 |
-
reload_func = chat.redraw_html if shared.args.cai_chat else lambda : shared.history['visible']
|
369 |
-
reload_inputs = [shared.gradio['name1'], shared.gradio['name2']] if shared.args.cai_chat else []
|
370 |
-
shared.gradio['upload_chat_history'].upload(reload_func, reload_inputs, [shared.gradio['display']])
|
371 |
-
shared.gradio['upload_img_me'].upload(reload_func, reload_inputs, [shared.gradio['display']])
|
372 |
-
shared.gradio['Stop'].click(reload_func, reload_inputs, [shared.gradio['display']])
|
373 |
-
|
374 |
-
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js+ui.chat_js}}}")
|
375 |
-
shared.gradio['interface'].load(lambda : chat.load_default_history(shared.settings[f'name1{suffix}'], shared.settings[f'name2{suffix}']), None, None)
|
376 |
-
shared.gradio['interface'].load(reload_func, reload_inputs, [shared.gradio['display']], show_progress=True)
|
377 |
-
|
378 |
-
elif shared.args.notebook:
|
379 |
-
with gr.Tab("Text generation", elem_id="main"):
|
380 |
-
with gr.Tab('Raw'):
|
381 |
-
shared.gradio['textbox'] = gr.Textbox(value=default_text, lines=25)
|
382 |
-
with gr.Tab('Markdown'):
|
383 |
-
shared.gradio['markdown'] = gr.Markdown()
|
384 |
-
with gr.Tab('HTML'):
|
385 |
-
shared.gradio['html'] = gr.HTML()
|
386 |
-
|
387 |
-
with gr.Row():
|
388 |
-
shared.gradio['Stop'] = gr.Button('Stop')
|
389 |
-
shared.gradio['Generate'] = gr.Button('Generate')
|
390 |
-
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'])
|
391 |
-
|
392 |
-
create_model_and_preset_menus()
|
393 |
-
with gr.Tab("Parameters", elem_id="parameters"):
|
394 |
-
create_settings_menus(default_preset)
|
395 |
-
|
396 |
-
shared.input_params = [shared.gradio[k] for k in ['textbox', 'max_new_tokens', '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']]
|
397 |
-
output_params = [shared.gradio[k] for k in ['textbox', 'markdown', 'html']]
|
398 |
-
gen_events.append(shared.gradio['Generate'].click(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream, api_name='textgen'))
|
399 |
-
gen_events.append(shared.gradio['textbox'].submit(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream))
|
400 |
-
shared.gradio['Stop'].click(None, None, None, cancels=gen_events)
|
401 |
-
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js}}}")
|
402 |
-
|
403 |
-
else:
|
404 |
-
with gr.Tab("Text generation", elem_id="main"):
|
405 |
-
with gr.Row():
|
406 |
-
with gr.Column():
|
407 |
-
shared.gradio['textbox'] = gr.Textbox(value=default_text, lines=15, label='Input')
|
408 |
-
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'])
|
409 |
-
shared.gradio['Generate'] = gr.Button('Generate')
|
410 |
-
with gr.Row():
|
411 |
-
with gr.Column():
|
412 |
-
shared.gradio['Continue'] = gr.Button('Continue')
|
413 |
-
with gr.Column():
|
414 |
-
shared.gradio['Stop'] = gr.Button('Stop')
|
415 |
-
|
416 |
-
create_model_and_preset_menus()
|
417 |
-
|
418 |
-
with gr.Column():
|
419 |
-
with gr.Tab('Raw'):
|
420 |
-
shared.gradio['output_textbox'] = gr.Textbox(lines=25, label='Output')
|
421 |
-
with gr.Tab('Markdown'):
|
422 |
-
shared.gradio['markdown'] = gr.Markdown()
|
423 |
-
with gr.Tab('HTML'):
|
424 |
-
shared.gradio['html'] = gr.HTML()
|
425 |
-
with gr.Tab("Parameters", elem_id="parameters"):
|
426 |
-
create_settings_menus(default_preset)
|
427 |
-
|
428 |
-
shared.input_params = [shared.gradio[k] for k in ['textbox', 'max_new_tokens', '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']]
|
429 |
-
output_params = [shared.gradio[k] for k in ['output_textbox', 'markdown', 'html']]
|
430 |
-
gen_events.append(shared.gradio['Generate'].click(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream, api_name='textgen'))
|
431 |
-
gen_events.append(shared.gradio['textbox'].submit(generate_reply, shared.input_params, output_params, show_progress=shared.args.no_stream))
|
432 |
-
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))
|
433 |
-
shared.gradio['Stop'].click(None, None, None, cancels=gen_events)
|
434 |
-
shared.gradio['interface'].load(None, None, None, _js=f"() => {{{ui.main_js}}}")
|
435 |
-
|
436 |
-
with gr.Tab("Interface mode", elem_id="interface-mode"):
|
437 |
-
modes = ["default", "notebook", "chat", "cai_chat"]
|
438 |
-
current_mode = "default"
|
439 |
-
for mode in modes[1:]:
|
440 |
-
if eval(f"shared.args.{mode}"):
|
441 |
-
current_mode = mode
|
442 |
-
break
|
443 |
-
cmd_list = vars(shared.args)
|
444 |
-
cmd_list = [k for k in cmd_list if type(cmd_list[k]) is bool and k not in modes]
|
445 |
-
active_cmd_list = [k for k in cmd_list if vars(shared.args)[k]]
|
446 |
-
|
447 |
-
gr.Markdown("*Experimental*")
|
448 |
-
shared.gradio['interface_modes_menu'] = gr.Dropdown(choices=modes, value=current_mode, label="Mode")
|
449 |
-
shared.gradio['extensions_menu'] = gr.CheckboxGroup(choices=get_available_extensions(), value=shared.args.extensions, label="Available extensions")
|
450 |
-
shared.gradio['cmd_arguments_menu'] = gr.CheckboxGroup(choices=cmd_list, value=active_cmd_list, label="Boolean command-line flags")
|
451 |
-
shared.gradio['reset_interface'] = gr.Button("Apply and restart the interface", type="primary")
|
452 |
-
|
453 |
-
shared.gradio['reset_interface'].click(set_interface_arguments, [shared.gradio[k] for k in ['interface_modes_menu', 'extensions_menu', 'cmd_arguments_menu']], None)
|
454 |
-
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)}')
|
455 |
-
|
456 |
-
if shared.args.extensions is not None:
|
457 |
-
extensions_module.create_extensions_block()
|
458 |
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
shared.gradio['interface'].launch(prevent_thread_lock=True, share=shared.args.share, server_name='0.0.0.0', server_port=shared.args.listen_port, inbrowser=shared.args.auto_launch)
|
463 |
-
else:
|
464 |
-
shared.gradio['interface'].launch(prevent_thread_lock=True, share=shared.args.share, server_port=shared.args.listen_port, inbrowser=shared.args.auto_launch)
|
465 |
|
466 |
-
|
|
|
|
|
|
|
467 |
|
468 |
-
|
469 |
-
time.sleep(0.5)
|
470 |
-
if shared.need_restart:
|
471 |
-
shared.need_restart = False
|
472 |
-
shared.gradio['interface'].close()
|
473 |
-
create_interface()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
+
description = "Story generation with GPT-2"
|
4 |
+
title = "Generate your own story"
|
5 |
+
examples = [["Adventurer is approached by a mysterious stranger in the tavern for a new quest."]]
|
|
|
|
|
|
|
6 |
|
7 |
+
interface = gr.Interface.load("huggingface/pranavpsv/gpt2-genre-story-generator",
|
8 |
+
description=description,
|
9 |
+
examples=examples
|
10 |
+
)
|
11 |
|
12 |
+
interface.launch()
|
|
|
|
|
|
|
|
|
|