fix(offers): background refresh + skip unchanged matching
Two things made Opdater show 'Opdatering fejlede': the refresh ran synchronously (so a slow, rate-limited translate timed out the browser) and a 429 returned 502. Now: - /api/offers/refresh starts the work in a background thread and returns immediately; the button says 'Opdaterer i baggrunden' and reloads a bit later as batches land. A lock prevents overlapping runs. - match_offers_ai skips the Claude call when the offer set is unchanged since the last successful match (hashed), so it runs ~weekly (when the avis turns over), not every daily refresh — fewer calls, less cost, less rate pressure.
This commit is contained in:
41
app.py
41
app.py
@@ -3,6 +3,7 @@ import os
|
|||||||
import re
|
import re
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
|
import hashlib
|
||||||
import threading
|
import threading
|
||||||
import unicodedata
|
import unicodedata
|
||||||
import socket
|
import socket
|
||||||
@@ -417,6 +418,18 @@ def match_offers_ai():
|
|||||||
"SELECT id, heading, catalog FROM offers")]
|
"SELECT id, heading, catalog FROM offers")]
|
||||||
if not offers:
|
if not offers:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
# Skip the (daily) match call when the offer set hasn't changed since the
|
||||||
|
# last successful match — the avis only turns over weekly, so this avoids a
|
||||||
|
# pointless Claude call most days.
|
||||||
|
sig = hashlib.md5(
|
||||||
|
"\n".join(sorted(o['id'] + '|' + (o.get('heading') or '') for o in offers))
|
||||||
|
.encode('utf-8')).hexdigest()
|
||||||
|
with get_db() as c:
|
||||||
|
if _meta_get(c, 'last_match_sig') == sig and \
|
||||||
|
c.execute("SELECT COUNT(*) FROM offer_matches").fetchone()[0]:
|
||||||
|
return 0
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import anthropic
|
import anthropic
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -465,6 +478,7 @@ def match_offers_ai():
|
|||||||
for ik, oid in pairs:
|
for ik, oid in pairs:
|
||||||
c.execute("INSERT OR REPLACE INTO offer_matches(item_key,offer_id,updated) "
|
c.execute("INSERT OR REPLACE INTO offer_matches(item_key,offer_id,updated) "
|
||||||
"VALUES(?,?,?)", (ik, oid, now))
|
"VALUES(?,?,?)", (ik, oid, now))
|
||||||
|
_meta_set(c, 'last_match_sig', sig) # remember this offer set as matched
|
||||||
app.logger.info("citti match: %d AI matches", len(pairs))
|
app.logger.info("citti match: %d AI matches", len(pairs))
|
||||||
return len(pairs)
|
return len(pairs)
|
||||||
|
|
||||||
@@ -496,6 +510,27 @@ def refresh_offers_safe():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
_refreshing = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_offers_async():
|
||||||
|
"""Run a refresh in the background. Translation/matching can be slow under
|
||||||
|
rate limits, so the manual Opdater button must not block the HTTP request
|
||||||
|
(and time out the browser). Returns True if a run was started, False if one
|
||||||
|
is already in progress."""
|
||||||
|
if not _refreshing.acquire(blocking=False):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _run():
|
||||||
|
try:
|
||||||
|
refresh_offers_safe()
|
||||||
|
finally:
|
||||||
|
_refreshing.release()
|
||||||
|
|
||||||
|
threading.Thread(target=_run, name="offer-refresh", daemon=True).start()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _offers_stale():
|
def _offers_stale():
|
||||||
with get_db() as c:
|
with get_db() as c:
|
||||||
last = _meta_get(c, 'last_refresh')
|
last = _meta_get(c, 'last_refresh')
|
||||||
@@ -843,10 +878,8 @@ def offer_pick():
|
|||||||
|
|
||||||
@app.route('/api/offers/refresh', methods=['POST'])
|
@app.route('/api/offers/refresh', methods=['POST'])
|
||||||
def offer_refresh():
|
def offer_refresh():
|
||||||
summary = refresh_offers_safe()
|
started = refresh_offers_async()
|
||||||
if summary is None:
|
return jsonify(ok=True, started=started)
|
||||||
return jsonify(ok=False, error='refresh failed'), 502
|
|
||||||
return jsonify(ok=True, **summary)
|
|
||||||
|
|
||||||
|
|
||||||
@app.route('/koeb-nu')
|
@app.route('/koeb-nu')
|
||||||
|
|||||||
@@ -156,15 +156,16 @@ async function refreshOffers() {
|
|||||||
const btn = document.getElementById('refresh-btn');
|
const btn = document.getElementById('refresh-btn');
|
||||||
btn.textContent = '⟳ Henter…'; btn.disabled = true;
|
btn.textContent = '⟳ Henter…'; btn.disabled = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/offers/refresh', {method: 'POST'});
|
// The refresh runs in the background (translation can be slow under rate
|
||||||
const data = await res.json();
|
// limits), so we just kick it off and reload a little later to show
|
||||||
if (data.ok) { window.location.reload(); return; }
|
// progress — the page fills in as batches complete.
|
||||||
alert('Opdatering fejlede. Prøv igen om lidt.');
|
await fetch('/api/offers/refresh', {method: 'POST'});
|
||||||
|
btn.textContent = '⟳ Opdaterer i baggrunden…';
|
||||||
|
setTimeout(function () { window.location.reload(); }, 12000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert('Opdatering fejlede. Prøv igen om lidt.');
|
|
||||||
}
|
|
||||||
btn.textContent = '⟳ Opdater'; btn.disabled = false;
|
btn.textContent = '⟳ Opdater'; btn.disabled = false;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user