import gradio as gr import pyscipopt def knapsack_optimization(values, weights, capacity): n = len(values) model = pyscipopt.Model("Knapsack") # Define decision variables x = {i: model.addVar(f"x_{i}", vtype="B") for i in range(n)} # Objective: Maximize total value model.setObjective(sum(values[i] * x[i] for i in range(n)), "maximize") # Constraint: Total weight should not exceed capacity model.addCons(sum(weights[i] * x[i] for i in range(n)) <= capacity) # Solve the problem model.optimize() # Get results selected_items = [i for i in range(n) if model.getVal(x[i]) > 0.5] total_value = sum(values[i] for i in selected_items) total_weight = sum(weights[i] for i in selected_items) return f"Optimal Value: {total_value}", f"Total Weight: {total_weight}", f"Selected Items: {selected_items}" # Create a Gradio Interface iface = gr.Interface( fn=lambda values, weights, capacity: knapsack_optimization( list(map(int, values.split(","))), list(map(int, weights.split(","))), int(capacity) ), inputs=[ gr.Textbox(label="Item Values (comma-separated)", placeholder="10, 40, 30, 50"), gr.Textbox(label="Item Weights (comma-separated)", placeholder="5, 8, 3, 6"), gr.Number(label="Knapsack Capacity", value=10) ], outputs=gr.JSON(label="Optimization Results"), title="📦 Knapsack Optimization with SCIP" ) iface.launch()