-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
360 lines (318 loc) · 13.9 KB
/
Copy pathapp.py
File metadata and controls
360 lines (318 loc) · 13.9 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""
1B-PuLP-B-flask/app.py
Flask web application for managing and solving integer linear programming (ILP) problems.
Provides a user interface for defining variables, setting constraints, and running optimizations.
Features:
- Add, import, export, and download optimization variables.
- Set budget constraints and maximize profit.
- Clean separation of concerns (web UI, optimization logic, configuration).
@author: Mafu
@date: 2025-06-14
"""
import os
import json
import threading
import time
import webbrowser
from typing import Tuple, Dict, Any, Optional
from flask import Flask, render_template, request, flash, redirect, url_for, send_file
from werkzeug.utils import secure_filename
from optimizer_core import (
IntegerVariable, create_integer_variable, optimize, variables_list,
clear_variables, OptimizationError
)
from config import Config
def create_app(config_class=Config) -> Flask:
"""Create and configure the Flask application."""
app = Flask(__name__)
app.config.from_object(config_class)
config_class.init_app(app)
return app
app = create_app()
budget = Config.DEFAULT_BUDGET
def safe_filename(filename: str) -> str:
"""Generate a secure filename and ensure .json extension."""
filename = secure_filename(filename)
if not filename.endswith('.json'):
filename += '.json'
return filename
def handle_file_operation(operation: str, filepath: str, variables: Optional[list] = None) -> None:
"""Handle file operations with error checking."""
try:
if operation == 'save':
with open(filepath, 'w') as f:
json.dump([var.to_dict() for var in variables or variables_list], f, indent=4)
elif operation == 'load':
with open(filepath, 'r') as f:
data = json.load(f)
clear_variables()
for item in data:
# Calculate missing fields if needed
if 'unit_selling_price' not in item and 'profit' in item and 'multiplier' in item:
item['unit_selling_price'] = item['multiplier'] * (1 + item['profit'])
if 'profit' not in item and 'unit_selling_price' in item and 'multiplier' in item:
item['profit'] = (item['unit_selling_price'] - item['multiplier']) / item['multiplier']
var = IntegerVariable.from_dict(item)
var.validate()
variables_list.append(var)
except Exception as e:
raise IOError(f"Error {operation}ing products: {str(e)}")
def parse_variable_form() -> Tuple[Dict[str, Any], bool]:
"""Parse and validate variable form data."""
try:
unit_cost = float(request.form['multiplier'])
input_mode = request.form.get('input_mode', 'selling_price')
if unit_cost <= 0:
raise ValueError("Unit cost must be positive.")
if input_mode == 'profit_per_dollar':
profit_per_dollar = float(request.form['profit_per_dollar'])
unit_selling_price = unit_cost * (1 + profit_per_dollar)
else:
unit_selling_price = float(request.form['unit_selling_price'])
profit_per_dollar = (unit_selling_price - unit_cost) / unit_cost
data = {
'name': request.form['name'],
'lowerBound': int(request.form['lowerBound']) if request.form['lowerBound'] else 0,
'upperBound': int(request.form['upperBound']) if request.form['upperBound'] else None,
'profit': profit_per_dollar,
'integer': bool(request.form.get('integer')),
'multiplier': unit_cost,
'unit_cost': unit_cost,
'unit_selling_price': unit_selling_price
}
return data, True
except ValueError as e:
flash(f"Invalid product input: {str(e)}", "error")
return {}, False
# Routes
@app.route("/", methods=["GET", "POST"])
def index():
"""Handle main page and form submissions."""
global budget
max_profit = None
result = {}
if request.method == "POST":
if "update_budget" in request.form:
try:
new_budget = int(request.form["budget"])
if new_budget <= 0:
raise ValueError("Budget must be positive")
budget = new_budget
flash("Budget updated successfully!", "success")
except ValueError as e:
flash(f"Invalid budget value: {str(e)}", "error")
elif "add_variable" in request.form:
data, valid = parse_variable_form()
if valid:
try:
create_integer_variable(**data)
flash("Product added successfully!", "success")
except OptimizationError as e:
flash(str(e), "error")
elif "optimize" in request.form:
if not variables_list:
flash("No products to optimize. Add products first.", "error")
else:
try:
max_profit, result = optimize(variables_list, budget)
# Calculate total unit cost and per-product units
product_units = {}
product_costs = {}
total_unit_cost = 0
total_revenue = 0
for var in variables_list:
units = 0
if var.multiplier > 0:
units = int(result[var.name] / var.multiplier)
product_units[var.name] = units
product_costs[var.name] = result[var.name]
total_unit_cost += result[var.name]
# Revenue for this product: units * selling price
if hasattr(var, 'unit_selling_price'):
total_revenue += units * var.unit_selling_price
else:
total_revenue += result[var.name]
max_profit_value = total_revenue - total_unit_cost
except OptimizationError as e:
flash(f"Optimization failed: {str(e)}", "error")
return render_template("index.html",
variables=variables_list,
max_profit=max_profit,
result=result,
budget=budget,
product_units=locals().get('product_units', {}),
product_costs=locals().get('product_costs', {}),
total_unit_cost=locals().get('total_unit_cost', 0),
total_revenue=locals().get('total_revenue', 0),
max_profit_value=locals().get('max_profit_value', 0))
@app.route("/export", methods=["POST"])
def export_variables():
"""Export variables to a JSON file in the exports folder."""
try:
filename = safe_filename(request.form.get("filename", "products.json"))
filepath = os.path.join(app.config['EXPORT_FOLDER'], filename)
handle_file_operation('save', filepath)
flash(f"Products exported successfully!", "success")
except Exception as e:
flash(f"Export failed: {str(e)}", "error")
return redirect(url_for("index"))
@app.route("/import", methods=["POST"])
def import_variables():
"""Import variables from an uploaded JSON file."""
if "file" not in request.files:
flash("No file selected for importing.", "error")
return redirect(url_for("index"))
file = request.files["file"]
if not file.filename:
flash("No file selected for importing.", "error")
return redirect(url_for("index"))
try:
filename = safe_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
handle_file_operation('load', filepath)
flash("Products imported successfully!", "success")
except Exception as e:
flash(f"Import failed: {str(e)}", "error")
return redirect(url_for("index"))
@app.route("/download", methods=["POST"])
def download_variables():
"""Download variables as a JSON file."""
try:
filename = safe_filename(request.form.get("filename", "products.json").strip())
filepath = os.path.join(app.config['EXPORT_FOLDER'], filename)
handle_file_operation('save', filepath)
return send_file(filepath, as_attachment=True, download_name=filename)
except Exception as e:
flash(f"Download failed: {str(e)}", "error")
return redirect(url_for("index"))
@app.route("/delete_variable/<name>", methods=["POST"])
def delete_variable(name):
"""Delete a variable by its name."""
try:
# Remove in-place to preserve shared state
variables_list[:] = [var for var in variables_list if var.name != name]
flash(f"Product '{name}' deleted successfully!", "success")
except Exception as e:
flash(f"Error deleting product: {str(e)}", "error")
return redirect(url_for("index"))
@app.route("/update_variable", methods=["POST"])
def update_variable():
"""Update an existing variable."""
try:
old_name = request.form.get('old_name')
if not old_name:
return {'status': 'error', 'message': 'Original product name is required'}, 400
# Find the product we're updating
old_var = next((var for var in variables_list if var.name == old_name), None)
if not old_var:
return {'status': 'error', 'message': f'Product {old_name} not found'}, 404
data, valid = parse_variable_form()
if not valid:
return {'status': 'error', 'message': 'Invalid input data'}, 400
# If we're not changing the name, or if the new name is available
if data['name'] == old_name or not any(var.name == data['name'] for var in variables_list if var.name != old_name):
# Create new product instance to validate before removing old one
new_var = IntegerVariable(**data)
new_var.validate()
# Remove the old product in-place
variables_list[:] = [var for var in variables_list if var.name != old_name]
# Add the new product
variables_list.append(new_var)
flash("Product updated successfully!", "success")
return {'status': 'success'}, 200
else:
return {'status': 'error', 'message': f'A product named {data["name"]} already exists'}, 400
except ValueError as e:
return {'status': 'error', 'message': f'Invalid value: {str(e)}'}, 400
except Exception as e:
flash(f"Error updating product: {str(e)}", "error")
return {'status': 'error', 'message': str(e)}, 500
@app.route("/clear_table", methods=["POST"])
def clear_table():
"""Delete all variables (clear the table)."""
global variables_list
try:
clear_variables()
flash("All products have been deleted.", "success")
except Exception as e:
flash(f"Error deleting products: {str(e)}", "error")
return redirect(url_for("index"))
def run_app(port: int = 5000, debug: bool = True):
"""Run the Flask application with browser auto-open."""
url = f"http://localhost:{port}"
def open_browser():
time.sleep(1)
webbrowser.open(url)
if not debug:
threading.Thread(target=open_browser).start()
app.run(debug=debug, use_reloader=False, port=port)
# --- Serve OpenAPI spec and Swagger UI ---
from flask import send_from_directory, Response
import pathlib
@app.route("/openapi.yaml")
def openapi_spec():
# Serve the OpenAPI YAML file
return send_from_directory(pathlib.Path(__file__).parent, "openapi.yaml", mimetype="text/yaml")
@app.route("/api/docs")
def swagger_ui():
# Serve Swagger UI using CDN, pointing to /openapi.yaml
html = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API Docs</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
<script>
window.onload = function() {
SwaggerUIBundle({
url: '/openapi.yaml',
dom_id: '#swagger-ui',
});
};
</script>
</body>
</html>
'''
return Response(html, mimetype="text/html")
# --- API endpoint for optimization ---
from flask import jsonify
@app.route("/api/optimize", methods=["POST"])
def api_optimize():
try:
data = request.get_json()
variables = data.get("variables")
budget = data.get("budget")
if not isinstance(variables, list) or budget is None:
return jsonify({"error": "Invalid input"}), 400
var_objs = []
for v in variables:
v = dict(v) # ensure mutable
# Compute profit if missing
if 'profit' not in v or v['profit'] is None:
multiplier = v.get('multiplier', v.get('unit_cost', 1))
# If profit_per_dollar is provided
if 'profit_per_dollar' in v:
v['profit'] = float(v['profit_per_dollar'])
# If unit_selling_price is provided
elif 'unit_selling_price' in v and multiplier:
v['profit'] = (float(v['unit_selling_price']) - float(multiplier)) / float(multiplier)
else:
v['profit'] = 0.0
var = IntegerVariable.from_dict(v)
var.validate()
var_objs.append(var)
max_profit, result = optimize(var_objs, budget)
return jsonify({
"max_profit": max_profit,
"result": result
})
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == "__main__":
run_app()