Elias207 commited on
Commit
760160a
·
verified ·
1 Parent(s): 9845856

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +122 -11
index.html CHANGED
@@ -3,7 +3,7 @@
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>AI Photoshop Pro</title>
7
  <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
8
  <style>
9
  :root {
@@ -257,9 +257,9 @@
257
  100% { width: 100%; }
258
  }
259
 
260
- #result-grid { display: none; grid-template-columns: repeat(2, 1fr); gap: 1.5rem; width: 100%; }
261
  #result-container.has-content #result-grid { display: grid; }
262
- #result-grid img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; border-radius: var(--radius-input); cursor: pointer; transition: var(--transition-smooth); box-shadow: var(--shadow-md); border: 1px solid var(--panel-border); }
263
  #result-grid img:hover { transform: scale(1.05); box-shadow: var(--shadow-lg); z-index: 10; position: relative; }
264
  #error-message { color: var(--danger-color); text-align: center; margin-top: 1rem; display: none; font-weight: 500; }
265
 
@@ -272,20 +272,19 @@
272
  #history-grid:empty::before { content: 'هنوز تصویری خلق نکرده‌اید. اولین ویرایش شما اینجا ذخیره خواهد شد.'; color: var(--text-secondary); grid-column: 1 / -1; text-align: center; padding: 3rem 1rem; background-color: var(--input-bg); border-radius: var(--radius-card); }
273
  .history-item { position: relative; background-color: var(--input-bg); border-radius: var(--radius-card); border: 1px solid var(--panel-border); padding: 1rem; transition: var(--transition-smooth); }
274
  .history-item:hover { transform: translateY(-5px); box-shadow: var(--shadow-lg); }
275
- .history-item-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 0.75rem; }
276
  .history-item-grid img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; border-radius: var(--radius-input); cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; border: 1px solid var(--panel-border); }
277
  .history-item-grid img:hover { transform: scale(1.1); box-shadow: var(--shadow-md); z-index: 5; position: relative; }
278
  .history-delete-btn { position: absolute; top: 0.75rem; right: 0.75rem; background: none; border: none; cursor: pointer; padding: 0.5rem; border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; color: var(--text-tertiary); transition: var(--transition-smooth); z-index: 5; }
279
  .history-delete-btn:hover { background-color: var(--panel-border); color: var(--danger-color); }
280
  .history-delete-btn svg { width: 18px; height: 18px; }
281
 
282
- /* --- FIX: Corrected Lightbox CSS --- */
283
  #lightbox {
284
  position: fixed;
285
  inset: 0;
286
  background-color: rgba(18, 24, 38, 0.6);
287
  backdrop-filter: blur(10px) saturate(150%);
288
- display: flex; /* Changed from none to flex */
289
  align-items: center;
290
  justify-content: center;
291
  z-index: 1000;
@@ -297,8 +296,6 @@
297
  opacity: 1;
298
  pointer-events: auto;
299
  }
300
- /* --- END OF FIX --- */
301
-
302
  #lightbox-content { position: relative; animation: fadeIn 0.3s ease; display: flex; align-items: center; justify-content: center; }
303
  #lightbox-img { max-width: 85vw; max-height: 80vh; object-fit: contain; border-radius: var(--radius-card); box-shadow: var(--shadow-xl); }
304
  .lightbox-btn { position: absolute; background-color: rgba(255, 255, 255, 0.1); color: white; border: 1px solid rgba(255,255,255,0.2); width: 44px; height: 44px; border-radius: 50%; cursor: pointer; display: flex; justify-content: center; align-items: center; transition: all 0.2s; text-decoration: none; font-size: 24px; }
@@ -443,10 +440,13 @@
443
  </div>
444
 
445
  <script>
446
- // --- START OF APPLICATION LOGIC SCRIPT (No changes needed here) ---
447
- const API_URL = 'https://alfa-editor-worker.onrender.com/api/edit';
 
448
  const uploadArea = document.getElementById('upload-area'); const fileInput = document.getElementById('file-input'); const previewImage = document.getElementById('preview-image-main'); const removeFileBtn = document.getElementById('remove-file-btn-main'); const promptInput = document.getElementById('prompt-input'); const submitBtn = document.getElementById('submit-btn'); const resultContainer = document.getElementById('result-container'); const resultGrid = document.getElementById('result-grid'); const errorMessage = document.getElementById('error-message'); const lightbox = document.getElementById('lightbox'); const lightboxImg = document.getElementById('lightbox-img'); const lightboxClose = document.getElementById('lightbox-close'); const lightboxDownload = document.getElementById('lightbox-download'); const lightboxNext = document.getElementById('lightbox-next'); const historyGrid = document.getElementById('history-grid'); const clearHistoryBtn = document.getElementById('clear-history-btn'); const confirmationModal = document.getElementById('confirmation-modal'); const modalMessageText = document.getElementById('modal-message-text'); const modalConfirmBtn = document.getElementById('modal-confirm-btn'); const modalCancelBtn = document.getElementById('modal-cancel-btn');
449
  let uploadedFile = null; let currentLightboxUrl = null; let currentLightboxGroup = []; let currentLightboxIndex = 0;
 
 
450
  const convertToPNG = (file) => {
451
  return new Promise((resolve, reject) => {
452
  const image = new Image();
@@ -498,9 +498,120 @@
498
  clearResult();
499
  };
500
  const showConfirmationModal = (message, onConfirm) => { modalMessageText.textContent = message; confirmationModal.classList.add('visible'); modalConfirmBtn.onclick = () => { onConfirm(); hideConfirmationModal(); }; modalCancelBtn.onclick = () => { hideConfirmationModal(); }; }; const hideConfirmationModal = () => { confirmationModal.classList.remove('visible'); modalConfirmBtn.onclick = null; modalCancelBtn.onclick = null; }; const resetUploader = () => { uploadedFile = null; fileInput.value = ''; previewImage.src = ''; uploadArea.classList.remove('has-file'); checkFormState(); }; const checkFormState = () => { submitBtn.disabled = !uploadedFile || promptInput.value.trim() === ''; }; const setLoading = (isLoading) => { const btnSpinner = submitBtn.querySelector('.spinner'); const btnText = document.getElementById('btn-text'); const btnIcon = submitBtn.querySelector('svg'); if (isLoading) { resultContainer.classList.remove('has-content'); resultContainer.classList.add('loading'); btnSpinner.style.display = 'inline-block'; btnIcon.style.display = 'none'; btnText.textContent = 'در حال پردازش...'; submitBtn.disabled = true; resultGrid.innerHTML = ''; errorMessage.style.display = 'none'; } else { resultContainer.classList.remove('loading'); btnSpinner.style.display = 'none'; btnIcon.style.display = 'inline-block'; btnText.textContent = 'ایجاد کن'; checkFormState(); } }; const displayResult = (imageUrls) => { resultGrid.innerHTML = ''; imageUrls.forEach((url) => { const img = document.createElement('img'); img.src = url; img.alt = 'تصویر ویرایش شده'; img.addEventListener('click', () => openLightbox(url, imageUrls)); resultGrid.appendChild(img); }); resultContainer.classList.add('has-content'); }; const clearResult = () => { resultGrid.innerHTML = ''; errorMessage.style.display = 'none'; resultContainer.classList.remove('has-content'); }; const displayError = (message) => { errorMessage.textContent = message; errorMessage.style.display = 'block'; }; const updateLightboxImage = () => { const newUrl = currentLightboxGroup[currentLightboxIndex]; lightboxImg.src = newUrl; currentLightboxUrl = newUrl; }; const openLightbox = (clickedUrl, urlGroup) => { currentLightboxGroup = urlGroup; currentLightboxIndex = urlGroup.indexOf(clickedUrl); updateLightboxImage(); lightboxNext.style.display = urlGroup.length > 1 ? 'flex' : 'none'; lightbox.classList.add('visible'); }; const closeLightbox = () => { lightbox.classList.remove('visible'); currentLightboxGroup = []; }; const handleDownload = async () => { if (!currentLightboxUrl) return; const spinner = lightboxDownload.querySelector('.spinner'); const icon = lightboxDownload.querySelector('svg'); spinner.style.display = 'block'; icon.style.display = 'none'; lightboxDownload.disabled = true; try { const response = await fetch(currentLightboxUrl); if (!response.ok) throw new Error('Network response was not ok.'); const blob = await response.blob(); const objectUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = objectUrl; a.download = `ai-edited-image-${Date.now()}.png`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(objectUrl); } catch (e) { console.error('Download failed:', e); alert('خطا در دانلود تصویر. لطفا دوباره تلاش کنید.'); } finally { spinner.style.display = 'none'; icon.style.display = 'block'; lightboxDownload.disabled = false; } }; const getHistory = () => JSON.parse(localStorage.getItem('aiPhotoshopHistory') || '[]'); const saveHistory = (history) => { localStorage.setItem('aiPhotoshopHistory', JSON.stringify(history)); renderHistory(); }; const addToHistory = (item) => { let history = getHistory(); history.unshift(item); if (history.length > 15) history.pop(); saveHistory(history); }; const handleClearHistory = () => { showConfirmationModal('آیا از پاک کردن تمام تاریخچه مطمئن هستید؟ این عمل غیرقابل بازگشت است.', () => { saveHistory([]); }); }; const handleDeleteItem = (index) => { showConfirmationModal('آیا از حذف این مورد از تاریخچه مطمئن هستید؟', () => { let history = getHistory(); history.splice(index, 1); saveHistory(history); }); }; const renderHistory = () => { const history = getHistory(); historyGrid.innerHTML = ''; clearHistoryBtn.style.display = history.length > 0 ? 'flex' : 'none'; history.forEach((item, index) => { const card = document.createElement('div'); card.className = 'history-item'; const deleteBtn = document.createElement('button'); deleteBtn.className = 'history-delete-btn'; deleteBtn.title = 'حذف این مورد'; deleteBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`; deleteBtn.onclick = () => handleDeleteItem(index); card.appendChild(deleteBtn); const imageGrid = document.createElement('div'); imageGrid.className = 'history-item-grid'; item.urls.forEach(url => { const img = document.createElement('img'); img.src = url; img.alt = 'تصویر از تاریخچه'; img.addEventListener('click', () => openLightbox(url, item.urls)); imageGrid.appendChild(img); }); card.appendChild(imageGrid); historyGrid.appendChild(card); }); };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
501
  document.addEventListener('DOMContentLoaded', () => { renderHistory(); checkFormState(); });
502
  removeFileBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); resetUploader(); }); fileInput.addEventListener('change', (e) => handleFile(e.target.files[0])); ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, p => { p.preventDefault(); p.stopPropagation(); }); }); ['dragenter', 'dragover'].forEach(e => { uploadArea.addEventListener(e, () => { if (!uploadArea.classList.contains('has-file')) uploadArea.classList.add('drag-over'); }); }); ['dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, () => uploadArea.classList.remove('drag-over')); }); uploadArea.addEventListener('drop', e => { if (!uploadArea.classList.contains('has-file')) handleFile(e.dataTransfer.files[0]); }); promptInput.addEventListener('input', checkFormState);
503
- submitBtn.addEventListener('click', async () => { if (submitBtn.disabled) return; setLoading(true); const formData = new FormData(); formData.append('image', uploadedFile); formData.append('prompt', promptInput.value.trim()); try { const response = await fetch(API_URL, { method: 'POST', body: formData }); if (!response.ok) { const errorData = await response.json().catch(() => ({ error: `خطای سرور: ${response.statusText}` })); throw new Error(errorData.error || `یک خطای ناشناخته رخ داد.`); } const result = await response.json(); if (result.image_urls && Array.isArray(result.image_urls) && result.image_urls.length > 0) { displayResult(result.image_urls); addToHistory({ prompt: promptInput.value.trim(), urls: result.image_urls }); } else { throw new Error('پاسخ معتبری از سرور دریافت نشد.'); } } catch (error) { displayError(error.message); } finally { setLoading(false); } });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
504
  lightboxClose.addEventListener('click', closeLightbox); lightbox.addEventListener('click', (e) => { if (e.target === lightbox) closeLightbox(); }); lightboxDownload.addEventListener('click', handleDownload); lightboxNext.addEventListener('click', () => { currentLightboxIndex = (currentLightboxIndex + 1) % currentLightboxGroup.length; updateLightboxImage(); }); clearHistoryBtn.addEventListener('click', handleClearHistory);
505
  </script>
506
 
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>AI Photoshop Pro (Nano Banana Edition)</title>
7
  <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
8
  <style>
9
  :root {
 
257
  100% { width: 100%; }
258
  }
259
 
260
+ #result-grid { display: none; grid-template-columns: 1fr; /* Changed for single result */ gap: 1.5rem; width: 100%; justify-items: center; }
261
  #result-container.has-content #result-grid { display: grid; }
262
+ #result-grid img { max-width: 100%; max-height: 400px; /* Added for better display */ width: auto; height: auto; object-fit: contain; border-radius: var(--radius-input); cursor: pointer; transition: var(--transition-smooth); box-shadow: var(--shadow-md); border: 1px solid var(--panel-border); }
263
  #result-grid img:hover { transform: scale(1.05); box-shadow: var(--shadow-lg); z-index: 10; position: relative; }
264
  #error-message { color: var(--danger-color); text-align: center; margin-top: 1rem; display: none; font-weight: 500; }
265
 
 
272
  #history-grid:empty::before { content: 'هنوز تصویری خلق نکرده‌اید. اولین ویرایش شما اینجا ذخیره خواهد شد.'; color: var(--text-secondary); grid-column: 1 / -1; text-align: center; padding: 3rem 1rem; background-color: var(--input-bg); border-radius: var(--radius-card); }
273
  .history-item { position: relative; background-color: var(--input-bg); border-radius: var(--radius-card); border: 1px solid var(--panel-border); padding: 1rem; transition: var(--transition-smooth); }
274
  .history-item:hover { transform: translateY(-5px); box-shadow: var(--shadow-lg); }
275
+ .history-item-grid { display: grid; grid-template-columns: 1fr; /* Changed for single result */ gap: 0.75rem; }
276
  .history-item-grid img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; border-radius: var(--radius-input); cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; border: 1px solid var(--panel-border); }
277
  .history-item-grid img:hover { transform: scale(1.1); box-shadow: var(--shadow-md); z-index: 5; position: relative; }
278
  .history-delete-btn { position: absolute; top: 0.75rem; right: 0.75rem; background: none; border: none; cursor: pointer; padding: 0.5rem; border-radius: 50%; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; color: var(--text-tertiary); transition: var(--transition-smooth); z-index: 5; }
279
  .history-delete-btn:hover { background-color: var(--panel-border); color: var(--danger-color); }
280
  .history-delete-btn svg { width: 18px; height: 18px; }
281
 
 
282
  #lightbox {
283
  position: fixed;
284
  inset: 0;
285
  background-color: rgba(18, 24, 38, 0.6);
286
  backdrop-filter: blur(10px) saturate(150%);
287
+ display: flex;
288
  align-items: center;
289
  justify-content: center;
290
  z-index: 1000;
 
296
  opacity: 1;
297
  pointer-events: auto;
298
  }
 
 
299
  #lightbox-content { position: relative; animation: fadeIn 0.3s ease; display: flex; align-items: center; justify-content: center; }
300
  #lightbox-img { max-width: 85vw; max-height: 80vh; object-fit: contain; border-radius: var(--radius-card); box-shadow: var(--shadow-xl); }
301
  .lightbox-btn { position: absolute; background-color: rgba(255, 255, 255, 0.1); color: white; border: 1px solid rgba(255,255,255,0.2); width: 44px; height: 44px; border-radius: 50%; cursor: pointer; display: flex; justify-content: center; align-items: center; transition: all 0.2s; text-decoration: none; font-size: 24px; }
 
440
  </div>
441
 
442
  <script>
443
+ // --- START OF MODIFIED APPLICATION LOGIC SCRIPT ---
444
+ const API_BASE_URL = "https://ginigen-nano-banana-video.hf.space/gradio_api/";
445
+
446
  const uploadArea = document.getElementById('upload-area'); const fileInput = document.getElementById('file-input'); const previewImage = document.getElementById('preview-image-main'); const removeFileBtn = document.getElementById('remove-file-btn-main'); const promptInput = document.getElementById('prompt-input'); const submitBtn = document.getElementById('submit-btn'); const resultContainer = document.getElementById('result-container'); const resultGrid = document.getElementById('result-grid'); const errorMessage = document.getElementById('error-message'); const lightbox = document.getElementById('lightbox'); const lightboxImg = document.getElementById('lightbox-img'); const lightboxClose = document.getElementById('lightbox-close'); const lightboxDownload = document.getElementById('lightbox-download'); const lightboxNext = document.getElementById('lightbox-next'); const historyGrid = document.getElementById('history-grid'); const clearHistoryBtn = document.getElementById('clear-history-btn'); const confirmationModal = document.getElementById('confirmation-modal'); const modalMessageText = document.getElementById('modal-message-text'); const modalConfirmBtn = document.getElementById('modal-confirm-btn'); const modalCancelBtn = document.getElementById('modal-cancel-btn');
447
  let uploadedFile = null; let currentLightboxUrl = null; let currentLightboxGroup = []; let currentLightboxIndex = 0;
448
+
449
+ // --- ORIGINAL HELPER FUNCTIONS (UNCHANGED) ---
450
  const convertToPNG = (file) => {
451
  return new Promise((resolve, reject) => {
452
  const image = new Image();
 
498
  clearResult();
499
  };
500
  const showConfirmationModal = (message, onConfirm) => { modalMessageText.textContent = message; confirmationModal.classList.add('visible'); modalConfirmBtn.onclick = () => { onConfirm(); hideConfirmationModal(); }; modalCancelBtn.onclick = () => { hideConfirmationModal(); }; }; const hideConfirmationModal = () => { confirmationModal.classList.remove('visible'); modalConfirmBtn.onclick = null; modalCancelBtn.onclick = null; }; const resetUploader = () => { uploadedFile = null; fileInput.value = ''; previewImage.src = ''; uploadArea.classList.remove('has-file'); checkFormState(); }; const checkFormState = () => { submitBtn.disabled = !uploadedFile || promptInput.value.trim() === ''; }; const setLoading = (isLoading) => { const btnSpinner = submitBtn.querySelector('.spinner'); const btnText = document.getElementById('btn-text'); const btnIcon = submitBtn.querySelector('svg'); if (isLoading) { resultContainer.classList.remove('has-content'); resultContainer.classList.add('loading'); btnSpinner.style.display = 'inline-block'; btnIcon.style.display = 'none'; btnText.textContent = 'در حال پردازش...'; submitBtn.disabled = true; resultGrid.innerHTML = ''; errorMessage.style.display = 'none'; } else { resultContainer.classList.remove('loading'); btnSpinner.style.display = 'none'; btnIcon.style.display = 'inline-block'; btnText.textContent = 'ایجاد کن'; checkFormState(); } }; const displayResult = (imageUrls) => { resultGrid.innerHTML = ''; imageUrls.forEach((url) => { const img = document.createElement('img'); img.src = url; img.alt = 'تصویر ویرایش شده'; img.addEventListener('click', () => openLightbox(url, imageUrls)); resultGrid.appendChild(img); }); resultContainer.classList.add('has-content'); }; const clearResult = () => { resultGrid.innerHTML = ''; errorMessage.style.display = 'none'; resultContainer.classList.remove('has-content'); }; const displayError = (message) => { errorMessage.textContent = message; errorMessage.style.display = 'block'; }; const updateLightboxImage = () => { const newUrl = currentLightboxGroup[currentLightboxIndex]; lightboxImg.src = newUrl; currentLightboxUrl = newUrl; }; const openLightbox = (clickedUrl, urlGroup) => { currentLightboxGroup = urlGroup; currentLightboxIndex = urlGroup.indexOf(clickedUrl); updateLightboxImage(); lightboxNext.style.display = urlGroup.length > 1 ? 'flex' : 'none'; lightbox.classList.add('visible'); }; const closeLightbox = () => { lightbox.classList.remove('visible'); currentLightboxGroup = []; }; const handleDownload = async () => { if (!currentLightboxUrl) return; const spinner = lightboxDownload.querySelector('.spinner'); const icon = lightboxDownload.querySelector('svg'); spinner.style.display = 'block'; icon.style.display = 'none'; lightboxDownload.disabled = true; try { const response = await fetch(currentLightboxUrl); if (!response.ok) throw new Error('Network response was not ok.'); const blob = await response.blob(); const objectUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = objectUrl; a.download = `ai-edited-image-${Date.now()}.png`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(objectUrl); } catch (e) { console.error('Download failed:', e); alert('خطا در دانلود تصویر. لطفا دوباره تلاش کنید.'); } finally { spinner.style.display = 'none'; icon.style.display = 'block'; lightboxDownload.disabled = false; } }; const getHistory = () => JSON.parse(localStorage.getItem('aiPhotoshopHistory') || '[]'); const saveHistory = (history) => { localStorage.setItem('aiPhotoshopHistory', JSON.stringify(history)); renderHistory(); }; const addToHistory = (item) => { let history = getHistory(); history.unshift(item); if (history.length > 15) history.pop(); saveHistory(history); }; const handleClearHistory = () => { showConfirmationModal('آیا از پاک کردن تمام تاریخچه مطمئن هستید؟ این عمل غیرقابل بازگشت است.', () => { saveHistory([]); }); }; const handleDeleteItem = (index) => { showConfirmationModal('آیا از حذف این مورد از تاریخچه مطمئن هستید؟', () => { let history = getHistory(); history.splice(index, 1); saveHistory(history); }); }; const renderHistory = () => { const history = getHistory(); historyGrid.innerHTML = ''; clearHistoryBtn.style.display = history.length > 0 ? 'flex' : 'none'; history.forEach((item, index) => { const card = document.createElement('div'); card.className = 'history-item'; const deleteBtn = document.createElement('button'); deleteBtn.className = 'history-delete-btn'; deleteBtn.title = 'حذف این مورد'; deleteBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`; deleteBtn.onclick = () => handleDeleteItem(index); card.appendChild(deleteBtn); const imageGrid = document.createElement('div'); imageGrid.className = 'history-item-grid'; item.urls.forEach(url => { const img = document.createElement('img'); img.src = url; img.alt = 'تصویر از تاریخچه'; img.addEventListener('click', () => openLightbox(url, item.urls)); imageGrid.appendChild(img); }); card.appendChild(imageGrid); historyGrid.appendChild(card); }); };
501
+
502
+ // --- NEW GRADIO API HELPER FUNCTIONS ---
503
+ async function uploadFileToGradio(file) {
504
+ const formData = new FormData();
505
+ formData.append('files', file);
506
+ const response = await fetch(`${API_BASE_URL}upload`, { method: 'POST', body: formData });
507
+ if (!response.ok) throw new Error(`خطای سرور در آپلود: ${response.statusText}`);
508
+ const result = await response.json();
509
+ return result[0];
510
+ }
511
+
512
+ async function submitGradioJob(prompt, file, filePath, sessionHash) {
513
+ const payload = {
514
+ "data": [
515
+ prompt,
516
+ {
517
+ "path": filePath, "url": `${API_BASE_URL}file=${filePath}`,
518
+ "orig_name": file.name, "size": file.size, "mime_type": file.type,
519
+ "meta": { "_type": "gradio.FileData" }
520
+ },
521
+ null
522
+ ],
523
+ "event_data": null, "fn_index": 0, "session_hash": sessionHash
524
+ };
525
+ const response = await fetch(`${API_BASE_URL}queue/join`, {
526
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
527
+ body: JSON.stringify(payload)
528
+ });
529
+ if (!response.ok) throw new Error(`خطای سرور در ارسال جاب: ${response.statusText}`);
530
+ }
531
+
532
+ function listenForGradioResults(sessionHash) {
533
+ const eventSource = new EventSource(`${API_BASE_URL}queue/data?session_hash=${sessionHash}`);
534
+ const textOverlay = document.querySelector('.text-overlay');
535
+
536
+ eventSource.onmessage = function(event) {
537
+ const data = JSON.parse(event.data);
538
+ console.log('Received data:', JSON.stringify(data, null, 2));
539
+
540
+ switch (data.msg) {
541
+ case 'process_starts':
542
+ if (textOverlay) textOverlay.innerText = 'پردازش در سرور شروع شد...';
543
+ break;
544
+ case 'process_generating':
545
+ if (textOverlay) textOverlay.innerText = 'در حال ساخت تصویر...';
546
+ break;
547
+ case 'process_completed':
548
+ if (data.success === false && data.output && data.output.error) {
549
+ throw new Error(`خطا از سمت سرور: ${data.output.error}`);
550
+ }
551
+
552
+ if (data.output && data.output.data && data.output.data[0]) {
553
+ const resultData = data.output.data[0];
554
+ let resultUrl;
555
+ if (resultData.url) {
556
+ resultUrl = resultData.url;
557
+ } else if (resultData.path) {
558
+ resultUrl = `${API_BASE_URL}file=${resultData.path}`;
559
+ }
560
+
561
+ if (resultUrl) {
562
+ displayResult([resultUrl]); // displayResult expects an array
563
+ addToHistory({ prompt: promptInput.value.trim(), urls: [resultUrl] });
564
+ } else {
565
+ throw new Error('نتیجه دریافت شد اما لینک تصویر معتبر نبود.');
566
+ }
567
+ } else {
568
+ throw new Error('نتیجه دریافت شد اما ساختار داده غیرمنتظره بود.');
569
+ }
570
+
571
+ eventSource.close();
572
+ setLoading(false);
573
+ break;
574
+ }
575
+ };
576
+
577
+ eventSource.onerror = function(err) {
578
+ console.error('EventSource failed:', err);
579
+ displayError('خطا در ارتباط با سرور. لطفاً دوباره تلاش کنید.');
580
+ eventSource.close();
581
+ setLoading(false);
582
+ };
583
+ }
584
+
585
+ // --- EVENT LISTENERS ---
586
  document.addEventListener('DOMContentLoaded', () => { renderHistory(); checkFormState(); });
587
  removeFileBtn.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); resetUploader(); }); fileInput.addEventListener('change', (e) => handleFile(e.target.files[0])); ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, p => { p.preventDefault(); p.stopPropagation(); }); }); ['dragenter', 'dragover'].forEach(e => { uploadArea.addEventListener(e, () => { if (!uploadArea.classList.contains('has-file')) uploadArea.classList.add('drag-over'); }); }); ['dragleave', 'drop'].forEach(e => { uploadArea.addEventListener(e, () => uploadArea.classList.remove('drag-over')); }); uploadArea.addEventListener('drop', e => { if (!uploadArea.classList.contains('has-file')) handleFile(e.dataTransfer.files[0]); }); promptInput.addEventListener('input', checkFormState);
588
+
589
+ // --- MODIFIED SUBMIT BUTTON LOGIC ---
590
+ submitBtn.addEventListener('click', async () => {
591
+ if (submitBtn.disabled) return;
592
+ setLoading(true);
593
+
594
+ try {
595
+ const sessionHash = Math.random().toString(36).substring(7);
596
+ const textOverlay = document.querySelector('.text-overlay');
597
+
598
+ if (textOverlay) textOverlay.innerText = '۱/۳: آپلود تصویر...';
599
+ const uploadedFilePath = await uploadFileToGradio(uploadedFile);
600
+ if (!uploadedFilePath) throw new Error("آپلود فایل ناموفق بود.");
601
+
602
+ if (textOverlay) textOverlay.innerText = '۲/۳: ارسال درخواست...';
603
+ await submitGradioJob(promptInput.value.trim(), uploadedFile, uploadedFilePath, sessionHash);
604
+
605
+ if (textOverlay) textOverlay.innerText = '۳/۳: منتظر نتیجه...';
606
+ listenForGradioResults(sessionHash);
607
+
608
+ } catch (error) {
609
+ console.error('An error occurred:', error);
610
+ displayError(error.message);
611
+ setLoading(false); // Make sure to stop loading on initial error
612
+ }
613
+ });
614
+
615
  lightboxClose.addEventListener('click', closeLightbox); lightbox.addEventListener('click', (e) => { if (e.target === lightbox) closeLightbox(); }); lightboxDownload.addEventListener('click', handleDownload); lightboxNext.addEventListener('click', () => { currentLightboxIndex = (currentLightboxIndex + 1) % currentLightboxGroup.length; updateLightboxImage(); }); clearHistoryBtn.addEventListener('click', handleClearHistory);
616
  </script>
617