-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
212 lines (183 loc) · 7.4 KB
/
Copy pathapp.py
File metadata and controls
212 lines (183 loc) · 7.4 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
"""
Flask front-end for the 'Nearly-Fair Division with Capacity Constraints' demo.
To run locally with:
$ python3 -m venv venv && . venv/bin/activate
(venv)$ pip install -r requirements.txt
(venv)$ flask --app app run --debug
Open http://127.0.0.1:5000/ in your browser.
"""
import io
import json
import logging
import traceback
from flask import (Flask, flash, redirect, render_template,
request, url_for)
# ----------------------------------------------------------------------
# Import your algorithm and helpers (they live in NFD.py / fairpyx)
# ----------------------------------------------------------------------
from NFD import Nearly_Fair_Division
from fairpyx import Instance, divide
from is_EF11 import is_EF11 # Import the EF11 checker
# ----------------------------------------------------------------------
# Flask setup
# ----------------------------------------------------------------------
app = Flask(__name__)
app.secret_key = "CHANGE-ME-IN-PRODUCTION" # Needed for flash messages
# ----------------------------------------------------------------------
# Logging: capture algorithm output into an in-memory StringIO
# ----------------------------------------------------------------------
algo_logger = logging.getLogger("fair_division_demo")
algo_logger.setLevel(logging.INFO)
# algo_logger.setLevel(logging.WARNING)
if not algo_logger.handlers:
import sys
algo_logger.addHandler(logging.StreamHandler(sys.stdout))
def run_algorithm_and_capture_logs(instance: Instance) -> tuple[dict, str]:
"""
Execute Nearly_Fair_Division on *instance* and return:
(allocation_dict, log_text)
"""
log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
handler.setFormatter(
logging.Formatter("[%(levelname)s] %(message)s")
)
# Capture the NFD module's logger
nfd_logger = logging.getLogger("NFD")
nfd_logger.addHandler(handler)
nfd_logger.setLevel(logging.INFO) # or logging.DEBUG for more detail
try:
allocation = divide(Nearly_Fair_Division, instance=instance)
finally:
handler.flush()
nfd_logger.removeHandler(handler)
return allocation, log_stream.getvalue()
# ----------------------------------------------------------------------
# Routes
# ----------------------------------------------------------------------
@app.route("/")
def index():
"""Landing page – high-level explanation & nav links."""
return render_template("index.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/demo", methods=["GET", "POST"])
def demo():
"""
GET → show the input form.
POST → parse JSON, run the algorithm, show allocation + logs.
"""
if request.method == "GET":
# Blank form (prefilled with the example from the prompt)
return render_template("input.html", example=_EXAMPLE_INPUT)
# ------------------------------------------------------------------
# POST: read & validate the four JSON blocks
# ------------------------------------------------------------------
try:
valuations = json.loads(request.form["valuations"])
item_categories = json.loads(request.form["item_categories"])
item_capacities = {item: 1 for item in item_categories}
category_capacities = json.loads(request.form["category_capacities"])
except json.JSONDecodeError as exc:
flash(f" JSON parsing error: {exc}", "danger")
return redirect(url_for("demo"))
# ------------------------------------------------------------------
# Build an Instance object and run the algorithm
# ------------------------------------------------------------------
try:
instance = Instance(
valuations=valuations,
item_categories=item_categories,
item_capacities=item_capacities,
category_capacities=category_capacities,
)
allocation, log_text = run_algorithm_and_capture_logs(instance)
# Run EF11 analysis
ef11_result = None
if allocation:
try:
ef11_result = is_EF11(instance, allocation)
except Exception as e:
log_text += f"\n\n[WARNING] EF11 analysis failed: {e}"
except Exception as exc:
# Any failure (invalid input, algorithm bug, etc.) lands here
tb = traceback.format_exc()
flash(f"Algorithm raised an exception: {exc}", "danger")
return render_template(
"result.html",
raw_input=_pretty_json(
valuations, item_categories, category_capacities,
),
logs=tb,
allocation=None,
ef11_result=None,
item_details=None,
agents=None,
)
# ------------------------------------------------------------------
# Prepare item details for display
# ------------------------------------------------------------------
item_details = []
agents = list(valuations.keys())
if allocation:
for item, category in item_categories.items():
detail = {
'item': item,
'category': category,
'agent_values': {agent: valuations[agent].get(item, 0) for agent in agents},
'allocated_to': None
}
# Find which agent got this item
for agent, bundle in allocation.items():
if item in bundle:
detail['allocated_to'] = agent
break
item_details.append(detail)
# Sort by category then by item name
item_details.sort(key=lambda x: (x['category'], x['item']))
# ------------------------------------------------------------------
# Success: show everything
# ------------------------------------------------------------------
return render_template(
"result.html",
raw_input=_pretty_json(
valuations, item_categories, category_capacities
),
logs=log_text,
allocation=allocation,
ef11_result=ef11_result,
item_details=item_details,
agents=agents,
)
# ----------------------------------------------------------------------
# Helpers
# ----------------------------------------------------------------------
def _pretty_json(*objs) -> str:
"""Nicely indent several JSON dicts one after another."""
return "\n\n".join(json.dumps(o, indent=2, ensure_ascii=False) for o in objs)
# ----------------------------------------------------------------------
# Prefill-example exactly as you gave it
# ----------------------------------------------------------------------
_EXAMPLE_INPUT = {
"valuations": {
"Agent1": {"o1": 0, "o2": -1, "o3": -4, "o4": -5, "o5": 0, "o6": 2},
"Agent2": {"o1": 0, "o2": -1, "o3": -2, "o4": -1, "o5": -1, "o6": 0},
},
"item_categories": {
"o1": "cat1",
"o2": "cat1",
"o3": "cat1",
"o4": "cat1",
"o5": "cat2",
"o6": "cat2",
},
"category_capacities": {"cat1": 2, "cat2": 1},
}
# ----------------------------------------------------------------------
# 'main' guard – so gunicorn / flask run both work
# ----------------------------------------------------------------------
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0",port=5000)
# this is website address on the university server:
# https://matan.ziv.csariel.xyz/demo