server.py 32 KB

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