server.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. import argparse
  2. import base64
  3. import copy
  4. import gc
  5. import glob
  6. import io
  7. import json
  8. import os
  9. import re
  10. import sys
  11. import time
  12. import warnings
  13. import zipfile
  14. from datetime import datetime
  15. from pathlib import Path
  16. import gradio as gr
  17. import numpy as np
  18. import torch
  19. import transformers
  20. from PIL import Image
  21. from tqdm import tqdm
  22. from transformers import AutoConfig
  23. from transformers import AutoModelForCausalLM
  24. from transformers import AutoTokenizer
  25. from io import BytesIO
  26. from modules.html_generator import *
  27. from modules.stopping_criteria import _SentinelTokenStoppingCriteria
  28. from modules.ui import *
  29. transformers.logging.set_verbosity_error()
  30. parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=54))
  31. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  32. 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.')
  33. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode.')
  34. 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.')
  35. parser.add_argument('--picture', action='store_true', help='Adds an ability to send pictures in chat UI modes. Captions are generated by BLIP.')
  36. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  37. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  38. parser.add_argument('--bf16', action='store_true', help='Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU.')
  39. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  40. 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.')
  41. parser.add_argument('--disk-cache-dir', type=str, help='Directory to save the disk cache to. Defaults to "cache/".')
  42. 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.')
  43. 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.')
  44. parser.add_argument('--deepspeed', action='store_true', help='Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.')
  45. parser.add_argument('--nvme-offload-dir', type=str, help='DeepSpeed: Directory to use for ZeRO-3 NVME offloading.')
  46. parser.add_argument('--local_rank', type=int, default=0, help='DeepSpeed: Optional argument for distributed setups.')
  47. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time. This improves the text generation performance.')
  48. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example.')
  49. 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".')
  50. parser.add_argument('--listen', action='store_true', help='Make the web UI reachable from your local network.')
  51. parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
  52. 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.')
  53. parser.add_argument('--verbose', action='store_true', help='Print the prompts to the terminal.')
  54. args = parser.parse_args()
  55. if (args.chat or args.cai_chat) and not args.no_stream:
  56. print("Warning: chat mode currently becomes somewhat slower with text streaming on.\nConsider starting the web UI with the --no-stream option.\n")
  57. settings = {
  58. 'max_new_tokens': 200,
  59. 'max_new_tokens_min': 1,
  60. 'max_new_tokens_max': 2000,
  61. 'preset': 'NovelAI-Sphinx Moth',
  62. 'name1': 'Person 1',
  63. 'name2': 'Person 2',
  64. 'context': 'This is a conversation between two people.',
  65. 'prompt': 'Common sense questions and answers\n\nQuestion: \nFactual answer:',
  66. 'prompt_gpt4chan': '-----\n--- 865467536\nInput text\n--- 865467537\n',
  67. 'stop_at_newline': True,
  68. 'chat_prompt_size': 2048,
  69. 'chat_prompt_size_min': 0,
  70. 'chat_prompt_size_max': 2048,
  71. 'preset_pygmalion': 'Pygmalion',
  72. 'name1_pygmalion': 'You',
  73. 'name2_pygmalion': 'Kawaii',
  74. '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>",
  75. 'stop_at_newline_pygmalion': False,
  76. }
  77. if args.settings is not None and Path(args.settings).exists():
  78. new_settings = json.loads(open(Path(args.settings), 'r').read())
  79. for item in new_settings:
  80. settings[item] = new_settings[item]
  81. if args.deepspeed:
  82. import deepspeed
  83. from transformers.deepspeed import HfDeepSpeedConfig, is_deepspeed_zero3_enabled
  84. from modules.deepspeed_parameters import generate_ds_config
  85. # Distributed setup
  86. local_rank = args.local_rank if args.local_rank is not None else int(os.getenv("LOCAL_RANK", "0"))
  87. world_size = int(os.getenv("WORLD_SIZE", "1"))
  88. torch.cuda.set_device(local_rank)
  89. deepspeed.init_distributed()
  90. ds_config = generate_ds_config(args.bf16, 1 * world_size, args.nvme_offload_dir)
  91. dschf = HfDeepSpeedConfig(ds_config) # Keep this object alive for the Transformers integration
  92. if args.picture and (args.cai_chat or args.chat):
  93. import modules.bot_picture as bot_picture
  94. def load_model(model_name):
  95. print(f"Loading {model_name}...")
  96. t0 = time.time()
  97. # Default settings
  98. if not (args.cpu or args.load_in_8bit or args.auto_devices or args.disk or args.gpu_memory is not None or args.cpu_memory is not None or args.deepspeed):
  99. if Path(f"torch-dumps/{model_name}.pt").exists():
  100. print("Loading in .pt format...")
  101. model = torch.load(Path(f"torch-dumps/{model_name}.pt"))
  102. elif model_name.lower().startswith(('gpt-neo', 'opt-', 'galactica')) and any(size in model_name.lower() for size in ('13b', '20b', '30b')):
  103. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), device_map='auto', load_in_8bit=True)
  104. else:
  105. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), low_cpu_mem_usage=True, torch_dtype=torch.bfloat16 if args.bf16 else torch.float16).cuda()
  106. # DeepSpeed ZeRO-3
  107. elif args.deepspeed:
  108. model = AutoModelForCausalLM.from_pretrained(Path(f"models/{model_name}"), torch_dtype=torch.bfloat16 if args.bf16 else torch.float16)
  109. model = deepspeed.initialize(model=model, config_params=ds_config, model_parameters=None, optimizer=None, lr_scheduler=None)[0]
  110. model.module.eval() # Inference
  111. print(f"DeepSpeed ZeRO-3 is enabled: {is_deepspeed_zero3_enabled()}")
  112. # Custom
  113. else:
  114. command = "AutoModelForCausalLM.from_pretrained"
  115. params = ["low_cpu_mem_usage=True"]
  116. if not args.cpu and not torch.cuda.is_available():
  117. print("Warning: no GPU has been detected.\nFalling back to CPU mode.\n")
  118. args.cpu = True
  119. if args.cpu:
  120. params.append("low_cpu_mem_usage=True")
  121. params.append("torch_dtype=torch.float32")
  122. else:
  123. params.append("device_map='auto'")
  124. params.append("load_in_8bit=True" if args.load_in_8bit else "torch_dtype=torch.bfloat16" if args.bf16 else "torch_dtype=torch.float16")
  125. if args.gpu_memory:
  126. params.append(f"max_memory={{0: '{args.gpu_memory or '99'}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  127. elif not args.load_in_8bit:
  128. total_mem = (torch.cuda.get_device_properties(0).total_memory/(1024*1024))
  129. suggestion = round((total_mem-1000)/1000)*1000
  130. if total_mem-suggestion < 800:
  131. suggestion -= 1000
  132. suggestion = int(round(suggestion/1000))
  133. print(f"\033[1;32;1mAuto-assiging --gpu-memory {suggestion} for your GPU to try to prevent out-of-memory errors.\nYou can manually set other values.\033[0;37;0m")
  134. params.append(f"max_memory={{0: '{suggestion}GiB', 'cpu': '{args.cpu_memory or '99'}GiB'}}")
  135. if args.disk:
  136. params.append(f"offload_folder='{args.disk_cache_dir or 'cache'}'")
  137. command = f"{command}(Path(f'models/{model_name}'), {', '.join(set(params))})"
  138. model = eval(command)
  139. # Loading the tokenizer
  140. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')) and Path(f"models/gpt-j-6B/").exists():
  141. tokenizer = AutoTokenizer.from_pretrained(Path("models/gpt-j-6B/"))
  142. else:
  143. tokenizer = AutoTokenizer.from_pretrained(Path(f"models/{model_name}/"))
  144. tokenizer.truncation_side = 'left'
  145. print(f"Loaded the model in {(time.time()-t0):.2f} seconds.")
  146. return model, tokenizer
  147. def load_soft_prompt(name):
  148. global soft_prompt, soft_prompt_tensor
  149. if name == 'None':
  150. soft_prompt = False
  151. soft_prompt_tensor = None
  152. else:
  153. with zipfile.ZipFile(Path(f'softprompts/{name}.zip')) as zf:
  154. zf.extract('tensor.npy')
  155. tensor = np.load('tensor.npy')
  156. tensor = torch.Tensor(tensor).to(device=model.device, dtype=model.dtype)
  157. tensor = torch.reshape(tensor, (1, tensor.shape[0], tensor.shape[1]))
  158. soft_prompt = True
  159. soft_prompt_tensor = tensor
  160. return name
  161. def upload_soft_prompt(file):
  162. with zipfile.ZipFile(io.BytesIO(file)) as zf:
  163. zf.extract('meta.json')
  164. j = json.loads(open('meta.json', 'r').read())
  165. name = j['name']
  166. with open(Path(f'softprompts/{name}.zip'), 'wb') as f:
  167. f.write(file)
  168. return name
  169. def load_model_wrapper(selected_model):
  170. global model_name, model, tokenizer
  171. if selected_model != model_name:
  172. model_name = selected_model
  173. model = tokenizer = None
  174. if not args.cpu:
  175. gc.collect()
  176. torch.cuda.empty_cache()
  177. model, tokenizer = load_model(model_name)
  178. return selected_model
  179. def load_preset_values(preset_menu, return_dict=False):
  180. generate_params = {
  181. 'do_sample': True,
  182. 'temperature': 1,
  183. 'top_p': 1,
  184. 'typical_p': 1,
  185. 'repetition_penalty': 1,
  186. 'top_k': 50,
  187. 'num_beams': 1,
  188. 'penalty_alpha': 0,
  189. 'min_length': 0,
  190. 'length_penalty': 1,
  191. 'no_repeat_ngram_size': 0,
  192. 'early_stopping': False,
  193. }
  194. with open(Path(f'presets/{preset_menu}.txt'), 'r') as infile:
  195. preset = infile.read()
  196. for i in preset.splitlines():
  197. i = i.rstrip(',').strip().split('=')
  198. if len(i) == 2 and i[0].strip() != 'tokens':
  199. generate_params[i[0].strip()] = eval(i[1].strip())
  200. generate_params['temperature'] = min(1.99, generate_params['temperature'])
  201. if return_dict:
  202. return generate_params
  203. else:
  204. return generate_params['do_sample'], generate_params['temperature'], generate_params['top_p'], generate_params['typical_p'], generate_params['repetition_penalty'], generate_params['top_k'], generate_params['min_length'], generate_params['no_repeat_ngram_size'], generate_params['num_beams'], generate_params['penalty_alpha'], generate_params['length_penalty'], generate_params['early_stopping']
  205. # Removes empty replies from gpt4chan outputs
  206. def fix_gpt4chan(s):
  207. for i in range(10):
  208. s = re.sub("--- [0-9]*\n>>[0-9]*\n---", "---", s)
  209. s = re.sub("--- [0-9]*\n *\n---", "---", s)
  210. s = re.sub("--- [0-9]*\n\n\n---", "---", s)
  211. return s
  212. # Fix the LaTeX equations in galactica
  213. def fix_galactica(s):
  214. s = s.replace(r'\[', r'$')
  215. s = s.replace(r'\]', r'$')
  216. s = s.replace(r'\(', r'$')
  217. s = s.replace(r'\)', r'$')
  218. s = s.replace(r'$$', r'$')
  219. return s
  220. def get_max_prompt_length(tokens):
  221. global soft_prompt, soft_prompt_tensor
  222. max_length = 2048-tokens
  223. if soft_prompt:
  224. max_length -= soft_prompt_tensor.shape[1]
  225. return max_length
  226. def encode(prompt, tokens_to_generate=0, add_special_tokens=True):
  227. input_ids = tokenizer.encode(str(prompt), return_tensors='pt', truncation=True, max_length=get_max_prompt_length(tokens_to_generate), add_special_tokens=add_special_tokens)
  228. if args.cpu:
  229. return input_ids
  230. elif args.deepspeed:
  231. return input_ids.to(device=local_rank)
  232. else:
  233. return input_ids.cuda()
  234. def decode(output_ids):
  235. reply = tokenizer.decode(output_ids, skip_special_tokens=True)
  236. reply = reply.replace(r'<|endoftext|>', '')
  237. return reply
  238. def formatted_outputs(reply, model_name):
  239. if not (args.chat or args.cai_chat):
  240. if model_name.lower().startswith('galactica'):
  241. reply = fix_galactica(reply)
  242. return reply, reply, generate_basic_html(reply)
  243. elif model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  244. reply = fix_gpt4chan(reply)
  245. return reply, 'Only applicable for GALACTICA models.', generate_4chan_html(reply)
  246. else:
  247. return reply, 'Only applicable for GALACTICA models.', generate_basic_html(reply)
  248. else:
  249. return reply
  250. def generate_softprompt_input_tensors(input_ids):
  251. inputs_embeds = model.transformer.wte(input_ids)
  252. inputs_embeds = torch.cat((soft_prompt_tensor, inputs_embeds), dim=1)
  253. filler_input_ids = torch.zeros((1, inputs_embeds.shape[1]), dtype=input_ids.dtype).to(model.device)
  254. filler_input_ids += model.config.bos_token_id # setting dummy input_ids to bos tokens
  255. return inputs_embeds, filler_input_ids
  256. def generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=None, stopping_string=None):
  257. global model_name, model, tokenizer, soft_prompt, soft_prompt_tensor
  258. original_question = question
  259. if not (args.chat or args.cai_chat):
  260. question = apply_extensions(question, "input")
  261. if args.verbose:
  262. print(f"\n\n{question}\n--------------------\n")
  263. input_ids = encode(question, tokens)
  264. cuda = "" if (args.cpu or args.deepspeed) else ".cuda()"
  265. n = tokenizer.eos_token_id if eos_token is None else tokenizer.encode(eos_token, return_tensors='pt')[0][-1]
  266. if stopping_string is not None:
  267. # The stopping_criteria code below was copied from
  268. # https://github.com/PygmalionAI/gradio-ui/blob/master/src/model.py
  269. t = encode(stopping_string, 0, add_special_tokens=False)
  270. stopping_criteria_list = transformers.StoppingCriteriaList([
  271. _SentinelTokenStoppingCriteria(
  272. sentinel_token_ids=t,
  273. starting_idx=len(input_ids[0])
  274. )
  275. ])
  276. else:
  277. stopping_criteria_list = None
  278. generate_params = [
  279. f"eos_token_id={n}",
  280. f"stopping_criteria=stopping_criteria_list",
  281. f"do_sample={do_sample}",
  282. f"temperature={temperature}",
  283. f"top_p={top_p}",
  284. f"typical_p={typical_p}",
  285. f"repetition_penalty={repetition_penalty}",
  286. f"top_k={top_k}",
  287. f"min_length={min_length if args.no_stream else 0}",
  288. f"no_repeat_ngram_size={no_repeat_ngram_size}",
  289. f"num_beams={num_beams}",
  290. f"penalty_alpha={penalty_alpha}",
  291. f"length_penalty={length_penalty}",
  292. f"early_stopping={early_stopping}",
  293. ]
  294. if args.deepspeed:
  295. generate_params.append("synced_gpus=True")
  296. if args.no_stream:
  297. generate_params.append(f"max_new_tokens=tokens")
  298. else:
  299. generate_params.append(f"max_new_tokens=8")
  300. if soft_prompt:
  301. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  302. generate_params.insert(0, "inputs_embeds=inputs_embeds")
  303. generate_params.insert(0, "filler_input_ids")
  304. else:
  305. generate_params.insert(0, "input_ids")
  306. # Generate the entire reply at once
  307. if args.no_stream:
  308. t0 = time.time()
  309. with torch.no_grad():
  310. output = eval(f"model.generate({', '.join(generate_params)}){cuda}")[0]
  311. if soft_prompt:
  312. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  313. reply = decode(output)
  314. if not (args.chat or args.cai_chat):
  315. reply = original_question + apply_extensions(reply[len(question):], "output")
  316. yield formatted_outputs(reply, model_name)
  317. t1 = time.time()
  318. print(f"Output generated in {(t1-t0):.2f} seconds ({(len(output)-len(input_ids[0]))/(t1-t0)/8:.2f} it/s, {len(output)-len(input_ids[0])} tokens)")
  319. # Generate the reply 1 token at a time
  320. else:
  321. yield formatted_outputs(original_question, model_name)
  322. for i in tqdm(range(tokens//8+1)):
  323. with torch.no_grad():
  324. output = eval(f"model.generate({', '.join(generate_params)}){cuda}")[0]
  325. if soft_prompt:
  326. output = torch.cat((input_ids[0], output[filler_input_ids.shape[1]:]))
  327. reply = decode(output)
  328. if not (args.chat or args.cai_chat):
  329. reply = original_question + apply_extensions(reply[len(question):], "output")
  330. yield formatted_outputs(reply, model_name)
  331. input_ids = torch.reshape(output, (1, output.shape[0]))
  332. if soft_prompt:
  333. inputs_embeds, filler_input_ids = generate_softprompt_input_tensors(input_ids)
  334. if output[-1] == n:
  335. break
  336. def apply_extensions(text, typ):
  337. global available_extensions, extension_state
  338. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  339. if extension_state[ext][0] == True:
  340. ext_string = f"extensions.{ext}.script"
  341. if typ == "input" and hasattr(eval(ext_string), "input_modifier"):
  342. text = eval(f"{ext_string}.input_modifier(text)")
  343. elif typ == "output" and hasattr(eval(ext_string), "output_modifier"):
  344. text = eval(f"{ext_string}.output_modifier(text)")
  345. elif typ == "bot_prefix" and hasattr(eval(ext_string), "bot_prefix_modifier"):
  346. text = eval(f"{ext_string}.bot_prefix_modifier(text)")
  347. return text
  348. def update_extensions_parameters(*kwargs):
  349. i = 0
  350. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  351. if extension_state[ext][0] == True:
  352. params = eval(f"extensions.{ext}.script.params")
  353. for param in params:
  354. if len(kwargs) >= i+1:
  355. params[param] = eval(f"kwargs[{i}]")
  356. i += 1
  357. def get_available_models():
  358. 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)
  359. def get_available_presets():
  360. return sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('presets').glob('*.txt'))), key=str.lower)
  361. def get_available_characters():
  362. return ["None"] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('characters').glob('*.json'))), key=str.lower)
  363. def get_available_extensions():
  364. return sorted(set(map(lambda x : x.parts[1], Path('extensions').glob('*/script.py'))), key=str.lower)
  365. def get_available_softprompts():
  366. return ["None"] + sorted(set(map(lambda x : '.'.join(str(x.name).split('.')[:-1]), Path('softprompts').glob('*.zip'))), key=str.lower)
  367. def create_extensions_block():
  368. extensions_ui_elements = []
  369. default_values = []
  370. if not (args.chat or args.cai_chat):
  371. gr.Markdown('## Extensions parameters')
  372. for ext in sorted(extension_state, key=lambda x : extension_state[x][1]):
  373. if extension_state[ext][0] == True:
  374. params = eval(f"extensions.{ext}.script.params")
  375. for param in params:
  376. _id = f"{ext}-{param}"
  377. default_value = settings[_id] if _id in settings else params[param]
  378. default_values.append(default_value)
  379. if type(params[param]) == str:
  380. extensions_ui_elements.append(gr.Textbox(value=default_value, label=f"{ext}-{param}"))
  381. elif type(params[param]) in [int, float]:
  382. extensions_ui_elements.append(gr.Number(value=default_value, label=f"{ext}-{param}"))
  383. elif type(params[param]) == bool:
  384. extensions_ui_elements.append(gr.Checkbox(value=default_value, label=f"{ext}-{param}"))
  385. update_extensions_parameters(*default_values)
  386. btn_extensions = gr.Button("Apply")
  387. btn_extensions.click(update_extensions_parameters, [*extensions_ui_elements], [])
  388. def create_settings_menus():
  389. generate_params = load_preset_values(settings[f'preset{suffix}'], return_dict=True)
  390. with gr.Row():
  391. with gr.Column():
  392. with gr.Row():
  393. model_menu = gr.Dropdown(choices=available_models, value=model_name, label='Model')
  394. create_refresh_button(model_menu, lambda : None, lambda : {"choices": get_available_models()}, "refresh-button")
  395. with gr.Column():
  396. with gr.Row():
  397. preset_menu = gr.Dropdown(choices=available_presets, value=settings[f'preset{suffix}'], label='Generation parameters preset')
  398. create_refresh_button(preset_menu, lambda : None, lambda : {"choices": get_available_presets()}, "refresh-button")
  399. with gr.Accordion("Custom generation parameters", open=False):
  400. with gr.Row():
  401. with gr.Column():
  402. do_sample = gr.Checkbox(value=generate_params['do_sample'], label="do_sample")
  403. temperature = gr.Slider(0.01, 1.99, value=generate_params['temperature'], step=0.01, label="temperature")
  404. top_p = gr.Slider(0.0,1.0,value=generate_params['top_p'],step=0.01,label="top_p")
  405. typical_p = gr.Slider(0.0,1.0,value=generate_params['typical_p'],step=0.01,label="typical_p")
  406. with gr.Column():
  407. repetition_penalty = gr.Slider(1.0,4.99,value=generate_params['repetition_penalty'],step=0.01,label="repetition_penalty")
  408. top_k = gr.Slider(0,200,value=generate_params['top_k'],step=1,label="top_k")
  409. no_repeat_ngram_size = gr.Slider(0, 20, step=1, value=generate_params["no_repeat_ngram_size"], label="no_repeat_ngram_size")
  410. penalty_alpha = gr.Slider(0, 5, value=generate_params["penalty_alpha"], label="penalty_alpha")
  411. gr.Markdown("Special parameters (only use them if you really need them):")
  412. with gr.Row():
  413. with gr.Column():
  414. num_beams = gr.Slider(0, 20, step=1, value=generate_params["num_beams"], label="num_beams")
  415. length_penalty = gr.Slider(-5, 5, value=generate_params["length_penalty"], label="length_penalty")
  416. with gr.Column():
  417. min_length = gr.Slider(0, 2000, step=1, value=generate_params["min_length"] if args.no_stream else 0, label="min_length", interactive=args.no_stream)
  418. early_stopping = gr.Checkbox(value=generate_params["early_stopping"], label="early_stopping")
  419. with gr.Accordion("Soft prompt", open=False):
  420. with gr.Row():
  421. softprompts_menu = gr.Dropdown(choices=available_softprompts, value="None", label='Soft prompt')
  422. create_refresh_button(softprompts_menu, lambda : None, lambda : {"choices": get_available_softprompts()}, "refresh-button")
  423. gr.Markdown('Upload a soft prompt (.zip format):')
  424. with gr.Row():
  425. upload_softprompt = gr.File(type='binary')
  426. model_menu.change(load_model_wrapper, [model_menu], [model_menu], show_progress=True)
  427. preset_menu.change(load_preset_values, [preset_menu], [do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping])
  428. softprompts_menu.change(load_soft_prompt, [softprompts_menu], [softprompts_menu], show_progress=True)
  429. upload_softprompt.change(upload_soft_prompt, [upload_softprompt], [softprompts_menu])
  430. return preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping
  431. # This gets the new line characters right.
  432. def clean_chat_message(text):
  433. text = text.replace('\n', '\n\n')
  434. text = re.sub(r"\n{3,}", "\n\n", text)
  435. text = text.strip()
  436. return text
  437. def generate_chat_prompt(text, tokens, name1, name2, context, chat_prompt_size, impersonate=False):
  438. text = clean_chat_message(text)
  439. rows = [f"{context.strip()}\n"]
  440. i = len(history['internal'])-1
  441. count = 0
  442. max_length = min(get_max_prompt_length(tokens), chat_prompt_size)
  443. while i >= 0 and len(encode(''.join(rows), tokens)[0]) < max_length:
  444. rows.insert(1, f"{name2}: {history['internal'][i][1].strip()}\n")
  445. count += 1
  446. if not (history['internal'][i][0] == '<|BEGIN-VISIBLE-CHAT|>'):
  447. rows.insert(1, f"{name1}: {history['internal'][i][0].strip()}\n")
  448. count += 1
  449. i -= 1
  450. if not impersonate:
  451. rows.append(f"{name1}: {text}\n")
  452. rows.append(apply_extensions(f"{name2}:", "bot_prefix"))
  453. limit = 3
  454. else:
  455. rows.append(f"{name1}:")
  456. limit = 2
  457. while len(rows) > limit and len(encode(''.join(rows), tokens)[0]) >= max_length:
  458. rows.pop(1)
  459. rows.pop(1)
  460. question = ''.join(rows)
  461. return question
  462. def extract_message_from_reply(question, reply, current, other, check, extensions=False):
  463. next_character_found = False
  464. substring_found = False
  465. previous_idx = [m.start() for m in re.finditer(f"(^|\n){current}:", question)]
  466. idx = [m.start() for m in re.finditer(f"(^|\n){current}:", reply)]
  467. idx = idx[len(previous_idx)-1]
  468. if extensions:
  469. reply = reply[idx + 1 + len(apply_extensions(f"{current}:", "bot_prefix")):]
  470. else:
  471. reply = reply[idx + 1 + len(f"{current}:"):]
  472. if check:
  473. reply = reply.split('\n')[0].strip()
  474. else:
  475. idx = reply.find(f"\n{other}:")
  476. if idx != -1:
  477. reply = reply[:idx]
  478. next_character_found = True
  479. reply = clean_chat_message(reply)
  480. # Detect if something like "\nYo" is generated just before
  481. # "\nYou:" is completed
  482. tmp = f"\n{other}:"
  483. for j in range(1, len(tmp)):
  484. if reply[-j:] == tmp[:j]:
  485. substring_found = True
  486. return reply, next_character_found, substring_found
  487. def generate_chat_picture(picture, name1, name2):
  488. text = f'*{name1} sends {name2} a picture that contains the following: "{bot_picture.caption_image(picture)}"*'
  489. buffer = BytesIO()
  490. picture.save(buffer, format="JPEG")
  491. img_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
  492. visible_text = f'<img src="data:image/jpeg;base64,{img_str}">'
  493. return text, visible_text
  494. def stop_everything_event():
  495. global stop_everything
  496. stop_everything = True
  497. def chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  498. global stop_everything
  499. stop_everything = False
  500. if 'pygmalion' in model_name.lower():
  501. name1 = "You"
  502. if args.picture and picture is not None:
  503. text, visible_text = generate_chat_picture(picture, name1, name2)
  504. else:
  505. visible_text = text
  506. text = apply_extensions(text, "input")
  507. question = generate_chat_prompt(text, tokens, name1, name2, context, chat_prompt_size)
  508. eos_token = '\n' if check else None
  509. first = True
  510. for reply in generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name1}:"):
  511. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name2, name1, check, extensions=True)
  512. visible_reply = apply_extensions(reply, "output")
  513. # We need this global variable to handle the Stop event,
  514. # otherwise gradio gets confused
  515. if stop_everything:
  516. return history['visible']
  517. if first:
  518. first = False
  519. history['internal'].append(['', ''])
  520. history['visible'].append(['', ''])
  521. history['internal'][-1] = [text, reply]
  522. history['visible'][-1] = [visible_text, visible_reply]
  523. if not substring_found:
  524. yield history['visible']
  525. if next_character_found:
  526. break
  527. yield history['visible']
  528. def impersonate_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  529. if 'pygmalion' in model_name.lower():
  530. name1 = "You"
  531. question = generate_chat_prompt(text, tokens, name1, name2, context, chat_prompt_size, impersonate=True)
  532. eos_token = '\n' if check else None
  533. for reply in generate_reply(question, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, eos_token=eos_token, stopping_string=f"\n{name2}:"):
  534. reply, next_character_found, substring_found = extract_message_from_reply(question, reply, name1, name2, check, extensions=False)
  535. if not substring_found:
  536. yield reply
  537. if next_character_found:
  538. break
  539. yield reply
  540. def cai_chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  541. for _history in chatbot_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture):
  542. yield generate_chat_html(_history, name1, name2, character)
  543. def regenerate_wrapper(text, tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture=None):
  544. if character is not None and len(history['visible']) == 1:
  545. if args.cai_chat:
  546. yield generate_chat_html(history['visible'], name1, name2, character)
  547. else:
  548. yield history['visible']
  549. else:
  550. last_visible = history['visible'].pop()
  551. last_internal = history['internal'].pop()
  552. for _history in chatbot_wrapper(last_internal[0], tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size, picture):
  553. if args.cai_chat:
  554. history['visible'][-1] = [last_visible[0], _history[-1][1]]
  555. yield generate_chat_html(history['visible'], name1, name2, character)
  556. else:
  557. history['visible'][-1] = (last_visible[0], _history[-1][1])
  558. yield history['visible']
  559. def remove_last_message(name1, name2):
  560. if not history['internal'][-1][0] == '<|BEGIN-VISIBLE-CHAT|>':
  561. last = history['visible'].pop()
  562. history['internal'].pop()
  563. else:
  564. last = ['', '']
  565. if args.cai_chat:
  566. return generate_chat_html(history['visible'], name1, name2, character), last[0]
  567. else:
  568. return history['visible'], last[0]
  569. def send_last_reply_to_input():
  570. if len(history['internal']) > 0:
  571. return history['internal'][-1][1]
  572. else:
  573. return ''
  574. def replace_last_reply(text, name1, name2):
  575. if len(history['visible']) > 0:
  576. if args.cai_chat:
  577. history['visible'][-1][1] = text
  578. else:
  579. history['visible'][-1] = (history['visible'][-1][0], text)
  580. history['internal'][-1][1] = apply_extensions(text, "input")
  581. if args.cai_chat:
  582. return generate_chat_html(history['visible'], name1, name2, character)
  583. else:
  584. return history['visible']
  585. def clear_html():
  586. return generate_chat_html([], "", "", character)
  587. def clear_chat_log(_character, name1, name2):
  588. global history
  589. if _character != 'None':
  590. for i in range(len(history['internal'])):
  591. if '<|BEGIN-VISIBLE-CHAT|>' in history['internal'][i][0]:
  592. history['visible'] = [['', history['internal'][i][1]]]
  593. history['internal'] = history['internal'][:i+1]
  594. break
  595. else:
  596. history['internal'] = []
  597. history['visible'] = []
  598. if args.cai_chat:
  599. return generate_chat_html(history['visible'], name1, name2, character)
  600. else:
  601. return history['visible']
  602. def redraw_html(name1, name2):
  603. global history
  604. return generate_chat_html(history['visible'], name1, name2, character)
  605. def tokenize_dialogue(dialogue, name1, name2):
  606. _history = []
  607. dialogue = re.sub('<START>', '', dialogue)
  608. dialogue = re.sub('<start>', '', dialogue)
  609. dialogue = re.sub('(\n|^)[Aa]non:', '\\1You:', dialogue)
  610. dialogue = re.sub('(\n|^)\[CHARACTER\]:', f'\\g<1>{name2}:', dialogue)
  611. idx = [m.start() for m in re.finditer(f"(^|\n)({name1}|{name2}):", dialogue)]
  612. if len(idx) == 0:
  613. return _history
  614. messages = []
  615. for i in range(len(idx)-1):
  616. messages.append(dialogue[idx[i]:idx[i+1]].strip())
  617. messages.append(dialogue[idx[-1]:].strip())
  618. entry = ['', '']
  619. for i in messages:
  620. if i.startswith(f'{name1}:'):
  621. entry[0] = i[len(f'{name1}:'):].strip()
  622. elif i.startswith(f'{name2}:'):
  623. entry[1] = i[len(f'{name2}:'):].strip()
  624. if not (len(entry[0]) == 0 and len(entry[1]) == 0):
  625. _history.append(entry)
  626. entry = ['', '']
  627. print(f"\033[1;32;1m\nDialogue tokenized to:\033[0;37;0m\n", end='')
  628. for row in _history:
  629. for column in row:
  630. print("\n")
  631. for line in column.strip().split('\n'):
  632. print("| "+line+"\n")
  633. print("|\n")
  634. print("------------------------------")
  635. return _history
  636. def save_history(timestamp=True):
  637. if timestamp:
  638. fname = f"{character or ''}{'_' if character else ''}{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
  639. else:
  640. fname = f"{character or ''}{'_' if character else ''}persistent.json"
  641. if not Path('logs').exists():
  642. Path('logs').mkdir()
  643. with open(Path(f'logs/{fname}'), 'w') as f:
  644. f.write(json.dumps({'data': history['internal'], 'data_visible': history['visible']}))
  645. return Path(f'logs/{fname}')
  646. def load_history(file, name1, name2):
  647. global history
  648. file = file.decode('utf-8')
  649. try:
  650. j = json.loads(file)
  651. if 'data' in j:
  652. history['internal'] = j['data']
  653. if 'data_visible' in j:
  654. history['visible'] = j['data_visible']
  655. else:
  656. history['visible'] = copy.deepcopy(history['internal'])
  657. # Compatibility with Pygmalion AI's official web UI
  658. elif 'chat' in j:
  659. history['internal'] = [':'.join(x.split(':')[1:]).strip() for x in j['chat']]
  660. if len(j['chat']) > 0 and j['chat'][0].startswith(f'{name2}:'):
  661. 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)]
  662. history['visible'] = copy.deepcopy(history['internal'])
  663. history['visible'][0][0] = ''
  664. else:
  665. history['internal'] = [[history['internal'][i], history['internal'][i+1]] for i in range(0, len(history['internal'])-1, 2)]
  666. history['visible'] = copy.deepcopy(history['internal'])
  667. except:
  668. history['internal'] = tokenize_dialogue(file, name1, name2)
  669. history['visible'] = copy.deepcopy(history['internal'])
  670. def load_character(_character, name1, name2):
  671. global history, character
  672. context = ""
  673. history['internal'] = []
  674. history['visible'] = []
  675. if _character != 'None':
  676. character = _character
  677. data = json.loads(open(Path(f'characters/{_character}.json'), 'r').read())
  678. name2 = data['char_name']
  679. if 'char_persona' in data and data['char_persona'] != '':
  680. context += f"{data['char_name']}'s Persona: {data['char_persona']}\n"
  681. if 'world_scenario' in data and data['world_scenario'] != '':
  682. context += f"Scenario: {data['world_scenario']}\n"
  683. context = f"{context.strip()}\n<START>\n"
  684. if 'example_dialogue' in data and data['example_dialogue'] != '':
  685. history['internal'] = tokenize_dialogue(data['example_dialogue'], name1, name2)
  686. if 'char_greeting' in data and len(data['char_greeting'].strip()) > 0:
  687. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', data['char_greeting']]]
  688. history['visible'] += [['', apply_extensions(data['char_greeting'], "output")]]
  689. else:
  690. history['internal'] += [['<|BEGIN-VISIBLE-CHAT|>', "Hello there!"]]
  691. history['visible'] += [['', "Hello there!"]]
  692. else:
  693. character = None
  694. context = settings['context_pygmalion']
  695. name2 = settings['name2_pygmalion']
  696. if Path(f'logs/{character}_persistent.json').exists():
  697. load_history(open(Path(f'logs/{character}_persistent.json'), 'rb').read(), name1, name2)
  698. if args.cai_chat:
  699. return name2, context, generate_chat_html(history['visible'], name1, name2, character)
  700. else:
  701. return name2, context, history['visible']
  702. def upload_character(json_file, img, tavern=False):
  703. json_file = json_file if type(json_file) == str else json_file.decode('utf-8')
  704. data = json.loads(json_file)
  705. outfile_name = data["char_name"]
  706. i = 1
  707. while Path(f'characters/{outfile_name}.json').exists():
  708. outfile_name = f'{data["char_name"]}_{i:03d}'
  709. i += 1
  710. if tavern:
  711. outfile_name = f'TavernAI-{outfile_name}'
  712. with open(Path(f'characters/{outfile_name}.json'), 'w') as f:
  713. f.write(json_file)
  714. if img is not None:
  715. img = Image.open(io.BytesIO(img))
  716. img.save(Path(f'characters/{outfile_name}.png'))
  717. print(f'New character saved to "characters/{outfile_name}.json".')
  718. return outfile_name
  719. def upload_tavern_character(img, name1, name2):
  720. _img = Image.open(io.BytesIO(img))
  721. _img.getexif()
  722. decoded_string = base64.b64decode(_img.info['chara'])
  723. _json = json.loads(decoded_string)
  724. _json = {"char_name": _json['name'], "char_persona": _json['description'], "char_greeting": _json["first_mes"], "example_dialogue": _json['mes_example'], "world_scenario": _json['scenario']}
  725. _json['example_dialogue'] = _json['example_dialogue'].replace('{{user}}', name1).replace('{{char}}', _json['char_name'])
  726. return upload_character(json.dumps(_json), img, tavern=True)
  727. def upload_your_profile_picture(img):
  728. img = Image.open(io.BytesIO(img))
  729. img.save(Path(f'img_me.png'))
  730. print(f'Profile picture saved to "img_me.png"')
  731. # Global variables
  732. available_models = get_available_models()
  733. available_presets = get_available_presets()
  734. available_characters = get_available_characters()
  735. available_extensions = get_available_extensions()
  736. available_softprompts = get_available_softprompts()
  737. extension_state = {}
  738. if args.extensions is not None:
  739. for i,ext in enumerate(args.extensions.split(',')):
  740. if ext in available_extensions:
  741. print(f'Loading the extension "{ext}"... ', end='')
  742. ext_string = f"extensions.{ext}.script"
  743. exec(f"import {ext_string}")
  744. extension_state[ext] = [True, i]
  745. print(f'Ok.')
  746. # Choosing the default model
  747. if args.model is not None:
  748. model_name = args.model
  749. else:
  750. if len(available_models) == 0:
  751. print("No models are available! Please download at least one.")
  752. sys.exit(0)
  753. elif len(available_models) == 1:
  754. i = 0
  755. else:
  756. print("The following models are available:\n")
  757. for i,model in enumerate(available_models):
  758. print(f"{i+1}. {model}")
  759. print(f"\nWhich one do you want to load? 1-{len(available_models)}\n")
  760. i = int(input())-1
  761. print()
  762. model_name = available_models[i]
  763. model, tokenizer = load_model(model_name)
  764. loaded_preset = None
  765. soft_prompt_tensor = None
  766. soft_prompt = False
  767. stop_everything = False
  768. # UI settings
  769. if model_name.lower().startswith(('gpt4chan', 'gpt-4chan', '4chan')):
  770. default_text = settings['prompt_gpt4chan']
  771. elif re.match('(rosey|chip|joi)_.*_instruct.*', model_name.lower()) is not None:
  772. default_text = 'User: \n'
  773. else:
  774. default_text = settings['prompt']
  775. description = f"\n\n# Text generation lab\nGenerate text using Large Language Models.\n"
  776. css = ".tabs.svelte-710i53 {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}"
  777. chat_css = ".h-\[40vh\], .wrap.svelte-byatnx.svelte-byatnx.svelte-byatnx {height: 66.67vh} .gradio-container {max-width: 800px; margin-left: auto; margin-right: auto} .w-screen {width: unset} div.svelte-362y77>*, div.svelte-362y77>.form>* {flex-wrap: nowrap}"
  778. suffix = '_pygmalion' if 'pygmalion' in model_name.lower() else ''
  779. buttons = {}
  780. gen_events = []
  781. history = {'internal': [], 'visible': []}
  782. character = None
  783. if args.chat or args.cai_chat:
  784. if Path(f'logs/persistent.json').exists():
  785. load_history(open(Path(f'logs/persistent.json'), 'rb').read(), settings[f'name1{suffix}'], settings[f'name2{suffix}'])
  786. with gr.Blocks(css=css+chat_css, analytics_enabled=False) as interface:
  787. if args.cai_chat:
  788. display = gr.HTML(value=generate_chat_html(history['visible'], settings[f'name1{suffix}'], settings[f'name2{suffix}'], character))
  789. else:
  790. display = gr.Chatbot(value=history['visible'])
  791. textbox = gr.Textbox(label='Input')
  792. with gr.Row():
  793. buttons["Stop"] = gr.Button("Stop")
  794. buttons["Generate"] = gr.Button("Generate")
  795. buttons["Regenerate"] = gr.Button("Regenerate")
  796. with gr.Row():
  797. buttons["Impersonate"] = gr.Button("Impersonate")
  798. buttons["Remove last"] = gr.Button("Remove last")
  799. buttons["Clear history"] = gr.Button("Clear history")
  800. with gr.Row():
  801. buttons["Send last reply to input"] = gr.Button("Send last reply to input")
  802. buttons["Replace last reply"] = gr.Button("Replace last reply")
  803. if args.picture:
  804. with gr.Row():
  805. picture_select = gr.Image(label="Send a picture", type='pil')
  806. with gr.Tab("Chat settings"):
  807. name1 = gr.Textbox(value=settings[f'name1{suffix}'], lines=1, label='Your name')
  808. name2 = gr.Textbox(value=settings[f'name2{suffix}'], lines=1, label='Bot\'s name')
  809. context = gr.Textbox(value=settings[f'context{suffix}'], lines=2, label='Context')
  810. with gr.Row():
  811. character_menu = gr.Dropdown(choices=available_characters, value="None", label='Character')
  812. create_refresh_button(character_menu, lambda : None, lambda : {"choices": get_available_characters()}, "refresh-button")
  813. with gr.Row():
  814. check = gr.Checkbox(value=settings[f'stop_at_newline{suffix}'], label='Stop generating at new line character?')
  815. with gr.Row():
  816. with gr.Tab('Chat history'):
  817. with gr.Row():
  818. with gr.Column():
  819. gr.Markdown('Upload')
  820. upload = gr.File(type='binary')
  821. with gr.Column():
  822. gr.Markdown('Download')
  823. download = gr.File()
  824. buttons["Download"] = gr.Button(value="Click me")
  825. with gr.Tab('Upload character'):
  826. with gr.Row():
  827. with gr.Column():
  828. gr.Markdown('1. Select the JSON file')
  829. upload_char = gr.File(type='binary')
  830. with gr.Column():
  831. gr.Markdown('2. Select your character\'s profile picture (optional)')
  832. upload_img = gr.File(type='binary')
  833. buttons["Upload character"] = gr.Button(value="Submit")
  834. with gr.Tab('Upload your profile picture'):
  835. upload_img_me = gr.File(type='binary')
  836. with gr.Tab('Upload TavernAI Character Card'):
  837. upload_img_tavern = gr.File(type='binary')
  838. with gr.Tab("Generation settings"):
  839. with gr.Row():
  840. with gr.Column():
  841. max_new_tokens = 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'])
  842. with gr.Column():
  843. chat_prompt_size_slider = gr.Slider(minimum=settings['chat_prompt_size_min'], maximum=settings['chat_prompt_size_max'], step=1, label='Maximum prompt size in tokens', value=settings['chat_prompt_size'])
  844. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping = create_settings_menus()
  845. if args.extensions is not None:
  846. with gr.Tab("Extensions"):
  847. create_extensions_block()
  848. input_params = [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping, name1, name2, context, check, chat_prompt_size_slider]
  849. if args.picture:
  850. input_params.append(picture_select)
  851. function_call = "cai_chatbot_wrapper" if args.cai_chat else "chatbot_wrapper"
  852. gen_events.append(buttons["Generate"].click(eval(function_call), input_params, display, show_progress=args.no_stream, api_name="textgen"))
  853. gen_events.append(textbox.submit(eval(function_call), input_params, display, show_progress=args.no_stream))
  854. if args.picture:
  855. gen_events.append(picture_select.change(eval(function_call), input_params, display, show_progress=args.no_stream))
  856. gen_events.append(buttons["Regenerate"].click(regenerate_wrapper, input_params, display, show_progress=args.no_stream))
  857. gen_events.append(buttons["Impersonate"].click(impersonate_wrapper, input_params, textbox, show_progress=args.no_stream))
  858. buttons["Stop"].click(stop_everything_event, [], [], cancels=gen_events)
  859. buttons["Send last reply to input"].click(send_last_reply_to_input, [], textbox, show_progress=args.no_stream)
  860. buttons["Replace last reply"].click(replace_last_reply, [textbox, name1, name2], display, show_progress=args.no_stream)
  861. buttons["Clear history"].click(clear_chat_log, [character_menu, name1, name2], display)
  862. buttons["Remove last"].click(remove_last_message, [name1, name2], [display, textbox], show_progress=False)
  863. buttons["Download"].click(save_history, inputs=[], outputs=[download])
  864. buttons["Upload character"].click(upload_character, [upload_char, upload_img], [character_menu])
  865. # Clearing stuff and saving the history
  866. for i in ["Generate", "Regenerate", "Replace last reply"]:
  867. buttons[i].click(lambda x: "", textbox, textbox, show_progress=False)
  868. buttons[i].click(lambda : save_history(timestamp=False), [], [], show_progress=False)
  869. buttons["Clear history"].click(lambda : save_history(timestamp=False), [], [], show_progress=False)
  870. textbox.submit(lambda x: "", textbox, textbox, show_progress=False)
  871. textbox.submit(lambda : save_history(timestamp=False), [], [], show_progress=False)
  872. character_menu.change(load_character, [character_menu, name1, name2], [name2, context, display])
  873. upload_img_tavern.change(upload_tavern_character, [upload_img_tavern, name1, name2], [character_menu])
  874. upload.change(load_history, [upload, name1, name2], [])
  875. upload_img_me.change(upload_your_profile_picture, [upload_img_me], [])
  876. if args.picture:
  877. picture_select.change(lambda : None, [], [picture_select], show_progress=False)
  878. if args.cai_chat:
  879. upload.change(redraw_html, [name1, name2], [display])
  880. upload_img_me.change(redraw_html, [name1, name2], [display])
  881. else:
  882. upload.change(lambda : history['visible'], [], [display])
  883. upload_img_me.change(lambda : history['visible'], [], [display])
  884. elif args.notebook:
  885. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  886. gr.Markdown(description)
  887. with gr.Tab('Raw'):
  888. textbox = gr.Textbox(value=default_text, lines=23)
  889. with gr.Tab('Markdown'):
  890. markdown = gr.Markdown()
  891. with gr.Tab('HTML'):
  892. html = gr.HTML()
  893. buttons["Generate"] = gr.Button("Generate")
  894. buttons["Stop"] = gr.Button("Stop")
  895. max_new_tokens = 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'])
  896. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping = create_settings_menus()
  897. if args.extensions is not None:
  898. create_extensions_block()
  899. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  900. gen_events.append(textbox.submit(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [textbox, markdown, html], show_progress=args.no_stream))
  901. buttons["Stop"].click(None, None, None, cancels=gen_events)
  902. else:
  903. with gr.Blocks(css=css, analytics_enabled=False) as interface:
  904. gr.Markdown(description)
  905. with gr.Row():
  906. with gr.Column():
  907. textbox = gr.Textbox(value=default_text, lines=15, label='Input')
  908. max_new_tokens = 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'])
  909. buttons["Generate"] = gr.Button("Generate")
  910. with gr.Row():
  911. with gr.Column():
  912. buttons["Continue"] = gr.Button("Continue")
  913. with gr.Column():
  914. buttons["Stop"] = gr.Button("Stop")
  915. preset_menu, do_sample, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping = create_settings_menus()
  916. if args.extensions is not None:
  917. create_extensions_block()
  918. with gr.Column():
  919. with gr.Tab('Raw'):
  920. output_textbox = gr.Textbox(lines=15, label='Output')
  921. with gr.Tab('Markdown'):
  922. markdown = gr.Markdown()
  923. with gr.Tab('HTML'):
  924. html = gr.HTML()
  925. gen_events.append(buttons["Generate"].click(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream, api_name="textgen"))
  926. gen_events.append(textbox.submit(generate_reply, [textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream))
  927. gen_events.append(buttons["Continue"].click(generate_reply, [output_textbox, max_new_tokens, do_sample, max_new_tokens, temperature, top_p, typical_p, repetition_penalty, top_k, min_length, no_repeat_ngram_size, num_beams, penalty_alpha, length_penalty, early_stopping], [output_textbox, markdown, html], show_progress=args.no_stream))
  928. buttons["Stop"].click(None, None, None, cancels=gen_events)
  929. interface.queue()
  930. if args.listen:
  931. interface.launch(prevent_thread_lock=True, share=args.share, server_name="0.0.0.0", server_port=args.listen_port)
  932. else:
  933. interface.launch(prevent_thread_lock=True, share=args.share, server_port=args.listen_port)
  934. # I think that I will need this later
  935. while True:
  936. time.sleep(0.5)