server.py 33 KB

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