File size: 5,939 Bytes
c4a514c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * MFAF-Net — Standalone JS Utilities
 * Main application logic lives in templates/index.html <script> block.
 * This file provides reusable helpers that can be imported or included separately.
 */

'use strict';

/* =========================================================
   IMAGE DOWNLOAD UTILITY
   ========================================================= */

/**
 * Trigger a browser download of an image from a URL.
 * @param {string} url      - Absolute or relative URL of the image.
 * @param {string} filename - Desired download filename (e.g. "result.png").
 */
function downloadImage(url, filename) {
  if (!url) {
    console.warn('downloadImage: no URL provided');
    return;
  }
  filename = filename || deriveFilename(url);

  fetch(url)
    .then(function (response) {
      if (!response.ok) throw new Error('Network response was not ok');
      return response.blob();
    })
    .then(function (blob) {
      var objectUrl = URL.createObjectURL(blob);
      var anchor = document.createElement('a');
      anchor.href = objectUrl;
      anchor.download = filename;
      document.body.appendChild(anchor);
      anchor.click();
      document.body.removeChild(anchor);
      setTimeout(function () { URL.revokeObjectURL(objectUrl); }, 1000);
    })
    .catch(function (err) {
      console.error('downloadImage failed:', err);
      // Fallback: open in new tab
      window.open(url, '_blank');
    });
}

/**
 * Derive a filename from a URL path.
 * @param {string} url
 * @returns {string}
 */
function deriveFilename(url) {
  try {
    var parts = new URL(url, window.location.href).pathname.split('/');
    return parts[parts.length - 1] || 'download.png';
  } catch (e) {
    return 'download.png';
  }
}

/* =========================================================
   CLIPBOARD UTILITY
   ========================================================= */

/**
 * Copy text to the system clipboard.
 * Falls back to execCommand for older browsers.
 * @param {string}   text       - Text to copy.
 * @param {Function} [callback] - Optional callback(success: boolean).
 */
function copyToClipboard(text, callback) {
  if (!text) {
    if (callback) callback(false);
    return;
  }

  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(text).then(
      function () { if (callback) callback(true); },
      function () { legacyCopy(text, callback); }
    );
  } else {
    legacyCopy(text, callback);
  }
}

/**
 * execCommand-based fallback clipboard copy.
 * @param {string}   text
 * @param {Function} [callback]
 */
function legacyCopy(text, callback) {
  var textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0';
  document.body.appendChild(textarea);
  textarea.focus();
  textarea.select();
  var success = false;
  try {
    success = document.execCommand('copy');
  } catch (e) {
    console.error('legacyCopy failed:', e);
  }
  document.body.removeChild(textarea);
  if (callback) callback(success);
}

/* =========================================================
   METRIC FORMATTING HELPERS
   ========================================================= */

/**
 * Format a floating-point metric value for display.
 * @param {number} value
 * @param {number} [decimals=4]
 * @returns {string}
 */
function formatMetric(value, decimals) {
  if (value === null || value === undefined || isNaN(value)) return 'N/A';
  decimals = (decimals !== undefined) ? decimals : 4;
  return parseFloat(value).toFixed(decimals);
}

/**
 * Format SSIM (0–1) as a percentage string.
 * @param {number} ssim
 * @returns {string}
 */
function formatSSIM(ssim) {
  if (ssim === null || ssim === undefined || isNaN(ssim)) return 'N/A';
  return (parseFloat(ssim) * 100).toFixed(2) + '%';
}

/**
 * Format PSNR in dB.
 * @param {number} psnr
 * @returns {string}
 */
function formatPSNR(psnr) {
  if (psnr === null || psnr === undefined || isNaN(psnr)) return 'N/A';
  return parseFloat(psnr).toFixed(2) + ' dB';
}

/**
 * Format a pixel-change percentage.
 * @param {number} pct
 * @returns {string}
 */
function formatChangedPct(pct) {
  if (pct === null || pct === undefined || isNaN(pct)) return 'N/A';
  return parseFloat(pct).toFixed(2) + '%';
}

/**
 * Format MAE (mean absolute error).
 * @param {number} mae
 * @returns {string}
 */
function formatMAE(mae) {
  if (mae === null || mae === undefined || isNaN(mae)) return 'N/A';
  return parseFloat(mae).toFixed(4);
}

/**
 * Map all metrics in a result object to display-friendly strings.
 * @param {Object} metrics - Raw metrics from /api/analyze response.
 * @returns {Object}       - { ssim, psnr, mae, changed_pixel_pct } as strings.
 */
function formatAllMetrics(metrics) {
  if (!metrics) return {};
  return {
    ssim:              formatSSIM(metrics.ssim),
    psnr:              formatPSNR(metrics.psnr),
    mae:               formatMAE(metrics.mae),
    changed_pixel_pct: formatChangedPct(metrics.changed_pixel_pct),
  };
}

/**
 * Assign a qualitative label to an SSIM score.
 * @param {number} ssim
 * @returns {string}
 */
function ssimQualityLabel(ssim) {
  var v = parseFloat(ssim);
  if (isNaN(v))  return 'Unknown';
  if (v >= 0.95) return 'Excellent';
  if (v >= 0.85) return 'Good';
  if (v >= 0.70) return 'Fair';
  return 'Low';
}

/* =========================================================
   EXPORT (for environments that support modules)
   ========================================================= */
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    downloadImage: downloadImage,
    copyToClipboard: copyToClipboard,
    formatMetric: formatMetric,
    formatSSIM: formatSSIM,
    formatPSNR: formatPSNR,
    formatChangedPct: formatChangedPct,
    formatMAE: formatMAE,
    formatAllMetrics: formatAllMetrics,
    ssimQualityLabel: ssimQualityLabel,
  };
}