chanraphone4 commited on
Commit
38eac3c
·
verified ·
1 Parent(s): 675448d

Delete index.html

Browse files
Files changed (1) hide show
  1. index.html +0 -1232
index.html DELETED
@@ -1,1232 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="km">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>ឧបករណ៍ក្លូនរូបភាព AI - AI Image Cloner</title>
7
- <!-- Tailwind CSS -->
8
- <script src="https://cdn.tailwindcss.com"></script>
9
- <!-- FontAwesome for Icons -->
10
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
11
- <!-- Google Fonts (Kantumruy & Battambang for Khmer) -->
12
- <link href="https://fonts.googleapis.com/css2?family=Kantumruy+Pro:wght@300;400;600;700&family=Battambang:wght@400;700&display=swap" rel="stylesheet">
13
- <style>
14
- body {
15
- font-family: 'Kantumruy Pro', 'Battambang', sans-serif;
16
- background-color: #0f172a;
17
- }
18
- .glass {
19
- background: rgba(30, 41, 59, 0.7);
20
- backdrop-filter: blur(12px);
21
- border: 1px solid rgba(255, 255, 255, 0.1);
22
- }
23
- .btn-pop-3d,
24
- .choice-pop-3d,
25
- .icon-pop-3d {
26
- transform: translateY(0);
27
- transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease, background 160ms ease;
28
- }
29
- .btn-pop-3d {
30
- box-shadow: 0 7px 0 rgba(15, 23, 42, 0.95), 0 16px 32px rgba(99, 102, 241, 0.22);
31
- }
32
- .btn-pop-3d:hover:not(:disabled) {
33
- transform: translateY(-2px);
34
- box-shadow: 0 9px 0 rgba(15, 23, 42, 0.95), 0 22px 40px rgba(99, 102, 241, 0.28);
35
- }
36
- .btn-pop-3d:active:not(:disabled) {
37
- transform: translateY(4px);
38
- box-shadow: 0 3px 0 rgba(15, 23, 42, 0.95), 0 10px 20px rgba(99, 102, 241, 0.18);
39
- }
40
- .btn-pop-3d:disabled {
41
- transform: none;
42
- box-shadow: none;
43
- }
44
- .choice-pop-3d {
45
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 5px 0 rgba(15, 23, 42, 0.9);
46
- }
47
- .choice-pop-3d:hover {
48
- transform: translateY(-2px);
49
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08), 0 7px 0 rgba(15, 23, 42, 0.9), 0 14px 26px rgba(99, 102, 241, 0.18);
50
- }
51
- .choice-pop-3d.active-style {
52
- background: linear-gradient(180deg, rgba(79, 70, 229, 0.24), rgba(15, 23, 42, 0.72));
53
- box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 6px 0 rgba(49, 46, 129, 0.85), 0 16px 30px rgba(99, 102, 241, 0.22);
54
- }
55
- .icon-pop-3d {
56
- box-shadow: 0 3px 0 rgba(15, 23, 42, 0.85);
57
- }
58
- .icon-pop-3d:hover {
59
- transform: translateY(-1px);
60
- box-shadow: 0 4px 0 rgba(15, 23, 42, 0.85), 0 10px 18px rgba(99, 102, 241, 0.14);
61
- }
62
- .icon-pop-3d:active {
63
- transform: translateY(2px);
64
- box-shadow: 0 1px 0 rgba(15, 23, 42, 0.85);
65
- }
66
- </style>
67
- </head>
68
- <body class="text-slate-100 min-h-screen flex flex-col justify-between">
69
-
70
- <!-- Header -->
71
- <header class="border-b border-slate-800 bg-slate-900/80 backdrop-blur sticky top-0 z-50">
72
- <div class="max-w-7xl mx-auto px-4 py-3 flex flex-col gap-3 lg:flex-row lg:justify-between lg:items-center">
73
- <div class="flex items-center space-x-3">
74
- <div class="p-2 bg-gradient-to-tr from-indigo-500 to-purple-500 rounded-lg shadow-lg shadow-indigo-500/30">
75
- <i class="fa-solid fa-clone text-lg text-white"></i>
76
- </div>
77
- <div>
78
- <h1 class="text-lg font-bold bg-gradient-to-r from-indigo-400 via-purple-400 to-pink-400 bg-clip-text text-transparent">
79
- ឧបករណ៍ក្លូនរូបភាព AI
80
- </h1>
81
- <p class="hidden sm:block text-[11px] text-slate-400">ជំនាន់ដំបូង៖ សាមញ្ញ លឿន និងងាយស្រួលប្រើប្រាស់</p>
82
- </div>
83
- </div>
84
- <div class="w-full lg:w-auto flex flex-col gap-1.5 lg:items-end">
85
- <div class="w-full lg:w-auto flex items-center gap-1.5 bg-slate-950/60 border border-slate-800 rounded-lg px-2 py-1.5">
86
- <i class="fa-solid fa-key text-xs text-indigo-400 shrink-0"></i>
87
- <input id="apiKeyInput" type="password" autocomplete="off" spellcheck="false" placeholder="API Key" class="min-w-0 flex-1 w-0 sm:w-52 lg:w-56 bg-transparent text-xs text-slate-200 placeholder-slate-500 focus:outline-none">
88
- <button id="toggleApiKeyBtn" type="button" class="icon-pop-3d shrink-0 w-7 h-7 flex items-center justify-center text-slate-400 hover:text-slate-200 p-1" title="បង្ហាញ/លាក់ API Key">
89
- <i id="toggleApiKeyIcon" class="fa-solid fa-eye"></i>
90
- </button>
91
- <button id="refreshBalanceBtn" type="button" class="icon-pop-3d shrink-0 w-7 h-7 flex items-center justify-center text-slate-400 hover:text-slate-200 p-1" title="ពិនិត្យ balance">
92
- <i class="fa-solid fa-rotate"></i>
93
- </button>
94
- </div>
95
- <div class="flex flex-wrap items-center gap-1.5 text-[10px]">
96
- <span class="flex h-2 w-2 relative shrink-0">
97
- <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
98
- <span class="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
99
- </span>
100
- <span class="leading-none text-slate-300 font-medium bg-slate-800/80 px-2 py-1 rounded-full border border-slate-700">R-Tool-AI</span>
101
- <span id="customerStatus" class="max-w-[142px] sm:max-w-none truncate leading-none text-slate-300 font-medium bg-slate-800/80 px-2 py-1 rounded-full border border-slate-700 whitespace-nowrap">Customer: --</span>
102
- <span id="keyExpiresStatus" class="leading-none text-slate-300 font-medium bg-slate-800/80 px-2 py-1 rounded-full border border-slate-700 whitespace-nowrap">Expiration: --</span>
103
- <span id="creditLimitStatus" class="leading-none text-slate-300 font-medium bg-slate-800/80 px-2 py-1 rounded-full border border-slate-700 whitespace-nowrap">Credit limit: --</span>
104
- </div>
105
- </div>
106
- </div>
107
- </header>
108
-
109
- <!-- Main Content -->
110
- <main class="max-w-7xl mx-auto px-4 py-8 w-full flex-grow">
111
- <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
112
-
113
- <!-- Left Panel: Upload and Settings -->
114
- <section class="lg:col-span-5 space-y-6">
115
- <!-- Dropzone for Image -->
116
- <div class="glass rounded-2xl p-6 shadow-xl">
117
- <h2 class="text-lg font-semibold mb-4 flex items-center gap-2 text-indigo-400">
118
- <i class="fa-solid fa-image"></i> ១. បញ្ចូលរូបភាពច្បាប់ដើម
119
- </h2>
120
-
121
- <div id="dropzone" class="border-2 border-dashed border-slate-700 hover:border-indigo-500 rounded-xl p-8 text-center cursor-pointer transition-all bg-slate-950/40 relative overflow-hidden group">
122
- <input type="file" id="imageInput" accept="image/png,image/jpeg,image/webp,image/gif" multiple class="hidden">
123
- <div id="uploadPlaceholder" class="space-y-4">
124
- <div class="mx-auto w-16 h-16 rounded-full bg-slate-800/80 flex items-center justify-center border border-slate-700 group-hover:scale-110 transition-transform">
125
- <i class="fa-solid fa-cloud-arrow-up text-2xl text-indigo-400"></i>
126
- </div>
127
- <div>
128
- <p class="font-medium text-slate-200">អូសរូបភាពមកទីនេះ ឬ ចុចដើម្បីជ្រើសរើសម្តងបានច្រើន</p>
129
- <p class="text-xs text-slate-500 mt-1">គាំទ្រប្រភេទ PNG, JPG, JPEG, WEBP, GIF (រូបនីមួយៗក្រោម 5MB)</p>
130
- </div>
131
- </div>
132
- <div id="imagePreviewContainer" class="hidden relative w-full rounded-lg border border-slate-700 bg-slate-900 p-3">
133
- <div class="flex items-center justify-between gap-3 mb-3">
134
- <span id="selectedImagesCount" class="text-xs text-indigo-300 font-semibold bg-indigo-500/10 border border-indigo-500/20 rounded-full px-3 py-1">0 រូបដើម</span>
135
- <button id="removeImageBtn" type="button" class="btn-pop-3d bg-red-500/80 hover:bg-red-600 text-white px-3 py-1.5 rounded-lg transition-colors shadow-lg backdrop-blur-sm text-xs flex items-center gap-1.5" title="លុបទាំងអស់">
136
- <i class="fa-solid fa-trash-can"></i> លុបទាំងអស់
137
- </button>
138
- </div>
139
- <div id="imagePreviewGrid" class="grid grid-cols-2 sm:grid-cols-3 gap-3 max-h-72 overflow-y-auto pr-1">
140
- <!-- Source image previews will be injected dynamically here -->
141
- </div>
142
- </div>
143
- </div>
144
- </div>
145
-
146
- <!-- Clone Configurations -->
147
- <div class="glass rounded-2xl p-6 shadow-xl space-y-5">
148
- <h2 class="text-lg font-semibold flex items-center gap-2 text-indigo-400">
149
- <i class="fa-solid fa-sliders"></i> ២. ការកំណត់ការក្លូន (Clone Settings)
150
- </h2>
151
-
152
- <!-- Clone Quantity -->
153
- <div>
154
- <div class="flex justify-between items-center mb-2">
155
- <label class="text-sm font-medium text-slate-300">ចំនួនក្លូនក្នុងមួយរូបដើម</label>
156
- <span id="quantityVal" class="text-indigo-400 font-bold bg-indigo-500/10 px-2.5 py-0.5 rounded-md border border-indigo-500/20">1 រូបភាព</span>
157
- </div>
158
- <input type="range" id="cloneQuantity" min="1" max="8" value="1" class="w-full h-2 bg-slate-800 rounded-lg appearance-none cursor-pointer accent-indigo-500 focus:outline-none">
159
- <div class="flex justify-between text-[10px] text-slate-500 mt-1 px-1">
160
- <span>1 រូបភាព</span>
161
- <span>4 រូបភាព</span>
162
- <span>8 រូបភាព</span>
163
- </div>
164
- </div>
165
-
166
- <!-- Similarity Options -->
167
- <div>
168
- <label class="text-sm font-medium text-slate-300 block mb-2">កម្រិតស្រដៀងនឹងច្បាប់ដើម</label>
169
- <div class="grid grid-cols-3 gap-2">
170
- <button type="button" data-similarity="high" class="similarity-btn choice-pop-3d border border-slate-700 bg-slate-950/40 rounded-xl p-3 text-center transition-all hover:bg-slate-800 active-style border-indigo-500 text-indigo-400">
171
- <i class="fa-solid fa-crosshairs block text-lg mb-1"></i>
172
- <span class="text-xs font-semibold">ស្រដៀងខ្លាំង</span>
173
- </button>
174
- <button type="button" data-similarity="medium" class="similarity-btn choice-pop-3d border border-slate-700 bg-slate-950/40 rounded-xl p-3 text-center transition-all hover:bg-slate-800">
175
- <i class="fa-solid fa-shuffle block text-lg mb-1"></i>
176
- <span class="text-xs font-semibold">ស្រដៀងល្មម</span>
177
- </button>
178
- <button type="button" data-similarity="creative" class="similarity-btn choice-pop-3d border border-slate-700 bg-slate-950/40 rounded-xl p-3 text-center transition-all hover:bg-slate-800">
179
- <i class="fa-solid fa-wand-magic-sparkles block text-lg mb-1"></i>
180
- <span class="text-xs font-semibold">ច្នៃប្រឌិតថ្មី</span>
181
- </button>
182
- </div>
183
- </div>
184
-
185
- <!-- AI Model Selector -->
186
- <div>
187
- <label class="text-sm font-medium text-slate-300 block mb-2 flex items-center justify-between">
188
- <span>ជ្រើសរើស AI Model</span>
189
- <button id="reloadModelsBtn" type="button" class="icon-pop-3d text-[10px] text-indigo-300 hover:text-indigo-200 font-semibold flex items-center gap-1 px-2 py-1 border border-slate-800 bg-slate-950/40">
190
- <i class="fa-solid fa-rotate"></i> Load Models
191
- </button>
192
- </label>
193
- <select id="modelSelect" class="w-full bg-slate-950/60 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-200 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors">
194
- <option value="google/gemini-2.5-flash-image">Google Gemini 2.5 Flash Image</option>
195
- </select>
196
- <p id="modelHelpText" class="text-[10px] text-slate-500 mt-2">បញ្ជីនេះបង្ហាញ model ដែលគាំទ្រ image input និង image output។</p>
197
- </div>
198
-
199
- <!-- Extra Prompt Modifiers -->
200
- <div>
201
- <label class="text-sm font-medium text-slate-300 block mb-2 flex items-center justify-between">
202
- <span>បន្ថែមការណែនាំពិសេស (គំនិតបន្ថែម)</span>
203
- <span class="text-[10px] text-slate-500 font-normal">ស្រេចចិត្ត</span>
204
- </label>
205
- <textarea id="promptModifier" rows="2" placeholder="ឧទាហរណ៍៖ ប្តូរស្ទីលជាគំនូរជីវចល (Anime), បន្ថែមពន្លឺថ្ងៃលិច, ប្តូរផ្ទៃខាងក្រោយ..." class="w-full bg-slate-950/60 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-200 placeholder-slate-500 focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition-colors resize-none"></textarea>
206
- </div>
207
-
208
- <!-- Action Button -->
209
- <button id="generateBtn" disabled class="btn-pop-3d w-full py-4 px-6 rounded-xl font-bold bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 text-white shadow-lg shadow-indigo-500/20 hover:shadow-indigo-500/40 hover:opacity-95 transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:shadow-none flex items-center justify-center gap-2">
210
- <i class="fa-solid fa-bolt"></i> ចាប់ផ្តើមក្លូនរូបភាព
211
- </button>
212
- </div>
213
- </section>
214
-
215
- <!-- Right Panel: Results & Gallery -->
216
- <section class="lg:col-span-7 flex flex-col space-y-6">
217
- <div class="glass rounded-2xl p-6 shadow-xl flex-grow flex flex-col">
218
- <div class="flex justify-between items-center mb-6">
219
- <h2 class="text-lg font-semibold flex items-center gap-2 text-indigo-400">
220
- <i class="fa-solid fa-images"></i> លទ្ធផលនៃការក្លូន (Cloned Gallery)
221
- </h2>
222
- <button id="downloadAllBtn" class="btn-pop-3d hidden text-xs bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 px-3 py-1.5 rounded-lg transition-colors flex items-center gap-1.5">
223
- <i class="fa-solid fa-download"></i> ទាញយករូបទាំងអស់
224
- </button>
225
- </div>
226
-
227
- <!-- Gallery Content Area -->
228
- <div id="galleryContainer" class="flex-grow flex flex-col justify-center items-center text-center p-8 border border-dashed border-slate-800 rounded-xl bg-slate-950/20">
229
- <div id="galleryEmptyState" class="space-y-4 max-w-sm">
230
- <div class="w-20 h-20 mx-auto rounded-full bg-slate-900 flex items-center justify-center border border-slate-800 text-slate-600">
231
- <i class="fa-solid fa-shapes text-3xl"></i>
232
- </div>
233
- <div>
234
- <h3 class="font-semibold text-slate-300">មិនទាន់មានរូបភាពក្លូននៅឡើយទេ</h3>
235
- <p class="text-sm text-slate-500 mt-1">សូមបញ្ចូលរូបភាព រួចចុច "ចាប់ផ្តើមក្លូនរូបភាព" ដើម្បីបង្ហាញលទ្ធផល!</p>
236
- </div>
237
- </div>
238
-
239
- <!-- Grid View for cloned results -->
240
- <div id="clonesGrid" class="hidden w-full grid grid-cols-1 sm:grid-cols-2 gap-4">
241
- <!-- Cloned cards will be injected dynamically here -->
242
- </div>
243
- </div>
244
- </div>
245
- </section>
246
-
247
- </div>
248
- </main>
249
-
250
- <!-- Unified Popup for iPhone & Desktop Preview -->
251
- <div id="previewModal" class="fixed inset-0 bg-slate-950/95 z-50 hidden flex-col items-center justify-center p-4 backdrop-blur-md">
252
- <div class="relative max-w-md w-full flex flex-col items-center">
253
- <!-- Close Button -->
254
- <button id="closeModalBtn" class="icon-pop-3d absolute -top-12 right-0 bg-slate-800 hover:bg-slate-700 text-white p-2.5 rounded-full transition-all border border-slate-700">
255
- <i class="fa-solid fa-xmark text-lg"></i>
256
- </button>
257
-
258
- <!-- iOS Instructions Alert Box -->
259
- <div id="iosInstruction" class="w-full bg-indigo-600/20 border border-indigo-500/40 rounded-xl p-4 mb-4 text-center">
260
- <p class="text-sm font-semibold text-indigo-300 flex items-center justify-center gap-2">
261
- <i class="fa-solid fa-hand-pointer animate-bounce"></i> សម្រាប់ទូរសព្ទ iPhone
262
- </p>
263
- <p class="text-xs text-slate-300 mt-1">សូមចុចសង្កត់ (Long Press) លើរូបភាពខាងក្រោម រួចជ្រើសរើស <strong>"រក្សាទុកក្នុងរូបភាព" (Save to Photos)</strong> ដើម្បីទាញយក។</p>
264
- </div>
265
-
266
- <!-- Image Container -->
267
- <div class="w-full bg-slate-900 rounded-xl overflow-hidden border border-slate-800 p-2 shadow-2xl">
268
- <img id="modalTargetImg" src="" alt="Preview" class="w-full max-h-[60vh] object-contain rounded-lg">
269
- </div>
270
-
271
- <!-- Standard Download Button (Hidden on iOS) -->
272
- <div id="standardDownloadBtnContainer" class="mt-4 w-full">
273
- <a id="modalDownloadBtn" href="#" download="cloned_image.png" class="btn-pop-3d w-full justify-center bg-indigo-600 hover:bg-indigo-700 text-white px-6 py-3 rounded-xl font-bold transition-colors flex items-center gap-2">
274
- <i class="fa-solid fa-download"></i> ទាញយករូបនេះ
275
- </a>
276
- </div>
277
- </div>
278
- </div>
279
-
280
- <!-- Admin Contact Notice Modal -->
281
- <div id="adminNoticeModal" class="fixed inset-0 bg-slate-950/80 z-50 hidden items-center justify-center p-4 backdrop-blur-sm">
282
- <div class="max-w-md w-full bg-slate-900 border border-red-500/30 rounded-2xl p-6 shadow-2xl">
283
- <div class="flex items-start gap-3">
284
- <div class="w-10 h-10 rounded-full bg-red-500/15 border border-red-500/30 flex items-center justify-center text-red-300 shrink-0">
285
- <i class="fa-solid fa-triangle-exclamation"></i>
286
- </div>
287
- <div class="min-w-0">
288
- <h3 id="adminNoticeTitle" class="text-lg font-bold text-white">សូមទាក់ទង Admin</h3>
289
- <p id="adminNoticeMessage" class="text-sm text-slate-300 mt-1 leading-relaxed">សូមទាក់ទង Admin ដើម្បីទិញ ឬបន្ត API Key។</p>
290
- </div>
291
- </div>
292
- <div class="mt-5 grid gap-2 text-sm">
293
- <a href="mailto:chanraphone4@gmail.com" class="flex items-center gap-2 text-indigo-200 hover:text-indigo-100 bg-slate-950/60 border border-slate-800 rounded-lg px-3 py-2">
294
- <i class="fa-solid fa-envelope text-indigo-300"></i>
295
- <span>chanraphone4@gmail.com</span>
296
- </a>
297
- <a href="tel:077857878" class="flex items-center gap-2 text-indigo-200 hover:text-indigo-100 bg-slate-950/60 border border-slate-800 rounded-lg px-3 py-2">
298
- <i class="fa-solid fa-phone text-indigo-300"></i>
299
- <span>077857878</span>
300
- </a>
301
- <a href="tel:086680000" class="flex items-center gap-2 text-indigo-200 hover:text-indigo-100 bg-slate-950/60 border border-slate-800 rounded-lg px-3 py-2">
302
- <i class="fa-solid fa-phone text-indigo-300"></i>
303
- <span>086680000</span>
304
- </a>
305
- </div>
306
- <button id="adminNoticeCloseBtn" type="button" class="btn-pop-3d mt-5 w-full bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2.5 rounded-xl font-semibold transition-colors">
307
- OK
308
- </button>
309
- </div>
310
- </div>
311
-
312
- <!-- Error/Notification Toast -->
313
- <div id="toast" class="fixed bottom-6 right-6 z-50 transform translate-y-20 opacity-0 transition-all duration-300 max-w-md w-full">
314
- <div class="bg-red-500/90 text-white p-4 rounded-xl shadow-2xl backdrop-blur flex items-center gap-3 border border-red-400/20">
315
- <i id="toastIcon" class="fa-solid fa-circle-exclamation text-xl"></i>
316
- <span id="toastMessage" class="text-sm font-medium">មានកំហុសមួយបានកើតឡើង!</span>
317
- </div>
318
- </div>
319
-
320
- <!-- Footer -->
321
- <footer class="border-t border-slate-800/80 bg-slate-950/60 py-4 mt-12 text-center text-xs text-slate-500">
322
- <div class="max-w-7xl mx-auto px-4">
323
- <p>© 2026 R-Tool-AI ។ អ្នកផលិតធូល៖ 077857878 / 086680000</p>
324
- </div>
325
- </footer>
326
-
327
- <!-- Scripts -->
328
- <script>
329
- // OpenRouter API configuration
330
- const openRouterEndpoint = "https://openrouter.ai/api/v1/chat/completions";
331
- const openRouterKeyEndpoint = "https://openrouter.ai/api/v1/key";
332
- const openRouterModelsEndpoint = "https://openrouter.ai/api/v1/models";
333
- const defaultOpenRouterModel = "google/gemini-2.5-flash-image";
334
- const workspaceCreditLimit = 1;
335
- const workspaceCreditLimitResetInterval = "weekly";
336
- const openRouterAppTitle = "AI Image Cloner";
337
- const adminContactEmail = "chanraphone4@gmail.com";
338
- const adminContactPhones = "077857878 / 086680000";
339
- const apiKeyStorageKey = "openrouter_api_key";
340
- const selectedModelStorageKey = "openrouter_selected_model";
341
- const requestCountStorageKey = "openrouter_request_count";
342
- const supportedImageTypes = ["image/png", "image/jpeg", "image/webp", "image/gif"];
343
- let uploadedImages = [];
344
- let selectedSimilarity = "high";
345
- let generatedImagesArray = [];
346
- let balanceRefreshTimer;
347
- let latestKeyData = null;
348
- const savedOpenRouterModel = localStorage.getItem(selectedModelStorageKey);
349
- let selectedOpenRouterModel = savedOpenRouterModel && !["undefined", "null", ""].includes(savedOpenRouterModel)
350
- ? savedOpenRouterModel
351
- : defaultOpenRouterModel;
352
- let requestCount = parseInt(localStorage.getItem(requestCountStorageKey) || "0", 10);
353
-
354
- // Detect device
355
- const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
356
-
357
- // DOM elements
358
- const imageInput = document.getElementById('imageInput');
359
- const dropzone = document.getElementById('dropzone');
360
- const uploadPlaceholder = document.getElementById('uploadPlaceholder');
361
- const imagePreviewContainer = document.getElementById('imagePreviewContainer');
362
- const imagePreviewGrid = document.getElementById('imagePreviewGrid');
363
- const selectedImagesCount = document.getElementById('selectedImagesCount');
364
- const removeImageBtn = document.getElementById('removeImageBtn');
365
- const cloneQuantity = document.getElementById('cloneQuantity');
366
- const quantityVal = document.getElementById('quantityVal');
367
- const apiKeyInput = document.getElementById('apiKeyInput');
368
- const toggleApiKeyBtn = document.getElementById('toggleApiKeyBtn');
369
- const toggleApiKeyIcon = document.getElementById('toggleApiKeyIcon');
370
- const refreshBalanceBtn = document.getElementById('refreshBalanceBtn');
371
- const customerStatus = document.getElementById('customerStatus');
372
- const creditLimitStatus = document.getElementById('creditLimitStatus');
373
- const keyExpiresStatus = document.getElementById('keyExpiresStatus');
374
- const modelSelect = document.getElementById('modelSelect');
375
- const reloadModelsBtn = document.getElementById('reloadModelsBtn');
376
- const modelHelpText = document.getElementById('modelHelpText');
377
- const promptModifier = document.getElementById('promptModifier');
378
- const generateBtn = document.getElementById('generateBtn');
379
- const galleryEmptyState = document.getElementById('galleryEmptyState');
380
- const clonesGrid = document.getElementById('clonesGrid');
381
- const galleryContainer = document.getElementById('galleryContainer');
382
- const downloadAllBtn = document.getElementById('downloadAllBtn');
383
- const similarityBtns = document.querySelectorAll('.similarity-btn');
384
- const toast = document.getElementById('toast');
385
- const toastMessage = document.getElementById('toastMessage');
386
- const toastIcon = document.getElementById('toastIcon');
387
- const adminNoticeModal = document.getElementById('adminNoticeModal');
388
- const adminNoticeTitle = document.getElementById('adminNoticeTitle');
389
- const adminNoticeMessage = document.getElementById('adminNoticeMessage');
390
- const adminNoticeCloseBtn = document.getElementById('adminNoticeCloseBtn');
391
-
392
- // Modal elements
393
- const previewModal = document.getElementById('previewModal');
394
- const closeModalBtn = document.getElementById('closeModalBtn');
395
- const iosInstruction = document.getElementById('iosInstruction');
396
- const modalTargetImg = document.getElementById('modalTargetImg');
397
- const standardDownloadBtnContainer = document.getElementById('standardDownloadBtnContainer');
398
- const modalDownloadBtn = document.getElementById('modalDownloadBtn');
399
-
400
- apiKeyInput.value = localStorage.getItem(apiKeyStorageKey) || "";
401
- modelSelect.value = selectedOpenRouterModel;
402
- updateRequestCountStatus();
403
-
404
- function getOpenRouterApiKey() {
405
- return apiKeyInput.value.trim();
406
- }
407
-
408
- function getSelectedOpenRouterModel() {
409
- const model = modelSelect.value || selectedOpenRouterModel || defaultOpenRouterModel;
410
- return ["undefined", "null", ""].includes(model) ? defaultOpenRouterModel : model;
411
- }
412
-
413
- function updateRequestCountStatus() {
414
- }
415
-
416
- function getCustomerName(keyData) {
417
- return keyData?.name || keyData?.label || "";
418
- }
419
-
420
- function updateCustomerStatus(keyData) {
421
- const hasApiKey = Boolean(getOpenRouterApiKey());
422
- const customerName = getCustomerName(keyData);
423
- customerStatus.textContent = customerName
424
- ? `Customer: ${customerName}`
425
- : hasApiKey ? "Customer: checking" : "Customer: --";
426
- if (customerName) {
427
- customerStatus.title = customerName;
428
- } else {
429
- customerStatus.removeAttribute("title");
430
- }
431
- }
432
-
433
- function formatLimitResetLabel(value) {
434
- if (!value) return "";
435
- const labels = {
436
- daily: "day",
437
- weekly: "week",
438
- monthly: "month"
439
- };
440
- return ` / ${labels[value] || String(value).replaceAll("_", " ")}`;
441
- }
442
-
443
- function updateCreditLimitStatus(value, resetInterval = "") {
444
- if (value === undefined) {
445
- creditLimitStatus.textContent = "Credit limit: --";
446
- creditLimitStatus.removeAttribute("title");
447
- return false;
448
- }
449
-
450
- if (value === null || value === "") {
451
- creditLimitStatus.textContent = "Credit limit: Unlimited";
452
- creditLimitStatus.removeAttribute("title");
453
- return false;
454
- }
455
-
456
- const limit = getFiniteNumber(value);
457
- if (limit === null) {
458
- creditLimitStatus.textContent = `Credit limit: ${String(value)}`;
459
- creditLimitStatus.title = String(value);
460
- return true;
461
- }
462
-
463
- const resetLabel = formatLimitResetLabel(resetInterval);
464
- creditLimitStatus.textContent = `Credit limit: $${formatCreditAmount(limit)}${resetLabel}`;
465
- creditLimitStatus.title = resetInterval ? `Resets: ${String(resetInterval)}` : "Credit limit";
466
- return true;
467
- }
468
-
469
- function updateWorkspaceCreditLimitStatus() {
470
- const hasWorkspaceLimit = updateCreditLimitStatus(workspaceCreditLimit, workspaceCreditLimitResetInterval);
471
- creditLimitStatus.title = "Workspace guardrail budget configured in OpenRouter.";
472
- return hasWorkspaceLimit;
473
- }
474
-
475
- function getCreditRemaining(keyData) {
476
- const directRemaining = getFiniteNumber(keyData?.limit_remaining);
477
- if (directRemaining !== null) return directRemaining;
478
-
479
- const keyLimit = getFiniteNumber(keyData?.limit);
480
- const keyUsage = getFiniteNumber(keyData?.usage);
481
- if (keyLimit !== null && keyUsage !== null) {
482
- return Math.max(keyLimit - keyUsage, 0);
483
- }
484
-
485
- return null;
486
- }
487
-
488
- function isKeyExpired(value) {
489
- if (value === null || value === undefined || value === "") return false;
490
- const expiresDate = new Date(value);
491
- return Number.isFinite(expiresDate.getTime()) && expiresDate.getTime() <= Date.now();
492
- }
493
-
494
- function showAdminContactNotice(reason) {
495
- const messages = {
496
- expired: "API Key របស់អ្នកបានផុតកំណត់។ សូមទាក់ទង Admin ដើម្បីទិញ ឬបន្ត key។",
497
- credit: "Credit របស់ API Key អស់ហើយ។ សូមទាក់ទង Admin ដើម្បីទិញ credit ឬបន្ត key។"
498
- };
499
-
500
- adminNoticeTitle.textContent = reason === "expired" ? "API Key ផុតកំណត់" : "Credit អស់";
501
- adminNoticeMessage.textContent = `${messages[reason]} Email: ${adminContactEmail}. Phone: ${adminContactPhones}.`;
502
- adminNoticeModal.classList.remove('hidden');
503
- adminNoticeModal.classList.add('flex');
504
- }
505
-
506
- function hideAdminContactNotice() {
507
- adminNoticeModal.classList.add('hidden');
508
- adminNoticeModal.classList.remove('flex');
509
- }
510
-
511
- function checkKeyAccessNotice(keyData) {
512
- if (isKeyExpired(keyData?.expires_at)) {
513
- showAdminContactNotice("expired");
514
- return false;
515
- }
516
-
517
- const creditRemaining = getCreditRemaining(keyData);
518
- if (creditRemaining !== null && creditRemaining <= 0) {
519
- showAdminContactNotice("credit");
520
- return false;
521
- }
522
-
523
- hideAdminContactNotice();
524
- return true;
525
- }
526
-
527
- function isCreditError(error) {
528
- const message = String(error?.message || "").toLowerCase();
529
- return error?.status === 402
530
- || message.includes("credit")
531
- || message.includes("quota")
532
- || message.includes("insufficient")
533
- || message.includes("limit exceeded");
534
- }
535
-
536
- function formatTimeRemaining(targetDate) {
537
- const remainingMs = targetDate.getTime() - Date.now();
538
- if (remainingMs <= 0) return "Expired";
539
-
540
- const totalMinutes = Math.ceil(remainingMs / 60000);
541
- const days = Math.floor(totalMinutes / 1440);
542
- const hours = Math.floor((totalMinutes % 1440) / 60);
543
- const minutes = totalMinutes % 60;
544
-
545
- if (days >= 1) {
546
- return hours > 0 ? `${days}d ${hours}h left` : `${days}d left`;
547
- }
548
-
549
- if (hours >= 1) {
550
- return minutes > 0 ? `${hours}h ${minutes}m left` : `${hours}h left`;
551
- }
552
-
553
- return `${minutes}m left`;
554
- }
555
-
556
- function updateKeyExpiresStatus(value) {
557
- if (value === undefined) {
558
- keyExpiresStatus.textContent = "Expiration: --";
559
- keyExpiresStatus.removeAttribute("title");
560
- return;
561
- }
562
-
563
- if (value === null || value === "") {
564
- keyExpiresStatus.textContent = "Expiration: Never";
565
- keyExpiresStatus.removeAttribute("title");
566
- return;
567
- }
568
-
569
- const expiresDate = new Date(value);
570
- if (Number.isNaN(expiresDate.getTime())) {
571
- keyExpiresStatus.textContent = `Expiration: ${String(value)}`;
572
- keyExpiresStatus.title = String(value);
573
- return;
574
- }
575
-
576
- keyExpiresStatus.textContent = `Expiration: ${formatTimeRemaining(expiresDate)}`;
577
- keyExpiresStatus.title = expiresDate.toLocaleString();
578
- }
579
-
580
- function incrementRequestCount() {
581
- requestCount++;
582
- localStorage.setItem(requestCountStorageKey, String(requestCount));
583
- updateRequestCountStatus();
584
- }
585
-
586
- function setModelHelp(message, type = "neutral") {
587
- modelHelpText.textContent = message;
588
- modelHelpText.classList.remove('text-slate-500', 'text-emerald-300', 'text-red-300');
589
- if (type === "success") {
590
- modelHelpText.classList.add('text-emerald-300');
591
- } else if (type === "error") {
592
- modelHelpText.classList.add('text-red-300');
593
- } else {
594
- modelHelpText.classList.add('text-slate-500');
595
- }
596
- }
597
-
598
- function applyModelOptions(models) {
599
- let currentModel = selectedOpenRouterModel || defaultOpenRouterModel;
600
- const modelOptions = models.length ? models : [{
601
- id: defaultOpenRouterModel,
602
- name: "Google Gemini 2.5 Flash Image"
603
- }];
604
- let hasCurrentModel = modelOptions.some(model => model.id === currentModel);
605
-
606
- if (models.length && !hasCurrentModel) {
607
- currentModel = defaultOpenRouterModel;
608
- selectedOpenRouterModel = defaultOpenRouterModel;
609
- localStorage.setItem(selectedModelStorageKey, defaultOpenRouterModel);
610
- hasCurrentModel = modelOptions.some(model => model.id === currentModel);
611
- }
612
-
613
- modelSelect.innerHTML = modelOptions.map(model => `
614
- <option value="${escapeHtml(model.id)}">${escapeHtml(model.name || model.id)}</option>
615
- `).join('');
616
-
617
- if (!hasCurrentModel) {
618
- modelSelect.insertAdjacentHTML('afterbegin', `<option value="${escapeHtml(currentModel)}">${escapeHtml(currentModel)}</option>`);
619
- }
620
-
621
- modelSelect.value = currentModel;
622
- }
623
-
624
- function isImageToImageModel(model) {
625
- const inputModalities = model?.architecture?.input_modalities || [];
626
- const outputModalities = model?.architecture?.output_modalities || [];
627
- return inputModalities.includes("image") && outputModalities.includes("image");
628
- }
629
-
630
- async function loadImageModels(showToastOnSuccess = false) {
631
- setModelHelp("កំពុង load image models...");
632
-
633
- try {
634
- const data = await fetchOpenRouterJson(openRouterModelsEndpoint, getOpenRouterApiKey());
635
- const models = (data?.data || [])
636
- .filter(isImageToImageModel)
637
- .sort((first, second) => (first.name || first.id).localeCompare(second.name || second.id));
638
-
639
- applyModelOptions(models);
640
- setModelHelp(`បាន load image-capable models ចំនួន ${models.length}។`, "success");
641
- if (showToastOnSuccess) showToast("បាន load AI Models រួចរាល់!", "success");
642
- } catch (error) {
643
- console.error(error);
644
- applyModelOptions([]);
645
- setModelHelp("មិនអាច load models បាន។ ប្រើ default model សិន។", "error");
646
- }
647
- }
648
-
649
- apiKeyInput.addEventListener('input', () => {
650
- localStorage.setItem(apiKeyStorageKey, getOpenRouterApiKey());
651
- clearTimeout(balanceRefreshTimer);
652
- const openRouterApiKey = getOpenRouterApiKey();
653
- latestKeyData = null;
654
- customerStatus.textContent = openRouterApiKey ? "Customer: checking" : "Customer: --";
655
- if (!openRouterApiKey) hideAdminContactNotice();
656
- updateCreditLimitStatus(undefined);
657
- updateKeyExpiresStatus(undefined);
658
- if (openRouterApiKey.length > 20) {
659
- balanceRefreshTimer = setTimeout(() => refreshOpenRouterBalance(false), 900);
660
- }
661
- });
662
-
663
- apiKeyInput.addEventListener('blur', () => {
664
- if (getOpenRouterApiKey()) refreshOpenRouterBalance(false);
665
- });
666
-
667
- apiKeyInput.addEventListener('keydown', (event) => {
668
- if (event.key === 'Enter') {
669
- apiKeyInput.blur();
670
- }
671
- });
672
-
673
- toggleApiKeyBtn.addEventListener('click', () => {
674
- const shouldShow = apiKeyInput.type === 'password';
675
- apiKeyInput.type = shouldShow ? 'text' : 'password';
676
- toggleApiKeyIcon.className = shouldShow ? 'fa-solid fa-eye-slash' : 'fa-solid fa-eye';
677
- });
678
-
679
- refreshBalanceBtn.addEventListener('click', () => {
680
- refreshOpenRouterBalance(true);
681
- });
682
-
683
- modelSelect.addEventListener('change', () => {
684
- selectedOpenRouterModel = getSelectedOpenRouterModel();
685
- localStorage.setItem(selectedModelStorageKey, selectedOpenRouterModel);
686
- setModelHelp(`កំពុងប្រើ model: ${selectedOpenRouterModel}`);
687
- });
688
-
689
- reloadModelsBtn.addEventListener('click', () => {
690
- loadImageModels(true);
691
- });
692
-
693
- function formatCreditAmount(value) {
694
- return Number(value).toLocaleString(undefined, {
695
- minimumFractionDigits: 2,
696
- maximumFractionDigits: 2
697
- });
698
- }
699
-
700
- function getFiniteNumber(value) {
701
- if (value === null || value === undefined || value === "") return null;
702
- const numberValue = Number(value);
703
- return Number.isFinite(numberValue) ? numberValue : null;
704
- }
705
-
706
- async function fetchOpenRouterJson(url, openRouterApiKey) {
707
- const headers = {
708
- 'HTTP-Referer': window.location.origin === 'null' ? 'http://localhost' : window.location.origin,
709
- 'X-OpenRouter-Title': openRouterAppTitle
710
- };
711
-
712
- if (openRouterApiKey) {
713
- headers.Authorization = `Bearer ${openRouterApiKey}`;
714
- }
715
-
716
- const response = await fetch(url, {
717
- method: 'GET',
718
- headers
719
- });
720
- const responseText = await response.text();
721
- const data = responseText ? JSON.parse(responseText) : {};
722
-
723
- if (!response.ok) {
724
- const message = data?.error?.message || data?.message || responseText || `HTTP error! status: ${response.status}`;
725
- throw new Error(message);
726
- }
727
-
728
- return data;
729
- }
730
-
731
- async function refreshOpenRouterBalance(showToastOnSuccess = false) {
732
- const openRouterApiKey = getOpenRouterApiKey();
733
- if (!openRouterApiKey) {
734
- latestKeyData = null;
735
- hideAdminContactNotice();
736
- updateCustomerStatus(null);
737
- updateCreditLimitStatus(undefined);
738
- updateKeyExpiresStatus(undefined);
739
- return;
740
- }
741
-
742
- customerStatus.textContent = "Customer: checking";
743
- creditLimitStatus.textContent = "Credit limit: checking";
744
- creditLimitStatus.removeAttribute("title");
745
- keyExpiresStatus.textContent = "Expiration: checking";
746
-
747
- try {
748
- const keyInfo = await fetchOpenRouterJson(openRouterKeyEndpoint, openRouterApiKey);
749
- const keyData = keyInfo?.data || {};
750
- latestKeyData = keyData;
751
- updateCustomerStatus(keyData);
752
- const hasKeyCreditLimit = updateCreditLimitStatus(keyData.limit, keyData.limit_reset);
753
- if (!hasKeyCreditLimit) {
754
- updateWorkspaceCreditLimitStatus();
755
- }
756
- updateKeyExpiresStatus(keyData.expires_at);
757
- checkKeyAccessNotice(keyData);
758
-
759
- if (showToastOnSuccess) showToast("បានពិនិត្យ customer info រួចរាល់!", "success");
760
- } catch (error) {
761
- console.error(error);
762
- latestKeyData = null;
763
- customerStatus.textContent = "Customer: key error";
764
- updateCreditLimitStatus(undefined);
765
- updateKeyExpiresStatus(undefined);
766
- showToast("មិនអាចពិនិត្យ OpenRouter balance បានទេ។ សូមពិនិត្យ API Key។", "error");
767
- }
768
- }
769
-
770
- if (getOpenRouterApiKey()) {
771
- refreshOpenRouterBalance(false);
772
- }
773
-
774
- // Manage similarity configurations
775
- similarityBtns.forEach(btn => {
776
- btn.addEventListener('click', () => {
777
- similarityBtns.forEach(b => {
778
- b.classList.remove('active-style', 'border-indigo-500', 'text-indigo-400');
779
- b.classList.add('border-slate-700');
780
- });
781
- btn.classList.remove('border-slate-700');
782
- btn.classList.add('active-style', 'border-indigo-500', 'text-indigo-400');
783
- selectedSimilarity = btn.dataset.similarity;
784
- });
785
- });
786
-
787
- // Clone counter update
788
- cloneQuantity.addEventListener('input', (e) => {
789
- quantityVal.textContent = `${e.target.value} រូបភាព`;
790
- });
791
-
792
- // Drag and drop setup
793
- dropzone.addEventListener('click', (e) => {
794
- if (e.target.closest('button')) return;
795
- imageInput.click();
796
- });
797
-
798
- dropzone.addEventListener('dragover', (e) => {
799
- e.preventDefault();
800
- dropzone.classList.add('border-indigo-500', 'bg-indigo-500/5');
801
- });
802
-
803
- dropzone.addEventListener('dragleave', () => {
804
- dropzone.classList.remove('border-indigo-500', 'bg-indigo-500/5');
805
- });
806
-
807
- dropzone.addEventListener('drop', (e) => {
808
- e.preventDefault();
809
- dropzone.classList.remove('border-indigo-500', 'bg-indigo-500/5');
810
- if (e.dataTransfer.files.length) {
811
- handleImageFiles(Array.from(e.dataTransfer.files));
812
- }
813
- });
814
-
815
- imageInput.addEventListener('change', (e) => {
816
- if (e.target.files.length) {
817
- handleImageFiles(Array.from(e.target.files));
818
- }
819
- });
820
-
821
- removeImageBtn.addEventListener('click', (e) => {
822
- e.stopPropagation();
823
- resetUpload();
824
- });
825
-
826
- async function handleImageFiles(files) {
827
- const validFiles = [];
828
-
829
- files.forEach(file => {
830
- if (!supportedImageTypes.includes(file.type)) {
831
- showToast("មានឯកសារខ្លះមិនមែន PNG, JPG, WEBP ឬ GIF។ បានរំលងឯកសារទាំងនោះ។", "error");
832
- return;
833
- }
834
- if (file.size > 5 * 1024 * 1024) {
835
- showToast("មានរូបភាពខ្លះធំពេក។ សូមប្រើរូបនីមួយៗក្រោម 5MB។", "error");
836
- return;
837
- }
838
- validFiles.push(file);
839
- });
840
-
841
- if (!validFiles.length) return;
842
-
843
- try {
844
- const images = await Promise.all(validFiles.map(readImageFile));
845
- uploadedImages = uploadedImages.concat(images);
846
- imageInput.value = "";
847
- renderUploadedImages();
848
- showToast(`បានបញ្ចូលរូបដើម ${images.length} រូប។ សរុប ${uploadedImages.length} រូប។`, "success");
849
- } catch (error) {
850
- console.error(error);
851
- showToast("ការអានឯកសាររូបភាពមានបញ្ហា!", "error");
852
- }
853
- }
854
-
855
- function readImageFile(file) {
856
- return new Promise((resolve, reject) => {
857
- const reader = new FileReader();
858
- reader.readAsDataURL(file);
859
- reader.onload = () => {
860
- const dataUrl = reader.result;
861
- resolve({
862
- id: `${Date.now()}-${Math.random().toString(16).slice(2)}`,
863
- name: file.name,
864
- type: file.type,
865
- dataUrl,
866
- base64: dataUrl.split(',')[1]
867
- });
868
- };
869
- reader.onerror = reject;
870
- });
871
- }
872
-
873
- function escapeHtml(value) {
874
- return value.replace(/[&<>"']/g, char => ({
875
- '&': '&amp;',
876
- '<': '&lt;',
877
- '>': '&gt;',
878
- '"': '&quot;',
879
- "'": '&#039;'
880
- }[char]));
881
- }
882
-
883
- applyModelOptions([]);
884
- loadImageModels(false);
885
-
886
- function renderUploadedImages() {
887
- if (!uploadedImages.length) {
888
- imagePreviewGrid.innerHTML = "";
889
- selectedImagesCount.textContent = "0 រូបដើម";
890
- uploadPlaceholder.classList.remove('hidden');
891
- imagePreviewContainer.classList.add('hidden');
892
- generateBtn.setAttribute('disabled', 'true');
893
- return;
894
- }
895
-
896
- selectedImagesCount.textContent = `${uploadedImages.length} រូបដើម`;
897
- imagePreviewGrid.innerHTML = uploadedImages.map((image, index) => `
898
- <div class="relative rounded-lg overflow-hidden border border-slate-700 bg-slate-950/60 h-28 group/source">
899
- <img src="${image.dataUrl}" alt="${escapeHtml(image.name)}" class="w-full h-full object-cover">
900
- <button type="button" onclick="event.stopPropagation(); removeUploadedImage('${image.id}')" class="icon-pop-3d absolute top-2 right-2 bg-red-500/85 hover:bg-red-600 text-white w-7 h-7 rounded-lg transition-colors flex items-center justify-center opacity-100 sm:opacity-0 sm:group-hover/source:opacity-100" title="លុបរូបនេះ">
901
- <i class="fa-solid fa-xmark text-xs"></i>
902
- </button>
903
- <div class="absolute left-2 bottom-2 max-w-[calc(100%-1rem)] text-[10px] text-white bg-slate-950/70 px-2 py-1 rounded-md truncate">#${index + 1} ${escapeHtml(image.name)}</div>
904
- </div>
905
- `).join('');
906
- uploadPlaceholder.classList.add('hidden');
907
- imagePreviewContainer.classList.remove('hidden');
908
- generateBtn.removeAttribute('disabled');
909
- }
910
-
911
- window.removeUploadedImage = function(imageId) {
912
- uploadedImages = uploadedImages.filter(image => image.id !== imageId);
913
- renderUploadedImages();
914
- };
915
-
916
- function resetUpload() {
917
- uploadedImages = [];
918
- imageInput.value = "";
919
- renderUploadedImages();
920
- }
921
-
922
- // Beautiful toast handler
923
- function showToast(message, type = "error") {
924
- toastMessage.textContent = message;
925
- if (type === "success") {
926
- toast.firstElementChild.className = "bg-emerald-500/90 text-white p-4 rounded-xl shadow-2xl backdrop-blur flex items-center gap-3 border border-emerald-400/20";
927
- toastIcon.className = "fa-solid fa-circle-check text-xl";
928
- } else {
929
- toast.firstElementChild.className = "bg-red-500/90 text-white p-4 rounded-xl shadow-2xl backdrop-blur flex items-center gap-3 border border-red-400/20";
930
- toastIcon.className = "fa-solid fa-circle-exclamation text-xl";
931
- }
932
- toast.classList.remove('translate-y-20', 'opacity-0');
933
-
934
- setTimeout(() => {
935
- toast.classList.add('translate-y-20', 'opacity-0');
936
- }, 4000);
937
- }
938
-
939
- // Exponential backoff mechanism
940
- async function fetchWithRetry(url, options, retries = 3, delay = 1200) {
941
- try {
942
- incrementRequestCount();
943
- const response = await fetch(url, options);
944
- const responseText = await response.text();
945
- let data = {};
946
-
947
- try {
948
- data = responseText ? JSON.parse(responseText) : {};
949
- } catch (parseError) {
950
- if (response.ok) throw parseError;
951
- }
952
-
953
- if (!response.ok) {
954
- const message = data?.error?.message || data?.message || responseText || `HTTP error! status: ${response.status}`;
955
- const error = new Error(`OpenRouter API error (${response.status}): ${message}`);
956
- error.status = response.status;
957
- throw error;
958
- }
959
-
960
- return data;
961
- } catch (error) {
962
- const canRetry = !error.status || error.status === 429 || error.status >= 500;
963
- if (retries > 0 && canRetry) {
964
- await new Promise(resolve => setTimeout(resolve, delay));
965
- return fetchWithRetry(url, options, retries - 1, delay * 2);
966
- }
967
- throw error;
968
- }
969
- }
970
-
971
- // Open optimized preview modal
972
- window.openPreviewModal = function(imageSrc, index = 1) {
973
- modalTargetImg.src = imageSrc;
974
- modalDownloadBtn.href = imageSrc;
975
- modalDownloadBtn.download = `cloned_image_${index}.png`;
976
-
977
- if (isIOS) {
978
- iosInstruction.classList.remove('hidden');
979
- standardDownloadBtnContainer.classList.add('hidden');
980
- } else {
981
- iosInstruction.classList.add('hidden');
982
- standardDownloadBtnContainer.classList.remove('hidden');
983
- }
984
-
985
- previewModal.classList.remove('hidden');
986
- previewModal.classList.add('flex');
987
- };
988
-
989
- closeModalBtn.addEventListener('click', () => {
990
- previewModal.classList.add('hidden');
991
- previewModal.classList.remove('flex');
992
- });
993
-
994
- adminNoticeCloseBtn.addEventListener('click', hideAdminContactNotice);
995
-
996
- // Smart downloader
997
- window.downloadImage = function(src, index) {
998
- if (isIOS) {
999
- openPreviewModal(src, index);
1000
- } else {
1001
- const link = document.createElement('a');
1002
- link.href = src;
1003
- link.download = `cloned_image_${index}.png`;
1004
- document.body.appendChild(link);
1005
- link.click();
1006
- link.remove();
1007
- }
1008
- };
1009
-
1010
- // Main Image Clone Process
1011
- generateBtn.addEventListener('click', async () => {
1012
- if (!uploadedImages.length) return;
1013
- const openRouterApiKey = getOpenRouterApiKey();
1014
- if (!openRouterApiKey) {
1015
- showToast("សូមបញ្ចូល OpenRouter API Key មុនពេលក្លូនរូបភាព!", "error");
1016
- return;
1017
- }
1018
-
1019
- try {
1020
- const keyInfo = await fetchOpenRouterJson(openRouterKeyEndpoint, openRouterApiKey);
1021
- const keyData = keyInfo?.data || {};
1022
- latestKeyData = keyData;
1023
- updateCustomerStatus(keyData);
1024
- const hasKeyCreditLimit = updateCreditLimitStatus(keyData.limit, keyData.limit_reset);
1025
- if (!hasKeyCreditLimit) {
1026
- updateWorkspaceCreditLimitStatus();
1027
- }
1028
- updateKeyExpiresStatus(keyData.expires_at);
1029
- if (!checkKeyAccessNotice(keyData)) return;
1030
- } catch (error) {
1031
- console.error(error);
1032
- showToast("មិនអាចពិនិត្យស្ថានភាព API Key បានទេ។ សូមពិនិត្យ Key ម្តងទៀត។", "error");
1033
- return;
1034
- }
1035
-
1036
- const countPerSource = parseInt(cloneQuantity.value);
1037
- const totalCloneCount = uploadedImages.length * countPerSource;
1038
- const extraPrompt = promptModifier.value.trim();
1039
-
1040
- // Set up gallery layout
1041
- galleryEmptyState.classList.add('hidden');
1042
- clonesGrid.classList.remove('hidden');
1043
- clonesGrid.innerHTML = '';
1044
- downloadAllBtn.classList.add('hidden');
1045
- galleryContainer.className = "flex-grow p-4 border border-dashed border-slate-800 rounded-xl bg-slate-950/20";
1046
-
1047
- generatedImagesArray = [];
1048
-
1049
- // Add skeletons
1050
- for (let i = 1; i <= totalCloneCount; i++) {
1051
- clonesGrid.innerHTML += `
1052
- <div id="clone-card-${i}" class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-lg p-4 flex flex-col justify-between min-h-[320px]">
1053
- <div class="relative flex-grow flex items-center justify-center bg-slate-950/40 rounded-lg overflow-hidden h-52">
1054
- <div class="text-center space-y-3">
1055
- <i class="fa-solid fa-spinner animate-spin text-3xl text-indigo-400"></i>
1056
- <p class="text-xs text-slate-400 tracking-wide">កំពុងក្លូនរូបភាពទី ${i}...</p>
1057
- </div>
1058
- </div>
1059
- <div class="mt-4 flex justify-between items-center">
1060
- <span class="text-xs text-indigo-400 bg-indigo-500/10 px-2.5 py-1 rounded-full font-semibold border border-indigo-500/10">រូបភាពក្លូន #${i}</span>
1061
- <button disabled class="btn-pop-3d opacity-50 text-slate-400 bg-slate-800 px-3 py-1.5 rounded-lg text-xs flex items-center gap-1.5 cursor-not-allowed">
1062
- <i class="fa-solid fa-spinner animate-spin"></i> រង់ចាំ
1063
- </button>
1064
- </div>
1065
- </div>
1066
- `;
1067
- }
1068
-
1069
- generateBtn.setAttribute('disabled', 'true');
1070
- generateBtn.innerHTML = `<i class="fa-solid fa-spinner animate-spin"></i> កំពុងដំណើរការក្លូន...`;
1071
-
1072
- try {
1073
- let basePrompt = "Generate a visually similar, high-quality variation of this image. Preserve the central subject, composition, color palette, and general details to make it look like an authentic duplicate clone.";
1074
- if (selectedSimilarity === "medium") {
1075
- basePrompt = "Create a modern, creative alternative clone of this image. Keep the main core subject but alter small elements, lighting, or the surrounding background slightly for a unique variation.";
1076
- } else if (selectedSimilarity === "creative") {
1077
- basePrompt = "Use this image as a structural inspiration to create a brand new, artistically distinct clone. Keep only the basic idea or composition while applying a fresh visual style, dynamic range, and imaginative background changes.";
1078
- }
1079
-
1080
- if (extraPrompt) {
1081
- basePrompt += ` Additionally, incorporate the following creative direction requested by the user: ${extraPrompt}.`;
1082
- }
1083
-
1084
- // Execute clones sequentially for mobile stability
1085
- let cloneIndex = 1;
1086
- for (let sourceIndex = 0; sourceIndex < uploadedImages.length; sourceIndex++) {
1087
- const sourceImage = uploadedImages[sourceIndex];
1088
- for (let sourceCloneIndex = 1; sourceCloneIndex <= countPerSource; sourceCloneIndex++) {
1089
- await generateSingleClone(cloneIndex, basePrompt, sourceImage, openRouterApiKey, sourceIndex + 1, sourceCloneIndex);
1090
- cloneIndex++;
1091
- }
1092
- }
1093
-
1094
- if (generatedImagesArray.length > 0) {
1095
- downloadAllBtn.classList.remove('hidden');
1096
- if (isIOS) {
1097
- showToast("ក្លូនបានជោគជ័យ! ចុចលើរូបនីមួយៗដើម្បី 'រក្សាទុក' ទៅ iPhone។", "success");
1098
- } else {
1099
- showToast(`ការក្លូនបានជោគជ័យចំនួន ${generatedImagesArray.length} រូបភាព!`, "success");
1100
- }
1101
- } else {
1102
- showToast("ការក្លូនរូបភាពមានបញ្ហា! សូមពិនិត្យ Model ឬ API Key។", "error");
1103
- }
1104
- } catch (error) {
1105
- console.error(error);
1106
- if (isCreditError(error)) {
1107
- showAdminContactNotice("credit");
1108
- }
1109
- showToast(error.message || "ការក្លូនមានបញ្ហា។ សូមពិនិត្យ Model ឬ API Key។", "error");
1110
- } finally {
1111
- generateBtn.removeAttribute('disabled');
1112
- generateBtn.innerHTML = `<i class="fa-solid fa-bolt"></i> ចាប់ផ្តើមក្លូនរ���បភាព`;
1113
- refreshOpenRouterBalance(false);
1114
- }
1115
- });
1116
-
1117
- // Singular Clone Processor
1118
- async function generateSingleClone(index, prompt, sourceImage, openRouterApiKey, sourceNumber, sourceCloneNumber) {
1119
- const card = document.getElementById(`clone-card-${index}`);
1120
-
1121
- try {
1122
- const uniquePrompt = prompt + ` [Source image: ${sourceNumber}. Clone variation: ${sourceCloneNumber}. Make this clone variation distinct and unique to index: ${index + Math.random()}]`;
1123
- const imageDataUrl = `data:${sourceImage.type};base64,${sourceImage.base64}`;
1124
- const payload = {
1125
- model: getSelectedOpenRouterModel(),
1126
- messages: [{
1127
- role: "user",
1128
- content: [
1129
- {
1130
- type: "text",
1131
- text: uniquePrompt
1132
- },
1133
- {
1134
- type: "image_url",
1135
- image_url: {
1136
- url: imageDataUrl
1137
- }
1138
- }
1139
- ]
1140
- }],
1141
- modalities: ["image", "text"],
1142
- image_config: {
1143
- aspect_ratio: "1:1"
1144
- },
1145
- stream: false
1146
- };
1147
-
1148
- const data = await fetchWithRetry(openRouterEndpoint, {
1149
- method: 'POST',
1150
- headers: {
1151
- 'Authorization': `Bearer ${openRouterApiKey}`,
1152
- 'Content-Type': 'application/json',
1153
- 'HTTP-Referer': window.location.origin === 'null' ? 'http://localhost' : window.location.origin,
1154
- 'X-OpenRouter-Title': openRouterAppTitle
1155
- },
1156
- body: JSON.stringify(payload)
1157
- });
1158
-
1159
- const generatedImage = data.choices?.[0]?.message?.images?.[0];
1160
- const imageUrl = generatedImage?.image_url?.url || generatedImage?.imageUrl?.url;
1161
-
1162
- if (!imageUrl) {
1163
- throw new Error("OpenRouter returned a response without image data.");
1164
- }
1165
-
1166
- const finalImageSrc = imageUrl.startsWith('data:') ? imageUrl : `data:image/png;base64,${imageUrl}`;
1167
- generatedImagesArray.push(finalImageSrc);
1168
-
1169
- card.innerHTML = `
1170
- <div onclick="openPreviewModal('${finalImageSrc}', ${index})" class="relative flex-grow flex items-center justify-center bg-slate-950/40 rounded-lg overflow-hidden h-52 group/item cursor-pointer">
1171
- <img src="${finalImageSrc}" alt="Cloned Image ${index}" class="cloned-success-img w-full h-full object-cover">
1172
- <div class="absolute inset-0 bg-slate-950/40 opacity-0 group-hover/item:opacity-100 transition-opacity flex items-center justify-center">
1173
- <span class="bg-indigo-600/90 text-white text-xs px-3 py-1.5 rounded-lg flex items-center gap-1">
1174
- <i class="fa-solid fa-magnifying-glass-plus"></i> មើលរូបធំ
1175
- </span>
1176
- </div>
1177
- </div>
1178
- <div class="mt-4 flex justify-between items-center">
1179
- <span class="text-xs text-indigo-400 bg-indigo-500/10 px-2.5 py-1 rounded-full font-semibold border border-indigo-500/10">រូបដើម #${sourceNumber} • ក្លូន #${sourceCloneNumber}</span>
1180
- <button onclick="downloadImage('${finalImageSrc}', ${index})" class="btn-pop-3d text-xs text-white bg-indigo-600 hover:bg-indigo-700 px-3 py-1.5 rounded-lg flex items-center gap-1.5 transition-colors">
1181
- <i class="fa-solid fa-download"></i> ទាញយក
1182
- </button>
1183
- </div>
1184
- `;
1185
-
1186
- } catch (error) {
1187
- console.error(error);
1188
- if (isCreditError(error)) {
1189
- showAdminContactNotice("credit");
1190
- }
1191
- const shortError = escapeHtml((error.message || "API request failed").slice(0, 120));
1192
- card.innerHTML = `
1193
- <div class="relative flex-grow flex items-center justify-center bg-red-950/20 border border-red-900/30 rounded-lg h-52">
1194
- <div class="text-center p-4">
1195
- <i class="fa-solid fa-triangle-exclamation text-2xl text-red-500 mb-2"></i>
1196
- <p class="text-xs text-red-400 font-semibold">បរាជ័យក្នុងការក្លូន</p>
1197
- <p class="text-[9px] text-slate-500 mt-1 break-words">${shortError}</p>
1198
- </div>
1199
- </div>
1200
- <div class="mt-4 flex justify-between items-center">
1201
- <span class="text-xs text-red-500/50 bg-red-500/5 px-2.5 py-1 rounded-full font-semibold border border-red-500/10">រូបដើម #${sourceNumber} • ក្លូន #${sourceCloneNumber}</span>
1202
- <button disabled class="btn-pop-3d opacity-40 text-slate-500 bg-slate-800 px-3 py-1.5 rounded-lg text-xs cursor-not-allowed">
1203
- <i class="fa-solid fa-ban"></i> បរាជ័យ
1204
- </button>
1205
- </div>
1206
- `;
1207
- }
1208
- }
1209
-
1210
- // Master downloader
1211
- downloadAllBtn.addEventListener('click', () => {
1212
- if (isIOS) {
1213
- showToast("សម្រាប់ iPhone៖ សូមចុចលើរូបនីមួយៗ រួចសង្កត់ដើម្បីរក្សាទុកក្នុងទូរសព្ទ។", "success");
1214
- return;
1215
- }
1216
-
1217
- const successImages = document.querySelectorAll('.cloned-success-img');
1218
- successImages.forEach((img, i) => {
1219
- setTimeout(() => {
1220
- const link = document.createElement('a');
1221
- link.href = img.src;
1222
- link.download = `cloned_image_${i + 1}.png`;
1223
- document.body.appendChild(link);
1224
- link.click();
1225
- link.remove();
1226
- }, i * 300);
1227
- });
1228
- showToast("កំពុងទាញយករូបភាពទាំងអស់...", "success");
1229
- });
1230
- </script>
1231
- </body>
1232
- </html>