FajarHidaa commited on
Commit
4dfe84e
Β·
verified Β·
1 Parent(s): 67ff16a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +666 -1
app.py CHANGED
@@ -1 +1,666 @@
1
- https://huggingface.co/spaces/FajarHidaa/SheetReader/resolve/main/app.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Nesting Otomatis + Visualisasi Layout untuk Percetakan Banner
3
+ ================================================================
4
+ Menggunakan rectpack untuk menghitung penempatan terbaik banner-banner
5
+ pada satu roll/lembar bahan cetak (dengan rotasi otomatis jika hemat bahan),
6
+ dan Pillow untuk menghasilkan gambar pratinjau layout.
7
+
8
+ Fitur:
9
+ - Inner/Outer visualization (banner asli vs area margin)
10
+ - Iterasi multi-lebar roll: coba semua ukuran roll, pilih yang paling hemat
11
+ - 5 Mode Pencarian: Cepat / Standar / Dalaman / Pro / Menyeluruh
12
+ - Iterasi maksimal: grid search + pre-sort + Monte Carlo + Local Swap
13
+ - Setara kemampuan operator profesional
14
+ - Deploy di Hugging Face Spaces (Gradio SDK)
15
+ """
16
+
17
+ import random
18
+
19
+ import gradio as gr
20
+ import pandas as pd
21
+ from PIL import Image, ImageDraw, ImageFont
22
+ from rectpack import newPacker
23
+
24
+ # --- Import semua varian algoritma & sorting ---
25
+ from rectpack import (
26
+ SORT_AREA, SORT_PERI, SORT_DIFF, SORT_SSIDE, SORT_LSIDE, SORT_RATIO, SORT_NONE
27
+ )
28
+ from rectpack.maxrects import MaxRectsBl, MaxRectsBssf, MaxRectsBaf, MaxRectsBlsf
29
+ from rectpack.skyline import (
30
+ SkylineBl, SkylineBlWm, SkylineMwf, SkylineMwfl, SkylineMwfWm, SkylineMwflWm
31
+ )
32
+ from rectpack.guillotine import (
33
+ GuillotineBssfSas, GuillotineBssfLas, GuillotineBssfSlas,
34
+ GuillotineBssfLlas, GuillotineBssfMaxas, GuillotineBssfMinas,
35
+ GuillotineBafSas, GuillotineBafLas, GuillotineBafSlas,
36
+ GuillotineBafLlas, GuillotineBafMaxas, GuillotineBafMinas,
37
+ GuillotineBlsfSas, GuillotineBlsfLas, GuillotineBlsfSlas,
38
+ GuillotineBlsfLlas, GuillotineBlsfMaxas, GuillotineBlsfMinas,
39
+ )
40
+
41
+
42
+ # --------------------------------------------------------------------------
43
+ # 1. FUNGSI BANTU
44
+ # --------------------------------------------------------------------------
45
+
46
+ def generate_color(seed_text: str):
47
+ """Menghasilkan warna acak tapi konsisten berdasarkan label item."""
48
+ random.seed(seed_text)
49
+ return tuple(random.randint(90, 220) for _ in range(3))
50
+
51
+
52
+ def load_font(size: int = 14):
53
+ """Coba pakai font DejaVu (biasanya tersedia di Linux/HF Spaces)."""
54
+ candidates = [
55
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
56
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
57
+ ]
58
+ for path in candidates:
59
+ try:
60
+ return ImageFont.truetype(path, size)
61
+ except Exception:
62
+ continue
63
+ return ImageFont.load_default()
64
+
65
+
66
+ def lighten_color(c, factor=0.55):
67
+ """Buat warna lebih terang untuk area margin (outer)."""
68
+ return tuple(min(255, int(v + (255 - v) * factor)) for v in c)
69
+
70
+
71
+ def get_sort_name(sort_algo):
72
+ """Konversi constant sort ke string readable."""
73
+ mapping = {
74
+ SORT_AREA: "AREA",
75
+ SORT_PERI: "PERI",
76
+ SORT_LSIDE: "LSIDE",
77
+ SORT_SSIDE: "SSIDE",
78
+ SORT_RATIO: "RATIO",
79
+ SORT_DIFF: "DIFF",
80
+ SORT_NONE: "NONE",
81
+ None: "Default",
82
+ }
83
+ return mapping.get(sort_algo, str(sort_algo))
84
+
85
+
86
+ # --------------------------------------------------------------------------
87
+ # 2. PERSIAPAN DATA RECTANGLE
88
+ # --------------------------------------------------------------------------
89
+
90
+ def prepare_rects(df: pd.DataFrame, margin: float):
91
+ """
92
+ Konversi DataFrame ke daftar rectangle untuk rectpack.
93
+ Return: (rects, original_dims, total_rects, max_height)
94
+ """
95
+ rects = []
96
+ original_dims = {}
97
+
98
+ for idx, row in df.iterrows():
99
+ label = str(row["Label"]).strip() or f"Item{idx}"
100
+ try:
101
+ w = float(row["Width"])
102
+ h = float(row["Height"])
103
+ qty = int(row["Qty"])
104
+ except (TypeError, ValueError):
105
+ continue
106
+ if w <= 0 or h <= 0 or qty <= 0:
107
+ continue
108
+
109
+ for i in range(qty):
110
+ rid = f"{label}#{i + 1}"
111
+ rects.append((w + margin, h + margin, rid))
112
+ original_dims[rid] = (w, h)
113
+
114
+ if not rects:
115
+ return None, None, 0, 0
116
+
117
+ total_rects = len(rects)
118
+ max_height = sum(h for _, h, _ in rects) + margin * (len(rects) + 2)
119
+ return rects, original_dims, total_rects, max_height
120
+
121
+
122
+ # --------------------------------------------------------------------------
123
+ # 3. CORE: PACKING ENGINE
124
+ # --------------------------------------------------------------------------
125
+
126
+ def run_packer(rects, roll_width, max_height, allow_rotation,
127
+ pack_algo=None, sort_algo=None, reverse=False):
128
+ """
129
+ Jalankan rectpack dengan konfigurasi tertentu.
130
+ Jika reverse=True, urutan rects dibalik sebelum packing.
131
+ Return: (placed_rects, used_height, not_placed) atau None jika gagal.
132
+ """
133
+ input_rects = list(reversed(rects)) if reverse else rects[:]
134
+
135
+ kwargs = {"rotation": allow_rotation}
136
+ if pack_algo is not None:
137
+ kwargs["pack_algo"] = pack_algo
138
+ if sort_algo is not None:
139
+ kwargs["sort_algo"] = sort_algo
140
+
141
+ packer = newPacker(**kwargs)
142
+ for w, h, rid in input_rects:
143
+ packer.add_rect(w, h, rid=rid)
144
+ packer.add_bin(roll_width, max_height)
145
+ packer.pack()
146
+
147
+ if len(packer) == 0 or len(packer[0]) == 0:
148
+ return None
149
+
150
+ placed = packer[0]
151
+ not_placed = len(input_rects) - len(placed)
152
+ used_height = max(r.y + r.height for r in placed)
153
+
154
+ return placed, used_height, not_placed
155
+
156
+
157
+ # --------------------------------------------------------------------------
158
+ # 4. VISUALISASI (Pillow) β€” INNER + OUTER
159
+ # --------------------------------------------------------------------------
160
+
161
+ def render_layout(placed, used_height, original_dims, roll_width, margin,
162
+ px_per_unit=4.0):
163
+ """
164
+ Gambar hasil packing ke PIL Image.
165
+ Return: (img, used_area, true_used_area, efficiency, true_efficiency, rotated_count)
166
+ """
167
+ img_w = max(1, int(round(roll_width * px_per_unit)))
168
+ img_h = max(1, int(round(used_height * px_per_unit)))
169
+
170
+ img = Image.new("RGB", (img_w, img_h), "white")
171
+ draw = ImageDraw.Draw(img)
172
+ font = load_font(14)
173
+ font_small = load_font(11)
174
+
175
+ for r in placed:
176
+ base_label = r.rid.rsplit("#", 1)[0]
177
+ color = generate_color(base_label)
178
+ outer_color = lighten_color(color, 0.55)
179
+ inner_color = color
180
+
181
+ orig_w, orig_h = original_dims[r.rid]
182
+ is_rotated = round(r.width - margin, 3) != round(orig_w, 3)
183
+
184
+ # Koordinat OUTER (termasuk margin)
185
+ x0 = r.x * px_per_unit
186
+ y0 = (used_height - r.y - r.height) * px_per_unit
187
+ x1 = (r.x + r.width) * px_per_unit
188
+ y1 = (used_height - r.y) * px_per_unit
189
+
190
+ # Koordinat INNER (banner asli)
191
+ m = margin * px_per_unit
192
+ ix0, iy0 = x0 + m / 2, y0 + m / 2
193
+ ix1, iy1 = x1 - m / 2, y1 - m / 2
194
+
195
+ # Gambar OUTER (area margin) β€” warna pastel
196
+ draw.rectangle([x0, y0, x1, y1], fill=outer_color, outline="black", width=2)
197
+
198
+ # Gambar INNER (banner asli) β€” warna asli
199
+ if ix1 > ix0 and iy1 > iy0:
200
+ draw.rectangle([ix0, iy0, ix1, iy1], fill=inner_color, outline="black", width=1)
201
+
202
+ # Label
203
+ label_text = base_label
204
+ size_text = f"{orig_w:g} x {orig_h:g}" + (" (diputar)" if is_rotated else "")
205
+
206
+ bbox_label = draw.textbbox((0, 0), label_text, font=font)
207
+ bbox_size = draw.textbbox((0, 0), size_text, font=font_small)
208
+ total_th = (bbox_label[3] - bbox_label[1]) + (bbox_size[3] - bbox_size[1]) + 4
209
+
210
+ cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
211
+ ty = cy - total_th / 2
212
+
213
+ if (x1 - x0) > 20 and (y1 - y0) > 20:
214
+ draw.text((cx, ty), label_text, fill="black", font=font, anchor="ma")
215
+ draw.text((cx, ty + (bbox_label[3] - bbox_label[1]) + 4), size_text,
216
+ fill="black", font=font_small, anchor="ma")
217
+
218
+ # Bingkai roll
219
+ draw.rectangle([0, 0, img_w - 1, img_h - 1], outline="red", width=3)
220
+
221
+ # Statistik
222
+ used_area = sum(r.width * r.height for r in placed)
223
+ roll_area = roll_width * used_height
224
+ efficiency = (used_area / roll_area * 100) if roll_area > 0 else 0
225
+
226
+ true_used_area = sum(original_dims[r.rid][0] * original_dims[r.rid][1] for r in placed)
227
+ true_efficiency = (true_used_area / roll_area * 100) if roll_area > 0 else 0
228
+
229
+ rotated_count = sum(
230
+ 1 for r in placed
231
+ if round(r.width - margin, 3) != round(original_dims[r.rid][0], 3)
232
+ )
233
+
234
+ return img, used_area, true_used_area, efficiency, true_efficiency, rotated_count
235
+
236
+
237
+ # --------------------------------------------------------------------------
238
+ # 5. STRATEGI PRE-SORT MANUAL
239
+ # --------------------------------------------------------------------------
240
+
241
+ def get_pre_sort_strategies(rects):
242
+ """
243
+ Berbagai strategi pengurutan input manual sebelum masuk rectpack.
244
+ Return: list of (name, sorted_rects)
245
+ """
246
+ strategies = []
247
+
248
+ def area(r): return r[0] * r[1]
249
+ def peri(r): return 2 * (r[0] + r[1])
250
+ def max_side(r): return max(r[0], r[1])
251
+ def min_side(r): return min(r[0], r[1])
252
+ def ratio(r): return max(r[0], r[1]) / max(min(r[0], r[1]), 0.001)
253
+
254
+ base = [
255
+ ("default", rects[:]),
256
+ ("area_desc", sorted(rects, key=area, reverse=True)),
257
+ ("area_asc", sorted(rects, key=area)),
258
+ ("width_desc", sorted(rects, key=lambda r: r[0], reverse=True)),
259
+ ("width_asc", sorted(rects, key=lambda r: r[0])),
260
+ ("height_desc", sorted(rects, key=lambda r: r[1], reverse=True)),
261
+ ("height_asc", sorted(rects, key=lambda r: r[1])),
262
+ ("peri_desc", sorted(rects, key=peri, reverse=True)),
263
+ ("peri_asc", sorted(rects, key=peri)),
264
+ ("longest_desc", sorted(rects, key=max_side, reverse=True)),
265
+ ("longest_asc", sorted(rects, key=max_side)),
266
+ ("shortest_desc", sorted(rects, key=min_side, reverse=True)),
267
+ ("ratio_desc", sorted(rects, key=ratio, reverse=True)),
268
+ ("ratio_asc", sorted(rects, key=ratio)),
269
+ ]
270
+ strategies.extend(base)
271
+
272
+ # Group by label (keep same-label items together)
273
+ label_groups = {}
274
+ for r in rects:
275
+ label = r[2].rsplit("#", 1)[0]
276
+ label_groups.setdefault(label, []).append(r)
277
+ grouped = []
278
+ for label in sorted(label_groups.keys()):
279
+ grouped.extend(label_groups[label])
280
+ strategies.append(("group_label", grouped))
281
+
282
+ # Interleave large-small (skyline strategy)
283
+ by_area = sorted(rects, key=area, reverse=True)
284
+ interleaved = []
285
+ i, j = 0, len(by_area) - 1
286
+ while i <= j:
287
+ interleaved.append(by_area[i])
288
+ if i != j:
289
+ interleaved.append(by_area[j])
290
+ i += 1
291
+ j -= 1
292
+ strategies.append(("interleave", interleaved))
293
+
294
+ return strategies
295
+
296
+
297
+ # --------------------------------------------------------------------------
298
+ # 6. OPTIMASI: PENCARIAN UNTUK SATU LEBAR ROLL
299
+ # --------------------------------------------------------------------------
300
+
301
+ def search_single_width(rects, original_dims, total_rects, max_height,
302
+ roll_width, margin, allow_rotation,
303
+ search_mode, px_per_unit):
304
+ """
305
+ Iterasi berbagai kombinasi untuk SATU lebar roll tertentu.
306
+ Return: (img, stats_text, used_height, true_eff) atau (None, error_msg, None, None)
307
+ """
308
+ best_result = None
309
+ best_key = None
310
+ best_config = None
311
+ best_rects_order = None
312
+ tried = 0
313
+ failed = 0
314
+
315
+ def evaluate(result, config_name, rects_order):
316
+ nonlocal best_result, best_key, best_config, best_rects_order
317
+ if result is None:
318
+ return
319
+ placed, used_height, not_placed = result
320
+ if not_placed > 0:
321
+ return
322
+ true_area = sum(original_dims[r.rid][0] * original_dims[r.rid][1] for r in placed)
323
+ roll_area = roll_width * used_height
324
+ true_eff = (true_area / roll_area * 100) if roll_area > 0 else 0
325
+ key = (used_height, -true_eff)
326
+ if best_key is None or key < best_key:
327
+ best_key = key
328
+ best_result = result
329
+ best_config = config_name
330
+ best_rects_order = rects_order[:]
331
+
332
+ # ============================================================
333
+ # PHASE 1: GRID SEARCH
334
+ # ============================================================
335
+ ALL_PACK_ALGOS = [
336
+ None, MaxRectsBssf, MaxRectsBaf, MaxRectsBl, MaxRectsBlsf,
337
+ SkylineBl, SkylineBlWm, SkylineMwf, SkylineMwfl,
338
+ SkylineMwfWm, SkylineMwflWm,
339
+ GuillotineBssfSas, GuillotineBssfLas, GuillotineBssfSlas,
340
+ GuillotineBssfLlas, GuillotineBssfMaxas, GuillotineBssfMinas,
341
+ GuillotineBafSas, GuillotineBafLas, GuillotineBafSlas,
342
+ GuillotineBafLlas, GuillotineBafMaxas, GuillotineBafMinas,
343
+ GuillotineBlsfSas, GuillotineBlsfLas, GuillotineBlsfSlas,
344
+ GuillotineBlsfLlas, GuillotineBlsfMaxas, GuillotineBlsfMinas,
345
+ ]
346
+
347
+ ALL_SORT_ALGOS = [None, SORT_AREA, SORT_PERI, SORT_LSIDE, SORT_SSIDE,
348
+ SORT_RATIO, SORT_DIFF, SORT_NONE]
349
+
350
+ if search_mode in ("standard", "deep", "pro", "exhaustive"):
351
+ if search_mode == "standard":
352
+ pack_algos = [
353
+ None, MaxRectsBssf, MaxRectsBaf, MaxRectsBlsf,
354
+ SkylineMwfl, SkylineMwflWm, SkylineMwf,
355
+ GuillotineBssfSas, GuillotineBssfLas, GuillotineBssfMaxas,
356
+ GuillotineBafSas, GuillotineBafLas, GuillotineBafMaxas,
357
+ GuillotineBlsfSas, GuillotineBlsfLas,
358
+ ]
359
+ sort_algos = [None, SORT_AREA, SORT_LSIDE, SORT_RATIO]
360
+ else:
361
+ pack_algos = ALL_PACK_ALGOS
362
+ sort_algos = ALL_SORT_ALGOS
363
+
364
+ for pack_algo in pack_algos:
365
+ for sort_algo in sort_algos:
366
+ for reverse in [False, True]:
367
+ tried += 1
368
+ result = run_packer(
369
+ rects, roll_width, max_height, allow_rotation,
370
+ pack_algo, sort_algo, reverse
371
+ )
372
+ if result is None:
373
+ failed += 1
374
+ continue
375
+ algo_name = pack_algo.__name__ if pack_algo else "Default"
376
+ sort_name = get_sort_name(sort_algo)
377
+ rev = " (rev)" if reverse else ""
378
+ config = f"[Grid] {algo_name} + SORT_{sort_name}{rev}"
379
+ evaluate(result, config, rects)
380
+
381
+ # ============================================================
382
+ # PHASE 2: PRE-SORT MANUAL
383
+ # ============================================================
384
+ if search_mode in ("pro", "exhaustive"):
385
+ pre_sorts = get_pre_sort_strategies(rects)
386
+ top_packs = [
387
+ None, MaxRectsBssf, MaxRectsBaf, SkylineMwfl,
388
+ GuillotineBssfSas, GuillotineBafSas, GuillotineBlsfSas,
389
+ ]
390
+
391
+ for sort_name, sorted_rects in pre_sorts:
392
+ for pack_algo in top_packs:
393
+ for reverse in [False, True]:
394
+ tried += 1
395
+ result = run_packer(
396
+ sorted_rects, roll_width, max_height, allow_rotation,
397
+ pack_algo, SORT_NONE, reverse
398
+ )
399
+ if result is None:
400
+ failed += 1
401
+ continue
402
+ algo_name = pack_algo.__name__ if pack_algo else "Default"
403
+ rev = " (rev)" if reverse else ""
404
+ config = f"[PreSort:{sort_name}] {algo_name}{rev}"
405
+ evaluate(result, config, sorted_rects)
406
+
407
+ # ============================================================
408
+ # PHASE 3: MONTE CARLO RANDOM SHUFFLE
409
+ # ============================================================
410
+ if search_mode in ("pro", "exhaustive"):
411
+ mc_count = 500 if search_mode == "pro" else 2000
412
+ mc_configs = [
413
+ (None, None),
414
+ (MaxRectsBssf, SORT_AREA),
415
+ (GuillotineBssfSas, SORT_AREA),
416
+ ]
417
+
418
+ for seed in range(mc_count):
419
+ random.seed(seed)
420
+ shuffled = random.sample(rects, len(rects))
421
+ for pack_algo, sort_algo in mc_configs:
422
+ tried += 1
423
+ result = run_packer(
424
+ shuffled, roll_width, max_height, allow_rotation,
425
+ pack_algo, sort_algo, False
426
+ )
427
+ if result is None:
428
+ failed += 1
429
+ continue
430
+ algo_name = pack_algo.__name__ if pack_algo else "Default"
431
+ config = f"[MC:{seed}] {algo_name}"
432
+ evaluate(result, config, shuffled)
433
+
434
+ # ============================================================
435
+ # PHASE 4: LOCAL SWAP OPTIMIZATION
436
+ # ============================================================
437
+ if search_mode == "exhaustive" and best_rects_order is not None:
438
+ base_order = best_rects_order[:]
439
+ n = len(base_order)
440
+ swap_iters = min(300, n * (n - 1) // 2)
441
+
442
+ seen_swaps = set()
443
+ attempts = 0
444
+ while len(seen_swaps) < swap_iters and attempts < swap_iters * 3:
445
+ attempts += 1
446
+ i, j = random.randint(0, n - 1), random.randint(0, n - 1)
447
+ if i >= j:
448
+ continue
449
+ pair = (i, j)
450
+ if pair in seen_swaps:
451
+ continue
452
+ seen_swaps.add(pair)
453
+
454
+ swapped = base_order[:]
455
+ swapped[i], swapped[j] = swapped[j], swapped[i]
456
+
457
+ tried += 1
458
+ result = run_packer(
459
+ swapped, roll_width, max_height, allow_rotation,
460
+ None, SORT_NONE, False
461
+ )
462
+ if result is None:
463
+ failed += 1
464
+ continue
465
+ config = f"[Swap:{i}-{j}] Default"
466
+ evaluate(result, config, swapped)
467
+
468
+ # --- Finalisasi ---
469
+ if best_result is None:
470
+ return None, (
471
+ f"⚠️ Lebar {roll_width:g} cm: tidak ada kombinasi yang muat. "
472
+ "Banner terlalu besar untuk lebar ini."
473
+ ), None, None
474
+
475
+ placed, used_height, not_placed = best_result
476
+ img, used_area, true_used_area, eff, true_eff, rot_count = render_layout(
477
+ placed, used_height, original_dims, roll_width, margin, px_per_unit
478
+ )
479
+
480
+ stats_lines = [
481
+ f"πŸ† Algoritma terpilih : {best_config}",
482
+ f"πŸ” Mode pencarian : {search_mode.upper()}",
483
+ f"πŸ” Total iterasi dicoba : {tried} (gagal: {failed})",
484
+ f"βœ… Item berhasil ditempatkan : {len(placed)} / {total_rects}",
485
+ f"πŸ”„ Item yang diputar 90Β° : {rot_count}",
486
+ f"πŸ“ Ukuran layout terpakai : {roll_width:g} x {used_height:.1f}",
487
+ f"πŸ“ Total luas item (asli) : {true_used_area:.1f} unitΒ²",
488
+ f"πŸ“Š Efisiensi bahan (asli) : {true_eff:.1f}%",
489
+ f"πŸ“Š Efisiensi bahan (dgn margin): {eff:.1f}%",
490
+ ]
491
+
492
+ return img, "\n".join(stats_lines), used_height, true_eff
493
+
494
+
495
+ # --------------------------------------------------------------------------
496
+ # 7. FUNGSI UTAMA: ITERASI SEMUA LEBAR ROLL
497
+ # --------------------------------------------------------------------------
498
+
499
+ def process(roll_widths_text, margin, allow_rotation, search_mode, table_data):
500
+ if table_data is None or len(table_data) == 0:
501
+ return None, "⚠️ Silakan isi tabel daftar banner terlebih dahulu."
502
+
503
+ df = pd.DataFrame(table_data, columns=["Label", "Width", "Height", "Qty"])
504
+ df = df.dropna(subset=["Width", "Height", "Qty"], how="any")
505
+
506
+ # Parse daftar lebar roll
507
+ try:
508
+ widths = [float(w.strip()) for w in roll_widths_text.split(",") if w.strip()]
509
+ widths = [w for w in widths if w > 0]
510
+ except ValueError:
511
+ return None, "⚠️ Format daftar lebar roll tidak valid. Gunakan angka dipisah koma, misal: 150, 200, 250"
512
+
513
+ if not widths:
514
+ return None, "⚠️ Masukkan minimal satu lebar roll yang valid."
515
+
516
+ try:
517
+ margin = float(margin) if margin is not None else 0.0
518
+ except (TypeError, ValueError):
519
+ margin = 0.0
520
+
521
+ # Persiapkan rects sekali untuk semua lebar
522
+ rects, original_dims, total_rects, max_height = prepare_rects(df, margin)
523
+ if rects is None:
524
+ return None, "⚠️ Tidak ada data banner yang valid untuk di-nesting."
525
+
526
+ # --- Iterasi semua lebar roll, cari yang paling hemat ---
527
+ best_overall = None
528
+ best_key = None
529
+ best_width = None
530
+ width_results = []
531
+
532
+ for width in widths:
533
+ if search_mode == "quick":
534
+ # Mode cepat: 1 kombinasi default per lebar
535
+ result = run_packer(rects, width, max_height, bool(allow_rotation))
536
+ if result is None:
537
+ width_results.append((width, None, "Gagal"))
538
+ continue
539
+ placed, used_height, not_placed = result
540
+ if not_placed > 0:
541
+ width_results.append((width, used_height, f"{not_placed} item tidak muat"))
542
+ continue
543
+
544
+ img, _, true_used_area, _, true_eff, rot_count = render_layout(
545
+ placed, used_height, original_dims, width, margin
546
+ )
547
+
548
+ stats_lines = [
549
+ f"πŸ† Mode : CEPAT (1 kombinasi)",
550
+ f"πŸ“ Lebar roll : {width:g} cm",
551
+ f"βœ… Item berhasil ditempatkan : {len(placed)} / {total_rects}",
552
+ f"πŸ”„ Item yang diputar 90Β° : {rot_count}",
553
+ f"πŸ“ Ukuran layout terpakai : {width:g} x {used_height:.1f}",
554
+ f"πŸ“ Total luas item (asli) : {true_used_area:.1f} unitΒ²",
555
+ f"πŸ“Š Efisiensi bahan (asli) : {true_eff:.1f}%",
556
+ ]
557
+
558
+ key = (used_height, -true_eff)
559
+ if best_key is None or key < best_key:
560
+ best_key = key
561
+ best_overall = (img, "\n".join(stats_lines))
562
+ best_width = width
563
+
564
+ width_results.append((width, used_height, f"{true_eff:.1f}%"))
565
+
566
+ else:
567
+ # Mode optimasi: jalankan pencarian mendalam per lebar
568
+ img, stats, used_height, true_eff = search_single_width(
569
+ rects, original_dims, total_rects, max_height,
570
+ width, margin, bool(allow_rotation),
571
+ search_mode, px_per_unit=4.0
572
+ )
573
+
574
+ if img is None:
575
+ width_results.append((width, None, "Gagal"))
576
+ continue
577
+
578
+ key = (used_height, -true_eff)
579
+ if best_key is None or key < best_key:
580
+ best_key = key
581
+ best_overall = (img, stats)
582
+ best_width = width
583
+
584
+ width_results.append((width, used_height, f"{true_eff:.1f}%"))
585
+
586
+ if best_overall is None:
587
+ return None, (
588
+ "⚠️ Tidak ada satupun lebar roll yang bisa menampung semua banner. "
589
+ "Coba tambahkan lebar roll yang lebih besar atau kurangi ukuran banner."
590
+ )
591
+
592
+ # Tambahkan ringkasan perbandingan lebar roll ke stats
593
+ img, stats = best_overall
594
+ comparison = ["\n" + "─" * 40, "πŸ“‹ PERBANDINGAN SEMUA LEBAR ROLL:"]
595
+ for w, h, note in width_results:
596
+ if h is None:
597
+ comparison.append(f" ❌ {w:g} cm β†’ {note}")
598
+ else:
599
+ mark = " ⭐" if w == best_width else ""
600
+ comparison.append(f" {'βœ…' if w == best_width else ' '} {w:g} cm β†’ tinggi {h:.1f}, efisiensi {note}{mark}")
601
+
602
+ final_stats = stats + "\n" + "\n".join(comparison)
603
+
604
+ return img, final_stats
605
+
606
+
607
+ # --------------------------------------------------------------------------
608
+ # 8. UI GRADIO
609
+ # --------------------------------------------------------------------------
610
+
611
+ with gr.Blocks(title="Nesting Otomatis Banner - Percetakan") as demo:
612
+ gr.Markdown("# πŸ–¨οΈ Nesting Otomatis & Visualisasi Layout Cetak Banner")
613
+ gr.Markdown(
614
+ "Masukkan daftar banner dan **beberapa ukuran lebar roll** (pisah dengan koma). "
615
+ "Aplikasi akan mencoba semua kombinasi algoritma pada **setiap lebar roll**, "
616
+ "lalu memilih yang paling hemat bahan. Area **pastel** = margin, "
617
+ "area **pekat** = ukuran banner asli."
618
+ )
619
+
620
+ with gr.Row():
621
+ with gr.Column(scale=1):
622
+ roll_widths = gr.Textbox(
623
+ label="Daftar Lebar Roll (cm, pisah koma)",
624
+ value="150, 200, 250, 300",
625
+ placeholder="Contoh: 150, 200, 250, 300",
626
+ )
627
+ margin = gr.Number(label="Jarak Antar Item / Margin (cm)", value=2, minimum=0)
628
+ allow_rotation = gr.Checkbox(label="Izinkan Rotasi Otomatis", value=True)
629
+
630
+ search_mode = gr.Dropdown(
631
+ label="Mode Pencarian",
632
+ choices=[
633
+ ("⚑ Cepat (1 kombinasi per lebar)", "quick"),
634
+ ("🎯 Standar (~120 kombinasi per lebar)", "standard"),
635
+ ("πŸ” Dalaman (~464 kombinasi per lebar)", "deep"),
636
+ ("🧠 Pro (~2.500+ kombinasi per lebar)", "pro"),
637
+ ("πŸ’Ž Menyeluruh (~5.000+ kombinasi per lebar)", "exhaustive"),
638
+ ],
639
+ value="standard",
640
+ )
641
+
642
+ gr.Markdown("### πŸ“‹ Daftar Banner")
643
+ data_input = gr.Dataframe(
644
+ headers=["Label", "Width", "Height", "Qty"],
645
+ datatype=["str", "number", "number", "number"],
646
+ row_count=(3, "dynamic"),
647
+ value=[
648
+ ["Banner A", 100, 60, 3],
649
+ ["Banner B", 80, 120, 2],
650
+ ["Banner C", 50, 50, 4],
651
+ ],
652
+ )
653
+ btn = gr.Button("πŸ”„ Proses Nesting", variant="primary")
654
+
655
+ with gr.Column(scale=2):
656
+ output_img = gr.Image(label="Pratinjau Layout Cetakan", type="pil")
657
+ output_stats = gr.Textbox(label="Statistik Hasil Nesting", lines=12)
658
+
659
+ btn.click(
660
+ fn=process,
661
+ inputs=[roll_widths, margin, allow_rotation, search_mode, data_input],
662
+ outputs=[output_img, output_stats],
663
+ )
664
+
665
+ if __name__ == "__main__":
666
+ demo.launch()