buzzbandit commited on
Commit
d6deffc
·
verified ·
1 Parent(s): 7e5efdd

try fix again

Browse files
Files changed (1) hide show
  1. app.py +47 -23
app.py CHANGED
@@ -186,6 +186,12 @@ def query_inventory(query_text="", category="", country_name="", capacity=10, re
186
  stocks = data.get("stocks", {})
187
  rows = []
188
 
 
 
 
 
 
 
189
  parsed_item, parsed_country = parse_freeform_query(query_text)
190
  if not country_name and parsed_country:
191
  country_name = parsed_country
@@ -200,7 +206,7 @@ def query_inventory(query_text="", category="", country_name="", capacity=10, re
200
  code = code_raw.upper()
201
  cname = COUNTRY_NAMES.get(code, code)
202
 
203
- # Filter by requested country
204
  if country_name:
205
  if user_code:
206
  if code != user_code:
@@ -212,10 +218,10 @@ def query_inventory(query_text="", category="", country_name="", capacity=10, re
212
  update_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(update_ts)) if update_ts else "Unknown"
213
 
214
  live_lookup = {i["name"]: i for i in cdata.get("stocks", [])}
 
215
 
216
- # Merge known items (include 0-qty)
217
- for iname, itype in ITEM_TO_TYPE.items():
218
- itype = itype.lower()
219
  item_data = live_lookup.get(iname, {"quantity": 0, "cost": 0})
220
  qty = item_data.get("quantity", 0)
221
  cost = item_data.get("cost", 0)
@@ -235,7 +241,7 @@ def query_inventory(query_text="", category="", country_name="", capacity=10, re
235
  rows.append({
236
  "Country": cname,
237
  "Item": iname,
238
- "Category": itype.title(),
239
  "Quantity": qty,
240
  "Cost": cost,
241
  "Max Capacity Cost": cost * capacity,
@@ -243,10 +249,10 @@ def query_inventory(query_text="", category="", country_name="", capacity=10, re
243
  })
244
 
245
  if not rows:
 
246
  return pd.DataFrame([{"Result": "No inventory found for that query."}]), f"Last update: {last_update}"
247
 
248
- df = pd.DataFrame(rows)
249
- df = df.sort_values(by=["Country", "Item"])
250
  for col in ["Quantity", "Cost", "Max Capacity Cost"]:
251
  if col in df.columns:
252
  df[col] = df[col].apply(lambda x: f"{x:,.0f}" if isinstance(x, (int, float)) and x != "" else x)
@@ -278,24 +284,42 @@ with gr.Blocks(title="🧳 Torn Inventory Viewer") as iface:
278
  # --- JS fix for persistent capacity ---
279
  gr.HTML("""
280
  <script>
281
- window.addEventListener('DOMContentLoaded', () => {
282
- const saved = localStorage.getItem('travel_capacity');
283
- const capField = document.querySelector('input[type=number]');
284
- if (saved && capField) {
285
- capField.value = saved;
286
- capField.dispatchEvent(new Event('input', { bubbles: true }));
 
 
 
 
 
 
287
  }
288
- const observer = new MutationObserver(() => {
289
- const field = document.querySelector('input[type=number]');
290
- if (field && !field.dataset.synced) {
291
- field.dataset.synced = "1";
292
- field.addEventListener('input', () => {
293
- localStorage.setItem('travel_capacity', field.value);
294
- });
295
- }
 
 
 
 
 
 
 
 
 
 
 
 
296
  });
297
- observer.observe(document.body, { childList: true, subtree: true });
298
- });
299
  </script>
300
  """)
301
 
 
186
  stocks = data.get("stocks", {})
187
  rows = []
188
 
189
+ # --- Build per-country catalogs from live payload ---
190
+ COUNTRY_CATALOG = {
191
+ code.upper(): {i["name"] for i in cdata.get("stocks", [])}
192
+ for code, cdata in stocks.items()
193
+ }
194
+
195
  parsed_item, parsed_country = parse_freeform_query(query_text)
196
  if not country_name and parsed_country:
197
  country_name = parsed_country
 
206
  code = code_raw.upper()
207
  cname = COUNTRY_NAMES.get(code, code)
208
 
209
+ # Strict country filter
210
  if country_name:
211
  if user_code:
212
  if code != user_code:
 
218
  update_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(update_ts)) if update_ts else "Unknown"
219
 
220
  live_lookup = {i["name"]: i for i in cdata.get("stocks", [])}
221
+ candidate_names = sorted(COUNTRY_CATALOG.get(code, set())) # ONLY this country's items
222
 
223
+ for iname in candidate_names:
224
+ itype = ITEM_TO_TYPE.get(iname, "").lower()
 
225
  item_data = live_lookup.get(iname, {"quantity": 0, "cost": 0})
226
  qty = item_data.get("quantity", 0)
227
  cost = item_data.get("cost", 0)
 
241
  rows.append({
242
  "Country": cname,
243
  "Item": iname,
244
+ "Category": itype.title() if itype else "",
245
  "Quantity": qty,
246
  "Cost": cost,
247
  "Max Capacity Cost": cost * capacity,
 
249
  })
250
 
251
  if not rows:
252
+ print(f"⚠️ No matches for '{item_term or category or 'all items'}' in {country_name or 'ALL'}")
253
  return pd.DataFrame([{"Result": "No inventory found for that query."}]), f"Last update: {last_update}"
254
 
255
+ df = pd.DataFrame(rows).sort_values(by=["Country", "Item"])
 
256
  for col in ["Quantity", "Cost", "Max Capacity Cost"]:
257
  if col in df.columns:
258
  df[col] = df[col].apply(lambda x: f"{x:,.0f}" if isinstance(x, (int, float)) and x != "" else x)
 
284
  # --- JS fix for persistent capacity ---
285
  gr.HTML("""
286
  <script>
287
+ (function () {
288
+ function root() {
289
+ const app = document.querySelector('gradio-app');
290
+ return app && app.shadowRoot ? app.shadowRoot : document;
291
+ }
292
+ function setCapacity(val) {
293
+ const r = root();
294
+ const field = r.querySelector('input[type=number]');
295
+ if (!field) return false;
296
+ field.value = val;
297
+ field.dispatchEvent(new Event('input', { bubbles: true }));
298
+ return true;
299
  }
300
+ function restoreOnce() {
301
+ const saved = localStorage.getItem('travel_capacity');
302
+ if (!saved) return;
303
+ if (setCapacity(saved)) console.log('🧳 capacity restored:', saved);
304
+ }
305
+ function attachSaver() {
306
+ const r = root();
307
+ const field = r.querySelector('input[type=number]');
308
+ if (!field || field.dataset.tcListen === '1') return;
309
+ field.dataset.tcListen = '1';
310
+ field.addEventListener('input', () => {
311
+ localStorage.setItem('travel_capacity', field.value);
312
+ });
313
+ }
314
+ window.addEventListener('DOMContentLoaded', () => {
315
+ setTimeout(() => { restoreOnce(); attachSaver(); }, 500);
316
+ });
317
+ const obs = new MutationObserver(() => {
318
+ restoreOnce();
319
+ attachSaver();
320
  });
321
+ obs.observe(document.documentElement, { childList: true, subtree: true });
322
+ })();
323
  </script>
324
  """)
325