server.py 31 KB

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