script.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. image.thumbnail((300, 300))
  78. buffered = io.BytesIO()
  79. image.save(buffered, format="JPEG")
  80. buffered.seek(0)
  81. image_bytes = buffered.getvalue()
  82. img_str = "data:image/jpeg;base64," + base64.b64encode(image_bytes).decode()
  83. visible_result = visible_result + f'<img src="{img_str}" alt="{description}">\n'
  84. return visible_result
  85. # TODO: how do I make the UI history ignore the resulting pictures (I don't want HTML to appear in history)
  86. # and replace it with 'text' for the purposes of logging?
  87. def output_modifier(string):
  88. """
  89. This function is applied to the model outputs.
  90. """
  91. global pic_id, picture_response, streaming_state
  92. if not picture_response:
  93. return string
  94. string = remove_surrounded_chars(string)
  95. string = string.replace('"', '')
  96. string = string.replace('“', '')
  97. string = string.replace('\n', ' ')
  98. string = string.strip()
  99. if string == '':
  100. string = 'no viable description in reply, try regenerating'
  101. # 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
  102. text = f'*Description: "{string}"*'
  103. image = get_SD_pictures(string)
  104. picture_response = False
  105. shared.processing_message = "*Is typing...*"
  106. shared.args.no_stream = streaming_state
  107. return image + "\n" + text
  108. def bot_prefix_modifier(string):
  109. """
  110. This function is only applied in chat mode. It modifies
  111. the prefix text for the Bot and can be used to bias its
  112. behavior.
  113. """
  114. return string
  115. def force_pic():
  116. global picture_response
  117. picture_response = True
  118. def ui():
  119. # Gradio elements
  120. with gr.Accordion("Stable Diffusion api integration", open=True):
  121. with gr.Row():
  122. with gr.Column():
  123. enable = gr.Checkbox(value=params['enable_SD_api'], label='Activate SD Api integration')
  124. save_img = gr.Checkbox(value=params['save_img'], label='Keep original received images in the outputs subdir')
  125. with gr.Column():
  126. address = gr.Textbox(placeholder=params['address'], value=params['address'], label='Stable Diffusion host address')
  127. with gr.Row():
  128. force_btn = gr.Button("Force the next response to be a picture")
  129. generate_now_btn = gr.Button("Generate an image response to the input")
  130. with gr.Accordion("Generation parameters", open=False):
  131. prompt_prefix = gr.Textbox(placeholder=params['prompt_prefix'], value=params['prompt_prefix'], label='Prompt Prefix (best used to describe the look of the character)')
  132. with gr.Row():
  133. negative_prompt = gr.Textbox(placeholder=params['negative_prompt'], value=params['negative_prompt'], label='Negative Prompt')
  134. dimensions = gr.Slider(256, 702, value=params['side_length'], step=64, label='Image dimensions')
  135. # model = gr.Dropdown(value=SD_models[0], choices=SD_models, label='Model')
  136. # Event functions to update the parameters in the backend
  137. enable.change(lambda x: params.update({"enable_SD_api": x}), enable, None)
  138. save_img.change(lambda x: params.update({"save_img": x}), save_img, None)
  139. address.change(lambda x: params.update({"address": x}), address, None)
  140. prompt_prefix.change(lambda x: params.update({"prompt_prefix": x}), prompt_prefix, None)
  141. negative_prompt.change(lambda x: params.update({"negative_prompt": x}), negative_prompt, None)
  142. dimensions.change(lambda x: params.update({"side_length": x}), dimensions, None)
  143. # model.change(lambda x: params.update({"SD_model": x}), model, None)
  144. force_btn.click(force_pic)
  145. generate_now_btn.click(force_pic)
  146. generate_now_btn.click(chat.cai_chatbot_wrapper, shared.input_params, shared.gradio['display'], show_progress=shared.args.no_stream)