dikdimon commited on
Commit
4ad8272
·
verified ·
1 Parent(s): d7cdd26

Update asymmetric-tiling-sd-webui-2.0/scripts/asymmetric_tiling_UNIFIED.py

Browse files
asymmetric-tiling-sd-webui-2.0/scripts/asymmetric_tiling_UNIFIED.py CHANGED
@@ -12,6 +12,14 @@ import numpy as np
12
  from collections import OrderedDict
13
 
14
  from PIL import Image
 
 
 
 
 
 
 
 
15
  # ========================================================================
16
  # КОНСТАНТЫ И КОНФИГУРАЦИЯ
17
  # ========================================================================
@@ -1632,44 +1640,6 @@ def compute_hex_padding_x(input_tensor, pad_l, pad_r):
1632
 
1633
  return torch.cat([left_pad, input_tensor, right_pad], dim=3)
1634
 
1635
- def compute_blend_overlay(padded, pad_h, pad_w, blend_strength=0.1):
1636
- """
1637
- Мягкое смешивание краев поверх уже примененного паддинга.
1638
- Работает с любым базовым режимом.
1639
- NOTE: This applies blend as an overlay on already-padded tensor.
1640
- For creating padding from scratch with blend, use compute_blend_padding().
1641
- """
1642
- b, c, H, W = padded.shape
1643
-
1644
- h = max(H - 2 * pad_h, 0)
1645
- w = max(W - 2 * pad_w, 0)
1646
-
1647
- if h <= 0 or w <= 0:
1648
- return padded
1649
-
1650
- blend_w = min(int(w * blend_strength), w)
1651
- blend_h = min(int(h * blend_strength), h)
1652
-
1653
- if blend_h > 0 and pad_h > 0:
1654
- top_mask = torch.linspace(0.0, 1.0, steps=blend_h, device=padded.device, dtype=padded.dtype)
1655
- top_mask = top_mask.view(1, 1, blend_h, 1).expand(b, c, blend_h, W)
1656
- padded[:, :, pad_h:pad_h + blend_h, :] *= top_mask
1657
-
1658
- bottom_mask = torch.linspace(1.0, 0.0, steps=blend_h, device=padded.device, dtype=padded.dtype)
1659
- bottom_mask = bottom_mask.view(1, 1, blend_h, 1).expand(b, c, blend_h, W)
1660
- padded[:, :, pad_h + h - blend_h:pad_h + h, :] *= bottom_mask
1661
-
1662
- if blend_w > 0 and pad_w > 0:
1663
- left_mask = torch.linspace(0.0, 1.0, steps=blend_w, device=padded.device, dtype=padded.dtype)
1664
- left_mask = left_mask.view(1, 1, 1, blend_w).expand(b, c, H, blend_w)
1665
- padded[:, :, :, pad_w:pad_w + blend_w] *= left_mask
1666
-
1667
- right_mask = torch.linspace(1.0, 0.0, steps=blend_w, device=padded.device, dtype=padded.dtype)
1668
- right_mask = right_mask.view(1, 1, 1, blend_w).expand(b, c, H, blend_w)
1669
- padded[:, :, :, pad_w + w - blend_w:pad_w + w] *= right_mask
1670
-
1671
- return padded
1672
-
1673
  # ========================================================================
1674
  # ГЛАВНАЯ ФУНКЦИЯ ПАДДИНГА
1675
  # ========================================================================
@@ -1784,15 +1754,26 @@ def custom_padding_forward(input_tensor, weight, bias, stride, padding, dilation
1784
  )
1785
  # Multi-resolution blend (keeps original behavior but in output space)
1786
  if params.get('multires_enabled', False):
1787
- denom = max(int(params['end_step']) - int(params['start_step']), 1)
1788
- step_ratio = (current_step - int(params['start_step'])) / denom
1789
- step_ratio = max(0.0, min(float(step_ratio), 1.0))
1790
- if step_ratio < 0.3:
1791
- x_default = F.pad(input_tensor, (req_pad_w, req_pad_w, req_pad_h, req_pad_h),
1792
- mode='constant', value=0)
1793
- out_default = F.conv2d(x_default, weight, bias, stride, 0, dilation, groups)
1794
- alpha = step_ratio / 0.3 # 0..1
1795
- out_cube = out_cube * alpha + out_default * (1.0 - alpha)
 
 
 
 
 
 
 
 
 
 
 
1796
 
1797
  return out_cube
1798
  # Панорама
@@ -1846,15 +1827,26 @@ def custom_padding_forward(input_tensor, weight, bias, stride, padding, dilation
1846
 
1847
  # Multi-resolution blend (output-space) — same policy as cubemap
1848
  if params.get('multires_enabled', False):
1849
- denom = max(int(params['end_step']) - int(params['start_step']), 1)
1850
- step_ratio = (current_step - int(params['start_step'])) / denom
1851
- step_ratio = max(0.0, min(float(step_ratio), 1.0))
1852
- if step_ratio < 0.3:
1853
- x_default = F.pad(input_tensor, (req_pad_w, req_pad_w, req_pad_h, req_pad_h),
1854
- mode='constant', value=0)
1855
- out_default = F.conv2d(x_default, weight, bias, stride, 0, dilation, groups)
1856
- alpha = step_ratio / 0.3 # 0..1
1857
- out_pano = out_pano * alpha + out_default * (1.0 - alpha)
 
 
 
 
 
 
 
 
 
 
 
1858
 
1859
  return out_pano
1860
 
@@ -1928,19 +1920,52 @@ def custom_padding_forward(input_tensor, weight, bias, stride, padding, dilation
1928
 
1929
  # Дополнительный мягкий бленд поверх выбранного режима
1930
  if params.get('blend_enabled', False) and (req_pad_h > 0 or req_pad_w > 0):
1931
- blend_str = params.get('blend_strength', 0.1)
1932
- x = compute_blend_overlay(x, req_pad_h, req_pad_w, blend_str)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1933
 
1934
  # Мультиразрешение
1935
  if params.get('multires_enabled', False):
1936
- denom = max(int(params['end_step']) - int(params['start_step']), 1)
1937
- step_ratio = (current_step - int(params['start_step'])) / denom
1938
- step_ratio = max(0.0, min(float(step_ratio), 1.0))
1939
- if step_ratio < 0.3:
1940
- x_default = F.pad(input_tensor, (req_pad_w, req_pad_w, req_pad_h, req_pad_h),
1941
- mode='constant', value=0)
1942
- alpha = step_ratio * 3
1943
- x = x * alpha + x_default * (1 - alpha)
 
 
 
 
 
 
 
 
 
 
1944
 
1945
  return F.conv2d(x, weight, bias, stride, 0, dilation, groups)
1946
 
@@ -2109,9 +2134,89 @@ class AdvancedTilingScriptV3(scripts.Script):
2109
  )
2110
 
2111
  with gr.Row():
2112
- multires = gr.Checkbox(label="Multi-Resolution Mode", value=False)
2113
- use_blend = gr.Checkbox(label="Soft Blend Edges", value=False)
2114
- blend_strength = gr.Slider(0.0, 0.5, step=0.05, label="Blend Strength", value=0.1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2115
 
2116
  # NEW ENHANCED MODES Parameters
2117
  with gr.Accordion("✨ NEW Enhanced Modes Parameters", open=False):
@@ -2771,7 +2876,7 @@ class AdvancedTilingScriptV3(scripts.Script):
2771
  enabled, mode_x, mode_y,
2772
  start_step, end_step,
2773
  step_mode, step_start_frac, step_end_frac,
2774
- multires,
2775
  voronoi_cells, voronoi_seed,
2776
  perlin_strength, perlin_scale,
2777
  fractal_iterations, fractal_scale,
@@ -2786,7 +2891,7 @@ class AdvancedTilingScriptV3(scripts.Script):
2786
  panorama_grid_interp, panorama_grid_padding, panorama_cache_angle_quant,
2787
  use_cubemap, cubemap_engine, cubemap_resolution_mode, cubemap_pad_mode, cubemap_blend_width, cubemap_blend_strength,
2788
  cubemap_yaw, cubemap_pitch, cubemap_roll, cubemap_coord_mode, cubemap_twist_deg, cubemap_polar_scale, cubemap_polar_power, cubemap_swirl_deg, cubemap_swirl_power, cubemap_grid_interp, cubemap_grid_padding, cubemap_cache_angle_quant, cubemap_geoaa_samples, cubemap_geoaa_radius, cubemap_antipode_strength,
2789
- use_blend, blend_strength,
2790
  use_anisotropic, aniso_angle, aniso_angle2, aniso_angle_mix,
2791
  stereo_enabled, stereo_eye, stereo_engine, stereo_output, stereo_in_model, stereo_separation, stereo_convergence, stereo_depth_power, stereo_pole_power,
2792
  patch_vae, tiling_disable_hr, use_kohaku,
@@ -2971,6 +3076,10 @@ class AdvancedTilingScriptV3(scripts.Script):
2971
  'start_step': start_step,
2972
  'end_step': end_step,
2973
  'multires_enabled': multires,
 
 
 
 
2974
  # NEW ENHANCED MODES parameters
2975
  'voronoi_cells': voronoi_cells,
2976
  'voronoi_seed': voronoi_seed,
@@ -3002,6 +3111,9 @@ class AdvancedTilingScriptV3(scripts.Script):
3002
  'panorama_cache_angle_quant': panorama_cache_angle_quant,
3003
  'blend_enabled': use_blend,
3004
  'blend_strength': blend_strength,
 
 
 
3005
  'cubemap_engine': cubemap_engine,
3006
  'cubemap_pad_mode': cubemap_pad_mode,
3007
  'cubemap_blend_width': cubemap_blend_width,
 
12
  from collections import OrderedDict
13
 
14
  from PIL import Image
15
+ from improved_tiling_functions import (
16
+ compute_advanced_blend_padding,
17
+ apply_multires_blend,
18
+ validate_blend_params,
19
+ validate_multires_params,
20
+ BlendStrategy,
21
+ MultiResStrategy
22
+ )
23
  # ========================================================================
24
  # КОНСТАНТЫ И КОНФИГУРАЦИЯ
25
  # ========================================================================
 
1640
 
1641
  return torch.cat([left_pad, input_tensor, right_pad], dim=3)
1642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1643
  # ========================================================================
1644
  # ГЛАВНАЯ ФУНКЦИЯ ПАДДИНГА
1645
  # ========================================================================
 
1754
  )
1755
  # Multi-resolution blend (keeps original behavior but in output space)
1756
  if params.get('multires_enabled', False):
1757
+ multires_params = validate_multires_params(params)
1758
+
1759
+ # Создаем простой padding (для сравнения)
1760
+ x_simple = F.pad(input_tensor, (req_pad_w, req_pad_w, req_pad_h, req_pad_h),
1761
+ mode='replicate')
1762
+
1763
+ # Применяем смешивание ПЕРЕД конволюцией
1764
+ # (для input-space blending)
1765
+ x = apply_multires_blend(
1766
+ tensor_simple=x_simple,
1767
+ tensor_advanced=x, # x уже содержит продвинутый padding
1768
+ current_step=current_step,
1769
+ start_step=params['start_step'],
1770
+ end_step=params['end_step'],
1771
+ strategy=multires_params['strategy'],
1772
+ transition_start=multires_params['transition_start'],
1773
+ transition_end=multires_params['transition_end'],
1774
+ sharpness=multires_params['sharpness'],
1775
+ enabled=True
1776
+ )
1777
 
1778
  return out_cube
1779
  # Панорама
 
1827
 
1828
  # Multi-resolution blend (output-space) — same policy as cubemap
1829
  if params.get('multires_enabled', False):
1830
+ multires_params = validate_multires_params(params)
1831
+
1832
+ # Простая версия (output space)
1833
+ x_default = F.pad(input_tensor, (req_pad_w, req_pad_w, req_pad_h, req_pad_h),
1834
+ mode='replicate')
1835
+ out_default = F.conv2d(x_default, weight, bias, stride, 0, dilation, groups)
1836
+
1837
+ # Применяем улучшенное смешивание
1838
+ out_pano = apply_multires_blend(
1839
+ tensor_simple=out_default,
1840
+ tensor_advanced=out_pano,
1841
+ current_step=current_step,
1842
+ start_step=params['start_step'],
1843
+ end_step=params['end_step'],
1844
+ strategy=multires_params['strategy'],
1845
+ transition_start=multires_params['transition_start'],
1846
+ transition_end=multires_params['transition_end'],
1847
+ sharpness=multires_params['sharpness'],
1848
+ enabled=True
1849
+ )
1850
 
1851
  return out_pano
1852
 
 
1920
 
1921
  # Дополнительный мягкий бленд поверх выбранного режима
1922
  if params.get('blend_enabled', False) and (req_pad_h > 0 or req_pad_w > 0):
1923
+ blend_params = validate_blend_params(params)
1924
+
1925
+ # Определяем простой режим
1926
+ mode_simple = 'replicate' # или 'constant'
1927
+
1928
+ # x уже содержит результат продвинутого padding
1929
+ # Нам нужно смешать его с простым режимом
1930
+
1931
+ # Метод 1: Применяем blend прямо на x (если x уже западдингован)
1932
+ # В этом случае нужно создать simple версию
1933
+ x_simple = F.pad(input_tensor, (req_pad_w, req_pad_w, req_pad_h, req_pad_h),
1934
+ mode=mode_simple)
1935
+
1936
+ # Смешиваем
1937
+ x = compute_advanced_blend_padding(
1938
+ input_tensor,
1939
+ pad_h=req_pad_h,
1940
+ pad_w=req_pad_w,
1941
+ mode_simple=mode_simple,
1942
+ mode_advanced=x, # Передаем уже готовый тензор
1943
+ blend_strength=blend_params['strength'],
1944
+ blend_width=blend_params['width'],
1945
+ falloff_curve=blend_params['falloff'],
1946
+ edge_sharpness=blend_params['sharpness']
1947
+ )
1948
 
1949
  # Мультиразрешение
1950
  if params.get('multires_enabled', False):
1951
+ multires_params = validate_multires_params(params)
1952
+
1953
+ x_default = F.pad(input_tensor, (req_pad_w, req_pad_w, req_pad_h, req_pad_h),
1954
+ mode='replicate')
1955
+ out_default = F.conv2d(x_default, weight, bias, stride, 0, dilation, groups)
1956
+
1957
+ out_pano = apply_multires_blend(
1958
+ tensor_simple=out_default,
1959
+ tensor_advanced=out_pano,
1960
+ current_step=current_step,
1961
+ start_step=params['start_step'],
1962
+ end_step=params['end_step'],
1963
+ strategy=multires_params['strategy'],
1964
+ transition_start=multires_params['transition_start'],
1965
+ transition_end=multires_params['transition_end'],
1966
+ sharpness=multires_params['sharpness'],
1967
+ enabled=True
1968
+ )
1969
 
1970
  return F.conv2d(x, weight, bias, stride, 0, dilation, groups)
1971
 
 
2134
  )
2135
 
2136
  with gr.Row():
2137
+ multires = gr.Checkbox(
2138
+ label="Multi-Resolution Mode",
2139
+ value=False,
2140
+ info="Gradually transition from simple to advanced tiling"
2141
+ )
2142
+ use_blend = gr.Checkbox(
2143
+ label="Advanced Blend Mode",
2144
+ value=False,
2145
+ info="Smart blending between padding modes (NEW!)"
2146
+ )
2147
+ blend_strength = gr.Slider(
2148
+ 0.0, 1.0, step=0.05,
2149
+ label="Blend Strength (0=simple, 1=advanced)",
2150
+ value=0.5,
2151
+ info="Controls proximity/zoom effect"
2152
+ )
2153
+
2154
+ # ═══ NEW: ADVANCED BLEND SETTINGS ═══
2155
+ with gr.Accordion("🎨 Advanced Blend Settings", open=False):
2156
+ gr.Markdown("""
2157
+ **Blend Mode улучшен!** Теперь это настоящий слайдер приближения/отдаления:
2158
+ - `0.0` = далеко (простой padding)
2159
+ - `0.5` = средняя дистанция (смешивание)
2160
+ - `1.0` = близко (полный advanced tiling)
2161
+ """)
2162
+
2163
+ with gr.Row():
2164
+ blend_falloff = gr.Dropdown(
2165
+ label="Falloff Curve",
2166
+ choices=["linear", "smoothstep", "cosine", "perceptual"],
2167
+ value="smoothstep",
2168
+ info="Shape of the transition gradient"
2169
+ )
2170
+ blend_sharpness = gr.Slider(
2171
+ 0.1, 5.0, step=0.1,
2172
+ label="Edge Sharpness",
2173
+ value=1.0,
2174
+ info="<1 = softer, >1 = sharper transitions"
2175
+ )
2176
+
2177
+ blend_width = gr.Slider(
2178
+ 0, 128, step=8,
2179
+ label="Blend Width (pixels, 0=auto)",
2180
+ value=0,
2181
+ info="Width of transition zone"
2182
+ )
2183
+
2184
+ # ═══ NEW: ADVANCED MULTI-RESOLUTION SETTINGS ═══
2185
+ with gr.Accordion("🔬 Advanced Multi-Resolution Settings", open=False):
2186
+ gr.Markdown("""
2187
+ **Multi-Resolution улучшен!** Гибкие стратегии и параметры:
2188
+ - **Cosine**: плавная (рекомендуется)
2189
+ - **Exponential**: быстрый старт
2190
+ - **Sigmoid**: S-кривая
2191
+ """)
2192
+
2193
+ multires_strategy = gr.Dropdown(
2194
+ label="Interpolation Strategy",
2195
+ choices=["linear", "cosine", "exponential", "sigmoid", "early_boost", "late_smooth"],
2196
+ value="cosine",
2197
+ info="How to blend simple → advanced"
2198
+ )
2199
+
2200
+ with gr.Row():
2201
+ multires_start = gr.Slider(
2202
+ 0.0, 1.0, step=0.05,
2203
+ label="Transition Start",
2204
+ value=0.0,
2205
+ info="When to begin transition (0.0 = from start)"
2206
+ )
2207
+ multires_end = gr.Slider(
2208
+ 0.0, 1.0, step=0.05,
2209
+ label="Transition End",
2210
+ value=0.3,
2211
+ info="When to finish transition (0.3 = at 30%)"
2212
+ )
2213
+
2214
+ multires_sharpness = gr.Slider(
2215
+ 0.1, 5.0, step=0.1,
2216
+ label="Transition Sharpness",
2217
+ value=1.0,
2218
+ info="Speed of transition (<1 = slower, >1 = faster)"
2219
+ )
2220
 
2221
  # NEW ENHANCED MODES Parameters
2222
  with gr.Accordion("✨ NEW Enhanced Modes Parameters", open=False):
 
2876
  enabled, mode_x, mode_y,
2877
  start_step, end_step,
2878
  step_mode, step_start_frac, step_end_frac,
2879
+ multires, multires_strategy, multires_start, multires_end, multires_sharpness,
2880
  voronoi_cells, voronoi_seed,
2881
  perlin_strength, perlin_scale,
2882
  fractal_iterations, fractal_scale,
 
2891
  panorama_grid_interp, panorama_grid_padding, panorama_cache_angle_quant,
2892
  use_cubemap, cubemap_engine, cubemap_resolution_mode, cubemap_pad_mode, cubemap_blend_width, cubemap_blend_strength,
2893
  cubemap_yaw, cubemap_pitch, cubemap_roll, cubemap_coord_mode, cubemap_twist_deg, cubemap_polar_scale, cubemap_polar_power, cubemap_swirl_deg, cubemap_swirl_power, cubemap_grid_interp, cubemap_grid_padding, cubemap_cache_angle_quant, cubemap_geoaa_samples, cubemap_geoaa_radius, cubemap_antipode_strength,
2894
+ use_blend, blend_strength, blend_falloff, blend_sharpness, blend_width,
2895
  use_anisotropic, aniso_angle, aniso_angle2, aniso_angle_mix,
2896
  stereo_enabled, stereo_eye, stereo_engine, stereo_output, stereo_in_model, stereo_separation, stereo_convergence, stereo_depth_power, stereo_pole_power,
2897
  patch_vae, tiling_disable_hr, use_kohaku,
 
3076
  'start_step': start_step,
3077
  'end_step': end_step,
3078
  'multires_enabled': multires,
3079
+ 'multires_strategy': multires_strategy, # NEW
3080
+ 'multires_start': multires_start, # NEW
3081
+ 'multires_end': multires_end, # NEW
3082
+ 'multires_sharpness': multires_sharpness, # NEW
3083
  # NEW ENHANCED MODES parameters
3084
  'voronoi_cells': voronoi_cells,
3085
  'voronoi_seed': voronoi_seed,
 
3111
  'panorama_cache_angle_quant': panorama_cache_angle_quant,
3112
  'blend_enabled': use_blend,
3113
  'blend_strength': blend_strength,
3114
+ 'blend_falloff': blend_falloff, # NEW
3115
+ 'blend_sharpness': blend_sharpness, # NEW
3116
+ 'blend_width': blend_width if blend_width > 0 else None, # NEW
3117
  'cubemap_engine': cubemap_engine,
3118
  'cubemap_pad_mode': cubemap_pad_mode,
3119
  'cubemap_blend_width': cubemap_blend_width,