forked from jerry800416/3D-bin-packing
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
188 lines (165 loc) · 5.78 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
from py3dbp import Packer, Bin, Item, Painter
import streamlit as st
import random
import csv
import pandas as pd
import subprocess
import sys
def run_python_file(file_path):
try:
# Execute the Python file using subprocess
subprocess.run([f"{sys.executable}", file_path])
st.success(f"Python file '{file_path}' executed successfully.")
except Exception as e:
st.error(f"Error executing '{file_path}': {e}")
# script_path = "interactiveplot.py"
# current_permissions = os.stat(script_path).st_mode
# if not current_permissions & 0o111:
# os.chmod(script_path, current_permissions | 0o111)
# st.text("Execute permissions added.")
#st.text(f"Current permissions: {current_permissions:o}")
st.set_page_config(page_title="EZPack", page_icon=":smiley:")
st.title("EZPack")
uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
# Read the contents of the uploaded file into memory
file_contents = uploaded_file.read()
# Save the uploaded file's contents to a file named "data.csv"
with open("data.csv", "wb") as f:
f.write(file_contents)
if st.button("Open interactive view"):
file_path = "interactiveplot.py" # Replace with the path to your Python file
run_python_file(file_path)
seed_value = 42
random.seed(seed_value)
COLORS = ["yellow", "olive", "pink", "brown", "red",
"blue", "green", "purple", "orange", "gray"]
# Initialize variables to store bins and items
bins = []
bin_size = -1
items = []
item_size = 0
counter = 0
bin_weights = []
item_weights = []
bins_used = 0
if uploaded_file is not None:
with open('data.csv', mode='r', encoding='utf-8-sig') as csv_file:
csv_reader = csv.reader(csv_file)
# Iterate through the rows and parse bins and items
for row in csv_reader:
# Check if the row is empty
if not any(row):
continue
# If there is a single number in the row, it represents the number of bins or items
if row[1] == "":
num = int(row[0].strip('\ufeff'))
if bin_size == -1:
bin_size = num
counter = bin_size
else:
item_size = num
else:
dimensions = tuple(int(val) for val in row[:3])
if counter > 0:
bins.append(dimensions)
bin_weights.append(int(row[3]))
counter -= 1
else:
items.append(dimensions)
item_weights.append(int(row[3]))
# init packing function
packer = Packer()
# init bin
for i in range(len(bins)):
box = Bin('Container {}'.format(str(i+1)), bins[i], 100, 0, 0)
packer.addBin(box)
# add item
for i in range(len(items)):
packer.addItem(Item(
partno='{}'.format(str(i+1)),
name='test{}'.format(str(i+1)),
typeof='cube',
WHD=items[i],
weight=item_weights[i],
level=1,
loadbear=100,
updown=True,
color=random.choice(COLORS)
)
)
# calculate packing
packer.pack(
bigger_first=True,
distribute_items=True,
fix_point=True,
check_stable=True,
support_surface_ratio=0.75,
number_of_decimals=0
)
# put order
packer.putOrder()
st.title("Packing information:")
for idx, b in enumerate(packer.bins):
st.header(f"{b.string()} \n")
current_bin_weight = 0
volume = b.width * b.height * b.depth
volume_t = 0
volume_f = 0
data = {
"Package no": [],
"Dimensions / meters": [],
"Weight / kg": []
}
for item in b.items:
current_bin_weight += float(item.weight)
data["Package no"].append(item.partno)
data["Dimensions / meters"].append(
f"{item.width} x {item.height} x {item.depth}")
data["Weight / kg"].append(item.weight)
volume_t += float(item.width) * \
float(item.height) * float(item.depth)
data1 = {
"Space utilization": [],
"Total weight of items / kg": [],
"Residual volume": []
}
data1["Space utilization"].append(
f'{round(volume_t / float(volume) * 100, 2)}%')
data1["Total weight of items / kg"].append(current_bin_weight)
data1["Residual volume"].append(float(volume) - volume_t)
# draw results
painter = Painter(b)
fig = painter.plotBoxAndItems(
title=b.partno,
alpha=0.8,
write_num=False,
fontsize=10
)
df = pd.DataFrame(data)
df1 = pd.DataFrame(data1)
df.index += 1
if round(volume_t / float(volume) * 100, 2) != 0.0:
bins_used += 1
st.pyplot(fig)
st.subheader("FITTED ITEMS")
st.table(df)
st.table(df1)
unfitted_items = {
"Package no": [],
"Dimensions / meters": [],
"Weight / kg": []
}
for item in packer.unfit_items:
unfitted_items["Package no"].append(item.partno)
unfitted_items["Dimensions / meters"].append(
f"{item.width} x {item.height} x {item.depth}")
unfitted_items["Weight / kg"].append(item.weight)
# Print the entire output
st.header("Summary:")
st.subheader("Total Containers utilised: " +
str(bins_used) + "/" + str(len(bins)))
st.subheader("Unpacked Items:")
unfitted_items = pd.DataFrame(unfitted_items)
unfitted_items.index += 1
st.table(unfitted_items)