server.py 29 KB

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