server.py 39 KB

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