script.py 7.9 KB

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