File size: 23,128 Bytes
38ba4c0 | 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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 | """Validate and import the bundled 115-feature gallery into PostgreSQL.
Run --validate-only first. Normal execution prompts for a password and uses
one transaction. Existing matching records are skipped; conflicting records
are rejected rather than silently overwritten. No schema is created here.
"""
import argparse
import csv
from dataclasses import dataclass
from getpass import getpass
import hashlib
import json
import os
from pathlib import Path
import joblib
import numpy as np
BASE=Path(__file__).resolve().parent
PROJECT=BASE.parent
META=['file_id','image_path','label','bw_image_path','specimen_group','feature_version']
# Filled from the validated extraction artifacts when the bundle is prepared.
# This keeps the requested bundle self-contained without extra metadata files.
BUNDLE_SPEC = {'expected_rows': 6029,
'extraction_version': 'leafsnap_rgb720_bw720_v115_v1',
'normalization_version': 'leafsnap_rgb720_bw720_v115_standardscaler_v1',
'feature_names': ['eccentricity',
'aspect_ratio',
'elongation',
'solidity',
'stochastic_convexity',
'isoperimetric_factor',
'maximal_indentation_depth',
'lobedness',
'intensity_mean',
'intensity_std',
'smoothness',
'third_moment',
'uniformity',
'entropy',
'lbp_uniform_8_1_bin_0',
'lbp_uniform_8_1_bin_1',
'lbp_uniform_8_1_bin_2',
'lbp_uniform_8_1_bin_3',
'lbp_uniform_8_1_bin_4',
'lbp_uniform_8_1_bin_5',
'lbp_uniform_8_1_bin_6',
'lbp_uniform_8_1_bin_7',
'lbp_uniform_8_1_bin_8',
'lbp_uniform_8_1_bin_9',
'glcm_d1_contrast',
'glcm_d1_dissimilarity',
'glcm_d1_homogeneity',
'glcm_d1_ASM',
'glcm_d1_correlation',
'glcm_d3_contrast',
'glcm_d3_dissimilarity',
'glcm_d3_homogeneity',
'glcm_d3_ASM',
'glcm_d3_correlation',
'fourier_radius_h01',
'fourier_radius_h02',
'fourier_radius_h03',
'fourier_radius_h04',
'fourier_radius_h05',
'fourier_radius_h06',
'fourier_radius_h07',
'fourier_radius_h08',
'fourier_radius_h09',
'fourier_radius_h10',
'fourier_radius_h11',
'fourier_radius_h12',
'fourier_radius_h13',
'fourier_radius_h14',
'fourier_radius_h15',
'fourier_radius_h16',
'curvature_s2_mean_abs',
'curvature_s2_std_abs',
'curvature_s2_median_abs',
'curvature_s2_q90_abs',
'curvature_s2_q99_abs',
'curvature_s2_concave_fraction',
'curvature_s2_sign_change_rate',
'curvature_s2_bending_energy',
'curvature_s6_mean_abs',
'curvature_s6_std_abs',
'curvature_s6_median_abs',
'curvature_s6_q90_abs',
'curvature_s6_q99_abs',
'curvature_s6_concave_fraction',
'curvature_s6_sign_change_rate',
'curvature_s6_bending_energy',
'serration_peak_count',
'serration_prom_mean',
'serration_prom_std',
'serration_prom_max',
'serration_width_mean',
'serration_spacing_cv',
'serration_residual_std',
'serration_length_excess',
'hsv_H_bin_00',
'hsv_H_bin_01',
'hsv_H_bin_02',
'hsv_H_bin_03',
'hsv_H_bin_04',
'hsv_H_bin_05',
'hsv_H_bin_06',
'hsv_H_bin_07',
'hsv_H_bin_08',
'hsv_H_bin_09',
'hsv_H_bin_10',
'hsv_H_bin_11',
'hsv_H_bin_12',
'hsv_H_bin_13',
'hsv_H_bin_14',
'hsv_H_bin_15',
'hsv_S_bin_00',
'hsv_S_bin_01',
'hsv_S_bin_02',
'hsv_S_bin_03',
'hsv_S_bin_04',
'hsv_S_bin_05',
'hsv_S_bin_06',
'hsv_S_bin_07',
'hsv_V_bin_00',
'hsv_V_bin_01',
'hsv_V_bin_02',
'hsv_V_bin_03',
'hsv_V_bin_04',
'hsv_V_bin_05',
'hsv_V_bin_06',
'hsv_V_bin_07',
'lab_L_mean',
'lab_L_std',
'lab_L_skewness',
'lab_a_mean',
'lab_a_std',
'lab_a_skewness',
'lab_b_mean',
'lab_b_std',
'lab_b_skewness'],
'extraction_config': {'feature_version': 'leafsnap_rgb720_bw720_v115_v1',
'vector_dimensions': 115,
'feature_order_sha256': '12017e209abd1642a65f2caced1454c1d50360dd0db7a08bce32eb21daaebb0f',
'raw_features': True,
'StandardScaler_applied': False,
'input_RGB': 'data1/RGB_test',
'input_BW': 'data1/BW',
'expected_size': [720, 960],
'alpha_must_equal_BW': True,
'group_sizes': {'shape': 8,
'grayscale': 6,
'LBP': 10,
'GLCM': 10,
'Fourier': 16,
'Curvature': 16,
'Serration': 8,
'HSV': 32,
'Lab': 9},
'shape': {'stochastic_samples': 2000,
'seed': 'SHA256(species_folder/filename), first 8 bytes little '
'endian'},
'grayscale': {'bins': 256,
'thumbnail_max': [512, 512],
'foreground': 'alpha>127 with existing pink exclusion and '
'clean_mask'},
'LBP_GLCM': {'longest_leaf_side': 384,
'lbp_P': 8,
'lbp_R': 1,
'lbp_method': 'uniform',
'gray_levels': 32,
'distances': [1, 3],
'angles_degrees': [0, 45, 90, 135],
'mask_erosion_pixels': 4,
'GLCM': 'symmetric, normalized, equal mean over directions; '
'both endpoints inside eroded mask'},
'contour_color': {'contour_samples': 512,
'mask_longest_side': 512,
'fourier': '16 non-DC magnitudes of centroid-distance '
'signature / mean radius; not elliptic Fourier '
'descriptors',
'curvature_sigmas': [2, 6],
'curvature_coordinates': 'CCW Cartesian contour, '
'perimeter normalized to 1',
'serration': {'fine_sigma': 1.5,
'coarse_sigma': 10,
'peak_prominence': 0.003,
'peak_distance': 6,
'peak_width': [1, 32]},
'color_leaf_longest_side': 384,
'color_mask_erosion': 4,
'color_resampling': 'RGBA premultiplied-alpha Lanczos',
'HSV_bins': [16, 8, 8],
'hue_histogram': 'saturation-weighted; all-zero if '
'saturation sum is zero',
'Lab': 'D65/2-degree sRGB conversion; mean, std, '
'standardized skewness on each channel; no white '
'balancing'},
'code_sha256': {'extract_leaf_features.py': 'da9b0864ac8fea38e079ef98f536459901d53bb7af62ed61b9bebf5cb79ea8f7',
'experiment_texture_features.py': 'cd7fcd3d8bdbfda71cdbda9f903d159e7a73766c3ed483df61554b2a54325634',
'experiment_contour_color.py': '63c753c4792aede473cd902ee8df546467f65e42da5bfea2833233b9bc72fffb',
'leaf_descriptor_v115.py': '0163cc0f58b69ed6a95cb5fdbdb4315ae6e8985e8e0f5645242effce59b7cc99',
'extract_final_v115.py': '15eec44ab28bc3bccee18273fa8649d9ff0f96ceda2d963280d364258667233c'},
'versions': {'python': '3.12.10',
'numpy': '2.5.5',
'Pillow': '13.0.0',
'scipy': '1.18.1',
'skimage': '0.26.0',
'sklearn': '1.9.1'}},
'raw_sha256': 'd5f3593bc94072a337d2e1e87c1a89f559b85870cf4517f6e495936ecb61328d',
'standardized_sha256': '1b25918136c982c38e12b4ceaf2d6f4f58ef49a6dca8b81cf49a0ecce7097083',
'scaler_sha256': '5008dcd7363284ae1c70d76959f280c031166a990f7b91edaa3e79f0311ec46e'}
@dataclass
class Bundle:
rows: list
names: list
raw: np.ndarray
normalized: np.ndarray
mean: np.ndarray
scale: np.ndarray
source_hash: str
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def read_table(path):
with path.open(encoding='utf-8-sig',newline='') as f:
reader=csv.DictReader(f);return reader.fieldnames,list(reader)
def validate_bundle(base=BASE,spec=None):
spec=BUNDLE_SPEC if spec is None else spec
if not spec:raise ValueError('Bundle metadata is missing')
raw_path=base/'data/features_115.csv'
z_path=base/'data/features_115_standardized.csv'
scaler_path=base/'scaler/scaler_115.joblib'
for key,path in [('raw_sha256',raw_path),('standardized_sha256',z_path),('scaler_sha256',scaler_path)]:
if not path.is_file():raise FileNotFoundError(path)
if sha(path)!=spec[key]:raise ValueError('Bundle file changed: '+str(path))
names=spec['feature_names']
if len(names)!=115 or len(set(names))!=115 or not all(isinstance(n,str) and n.strip() for n in names):
raise ValueError('Expected exactly 115 unique feature names')
header,rows=read_table(raw_path);z_header,z_rows=read_table(z_path)
if header!=META+names or z_header!=header:raise ValueError('CSV columns/order differ from the extraction schema')
if not rows or len(rows)!=len(z_rows) or len(rows)!=spec['expected_rows']:
raise ValueError('CSV row counts differ from the frozen bundle')
ids=[]
for row,zrow in zip(rows,z_rows):
if any(row[n]!=zrow[n] for n in META):raise ValueError('Raw/scaled metadata or row order differs')
if any(not row[n].strip() for n in META):raise ValueError('Empty required metadata')
if row['feature_version']!=spec['extraction_version']:raise ValueError('Mixed extraction versions')
image_id=int(row['file_id'])
if not 0<image_id<2**63:raise ValueError('image_id does not fit positive BIGINT')
ids.append(image_id)
if len(row['label'])>255:raise ValueError('Species name exceeds VARCHAR(255)')
if len(set(ids))!=len(ids):raise ValueError('Duplicate image IDs')
raw=np.array([[float(r[n]) for n in names] for r in rows],dtype=np.float64)
normalized=np.array([[float(r[n]) for n in names] for r in z_rows],dtype=np.float64)
if not np.isfinite(raw).all() or not np.isfinite(normalized).all():raise ValueError('NaN or infinity in vectors')
# Load only the trusted scaler copied from the project's own extraction.
scaler=joblib.load(scaler_path)
mean=np.asarray(scaler.mean_,dtype=np.float64);scale=np.asarray(scaler.scale_,dtype=np.float64)
if getattr(scaler,'n_features_in_',None)!=115 or not scaler.with_mean or not scaler.with_std:
raise ValueError('Expected a fitted StandardScaler with 115 columns')
if mean.shape!=(115,) or scale.shape!=(115,) or not np.isfinite(mean).all() or not np.isfinite(scale).all() or np.any(scale<=0):
raise ValueError('Invalid scaler parameters')
if not np.allclose(scaler.transform(raw),normalized,rtol=1e-12,atol=1e-12):
raise ValueError('Scaled CSV does not match raw CSV and scaler')
return Bundle(rows,names,raw,normalized,mean,scale,spec['raw_sha256'])
def expected_image(row,species_id):
return (int(row['file_id']),species_id,row['image_path'],row['bw_image_path'],720,960,row['specimen_group'])
def array_value(value):
if hasattr(value,'to_numpy'):value=value.to_numpy()
return np.asarray(value)
def import_bundle(conn,bundle,spec=None):
"""Caller owns transaction/connection; exceptions must trigger rollback."""
from psycopg.types.json import Jsonb
from pgvector import Vector
from pgvector.psycopg import register_vector
spec=BUNDLE_SPEC if spec is None else spec
required=['species','leaf_images','feature_versions','leaf_features']
for table in required:
if conn.execute('SELECT to_regclass(%s)',('public.'+table,)).fetchone()[0] is None:
raise RuntimeError('Missing table public.'+table+'; run src/database/schema.sql first')
if conn.execute("SELECT 1 FROM pg_extension WHERE extname='vector'").fetchone() is None:
raise RuntimeError('pgvector extension is not enabled in this database')
register_vector(conn)
# Serialize instances of this importer; never truncate/delete existing data.
conn.execute("SELECT pg_advisory_xact_lock(hashtext('leaf-database/import_features/v115'))")
config={'descriptor':spec['extraction_config'],'normalization':{
'method':'standard_scaler','version':spec['normalization_version'],
'fit_scope':'all gallery images','n_samples':len(bundle.rows),
'standardized_csv_sha256':spec['standardized_sha256'],'scaler_file_sha256':spec['scaler_sha256']}}
version_name=spec['normalization_version']
existing=conn.execute('''SELECT version_id,feature_count,feature_names,extraction_config,
normalization_method,scaler_mean,scaler_scale,source_csv_sha256
FROM public.feature_versions WHERE version_name=%s''',(version_name,)).fetchone()
if existing:
version_id,count,names,old_config,method,mean,scale,source_hash=existing
if not (count==115 and names==bundle.names and old_config==config and method=='standard_scaler'
and np.array_equal(mean,bundle.mean) and np.array_equal(scale,bundle.scale)
and source_hash.lower()==bundle.source_hash.lower()):
raise ValueError('Existing feature version conflicts with this CSV/scaler; use a new version')
else:
version_id=conn.execute('''INSERT INTO public.feature_versions
(version_name,feature_count,feature_names,extraction_config,normalization_method,
scaler_mean,scaler_scale,source_csv_sha256)
VALUES (%s,115,%s,%s,'standard_scaler',%s,%s,%s) RETURNING version_id''',
(version_name,Jsonb(bundle.names),Jsonb(config),bundle.mean.tolist(),bundle.scale.tolist(),bundle.source_hash)).fetchone()[0]
labels=sorted({r['label'] for r in bundle.rows})
with conn.cursor() as cur:
cur.executemany('''INSERT INTO public.species(scientific_name) VALUES (%s)
ON CONFLICT(scientific_name) DO NOTHING''',[(label,) for label in labels])
species_ids=dict(conn.execute('''SELECT scientific_name,species_id FROM public.species
WHERE scientific_name=ANY(%s::text[])''',(labels,)).fetchall())
ids=[int(r['file_id']) for r in bundle.rows]
existing_images={r[0]:r for r in conn.execute('''SELECT image_id,species_id,rgb_path,bw_path,width,height,specimen_group
FROM public.leaf_images WHERE image_id=ANY(%s::bigint[])''',(ids,)).fetchall()}
new_images=[]
for row in bundle.rows:
expected=expected_image(row,species_ids[row['label']]);old=existing_images.get(expected[0])
if old is not None and tuple(old)!=expected:
raise ValueError(f'Existing image metadata conflicts for image_id={expected[0]}; no overwrite performed')
if old is None:new_images.append(expected)
with conn.cursor() as cur:
cur.executemany('''INSERT INTO public.leaf_images
(image_id,species_id,rgb_path,bw_path,width,height,specimen_group)
VALUES (%s,%s,%s,%s,%s,%s,%s)''',new_images)
existing_features={r[0]:r[1:] for r in conn.execute('''SELECT image_id,raw_features,normalized_features
FROM public.leaf_features WHERE version_id=%s AND image_id=ANY(%s::bigint[])''',(version_id,ids)).fetchall()}
inserted=0;skipped=0
with conn.cursor() as cur:
for start in range(0,len(bundle.rows),256):
batch=[]
for i in range(start,min(start+256,len(bundle.rows))):
image_id=ids[i];old=existing_features.get(image_id)
if old is not None:
# pgvector VECTOR stores float32, while raw arrays retain float64.
if not (np.array_equal(np.asarray(old[0],dtype=np.float64),bundle.raw[i])
and np.array_equal(array_value(old[1]).astype(np.float32),bundle.normalized[i].astype(np.float32))):
raise ValueError(f'Existing feature vector conflicts for image_id={image_id}; no overwrite performed')
skipped+=1
else:batch.append((image_id,version_id,bundle.raw[i].tolist(),Vector(bundle.normalized[i].astype(np.float32))))
cur.executemany('''INSERT INTO public.leaf_features
(image_id,version_id,raw_features,normalized_features) VALUES (%s,%s,%s,%s)''',batch)
inserted+=len(batch)
print(f'Checked {min(start+256,len(bundle.rows))}/{len(bundle.rows)}; new vectors={inserted}; matching existing={skipped}',flush=True)
present=conn.execute('''SELECT COUNT(*) FROM public.leaf_features
WHERE version_id=%s AND image_id=ANY(%s::bigint[])''',(version_id,ids)).fetchone()[0]
if present!=len(bundle.rows):raise RuntimeError('Imported vector count differs from bundle')
# Round-trip every row before commit to catch ordering/adaptation mistakes.
saved={r[0]:r[1:] for r in conn.execute('''SELECT image_id,raw_features,normalized_features
FROM public.leaf_features WHERE version_id=%s AND image_id=ANY(%s::bigint[])''',(version_id,ids)).fetchall()}
for i,image_id in enumerate(ids):
if not (np.array_equal(saved[image_id][0],bundle.raw[i]) and
np.array_equal(array_value(saved[image_id][1]).astype(np.float32),bundle.normalized[i].astype(np.float32))):
raise RuntimeError('Database round-trip mismatch for '+str(image_id))
return {'version_id':version_id,'version_name':version_name,'bundle_images':len(bundle.rows),
'bundle_species':len(labels),'new_images':len(new_images),'new_feature_rows':inserted,
'matching_existing_feature_rows':skipped,'verified_feature_rows':present,'feature_dimensions':115,
'database_vectors_round_trip_verified':True,'raw_CSV_sha256':bundle.source_hash,
'normalized_vector_storage':'pgvector float32','default_retrieval_distance':'Manhattan; choose with SQL <+>'}
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--validate-only',action='store_true',help='Check files/scaler without any database connection')
parser.add_argument('--host',default=os.getenv('PGHOST','localhost'))
parser.add_argument('--port',type=int,default=int(os.getenv('PGPORT','5432')))
parser.add_argument('--database',default=os.getenv('PGDATABASE','leaf_db'))
parser.add_argument('--user',default=os.getenv('PGUSER','postgres'))
args=parser.parse_args()
bundle=validate_bundle()
validation={'status':'validated','images':len(bundle.rows),'species':len({r['label'] for r in bundle.rows}),
'feature_dimensions':len(bundle.names),'CSV_and_scaler_consistent':True,
'normalization_version':BUNDLE_SPEC['normalization_version'],'database_connected':False}
print(json.dumps(validation),flush=True)
folder=PROJECT/'outputs/leaf_database_import';folder.mkdir(parents=True,exist_ok=True)
(folder/'validation.json').write_text(json.dumps(validation,indent=2),encoding='utf-8')
if args.validate_only:return
try:import psycopg
except ImportError:raise SystemExit('Install dependencies: python -m pip install "psycopg[binary]" pgvector')
password=os.getenv('PGPASSWORD')
if password is None:password=getpass('PostgreSQL password: ')
# All writes are committed together on successful context exit; rolled back on failure.
with psycopg.connect(host=args.host,port=args.port,dbname=args.database,user=args.user,
password=password,connect_timeout=10,application_name='leaf_v115_import') as conn:
result=import_bundle(conn,bundle)
result.update(status='committed',database=args.database)
(folder/'last_import.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
print(json.dumps(result),flush=True)
if __name__=='__main__':main()
|