script.py 7.4 KB

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