Akash8150 commited on
Commit Β·
1010bf9
1
Parent(s): b17d851
Add sample images with one-click denoising UI
Browse filesFiles changed (15)
- Dockerfile+1
- app.py+43-2
- static/script.js+80-59
- static/style.css+84
- templates/index.html+19-16
- test_images/noisy_digit_2_8.pngAdded
- test_images/noisy_digit_3_1.pngAdded
- test_images/noisy_digit_3_4.pngAdded
- test_images/noisy_digit_4_2.pngAdded
- test_images/noisy_digit_4_6.pngAdded
- test_images/noisy_digit_5_10.pngAdded
- test_images/noisy_digit_5_5.pngAdded
- test_images/noisy_digit_5_7.pngAdded
- test_images/noisy_digit_5_9.pngAdded
- test_images/noisy_digit_8_3.pngAdded
28 unmodified lines29303132333428 unmodified linesCOPY src/ ./src/COPY static/ ./static/COPY templates/ ./templates/# Hugging Face Spaces runs on port 7860EXPOSE 786028 unmodified lines2930313233343528 unmodified linesCOPY src/ ./src/COPY static/ ./static/COPY templates/ ./templates/COPY test_images/ ./test_images/# Hugging Face Spaces runs on port 7860EXPOSE 7860
9 unmodified lines1011121314157 unmodified lines232425262728293058 unmodified lines8990919293949 unmodified linesMODEL_PATH = "best_autoencoder_model.h5"MODEL_INFO_PATH = "model_info.json"model = Nonemodel_info = None7 unmodified linesfrom 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)58 unmodified linesreturn jsonify({"error": "not available"}), 404@app.route("/denoise", methods=["POST"])def denoise():if model is None:9 unmodified lines101112131415167 unmodified lines24252627282958 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341359 unmodified linesMODEL_PATH = "best_autoencoder_model.h5"MODEL_INFO_PATH = "model_info.json"SAMPLES_DIR = "test_images"model = Nonemodel_info = None7 unmodified linesfrom tensorflow.keras.models import Modelfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2Dtry:inp = Input(shape=(28, 28, 1))x = Conv2D(32, (3, 3), activation="relu", padding="same")(inp)x = MaxPooling2D((2, 2), padding="same")(x)58 unmodified linesreturn jsonify({"error": "not available"}), 404@app.route("/api/samples")def get_samples():"""Return list of sample images as base64 thumbnails"""samples = []if os.path.exists(SAMPLES_DIR):for fname in sorted(os.listdir(SAMPLES_DIR)):if fname.lower().endswith((".png", ".jpg", ".jpeg")):fpath = os.path.join(SAMPLES_DIR, fname)with open(fpath, "rb") as f:b64 = base64.b64encode(f.read()).decode()# Parse label from filename e.g. noisy_digit_2_8.png -> Digit 2parts = fname.replace(".png", "").split("_")label = f"Digit {parts[2]}" if len(parts) >= 3 else fnamesamples.append({"filename": fname,"label": label,"thumbnail": f"data:image/png;base64,{b64}"})return jsonify(samples)@app.route("/api/denoise-sample", methods=["POST"])def denoise_sample():"""Denoise a built-in sample image by filename"""if model is None:return jsonify({"error": "Model not loaded"}), 500data = request.get_json()filename = data.get("filename", "")# Sanitize: only allow filenames, no path traversalfilename = os.path.basename(filename)fpath = os.path.join(SAMPLES_DIR, filename)if not os.path.exists(fpath):return jsonify({"error": "Sample not found"}), 404try:image = Image.open(fpath)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)}), 500@app.route("/denoise", methods=["POST"])def denoise():if model is None:
6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171186 unmodified linesconst error = document.getElementById('error');const originalImg = document.getElementById('originalImg');const denoisedImg = document.getElementById('denoisedImg');let selectedFile = null;// Click to uploaduploadBox.addEventListener('click', () => {imageInput.click();});// File selectionimageInput.addEventListener('change', (e) => {handleFile(e.target.files[0]);});// Drag and dropuploadBox.addEventListener('dragover', (e) => {e.preventDefault();uploadBox.classList.add('dragover');});uploadBox.addEventListener('dragleave', () => {uploadBox.classList.remove('dragover');});uploadBox.addEventListener('drop', (e) => {e.preventDefault();uploadBox.classList.remove('dragover');handleFile(e.dataTransfer.files[0]);});// Handle file selectionfunction handleFile(file) {if (!file) return;if (!file.type.startsWith('image/')) {showError('Please upload an image file');return;}selectedFile = file;denoiseBtn.disabled = false;// Update upload box to show file nameconst uploadContent = uploadBox.querySelector('.upload-content');uploadContent.innerHTML = `<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg><p style="color: #667eea; font-weight: 600;">${file.name}</p><span>Click to change file</span>`;hideError();resultsSection.style.display = 'none';}// Denoise button clickdenoiseBtn.addEventListener('click', async () => {if (!selectedFile) return;// Show loadingloading.style.display = 'block';resultsSection.style.display = 'none';hideError();denoiseBtn.disabled = true;// Create form dataconst formData = new FormData();formData.append('image', selectedFile);try {const response = await fetch('/denoise', {method: 'POST',body: formData});const data = await response.json();if (!response.ok) {throw new Error(data.error || 'Failed to denoise image');}// Display resultsoriginalImg.src = data.original;denoisedImg.src = data.denoised;loading.style.display = 'none';resultsSection.style.display = 'block';denoiseBtn.disabled = false;} catch (err) {loading.style.display = 'none';showError(err.message);denoiseBtn.disabled = false;}});// Error handlingfunction showError(message) {error.textContent = message;error.style.display = 'block';setTimeout(() => {hideError();}, 5000);}function hideError() {error.style.display = 'none';}6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381396 unmodified linesconst error = document.getElementById('error');const originalImg = document.getElementById('originalImg');const denoisedImg = document.getElementById('denoisedImg');const samplesGrid = document.getElementById('samplesGrid');let selectedFile = null;// ββ Load sample images on page load ββββββββββββββββββββββββββββββββββββββββββasync function loadSamples() {try {const res = await fetch('/api/samples');const samples = await res.json();samplesGrid.innerHTML = '';samples.forEach(s => {const card = document.createElement('div');card.className = 'sample-card';card.innerHTML = `<img src="${s.thumbnail}" alt="${s.label}" title="Click to denoise"><span>${s.label}</span>`;card.addEventListener('click', () => denoiseSample(s.filename, card));samplesGrid.appendChild(card);});} catch (e) {samplesGrid.innerHTML = '<p style="color:#999">Could not load samples.</p>';}}async function denoiseSample(filename, card) {// Highlight selected carddocument.querySelectorAll('.sample-card').forEach(c => c.classList.remove('active'));card.classList.add('active');showLoading();hideError();try {const res = await fetch('/api/denoise-sample', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ filename })});const data = await res.json();if (!res.ok) throw new Error(data.error || 'Failed');showResults(data.original, data.denoised);} catch (err) {hideLoading();showError(err.message);}}// ββ Upload flow βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββuploadBox.addEventListener('click', () => imageInput.click());imageInput.addEventListener('change', (e) => handleFile(e.target.files[0]));uploadBox.addEventListener('dragover', (e) => {e.preventDefault();uploadBox.classList.add('dragover');});uploadBox.addEventListener('dragleave', () => uploadBox.classList.remove('dragover'));uploadBox.addEventListener('drop', (e) => {e.preventDefault();uploadBox.classList.remove('dragover');handleFile(e.dataTransfer.files[0]);});function handleFile(file) {if (!file) return;if (!file.type.startsWith('image/')) { showError('Please upload an image file'); return; }selectedFile = file;denoiseBtn.disabled = false;const uploadContent = uploadBox.querySelector('.upload-content');uploadContent.innerHTML = `<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg><p style="color:#667eea;font-weight:600;">${file.name}</p><span>Click to change file</span>`;hideError();resultsSection.style.display = 'none';}denoiseBtn.addEventListener('click', async () => {if (!selectedFile) return;showLoading();hideError();denoiseBtn.disabled = true;const formData = new FormData();formData.append('image', selectedFile);try {const res = await fetch('/denoise', { method: 'POST', body: formData });const data = await res.json();if (!res.ok) throw new Error(data.error || 'Failed to denoise image');showResults(data.original, data.denoised);denoiseBtn.disabled = false;} catch (err) {hideLoading();showError(err.message);denoiseBtn.disabled = false;}});// ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfunction showResults(original, denoised) {originalImg.src = original;denoisedImg.src = denoised;hideLoading();resultsSection.style.display = 'block';resultsSection.scrollIntoView({ behavior: 'smooth' });}function showLoading() {loading.style.display = 'block';resultsSection.style.display = 'none';}function hideLoading() { loading.style.display = 'none'; }function showError(message) {error.textContent = message;error.style.display = 'block';setTimeout(hideError, 5000);}function hideError() { error.style.display = 'none'; }// InitloadSamples();
303 unmodified lines304305306303 unmodified linespadding: 20px;}}303 unmodified lines304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390303 unmodified linespadding: 20px;}}/* ββ Sample images section βββββββββββββββββββββββββββββββββββββββ */.samples-section {background: white;border-radius: 20px;padding: 40px;box-shadow: 0 10px 30px rgba(0,0,0,0.1);margin-bottom: 30px;}.samples-section h2 {color: #333;font-size: 1.8rem;font-weight: 700;margin-bottom: 8px;text-align: center;}.samples-subtitle {text-align: center;color: #666;margin-bottom: 24px;font-size: 1rem;}.samples-grid {display: flex;flex-wrap: wrap;gap: 16px;justify-content: center;}.samples-loading {color: #999;font-size: 1rem;}.sample-card {display: flex;flex-direction: column;align-items: center;gap: 8px;cursor: pointer;padding: 12px;border-radius: 12px;border: 2px solid #e8e9ff;background: #f8f9ff;transition: all 0.2s ease;width: 100px;}.sample-card:hover {border-color: #667eea;transform: translateY(-4px);box-shadow: 0 6px 16px rgba(102,126,234,0.25);}.sample-card.active {border-color: #764ba2;background: #f0eaff;box-shadow: 0 6px 16px rgba(118,75,162,0.3);}.sample-card img {width: 64px;height: 64px;image-rendering: pixelated;border-radius: 6px;}.sample-card span {font-size: 0.8rem;font-weight: 600;color: #555;}.upload-section h2,.results-section h2 {color: #333;font-size: 1.5rem;font-weight: 700;margin-bottom: 20px;text-align: center;}
2 unmodified lines3456789101112131415161 unmodified line181920212223242 unmodified lines272829303132333435363738391 unmodified line414243444546474849505152531 unmodified line555657585960616263646566676829 unmodified lines98991001011021031049 unmodified lines1141151161171181191202 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Image Denoiser - AI Powered</title><link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head><body><div class="container"><header><h1>π¨ Image Denoiser</h1><p>Upload a noisy image and let AI clean it up</p></header><!-- Model Info Section -->1 unmodified line<div class="info-header"><h2>π Model Performance</h2></div><div class="metrics-grid"><div class="metric-box"><div class="metric-icon">π―</div>2 unmodified lines<div class="metric-value">{% if model_info and model_info.test_accuracy != 'N/A' %}{{ "%.2f"|format(model_info.test_accuracy * 100) }}%{% else %}N/A{% endif %}</div></div></div><div class="metric-box"><div class="metric-icon">π</div><div class="metric-content">1 unmodified line<div class="metric-value">{% if model_info and model_info.test_f1_score != 'N/A' %}{{ "%.4f"|format(model_info.test_f1_score) }}{% else %}N/A{% endif %}</div></div></div><div class="metric-box"><div class="metric-icon">π</div><div class="metric-content">1 unmodified line<div class="metric-value">{% if model_info and model_info.test_loss != 'N/A' %}{{ "%.4f"|format(model_info.test_loss) }}{% else %}N/A{% endif %}</div></div></div></div><div class="dataset-section"><h3>π Training Information</h3><div class="dataset-grid">29 unmodified lines</div></div><div class="upload-section"><div class="upload-box" id="uploadBox"><input type="file" id="imageInput" accept="image/*" hidden><div class="upload-content">9 unmodified lines<button id="denoiseBtn" class="btn-primary" disabled>Denoise Image</button></div><div class="results-section" id="resultsSection" style="display: none;"><div class="image-comparison"><div class="image-box"><h3>Original (Noisy)</h3>2 unmodified lines3456789101112131415161 unmodified line1819202122232 unmodified lines262728293031323334351 unmodified line373839404142434445461 unmodified line484950515253545556575829 unmodified lines8889909192939495969798991001011021031041059 unmodified lines1151161171181191201211221232 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>DeepClean - Image Denoiser</title><link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head><body><div class="container"><header><h1>π¨ DeepClean</h1><p>CNN Autoencoder β Upload a noisy image or try a sample below</p></header><!-- Model Info Section -->1 unmodified line<div class="info-header"><h2>π Model Performance</h2></div><div class="metrics-grid"><div class="metric-box"><div class="metric-icon">π―</div>2 unmodified lines<div class="metric-value">{% if model_info and model_info.test_accuracy != 'N/A' %}{{ "%.2f"|format(model_info.test_accuracy * 100) }}%{% else %}N/A{% endif %}</div></div></div><div class="metric-box"><div class="metric-icon">π</div><div class="metric-content">1 unmodified line<div class="metric-value">{% if model_info and model_info.test_f1_score != 'N/A' %}{{ "%.4f"|format(model_info.test_f1_score) }}{% else %}N/A{% endif %}</div></div></div><div class="metric-box"><div class="metric-icon">π</div><div class="metric-content">1 unmodified line<div class="metric-value">{% if model_info and model_info.test_loss != 'N/A' %}{{ "%.4f"|format(model_info.test_loss) }}{% else %}N/A{% endif %}</div></div></div></div><div class="dataset-section"><h3>π Training Information</h3><div class="dataset-grid">29 unmodified lines</div></div><!-- Sample Images Section --><div class="samples-section"><h2>πΌοΈ Try a Sample Image</h2><p class="samples-subtitle">Click any noisy digit below to instantly denoise it</p><div class="samples-grid" id="samplesGrid"><div class="samples-loading">Loading samples...</div></div></div><!-- Upload Section --><div class="upload-section"><h2>π€ Or Upload Your Own</h2><div class="upload-box" id="uploadBox"><input type="file" id="imageInput" accept="image/*" hidden><div class="upload-content">9 unmodified lines<button id="denoiseBtn" class="btn-primary" disabled>Denoise Image</button></div><!-- Results Section --><div class="results-section" id="resultsSection" style="display: none;"><h2>β¨ Result</h2><div class="image-comparison"><div class="image-box"><h3>Original (Noisy)</h3>
Dockerfile+1
app.py+43-2
static/script.js+80-59
static/style.css+84
templates/index.html+19-16
test_images/noisy_digit_2_8.pngAdded

test_images/noisy_digit_3_1.pngAdded

test_images/noisy_digit_3_4.pngAdded

test_images/noisy_digit_4_2.pngAdded

test_images/noisy_digit_4_6.pngAdded

test_images/noisy_digit_5_10.pngAdded

test_images/noisy_digit_5_5.pngAdded

test_images/noisy_digit_5_7.pngAdded

test_images/noisy_digit_5_9.pngAdded

test_images/noisy_digit_8_3.pngAdded
