server.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. import argparse
  2. import base64
  3. import copy
  4. import gc
  5. import glob
  6. import io
  7. import json
  8. import os
  9. import re
  10. import sys
  11. import time
  12. import warnings
  13. from datetime import datetime
  14. from pathlib import Path
  15. import gradio as gr
  16. import torch
  17. import transformers
  18. from PIL import Image
  19. from tqdm import tqdm
  20. from transformers import AutoConfig
  21. from transformers import AutoModelForCausalLM
  22. from transformers import AutoTokenizer
  23. from modules.html_generator import *
  24. from modules.stopping_criteria import _SentinelTokenStoppingCriteria
  25. from modules.ui import *
  26. transformers.logging.set_verbosity_error()
  27. parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=54))
  28. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  29. 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.')
  30. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode.')
  31. 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 img_bot.png or img_bot.jpg exists in the same folder as server.py, this image will be used as the bot\'s profile picture. Similarly, img_me.png or img_me.jpg will be used as your profile picture.')
  32. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  33. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  34. parser.add_argument('--bf16', action='store_true', help='Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU.')
  35. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  36. 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.')
  37. parser.add_argument('--disk-cache-dir', type=str, help='Directory to save the disk cache to. Defaults to "cache/".')
  38. 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.')
  39. 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.')
  40. parser.add_argument('--deepspeed', action='store_true', help='Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.')
  41. parser.add_argument('--nvme-offload-dir', type=str, help='DeepSpeed: Directory to use for ZeRO-3 NVME offloading.')
  42. parser.add_argument('--local_rank', type=int, default=0, help='DeepSpeed: Optional argument for distributed setups.')
  43. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time. This improves the text generation performance.')
  44. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example.')
  45. parser.add_argument('--extensions', type=str, help='The list of extensions to load. If you want to load more than one extension, write the names separated by commas and between quotation marks, "like,this".')
  46. parser.add_argument('--listen', action='store_true', help='Make the web UI reachable from your local network.')
  47. parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
  48. 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.')
  49. parser.add_argument('--verbose', action='store_true', help='Print the prompts to the terminal.')
  50. args = parser.parse_args()
  51. if (args.chat or args.cai_chat) and not args.no_stream:
  52. print("Warning: chat mode currently becomes somewhat slower with text streaming on.\nConsider starting the web UI with the --no-stream option.\n")
  53. settings = {
  54. 'max_new_tokens': 200,
  55. 'max_new_tokens_min': 1,
  56. 'max_new_tokens_max': 2000,
  57. 'preset': 'NovelAI-Sphinx Moth',
  58. 'name1': 'Person 1',
  59. 'name2': 'Person 2',
  60. 'context': 'This is a conversation between two people.',
  61. 'prompt': 'Common sense questions and answers\n\nQuestion: \nFactual answer:',
  62. 'prompt_gpt4chan': '-----\n--- 865467536\nInput text\n--- 865467537\n',
  63. 'stop_at_newline': True,
  64. 'history_size': 0,
  65. 'history_size_min': 0,
  66. 'history_size_max': 64,
  67. 'preset_pygmalion': 'Pygmalion',
  68. 'name1_pygmalion': 'You',
  69. 'name2_pygmalion': 'Kawaii',
  70. '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>",
  71. 'stop_at_newline_pygmalion': False,
  72. }
  73. if args.settings is not None and Path(args.settings).exists():
  74. new_settings = json.loads(open(Path(args.settings), 'r').read())
  75. for item in new_settings:
  76. settings[item] = new_settings[item]
  77. if args.deepspeed:
  78. import deepspeed
  79. from transformers.deepspeed import HfDeepSpeedConfig, is_deepspeed_zero3_enabled
  80. from modules.deepspeed_parameters import generate_ds_config
  81. # Distributed setup
  82. local_rank = args.local_rank if args.local_rank is not None else int(os.getenv("LOCAL_RANK", "0"))
  83. world_size = int(os.getenv("WORLD_SIZE", "1"))
  84. torch.cuda.set_device(local_rank)
  85. deepspeed.init_distributed()
  86. ds_config = generate_ds_config(args.bf16, 1 * world_size, args.nvme_offload_dir)
  87. dschf = HfDeepSpeedConfig(ds_config) # Keep this object alive for the Transformers integration
  88. def load_model(model_name):
  89. print(f"Loading {model_name}...")
  90. t0 = time.time()
  91. # Default settings
  92. if not (args.cpu or args.load_in_8bit or args.auto_devices or args.disk or args.gpu_memory is not None or args.cpu_memory is not None or args.deepspeed):
  93. if Path(f"torch-dumps/{model_name}.pt").exists():
  94. print("Loading in .pt format...")
  95. model = torch.load(Path(f"torch-dumps/{model_name}.pt"))
  96. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')) and any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  97. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  98. else:
  99. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.bfloat16 if args.bf16 else torch.float16).cuda()
  100. # DeepSpeed ZeRO-3
  101. elif args.deepspeed:
  102. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), torch_dtype=torch.bfloat16 if args.bf16 else torch.float16)
  103. model = deepspeed.initialize(model=model, config_params=ds_config, model_parameters=None, optimizer=None, lr_scheduler=None)[0]
  104. model.module.eval() # Inference
  105. print(f"DeepSpeed ZeRO-3 is enabled: {is_deepspeed_zero3_enabled()}")
  106. # Custom
  107. else:
  108. command = "AutoModelForCausalLM.from_pretrained"
  109. params = ["low_cpu_mem_usage=True"]
  110. if args.cpu:
  111. params.append("low_cpu_mem_usage=True")
  112. params.append("torch_dtype=torch.float32")
  113. else:
  114. params.append("device_map='auto'")
  115. params.append("load_in_8bit=True" if args.load_in_8bit else "torch_dtype=torch.bfloat16" if args.bf16 else "torch_dtype=torch.float16")
  116. if args.gpu_memory:
  117. params.append(f"max_memory={{0: '{args.gpu_memory or '99'}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  118. elif not args.load_in_8bit:
  119. total_mem = (torch.cuda.get_device_properties(0).total_memory/(1024*1024))
  120. suggestion = round((total_mem-1000)/1000)*1000
  121. if total_mem-suggestion < 800:
  122. suggestion -= 1000
  123. suggestion = int(round(suggestion/1000))
  124. print(f"\033[1;32;1mAuto-assiging --gpu-memory {suggestion} for your GPU to try to prevent out-of-memory errors.\nYou can manually set other values.\033[0;37;0m")
  125. params.append(f"max_memory={{0: '{suggestion}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  126. if args.disk:
  127. params.append(f"offload_folder='{args.disk_cache_dir or 'cache'}'")
  128. command = f"{command}(Path(f'models/{model_name}'), {','.join(set(params))})"
  129. model = eval(command)
  130. # Loading the tokenizer
  131. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  132. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  133. else:
  134. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  135. tokenizer.truncation_side = 'left'
  136. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  137. return model, tokenizer
  138. def load_model_wrapper(selected_model):
  139. global model_name, model, tokenizer
  140. if selected_model != model_name:
  141. model_name = selected_model
  142. model = tokenizer = None
  143. if not args.cpu:
  144. gc.collect()
  145. torch.cuda.empty_cache()
  146. model, tokenizer = load_model(model_name)
  147. def load_preset_values(preset_menu, return_dict=False):
  148. generate_params = {
  149. 'do_sample': True,
  150. 'temperature': 1,
  151. 'top_p': 1,
  152. 'typical_p': 1,
  153. 'repetition_penalty': 1,
  154. 'top_k': 50,
  155. 'num_beams': 1,
  156. 'min_length': 0,
  157. 'length_penalty': 1,
  158. 'no_repeat_ngram_size': 0,
  159. 'early_stopping': False,
  160. }
  161. with open(Path(f'presets/{preset_menu}.txt'), 'r') as infile:
  162. preset = infile.read()
  163. for i in preset.split(','):
  164. i = i.strip().split('=')
  165. if len(i) == 2 and i[0].strip() != 'tokens':
  166. generate_params[i[0].strip()] = eval(i[1].strip())
  167. generate_params['temperature'] = min(1.99, generate_params['temperature'])
  168. if return_dict:
  169. return generate_params
  170. else:
  171. return generate_params['do_sample'], generate_params['temperature'], generate_params['top_p'], generate_params['typical_p'], generate_params['repetition_penalty'], generate_params['top_k'], generate_params['min_length'], generate_params['no_repeat_ngram_size'], generate_params['num_beams'], generate_params['length_penalty'], generate_params['early_stopping']
  172. # Removes empty replies from gpt4chan outputs
  173. def fix_gpt4chan(s):
  174. for i in range(10):
  175. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  176. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  177. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  178. return s
  179. # Fix the LaTeX equations in galactica
  180. def fix_galactica(s):
  181. s = s.replace(r'\[', r'$')
  182. s = s.replace(r'\]', r'$')
  183. s = s.replace(r'\(', r'$')
  184. s = s.replace(r'\)', r'$')
  185. s = s.replace(r'$$', r'$')
  186. return s
  187. def encode(prompt, tokens_to_generate=0, add_special_tokens=True):
  188. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=2048-tokens_to_generate, add_special_tokens=add_special_tokens)
  189. if args.cpu:
  190. return input_ids
  191. elif args.deepspeed:
  192. return input_ids.to(device=local_rank)
  193. else:
  194. return input_ids.cuda()
  195. def decode(output_ids):
  196. reply = tokenizer.decode(output_ids, skip_special_tokens=True)
  197. reply = reply.replace(r'<|endoftext|>', '')
  198. return reply
  199. def formatted_outputs(reply, model_name):
  200. if not (args.chat or args.cai_chat):
  201. if model_name.lower().startswith('galactica'):
  202. reply = fix_galactica(reply)
  203. return reply, reply, generate_basic_html(reply)
  204. elif model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  205. reply = fix_gpt4chan(reply)
  206. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  207. else:
  208. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  209. else:
  210. return reply
  211. def generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, eos_token=None, stopping_string=None):
  212. global model_name, model, tokenizer
  213. original_question = question
  214. if not (args.chat or args.cai_chat):
  215. question = apply_extensions(question, "input")
  216. if args.verbose:
  217. print(f"\n\n{question}\n--------------------\n")
  218. input_ids = encode(question, tokens)
  219. cuda = "" if (args.cpu or args.deepspeed) else ".cuda()"
  220. n = tokenizer.eos_token_id if eos_token is None else tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  221. if stopping_string is not None:
  222. # The stopping_criteria code below was copied from
  223. # https://github.com/PygmalionAI/gradio-ui/blob/master/src/model.py
  224. t = encode(stopping_string, 0, add_special_tokens=False)
  225. stopping_criteria_list = transformers.StoppingCriteriaList([
  226. _SentinelTokenStoppingCriteria(
  227. sentinel_token_ids=t,
  228. starting_idx=len(input_ids[0])
  229. )
  230. ])
  231. else:
  232. stopping_criteria_list = None
  233. generate_params = [
  234. f"eos_token_id={n}",
  235. f"stopping_criteria=stopping_criteria_list",
  236. f"do_sample={do_sample}",
  237. f"temperature={temperature}",
  238. f"top_p={top_p}",
  239. f"typical_p={typical_p}",
  240. f"repetition_penalty={repetition_penalty}",
  241. f"top_k={top_k}",
  242. f"min_length={min_length if args.no_stream else 0}",
  243. f"no_repeat_ngram_size={no_repeat_ngram_size}",
  244. f"num_beams={num_beams}",
  245. f"length_penalty={length_penalty}",
  246. f"early_stopping={early_stopping}",
  247. ]
  248. if args.deepspeed:
  249. generate_params.append("synced_gpus=True")
  250. if args.no_stream:
  251. generate_params.append(f"max_new_tokens=tokens")
  252. else:
  253. generate_params.append(f"max_new_tokens=8")
  254. # Generate the entire reply at once
  255. if args.no_stream:
  256. t0 = time.time()
  257. with torch.no_grad():
  258. output = eval(f"model.generate(input_ids, {','.join(generate_params)}){cuda}")
  259. reply = decode(output[0])
  260. t1 = time.time()
  261. print(f"Output generated in {(t1-t0):.2f} seconds ({(len(output[0])-len(input_ids[0]))/(t1-t0)/8:.2f} it/s, {len(output[0])-len(input_ids[0])} tokens)")
  262. if not (args.chat or args.cai_chat):
  263. reply = original_question + apply_extensions(reply[len(question):], "output")
  264. yield formatted_outputs(reply, model_name)
  265. # Generate the reply 1 token at a time
  266. else:
  267. yield formatted_outputs(original_question, model_name)
  268. for i in tqdm(range(tokens//8+1)):
  269. with torch.no_grad():
  270. output = eval(f"model.generate(input_ids, {','.join(generate_params)}){cuda}")
  271. reply = decode(output[0])
  272. if not (args.chat or args.cai_chat):
  273. reply = original_question + apply_extensions(reply[len(question):], "output")
  274. yield formatted_outputs(reply, model_name)
  275. input_ids = output
  276. if output[0][-1] == n:
  277. break
  278. def apply_extensions(text, typ):
  279. global available_extensions, extension_state
  280. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  281. if extension_state[ext][0] == True:
  282. ext_string = f"extensions.{ext}.script"
  283. if typ == "input" and hasattr(eval(ext_string), "input_modifier"):
  284. text = eval(f"{ext_string}.input_modifier(text)")
  285. elif typ == "output" and hasattr(eval(ext_string), "output_modifier"):
  286. text = eval(f"{ext_string}.output_modifier(text)")
  287. elif typ == "bot_prefix" and hasattr(eval(ext_string), "bot_prefix_modifier"):
  288. text = eval(f"{ext_string}.bot_prefix_modifier(text)")
  289. return text
  290. def update_extensions_parameters(*kwargs):
  291. i = 0
  292. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  293. if extension_state[ext][0] == True:
  294. params = eval(f"extensions.{ext}.script.params")
  295. for param in params:
  296. if len(kwargs) >= i+1:
  297. params[param] = eval(f"kwargs[{i}]")
  298. i += 1
  299. def get_available_models():
  300. 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)
  301. def get_available_presets():
  302. return sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('presets').glob('*.txt'))), key=str.lower)
  303. def get_available_characters():
  304. return ["None"] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('characters').glob('*.json'))), key=str.lower)
  305. def get_available_extensions():
  306. return sorted(set(map(lambda x : x.parts[1], Path('extensions').glob('*/script.py'))), key=str.lower)
  307. def create_extensions_block():
  308. extensions_ui_elements = []
  309. default_values = []
  310. gr.Markdown('## Extensions parameters')
  311. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  312. if extension_state[ext][0] == True:
  313. params = eval(f"extensions.{ext}.script.params")
  314. for param in params:
  315. _id = f"{ext}-{param}"
  316. default_value = settings[_id] if _id in settings else params[param]
  317. default_values.append(default_value)
  318. if type(params[param]) == str:
  319. extensions_ui_elements.append(gr.Textbox(value=default_value, label=f"{ext}-{param}"))
  320. elif type(params[param]) in [int, float]:
  321. extensions_ui_elements.append(gr.Number(value=default_value, label=f"{ext}-{param}"))
  322. elif type(params[param]) == bool:
  323. extensions_ui_elements.append(gr.Checkbox(value=default_value, label=f"{ext}-{param}"))
  324. update_extensions_parameters(*default_values)
  325. btn_extensions = gr.Button("Apply")
  326. btn_extensions.click(update_extensions_parameters, [*extensions_ui_elements], [])
  327. def create_settings_menus():
  328. generate_params = load_preset_values(settings[f'preset{suffix}'], return_dict=True)
  329. with gr.Row():
  330. with gr.Column():
  331. with gr.Row():
  332. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  333. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  334. with gr.Column():
  335. with gr.Row():
  336. preset_menu = gr.Dropdown(choices=available_presets, value=settings[f'preset{suffix}'], label='Generation parameters preset')
  337. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  338. with gr.Accordion("Custom generation parameters", open=False):
  339. with gr.Row():
  340. with gr.Column():
  341. do_sample = gr.Checkbox(value=generate_params['do_sample'], label="do_sample")
  342. temperature = gr.Slider(0.01, 1.99, value=generate_params['temperature'], step=0.01, label="temperature")
  343. top_p = gr.Slider(0.0,1.0,value=generate_params['top_p'],step=0.01,label="top_p")
  344. typical_p = gr.Slider(0.0,1.0,value=generate_params['typical_p'],step=0.01,label="typical_p")
  345. with gr.Column():
  346. repetition_penalty = gr.Slider(1.0,4.99,value=generate_params['repetition_penalty'],step=0.01,label="repetition_penalty")
  347. top_k = gr.Slider(0,200,value=generate_params['top_k'],step=1,label="top_k")
  348. no_repeat_ngram_size = gr.Slider(0, 20, step=1, value=generate_params["no_repeat_ngram_size"], label="no_repeat_ngram_size")
  349. gr.Markdown("Special parameters (only use them if you really need them):")
  350. with gr.Row():
  351. with gr.Column():
  352. num_beams = gr.Slider(0, 20, step=1, value=generate_params["num_beams"], label="num_beams")
  353. length_penalty = gr.Slider(-5, 5, value=generate_params["length_penalty"], label="length_penalty")
  354. with gr.Column():
  355. min_length = gr.Slider(0, 2000, step=1, value=generate_params["min_length"] if args.no_stream else 0, label="min_length", interactive=args.no_stream)
  356. early_stopping = gr.Checkbox(value=generate_params["early_stopping"], label="early_stopping")
  357. model_menu.change(load_model_wrapper, [model_menu], [])
  358. preset_menu.change(load_preset_values, [preset_menu], [do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping])
  359. return preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping
  360. # This gets the new line characters right.
  361. def clean_chat_message(text):
  362. text = text.replace('\n', '\n\n')
  363. text = re.sub(r"\n{3,}", "\n\n", text)
  364. text = text.strip()
  365. return text
  366. def generate_chat_prompt(text, tokens, name1, name2, context, history_size, impersonate=False):
  367. text = clean_chat_message(text)
  368. rows = [f"{context.strip()}\n"]
  369. i = len(history['internal'])-1
  370. count = 0
  371. while i >= 0 and len(encode(''.join(rows), tokens)[0]) < 2048-tokens:
  372. rows.insert(1, f"{name2}: {history['internal'][i][1].strip()}\n")
  373. count += 1
  374. if not (history['internal'][i][0] == '<|BEGIN-VISIBLE-CHAT|>'):
  375. rows.insert(1, f"{name1}: {history['internal'][i][0].strip()}\n")
  376. count += 1
  377. i -= 1
  378. if history_size != 0 and count >= history_size:
  379. break
  380. if not impersonate:
  381. rows.append(f"{name1}: {text}\n")
  382. rows.append(apply_extensions(f"{name2}:", "bot_prefix"))
  383. limit = 3
  384. else:
  385. rows.append(f"{name1}:")
  386. limit = 2
  387. while len(rows) > limit and len(encode(''.join(rows), tokens)[0]) >= 2048-tokens:
  388. rows.pop(1)
  389. rows.pop(1)
  390. question = ''.join(rows)
  391. return question
  392. def extract_message_from_reply(question, reply, current, other, check, extensions=False):
  393. next_character_found = False
  394. substring_found = False
  395. previous_idx = [m.start() for m in re.finditer(f"(^|\n){current}:", question)]
  396. idx = [m.start() for m in re.finditer(f"(^|\n){current}:", reply)]
  397. idx = idx[len(previous_idx)-1]
  398. if extensions:
  399. reply = reply[idx + 1 + len(apply_extensions(f"{current}:", "bot_prefix")):]
  400. else:
  401. reply = reply[idx + 1 + len(f"{current}:"):]
  402. if check:
  403. reply = reply.split('\n')[0].strip()
  404. else:
  405. idx = reply.find(f"\n{other}:")
  406. if idx != -1:
  407. reply = reply[:idx]
  408. next_character_found = True
  409. reply = clean_chat_message(reply)
  410. # Detect if something like "\nYo" is generated just before
  411. # "\nYou:" is completed
  412. tmp = f"\n{other}:"
  413. for j in range(1, len(tmp)):
  414. if reply[-j:] == tmp[:j]:
  415. substring_found = True
  416. return reply, next_character_found, substring_found
  417. def chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size):
  418. original_text = text
  419. text = apply_extensions(text, "input")
  420. question = generate_chat_prompt(text, tokens, name1, name2, context, history_size)
  421. history['internal'].append(['', ''])
  422. history['visible'].append(['', ''])
  423. eos_token = '\n' if check else None
  424. for reply in generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name1}:"):
  425. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name2, name1, check, extensions=True)
  426. history['internal'][-1] = [text, reply]
  427. history['visible'][-1] = [original_text, apply_extensions(reply, "output")]
  428. if not substring_found:
  429. yield history['visible']
  430. if next_character_found:
  431. break
  432. yield history['visible']
  433. def impersonate_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size):
  434. question = generate_chat_prompt(text, tokens, name1, name2, context, history_size, impersonate=True)
  435. eos_token = '\n' if check else None
  436. for reply in generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name2}:"):
  437. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name1, name2, check, extensions=False)
  438. if not substring_found:
  439. yield apply_extensions(reply, "output")
  440. if next_character_found:
  441. break
  442. yield apply_extensions(reply, "output")
  443. def cai_chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size):
  444. for _history in chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size):
  445. yield generate_chat_html(_history, name1, name2, character)
  446. def regenerate_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size):
  447. last = history['visible'].pop()
  448. history['internal'].pop()
  449. text = last[0]
  450. if args.cai_chat:
  451. for i in cai_chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size):
  452. yield i
  453. else:
  454. for i in chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size):
  455. yield i
  456. def remove_last_message(name1, name2):
  457. if not history['internal'][-1][0] == '<|BEGIN-VISIBLE-CHAT|>':
  458. last = history['visible'].pop()
  459. history['internal'].pop()
  460. else:
  461. last = ['', '']
  462. if args.cai_chat:
  463. return generate_chat_html(history['visible'], name1, name2, character), last[0]
  464. else:
  465. return history['visible'], last[0]
  466. def send_last_reply_to_input():
  467. if len(history['visible']) > 0:
  468. return history['visible'][-1][1]
  469. else:
  470. return ''
  471. def replace_last_reply(text, name1, name2):
  472. if len(history['visible']) > 0:
  473. history['visible'][-1][1] = text
  474. history['internal'][-1][1] = apply_extensions(text, "input")
  475. if args.cai_chat:
  476. return generate_chat_html(history['visible'], name1, name2, character)
  477. else:
  478. return history['visible']
  479. def clear_html():
  480. return generate_chat_html([], "", "", character)
  481. def clear_chat_log(_character, name1, name2):
  482. global history
  483. if _character != 'None':
  484. for i in range(len(history['internal'])):
  485. if '<|BEGIN-VISIBLE-CHAT|>' in history['internal'][i][0]:
  486. history['visible'] = [['', history['internal'][i][1]]]
  487. history['internal'] = history['internal'][:i+1]
  488. break
  489. else:
  490. history['internal'] = []
  491. history['visible'] = []
  492. if args.cai_chat:
  493. return generate_chat_html(history['visible'], name1, name2, character)
  494. else:
  495. return history['visible']
  496. def redraw_html(name1, name2):
  497. global history
  498. return generate_chat_html(history['visible'], name1, name2, character)
  499. def tokenize_dialogue(dialogue, name1, name2):
  500. _history = []
  501. dialogue = re.sub('<START>', '', dialogue)
  502. dialogue = re.sub('<start>', '', dialogue)
  503. dialogue = re.sub('(\n|^)[Aa]non:', '\\1You:', dialogue)
  504. dialogue = re.sub('(\n|^)\[CHARACTER\]:', f'\\g<1>{name2}:', dialogue)
  505. idx = [m.start() for m in re.finditer(f"(^|\n)({name1}|{name2}):", dialogue)]
  506. if len(idx) == 0:
  507. return _history
  508. messages = []
  509. for i in range(len(idx)-1):
  510. messages.append(dialogue[idx[i]:idx[i+1]].strip())
  511. messages.append(dialogue[idx[-1]:].strip())
  512. entry = ['', '']
  513. for i in messages:
  514. if i.startswith(f'{name1}:'):
  515. entry[0] = i[len(f'{name1}:'):].strip()
  516. elif i.startswith(f'{name2}:'):
  517. entry[1] = i[len(f'{name2}:'):].strip()
  518. if not (len(entry[0]) == 0 and len(entry[1]) == 0):
  519. _history.append(entry)
  520. entry = ['', '']
  521. print(f"\033[1;32;1m\nDialogue tokenized to:\033[0;37;0m\n", end='')
  522. for row in _history:
  523. for column in row:
  524. print("\n")
  525. for line in column.strip().split('\n'):
  526. print("| "+line+"\n")
  527. print("|\n")
  528. print("------------------------------")
  529. return _history
  530. def save_history():
  531. fname = f"{character or ''}{'_' if character else ''}{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
  532. if not Path('logs').exists():
  533. Path('logs').mkdir()
  534. with open(Path(f'logs/{fname}'), 'w') as f:
  535. f.write(json.dumps({'data': history['internal'], 'data_visible': history['visible']}))
  536. return Path(f'logs/{fname}')
  537. def load_history(file, name1, name2):
  538. global history
  539. file = file.decode('utf-8')
  540. try:
  541. j = json.loads(file)
  542. if 'data' in j:
  543. history['internal'] = j['data']
  544. if 'data_visible' in j:
  545. history['visible'] = j['data_visible']
  546. else:
  547. history['visible'] = copy.deepcopy(history['internal'])
  548. # Compatibility with Pygmalion AI's official web UI
  549. elif 'chat' in j:
  550. history['internal'] = [':'.join(x.split(':')[1:]).strip() for x in j['chat']]
  551. if len(j['chat']) > 0 and j['chat'][0].startswith(f'{name2}:'):
  552. history['internal'] = [['<|BEGIN-VISIBLE-CHAT|>', history['internal'][0]]] + [[history['internal'][i], history['internal'][i+1]] for i in range(1, len(history['internal'])-1, 2)]
  553. history['visible'] = copy.deepcopy(history['internal'])
  554. history['visible'][0][0] = ''
  555. else:
  556. history['internal'] = [[history['internal'][i], history['internal'][i+1]] for i in range(0, len(history['internal'])-1, 2)]
  557. history['visible'] = copy.deepcopy(history['internal'])
  558. except:
  559. history['internal'] = tokenize_dialogue(file, name1, name2)
  560. history['visible'] = copy.deepcopy(history['internal'])
  561. def load_character(_character, name1, name2):
  562. global history, character
  563. context = ""
  564. history['internal'] = []
  565. history['visible'] = []
  566. if _character != 'None':
  567. character = _character
  568. data = json.loads(open(Path(f'characters/{_character}.json'), 'r').read())
  569. name2 = data['char_name']
  570. if 'char_persona' in data and data['char_persona'] != '':
  571. context += f"{data['char_name']}'s Persona: {data['char_persona']}\n"
  572. if 'world_scenario' in data and data['world_scenario'] != '':
  573. context += f"Scenario: {data['world_scenario']}\n"
  574. context = f"{context.strip()}\n<START>\n"
  575. if 'example_dialogue' in data and data['example_dialogue'] != '':
  576. history['internal'] = tokenize_dialogue(data['example_dialogue'], name1, name2)
  577. if 'char_greeting' in data and len(data['char_greeting'].strip()) > 0:
  578. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', data['char_greeting']]]
  579. history['visible'] += [['', apply_extensions(data['char_greeting'], "output")]]
  580. else:
  581. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', "Hello there!"]]
  582. history['visible'] += [['', "Hello there!"]]
  583. else:
  584. character = None
  585. context = settings['context_pygmalion']
  586. name2 = settings['name2_pygmalion']
  587. if args.cai_chat:
  588. return name2, context, generate_chat_html(history['visible'], name1, name2, character)
  589. else:
  590. return name2, context, history['visible']
  591. def upload_character(json_file, img, tavern=False):
  592. json_file = json_file if type(json_file) == str else json_file.decode('utf-8')
  593. data = json.loads(json_file)
  594. outfile_name = data["char_name"]
  595. i = 1
  596. while Path(f'characters/{outfile_name}.json').exists():
  597. outfile_name = f'{data["char_name"]}_{i:03d}'
  598. i += 1
  599. if tavern:
  600. outfile_name = f'TavernAI-{outfile_name}'
  601. with open(Path(f'characters/{outfile_name}.json'), 'w') as f:
  602. f.write(json_file)
  603. if img is not None:
  604. img = Image.open(io.BytesIO(img))
  605. img.save(Path(f'characters/{outfile_name}.png'))
  606. print(f'New character saved to "characters/{outfile_name}.json".')
  607. return outfile_name
  608. def upload_tavern_character(img, name1, name2):
  609. _img = Image.open(io.BytesIO(img))
  610. _img.getexif()
  611. decoded_string = base64.b64decode(_img.info['chara'])
  612. _json = json.loads(decoded_string)
  613. _json = {"char_name": _json['name'], "char_persona": _json['description'], "char_greeting": _json["first_mes"], "example_dialogue": _json['mes_example'], "world_scenario": _json['scenario']}
  614. _json['example_dialogue'] = _json['example_dialogue'].replace('{{user}}', name1).replace('{{char}}', _json['char_name'])
  615. return upload_character(json.dumps(_json), img, tavern=True)
  616. def upload_your_profile_picture(img):
  617. img = Image.open(io.BytesIO(img))
  618. img.save(Path(f'img_me.png'))
  619. print(f'Profile picture saved to "img_me.png"')
  620. # Global variables
  621. available_models = get_available_models()
  622. available_presets = get_available_presets()
  623. available_characters = get_available_characters()
  624. available_extensions = get_available_extensions()
  625. extension_state = {}
  626. if args.extensions is not None:
  627. for i,ext in enumerate(args.extensions.split(',')):
  628. if ext in available_extensions:
  629. print(f'Loading the extension "{ext}"... ', end='')
  630. ext_string = f"extensions.{ext}.script"
  631. exec(f"import {ext_string}")
  632. extension_state[ext] = [True, i]
  633. print(f'Ok.')
  634. # Choosing the default model
  635. if args.model is not None:
  636. model_name = args.model
  637. else:
  638. if len(available_models) == 0:
  639. print("No models are available! Please download at least one.")
  640. sys.exit(0)
  641. elif len(available_models) == 1:
  642. i = 0
  643. else:
  644. print("The following models are available:\n")
  645. for i,model in enumerate(available_models):
  646. print(f"{i+1}. {model}")
  647. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  648. i = int(input())-1
  649. print()
  650. model_name = available_models[i]
  651. model, tokenizer = load_model(model_name)
  652. loaded_preset = None
  653. # UI settings
  654. default_text = settings['prompt_gpt4chan'] if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) else settings['prompt']
  655. description = f"\n\n# Text generation lab\nGenerate text using Large Language Models.\n"
  656. 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}"
  657. suffix = '_pygmalion' if 'pygmalion' in model_name.lower() else ''
  658. buttons = {}
  659. gen_events = []
  660. history = {'internal': [], 'visible': []}
  661. character = None
  662. if args.chat or args.cai_chat:
  663. with gr.Blocks(css=css+".h-\[40vh\] {height: 66.67vh} .gradio-container {max-width: 800px; margin-left: auto; margin-right: auto} .w-screen {width: unset}", analytics_enabled=False) as interface:
  664. if args.cai_chat:
  665. display = gr.HTML(value=generate_chat_html([], "", "", character))
  666. else:
  667. display = gr.Chatbot()
  668. textbox = gr.Textbox(label='Input')
  669. with gr.Row():
  670. buttons["Stop"] = gr.Button("Stop")
  671. buttons["Generate"] = gr.Button("Generate")
  672. buttons["Regenerate"] = gr.Button("Regenerate")
  673. with gr.Row():
  674. buttons["Impersonate"] = gr.Button("Impersonate")
  675. buttons["Remove last"] = gr.Button("Remove last")
  676. buttons["Clear"] = gr.Button("Clear history")
  677. with gr.Row():
  678. buttons["Send last reply to input"] = gr.Button("Send last reply to input")
  679. buttons["Replace last reply"] = gr.Button("Replace last reply")
  680. with gr.Row():
  681. with gr.Column():
  682. max_new_tokens = 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'])
  683. with gr.Column():
  684. 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'])
  685. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping = create_settings_menus()
  686. name1 = gr.Textbox(value=settings[f'name1{suffix}'], lines=1, label='Your name')
  687. name2 = gr.Textbox(value=settings[f'name2{suffix}'], lines=1, label='Bot\'s name')
  688. context = gr.Textbox(value=settings[f'context{suffix}'], lines=2, label='Context')
  689. with gr.Row():
  690. character_menu = gr.Dropdown(choices=available_characters, value="None", label='Character')
  691. create_refresh_button(character_menu, lambda : None, lambda : {"choices": get_available_characters()}, "refresh-button")
  692. with gr.Row():
  693. check = gr.Checkbox(value=settings[f'stop_at_newline{suffix}'], label='Stop generating at new line character?')
  694. with gr.Row():
  695. with gr.Tab('Chat history'):
  696. with gr.Row():
  697. with gr.Column():
  698. gr.Markdown('Upload')
  699. upload = gr.File(type='binary')
  700. with gr.Column():
  701. gr.Markdown('Download')
  702. download = gr.File()
  703. buttons["Download"] = gr.Button(value="Click me")
  704. with gr.Tab('Upload character'):
  705. with gr.Row():
  706. with gr.Column():
  707. gr.Markdown('1. Select the JSON file')
  708. upload_char = gr.File(type='binary')
  709. with gr.Column():
  710. gr.Markdown('2. Select your character\'s profile picture (optional)')
  711. upload_img = gr.File(type='binary')
  712. buttons["Upload character"] = gr.Button(value="Submit")
  713. with gr.Tab('Upload your profile picture'):
  714. upload_img_me = gr.File(type='binary')
  715. with gr.Tab('Upload TavernAI Character Card'):
  716. upload_img_tavern = gr.File(type='binary')
  717. if args.extensions is not None:
  718. create_extensions_block()
  719. input_params = [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping, name1, name2, context, check, history_size_slider]
  720. if args.cai_chat:
  721. gen_events.append(buttons["Generate"].click(cai_chatbot_wrapper, input_params, display, show_progress=args.no_stream, api_name="textgen"))
  722. gen_events.append(textbox.submit(cai_chatbot_wrapper, input_params, display, show_progress=args.no_stream))
  723. else:
  724. gen_events.append(buttons["Generate"].click(chatbot_wrapper, input_params, display, show_progress=args.no_stream, api_name="textgen"))
  725. gen_events.append(textbox.submit(chatbot_wrapper, input_params, display, show_progress=args.no_stream))
  726. gen_events.append(buttons["Regenerate"].click(regenerate_wrapper, input_params, display, show_progress=args.no_stream))
  727. gen_events.append(buttons["Impersonate"].click(impersonate_wrapper, input_params, textbox, show_progress=args.no_stream))
  728. buttons["Send last reply to input"].click(send_last_reply_to_input, [], textbox, show_progress=args.no_stream)
  729. buttons["Replace last reply"].click(replace_last_reply, [textbox, name1, name2], display, show_progress=args.no_stream)
  730. buttons["Clear"].click(clear_chat_log, [character_menu, name1, name2], display)
  731. buttons["Remove last"].click(remove_last_message, [name1, name2], [display, textbox], show_progress=False)
  732. buttons["Stop"].click(None, None, None, cancels=gen_events)
  733. buttons["Download"].click(save_history, inputs=[], outputs=[download])
  734. buttons["Upload character"].click(upload_character, [upload_char, upload_img], [character_menu])
  735. for i in ["Generate", "Regenerate", "Replace last reply"]:
  736. buttons[i].click(lambda x: "", textbox, textbox, show_progress=False)
  737. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  738. character_menu.change(load_character, [character_menu, name1, name2], [name2, context, display])
  739. upload_img_tavern.upload(upload_tavern_character, [upload_img_tavern, name1, name2], [character_menu])
  740. upload.upload(load_history, [upload, name1, name2], [])
  741. upload_img_me.upload(upload_your_profile_picture, [upload_img_me], [])
  742. if args.cai_chat:
  743. upload.upload(redraw_html, [name1, name2], [display])
  744. upload_img_me.upload(redraw_html, [name1, name2], [display])
  745. else:
  746. upload.upload(lambda : history['visible'], [], [display])
  747. upload_img_me.upload(lambda : history['visible'], [], [display])
  748. elif args.notebook:
  749. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  750. gr.Markdown(description)
  751. with gr.Tab('Raw'):
  752. textbox = gr.Textbox(value=default_text, lines=23)
  753. with gr.Tab('Markdown'):
  754. markdown = gr.Markdown()
  755. with gr.Tab('HTML'):
  756. html = gr.HTML()
  757. buttons["Generate"] = gr.Button("Generate")
  758. buttons["Stop"] = gr.Button("Stop")
  759. max_new_tokens = 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'])
  760. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping = create_settings_menus()
  761. if args.extensions is not None:
  762. create_extensions_block()
  763. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping], [textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  764. gen_events.append(textbox.submit(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping], [textbox, markdown, html], show_progress=args.no_stream))
  765. buttons["Stop"].click(None, None, None, cancels=gen_events)
  766. else:
  767. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  768. gr.Markdown(description)
  769. with gr.Row():
  770. with gr.Column():
  771. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  772. max_new_tokens = 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'])
  773. buttons["Generate"] = gr.Button("Generate")
  774. with gr.Row():
  775. with gr.Column():
  776. buttons["Continue"] = gr.Button("Continue")
  777. with gr.Column():
  778. buttons["Stop"] = gr.Button("Stop")
  779. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping = create_settings_menus()
  780. if args.extensions is not None:
  781. create_extensions_block()
  782. with gr.Column():
  783. with gr.Tab('Raw'):
  784. output_textbox = gr.Textbox(lines=15, label='Output')
  785. with gr.Tab('Markdown'):
  786. markdown = gr.Markdown()
  787. with gr.Tab('HTML'):
  788. html = gr.HTML()
  789. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  790. gen_events.append(textbox.submit(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream))
  791. gen_events.append(buttons["Continue"].click(generate_reply, [output_textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream))
  792. buttons["Stop"].click(None, None, None, cancels=gen_events)
  793. interface.queue()
  794. if args.listen:
  795. interface.launch(prevent_thread_lock=True, share=args.share, server_name="0.0.0.0", server_port=args.listen_port)
  796. else:
  797. interface.launch(prevent_thread_lock=True, share=args.share, server_port=args.listen_port)
  798. # I think that I will need this later
  799. while True:
  800. time.sleep(0.5)