FajarHidaa commited on
Commit
482a64d
Β·
verified Β·
1 Parent(s): f5606c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +359 -183
app.py CHANGED
@@ -1,14 +1,17 @@
1
  """
2
- Nesting Otomatis Banner v2 β€” Super Optimized (Fixed & Form Input)
 
3
  Perbaikan: original_dims dipass ke pack_multi_width_multi_roll
4
- Update UI: Input menggunakan Form dengan tombol Tambah Berkali-kali
5
  """
 
6
  import math
7
  import random
 
8
  import gradio as gr
9
  import pandas as pd
10
  from PIL import Image, ImageDraw, ImageFont
11
  from rectpack import newPacker
 
12
  from rectpack import (
13
  SORT_AREA, SORT_PERI, SORT_DIFF, SORT_SSIDE, SORT_LSIDE, SORT_RATIO, SORT_NONE
14
  )
@@ -25,13 +28,16 @@ from rectpack.guillotine import (
25
  GuillotineBlsfLlas, GuillotineBlsfMaxas, GuillotineBlsfMinas,
26
  )
27
 
 
28
  # --------------------------------------------------------------------------
29
  # 1. FUNGSI BANTU
30
  # --------------------------------------------------------------------------
 
31
  def generate_color(seed_text: str):
32
  random.seed(seed_text)
33
  return tuple(random.randint(90, 220) for _ in range(3))
34
 
 
35
  def load_font(size: int = 14):
36
  candidates = [
37
  "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
@@ -44,24 +50,50 @@ def load_font(size: int = 14):
44
  continue
45
  return ImageFont.load_default()
46
 
 
47
  def lighten_color(c, factor=0.55):
48
  return tuple(min(255, int(v + (255 - v) * factor)) for v in c)
49
 
 
50
  def get_sort_name(sort_algo):
51
  mapping = {
52
- SORT_AREA: "AREA ", SORT_PERI: "PERI ", SORT_LSIDE: "LSIDE ",
53
- SORT_SSIDE: "SSIDE ", SORT_RATIO: "RATIO ", SORT_DIFF: "DIFF ",
54
- SORT_NONE: "NONE ", None: "Default ",
55
  }
56
  return mapping.get(sort_algo, str(sort_algo))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  # --------------------------------------------------------------------------
59
  # 2. PERSIAPAN DATA
60
  # --------------------------------------------------------------------------
 
61
  def prepare_rects(df: pd.DataFrame, margin: float):
62
  rects, original_dims = [], {}
63
  for idx, row in df.iterrows():
64
- # Diperbaiki: hilangkan spasi di dalam key kolom
65
  label = str(row["Label"]).strip() or f"Item{idx}"
66
  try:
67
  w, h, qty = float(row["Width"]), float(row["Height"]), int(row["Qty"])
@@ -73,16 +105,16 @@ def prepare_rects(df: pd.DataFrame, margin: float):
73
  rid = f"{label}#{i + 1}"
74
  rects.append((w + margin * 2, h + margin * 2, rid))
75
  original_dims[rid] = (w, h)
76
-
77
  if not rects:
78
  return None, None, 0, 0
79
-
80
  max_height = sum(h for _, h, _ in rects) + margin * (len(rects) + 2)
81
  return rects, original_dims, len(rects), max_height
82
 
 
83
  # --------------------------------------------------------------------------
84
  # 3. CORE: PACKING ENGINE
85
  # --------------------------------------------------------------------------
 
86
  def pack_multi_roll(rects, roll_width, max_height, allow_rotation,
87
  pack_algo=None, sort_algo=None, reverse=False):
88
  remaining = list(reversed(rects)) if reverse else rects[:]
@@ -91,36 +123,39 @@ def pack_multi_roll(rects, roll_width, max_height, allow_rotation,
91
  if not remaining:
92
  break
93
  kwargs = {"rotation": allow_rotation}
94
- if pack_algo: kwargs["pack_algo"] = pack_algo
95
- if sort_algo: kwargs["sort_algo"] = sort_algo
96
-
 
97
  packer = newPacker(**kwargs)
98
  for w, h, rid in remaining:
99
  packer.add_rect(w, h, rid=rid)
100
  packer.add_bin(roll_width, max_height)
101
  packer.pack()
102
-
103
  if len(packer) == 0 or len(packer[0]) == 0:
104
  return rolls, len(remaining)
105
-
106
  placed = packer[0]
107
  used_height = max(r.y + r.height for r in placed)
108
  rolls.append((placed, used_height, roll_width))
109
  placed_ids = {r.rid for r in placed}
110
  remaining = [r for r in remaining if r[2] not in placed_ids]
111
-
112
  return rolls, len(remaining)
113
 
 
114
  # --------------------------------------------------------------------------
115
  # 4. GUILLOTINE CUT VALIDATION
116
  # --------------------------------------------------------------------------
 
117
  def is_guillotine_cuttable(rolls, margin):
118
  violations = 0
119
  for placed, used_height, roll_width in rolls:
120
  items = []
121
  for r in placed:
122
- items.append({'x': r.x, 'y': r.y, 'w': r.width, 'h': r.height, 'rid': r.rid})
123
-
 
 
 
124
  for a in items:
125
  has_free_top = a['y'] + a['h'] >= used_height - 0.01
126
  has_free_bottom = a['y'] <= 0.01
@@ -128,46 +163,74 @@ def is_guillotine_cuttable(rolls, margin):
128
  has_free_right = a['x'] + a['w'] >= roll_width - 0.01
129
  if has_free_top or has_free_bottom or has_free_left or has_free_right:
130
  continue
131
-
132
- can_slide_up = all(not (b['x'] < a['x'] + a['w'] and b['x'] + b['w'] > a['x'] and b['y'] > a['y'] + a['h']) for b in items if b['rid'] != a['rid'])
133
- if can_slide_up: continue
134
- can_slide_down = all(not (b['x'] < a['x'] + a['w'] and b['x'] + b['w'] > a['x'] and b['y'] + b['h'] < a['y']) for b in items if b['rid'] != a['rid'])
135
- if can_slide_down: continue
136
- can_slide_left = all(not (b['y'] < a['y'] + a['h'] and b['y'] + b['h'] > a['y'] and b['x'] + b['w'] < a['x']) for b in items if b['rid'] != a['rid'])
137
- if can_slide_left: continue
138
- can_slide_right = all(not (b['y'] < a['y'] + a['h'] and b['y'] + b['h'] > a['y'] and b['x'] > a['x'] + a['w']) for b in items if b['rid'] != a['rid'])
139
- if can_slide_right: continue
140
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  violations += 1
142
  return violations == 0, violations
143
 
 
144
  # --------------------------------------------------------------------------
145
  # 5. VISUALISASI
146
  # --------------------------------------------------------------------------
 
147
  def render_multi_roll(rolls, original_dims, margin, px_per_unit=4.0):
148
- if not rolls: return None, 0, 0, 0
 
 
149
  max_roll_w = max(w for _, _, w in rolls)
150
  img_w = max(1, int(round(max_roll_w * px_per_unit)))
151
  gap = 40
152
  total_h = sum(int(round(h * px_per_unit)) for _, h, _ in rolls)
153
  total_h += gap * (len(rolls) - 1) + 60
154
-
155
  img = Image.new("RGB", (img_w, total_h), "white")
156
  draw = ImageDraw.Draw(img)
157
  font = load_font(14)
158
  font_small = load_font(11)
159
  font_title = load_font(16)
160
-
161
  y_offset, total_true, total_roll_area, total_rot = 0, 0, 0, 0
 
162
  for roll_idx, (placed, used_height, roll_width) in enumerate(rolls):
163
  roll_h_px = int(round(used_height * px_per_unit))
164
  roll_label = f"ROLL {roll_idx + 1} | {roll_width:g} x {used_height:.1f} cm"
165
  draw.text((img_w / 2, y_offset + 5), roll_label, fill="#cc0000", font=font_title, anchor="ma")
166
-
167
  roll_y0 = y_offset + 25
168
  roll_y1 = roll_y0 + roll_h_px
169
  draw.rectangle([0, roll_y0, int(round(roll_width * px_per_unit)) - 1, roll_y1], outline="red", width=3)
170
-
171
  for r in placed:
172
  base_label = r.rid.rsplit("#", 1)[0]
173
  color = generate_color(base_label)
@@ -175,19 +238,20 @@ def render_multi_roll(rolls, original_dims, margin, px_per_unit=4.0):
175
  inner_color = color
176
  orig_w, orig_h = original_dims[r.rid]
177
  is_rotated = round(r.width - margin, 3) != round(orig_w, 3)
178
-
179
  x0 = r.x * px_per_unit
180
  y0 = roll_y0 + (used_height - r.y - r.height) * px_per_unit
181
  x1 = (r.x + r.width) * px_per_unit
182
  y1 = roll_y0 + (used_height - r.y) * px_per_unit
 
183
  m = margin * px_per_unit
184
  ix0, iy0 = x0 + m, y0 + m
185
  ix1, iy1 = x1 - m, y1 - m
186
-
187
  draw.rectangle([x0, y0, x1, y1], fill=outer_color, outline="black", width=2)
188
  if ix1 > ix0 and iy1 > iy0:
189
  draw.rectangle([ix0, iy0, ix1, iy1], fill=inner_color, outline="black", width=1)
190
-
191
  label_text = base_label
192
  size_text = f"{orig_w:g} x {orig_h:g}" + (" (diputar)" if is_rotated else "")
193
  bbox_label = draw.textbbox((0, 0), label_text, font=font)
@@ -195,32 +259,41 @@ def render_multi_roll(rolls, original_dims, margin, px_per_unit=4.0):
195
  total_th = (bbox_label[3] - bbox_label[1]) + (bbox_size[3] - bbox_size[1]) + 4
196
  cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
197
  ty = cy - total_th / 2
198
-
199
  if (x1 - x0) > 20 and (y1 - y0) > 20:
200
  draw.text((cx, ty), label_text, fill="black", font=font, anchor="ma")
201
- draw.text((cx, ty + (bbox_label[3] - bbox_label[1]) + 4), size_text, fill="black", font=font_small, anchor="ma")
202
-
 
203
  total_true += orig_w * orig_h
204
- if is_rotated: total_rot += 1
205
-
 
206
  for x in range(0, int(round(roll_width * px_per_unit)), 20):
207
  draw.line([(x, roll_y0), (x, roll_y1)], fill="#f5f5f5", width=1)
208
  for y in range(int(roll_y0), int(roll_y1), 20):
209
  draw.line([(0, y), (int(round(roll_width * px_per_unit)) - 1, y)], fill="#f5f5f5", width=1)
210
-
211
  total_roll_area += roll_width * used_height
212
  y_offset = roll_y1 + gap
213
-
214
  return img, total_true, total_roll_area, total_rot
215
 
 
216
  # --------------------------------------------------------------------------
217
  # 6. STRATEGI PRE-SORT
218
  # --------------------------------------------------------------------------
 
219
  def get_pre_sort_strategies(rects):
220
  strategies = []
221
- def area(r): return r[0] * r[1]
222
- def max_side(r): return max(r[0], r[1])
223
- def ratio(r): return max(r[0], r[1]) / max(min(r[0], r[1]), 0.001)
 
 
 
 
 
 
224
 
225
  base = [
226
  ("default", rects[:]),
@@ -250,31 +323,41 @@ def get_pre_sort_strategies(rects):
250
  i, j = 0, len(by_area) - 1
251
  while i <= j:
252
  interleaved.append(by_area[i])
253
- if i != j: interleaved.append(by_area[j])
 
254
  i += 1
255
  j -= 1
256
  strategies.append(("interleave", interleaved))
257
  return strategies
258
 
 
259
  # --------------------------------------------------------------------------
260
  # 7. SIMULATED ANNEALING
261
  # --------------------------------------------------------------------------
 
262
  def calculate_waste(rolls, original_dims):
263
- total_true = sum(original_dims[r.rid][0] * original_dims[r.rid][1] for placed, _, _ in rolls for r in placed)
 
 
 
264
  total_roll = sum(w * h for _, h, w in rolls)
265
  return total_roll - total_true, (total_roll - total_true) / total_roll * 100 if total_roll else 100
266
 
267
- def simulated_annealing(rects, roll_width, max_height, allow_rotation, pack_algo, sort_algo, original_dims,
 
 
268
  initial_temp=100, cooling=0.995, max_iter=3000):
269
  current = rects[:]
270
  best = rects[:]
271
  best_result = None
272
  best_waste = float('inf')
273
-
274
- current_result, _ = pack_multi_roll(current, roll_width, max_height, allow_rotation, pack_algo, sort_algo, False)
275
- if not current_result: return None, float('inf')
276
-
 
277
  current_waste, _ = calculate_waste(current_result, original_dims)
 
278
  temp = initial_temp
279
 
280
  for i in range(max_iter):
@@ -292,72 +375,98 @@ def simulated_annealing(rects, roll_width, max_height, allow_rotation, pack_algo
292
  item = neighbor.pop(a)
293
  neighbor.insert(b, item)
294
 
295
- rolls, _ = pack_multi_roll(neighbor, roll_width, max_height, allow_rotation, pack_algo, sort_algo, False)
296
- if not rolls: continue
297
-
 
 
 
298
  waste, _ = calculate_waste(rolls, original_dims)
 
299
  if waste < best_waste:
300
  best_waste = waste
301
  best = neighbor[:]
302
  best_result = rolls
303
-
304
  if waste < current_waste or random.random() < math.exp((current_waste - waste) / max(temp, 0.001)):
305
  current = neighbor[:]
306
  current_waste = waste
 
307
  temp *= cooling
308
 
309
  return best_result, best_waste
310
 
 
311
  # --------------------------------------------------------------------------
312
- # 8. MULTI-WIDTH MULTI-ROLL
313
  # --------------------------------------------------------------------------
314
- def pack_multi_width_multi_roll(rects, widths, max_height, allow_rotation, original_dims,
 
 
315
  pack_algo=None, sort_algo=None, reverse=False):
 
 
 
316
  remaining = list(reversed(rects)) if reverse else rects[:]
317
  all_rolls = []
318
  safety = 50
 
319
  for _ in range(safety):
320
- if not remaining: break
 
 
321
  best_roll = None
322
  best_waste = float('inf')
 
323
  best_remaining = None
324
-
325
  for w in widths:
326
  kwargs = {"rotation": allow_rotation}
327
- if pack_algo: kwargs["pack_algo"] = pack_algo
328
- if sort_algo: kwargs["sort_algo"] = sort_algo
329
-
 
330
  packer = newPacker(**kwargs)
331
  for rect_w, rect_h, rid in remaining:
332
  packer.add_rect(rect_w, rect_h, rid=rid)
333
  packer.add_bin(w, max_height)
334
  packer.pack()
335
-
336
- if len(packer) == 0 or len(packer[0]) == 0: continue
337
-
 
338
  placed = packer[0]
339
  used_height = max(r.y + r.height for r in placed)
340
  placed_ids = {r.rid for r in placed}
341
-
342
- true_area = sum((original_dims[rid][0] * original_dims[rid][1]) for _, _, rid in remaining if rid in placed_ids)
 
 
 
 
343
  roll_area = w * used_height
344
  waste = roll_area - true_area
345
-
346
  if waste < best_waste:
347
  best_waste = waste
348
  best_roll = (placed, used_height, w)
 
349
  best_remaining = [r for r in remaining if r[2] not in placed_ids]
350
-
351
- if best_roll is None: return all_rolls, len(remaining)
 
 
352
  all_rolls.append(best_roll)
353
  remaining = best_remaining
354
-
355
  return all_rolls, len(remaining)
356
 
 
357
  # --------------------------------------------------------------------------
358
  # 9. PENCARIAN UNTUK SATU LEBAR ROLL
359
  # --------------------------------------------------------------------------
360
- def search_single_width(rects, original_dims, total_rects, max_height, roll_width, margin, allow_rotation,
 
 
361
  search_mode, target_waste_pct, px_per_unit):
362
  best_result = None
363
  best_key = None
@@ -368,7 +477,8 @@ def search_single_width(rects, original_dims, total_rects, max_height, roll_widt
368
 
369
  def evaluate(rolls, not_placed, config_name):
370
  nonlocal best_result, best_key, best_config, best_rolls, hit_target
371
- if not rolls: return
 
372
  waste, waste_pct = calculate_waste(rolls, original_dims)
373
  num_rolls = len(rolls)
374
  key = (waste, num_rolls, not_placed)
@@ -377,26 +487,41 @@ def search_single_width(rects, original_dims, total_rects, max_height, roll_widt
377
  best_result = (rolls, not_placed)
378
  best_config = config_name
379
  best_rolls = rolls
380
- if waste_pct <= target_waste_pct: hit_target = True
381
-
382
- def should_stop(): return hit_target
383
-
384
- ALL_PACK = [None, MaxRectsBssf, MaxRectsBaf, MaxRectsBl, MaxRectsBlsf, SkylineBl, SkylineBlWm, SkylineMwf, SkylineMwfl, SkylineMwfWm, SkylineMwflWm, GuillotineBssfSas, GuillotineBssfLas, GuillotineBssfMaxas, GuillotineBafSas, GuillotineBafLas, GuillotineBafMaxas, GuillotineBlsfSas, GuillotineBlsfLas]
 
 
 
 
 
 
 
 
 
385
  ALL_SORT = [None, SORT_AREA, SORT_PERI, SORT_LSIDE, SORT_RATIO, SORT_DIFF]
386
 
 
387
  if search_mode in ("standard", "deep", "pro", "exhaustive"):
388
  if search_mode == "standard":
389
- pack_algos = [None, MaxRectsBssf, MaxRectsBaf, MaxRectsBlsf, SkylineMwfl, GuillotineBssfSas, GuillotineBafSas]
 
390
  sort_algos = [None, SORT_AREA, SORT_LSIDE]
391
  else:
392
  pack_algos, sort_algos = ALL_PACK, ALL_SORT
393
-
394
  for pack_algo in pack_algos:
395
  for sort_algo in sort_algos:
396
  for reverse in [False, True]:
397
- if should_stop(): break
 
398
  tried += 1
399
- rolls, not_placed = pack_multi_roll(rects, roll_width, max_height, allow_rotation, pack_algo, sort_algo, reverse)
 
 
 
400
  if not rolls:
401
  failed += 1
402
  continue
@@ -404,46 +529,68 @@ def search_single_width(rects, original_dims, total_rects, max_height, roll_widt
404
  config = f"[Grid] {algo_name} + {get_sort_name(sort_algo)}{' rev' if reverse else ''}"
405
  evaluate(rolls, not_placed, config)
406
 
 
407
  if search_mode in ("pro", "exhaustive") and not should_stop():
408
  for sort_name, sorted_rects in get_pre_sort_strategies(rects):
409
  for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
410
  for reverse in [False, True]:
411
- if should_stop(): break
 
412
  tried += 1
413
- rolls, not_placed = pack_multi_roll(sorted_rects, roll_width, max_height, allow_rotation, pack_algo, SORT_NONE, reverse)
 
 
 
414
  if not rolls:
415
  failed += 1
416
  continue
417
  config = f"[PreSort:{sort_name}] {pack_algo.__name__ if pack_algo else 'Default'}{' rev' if reverse else ''}"
418
  evaluate(rolls, not_placed, config)
419
 
 
420
  if search_mode in ("pro", "exhaustive") and not should_stop():
421
- sa_configs = [(None, None), (MaxRectsBssf, SORT_AREA), (GuillotineBssfSas, SORT_AREA)]
 
 
422
  for pack_algo, sort_algo in sa_configs:
423
- if should_stop(): break
 
424
  tried += 1
425
- sa_rolls, sa_waste = simulated_annealing(rects, roll_width, max_height, allow_rotation, pack_algo, sort_algo, original_dims, initial_temp=100, cooling=0.995, max_iter=5000 if search_mode == "exhaustive" else 2000)
 
 
 
 
 
426
  if sa_rolls:
427
  algo_name = pack_algo.__name__ if pack_algo else "Default"
428
  config = f"[SA] {algo_name} (waste {sa_waste:.1f})"
429
  evaluate(sa_rolls, 0, config)
430
 
 
431
  if search_mode == "exhaustive" and best_rolls and not should_stop():
432
  best_order = []
433
  placed_ids = set()
434
  for placed, _, _ in best_rolls:
435
- for r in placed: placed_ids.add(r.rid)
 
436
  for r in rects:
437
- if r[2] in placed_ids: best_order.append(r)
 
 
438
  n = len(best_order)
439
  for _ in range(min(500, n * n)):
440
- if should_stop(): break
 
441
  i, j = random.randint(0, n - 1), random.randint(0, n - 1)
442
- if i == j: continue
 
443
  swapped = best_order[:]
444
  swapped[i], swapped[j] = swapped[j], swapped[i]
445
  tried += 1
446
- rolls, not_placed = pack_multi_roll(swapped, roll_width, max_height, allow_rotation, None, None, False)
 
 
447
  if not rolls:
448
  failed += 1
449
  continue
@@ -451,14 +598,18 @@ def search_single_width(rects, original_dims, total_rects, max_height, roll_widt
451
 
452
  if best_result is None:
453
  return None, f"⚠️ Lebar {roll_width:g} cm: tidak muat.", None, None, None, tried, False
454
-
455
  rolls, not_placed = best_result
456
- img, total_true, total_roll, total_rot = render_multi_roll(rolls, original_dims, margin, px_per_unit)
 
 
457
  waste, waste_pct = calculate_waste(rolls, original_dims)
458
  num_rolls = len(rolls)
 
459
  is_guillotine, g_violations = is_guillotine_cuttable(rolls, margin)
 
460
  target_status = "βœ… TARGET TERCAPAI!" if waste_pct <= target_waste_pct else "❌ Target belum tercapai"
461
-
462
  stats = [
463
  f"{'🎯' if waste_pct <= target_waste_pct else '⚠️'} {target_status}",
464
  f"πŸ† Algoritma terpilih : {best_config}",
@@ -475,72 +626,50 @@ def search_single_width(rects, original_dims, total_rects, max_height, roll_widt
475
  f"πŸ“Š Persentase waste : {waste_pct:.2f}% (target: ≀{target_waste_pct}%)",
476
  f"πŸ”ͺ Guillotine cuttable : {'βœ… Ya' if is_guillotine else f'⚠️ Tidak ({g_violations} pelanggaran)'}",
477
  ]
478
- if not_placed > 0: stats.insert(7, f"⚠️ Item TIDAK muat : {not_placed}")
479
-
 
480
  return img, "\n".join(stats), waste, waste_pct, num_rolls, tried, hit_target
481
 
 
482
  # --------------------------------------------------------------------------
483
- # 10. FUNGSI UTAMA & FORM HANDLER
484
  # --------------------------------------------------------------------------
485
- # --- FUNGSI BARU UNTUK FORM INPUT ---
486
- def add_banner_to_list(current_data, label, w, h, q):
487
- """Menambahkan input form ke dalam list data"""
488
- if not label or w is None or h is None or q is None:
489
- gr.Warning("Mohon lengkapi semua field (Label, Width, Height, Qty)!")
490
- return current_data, label, w, h, q
491
- if w <= 0 or h <= 0 or q <= 0:
492
- gr.Warning("Nilai Width, Height, dan Qty harus lebih dari 0!")
493
- return current_data, label, w, h, q
494
-
495
- new_row = [str(label).strip(), float(w), float(h), int(q)]
496
-
497
- # Konversi data existing ke list of lists (jika berupa pandas/numpy)
498
- current_list = []
499
- if current_data is not None:
500
- if hasattr(current_data, 'values'):
501
- current_list = current_data.values.tolist()
502
- elif isinstance(current_data, list):
503
- current_list = current_data
504
-
505
- current_list.append(new_row)
506
-
507
- # Kembalikan data yang sudah diupdate, dan reset form input
508
- return current_list, "", 100, 60, 1
509
-
510
- def clear_banner_list():
511
- """Mengosongkan semua daftar banner"""
512
- return [], "", 100, 60, 1
513
- # ------------------------------------
514
 
515
  def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_pct,
516
  enable_multiwidth, table_data):
517
-
518
  if table_data is None or len(table_data) == 0:
519
- return None, "⚠️ Silakan tambahkan daftar banner melalui form terlebih dahulu."
520
-
521
  df = pd.DataFrame(table_data, columns=["Label", "Width", "Height", "Qty"])
522
  df = df.dropna(subset=["Width", "Height", "Qty"], how="any")
523
-
524
  try:
525
  widths = [float(w.strip()) for w in roll_widths_text.split(",") if w.strip()]
526
  widths = [w for w in widths if w > 0]
527
  except ValueError:
528
  return None, "⚠️ Format daftar lebar roll tidak valid."
 
529
  if not widths:
530
  return None, "⚠️ Masukkan minimal satu lebar roll yang valid."
531
 
532
- try: margin = float(margin) if margin is not None else 0.0
533
- except (TypeError, ValueError): margin = 0.0
 
 
534
 
535
  try:
536
  target_waste_pct = float(target_waste_pct)
537
- if target_waste_pct < 0: target_waste_pct = 5.0
538
- except (TypeError, ValueError): target_waste_pct = 5.0
 
 
539
 
540
  rects, original_dims, total_rects, max_height = prepare_rects(df, margin)
541
  if rects is None:
542
  return None, "⚠️ Tidak ada data banner yang valid."
543
 
 
544
  min_banner_w = max(w for w, _ in original_dims.values()) + margin
545
  auto_widths = set(widths)
546
  auto_widths.add(round(min_banner_w, 1))
@@ -557,20 +686,29 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
557
  width_results = []
558
  global_tried = 0
559
 
 
560
  if enable_multiwidth and search_mode in ("pro", "exhaustive"):
561
  tried = 0
562
  for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
563
  for sort_algo in [None, SORT_AREA]:
564
  for reverse in [False, True]:
565
  tried += 1
566
- rolls, not_placed = pack_multi_width_multi_roll(rects, all_widths, max_height, allow_rotation, original_dims, pack_algo, sort_algo, reverse)
567
- if not rolls: continue
 
 
 
 
 
 
568
  waste, waste_pct = calculate_waste(rolls, original_dims)
569
  if not_placed == 0:
570
  key = (waste, len(rolls), 0)
571
  if best_key is None or key < best_key:
572
  best_key = key
573
- img, total_true, total_roll, total_rot = render_multi_roll(rolls, original_dims, margin)
 
 
574
  is_g, g_v = is_guillotine_cuttable(rolls, margin)
575
  stats = [
576
  "🎯 MULTI-WIDTH MULTI-ROLL (tiap roll beda lebar)",
@@ -587,6 +725,7 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
587
  best_overall = (img, "\n".join(stats), waste, waste_pct)
588
  best_width = "multi"
589
 
 
590
  for width in all_widths:
591
  if search_mode == "quick":
592
  result = pack_multi_roll(rects, width, max_height, bool(allow_rotation))
@@ -594,9 +733,12 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
594
  width_results.append((width, None, None, "Gagal"))
595
  continue
596
  rolls, not_placed = result
597
- img, total_true, total_roll, total_rot = render_multi_roll(rolls, original_dims, margin)
 
 
598
  waste, waste_pct = calculate_waste(rolls, original_dims)
599
  num_rolls = len(rolls)
 
600
  stats = [
601
  f"πŸ† Mode : CEPAT",
602
  f"πŸ“ Lebar roll : {width:g} cm",
@@ -604,112 +746,146 @@ def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_
604
  f"♻️ Total waste : {waste:.1f} cmΒ²",
605
  f"πŸ“Š Persentase waste : {waste_pct:.2f}%",
606
  ]
 
607
  key = (waste, num_rolls, sum(h for _, h, _ in rolls))
608
  if best_key is None or key < best_key:
609
  best_key = key
610
  best_overall = (img, "\n".join(stats), waste, waste_pct)
611
  best_width = width
 
612
  width_results.append((width, waste, waste_pct, num_rolls, f"{waste_pct:.2f}%"))
613
  global_tried += 1
614
- if waste_pct <= target_waste_pct: break
 
 
615
  else:
616
- img, stats, waste, waste_pct, num_rolls, tried, hit = search_single_width(rects, original_dims, total_rects, max_height, width, margin, bool(allow_rotation), search_mode, target_waste_pct, 4.0)
 
 
 
 
617
  global_tried += tried
 
618
  if img is None:
619
  width_results.append((width, None, None, None, "Gagal"))
620
  continue
621
- key = (waste if waste is not None else float('inf'), num_rolls if num_rolls else 99, 0)
 
 
622
  if best_key is None or key < best_key:
623
  best_key = key
624
  best_overall = (img, stats, waste, waste_pct)
625
  best_width = width
 
626
  width_results.append((width, waste, waste_pct, num_rolls, f"{waste_pct:.2f}%"))
627
- if hit: break
 
628
 
629
  if best_overall is None:
630
  return None, "⚠️ Tidak ada satupun lebar roll yang bisa menampung semua banner."
631
 
632
  img, stats, best_waste, best_waste_pct = best_overall
 
633
  comparison = ["\n" + "─" * 55, "πŸ“‹ PERBANDINGAN LEBAR ROLL (10 teratas):"]
634
  sorted_r = sorted([r for r in width_results if r[1] is not None], key=lambda x: (x[1], x[3]))
635
  for w, waste, wpct, rolls, note in sorted_r[:10]:
636
  mark = " ⭐ PALING HEMAT" if w == best_width else ""
637
  target = " 🎯" if isinstance(wpct, (int, float)) and wpct <= target_waste_pct else ""
638
- comparison.append(f" {'βœ…' if w == best_width else ' '} {w:g} cm β†’ {rolls} roll, waste {waste:.1f} cmΒ² ({note}){mark}{target}")
 
 
 
639
 
640
  final = stats + "\n" + "\n".join(comparison)
641
  final += f"\n{'─' * 55}\nπŸ” Total iterasi keseluruhan: {global_tried} kombinasi"
 
642
  return img, final
643
 
 
644
  # --------------------------------------------------------------------------
645
- # 11. UI GRADIO (MODIFIED WITH FORM)
646
  # --------------------------------------------------------------------------
 
647
  with gr.Blocks(title="Nesting Otomatis Banner v2 β€” Super Optimized") as demo:
648
  gr.Markdown("# πŸ–¨οΈ Nesting Otomatis v2 β€” Simulated Annealing + Multi-Width")
649
- gr.Markdown("Upgrade: Simulated Annealing, Multi-Width Multi-Roll, dan Guillotine Validation.")
 
 
 
650
 
651
  with gr.Row():
652
  with gr.Column(scale=1):
653
- roll_widths = gr.Textbox(label="Daftar Lebar Roll (cm, pisah koma)", value="150, 200, 250, 300", placeholder="Contoh: 150, 200, 250, 300")
 
 
 
 
654
  margin = gr.Number(label="Jarak Antar Item / Margin (cm)", value=2, minimum=0)
655
  allow_rotation = gr.Checkbox(label="Izinkan Rotasi Otomatis", value=True)
656
- target_waste = gr.Number(label="🎯 Target Waste Maksimum (%)", value=5.0, minimum=0.1, maximum=50.0, step=0.5)
657
- enable_multiwidth = gr.Checkbox(label="🎨 Aktifkan Multi-Width Multi-Roll", value=False)
 
 
 
 
 
 
 
 
 
658
  search_mode = gr.Dropdown(
659
  label="Mode Pencarian",
660
- choices=[("⚑ Cepat", "quick"), ("🎯 Standar (~120)", "standard"), ("πŸ” Dalaman (~464)", "deep"), ("🧠 Pro (~3.000+ + SA)", "pro"), ("πŸ’Ž Menyeluruh (~8.000+ + SA + Swap)", "exhaustive")],
 
 
 
 
 
 
661
  value="standard",
662
  )
663
 
664
- # --- FORM INPUT BARU ---
665
- gr.Markdown("### πŸ“ Form Input Banner")
666
  with gr.Row():
667
- inp_label = gr.Textbox(label="Label / Nama", placeholder="Banner A", scale=2)
668
- inp_qty = gr.Number(label="Qty", value=1, minimum=1, precision=0, scale=1)
669
  with gr.Row():
670
- inp_width = gr.Number(label="Width (cm)", value=100, minimum=0.1, scale=1)
671
- inp_height = gr.Number(label="Height (cm)", value=60, minimum=0.1, scale=1)
672
 
673
- with gr.Row():
674
- btn_add = gr.Button("βž• Tambah ke Daftar", variant="secondary", scale=2)
675
- btn_clear = gr.Button("πŸ—‘οΈ Kosongkan Daftar", variant="stop", scale=1)
676
 
677
- gr.Markdown("### πŸ“‹ Daftar Banner Saat Ini")
678
- # Tabel dibuat read-only (interactive=False) agar user hanya bisa menambah via form
679
  data_input = gr.Dataframe(
680
  headers=["Label", "Width", "Height", "Qty"],
681
  datatype=["str", "number", "number", "number"],
682
- interactive=False,
683
- row_count=(0, "dynamic"),
684
- value=[]
 
 
 
 
 
 
 
 
 
 
685
  )
686
- # -------------------------
687
 
688
- btn_process = gr.Button("πŸš€ PROSES SUPER OPTIMIZED", variant="primary")
689
 
690
  with gr.Column(scale=2):
691
  output_img = gr.Image(label="Pratinjau Layout Cetakan", type="pil")
692
  output_stats = gr.Textbox(label="Statistik Hasil Nesting", lines=16)
693
 
694
- # --- EVENT LISTENERS UNTUK FORM ---
695
- btn_add.click(
696
- fn=add_banner_to_list,
697
- inputs=[data_input, inp_label, inp_width, inp_height, inp_qty],
698
- outputs=[data_input, inp_label, inp_width, inp_height, inp_qty]
699
- )
700
-
701
- btn_clear.click(
702
- fn=clear_banner_list,
703
- inputs=[],
704
- outputs=[data_input, inp_label, inp_width, inp_height, inp_qty]
705
- )
706
- # ----------------------------------
707
-
708
- btn_process.click(
709
  fn=process,
710
- inputs=[roll_widths, margin, allow_rotation, search_mode, target_waste, enable_multiwidth, data_input],
 
711
  outputs=[output_img, output_stats],
712
  )
713
 
714
  if __name__ == "__main__":
715
- demo.launch()
 
1
  """
2
+ Nesting Otomatis Banner v2 β€” Super Optimized (Fixed)
3
+ =====================================================
4
  Perbaikan: original_dims dipass ke pack_multi_width_multi_roll
 
5
  """
6
+
7
  import math
8
  import random
9
+
10
  import gradio as gr
11
  import pandas as pd
12
  from PIL import Image, ImageDraw, ImageFont
13
  from rectpack import newPacker
14
+
15
  from rectpack import (
16
  SORT_AREA, SORT_PERI, SORT_DIFF, SORT_SSIDE, SORT_LSIDE, SORT_RATIO, SORT_NONE
17
  )
 
28
  GuillotineBlsfLlas, GuillotineBlsfMaxas, GuillotineBlsfMinas,
29
  )
30
 
31
+
32
  # --------------------------------------------------------------------------
33
  # 1. FUNGSI BANTU
34
  # --------------------------------------------------------------------------
35
+
36
  def generate_color(seed_text: str):
37
  random.seed(seed_text)
38
  return tuple(random.randint(90, 220) for _ in range(3))
39
 
40
+
41
  def load_font(size: int = 14):
42
  candidates = [
43
  "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
 
50
  continue
51
  return ImageFont.load_default()
52
 
53
+
54
  def lighten_color(c, factor=0.55):
55
  return tuple(min(255, int(v + (255 - v) * factor)) for v in c)
56
 
57
+
58
  def get_sort_name(sort_algo):
59
  mapping = {
60
+ SORT_AREA: "AREA", SORT_PERI: "PERI", SORT_LSIDE: "LSIDE",
61
+ SORT_SSIDE: "SSIDE", SORT_RATIO: "RATIO", SORT_DIFF: "DIFF",
62
+ SORT_NONE: "NONE", None: "Default",
63
  }
64
  return mapping.get(sort_algo, str(sort_algo))
65
+
66
+
67
+ def add_banner_to_list(label, width, height, qty, current_data):
68
+ if not label or not str(label).strip():
69
+ label = f"Banner"
70
+ try:
71
+ w = float(width)
72
+ h = float(height)
73
+ q = int(qty)
74
+ except (TypeError, ValueError):
75
+ return current_data # Abaikan jika nilai tidak valid
76
+
77
+ new_row = [str(label).strip(), w, h, q]
78
+
79
+ # Tangkap apakah current_data berupa DataFrame pandas atau List of Lists
80
+ if isinstance(current_data, pd.DataFrame):
81
+ new_row_df = pd.DataFrame([new_row], columns=current_data.columns)
82
+ return pd.concat([current_data, new_row_df], ignore_index=True)
83
+ elif isinstance(current_data, list):
84
+ return current_data + [new_row]
85
+ else:
86
+ return [new_row]
87
+
88
+
89
 
90
  # --------------------------------------------------------------------------
91
  # 2. PERSIAPAN DATA
92
  # --------------------------------------------------------------------------
93
+
94
  def prepare_rects(df: pd.DataFrame, margin: float):
95
  rects, original_dims = [], {}
96
  for idx, row in df.iterrows():
 
97
  label = str(row["Label"]).strip() or f"Item{idx}"
98
  try:
99
  w, h, qty = float(row["Width"]), float(row["Height"]), int(row["Qty"])
 
105
  rid = f"{label}#{i + 1}"
106
  rects.append((w + margin * 2, h + margin * 2, rid))
107
  original_dims[rid] = (w, h)
 
108
  if not rects:
109
  return None, None, 0, 0
 
110
  max_height = sum(h for _, h, _ in rects) + margin * (len(rects) + 2)
111
  return rects, original_dims, len(rects), max_height
112
 
113
+
114
  # --------------------------------------------------------------------------
115
  # 3. CORE: PACKING ENGINE
116
  # --------------------------------------------------------------------------
117
+
118
  def pack_multi_roll(rects, roll_width, max_height, allow_rotation,
119
  pack_algo=None, sort_algo=None, reverse=False):
120
  remaining = list(reversed(rects)) if reverse else rects[:]
 
123
  if not remaining:
124
  break
125
  kwargs = {"rotation": allow_rotation}
126
+ if pack_algo:
127
+ kwargs["pack_algo"] = pack_algo
128
+ if sort_algo:
129
+ kwargs["sort_algo"] = sort_algo
130
  packer = newPacker(**kwargs)
131
  for w, h, rid in remaining:
132
  packer.add_rect(w, h, rid=rid)
133
  packer.add_bin(roll_width, max_height)
134
  packer.pack()
 
135
  if len(packer) == 0 or len(packer[0]) == 0:
136
  return rolls, len(remaining)
 
137
  placed = packer[0]
138
  used_height = max(r.y + r.height for r in placed)
139
  rolls.append((placed, used_height, roll_width))
140
  placed_ids = {r.rid for r in placed}
141
  remaining = [r for r in remaining if r[2] not in placed_ids]
 
142
  return rolls, len(remaining)
143
 
144
+
145
  # --------------------------------------------------------------------------
146
  # 4. GUILLOTINE CUT VALIDATION
147
  # --------------------------------------------------------------------------
148
+
149
  def is_guillotine_cuttable(rolls, margin):
150
  violations = 0
151
  for placed, used_height, roll_width in rolls:
152
  items = []
153
  for r in placed:
154
+ items.append({
155
+ 'x': r.x, 'y': r.y,
156
+ 'w': r.width, 'h': r.height,
157
+ 'rid': r.rid
158
+ })
159
  for a in items:
160
  has_free_top = a['y'] + a['h'] >= used_height - 0.01
161
  has_free_bottom = a['y'] <= 0.01
 
163
  has_free_right = a['x'] + a['w'] >= roll_width - 0.01
164
  if has_free_top or has_free_bottom or has_free_left or has_free_right:
165
  continue
166
+
167
+ can_slide_up = all(
168
+ not (b['x'] < a['x'] + a['w'] and b['x'] + b['w'] > a['x'] and
169
+ b['y'] > a['y'] + a['h'])
170
+ for b in items if b['rid'] != a['rid']
171
+ )
172
+ if can_slide_up:
173
+ continue
174
+
175
+ can_slide_down = all(
176
+ not (b['x'] < a['x'] + a['w'] and b['x'] + b['w'] > a['x'] and
177
+ b['y'] + b['h'] < a['y'])
178
+ for b in items if b['rid'] != a['rid']
179
+ )
180
+ if can_slide_down:
181
+ continue
182
+
183
+ can_slide_left = all(
184
+ not (b['y'] < a['y'] + a['h'] and b['y'] + b['h'] > a['y'] and
185
+ b['x'] + b['w'] < a['x'])
186
+ for b in items if b['rid'] != a['rid']
187
+ )
188
+ if can_slide_left:
189
+ continue
190
+
191
+ can_slide_right = all(
192
+ not (b['y'] < a['y'] + a['h'] and b['y'] + b['h'] > a['y'] and
193
+ b['x'] > a['x'] + a['w'])
194
+ for b in items if b['rid'] != a['rid']
195
+ )
196
+ if can_slide_right:
197
+ continue
198
+
199
  violations += 1
200
  return violations == 0, violations
201
 
202
+
203
  # --------------------------------------------------------------------------
204
  # 5. VISUALISASI
205
  # --------------------------------------------------------------------------
206
+
207
  def render_multi_roll(rolls, original_dims, margin, px_per_unit=4.0):
208
+ if not rolls:
209
+ return None, 0, 0, 0
210
+
211
  max_roll_w = max(w for _, _, w in rolls)
212
  img_w = max(1, int(round(max_roll_w * px_per_unit)))
213
  gap = 40
214
  total_h = sum(int(round(h * px_per_unit)) for _, h, _ in rolls)
215
  total_h += gap * (len(rolls) - 1) + 60
216
+
217
  img = Image.new("RGB", (img_w, total_h), "white")
218
  draw = ImageDraw.Draw(img)
219
  font = load_font(14)
220
  font_small = load_font(11)
221
  font_title = load_font(16)
222
+
223
  y_offset, total_true, total_roll_area, total_rot = 0, 0, 0, 0
224
+
225
  for roll_idx, (placed, used_height, roll_width) in enumerate(rolls):
226
  roll_h_px = int(round(used_height * px_per_unit))
227
  roll_label = f"ROLL {roll_idx + 1} | {roll_width:g} x {used_height:.1f} cm"
228
  draw.text((img_w / 2, y_offset + 5), roll_label, fill="#cc0000", font=font_title, anchor="ma")
229
+
230
  roll_y0 = y_offset + 25
231
  roll_y1 = roll_y0 + roll_h_px
232
  draw.rectangle([0, roll_y0, int(round(roll_width * px_per_unit)) - 1, roll_y1], outline="red", width=3)
233
+
234
  for r in placed:
235
  base_label = r.rid.rsplit("#", 1)[0]
236
  color = generate_color(base_label)
 
238
  inner_color = color
239
  orig_w, orig_h = original_dims[r.rid]
240
  is_rotated = round(r.width - margin, 3) != round(orig_w, 3)
241
+
242
  x0 = r.x * px_per_unit
243
  y0 = roll_y0 + (used_height - r.y - r.height) * px_per_unit
244
  x1 = (r.x + r.width) * px_per_unit
245
  y1 = roll_y0 + (used_height - r.y) * px_per_unit
246
+
247
  m = margin * px_per_unit
248
  ix0, iy0 = x0 + m, y0 + m
249
  ix1, iy1 = x1 - m, y1 - m
250
+
251
  draw.rectangle([x0, y0, x1, y1], fill=outer_color, outline="black", width=2)
252
  if ix1 > ix0 and iy1 > iy0:
253
  draw.rectangle([ix0, iy0, ix1, iy1], fill=inner_color, outline="black", width=1)
254
+
255
  label_text = base_label
256
  size_text = f"{orig_w:g} x {orig_h:g}" + (" (diputar)" if is_rotated else "")
257
  bbox_label = draw.textbbox((0, 0), label_text, font=font)
 
259
  total_th = (bbox_label[3] - bbox_label[1]) + (bbox_size[3] - bbox_size[1]) + 4
260
  cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
261
  ty = cy - total_th / 2
 
262
  if (x1 - x0) > 20 and (y1 - y0) > 20:
263
  draw.text((cx, ty), label_text, fill="black", font=font, anchor="ma")
264
+ draw.text((cx, ty + (bbox_label[3] - bbox_label[1]) + 4), size_text,
265
+ fill="black", font=font_small, anchor="ma")
266
+
267
  total_true += orig_w * orig_h
268
+ if is_rotated:
269
+ total_rot += 1
270
+
271
  for x in range(0, int(round(roll_width * px_per_unit)), 20):
272
  draw.line([(x, roll_y0), (x, roll_y1)], fill="#f5f5f5", width=1)
273
  for y in range(int(roll_y0), int(roll_y1), 20):
274
  draw.line([(0, y), (int(round(roll_width * px_per_unit)) - 1, y)], fill="#f5f5f5", width=1)
275
+
276
  total_roll_area += roll_width * used_height
277
  y_offset = roll_y1 + gap
278
+
279
  return img, total_true, total_roll_area, total_rot
280
 
281
+
282
  # --------------------------------------------------------------------------
283
  # 6. STRATEGI PRE-SORT
284
  # --------------------------------------------------------------------------
285
+
286
  def get_pre_sort_strategies(rects):
287
  strategies = []
288
+
289
+ def area(r):
290
+ return r[0] * r[1]
291
+
292
+ def max_side(r):
293
+ return max(r[0], r[1])
294
+
295
+ def ratio(r):
296
+ return max(r[0], r[1]) / max(min(r[0], r[1]), 0.001)
297
 
298
  base = [
299
  ("default", rects[:]),
 
323
  i, j = 0, len(by_area) - 1
324
  while i <= j:
325
  interleaved.append(by_area[i])
326
+ if i != j:
327
+ interleaved.append(by_area[j])
328
  i += 1
329
  j -= 1
330
  strategies.append(("interleave", interleaved))
331
  return strategies
332
 
333
+
334
  # --------------------------------------------------------------------------
335
  # 7. SIMULATED ANNEALING
336
  # --------------------------------------------------------------------------
337
+
338
  def calculate_waste(rolls, original_dims):
339
+ total_true = sum(
340
+ original_dims[r.rid][0] * original_dims[r.rid][1]
341
+ for placed, _, _ in rolls for r in placed
342
+ )
343
  total_roll = sum(w * h for _, h, w in rolls)
344
  return total_roll - total_true, (total_roll - total_true) / total_roll * 100 if total_roll else 100
345
 
346
+
347
+ def simulated_annealing(rects, roll_width, max_height, allow_rotation,
348
+ pack_algo, sort_algo, original_dims,
349
  initial_temp=100, cooling=0.995, max_iter=3000):
350
  current = rects[:]
351
  best = rects[:]
352
  best_result = None
353
  best_waste = float('inf')
354
+ current_result, _ = pack_multi_roll(
355
+ current, roll_width, max_height, allow_rotation, pack_algo, sort_algo, False
356
+ )
357
+ if not current_result:
358
+ return None, float('inf')
359
  current_waste, _ = calculate_waste(current_result, original_dims)
360
+
361
  temp = initial_temp
362
 
363
  for i in range(max_iter):
 
375
  item = neighbor.pop(a)
376
  neighbor.insert(b, item)
377
 
378
+ rolls, _ = pack_multi_roll(
379
+ neighbor, roll_width, max_height, allow_rotation, pack_algo, sort_algo, False
380
+ )
381
+ if not rolls:
382
+ continue
383
+
384
  waste, _ = calculate_waste(rolls, original_dims)
385
+
386
  if waste < best_waste:
387
  best_waste = waste
388
  best = neighbor[:]
389
  best_result = rolls
 
390
  if waste < current_waste or random.random() < math.exp((current_waste - waste) / max(temp, 0.001)):
391
  current = neighbor[:]
392
  current_waste = waste
393
+
394
  temp *= cooling
395
 
396
  return best_result, best_waste
397
 
398
+
399
  # --------------------------------------------------------------------------
400
+ # 8. MULTI-WIDTH MULTI-ROLL (FIXED: tambah original_dims parameter)
401
  # --------------------------------------------------------------------------
402
+
403
+ def pack_multi_width_multi_roll(rects, widths, max_height, allow_rotation,
404
+ original_dims, # <-- FIX: tambah parameter ini
405
  pack_algo=None, sort_algo=None, reverse=False):
406
+ """
407
+ Packing di mana TIAP ROLL boleh beda lebar.
408
+ """
409
  remaining = list(reversed(rects)) if reverse else rects[:]
410
  all_rolls = []
411
  safety = 50
412
+
413
  for _ in range(safety):
414
+ if not remaining:
415
+ break
416
+
417
  best_roll = None
418
  best_waste = float('inf')
419
+ best_width = None
420
  best_remaining = None
421
+
422
  for w in widths:
423
  kwargs = {"rotation": allow_rotation}
424
+ if pack_algo:
425
+ kwargs["pack_algo"] = pack_algo
426
+ if sort_algo:
427
+ kwargs["sort_algo"] = sort_algo
428
  packer = newPacker(**kwargs)
429
  for rect_w, rect_h, rid in remaining:
430
  packer.add_rect(rect_w, rect_h, rid=rid)
431
  packer.add_bin(w, max_height)
432
  packer.pack()
433
+
434
+ if len(packer) == 0 or len(packer[0]) == 0:
435
+ continue
436
+
437
  placed = packer[0]
438
  used_height = max(r.y + r.height for r in placed)
439
  placed_ids = {r.rid for r in placed}
440
+
441
+ # FIX: gunakan parameter original_dims, bukan variabel global
442
+ true_area = sum(
443
+ (original_dims[rid][0] * original_dims[rid][1])
444
+ for _, _, rid in remaining if rid in placed_ids
445
+ )
446
  roll_area = w * used_height
447
  waste = roll_area - true_area
448
+
449
  if waste < best_waste:
450
  best_waste = waste
451
  best_roll = (placed, used_height, w)
452
+ best_width = w
453
  best_remaining = [r for r in remaining if r[2] not in placed_ids]
454
+
455
+ if best_roll is None:
456
+ return all_rolls, len(remaining)
457
+
458
  all_rolls.append(best_roll)
459
  remaining = best_remaining
460
+
461
  return all_rolls, len(remaining)
462
 
463
+
464
  # --------------------------------------------------------------------------
465
  # 9. PENCARIAN UNTUK SATU LEBAR ROLL
466
  # --------------------------------------------------------------------------
467
+
468
+ def search_single_width(rects, original_dims, total_rects, max_height,
469
+ roll_width, margin, allow_rotation,
470
  search_mode, target_waste_pct, px_per_unit):
471
  best_result = None
472
  best_key = None
 
477
 
478
  def evaluate(rolls, not_placed, config_name):
479
  nonlocal best_result, best_key, best_config, best_rolls, hit_target
480
+ if not rolls:
481
+ return
482
  waste, waste_pct = calculate_waste(rolls, original_dims)
483
  num_rolls = len(rolls)
484
  key = (waste, num_rolls, not_placed)
 
487
  best_result = (rolls, not_placed)
488
  best_config = config_name
489
  best_rolls = rolls
490
+ if waste_pct <= target_waste_pct:
491
+ hit_target = True
492
+
493
+ def should_stop():
494
+ return hit_target
495
+
496
+ ALL_PACK = [
497
+ None, MaxRectsBssf, MaxRectsBaf, MaxRectsBl, MaxRectsBlsf,
498
+ SkylineBl, SkylineBlWm, SkylineMwf, SkylineMwfl,
499
+ SkylineMwfWm, SkylineMwflWm,
500
+ GuillotineBssfSas, GuillotineBssfLas, GuillotineBssfMaxas,
501
+ GuillotineBafSas, GuillotineBafLas, GuillotineBafMaxas,
502
+ GuillotineBlsfSas, GuillotineBlsfLas,
503
+ ]
504
  ALL_SORT = [None, SORT_AREA, SORT_PERI, SORT_LSIDE, SORT_RATIO, SORT_DIFF]
505
 
506
+ # PHASE 1: GRID SEARCH
507
  if search_mode in ("standard", "deep", "pro", "exhaustive"):
508
  if search_mode == "standard":
509
+ pack_algos = [None, MaxRectsBssf, MaxRectsBaf, MaxRectsBlsf,
510
+ SkylineMwfl, GuillotineBssfSas, GuillotineBafSas]
511
  sort_algos = [None, SORT_AREA, SORT_LSIDE]
512
  else:
513
  pack_algos, sort_algos = ALL_PACK, ALL_SORT
514
+
515
  for pack_algo in pack_algos:
516
  for sort_algo in sort_algos:
517
  for reverse in [False, True]:
518
+ if should_stop():
519
+ break
520
  tried += 1
521
+ rolls, not_placed = pack_multi_roll(
522
+ rects, roll_width, max_height, allow_rotation,
523
+ pack_algo, sort_algo, reverse
524
+ )
525
  if not rolls:
526
  failed += 1
527
  continue
 
529
  config = f"[Grid] {algo_name} + {get_sort_name(sort_algo)}{' rev' if reverse else ''}"
530
  evaluate(rolls, not_placed, config)
531
 
532
+ # PHASE 2: PRE-SORT
533
  if search_mode in ("pro", "exhaustive") and not should_stop():
534
  for sort_name, sorted_rects in get_pre_sort_strategies(rects):
535
  for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
536
  for reverse in [False, True]:
537
+ if should_stop():
538
+ break
539
  tried += 1
540
+ rolls, not_placed = pack_multi_roll(
541
+ sorted_rects, roll_width, max_height, allow_rotation,
542
+ pack_algo, SORT_NONE, reverse
543
+ )
544
  if not rolls:
545
  failed += 1
546
  continue
547
  config = f"[PreSort:{sort_name}] {pack_algo.__name__ if pack_algo else 'Default'}{' rev' if reverse else ''}"
548
  evaluate(rolls, not_placed, config)
549
 
550
+ # PHASE 3: SIMULATED ANNEALING
551
  if search_mode in ("pro", "exhaustive") and not should_stop():
552
+ sa_configs = [
553
+ (None, None), (MaxRectsBssf, SORT_AREA), (GuillotineBssfSas, SORT_AREA)
554
+ ]
555
  for pack_algo, sort_algo in sa_configs:
556
+ if should_stop():
557
+ break
558
  tried += 1
559
+ sa_rolls, sa_waste = simulated_annealing(
560
+ rects, roll_width, max_height, allow_rotation,
561
+ pack_algo, sort_algo, original_dims,
562
+ initial_temp=100, cooling=0.995,
563
+ max_iter=5000 if search_mode == "exhaustive" else 2000
564
+ )
565
  if sa_rolls:
566
  algo_name = pack_algo.__name__ if pack_algo else "Default"
567
  config = f"[SA] {algo_name} (waste {sa_waste:.1f})"
568
  evaluate(sa_rolls, 0, config)
569
 
570
+ # PHASE 4: LOCAL SWAP
571
  if search_mode == "exhaustive" and best_rolls and not should_stop():
572
  best_order = []
573
  placed_ids = set()
574
  for placed, _, _ in best_rolls:
575
+ for r in placed:
576
+ placed_ids.add(r.rid)
577
  for r in rects:
578
+ if r[2] in placed_ids:
579
+ best_order.append(r)
580
+
581
  n = len(best_order)
582
  for _ in range(min(500, n * n)):
583
+ if should_stop():
584
+ break
585
  i, j = random.randint(0, n - 1), random.randint(0, n - 1)
586
+ if i == j:
587
+ continue
588
  swapped = best_order[:]
589
  swapped[i], swapped[j] = swapped[j], swapped[i]
590
  tried += 1
591
+ rolls, not_placed = pack_multi_roll(
592
+ swapped, roll_width, max_height, allow_rotation, None, None, False
593
+ )
594
  if not rolls:
595
  failed += 1
596
  continue
 
598
 
599
  if best_result is None:
600
  return None, f"⚠️ Lebar {roll_width:g} cm: tidak muat.", None, None, None, tried, False
601
+
602
  rolls, not_placed = best_result
603
+ img, total_true, total_roll, total_rot = render_multi_roll(
604
+ rolls, original_dims, margin, px_per_unit
605
+ )
606
  waste, waste_pct = calculate_waste(rolls, original_dims)
607
  num_rolls = len(rolls)
608
+
609
  is_guillotine, g_violations = is_guillotine_cuttable(rolls, margin)
610
+
611
  target_status = "βœ… TARGET TERCAPAI!" if waste_pct <= target_waste_pct else "❌ Target belum tercapai"
612
+
613
  stats = [
614
  f"{'🎯' if waste_pct <= target_waste_pct else '⚠️'} {target_status}",
615
  f"πŸ† Algoritma terpilih : {best_config}",
 
626
  f"πŸ“Š Persentase waste : {waste_pct:.2f}% (target: ≀{target_waste_pct}%)",
627
  f"πŸ”ͺ Guillotine cuttable : {'βœ… Ya' if is_guillotine else f'⚠️ Tidak ({g_violations} pelanggaran)'}",
628
  ]
629
+ if not_placed > 0:
630
+ stats.insert(7, f"⚠️ Item TIDAK muat : {not_placed}")
631
+
632
  return img, "\n".join(stats), waste, waste_pct, num_rolls, tried, hit_target
633
 
634
+
635
  # --------------------------------------------------------------------------
636
+ # 10. FUNGSI UTAMA
637
  # --------------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
638
 
639
  def process(roll_widths_text, margin, allow_rotation, search_mode, target_waste_pct,
640
  enable_multiwidth, table_data):
 
641
  if table_data is None or len(table_data) == 0:
642
+ return None, "⚠️ Silakan isi tabel daftar banner terlebih dahulu."
643
+
644
  df = pd.DataFrame(table_data, columns=["Label", "Width", "Height", "Qty"])
645
  df = df.dropna(subset=["Width", "Height", "Qty"], how="any")
646
+
647
  try:
648
  widths = [float(w.strip()) for w in roll_widths_text.split(",") if w.strip()]
649
  widths = [w for w in widths if w > 0]
650
  except ValueError:
651
  return None, "⚠️ Format daftar lebar roll tidak valid."
652
+
653
  if not widths:
654
  return None, "⚠️ Masukkan minimal satu lebar roll yang valid."
655
 
656
+ try:
657
+ margin = float(margin) if margin is not None else 0.0
658
+ except (TypeError, ValueError):
659
+ margin = 0.0
660
 
661
  try:
662
  target_waste_pct = float(target_waste_pct)
663
+ if target_waste_pct < 0:
664
+ target_waste_pct = 5.0
665
+ except (TypeError, ValueError):
666
+ target_waste_pct = 5.0
667
 
668
  rects, original_dims, total_rects, max_height = prepare_rects(df, margin)
669
  if rects is None:
670
  return None, "⚠️ Tidak ada data banner yang valid."
671
 
672
+ # Auto-generate lebar tambahan
673
  min_banner_w = max(w for w, _ in original_dims.values()) + margin
674
  auto_widths = set(widths)
675
  auto_widths.add(round(min_banner_w, 1))
 
686
  width_results = []
687
  global_tried = 0
688
 
689
+ # MULTI-WIDTH MULTI-ROLL
690
  if enable_multiwidth and search_mode in ("pro", "exhaustive"):
691
  tried = 0
692
  for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
693
  for sort_algo in [None, SORT_AREA]:
694
  for reverse in [False, True]:
695
  tried += 1
696
+ # FIX: pass original_dims ke fungsi
697
+ rolls, not_placed = pack_multi_width_multi_roll(
698
+ rects, all_widths, max_height, allow_rotation,
699
+ original_dims, # <-- FIX: pass original_dims
700
+ pack_algo, sort_algo, reverse
701
+ )
702
+ if not rolls:
703
+ continue
704
  waste, waste_pct = calculate_waste(rolls, original_dims)
705
  if not_placed == 0:
706
  key = (waste, len(rolls), 0)
707
  if best_key is None or key < best_key:
708
  best_key = key
709
+ img, total_true, total_roll, total_rot = render_multi_roll(
710
+ rolls, original_dims, margin
711
+ )
712
  is_g, g_v = is_guillotine_cuttable(rolls, margin)
713
  stats = [
714
  "🎯 MULTI-WIDTH MULTI-ROLL (tiap roll beda lebar)",
 
725
  best_overall = (img, "\n".join(stats), waste, waste_pct)
726
  best_width = "multi"
727
 
728
+ # SINGLE-WIDTH per lebar
729
  for width in all_widths:
730
  if search_mode == "quick":
731
  result = pack_multi_roll(rects, width, max_height, bool(allow_rotation))
 
733
  width_results.append((width, None, None, "Gagal"))
734
  continue
735
  rolls, not_placed = result
736
+ img, total_true, total_roll, total_rot = render_multi_roll(
737
+ rolls, original_dims, margin
738
+ )
739
  waste, waste_pct = calculate_waste(rolls, original_dims)
740
  num_rolls = len(rolls)
741
+
742
  stats = [
743
  f"πŸ† Mode : CEPAT",
744
  f"πŸ“ Lebar roll : {width:g} cm",
 
746
  f"♻️ Total waste : {waste:.1f} cmΒ²",
747
  f"πŸ“Š Persentase waste : {waste_pct:.2f}%",
748
  ]
749
+
750
  key = (waste, num_rolls, sum(h for _, h, _ in rolls))
751
  if best_key is None or key < best_key:
752
  best_key = key
753
  best_overall = (img, "\n".join(stats), waste, waste_pct)
754
  best_width = width
755
+
756
  width_results.append((width, waste, waste_pct, num_rolls, f"{waste_pct:.2f}%"))
757
  global_tried += 1
758
+ if waste_pct <= target_waste_pct:
759
+ break
760
+
761
  else:
762
+ img, stats, waste, waste_pct, num_rolls, tried, hit = search_single_width(
763
+ rects, original_dims, total_rects, max_height,
764
+ width, margin, bool(allow_rotation),
765
+ search_mode, target_waste_pct, 4.0
766
+ )
767
  global_tried += tried
768
+
769
  if img is None:
770
  width_results.append((width, None, None, None, "Gagal"))
771
  continue
772
+
773
+ key = (waste if waste is not None else float('inf'),
774
+ num_rolls if num_rolls else 99, 0)
775
  if best_key is None or key < best_key:
776
  best_key = key
777
  best_overall = (img, stats, waste, waste_pct)
778
  best_width = width
779
+
780
  width_results.append((width, waste, waste_pct, num_rolls, f"{waste_pct:.2f}%"))
781
+ if hit:
782
+ break
783
 
784
  if best_overall is None:
785
  return None, "⚠️ Tidak ada satupun lebar roll yang bisa menampung semua banner."
786
 
787
  img, stats, best_waste, best_waste_pct = best_overall
788
+
789
  comparison = ["\n" + "─" * 55, "πŸ“‹ PERBANDINGAN LEBAR ROLL (10 teratas):"]
790
  sorted_r = sorted([r for r in width_results if r[1] is not None], key=lambda x: (x[1], x[3]))
791
  for w, waste, wpct, rolls, note in sorted_r[:10]:
792
  mark = " ⭐ PALING HEMAT" if w == best_width else ""
793
  target = " 🎯" if isinstance(wpct, (int, float)) and wpct <= target_waste_pct else ""
794
+ comparison.append(
795
+ f" {'βœ…' if w == best_width else ' '} {w:g} cm β†’ "
796
+ f"{rolls} roll, waste {waste:.1f} cmΒ² ({note}){mark}{target}"
797
+ )
798
 
799
  final = stats + "\n" + "\n".join(comparison)
800
  final += f"\n{'─' * 55}\nπŸ” Total iterasi keseluruhan: {global_tried} kombinasi"
801
+
802
  return img, final
803
 
804
+
805
  # --------------------------------------------------------------------------
806
+ # 11. UI GRADIO
807
  # --------------------------------------------------------------------------
808
+
809
  with gr.Blocks(title="Nesting Otomatis Banner v2 β€” Super Optimized") as demo:
810
  gr.Markdown("# πŸ–¨οΈ Nesting Otomatis v2 β€” Simulated Annealing + Multi-Width")
811
+ gr.Markdown(
812
+ "Upgrade: **Simulated Annealing**, **Multi-Width Multi-Roll**, "
813
+ "dan **Guillotine Validation**. Berburu waste minimum dengan target."
814
+ )
815
 
816
  with gr.Row():
817
  with gr.Column(scale=1):
818
+ roll_widths = gr.Textbox(
819
+ label="Daftar Lebar Roll (cm, pisah koma)",
820
+ value="150, 200, 250, 300",
821
+ placeholder="Contoh: 150, 200, 250, 300",
822
+ )
823
  margin = gr.Number(label="Jarak Antar Item / Margin (cm)", value=2, minimum=0)
824
  allow_rotation = gr.Checkbox(label="Izinkan Rotasi Otomatis", value=True)
825
+
826
+ target_waste = gr.Number(
827
+ label="🎯 Target Waste Maksimum (%)",
828
+ value=5.0, minimum=0.1, maximum=50.0, step=0.5,
829
+ )
830
+
831
+ enable_multiwidth = gr.Checkbox(
832
+ label="🎨 Aktifkan Multi-Width Multi-Roll (tiap roll beda lebar)",
833
+ value=False,
834
+ )
835
+
836
  search_mode = gr.Dropdown(
837
  label="Mode Pencarian",
838
+ choices=[
839
+ ("⚑ Cepat", "quick"),
840
+ ("🎯 Standar (~120)", "standard"),
841
+ ("πŸ” Dalaman (~464)", "deep"),
842
+ ("🧠 Pro (~3.000+ + Simulated Annealing)", "pro"),
843
+ ("πŸ’Ž Menyeluruh (~8.000+ + SA + Swap)", "exhaustive"),
844
+ ],
845
  value="standard",
846
  )
847
 
848
+ gr.Markdown("### πŸ“₯ Form Input Banner Baru")
 
849
  with gr.Row():
850
+ input_label = gr.Textbox(label="Label Banner", value="Banner Baru")
851
+ input_width = gr.Number(label="Lebar (cm)", value=100)
852
  with gr.Row():
853
+ input_height = gr.Number(label="Tinggi (cm)", value=60)
854
+ input_qty = gr.Number(label="Jumlah (Qty)", value=1, precision=0)
855
 
856
+ btn_add = gr.Button("βž• Tambah ke Daftar Banner", variant="secondary")
 
 
857
 
858
+ gr.Markdown("### πŸ“‹ Daftar Banner (Akumulasi)")
 
859
  data_input = gr.Dataframe(
860
  headers=["Label", "Width", "Height", "Qty"],
861
  datatype=["str", "number", "number", "number"],
862
+ row_count=(3, "dynamic"),
863
+ value=[
864
+ ["Banner A", 100, 60, 3],
865
+ ["Banner B", 80, 120, 2],
866
+ ["Banner C", 50, 50, 4],
867
+ ],
868
+ )
869
+
870
+ # Event listener untuk tombol tambah (bisa diklik berkali-kali)
871
+ btn_add.click(
872
+ fn=add_banner_to_list,
873
+ inputs=[input_label, input_width, input_height, input_qty, data_input],
874
+ outputs=[data_input]
875
  )
 
876
 
877
+ btn = gr.Button("πŸš€ PROSES SUPER OPTIMIZED", variant="primary")
878
 
879
  with gr.Column(scale=2):
880
  output_img = gr.Image(label="Pratinjau Layout Cetakan", type="pil")
881
  output_stats = gr.Textbox(label="Statistik Hasil Nesting", lines=16)
882
 
883
+ btn.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
884
  fn=process,
885
+ inputs=[roll_widths, margin, allow_rotation, search_mode, target_waste,
886
+ enable_multiwidth, data_input],
887
  outputs=[output_img, output_stats],
888
  )
889
 
890
  if __name__ == "__main__":
891
+ demo.launch()