FajarHidaa commited on
Commit
c2ea5fd
·
verified ·
1 Parent(s): 7dc5464

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1275
app.py DELETED
@@ -1,1275 +0,0 @@
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
- )
18
- from rectpack.maxrects import MaxRectsBl, MaxRectsBssf, MaxRectsBaf, MaxRectsBlsf
19
- from rectpack.skyline import (
20
- SkylineBl, SkylineBlWm, SkylineMwf, SkylineMwfl, SkylineMwfWm, SkylineMwflWm
21
- )
22
- from rectpack.guillotine import (
23
- GuillotineBssfSas, GuillotineBssfLas, GuillotineBssfSlas,
24
- GuillotineBssfLlas, GuillotineBssfMaxas, GuillotineBssfMinas,
25
- GuillotineBafSas, GuillotineBafLas, GuillotineBafSlas,
26
- GuillotineBafLlas, GuillotineBafMaxas, GuillotineBafMinas,
27
- GuillotineBlsfSas, GuillotineBlsfLas, GuillotineBlsfSlas,
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",
44
- "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
45
- ]
46
- for path in candidates:
47
- try:
48
- return ImageFont.truetype(path, size)
49
- except Exception:
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, item_margin, 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
- m = float(item_margin) if item_margin is not None else 0.0
74
- if m < 0:
75
- m = 0.0
76
- except (TypeError, ValueError):
77
- return current_data # Abaikan jika nilai tidak valid
78
-
79
- new_row = [str(label).strip(), w, h, m]
80
-
81
- # Tangkap apakah current_data berupa DataFrame pandas atau List of Lists
82
- if isinstance(current_data, pd.DataFrame):
83
- new_row_df = pd.DataFrame([new_row], columns=current_data.columns)
84
- return pd.concat([current_data, new_row_df], ignore_index=True)
85
- elif isinstance(current_data, list):
86
- return current_data + [new_row]
87
- else:
88
- return [new_row]
89
-
90
-
91
-
92
- # --------------------------------------------------------------------------
93
- # 2. PERSIAPAN DATA
94
- # --------------------------------------------------------------------------
95
-
96
- def prepare_rects(df: pd.DataFrame):
97
- """
98
- Setiap baris di tabel = satu banner (tanpa Qty). Margin/jarak antar item
99
- kini dibaca PER BARIS dari kolom "Margin", sehingga tiap desain banner
100
- bisa punya jarak potong yang berbeda-beda. Untuk mencetak banner yang
101
- sama lebih dari satu kali, tambahkan baris terpisah lewat form input
102
- (bisa dengan label & margin yang sama).
103
- """
104
- rects, original_dims, item_margins = [], {}, {}
105
- for idx, row in df.iterrows():
106
- label = str(row["Label"]).strip() or f"Item{idx}"
107
- try:
108
- w, h = float(row["Width"]), float(row["Height"])
109
- m = float(row["Margin"]) if pd.notna(row.get("Margin")) else 0.0
110
- except (TypeError, ValueError):
111
- continue
112
- if w <= 0 or h <= 0:
113
- continue
114
- if m < 0:
115
- m = 0.0
116
- rid = f"{label}#{idx}"
117
- rects.append((w + m * 2, h + m * 2, rid))
118
- original_dims[rid] = (w, h)
119
- item_margins[rid] = m
120
- if not rects:
121
- return None, None, None, 0, 0
122
- max_margin = max(item_margins.values()) if item_margins else 0.0
123
- max_height = sum(h for _, h, _ in rects) + max_margin * (len(rects) + 2) + 50
124
- return rects, original_dims, item_margins, len(rects), max_height
125
-
126
-
127
- # --------------------------------------------------------------------------
128
- # 3. CORE: PACKING ENGINE
129
- # --------------------------------------------------------------------------
130
-
131
- def pack_multi_roll(rects, roll_width, max_height, allow_rotation,
132
- pack_algo=None, sort_algo=None, reverse=False):
133
- remaining = list(reversed(rects)) if reverse else rects[:]
134
- rolls, safety = [], 50
135
- for _ in range(safety):
136
- if not remaining:
137
- break
138
- kwargs = {"rotation": allow_rotation}
139
- if pack_algo:
140
- kwargs["pack_algo"] = pack_algo
141
- if sort_algo:
142
- kwargs["sort_algo"] = sort_algo
143
- packer = newPacker(**kwargs)
144
- for w, h, rid in remaining:
145
- packer.add_rect(w, h, rid=rid)
146
- packer.add_bin(roll_width, max_height)
147
- packer.pack()
148
- if len(packer) == 0 or len(packer[0]) == 0:
149
- return rolls, len(remaining)
150
- placed = packer[0]
151
- used_height = max(r.y + r.height for r in placed)
152
- rolls.append((placed, used_height, roll_width))
153
- placed_ids = {r.rid for r in placed}
154
- remaining = [r for r in remaining if r[2] not in placed_ids]
155
- return rolls, len(remaining)
156
-
157
-
158
- # --------------------------------------------------------------------------
159
- # 4. GUILLOTINE CUT VALIDATION
160
- # --------------------------------------------------------------------------
161
-
162
- def is_guillotine_cuttable(rolls):
163
- violations = 0
164
- for placed, used_height, roll_width in rolls:
165
- items = []
166
- for r in placed:
167
- items.append({
168
- 'x': r.x, 'y': r.y,
169
- 'w': r.width, 'h': r.height,
170
- 'rid': r.rid
171
- })
172
- for a in items:
173
- has_free_top = a['y'] + a['h'] >= used_height - 0.01
174
- has_free_bottom = a['y'] <= 0.01
175
- has_free_left = a['x'] <= 0.01
176
- has_free_right = a['x'] + a['w'] >= roll_width - 0.01
177
- if has_free_top or has_free_bottom or has_free_left or has_free_right:
178
- continue
179
-
180
- can_slide_up = all(
181
- not (b['x'] < a['x'] + a['w'] and b['x'] + b['w'] > a['x'] and
182
- b['y'] > a['y'] + a['h'])
183
- for b in items if b['rid'] != a['rid']
184
- )
185
- if can_slide_up:
186
- continue
187
-
188
- can_slide_down = all(
189
- not (b['x'] < a['x'] + a['w'] and b['x'] + b['w'] > a['x'] and
190
- b['y'] + b['h'] < a['y'])
191
- for b in items if b['rid'] != a['rid']
192
- )
193
- if can_slide_down:
194
- continue
195
-
196
- can_slide_left = all(
197
- not (b['y'] < a['y'] + a['h'] and b['y'] + b['h'] > a['y'] and
198
- b['x'] + b['w'] < a['x'])
199
- for b in items if b['rid'] != a['rid']
200
- )
201
- if can_slide_left:
202
- continue
203
-
204
- can_slide_right = all(
205
- not (b['y'] < a['y'] + a['h'] and b['y'] + b['h'] > a['y'] and
206
- b['x'] > a['x'] + a['w'])
207
- for b in items if b['rid'] != a['rid']
208
- )
209
- if can_slide_right:
210
- continue
211
-
212
- violations += 1
213
- return violations == 0, violations
214
-
215
-
216
- # --------------------------------------------------------------------------
217
- # 5. VISUALISASI
218
- # --------------------------------------------------------------------------
219
-
220
- def render_multi_roll(rolls, original_dims, item_margins, px_per_unit=4.0):
221
- if not rolls:
222
- return None, 0, 0, 0
223
-
224
- max_roll_w = max(w for _, _, w in rolls)
225
- img_w = max(1, int(round(max_roll_w * px_per_unit)))
226
- gap = 40
227
- total_h = sum(int(round(h * px_per_unit)) for _, h, _ in rolls)
228
- total_h += gap * (len(rolls) - 1) + 60
229
-
230
- img = Image.new("RGB", (img_w, total_h), "white")
231
- draw = ImageDraw.Draw(img)
232
- font = load_font(14)
233
- font_small = load_font(11)
234
- font_title = load_font(16)
235
-
236
- y_offset, total_true, total_roll_area, total_rot = 0, 0, 0, 0
237
-
238
- for roll_idx, (placed, used_height, roll_width) in enumerate(rolls):
239
- roll_h_px = int(round(used_height * px_per_unit))
240
- roll_label = f"ROLL {roll_idx + 1} | {roll_width:g} x {used_height:.1f} cm"
241
- draw.text((img_w / 2, y_offset + 5), roll_label, fill="#cc0000", font=font_title, anchor="ma")
242
-
243
- roll_y0 = y_offset + 25
244
- roll_y1 = roll_y0 + roll_h_px
245
- draw.rectangle([0, roll_y0, int(round(roll_width * px_per_unit)) - 1, roll_y1], outline="red", width=3)
246
-
247
- for r in placed:
248
- base_label = r.rid.rsplit("#", 1)[0]
249
- color = generate_color(base_label)
250
- outer_color = lighten_color(color, 0.55)
251
- inner_color = color
252
- orig_w, orig_h = original_dims[r.rid]
253
- item_margin = item_margins.get(r.rid, 0.0)
254
- is_rotated = round(r.width - item_margin * 2, 3) != round(orig_w, 3)
255
-
256
- x0 = r.x * px_per_unit
257
- y0 = roll_y0 + (used_height - r.y - r.height) * px_per_unit
258
- x1 = (r.x + r.width) * px_per_unit
259
- y1 = roll_y0 + (used_height - r.y) * px_per_unit
260
-
261
- m = item_margin * px_per_unit
262
- ix0, iy0 = x0 + m, y0 + m
263
- ix1, iy1 = x1 - m, y1 - m
264
-
265
- draw.rectangle([x0, y0, x1, y1], fill=outer_color, outline="black", width=2)
266
- if ix1 > ix0 and iy1 > iy0:
267
- draw.rectangle([ix0, iy0, ix1, iy1], fill=inner_color, outline="black", width=1)
268
-
269
- label_text = base_label
270
- size_text = f"{orig_w:g} x {orig_h:g}" + (" (diputar)" if is_rotated else "")
271
- bbox_label = draw.textbbox((0, 0), label_text, font=font)
272
- bbox_size = draw.textbbox((0, 0), size_text, font=font_small)
273
- total_th = (bbox_label[3] - bbox_label[1]) + (bbox_size[3] - bbox_size[1]) + 4
274
- cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
275
- ty = cy - total_th / 2
276
- if (x1 - x0) > 20 and (y1 - y0) > 20:
277
- draw.text((cx, ty), label_text, fill="black", font=font, anchor="ma")
278
- draw.text((cx, ty + (bbox_label[3] - bbox_label[1]) + 4), size_text,
279
- fill="black", font=font_small, anchor="ma")
280
-
281
- total_true += orig_w * orig_h
282
- if is_rotated:
283
- total_rot += 1
284
-
285
- for x in range(0, int(round(roll_width * px_per_unit)), 20):
286
- draw.line([(x, roll_y0), (x, roll_y1)], fill="#f5f5f5", width=1)
287
- for y in range(int(roll_y0), int(roll_y1), 20):
288
- draw.line([(0, y), (int(round(roll_width * px_per_unit)) - 1, y)], fill="#f5f5f5", width=1)
289
-
290
- total_roll_area += roll_width * used_height
291
- y_offset = roll_y1 + gap
292
-
293
- return img, total_true, total_roll_area, total_rot
294
-
295
-
296
- # --------------------------------------------------------------------------
297
- # 5b. EKSPOR SVG (skala 1 unit SVG = 1 cm, untuk dibuka di CorelDraw/Illustrator)
298
- # --------------------------------------------------------------------------
299
-
300
- def _xml_escape(text: str) -> str:
301
- return (
302
- str(text)
303
- .replace("&", "&amp;")
304
- .replace("<", "&lt;")
305
- .replace(">", "&gt;")
306
- .replace('"', "&quot;")
307
- )
308
-
309
-
310
- def render_svg(rolls, original_dims, item_margins, roll_gap_cm=10.0, header_h_cm=2.0):
311
- """
312
- Render layout nesting sebagai SVG vektor, 1 unit SVG = 1 cm.
313
- Tiap item digambar dengan DUA kotak:
314
- - Kotak LUAR (garis hitam) = area termasuk margin/jarak antar item = garis potong roll.
315
- - Kotak DALAM (garis biru putus-putus) = ukuran desain ASLI banner
316
- (tanpa margin). Ini adalah area yang harus diisi dengan desain asli
317
- saat file dibuka di CorelDraw, sehingga posisinya sudah pas dengan
318
- hasil nesting.
319
- Jika item diputar 90°, kotak dalam otomatis ikut ditukar (swap w/h)
320
- supaya tetap merepresentasikan orientasi tempel yang benar.
321
- Roll ditumpuk vertikal, sama seperti pratinjau PNG, supaya keduanya
322
- konsisten secara visual.
323
- """
324
- if not rolls:
325
- return None
326
-
327
- max_roll_w = max(w for _, _, w in rolls)
328
- total_h = (
329
- sum(h for _, h, _ in rolls)
330
- + header_h_cm * len(rolls)
331
- + roll_gap_cm * max(0, len(rolls) - 1)
332
- )
333
-
334
- svg = []
335
- svg.append(
336
- f'<svg xmlns="http://www.w3.org/2000/svg" '
337
- f'width="{max_roll_w:.4f}cm" height="{total_h:.4f}cm" '
338
- f'viewBox="0 0 {max_roll_w:.4f} {total_h:.4f}">'
339
- )
340
- svg.append(
341
- '<desc>Layout nesting banner. 1 unit SVG = 1 cm. '
342
- 'Kotak hitam = garis potong roll (termasuk margin). '
343
- 'Kotak biru putus-putus = ukuran &amp; posisi desain asli banner.</desc>'
344
- )
345
-
346
- y_offset = 0.0
347
- for roll_idx, (placed, used_height, roll_width) in enumerate(rolls):
348
- label_y = y_offset + header_h_cm - 0.4
349
- svg.append(
350
- f'<text x="{roll_width / 2:.4f}" y="{label_y:.4f}" '
351
- f'font-family="sans-serif" font-size="0.7" text-anchor="middle" '
352
- f'fill="#cc0000">ROLL {roll_idx + 1} | {roll_width:g} x {used_height:.1f} cm</text>'
353
- )
354
-
355
- roll_y0 = y_offset + header_h_cm
356
- roll_y1 = roll_y0 + used_height
357
- svg.append(
358
- f'<rect x="0" y="{roll_y0:.4f}" width="{roll_width:.4f}" height="{used_height:.4f}" '
359
- f'fill="none" stroke="red" stroke-width="0.08"/>'
360
- )
361
-
362
- for r in placed:
363
- base_label = r.rid.rsplit("#", 1)[0]
364
- orig_w, orig_h = original_dims[r.rid]
365
- item_margin = item_margins.get(r.rid, 0.0)
366
- is_rotated = round(r.width - item_margin * 2, 3) != round(orig_w, 3)
367
-
368
- # Kotak luar (footprint termasuk margin), y di-flip spy sama
369
- # orientasinya dgn pratinjau PNG (roll dibaca dari bawah ke atas).
370
- x0 = r.x
371
- y0 = roll_y0 + (used_height - r.y - r.height)
372
- w0 = r.width
373
- h0 = r.height
374
-
375
- svg.append(
376
- f'<rect x="{x0:.4f}" y="{y0:.4f}" width="{w0:.4f}" height="{h0:.4f}" '
377
- f'fill="none" stroke="black" stroke-width="0.05"/>'
378
- )
379
-
380
- # Kotak dalam = ukuran desain asli (swap kalau item diputar)
381
- inner_w, inner_h = (orig_h, orig_w) if is_rotated else (orig_w, orig_h)
382
- ix0 = x0 + item_margin
383
- iy0 = y0 + item_margin
384
- if inner_w > 0 and inner_h > 0:
385
- svg.append(
386
- f'<rect x="{ix0:.4f}" y="{iy0:.4f}" width="{inner_w:.4f}" height="{inner_h:.4f}" '
387
- f'fill="none" stroke="blue" stroke-width="0.04" stroke-dasharray="0.3,0.2"/>'
388
- )
389
-
390
- label_text = f"{base_label} ({orig_w:g}x{orig_h:g}{'R' if is_rotated else ''})"
391
- svg.append(
392
- f'<text x="{x0 + w0 / 2:.4f}" y="{y0 + h0 / 2:.4f}" '
393
- f'font-family="sans-serif" font-size="0.4" text-anchor="middle" '
394
- f'dominant-baseline="middle" fill="#333333">{_xml_escape(label_text)}</text>'
395
- )
396
-
397
- y_offset = roll_y1 + roll_gap_cm
398
-
399
- svg.append('</svg>')
400
- return "\n".join(svg)
401
-
402
-
403
- def export_svg_file(rolls, original_dims, item_margins):
404
- """
405
- Tulis hasil render_svg() ke file .svg di folder 'exports/' dan kembalikan
406
- path-nya, supaya bisa dipakai sebagai output gr.File (tombol download).
407
- Nama file memakai uuid4 (bukan timestamp detik) supaya aman dipakai
408
- banyak user sekaligus di HuggingFace Space publik tanpa risiko
409
- tabrakan/overwrite antar request yang terjadi di detik yang sama.
410
- """
411
- if not rolls or not original_dims:
412
- return None
413
- svg_str = render_svg(rolls, original_dims, item_margins or {})
414
- if not svg_str:
415
- return None
416
-
417
- import os
418
- import uuid
419
-
420
- out_dir = "exports"
421
- os.makedirs(out_dir, exist_ok=True)
422
- path = os.path.join(out_dir, f"nesting_layout_{uuid.uuid4().hex}.svg")
423
- with open(path, "w", encoding="utf-8") as f:
424
- f.write(svg_str)
425
- return path
426
-
427
-
428
- # --------------------------------------------------------------------------
429
- # 6. STRATEGI PRE-SORT
430
- # --------------------------------------------------------------------------
431
-
432
- def get_pre_sort_strategies(rects):
433
- strategies = []
434
-
435
- def area(r):
436
- return r[0] * r[1]
437
-
438
- def max_side(r):
439
- return max(r[0], r[1])
440
-
441
- def ratio(r):
442
- return max(r[0], r[1]) / max(min(r[0], r[1]), 0.001)
443
-
444
- base = [
445
- ("default", rects[:]),
446
- ("area_desc", sorted(rects, key=area, reverse=True)),
447
- ("area_asc", sorted(rects, key=area)),
448
- ("width_desc", sorted(rects, key=lambda r: r[0], reverse=True)),
449
- ("width_asc", sorted(rects, key=lambda r: r[0])),
450
- ("height_desc", sorted(rects, key=lambda r: r[1], reverse=True)),
451
- ("height_asc", sorted(rects, key=lambda r: r[1])),
452
- ("longest_desc", sorted(rects, key=max_side, reverse=True)),
453
- ("ratio_desc", sorted(rects, key=ratio, reverse=True)),
454
- ("ratio_asc", sorted(rects, key=ratio)),
455
- ]
456
- strategies.extend(base)
457
-
458
- label_groups = {}
459
- for r in rects:
460
- label = r[2].rsplit("#", 1)[0]
461
- label_groups.setdefault(label, []).append(r)
462
- grouped = []
463
- for label in sorted(label_groups.keys()):
464
- grouped.extend(label_groups[label])
465
- strategies.append(("group_label", grouped))
466
-
467
- by_area = sorted(rects, key=area, reverse=True)
468
- interleaved = []
469
- i, j = 0, len(by_area) - 1
470
- while i <= j:
471
- interleaved.append(by_area[i])
472
- if i != j:
473
- interleaved.append(by_area[j])
474
- i += 1
475
- j -= 1
476
- strategies.append(("interleave", interleaved))
477
- return strategies
478
-
479
-
480
- # --------------------------------------------------------------------------
481
- # 7. SIMULATED ANNEALING
482
- # --------------------------------------------------------------------------
483
-
484
- def calculate_waste(rolls, original_dims):
485
- total_true = sum(
486
- original_dims[r.rid][0] * original_dims[r.rid][1]
487
- for placed, _, _ in rolls for r in placed
488
- )
489
- total_roll = sum(w * h for _, h, w in rolls)
490
- return total_roll - total_true, (total_roll - total_true) / total_roll * 100 if total_roll else 100
491
-
492
-
493
- def unified_key(waste, num_rolls, not_placed):
494
- """
495
- Langkah 5: format key SATU-SATUNYA yang dipakai untuk membandingkan
496
- hasil single-width, multi-width, dan mode cepat, supaya perbandingan
497
- `key < best_key` semantiknya valid di seluruh jalur di process().
498
- Item yang tidak muat diberi penalti besar (bukan diskualifikasi total),
499
- supaya solusi yang menempatkan semua item selalu diprioritaskan tapi
500
- solusi hampir-sempurna tetap bisa bersaing.
501
- """
502
- return (waste + not_placed * 1e6, num_rolls, not_placed)
503
-
504
-
505
- def simulated_annealing(rects, roll_width, max_height, allow_rotation,
506
- pack_algo, sort_algo, original_dims,
507
- initial_temp=100, cooling=0.995, max_iter=3000):
508
- current = rects[:]
509
- best = rects[:]
510
- best_result = None
511
- best_waste = float('inf')
512
- current_result, _ = pack_multi_roll(
513
- current, roll_width, max_height, allow_rotation, pack_algo, sort_algo, False
514
- )
515
- if not current_result:
516
- return None, float('inf')
517
- current_waste, _ = calculate_waste(current_result, original_dims)
518
-
519
- temp = initial_temp
520
-
521
- for i in range(max_iter):
522
- neighbor = current[:]
523
- op = random.choice(['swap', 'reverse', 'insert'])
524
- if op == 'swap' and len(neighbor) > 1:
525
- a, b = random.sample(range(len(neighbor)), 2)
526
- neighbor[a], neighbor[b] = neighbor[b], neighbor[a]
527
- elif op == 'reverse' and len(neighbor) > 2:
528
- a, b = sorted(random.sample(range(len(neighbor)), 2))
529
- neighbor[a:b + 1] = list(reversed(neighbor[a:b + 1]))
530
- elif op == 'insert' and len(neighbor) > 1:
531
- a = random.randint(0, len(neighbor) - 1)
532
- b = random.randint(0, len(neighbor) - 1)
533
- item = neighbor.pop(a)
534
- neighbor.insert(b, item)
535
-
536
- rolls, _ = pack_multi_roll(
537
- neighbor, roll_width, max_height, allow_rotation, pack_algo, sort_algo, False
538
- )
539
- if not rolls:
540
- continue
541
-
542
- waste, _ = calculate_waste(rolls, original_dims)
543
-
544
- if waste < best_waste:
545
- best_waste = waste
546
- best = neighbor[:]
547
- best_result = rolls
548
- if waste < current_waste or random.random() < math.exp((current_waste - waste) / max(temp, 0.001)):
549
- current = neighbor[:]
550
- current_waste = waste
551
-
552
- temp *= cooling
553
-
554
- return best_result, best_waste
555
-
556
-
557
- # --------------------------------------------------------------------------
558
- # 8. MULTI-WIDTH MULTI-ROLL (FIXED: tambah original_dims parameter)
559
- # --------------------------------------------------------------------------
560
-
561
- def _try_pack_width(remaining, w, max_height, allow_rotation, pack_algo, sort_algo, original_dims):
562
- """
563
- Helper: coba pack 'remaining' rects ke satu bin lebar w. Return None kalau
564
- gagal, atau (waste, placed, used_height, new_remaining) kalau berhasil.
565
- Dipakai bersama oleh pack_multi_width_multi_roll (greedy dan lookahead).
566
- """
567
- kwargs = {"rotation": allow_rotation}
568
- if pack_algo:
569
- kwargs["pack_algo"] = pack_algo
570
- if sort_algo:
571
- kwargs["sort_algo"] = sort_algo
572
- packer = newPacker(**kwargs)
573
- for rect_w, rect_h, rid in remaining:
574
- packer.add_rect(rect_w, rect_h, rid=rid)
575
- packer.add_bin(w, max_height)
576
- packer.pack()
577
-
578
- if len(packer) == 0 or len(packer[0]) == 0:
579
- return None
580
-
581
- placed = packer[0]
582
- used_height = max(r.y + r.height for r in placed)
583
- placed_ids = {r.rid for r in placed}
584
-
585
- true_area = sum(
586
- (original_dims[rid][0] * original_dims[rid][1])
587
- for _, _, rid in remaining if rid in placed_ids
588
- )
589
- roll_area = w * used_height
590
- waste = roll_area - true_area
591
- new_remaining = [r for r in remaining if r[2] not in placed_ids]
592
- return waste, placed, used_height, new_remaining
593
-
594
-
595
- def pack_multi_width_multi_roll(rects, widths, max_height, allow_rotation,
596
- original_dims, # <-- FIX: tambah parameter ini
597
- pack_algo=None, sort_algo=None, reverse=False,
598
- lookahead=False, lookahead_k=3):
599
- """
600
- Packing di mana TIAP ROLL boleh beda lebar.
601
-
602
- Langkah 4: bila lookahead=True, alih-alih langsung memilih lebar dengan
603
- waste terkecil untuk roll SAAT INI saja (murni greedy), fungsi ini
604
- mengambil top-`lookahead_k` kandidat lebar berdasar waste roll ini, lalu
605
- untuk tiap kandidat mengintip 1 roll ke depan (waste terbaik yang bisa
606
- dicapai pada sisa item) dan memilih kandidat dengan total waste gabungan
607
- (roll ini + estimasi roll berikutnya) terkecil. Ini membantu menghindari
608
- jebakan lokal di mana pilihan yang "tampak" optimal untuk roll saat ini
609
- justru membuat sisa item sulit dinestik secara efisien di roll berikutnya.
610
- """
611
- remaining = list(reversed(rects)) if reverse else rects[:]
612
- all_rolls = []
613
- safety = 50
614
-
615
- for _ in range(safety):
616
- if not remaining:
617
- break
618
-
619
- candidates = []
620
- for w in widths:
621
- res = _try_pack_width(remaining, w, max_height, allow_rotation,
622
- pack_algo, sort_algo, original_dims)
623
- if res is None:
624
- continue
625
- waste, placed, used_height, new_remaining = res
626
- candidates.append((waste, placed, used_height, w, new_remaining))
627
-
628
- if not candidates:
629
- return all_rolls, len(remaining)
630
-
631
- candidates.sort(key=lambda c: c[0])
632
-
633
- if not lookahead or len(candidates) <= 1:
634
- chosen = candidates[0]
635
- else:
636
- topk = candidates[:lookahead_k]
637
- chosen = None
638
- best_total = float('inf')
639
- for waste, placed, used_height, w, new_remaining in topk:
640
- if new_remaining:
641
- # Intip 1 langkah ke depan: waste terbaik di antara semua
642
- # lebar untuk sisa item setelah kandidat ini dipilih.
643
- next_best = float('inf')
644
- for w2 in widths:
645
- res2 = _try_pack_width(new_remaining, w2, max_height, allow_rotation,
646
- pack_algo, sort_algo, original_dims)
647
- if res2 is not None and res2[0] < next_best:
648
- next_best = res2[0]
649
- total = waste + (next_best if next_best != float('inf') else 0)
650
- else:
651
- total = waste
652
- if total < best_total:
653
- best_total = total
654
- chosen = (waste, placed, used_height, w, new_remaining)
655
-
656
- _, placed, used_height, w, new_remaining = chosen
657
- all_rolls.append((placed, used_height, w))
658
- remaining = new_remaining
659
-
660
- return all_rolls, len(remaining)
661
-
662
-
663
- # --------------------------------------------------------------------------
664
- # 8b. SIMULATED ANNEALING UNTUK MULTI-WIDTH MULTI-ROLL (Langkah 2)
665
- # --------------------------------------------------------------------------
666
-
667
- def simulated_annealing_multi_width(rects, widths, max_height, allow_rotation,
668
- pack_algo, sort_algo, original_dims,
669
- initial_temp=100, cooling=0.995, max_iter=1500):
670
- """
671
- Versi SA dari simulated_annealing(), tapi memakai pack_multi_width_multi_roll
672
- sebagai fungsi evaluasi sehingga tiap roll boleh punya lebar berbeda.
673
- Key evaluasi memakai (waste, not_placed) supaya solusi yang menempatkan
674
- semua item tetap diprioritaskan, tapi solusi dengan sedikit item tidak
675
- muat tidak langsung dibuang (lihat _mw_score).
676
- """
677
- def _mw_score(rolls, not_placed):
678
- waste, _ = calculate_waste(rolls, original_dims)
679
- # Penalti besar per item tidak muat, tapi tidak diskualifikasi total
680
- return waste + not_placed * 1e6, waste
681
-
682
- current = rects[:]
683
- best = rects[:]
684
- best_result = None
685
- best_not_placed = None
686
- best_waste = float('inf')
687
- best_score = float('inf')
688
-
689
- current_result, current_not_placed = pack_multi_width_multi_roll(
690
- current, widths, max_height, allow_rotation, original_dims, pack_algo, sort_algo, False
691
- )
692
- if not current_result:
693
- return None, float('inf'), None
694
- current_score, current_waste = _mw_score(current_result, current_not_placed)
695
- best_result, best_not_placed, best_waste, best_score = (
696
- current_result, current_not_placed, current_waste, current_score
697
- )
698
-
699
- temp = initial_temp
700
-
701
- for _ in range(max_iter):
702
- neighbor = current[:]
703
- op = random.choice(['swap', 'reverse', 'insert'])
704
- if op == 'swap' and len(neighbor) > 1:
705
- a, b = random.sample(range(len(neighbor)), 2)
706
- neighbor[a], neighbor[b] = neighbor[b], neighbor[a]
707
- elif op == 'reverse' and len(neighbor) > 2:
708
- a, b = sorted(random.sample(range(len(neighbor)), 2))
709
- neighbor[a:b + 1] = list(reversed(neighbor[a:b + 1]))
710
- elif op == 'insert' and len(neighbor) > 1:
711
- a = random.randint(0, len(neighbor) - 1)
712
- b = random.randint(0, len(neighbor) - 1)
713
- item = neighbor.pop(a)
714
- neighbor.insert(b, item)
715
-
716
- rolls, not_placed = pack_multi_width_multi_roll(
717
- neighbor, widths, max_height, allow_rotation, original_dims, pack_algo, sort_algo, False
718
- )
719
- if not rolls:
720
- continue
721
-
722
- score, waste = _mw_score(rolls, not_placed)
723
-
724
- if score < best_score:
725
- best_score = score
726
- best_waste = waste
727
- best_not_placed = not_placed
728
- best = neighbor[:]
729
- best_result = rolls
730
- if score < current_score or random.random() < math.exp((current_score - score) / max(temp, 0.001)):
731
- current = neighbor[:]
732
- current_score = score
733
-
734
- temp *= cooling
735
-
736
- return best_result, best_waste, best_not_placed
737
-
738
-
739
- # --------------------------------------------------------------------------
740
- # 9. PENCARIAN UNTUK SATU LEBAR ROLL
741
- # --------------------------------------------------------------------------
742
-
743
- def search_single_width(rects, original_dims, total_rects, max_height,
744
- roll_width, item_margins, allow_rotation,
745
- search_mode, target_waste_pct, px_per_unit):
746
- best_result = None
747
- best_key = None
748
- best_config = None
749
- best_rolls = None
750
- tried, failed = 0, 0
751
- hit_target = False
752
-
753
- def evaluate(rolls, not_placed, config_name):
754
- nonlocal best_result, best_key, best_config, best_rolls, hit_target
755
- if not rolls:
756
- return
757
- waste, waste_pct = calculate_waste(rolls, original_dims)
758
- num_rolls = len(rolls)
759
- key = (waste, num_rolls, not_placed)
760
- if best_key is None or key < best_key:
761
- best_key = key
762
- best_result = (rolls, not_placed)
763
- best_config = config_name
764
- best_rolls = rolls
765
- if waste_pct <= target_waste_pct:
766
- hit_target = True
767
-
768
- def should_stop():
769
- return hit_target
770
-
771
- ALL_PACK = [
772
- None, MaxRectsBssf, MaxRectsBaf, MaxRectsBl, MaxRectsBlsf,
773
- SkylineBl, SkylineBlWm, SkylineMwf, SkylineMwfl,
774
- SkylineMwfWm, SkylineMwflWm,
775
- GuillotineBssfSas, GuillotineBssfLas, GuillotineBssfMaxas,
776
- GuillotineBafSas, GuillotineBafLas, GuillotineBafMaxas,
777
- GuillotineBlsfSas, GuillotineBlsfLas,
778
- ]
779
- ALL_SORT = [None, SORT_AREA, SORT_PERI, SORT_LSIDE, SORT_RATIO, SORT_DIFF]
780
-
781
- # PHASE 1: GRID SEARCH
782
- if search_mode in ("standard", "deep", "pro", "exhaustive"):
783
- if search_mode == "standard":
784
- pack_algos = [None, MaxRectsBssf, MaxRectsBaf, MaxRectsBlsf,
785
- SkylineMwfl, GuillotineBssfSas, GuillotineBafSas]
786
- sort_algos = [None, SORT_AREA, SORT_LSIDE]
787
- else:
788
- pack_algos, sort_algos = ALL_PACK, ALL_SORT
789
-
790
- for pack_algo in pack_algos:
791
- for sort_algo in sort_algos:
792
- for reverse in [False, True]:
793
- if should_stop():
794
- break
795
- tried += 1
796
- rolls, not_placed = pack_multi_roll(
797
- rects, roll_width, max_height, allow_rotation,
798
- pack_algo, sort_algo, reverse
799
- )
800
- if not rolls:
801
- failed += 1
802
- continue
803
- algo_name = pack_algo.__name__ if pack_algo else "Default"
804
- config = f"[Grid] {algo_name} + {get_sort_name(sort_algo)}{' rev' if reverse else ''}"
805
- evaluate(rolls, not_placed, config)
806
-
807
- # PHASE 2: PRE-SORT
808
- if search_mode in ("pro", "exhaustive") and not should_stop():
809
- for sort_name, sorted_rects in get_pre_sort_strategies(rects):
810
- for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
811
- for reverse in [False, True]:
812
- if should_stop():
813
- break
814
- tried += 1
815
- rolls, not_placed = pack_multi_roll(
816
- sorted_rects, roll_width, max_height, allow_rotation,
817
- pack_algo, SORT_NONE, reverse
818
- )
819
- if not rolls:
820
- failed += 1
821
- continue
822
- config = f"[PreSort:{sort_name}] {pack_algo.__name__ if pack_algo else 'Default'}{' rev' if reverse else ''}"
823
- evaluate(rolls, not_placed, config)
824
-
825
- # PHASE 3: SIMULATED ANNEALING
826
- if search_mode in ("pro", "exhaustive") and not should_stop():
827
- sa_configs = [
828
- (None, None), (MaxRectsBssf, SORT_AREA), (GuillotineBssfSas, SORT_AREA)
829
- ]
830
- for pack_algo, sort_algo in sa_configs:
831
- if should_stop():
832
- break
833
- tried += 1
834
- sa_rolls, sa_waste = simulated_annealing(
835
- rects, roll_width, max_height, allow_rotation,
836
- pack_algo, sort_algo, original_dims,
837
- initial_temp=100, cooling=0.995,
838
- max_iter=5000 if search_mode == "exhaustive" else 2000
839
- )
840
- if sa_rolls:
841
- algo_name = pack_algo.__name__ if pack_algo else "Default"
842
- config = f"[SA] {algo_name} (waste {sa_waste:.1f})"
843
- evaluate(sa_rolls, 0, config)
844
-
845
- # PHASE 4: LOCAL SWAP
846
- if search_mode == "exhaustive" and best_rolls and not should_stop():
847
- best_order = []
848
- placed_ids = set()
849
- for placed, _, _ in best_rolls:
850
- for r in placed:
851
- placed_ids.add(r.rid)
852
- for r in rects:
853
- if r[2] in placed_ids:
854
- best_order.append(r)
855
-
856
- n = len(best_order)
857
- for _ in range(min(500, n * n)):
858
- if should_stop():
859
- break
860
- i, j = random.randint(0, n - 1), random.randint(0, n - 1)
861
- if i == j:
862
- continue
863
- swapped = best_order[:]
864
- swapped[i], swapped[j] = swapped[j], swapped[i]
865
- tried += 1
866
- rolls, not_placed = pack_multi_roll(
867
- swapped, roll_width, max_height, allow_rotation, None, None, False
868
- )
869
- if not rolls:
870
- failed += 1
871
- continue
872
- evaluate(rolls, not_placed, f"[Swap:{i}-{j}]")
873
-
874
- if best_result is None:
875
- return None, f"⚠️ Lebar {roll_width:g} cm: tidak muat.", None, None, None, tried, False, None, None
876
-
877
- rolls, not_placed = best_result
878
- img, total_true, total_roll, total_rot = render_multi_roll(
879
- rolls, original_dims, item_margins, px_per_unit
880
- )
881
- waste, waste_pct = calculate_waste(rolls, original_dims)
882
- num_rolls = len(rolls)
883
-
884
- is_guillotine, g_violations = is_guillotine_cuttable(rolls)
885
-
886
- target_status = "✅ TARGET TERCAPAI!" if waste_pct <= target_waste_pct else "❌ Target belum tercapai"
887
-
888
- stats = [
889
- f"{'🎯' if waste_pct <= target_waste_pct else '⚠️'} {target_status}",
890
- f"🏆 Algoritma terpilih : {best_config}",
891
- f"🔍 Mode : {search_mode.upper()}",
892
- f"🔍 Iterasi dicoba : {tried} (gagal: {failed})",
893
- f"📏 Lebar roll : {roll_width:g} cm",
894
- f"📦 Jumlah roll : {num_rolls}",
895
- f"📏 Total panjang : {sum(h for _, h, _ in rolls):.1f} cm",
896
- f"✅ Item ditempatkan : {sum(len(p) for p, _, _ in rolls)} / {total_rects}",
897
- f"🔄 Diputar 90° : {total_rot}",
898
- f"📐 Luas item (asli) : {total_true:.1f} cm²",
899
- f"📐 Luas roll terpakai : {total_roll:.1f} cm²",
900
- f"♻️ TOTAL WASTE : {waste:.1f} cm²",
901
- f"📊 Persentase waste : {waste_pct:.2f}% (target: ≤{target_waste_pct}%)",
902
- f"🔪 Guillotine cuttable : {'✅ Ya' if is_guillotine else f'⚠️ Tidak ({g_violations} pelanggaran)'}",
903
- ]
904
- if not_placed > 0:
905
- stats.insert(7, f"⚠️ Item TIDAK muat : {not_placed}")
906
-
907
- return img, "\n".join(stats), waste, waste_pct, num_rolls, tried, hit_target, not_placed, rolls
908
-
909
-
910
- # --------------------------------------------------------------------------
911
- # 10. FUNGSI UTAMA
912
- # --------------------------------------------------------------------------
913
-
914
- def process(roll_widths_text, allow_rotation, search_mode, target_waste_pct,
915
- enable_multiwidth, table_data):
916
- if table_data is None or len(table_data) == 0:
917
- return None, "⚠️ Silakan isi tabel daftar banner terlebih dahulu.", None, None, None
918
-
919
- df = pd.DataFrame(table_data, columns=["Label", "Width", "Height", "Margin"])
920
- df = df.dropna(subset=["Width", "Height"], how="any")
921
- df["Margin"] = pd.to_numeric(df["Margin"], errors="coerce").fillna(0.0)
922
-
923
- try:
924
- widths = [float(w.strip()) for w in roll_widths_text.split(",") if w.strip()]
925
- widths = [w for w in widths if w > 0]
926
- except ValueError:
927
- return None, "⚠️ Format daftar lebar roll tidak valid.", None, None, None
928
-
929
- if not widths:
930
- return None, "⚠️ Masukkan minimal satu lebar roll yang valid.", None, None, None
931
-
932
- try:
933
- target_waste_pct = float(target_waste_pct)
934
- if target_waste_pct < 0:
935
- target_waste_pct = 5.0
936
- except (TypeError, ValueError):
937
- target_waste_pct = 5.0
938
-
939
- rects, original_dims, item_margins, total_rects, max_height = prepare_rects(df)
940
- if rects is None:
941
- return None, "⚠️ Tidak ada data banner yang valid.", None, None, None
942
-
943
- # Auto-generate lebar tambahan
944
- # MURNI MENGGUNAKAN INPUT USER (TANPA AUTO-GENERATE)
945
- # Hitung lebar banner terbesar + margin (per baris) sebagai batas minimal roll
946
- min_banner_w = max(w + item_margins[rid] * 2 for rid, (w, h) in original_dims.items())
947
-
948
- # Filter: Hanya ambil lebar roll dari input user yang >= lebar banner terbesar
949
- all_widths = sorted([w for w in widths if w >= min_banner_w])
950
-
951
- # Validasi jika tidak ada lebar roll yang cocok
952
- if not all_widths:
953
- return None, (
954
- f"⚠️ Tidak ada lebar roll yang valid untuk menampung banner.\n"
955
- f"Lebar roll minimal yang diinput harus ≥ {min_banner_w:.1f} cm "
956
- f"(Lebar banner terbesar + margin item tersebut)."
957
- ), None, None, None
958
-
959
- best_overall = None
960
- best_key = None
961
- best_width = None
962
- width_results = []
963
- global_tried = 0
964
-
965
- # MULTI-WIDTH MULTI-ROLL
966
- if enable_multiwidth and search_mode in ("pro", "exhaustive"):
967
- tried = 0
968
- mw_best_rolls = None
969
- mw_best_not_placed = None
970
- mw_best_config = None
971
- # key global untuk multi-width sendiri: (waste + penalti not_placed, num_rolls)
972
- # dibandingkan terpisah dari single-width supaya kombinasi terbaik multi-width
973
- # yang benar-benar ditemukan (bukan cuma kombinasi pertama yang all-placed)
974
- mw_best_key = None
975
-
976
- def _mw_key(rolls, not_placed):
977
- waste, _ = calculate_waste(rolls, original_dims)
978
- return unified_key(waste, len(rolls), not_placed)
979
-
980
- def _consider_mw(rolls, not_placed, config_name):
981
- nonlocal mw_best_rolls, mw_best_not_placed, mw_best_config, mw_best_key
982
- if not rolls:
983
- return
984
- key = _mw_key(rolls, not_placed)
985
- if mw_best_key is None or key < mw_best_key:
986
- mw_best_key = key
987
- mw_best_rolls = rolls
988
- mw_best_not_placed = not_placed
989
- mw_best_config = config_name
990
-
991
- # --- Fase A: grid search dasar (kombinasi algo x sort x reverse) ---
992
- for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
993
- for sort_algo in [None, SORT_AREA]:
994
- for reverse in [False, True]:
995
- tried += 1
996
- rolls, not_placed = pack_multi_width_multi_roll(
997
- rects, all_widths, max_height, allow_rotation,
998
- original_dims, pack_algo, sort_algo, reverse
999
- )
1000
- algo_name = pack_algo.__name__ if pack_algo else "Default"
1001
- config = f"[Grid] {algo_name}+{get_sort_name(sort_algo)}{' rev' if reverse else ''}"
1002
- _consider_mw(rolls, not_placed, config)
1003
-
1004
- # --- Fase B (Langkah 1): pre-sort strategies, sama seperti single-width ---
1005
- if search_mode in ("pro", "exhaustive"):
1006
- for sort_name, sorted_rects in get_pre_sort_strategies(rects):
1007
- for pack_algo in [None, MaxRectsBssf, GuillotineBssfSas]:
1008
- for reverse in [False, True]:
1009
- tried += 1
1010
- rolls, not_placed = pack_multi_width_multi_roll(
1011
- sorted_rects, all_widths, max_height, allow_rotation,
1012
- original_dims, pack_algo, SORT_NONE, reverse
1013
- )
1014
- algo_name = pack_algo.__name__ if pack_algo else "Default"
1015
- config = f"[MW-PreSort:{sort_name}] {algo_name}{' rev' if reverse else ''}"
1016
- _consider_mw(rolls, not_placed, config)
1017
-
1018
- # --- Fase C (Langkah 2): Simulated Annealing versi multi-width ---
1019
- if search_mode in ("pro", "exhaustive"):
1020
- sa_mw_configs = [
1021
- (None, None), (MaxRectsBssf, SORT_AREA), (GuillotineBssfSas, SORT_AREA)
1022
- ]
1023
- for pack_algo, sort_algo in sa_mw_configs:
1024
- tried += 1
1025
- sa_rolls, sa_waste, sa_not_placed = simulated_annealing_multi_width(
1026
- rects, all_widths, max_height, allow_rotation,
1027
- pack_algo, sort_algo, original_dims,
1028
- initial_temp=100, cooling=0.995,
1029
- max_iter=2500 if search_mode == "exhaustive" else 1200
1030
- )
1031
- if sa_rolls:
1032
- algo_name = pack_algo.__name__ if pack_algo else "Default"
1033
- config = f"[MW-SA] {algo_name} (waste {sa_waste:.1f})"
1034
- _consider_mw(sa_rolls, sa_not_placed, config)
1035
-
1036
- # --- Fase D (Langkah 4): pilihan lebar dgn lookahead 1-langkah ---
1037
- # Dibatasi ke beberapa config saja karena tiap panggilan lebih mahal
1038
- # (evaluasi top-k kandidat x semua lebar untuk mengintip roll berikutnya).
1039
- if search_mode in ("pro", "exhaustive"):
1040
- lookahead_configs = [(None, None), (MaxRectsBssf, SORT_AREA)]
1041
- for pack_algo, sort_algo in lookahead_configs:
1042
- for sort_name, sorted_rects in [("default", rects), ("area_desc",
1043
- sorted(rects, key=lambda r: r[0] * r[1], reverse=True))]:
1044
- tried += 1
1045
- rolls, not_placed = pack_multi_width_multi_roll(
1046
- sorted_rects, all_widths, max_height, allow_rotation,
1047
- original_dims, pack_algo, sort_algo, False,
1048
- lookahead=True, lookahead_k=3
1049
- )
1050
- algo_name = pack_algo.__name__ if pack_algo else "Default"
1051
- config = f"[MW-Lookahead:{sort_name}] {algo_name}"
1052
- _consider_mw(rolls, not_placed, config)
1053
-
1054
- # --- Bandingkan hasil terbaik multi-width dengan best_overall global ---
1055
- if mw_best_rolls is not None:
1056
- waste, waste_pct = calculate_waste(mw_best_rolls, original_dims)
1057
- key = unified_key(waste, len(mw_best_rolls), mw_best_not_placed)
1058
- if best_key is None or key < best_key:
1059
- best_key = key
1060
- img, total_true, total_roll, total_rot = render_multi_roll(
1061
- mw_best_rolls, original_dims, item_margins
1062
- )
1063
- is_g, g_v = is_guillotine_cuttable(mw_best_rolls)
1064
- stats = [
1065
- "🎯 MULTI-WIDTH MULTI-ROLL (tiap roll beda lebar)",
1066
- f"🏆 Algoritma terpilih : {mw_best_config}",
1067
- f"🔍 Iterasi dicoba (multi-width): {tried}",
1068
- f"📦 Jumlah roll : {len(mw_best_rolls)}",
1069
- f"📏 Lebar per roll : {', '.join(f'{w:.0f}' for _, _, w in mw_best_rolls)} cm",
1070
- f"📏 Total panjang : {sum(h for _, h, _ in mw_best_rolls):.1f} cm",
1071
- f"✅ Item ditempatkan : {sum(len(p) for p, _, _ in mw_best_rolls)} / {total_rects}",
1072
- f"♻️ TOTAL WASTE : {waste:.1f} cm²",
1073
- f"📊 Persentase waste : {waste_pct:.2f}% (target: ≤{target_waste_pct}%)",
1074
- f"🔪 Guillotine cuttable : {'✅ Ya' if is_g else f'⚠️ Tidak ({g_v} pelanggaran)'}",
1075
- ]
1076
- if mw_best_not_placed:
1077
- stats.insert(7, f"⚠️ Item TIDAK muat : {mw_best_not_placed}")
1078
- best_overall = (img, "\n".join(stats), waste, waste_pct, mw_best_rolls)
1079
- best_width = "multi"
1080
- # Langkah 6 (persiapan): masukkan hasil multi-width ke tabel perbandingan juga
1081
- width_results.append(("multi", waste, waste_pct, len(mw_best_rolls), f"{waste_pct:.2f}%"))
1082
- global_tried += tried
1083
-
1084
- # SINGLE-WIDTH per lebar
1085
- for width in all_widths:
1086
- if search_mode == "quick":
1087
- result = pack_multi_roll(rects, width, max_height, bool(allow_rotation))
1088
- if not result or not result[0]:
1089
- width_results.append((width, None, None, "Gagal"))
1090
- continue
1091
- rolls, not_placed = result
1092
- img, total_true, total_roll, total_rot = render_multi_roll(
1093
- rolls, original_dims, item_margins
1094
- )
1095
- waste, waste_pct = calculate_waste(rolls, original_dims)
1096
- num_rolls = len(rolls)
1097
-
1098
- stats = [
1099
- f"🏆 Mode : CEPAT",
1100
- f"📏 Lebar roll : {width:g} cm",
1101
- f"📦 Jumlah roll : {num_rolls}",
1102
- f"♻️ Total waste : {waste:.1f} cm²",
1103
- f"📊 Persentase waste : {waste_pct:.2f}%",
1104
- ]
1105
-
1106
- key = unified_key(waste, num_rolls, not_placed)
1107
- if best_key is None or key < best_key:
1108
- best_key = key
1109
- best_overall = (img, "\n".join(stats), waste, waste_pct, rolls)
1110
- best_width = width
1111
-
1112
- width_results.append((width, waste, waste_pct, num_rolls, f"{waste_pct:.2f}%"))
1113
- global_tried += 1
1114
- if waste_pct <= target_waste_pct:
1115
- break
1116
-
1117
- else:
1118
- img, stats, waste, waste_pct, num_rolls, tried, hit, sw_not_placed, sw_rolls = search_single_width(
1119
- rects, original_dims, total_rects, max_height,
1120
- width, item_margins, bool(allow_rotation),
1121
- search_mode, target_waste_pct, 4.0
1122
- )
1123
- global_tried += tried
1124
-
1125
- if img is None:
1126
- width_results.append((width, None, None, None, "Gagal"))
1127
- continue
1128
-
1129
- key = unified_key(
1130
- waste if waste is not None else float('inf'),
1131
- num_rolls if num_rolls else 99,
1132
- sw_not_placed if sw_not_placed is not None else 0,
1133
- )
1134
- if best_key is None or key < best_key:
1135
- best_key = key
1136
- best_overall = (img, stats, waste, waste_pct, sw_rolls)
1137
- best_width = width
1138
-
1139
- width_results.append((width, waste, waste_pct, num_rolls, f"{waste_pct:.2f}%"))
1140
- if hit:
1141
- break
1142
-
1143
- if best_overall is None:
1144
- return None, "⚠️ Tidak ada satupun lebar roll yang bisa menampung semua banner.", None, None, None
1145
-
1146
- img, stats, best_waste, best_waste_pct, best_rolls_final = best_overall
1147
-
1148
- comparison = ["\n" + "─" * 55, "📋 PERBANDINGAN LEBAR ROLL (10 teratas):"]
1149
- sorted_r = sorted([r for r in width_results if r[1] is not None], key=lambda x: (x[1], x[3]))
1150
- for w, waste, wpct, num_rolls_disp, note in sorted_r[:10]:
1151
- mark = " ⭐ PALING HEMAT" if w == best_width else ""
1152
- target = " 🎯" if isinstance(wpct, (int, float)) and wpct <= target_waste_pct else ""
1153
- w_label = "MULTI (beda lebar)" if w == "multi" else f"{w:g} cm"
1154
- comparison.append(
1155
- f" {'✅' if w == best_width else ' '} {w_label} → "
1156
- f"{num_rolls_disp} roll, waste {waste:.1f} cm² ({note}){mark}{target}"
1157
- )
1158
-
1159
- final = stats + "\n" + "\n".join(comparison)
1160
- final += f"\n{'─' * 55}\n🔍 Total iterasi keseluruhan: {global_tried} kombinasi"
1161
-
1162
- return img, final, best_rolls_final, original_dims, item_margins
1163
-
1164
-
1165
- # --------------------------------------------------------------------------
1166
- # 11. UI GRADIO
1167
- # --------------------------------------------------------------------------
1168
-
1169
- with gr.Blocks(title="Nesting Otomatis Banner v2 — Super Optimized") as demo:
1170
- gr.Markdown("# 🖨️ Nesting Otomatis v2 — Simulated Annealing + Multi-Width")
1171
- gr.Markdown(
1172
- "Upgrade: **Simulated Annealing**, **Multi-Width Multi-Roll**, "
1173
- "dan **Guillotine Validation**. Berburu waste minimum dengan target."
1174
- )
1175
-
1176
- with gr.Row():
1177
- with gr.Column(scale=1):
1178
- roll_widths = gr.Textbox(
1179
- label="Daftar Lebar Roll (cm, pisah koma)",
1180
- value="150, 200, 250, 300",
1181
- placeholder="Contoh: 150, 200, 250, 300",
1182
- )
1183
- gr.Markdown(
1184
- "ℹ️ Jarak Antar Item / Margin kini diatur **per banner** lewat "
1185
- "kolom **Margin** di form & tabel di bawah, bukan satu nilai global."
1186
- )
1187
- allow_rotation = gr.Checkbox(label="Izinkan Rotasi Otomatis", value=True)
1188
-
1189
- target_waste = gr.Number(
1190
- label="🎯 Target Waste Maksimum (%)",
1191
- value=5.0, minimum=0.1, maximum=50.0, step=0.5,
1192
- )
1193
-
1194
- # 1. Multi-width aktif by default (True)
1195
- enable_multiwidth = gr.Checkbox(
1196
- label="🎨 Aktifkan Multi-Width Multi-Roll (tiap roll beda lebar)",
1197
- value=True,
1198
- )
1199
-
1200
- # 2. Mode pencarian diatur ke "exhaustive" (Menyeluruh) by default
1201
- search_mode = gr.Dropdown(
1202
- label="Mode Pencarian",
1203
- choices=[
1204
- ("⚡ Cepat", "quick"),
1205
- ("🎯 Standar (~120)", "standard"),
1206
- ("🔍 Dalaman (~464)", "deep"),
1207
- ("🧠 Pro (~3.000+ + Simulated Annealing)", "pro"),
1208
- ("💎 Menyeluruh (~8.000+ + SA + Swap)", "exhaustive"),
1209
- ],
1210
- value="exhaustive",
1211
- )
1212
-
1213
- gr.Markdown("### 📥 Form Input Banner Baru")
1214
- with gr.Row():
1215
- input_label = gr.Textbox(label="Label Banner", value="")
1216
- input_width = gr.Number(label="Lebar (cm)", value=100)
1217
- with gr.Row():
1218
- input_height = gr.Number(label="Tinggi (cm)", value=60)
1219
- input_margin = gr.Number(
1220
- label="Margin/Jarak Antar Item (cm)", value=2, minimum=0
1221
- )
1222
-
1223
- btn_add = gr.Button("➕ Tambah ke Daftar Banner", variant="secondary")
1224
- gr.Markdown(
1225
- "💡 Untuk mencetak banner yang sama lebih dari satu kali, tekan "
1226
- "tombol tambah beberapa kali (atau tambahkan baris manual di tabel)."
1227
- )
1228
-
1229
- gr.Markdown("### 📋 Daftar Banner")
1230
- # 3. Daftar banner default dikosongkan (value=[])
1231
- data_input = gr.Dataframe(
1232
- headers=["Label", "Width", "Height", "Margin"],
1233
- datatype=["str", "number", "number", "number"],
1234
- row_count=(0, "dynamic"),
1235
- value=[],
1236
- )
1237
-
1238
- # Event listener untuk tombol tambah banner berulang kali
1239
- btn_add.click(
1240
- fn=add_banner_to_list,
1241
- inputs=[input_label, input_width, input_height, input_margin, data_input],
1242
- outputs=[data_input]
1243
- )
1244
-
1245
- btn = gr.Button("🚀 PROSES SUPER OPTIMIZED", variant="primary")
1246
-
1247
- with gr.Column(scale=2):
1248
- output_img = gr.Image(label="Pratinjau Layout Cetakan", type="pil")
1249
- output_stats = gr.Textbox(label="Statistik Hasil Nesting", lines=16)
1250
-
1251
- gr.Markdown("### 📤 Ekspor Layout Terpilih")
1252
- btn_export_svg = gr.Button("💾 Download Layout (SVG untuk CorelDraw)", variant="secondary")
1253
- output_svg_file = gr.File(label="File SVG Hasil Nesting (1 unit = 1 cm)")
1254
-
1255
- # State tersembunyi: menyimpan data mentah hasil nesting terbaik supaya
1256
- # bisa dipakai ulang oleh tombol export SVG tanpa proses ulang perhitungan.
1257
- state_best_rolls = gr.State(None)
1258
- state_original_dims = gr.State(None)
1259
- state_item_margins = gr.State(None)
1260
-
1261
- btn.click(
1262
- fn=process,
1263
- inputs=[roll_widths, allow_rotation, search_mode, target_waste,
1264
- enable_multiwidth, data_input],
1265
- outputs=[output_img, output_stats, state_best_rolls, state_original_dims, state_item_margins],
1266
- )
1267
-
1268
- btn_export_svg.click(
1269
- fn=export_svg_file,
1270
- inputs=[state_best_rolls, state_original_dims, state_item_margins],
1271
- outputs=[output_svg_file],
1272
- )
1273
-
1274
- if __name__ == "__main__":
1275
- demo.launch()