server.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import re
  2. import gc
  3. import time
  4. import glob
  5. import torch
  6. import argparse
  7. import json
  8. from sys import exit
  9. from pathlib import Path
  10. import gradio as gr
  11. import warnings
  12. from tqdm import tqdm
  13. import transformers
  14. from transformers import AutoTokenizer, AutoModelForCausalLM
  15. from modules.html_generator import *
  16. from modules.ui import *
  17. transformers.logging.set_verbosity_error()
  18. parser = argparse.ArgumentParser()
  19. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  20. parser.add_argument('--notebook', action='store_true', help='Launch the web UI in notebook mode, where the output is written to the same text box as the input.')
  21. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode.')
  22. parser.add_argument('--cai-chat', action='store_true', help='Launch the web UI in chat mode with a style similar to Character.AI\'s. If the file profile.png or profile.jpg exists in the same folder as server.py, this image will be used as the bot\'s profile picture.')
  23. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  24. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  25. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  26. parser.add_argument('--disk', action='store_true', help='If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk.')
  27. parser.add_argument('--disk-cache-dir', type=str, help='Directory to save the disk cache to. Defaults to "cache/".')
  28. parser.add_argument('--gpu-memory', type=int, help='Maximum GPU memory in GiB to allocate. This is useful if you get out of memory errors while trying to generate text. Must be an integer number.')
  29. parser.add_argument('--cpu-memory', type=int, help='Maximum CPU memory in GiB to allocate for offloaded weights. Must be an integer number. Defaults to 99.')
  30. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time. This improves the text generation performance.')
  31. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example.')
  32. parser.add_argument('--listen', action='store_true', help='Make the web UI reachable from your local network.')
  33. parser.add_argument('--share', action='store_true', help='Create a public URL. This is useful for running the web UI on Google Colab or similar.')
  34. args = parser.parse_args()
  35. if (args.chat or args.cai_chat) and not args.no_stream:
  36. print("Warning: chat mode currently becomes a lot slower with text streaming on.\nConsider starting the web UI with the --no-stream option.\n")
  37. settings = {
  38. 'max_new_tokens': 200,
  39. 'max_new_tokens_min': 1,
  40. 'max_new_tokens_max': 2000,
  41. 'preset': 'NovelAI-Sphinx Moth',
  42. 'name1': 'Person 1',
  43. 'name2': 'Person 2',
  44. 'context': 'This is a conversation between two people.',
  45. 'prompt': 'Common sense questions and answers\n\nQuestion: \nFactual answer:',
  46. 'prompt_gpt4chan': '-----\n--- 865467536\nInput text\n--- 865467537\n',
  47. 'stop_at_newline': True,
  48. 'history_size': 0,
  49. 'history_size_min': 0,
  50. 'history_size_max': 64,
  51. 'preset_pygmalion': 'Pygmalion',
  52. 'name1_pygmalion': 'You',
  53. 'name2_pygmalion': 'Kawaii',
  54. 'context_pygmalion': "Kawaii's persona: Kawaii is a cheerful person who loves to make others smile. She is an optimist who loves to spread happiness and positivity wherever she goes.\n<START>",
  55. 'stop_at_newline_pygmalion': False,
  56. }
  57. if args.settings is not None and Path(args.settings).exists():
  58. with open(Path(args.settings), 'r') as f:
  59. new_settings = json.load(f)
  60. for item in new_settings:
  61. if item in settings:
  62. settings[item] = new_settings[item]
  63. def load_model(model_name):
  64. print(f"Loading {model_name}...")
  65. t0 = time.time()
  66. # Default settings
  67. if not (args.cpu or args.load_in_8bit or args.auto_devices or args.disk or args.gpu_memory is not None):
  68. if Path(f"torch-dumps/{model_name}.pt").exists():
  69. print("Loading in .pt format...")
  70. model = torch.load(Path(f"torch-dumps/{model_name}.pt"))
  71. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')) and any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  72. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  73. else:
  74. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.float16).cuda()
  75. # Custom
  76. else:
  77. settings = ["low_cpu_mem_usage=True"]
  78. command = "AutoModelForCausalLM.from_pretrained"
  79. if args.cpu:
  80. settings.append("torch_dtype=torch.float32")
  81. else:
  82. settings.append("device_map='auto'")
  83. if args.gpu_memory is not None:
  84. if args.cpu_memory is not None:
  85. settings.append(f"max_memory={{0: '{args.gpu_memory}GiB', 'cpu': '{args.cpu_memory}GiB'}}")
  86. else:
  87. settings.append(f"max_memory={{0: '{args.gpu_memory}GiB', 'cpu': '99GiB'}}")
  88. if args.disk:
  89. if args.disk_cache_dir is not None:
  90. settings.append(f"offload_folder='{args.disk_cache_dir}'")
  91. else:
  92. settings.append("offload_folder='cache'")
  93. if args.load_in_8bit:
  94. settings.append("load_in_8bit=True")
  95. else:
  96. settings.append("torch_dtype=torch.float16")
  97. settings = ', '.join(set(settings))
  98. command = f"{command}(Path(f'models/{model_name}'), {settings})"
  99. model = eval(command)
  100. # Loading the tokenizer
  101. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  102. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  103. else:
  104. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  105. tokenizer.truncation_side = 'left'
  106. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  107. return model, tokenizer
  108. # Removes empty replies from gpt4chan outputs
  109. def fix_gpt4chan(s):
  110. for i in range(10):
  111. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  112. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  113. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  114. return s
  115. # Fix the LaTeX equations in galactica
  116. def fix_galactica(s):
  117. s = s.replace(r'\[', r'$')
  118. s = s.replace(r'\]', r'$')
  119. s = s.replace(r'\(', r'$')
  120. s = s.replace(r'\)', r'$')
  121. s = s.replace(r'$$', r'$')
  122. return s
  123. def encode(prompt, tokens):
  124. if not args.cpu:
  125. torch.cuda.empty_cache()
  126. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens).cuda()
  127. else:
  128. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens)
  129. return input_ids
  130. def decode(output_ids):
  131. reply = tokenizer.decode(output_ids, skip_special_tokens=True)
  132. reply = reply.replace(r'<|endoftext|>', '')
  133. return reply
  134. def formatted_outputs(reply, model_name):
  135. if not (args.chat or args.cai_chat):
  136. if model_name.lower().startswith('galactica'):
  137. reply = fix_galactica(reply)
  138. return reply, reply, generate_basic_html(reply)
  139. elif model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  140. reply = fix_gpt4chan(reply)
  141. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  142. else:
  143. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  144. else:
  145. return reply
  146. def generate_reply(question, tokens, inference_settings, selected_model, eos_token=None):
  147. global model, tokenizer, model_name, loaded_preset, preset
  148. if selected_model != model_name:
  149. model_name = selected_model
  150. model = tokenizer = None
  151. if not args.cpu:
  152. gc.collect()
  153. torch.cuda.empty_cache()
  154. model, tokenizer = load_model(model_name)
  155. if inference_settings != loaded_preset:
  156. with open(Path(f'presets/{inference_settings}.txt'), 'r') as infile:
  157. preset = infile.read()
  158. loaded_preset = inference_settings
  159. cuda = "" if args.cpu else ".cuda()"
  160. n = None if eos_token is None else tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  161. input_ids = encode(question, tokens)
  162. # Generate the entire reply at once
  163. if args.no_stream:
  164. t0 = time.time()
  165. output = eval(f"model.generate(input_ids, eos_token_id={n}, {preset}){cuda}")
  166. reply = decode(output[0])
  167. t1 = time.time()
  168. print(f"Output generated in {(t1-t0):.2f} seconds ({(len(output[0])-len(input_ids[0]))/(t1-t0):.2f} it/s)")
  169. yield formatted_outputs(reply, model_name)
  170. # Generate the reply 1 token at a time
  171. else:
  172. yield formatted_outputs(question, model_name)
  173. preset = preset.replace('max_new_tokens=tokens', 'max_new_tokens=1')
  174. for i in tqdm(range(tokens)):
  175. output = eval(f"model.generate(input_ids, {preset}){cuda}")
  176. reply = decode(output[0])
  177. if eos_token is not None and reply[-1] == eos_token:
  178. break
  179. yield formatted_outputs(reply, model_name)
  180. input_ids = output
  181. def get_available_models():
  182. return sorted(set([item.replace('.pt', '') for item in map(lambda x : str(x.name), list(Path('models/').glob('*'))+list(Path('torch-dumps/').glob('*'))) if not item.endswith('.txt')]), key=str.lower)
  183. def get_available_presets():
  184. return sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('presets').glob('*.txt'))), key=str.lower)
  185. def get_available_characters():
  186. return ["None"] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('characters').glob('*.json'))), key=str.lower)
  187. available_models = get_available_models()
  188. available_presets = get_available_presets()
  189. available_characters = get_available_characters()
  190. # Choosing the default model
  191. if args.model is not None:
  192. model_name = args.model
  193. else:
  194. if len(available_models) == 0:
  195. print("No models are available! Please download at least one.")
  196. exit(0)
  197. elif len(available_models) == 1:
  198. i = 0
  199. else:
  200. print("The following models are available:\n")
  201. for i,model in enumerate(available_models):
  202. print(f"{i+1}. {model}")
  203. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  204. i = int(input())-1
  205. print()
  206. model_name = available_models[i]
  207. model, tokenizer = load_model(model_name)
  208. loaded_preset = None
  209. # UI settings
  210. default_text = settings['prompt_gpt4chan'] if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) else settings['prompt']
  211. description = f"\n\n# Text generation lab\nGenerate text using Large Language Models.\n"
  212. css = ".my-4 {margin-top: 0} .py-6 {padding-top: 2.5rem} #refresh-button {flex: none; margin: 0; padding: 0; min-width: 50px; border: none; box-shadow: none; border-radius: 0} #download-label, #upload-label {min-height: 0}"
  213. if args.chat or args.cai_chat:
  214. history = []
  215. character = None
  216. # This gets the new line characters right.
  217. def clean_chat_message(text):
  218. text = text.replace('\n', '\n\n')
  219. text = re.sub(r"\n{3,}", "\n\n", text)
  220. text = text.strip()
  221. return text
  222. def generate_chat_prompt(text, tokens, name1, name2, context, history_size):
  223. text = clean_chat_message(text)
  224. rows = [f"{context.strip()}\n"]
  225. i = len(history)-1
  226. count = 0
  227. while i >= 0 and len(encode(''.join(rows), tokens)[0]) < 2048-tokens:
  228. rows.insert(1, f"{name2}: {history[i][1].strip()}\n")
  229. count += 1
  230. if not (history[i][0] == '<|BEGIN-VISIBLE-CHAT|>'):
  231. rows.insert(1, f"{name1}: {history[i][0].strip()}\n")
  232. count += 1
  233. i -= 1
  234. if history_size != 0 and count >= history_size:
  235. break
  236. rows.append(f"{name1}: {text}\n")
  237. rows.append(f"{name2}:")
  238. while len(rows) > 3 and len(encode(''.join(rows), tokens)[0]) >= 2048-tokens:
  239. rows.pop(1)
  240. rows.pop(1)
  241. question = ''.join(rows)
  242. return question
  243. def remove_example_dialogue_from_history(history):
  244. _history = copy.deepcopy(history)
  245. for i in range(len(_history)):
  246. if '<|BEGIN-VISIBLE-CHAT|>' in _history[i][0]:
  247. _history[i][0] = _history[i][0].replace('<|BEGIN-VISIBLE-CHAT|>', '')
  248. _history = _history[i:]
  249. break
  250. return _history
  251. def chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  252. question = generate_chat_prompt(text, tokens, name1, name2, context, history_size)
  253. history.append(['', ''])
  254. eos_token = '\n' if check else None
  255. for reply in generate_reply(question, tokens, inference_settings, selected_model, eos_token=eos_token):
  256. next_character_found = False
  257. previous_idx = [m.start() for m in re.finditer(f"(^|\n){name2}:", question)]
  258. idx = [m.start() for m in re.finditer(f"(^|\n){name2}:", reply)]
  259. idx = idx[len(previous_idx)-1]
  260. reply = reply[idx + len(f"\n{name2}:"):]
  261. if check:
  262. reply = reply.split('\n')[0].strip()
  263. else:
  264. idx = reply.find(f"\n{name1}:")
  265. if idx != -1:
  266. reply = reply[:idx]
  267. next_character_found = True
  268. reply = clean_chat_message(reply)
  269. history[-1] = [text, reply]
  270. if next_character_found:
  271. break
  272. # Prevent the chat log from flashing if something like "\nYo" is generated just
  273. # before "\nYou:" is completed
  274. tmp = f"\n{name1}:"
  275. next_character_substring_found = False
  276. for j in range(1, len(tmp)):
  277. if reply[-j:] == tmp[:j]:
  278. next_character_substring_found = True
  279. if not next_character_substring_found:
  280. yield remove_example_dialogue_from_history(history)
  281. yield remove_example_dialogue_from_history(history)
  282. def cai_chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  283. for history in chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  284. yield generate_chat_html(history, name1, name2, character)
  285. def regenerate_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  286. last = history.pop()
  287. text = last[0]
  288. if args.cai_chat:
  289. for i in cai_chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  290. yield i
  291. else:
  292. for i in chatbot_wrapper(text, tokens, inference_settings, selected_model, name1, name2, context, check, history_size):
  293. yield i
  294. def remove_last_message(name1, name2):
  295. last = history.pop()
  296. _history = remove_example_dialogue_from_history(history)
  297. if args.cai_chat:
  298. return generate_chat_html(_history, name1, name2, character), last[0]
  299. else:
  300. return _history, last[0]
  301. def clear():
  302. global history
  303. history = []
  304. def clear_html():
  305. return generate_chat_html([], "", "", character)
  306. def redraw_html(name1, name2):
  307. global history
  308. _history = remove_example_dialogue_from_history(history)
  309. return generate_chat_html(_history, name1, name2, character)
  310. def save_history():
  311. if not Path('logs').exists():
  312. Path('logs').mkdir()
  313. with open(Path('logs/conversation.json'), 'w') as f:
  314. f.write(json.dumps({'data': history}, indent=2))
  315. return Path('logs/conversation.json')
  316. def load_history(file):
  317. global history
  318. history = json.loads(file.decode('utf-8'))['data']
  319. def tokenize_example_dialogue(dialogue, name1, name2):
  320. dialogue = re.sub('<START>', '', dialogue)
  321. dialogue = re.sub('(\n|^)[Aa]non:', '\\1You:', dialogue)
  322. idx = [m.start() for m in re.finditer(f"(^|\n)({name1}|{name2}):", dialogue)]
  323. messages = []
  324. for i in range(len(idx)-1):
  325. messages.append(dialogue[idx[i]:idx[i+1]].strip())
  326. history = []
  327. entry = ['', '']
  328. for i in messages:
  329. if i.startswith(f'{name1}:'):
  330. entry[0] = i[len(f'{name1}:'):].strip()
  331. elif i.startswith(f'{name2}:'):
  332. entry[1] = i[len(f'{name2}:'):].strip()
  333. if not (len(entry[0]) == 0 and len(entry[1]) == 0):
  334. history.append(entry)
  335. entry = ['', '']
  336. return history
  337. def load_character(_character, name1, name2):
  338. global history, character
  339. context = ""
  340. history = []
  341. if _character != 'None':
  342. character = _character
  343. with open(Path(f'characters/{_character}.json'), 'r') as f:
  344. data = json.loads(f.read())
  345. name2 = data['char_name']
  346. if 'char_persona' in data and data['char_persona'] != '':
  347. context += f"{data['char_name']}'s Persona: {data['char_persona']}\n"
  348. if 'world_scenario' in data and data['world_scenario'] != '':
  349. context += f"Scenario: {data['world_scenario']}\n"
  350. context = f"{context.strip()}\n<START>\n"
  351. if 'example_dialogue' in data and data['example_dialogue'] != '':
  352. history = tokenize_example_dialogue(data['example_dialogue'], name1, name2)
  353. if 'char_greeting' in data and len(data['char_greeting'].strip()) > 0:
  354. history += [['<|BEGIN-VISIBLE-CHAT|>', data['char_greeting']]]
  355. else:
  356. history += [['<|BEGIN-VISIBLE-CHAT|>', "Hello there!"]]
  357. else:
  358. character = None
  359. context = settings['context_pygmalion']
  360. name2 = settings['name2_pygmalion']
  361. _history = remove_example_dialogue_from_history(history)
  362. if args.cai_chat:
  363. return name2, context, generate_chat_html(_history, name1, name2, character)
  364. else:
  365. return name2, context, _history
  366. suffix = '_pygmalion' if 'pygmalion' in model_name.lower() else ''
  367. with gr.Blocks(css=css+".h-\[40vh\] {height: 66.67vh} .gradio-container {max-width: 800px; margin-left: auto; margin-right: auto}", analytics_enabled=False) as interface:
  368. if args.cai_chat:
  369. display1 = gr.HTML(value=generate_chat_html([], "", "", character))
  370. else:
  371. display1 = gr.Chatbot()
  372. textbox = gr.Textbox(lines=2, label='Input')
  373. btn = gr.Button("Generate")
  374. with gr.Row():
  375. stop = gr.Button("Stop")
  376. btn_regenerate = gr.Button("Regenerate")
  377. btn_remove_last = gr.Button("Remove last")
  378. btn_clear = gr.Button("Clear history")
  379. with gr.Row():
  380. with gr.Column():
  381. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  382. with gr.Row():
  383. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  384. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  385. with gr.Column():
  386. history_size_slider = gr.Slider(minimum=settings['history_size_min'], maximum=settings['history_size_max'], step=1, label='Chat history size in prompt (0 for no limit)', value=settings['history_size'])
  387. with gr.Row():
  388. preset_menu = gr.Dropdown(choices=available_presets, value=settings[f'preset{suffix}'], label='Settings preset')
  389. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  390. name1 = gr.Textbox(value=settings[f'name1{suffix}'], lines=1, label='Your name')
  391. name2 = gr.Textbox(value=settings[f'name2{suffix}'], lines=1, label='Bot\'s name')
  392. context = gr.Textbox(value=settings[f'context{suffix}'], lines=2, label='Context')
  393. with gr.Row():
  394. character_menu = gr.Dropdown(choices=available_characters, value="None", label='Character')
  395. create_refresh_button(character_menu, lambda : None, lambda : {"choices": get_available_characters()}, "refresh-button")
  396. with gr.Row():
  397. check = gr.Checkbox(value=settings[f'stop_at_newline{suffix}'], label='Stop generating at new line character?')
  398. with gr.Row():
  399. with gr.Tab('Download chat history'):
  400. download = gr.File()
  401. save_btn = gr.Button(value="Click me")
  402. with gr.Tab('Upload chat history'):
  403. upload = gr.File(type='binary')
  404. input_params = [textbox, length_slider, preset_menu, model_menu, name1, name2, context, check, history_size_slider]
  405. if args.cai_chat:
  406. gen_event = btn.click(cai_chatbot_wrapper, input_params, display1, show_progress=args.no_stream, api_name="textgen")
  407. gen_event2 = textbox.submit(cai_chatbot_wrapper, input_params, display1, show_progress=args.no_stream)
  408. btn_clear.click(clear_html, [], display1, show_progress=False)
  409. else:
  410. gen_event = btn.click(chatbot_wrapper, input_params, display1, show_progress=args.no_stream, api_name="textgen")
  411. gen_event2 = textbox.submit(chatbot_wrapper, input_params, display1, show_progress=args.no_stream)
  412. btn_clear.click(lambda x: "", display1, display1, show_progress=False)
  413. gen_event3 = btn_regenerate.click(regenerate_wrapper, input_params, display1, show_progress=args.no_stream)
  414. btn_clear.click(clear)
  415. btn_remove_last.click(remove_last_message, [name1, name2], [display1, textbox], show_progress=False)
  416. btn.click(lambda x: "", textbox, textbox, show_progress=False)
  417. btn_regenerate.click(lambda x: "", textbox, textbox, show_progress=False)
  418. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  419. stop.click(None, None, None, cancels=[gen_event, gen_event2, gen_event3])
  420. save_btn.click(save_history, inputs=[], outputs=[download])
  421. upload.upload(load_history, [upload], [])
  422. character_menu.change(load_character, [character_menu, name1, name2], [name2, context, display1])
  423. if args.cai_chat:
  424. upload.upload(redraw_html, [name1, name2], [display1])
  425. else:
  426. upload.upload(lambda : remove_example_dialogue_from_history(history), [], [display1])
  427. elif args.notebook:
  428. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  429. gr.Markdown(description)
  430. with gr.Tab('Raw'):
  431. textbox = gr.Textbox(value=default_text, lines=23)
  432. with gr.Tab('Markdown'):
  433. markdown = gr.Markdown()
  434. with gr.Tab('HTML'):
  435. html = gr.HTML()
  436. btn = gr.Button("Generate")
  437. stop = gr.Button("Stop")
  438. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  439. with gr.Row():
  440. with gr.Column():
  441. with gr.Row():
  442. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  443. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  444. with gr.Column():
  445. with gr.Row():
  446. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Settings preset')
  447. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  448. gen_event = btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream, api_name="textgen")
  449. gen_event2 = textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [textbox, markdown, html], show_progress=args.no_stream)
  450. stop.click(None, None, None, cancels=[gen_event, gen_event2])
  451. else:
  452. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  453. gr.Markdown(description)
  454. with gr.Row():
  455. with gr.Column():
  456. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  457. length_slider = gr.Slider(minimum=settings['max_new_tokens_min'], maximum=settings['max_new_tokens_max'], step=1, label='max_new_tokens', value=settings['max_new_tokens'])
  458. with gr.Row():
  459. preset_menu = gr.Dropdown(choices=available_presets, value=settings['preset'], label='Settings preset')
  460. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  461. with gr.Row():
  462. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  463. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  464. btn = gr.Button("Generate")
  465. with gr.Row():
  466. with gr.Column():
  467. cont = gr.Button("Continue")
  468. with gr.Column():
  469. stop = gr.Button("Stop")
  470. with gr.Column():
  471. with gr.Tab('Raw'):
  472. output_textbox = gr.Textbox(lines=15, label='Output')
  473. with gr.Tab('Markdown'):
  474. markdown = gr.Markdown()
  475. with gr.Tab('HTML'):
  476. html = gr.HTML()
  477. gen_event = btn.click(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream, api_name="textgen")
  478. gen_event2 = textbox.submit(generate_reply, [textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream)
  479. cont_event = cont.click(generate_reply, [output_textbox, length_slider, preset_menu, model_menu], [output_textbox, markdown, html], show_progress=args.no_stream)
  480. stop.click(None, None, None, cancels=[gen_event, gen_event2, cont_event])
  481. interface.queue()
  482. if args.listen:
  483. interface.launch(share=args.share, server_name="0.0.0.0")
  484. else:
  485. interface.launch(share=args.share)