server.py 39 KB

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