File size: 13,595 Bytes
f4a41d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import json,os
from modules.paths_internal import data_path

PNGINFO_2_LIGHTDIFFUSIONFLOW = {}
PNGINFO_CN_2_LIGHTDIFFUSIONFLOW = {}
Image_Components_Key = {}
LoRAs_In_Use = "loras_in_use"
Flow_Save_mode = "All"
Auto_Fix_Params = True
Local_Flows_Path = "models/LightDiffusionFlow"

class OutputPrompt_English:

  def startimport():
    return "<hr style='margin-top:10px;margin-bottom:10px'></hr><b style='color:LimeGreen;'>Start parsing settings...</b>"

  def invalid_file():
    return "<b style='color:Red;'>Please select a valid lightdiffusionflow or image file!</b>"

  def importing_image(image_name):
    return f"<b style='color:LimeGreen;'>Importing image: '{image_name}'.</b>"

  def import_completed():
    return "<b style='color:LimeGreen;'>Import Completed!</b>"

  def import_completed_info():
    return "Import Completed!"
  
  def save_completed():
    return "<b style='color:LimeGreen;'>Save Completed!</b>"

  def save_failed():
    return "<b style='color:Red;'>Save Failed!</b>"

  def alternative_option(target_value, new_value):
    return f'''Note: '<b style='color:Orange;'>{target_value}</b>' not found,<br>\
      An approximate match '<b style='color:Orange;'>{new_value}</b>' has been automatically selected as replacement.'''

  def no_option(option_name, value):
    return f'''Error: '<b style='color:Red;'>{option_name}</b>' import failed!<br>\
    The option '<b style='color:Red;'>{value}</b>' was not found!'''

  def missing_extensions(ext_list:[]):
    if(Flow_Save_mode == "Core"):
      error_str = "Note:  <b style='color:Orange;'>The current flow file contains parameters for other plugins:</b></p>"
      for ext in ext_list:
        error_str+="<p>- <b style='color:Orange;'>"+ext+"</b></p> "
      error_str+="<b style='color:Orange;'>You can switch to 'ALL' mode to load more parameters. (This prompt is for reference only, please choose the plugin mode according to the actual situation.)</b></p> "
    else:
      error_str = "Note: <b style='color:Orange;'>Found missing extensions.</b></p>"
      for ext in ext_list:
        error_str+="<p>- <b style='color:Orange;'>"+ext+"</b></p> "
      error_str+="<b style='color:Orange;'>The above Extension Missing Reminder is for reference only. Please determine the necessary plugins based on your actual needs and specific conditions.</b></p> "
    return error_str

  def missing_loras(loras_list:[]):
    error_str = "Note: <b style='color:Orange;'>Found missing LoRAs.</b></p>"
    for lora in loras_list:
      error_str+="<p>- <b style='color:Orange;'>"+lora+"</b></p> "
    return error_str

  def click_to_download(file_name, file_url):
    return f'''<p style="color:Orange;">Click to download \
    <a style ='text-decoration:underline;color:cornflowerblue;', target="_blank", href='{file_url}'> {file_name} </a>
    '''

  def download_link(file_name, file_url):
    return f'''<a style ='text-decoration:underline;color:cornflowerblue;', target="_blank", href='{file_url}'> {file_name} </a>'''

  def note_for_save_mode():
    return "Core mode only supports basic parameters for Text-to-Image and Image-to-Image, along with ControlNet parameters. \
The All mode, on the other hand, aims to support as many parameters as possible on the page, \
but the downside is that it may occasionally cause the UI to freeze with an infinite loading circle."

class OutputPrompt_Chinese:

  def startimport():
    return "<hr style='margin-top:10px;margin-bottom:10px'></hr><b style='color:LimeGreen;'>开始解析设置...</b>"

  def invalid_file():
    return "<b style='color:Red;'>请选择一个有效的flow文件,或者含png_info数据的图片!</b>"

  def importing_image(image_name):
    return f"<b style='color:LimeGreen;'>导入图片'{image_name}'...</b>"

  def import_completed():
    return "<b style='color:LimeGreen;'>导入完成!</b>"
    
  def import_completed_info():
    return "导入完成!"

  def save_completed():
    return "<b style='color:LimeGreen;'>保存完毕!</b>"

  def save_failed():
    return "<b style='color:Red;'>保存失败!</b>"

  def alternative_option(target_value, new_value):
    return f'''注意: 未找到选项'<b style='color:Orange;'>{target_value}</b>',<br>\
      已使用近似选项'<b style='color:Orange;'>{new_value}</b>'代替.'''

  def no_option(option_name, value):
    if(option_name == "stable diffusion checkpoint"):
      return f'''未找到大模型'<b style='color:Orange;'>{value}</b>'!'''
    clear_option_name = option_name.replace("state-ext-","")
    return f'''错误: '<b style='color:Red;'>{clear_option_name}</b>'导入失败!<br>\
    未找到选项'<b style='color:Red;'>{value}</b>'!'''

  def missing_extensions(ext_list:[]):
    global Flow_Save_mode
    if(Flow_Save_mode == "Core"):
      error_str = "注意, <b style='color:Orange;'>当前flow文件含有其他插件参数:</b></p>"
      for ext in ext_list:
        error_str+="<p>- <b style='color:Orange;'>"+ext+"</b></p> "
      error_str+="<b style='color:Orange;'>可切换至'ALL'模式加载更多参数。(提示仅供参考,请根据实际情况选择插件模式。)</b></p> "
    else:
      error_str = "注意, <b style='color:Orange;'>发现缺失的插件:</b></p>"
      for ext in ext_list:
        error_str+="<p>- <b style='color:Orange;'>"+ext+"</b></p> "
      error_str+="<b style='color:Orange;'>以上插件缺失提示仅供参考,请注意辨别实际情况下您所需要安装的插件。</b></p> "
    return error_str

  def missing_loras(loras_list:[]):
    error_str = "注意, <b style='color:Orange;'>发现缺失的LoRA模型:</b></p>"
    for lora in loras_list:
      error_str+="<p>- <b style='color:Orange;'>"+lora+"</b></p> "
    return error_str

  def click_to_download(file_name, file_url):
    name = file_name
    if(name == "ControlNet Models"):
      name = "常用ControlNet模型"
      return f'''<p style="color:Orange;">点击下载 \
      <a style ='text-decoration:underline;color:cornflowerblue;', target="_blank", href='https://pan.quark.cn/s/eafa2a9df949'> 常用ControlNet模型 </a>
      '''

    return f'''<p style="color:Orange;">点击下载 \
    <a style ='text-decoration:underline;color:cornflowerblue;', target="_blank", href='{file_url}'> {name} </a>
    '''

  def download_link(file_name, file_url):
    return f'''<a style ='text-decoration:underline;color:cornflowerblue;', target="_blank", href='{file_url}'> {file_name} </a>'''

  def note_for_save_mode():
    return "Core模式仅支持文生图和图生图的基本参数+ControlNet参数。All模式则会尽可能多的支持页面上的参数,但是缺点是有概率导致UI卡住,无限转圈。"


OutputPrompt = OutputPrompt_English

def create_local_flow_path():
  global Local_Flows_Path
  
  if os.path.isabs(Local_Flows_Path):
    flows_path = Local_Flows_Path
  else:
    flows_path = os.path.join(data_path, Local_Flows_Path) 
  flows_path = flows_path.replace("\\","/") # linux下反斜杠有问题
  #print(flows_path)
  try:
    if(not os.path.exists(flows_path)):
      os.makedirs(flows_path)
      if(os.path.exists(flows_path)):
        print(f"本地文件夹'{flows_path}'创建成功!")
      else:
        print(f"本地文件夹'{flows_path}'创建失败!")
  except BaseException as e:
    pass
  if(not os.path.exists(flows_path)):
    print(f"The creation of the folder '{Local_Flows_Path}' has failed! Please create this folder manually to ensure the proper functioning of the extension.")
    print(f"创建文件夹'{Local_Flows_Path}'失败!请手动创建该文件夹,以保证插件功能正常运行。")

  Local_Flows_Path = flows_path


# 改成函数调用,修改配置之后能及时刷新
def init():
  global PNGINFO_2_LIGHTDIFFUSIONFLOW,PNGINFO_CN_2_LIGHTDIFFUSIONFLOW
  global OutputPrompt,Flow_Save_mode,Auto_Fix_Params,Local_Flows_Path,Image_Components_Key
  # PNG Info的功能除了主要的选项以外其他的都靠第三方插件的主动支持,后续再考虑能否有优化的办法
  #print(parameters_copypaste.paste_fields) 
  PNGINFO_2_LIGHTDIFFUSIONFLOW = {
    "Prompt": "state-txt2img_prompt",
    "Negative prompt": "state-txt2img_neg_prompt",
    "Steps": "state-txt2img_steps",
    "Sampler": "state-txt2img_sampling",
    "CFG scale": "state-txt2img_cfg_scale",
    "Seed": "state-txt2img_seed",
    "Face restoration": "state-txt2img_restore_faces",
    "Size-1": "state-txt2img_width",
    "Size-2": "state-txt2img_height",
    "Model hash": "state-setting_sd_model_checkpoint",
    "Denoising strength": "state-txt2img_denoising_strength",
    "Hires upscale": "state-txt2img_hr_scale",
    "Hires steps": "state-txt2img_hires_steps",
    "Hires upscaler": "state-txt2img_hr_upscaler",
    "Hires resize-1": "state-txt2img_hr_resize_x",
    "Hires resize-2": "state-txt2img_hr_resize_y",
    "Clip skip": "setting_CLIP_stop_at_last_layers",
    "ENSD": "setting_eta_noise_seed_delta"
  }

  PNGINFO_CN_2_LIGHTDIFFUSIONFLOW = {
    "Module": "state-ext-control-net-txt2img_0-preprocessor",
    "preprocessor": "state-ext-control-net-txt2img_0-preprocessor",
    "model": "state-ext-control-net-txt2img_0-model",
    "weight": "state-ext-control-net-txt2img_0-control-weight",
    "starting": "state-ext-control-net-txt2img_0-starting-control-step",
    "ending": "state-ext-control-net-txt2img_0-guidance-end-(t)",
    "guidance start": "state-ext-control-net-txt2img_0-starting-control-step",
    "guidance end": "state-ext-control-net-txt2img_0-ending-control-step",
    "resize mode": "state-ext-control-net-txt2img_0-resize-mode",
    "pixel perfect": "state-ext-control-net-txt2img_0-pixel-perfect",
    "control mode": "state-ext-control-net-txt2img_0-control-mode",
    "preprocessor params": ""
  }

  try:
    import modules.shared as shared
    webui_settings = {}
    with open(shared.cmd_opts.ui_settings_file, mode='r') as f:
      json_str = f.read()
      webui_settings = json.loads(json_str)

      # 保存模式
      try:
        Flow_Save_mode = webui_settings["lightdiffusionflow-mode"]
      except:
        pass

      # 自动纠正错误的参数
      try:
        Auto_Fix_Params = webui_settings["lightdiffusionflow-auto-fix-params"]
      except:
        pass

      # 本地flow保存位置,先读本地设置,再读命令行设置
      try:
        Local_Flows_Path = webui_settings["lightdiffusionflow-local-flows-path"]
      except:
        pass
      if shared.cmd_opts.local_flows_path:
        Local_Flows_Path = shared.cmd_opts.local_flows_path
      create_local_flow_path()


      language_successed = False
      auto_language = False
      try:
        # 优先读取自己的设置
        if(webui_settings['lightdiffusionflow-language'] == "default"):
          auto_language = True
        elif(webui_settings['lightdiffusionflow-language'] == "english"):
          OutputPrompt = OutputPrompt_English
          language_successed = True
        else:
          OutputPrompt = OutputPrompt_Chinese
          language_successed = True
      except:
        OutputPrompt = OutputPrompt_English
      
      # 如果是default就读取其他设置配合
      if(auto_language and not language_successed):
        # 自带的本地化文件
        localization_files = ["zh_CN", "zh-Hans (Stable) [vladmandic]", "zh-Hans (Stable)",
          "zh-Hans (Testing) [vladmandic]", "zh-Hans (Testing)","chinese-all-1024","chinese-english-1024"]
        try:
          # 如果用户使用了中文汉化文件,插件也默认显示中文
          localization_files.index(webui_settings["localization"])
          OutputPrompt = OutputPrompt_Chinese
          language_successed = True
        except:
          pass
        
        # 第三方翻译插件bilingual-localization
        if(not language_successed):
          try:
            if(webui_settings["bilingual_localization_enabled"] and webui_settings["bilingual_localization_file"] != "None"):
              OutputPrompt = OutputPrompt_Chinese
              language_successed = True
          except:
            OutputPrompt = OutputPrompt_English
  except:
    pass

  Image_Components_Key = [
    # 第一个组件是用来预计算第一张有效图的索引 防止出现有没用的页面跳转
    "useless_Textbox", 
    # 每个图片组件的elem_id
    "img2img_image","img2img_sketch","img2maskimg","inpaint_sketch","img_inpaint_base","img_inpaint_mask", 
    ] # 只保存图片组件id,其他参数js里搞定


  # # init number of controlnet
  # try:
  #   webui_settings = {}
  #   with open(shared.cmd_opts.ui_settings_file, mode='r') as f:
  #     json_str = f.read()
  #     webui_settings = json.loads(json_str)
    
  #   Multi_ControlNet = webui_settings.get("control_net_unit_count", None) # controlnet数量,新版名字
  #   if(Multi_ControlNet == None):
  #     Multi_ControlNet = webui_settings.get("control_net_max_models_num", 0)
  #   print(f"Multi_ControlNet = {Multi_ControlNet}")
  #   if(Multi_ControlNet == 1):
  #     Image_Components_Key.append(f"txt2img_controlnet_ControlNet_input_image")
  #     Image_Components_Key.append(f"img2img_controlnet_ControlNet_input_image")
  #   else:
  #     for i in range(Multi_ControlNet):
  #       Image_Components_Key.append(f"txt2img_controlnet_ControlNet-{i}_input_image")
  #       Image_Components_Key.append(f"img2img_controlnet_ControlNet-{i}_input_image")
        
  # except:
  #   pass

  # # Segment Anything images
  # Image_Components_Key.extend(["txt2img_sam_input_image","img2img_sam_input_image"])



init()