Akash8150 commited on
Commit ·
b17d851
1
Parent(s): cc9042f
Fix: rebuild model architecture and load weights only to bypass Keras deserialization
Browse filesFiles changed (2)
- app.py+71-81
- requirements-hf.txt+2-4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748493 unmodified lines5354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""Flask Web Application for Image Denoising"""import osimport sysimport numpy as npimport json# Use tf-keras (Keras 2 compatibility layer) to load old .h5 modelsos.environ["TF_USE_LEGACY_KERAS"] = "1"from flask import Flask, render_template, request, jsonifyimport tf_keras as kerasfrom tf_keras.models import load_modelfrom PIL import Imageimport ioimport base64# Add src directory to pathsys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))app = Flask(__name__)app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size# Load the trained modelMODEL_PATH = 'best_autoencoder_model.h5'MODEL_INFO_PATH = 'model_info.json'model = Nonemodel_info = Nonedef load_trained_model():"""Load the trained autoencoder model"""global modelif os.path.exists(MODEL_PATH):model = load_model(MODEL_PATH)print(f"Model loaded from {MODEL_PATH}")else:print(f"Warning: Model file {MODEL_PATH} not found!")def load_model_info():"""Load model information from JSON file"""global model_infoif os.path.exists(MODEL_INFO_PATH):with open(MODEL_INFO_PATH, 'r') as f:model_info = json.load(f)print(f"Model info loaded from {MODEL_INFO_PATH}")else:model_info = {"model_name": "CNN Autoencoder",3 unmodified lines"test_loss": "N/A"}def preprocess_image(image):"""Preprocess uploaded image for model"""img = image.convert('L')img = img.resize((28, 28))img_array = np.array(img) / 255.0img_array = img_array.reshape(1, 28, 28, 1)return img_arraydef array_to_base64(img_array):"""Convert numpy array to base64 string for display"""img_array = img_array.squeeze()img_array = (img_array * 255).astype(np.uint8)img = Image.fromarray(img_array, mode='L')buffer = io.BytesIO()img.save(buffer, format='PNG')img_str = base64.b64encode(buffer.getvalue()).decode()return f"data:image/png;base64,{img_str}"# Load model and info at module level so it works with Dockerload_trained_model()load_model_info()@app.route('/')def index():"""Render main page"""return render_template('index.html', model_info=model_info)@app.route('/api/model-info', methods=['GET'])def get_model_info():"""Return model information"""if model_info:return jsonify(model_info)return jsonify({'error': 'Model info not available'}), 404@app.route('/denoise', methods=['POST'])def denoise():"""Handle image denoising request"""if model is None:return jsonify({'error': 'Model not loaded'}), 500if 'image' not in request.files:return jsonify({'error': 'No image uploaded'}), 400file = request.files['image']if file.filename == '':return jsonify({'error': 'No image selected'}), 400try:image = Image.open(file.stream)processed_img = preprocess_image(image)denoised_img = model.predict(processed_img, verbose=0)original_b64 = array_to_base64(processed_img)denoised_b64 = array_to_base64(denoised_img)return jsonify({'original': original_b64,'denoised': denoised_b64})except Exception as e:return jsonify({'error': str(e)}), 500if __name__ == '__main__':port = int(os.environ.get('PORT', 7860))app.run(debug=False, host='0.0.0.0', port=port)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152533 unmodified lines57585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import os, sys, numpy as np, json, io, base64os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"from flask import Flask, render_template, request, jsonifyfrom PIL import Imagesys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "src"))app = Flask(__name__)app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024MODEL_PATH = "best_autoencoder_model.h5"MODEL_INFO_PATH = "model_info.json"model = Nonemodel_info = Nonedef load_trained_model():global modelif not os.path.exists(MODEL_PATH):print(f"Warning: {MODEL_PATH} not found")returnimport tensorflow as tffrom tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2Dtry:# Rebuild the exact same architecture, then load weights only.# This bypasses Keras version deserialization issues with InputLayer config.inp = Input(shape=(28, 28, 1))x = Conv2D(32, (3, 3), activation="relu", padding="same")(inp)x = MaxPooling2D((2, 2), padding="same")(x)x = Conv2D(16, (3, 3), activation="relu", padding="same")(x)enc = MaxPooling2D((2, 2), padding="same")(x)x = Conv2D(16, (3, 3), activation="relu", padding="same")(enc)x = UpSampling2D((2, 2))(x)x = Conv2D(32, (3, 3), activation="relu", padding="same")(x)x = UpSampling2D((2, 2))(x)out = Conv2D(1, (3, 3), activation="sigmoid", padding="same")(x)rebuilt = Model(inp, out)rebuilt.load_weights(MODEL_PATH)model = rebuiltprint("Model loaded via weights-only approach")except Exception as e:print(f"Model load failed: {e}")def load_model_info():global model_infoif os.path.exists(MODEL_INFO_PATH):with open(MODEL_INFO_PATH) as f:model_info = json.load(f)else:model_info = {"model_name": "CNN Autoencoder",3 unmodified lines"test_loss": "N/A"}def preprocess_image(image):img = image.convert("L").resize((28, 28))arr = np.array(img) / 255.0return arr.reshape(1, 28, 28, 1)def array_to_base64(arr):arr = arr.squeeze()arr = (arr * 255).astype(np.uint8)img = Image.fromarray(arr, mode="L")buf = io.BytesIO()img.save(buf, format="PNG")return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()load_trained_model()load_model_info()@app.route("/")def index():return render_template("index.html", model_info=model_info)@app.route("/api/model-info")def get_model_info():if model_info:return jsonify(model_info)return jsonify({"error": "not available"}), 404@app.route("/denoise", methods=["POST"])def denoise():if model is None:return jsonify({"error": "Model not loaded"}), 500if "image" not in request.files:return jsonify({"error": "No image uploaded"}), 400file = request.files["image"]if not file.filename:return jsonify({"error": "No image selected"}), 400try:image = Image.open(file.stream)proc = preprocess_image(image)denoised = model.predict(proc, verbose=0)return jsonify({"original": array_to_base64(proc), "denoised": array_to_base64(denoised)})except Exception as e:return jsonify({"error": str(e)}), 500if __name__ == "__main__":port = int(os.environ.get("PORT", 7860))app.run(debug=False, host="0.0.0.0", port=port)
1234567# Inference-only requirements for Hugging Face deployment# tf-keras provides Keras 2.x compatibility for loading old .h5 models with TF 2.16+tensorflow-cpu==2.16.1tf-keras==2.16.0numpy==1.26.4flask==3.0.3pillow==10.3.012345# Inference-only requirements for Hugging Face deploymenttensorflow-cpu==2.16.1numpy==1.26.4flask==3.0.3pillow==10.3.0
app.py+71-81
requirements-hf.txt+2-4