merge
Browse files- extract_weights.py +60 -0
extract_weights.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Extract weights from .keras file without deserializing the model architecture.
|
| 3 |
+
.keras files are ZIP archives containing metadata and weights.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import zipfile
|
| 7 |
+
import json
|
| 8 |
+
import h5py
|
| 9 |
+
import os
|
| 10 |
+
import shutil
|
| 11 |
+
|
| 12 |
+
KERAS_PATH = "./models/aging_score_autoencoder.keras"
|
| 13 |
+
WEIGHTS_PATH = "./models/aging_score_autoencoder.weights.h5"
|
| 14 |
+
BACKUP_PATH = "./models/aging_score_autoencoder.keras.bak"
|
| 15 |
+
|
| 16 |
+
print(f"Extracting weights from {KERAS_PATH}...")
|
| 17 |
+
|
| 18 |
+
if not os.path.exists(KERAS_PATH):
|
| 19 |
+
print(f"ERROR: {KERAS_PATH} not found!")
|
| 20 |
+
exit(1)
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
# Backup original
|
| 24 |
+
if not os.path.exists(BACKUP_PATH):
|
| 25 |
+
shutil.copy(KERAS_PATH, BACKUP_PATH)
|
| 26 |
+
print(f"Backed up to {BACKUP_PATH}")
|
| 27 |
+
|
| 28 |
+
# Extract weights from .keras ZIP
|
| 29 |
+
with zipfile.ZipFile(KERAS_PATH, 'r') as zf:
|
| 30 |
+
# List contents
|
| 31 |
+
files = zf.namelist()
|
| 32 |
+
print(f"Files in {KERAS_PATH}: {files}")
|
| 33 |
+
|
| 34 |
+
# Find the weights file (usually 'model.weights.h5')
|
| 35 |
+
weights_file = None
|
| 36 |
+
for f in files:
|
| 37 |
+
if 'weights' in f.lower() and f.endswith('.h5'):
|
| 38 |
+
weights_file = f
|
| 39 |
+
break
|
| 40 |
+
|
| 41 |
+
if weights_file:
|
| 42 |
+
print(f"Found weights file: {weights_file}")
|
| 43 |
+
# Extract to temp location
|
| 44 |
+
with zf.open(weights_file) as src:
|
| 45 |
+
with open(WEIGHTS_PATH, 'wb') as dst:
|
| 46 |
+
dst.write(src.read())
|
| 47 |
+
print(f"Extracted weights to {WEIGHTS_PATH}")
|
| 48 |
+
else:
|
| 49 |
+
print("ERROR: No .h5 weights file found in archive!")
|
| 50 |
+
print(f"Contents: {files}")
|
| 51 |
+
exit(1)
|
| 52 |
+
|
| 53 |
+
print("\nSuccess! Now update app.py to use the weights file.")
|
| 54 |
+
print(f"Change MODEL_PATH to: {WEIGHTS_PATH}")
|
| 55 |
+
|
| 56 |
+
except Exception as e:
|
| 57 |
+
print(f"ERROR: {e}")
|
| 58 |
+
import traceback
|
| 59 |
+
traceback.print_exc()
|
| 60 |
+
exit(1)
|