script.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import base64
  2. import io
  3. import re
  4. from pathlib import Path
  5. import gradio as gr
  6. import modules.chat as chat
  7. import modules.shared as shared
  8. import requests
  9. import torch
  10. from PIL import Image
  11. torch._C._jit_set_profiling_mode(False)
  12. # parameters which can be customized in settings.json of webui
  13. params = {
  14. 'enable_SD_api': False,
  15. 'address': 'http://127.0.0.1:7860',
  16. 'save_img': False,
  17. 'SD_model': 'NeverEndingDream', # not really used right now
  18. 'prompt_prefix': '(Masterpiece:1.1), (solo:1.3), detailed, intricate, colorful',
  19. 'negative_prompt': '(worst quality, low quality:1.3)',
  20. 'side_length': 512,
  21. 'restore_faces': False
  22. }
  23. SD_models = ['NeverEndingDream'] # TODO: get with http://{address}}/sdapi/v1/sd-models and allow user to select
  24. streaming_state = shared.args.no_stream # remember if chat streaming was enabled
  25. picture_response = False # specifies if the next model response should appear as a picture
  26. pic_id = 0
  27. def remove_surrounded_chars(string):
  28. # this expression matches to 'as few symbols as possible (0 upwards) between any asterisks' OR
  29. # 'as few symbols as possible (0 upwards) between an asterisk and the end of the string'
  30. return re.sub('\*[^\*]*?(\*|$)','',string)
  31. # I don't even need input_hijack for this as visible text will be commited to history as the unmodified string
  32. def input_modifier(string):
  33. """
  34. This function is applied to your text inputs before
  35. they are fed into the model.
  36. """
  37. global params, picture_response
  38. if not params['enable_SD_api']:
  39. return string
  40. commands = ['send', 'mail', 'me']
  41. mediums = ['image', 'pic', 'picture', 'photo']
  42. subjects = ['yourself', 'own']
  43. lowstr = string.lower()
  44. # TODO: refactor out to separate handler and also replace detection with a regexp
  45. if any(command in lowstr for command in commands) and any(case in lowstr for case in mediums): # trigger the generation if a command signature and a medium signature is found
  46. picture_response = True
  47. shared.args.no_stream = True # Disable streaming cause otherwise the SD-generated picture would return as a dud
  48. shared.processing_message = "*Is sending a picture...*"
  49. string = "Please provide a detailed description of your surroundings, how you look and the situation you're in and what you are doing right now"
  50. if any(target in lowstr for target in subjects): # the focus of the image should be on the sending character
  51. string = "Please provide a detailed and vivid description of how you look and what you are wearing"
  52. return string
  53. # Get and save the Stable Diffusion-generated picture
  54. def get_SD_pictures(description):
  55. global params, pic_id
  56. payload = {
  57. "prompt": params['prompt_prefix'] + description,
  58. "seed": -1,
  59. "sampler_name": "DPM++ 2M Karras",
  60. "steps": 32,
  61. "cfg_scale": 7,
  62. "width": params['side_length'],
  63. "height": params['side_length'],
  64. "restore_faces": params['restore_faces'],
  65. "negative_prompt": params['negative_prompt']
  66. }
  67. response = requests.post(url=f'{params["address"]}/sdapi/v1/txt2img', json=payload)
  68. r = response.json()
  69. visible_result = ""
  70. for img_str in r['images']:
  71. image = Image.open(io.BytesIO(base64.b64decode(img_str.split(",",1)[0])))
  72. if params['save_img']:
  73. output_file = Path(f'extensions/sd_api_pictures/outputs/{pic_id:06d}.png')
  74. image.save(output_file.as_posix())
  75. pic_id += 1
  76. # lower the resolution of received images for the chat, otherwise the log size gets out of control quickly with all the base64 values in visible history
  77. width, height = image.size
  78. if (width > 300):
  79. height = int(height * (300 / width))
  80. width = 300
  81. elif (height > 300):
  82. width = int(width * (300 / height))
  83. height = 300
  84. newsize = (width, height)
  85. image = image.resize(newsize, Image.LANCZOS)
  86. buffered = io.BytesIO()
  87. image.save(buffered, format="JPEG")
  88. buffered.seek(0)
  89. image_bytes = buffered.getvalue()
  90. img_str = "data:image/jpeg;base64," + base64.b64encode(image_bytes).decode()
  91. visible_result = visible_result + f'<img src="{img_str}" alt="{description}">\n'
  92. return visible_result
  93. # TODO: how do I make the UI history ignore the resulting pictures (I don't want HTML to appear in history)
  94. # and replace it with 'text' for the purposes of logging?
  95. def output_modifier(string):
  96. """
  97. This function is applied to the model outputs.
  98. """
  99. global pic_id, picture_response, streaming_state
  100. if not picture_response:
  101. return string
  102. string = remove_surrounded_chars(string)
  103. string = string.replace('"', '')
  104. string = string.replace('“', '')
  105. string = string.replace('\n', ' ')
  106. string = string.strip()
  107. if string == '':
  108. string = 'no viable description in reply, try regenerating'
  109. # I can't for the love of all that's holy get the name from shared.gradio['name1'], so for now it will be like this
  110. text = f'*Description: "{string}"*'
  111. image = get_SD_pictures(string)
  112. picture_response = False
  113. shared.processing_message = "*Is typing...*"
  114. shared.args.no_stream = streaming_state
  115. return image + "\n" + text
  116. def bot_prefix_modifier(string):
  117. """
  118. This function is only applied in chat mode. It modifies
  119. the prefix text for the Bot and can be used to bias its
  120. behavior.
  121. """
  122. return string
  123. def force_pic():
  124. global picture_response
  125. picture_response = True
  126. def ui():
  127. # Gradio elements
  128. with gr.Accordion("Stable Diffusion api integration", open=True):
  129. with gr.Row():
  130. with gr.Column():
  131. enable = gr.Checkbox(value=params['enable_SD_api'], label='Activate SD Api integration')
  132. save_img = gr.Checkbox(value=params['save_img'], label='Keep original received images in the outputs subdir')
  133. with gr.Column():
  134. address = gr.Textbox(placeholder=params['address'], value=params['address'], label='Stable Diffusion host address')
  135. with gr.Row():
  136. force_btn = gr.Button("Force the next response to be a picture")
  137. generate_now_btn = gr.Button("Generate an image response to the input")
  138. with gr.Accordion("Generation parameters", open=False):
  139. prompt_prefix = gr.Textbox(placeholder=params['prompt_prefix'], value=params['prompt_prefix'], label='Prompt Prefix (best used to describe the look of the character)')
  140. with gr.Row():
  141. negative_prompt = gr.Textbox(placeholder=params['negative_prompt'], value=params['negative_prompt'], label='Negative Prompt')
  142. dimensions = gr.Slider(256,702,value=params['side_length'],step=64,label='Image dimensions')
  143. # model = gr.Dropdown(value=SD_models[0], choices=SD_models, label='Model')
  144. # Event functions to update the parameters in the backend
  145. enable.change(lambda x: params.update({"enable_SD_api": x}), enable, None)
  146. save_img.change(lambda x: params.update({"save_img": x}), save_img, None)
  147. address.change(lambda x: params.update({"address": x}), address, None)
  148. prompt_prefix.change(lambda x: params.update({"prompt_prefix": x}), prompt_prefix, None)
  149. negative_prompt.change(lambda x: params.update({"negative_prompt": x}), negative_prompt, None)
  150. dimensions.change(lambda x: params.update({"side_length": x}), dimensions, None)
  151. # model.change(lambda x: params.update({"SD_model": x}), model, None)
  152. force_btn.click(force_pic)
  153. generate_now_btn.click(force_pic)
  154. generate_now_btn.click(eval('chat.cai_chatbot_wrapper'), shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream)