data_sync.py
12 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
"""Overlap-window sync and content reconciliation, serialized across all entry points."""
from datetime import datetime, timedelta
import json
import logging
import re
import tempfile
import threading
from pathlib import Path
import numpy as np
logger = logging.getLogger(__name__)
def primary_url(images):
"""Preserve score=1 preference and the existing URL field aliases."""
try:
data = json.loads(images) if isinstance(images, str) else images
except (ValueError, TypeError):
return None
def url(item):
if isinstance(item, dict):
return item.get('imgUrl') or item.get('url') or item.get('image_url') or item.get('src')
return item
result = None
if isinstance(data, list) and data:
result = url(data[0])
if isinstance(data[0], dict):
for item in data:
if isinstance(item, dict) and item.get('score') == 1:
result = url(item)
break
elif isinstance(data, dict) and data:
result = url(data) or data.get('main')
if not result:
result = url(next(iter(data.values())))
return result if isinstance(result, str) and result.startswith(('http://', 'https://')) else None
def as_datetime(value):
return value if isinstance(value, datetime) else datetime.fromisoformat(value)
class MySQLSource:
def __init__(self, config):
self.config = config
def _query(self, sql, params):
import pymysql
c = self.config
with pymysql.connect(host=c['host'], port=int(c['port']), user=c['username'],
password=c['password'], database=c['database'],
charset=c.get('charset', 'utf8mb4'),
connect_timeout=10, read_timeout=60, write_timeout=60,
cursorclass=pymysql.cursors.DictCursor) as conn:
with conn.cursor() as cursor:
cursor.execute(sql, params)
return cursor.fetchall()
def fetch_batch(self, eps_ids, modified, last_id, limit):
if not eps_ids:
return []
return self._query("""SELECT id, eps_id, design_no, images, delete_key, utc_modified
FROM saas_design.design WHERE eps_id IN (""" + ','.join(['%s'] * len(eps_ids)) + """)
AND (utc_modified > %s OR (utc_modified = %s AND id > %s))
ORDER BY utc_modified ASC, id ASC LIMIT %s""",
(*eps_ids, modified, modified, last_id, limit))
def fetch_active(self, eps_ids):
if not eps_ids:
return []
return self._query("""SELECT id, eps_id, design_no, images, delete_key, utc_modified
FROM saas_design.design WHERE eps_id IN (""" + ','.join(['%s'] * len(eps_ids)) + """)
AND (delete_key='0' OR delete_key IS NULL)""", tuple(eps_ids))
class DesignDataSync:
def __init__(self, config, index=None, db_manager=None, source=None, downloader=None, extractor=None):
from database import DatabaseManager
from core.vector_index import VectorIndex, configured_dimension
from core.feature_extractor import FeatureExtractor
self.config = config
self.settings = config.get('sync', {})
self.eps_ids = self.settings.get('eps_ids', [2])
self.db_manager = db_manager if db_manager is not None else DatabaseManager(config['database']['sqlite']['path'])
self.index = index if index is not None else VectorIndex(configured_dimension(config))
if index is None:
self.index.bulk_load(self.db_manager.iter_index_rows())
self.version = self.db_manager.max_feat_version()
self.source = source if source is not None else MySQLSource(config['mysql'])
self.downloader = downloader if downloader is not None else self._download_image
self.feature_extractor = extractor if extractor is not None else FeatureExtractor(
orb_max_features=config.get('feature_extractor', {}).get('orb', {}).get('max_features', 1200))
self.mutex = threading.Lock()
self.status_lock = threading.Lock()
self._status = {'status': 'idle'}
self.stop_event = threading.Event()
self.worker = None
def _download_image(self, url):
import requests
response = requests.get(url, timeout=self.settings.get('image_download_timeout', 30))
response.raise_for_status()
directory = Path(self.settings.get('image_cache_dir', './data/design_images'))
directory.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=directory, suffix='.jpg', delete=False) as f:
f.write(response.content)
return f.name
def _remove(self, design_id):
with self.index.lock:
self.db_manager.remove(design_id)
self.index.remove(design_id)
def _log_failure(self, stage, design_id, error):
# Request errors may include signed URLs or credentials; log only a bounded diagnostic.
message = re.sub(r'https?://\S+', '<url>', str(error))
message = re.sub(r'''b(['"]).*?\1''', '<bytes>', message)
for section, key in (('mysql', 'password'), ('jwt', 'secret')):
secret = self.config.get(section, {}).get(key)
if secret:
message = message.replace(str(secret), '<redacted>')
message = re.sub(r'(?i)(password|token|secret|authorization)\s*[=:]\s*\S+',
r'\1=<redacted>', message)
logger.warning('%s failed for design %s: %s: %s; retaining previous record',
stage, design_id, type(error).__name__, message.replace('\n', ' ')[:400])
def _process_design(self, row):
design_id = int(row['id'])
eps_id = row.get('eps_id')
if eps_id is None:
logger.warning('Skipping design %s with NULL eps_id', design_id)
return False
if eps_id not in self.eps_ids:
return False
url = primary_url(row.get('images'))
if row.get('delete_key') not in (None, '0') or not url:
self._remove(design_id)
return True
existing = self.db_manager.get_features([design_id]).get(design_id)
if existing and existing['image_url'] == url:
if existing['eps_id'] != eps_id or existing['design_no'] != row.get('design_no'):
with self.index.lock:
self.db_manager.update_metadata(design_id, eps_id, row.get('design_no'))
self.index.upsert(design_id, eps_id, existing['cnn_vector'], existing['feat_version'])
return True
path = None
stage = 'download'
try:
path = self.downloader(url)
if not path:
raise RuntimeError('Downloader returned no file')
stage = 'feature extraction'
extractor = self.feature_extractor
extract = getattr(extractor, 'extract_index_features', extractor.extract_all_features)
features = extract(path)
if not features or features.get('cnn_vector') is None:
raise ValueError('Extractor returned no CNN vector')
vector = np.asarray(features['cnn_vector'], dtype=np.float32)
norm = np.linalg.norm(vector)
if vector.shape != (self.index.dimension,) or not np.isfinite(norm) or norm == 0:
raise ValueError('Invalid CNN vector')
stage = 'feature persistence'
self.version += 1
with self.index.lock:
self.db_manager.upsert(design_id, eps_id, row.get('design_no'), url,
features, self.version, row.get('utc_modified'))
self.index.upsert(design_id, eps_id, vector, self.version)
return True
except Exception as error:
self._log_failure(stage, design_id, error)
return False
finally:
# Only the built-in downloader transfers ownership of a temporary file.
if path and self.downloader == self._download_image:
Path(path).unlink(missing_ok=True)
def _sync(self):
state = self.db_manager.state()
cursor = as_datetime(state['cursor_modified']) if state['cursor_modified'] else datetime(1970, 1, 1)
modified = cursor - timedelta(seconds=self.settings.get('overlap_seconds', 120))
last_id = 0
count = success = 0
size = self.settings.get('batch_size', 500)
if size < 1:
raise ValueError('batch_size must be positive')
while True:
rows = self.source.fetch_batch(self.eps_ids, modified, last_id, size)
if not rows:
break
for row in rows:
success += int(self._process_design(row))
count += 1
cursor = max(cursor, as_datetime(row['utc_modified']))
modified, last_id = as_datetime(rows[-1]['utc_modified']), int(rows[-1]['id'])
self.db_manager.set_state(cursor_modified=cursor.isoformat(), last_sync_at=datetime.now().isoformat())
if count:
logger.info('Sync round processed=%s succeeded=%s failed=%s', count, success, count - success)
return {'total_processed': count, 'total_success': success, 'total_failed': count - success}
def _reconcile(self):
# Materialize and validate the entire source before any mutation/removal.
rows = list(self.source.fetch_active(self.eps_ids))
if not rows and self.db_manager.health_stats()['total_images']:
raise RuntimeError('Empty reconciliation source with non-empty local store; retaining index')
active = {int(row['id']): row for row in rows
if row.get('eps_id') in self.eps_ids and
row.get('delete_key') in (None, '0') and primary_url(row.get('images'))}
for row in active.values():
self._process_design(row)
for design_id in self.db_manager.metadata().keys() - active.keys():
self._remove(design_id)
self.db_manager.set_state(last_reconcile_at=datetime.now().isoformat())
return {'active_count': len(active)}
def _run_locked(self, action):
if not self.mutex.acquire(blocking=False):
return {'status': 'in_progress'}
try:
return action()
finally:
self.mutex.release()
def sync_once(self):
return self._run_locked(self._sync)
def reconcile(self):
return self._run_locked(self._reconcile)
def rebuild_status(self):
with self.status_lock:
return dict(self._status)
def start_rebuild(self):
if not self.mutex.acquire(blocking=False):
return {'status': 'in_progress'}
with self.status_lock:
self._status = {'status': 'in_progress'}
def run():
try:
self.db_manager.set_state(cursor_modified=None)
result = self._sync()
self._reconcile()
status = {'status': 'completed', 'result': result}
except Exception:
logger.exception('Rebuild failed')
status = {'status': 'failed'}
finally:
with self.status_lock:
self._status = status
self.mutex.release()
self.worker = threading.Thread(target=run, daemon=True)
try:
self.worker.start()
except Exception:
self.mutex.release()
with self.status_lock:
self._status = {'status': 'failed'}
raise
return {'status': 'started'}
def run_forever(self):
while not self.stop_event.is_set():
try:
self.sync_once()
now = datetime.now()
last = self.db_manager.state()['last_reconcile_at']
if now.hour >= self.settings.get('reconcile_hour', 0) and (not last or as_datetime(last).date() < now.date()):
self.reconcile()
except Exception:
logger.exception('Sync round failed')
self.stop_event.wait(self.settings.get('interval_seconds', 60))