vidpro2ta / templates /index.html
Ezmary's picture
Update templates/index.html
a4707c7 verified
Raw
History Blame Contribute Delete
66.3 kB
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Video Studio - Two Frames</title>
<link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root {
--app-font: 'Vazirmatn', sans-serif;
--app-bg: #F8F9FC;
--panel-bg: #FFFFFF;
--panel-border: #EAEFF7;
--input-bg: #F6F8FB;
--input-border: #E1E7EF;
--text-primary: #1A202C;
--text-secondary: #626F86;
--text-tertiary: #8A94A6;
--accent-primary: #4A6CFA;
--accent-primary-hover: #3553D6;
--accent-primary-glow: rgba(74, 108, 250, 0.25);
--accent-secondary: #0FD4A8;
--accent-premium: #FFC107;
--accent-premium-glow: rgba(255, 193, 7, 0.3);
--success-color: #38A169;
--danger-color: #e53e3e;
--danger-color-hover: #c53030;
--shadow-sm: 0 1px 2px 0 rgba(26, 32, 44, 0.03);
--shadow-md: 0 4px 6px -1px rgba(26, 32, 44, 0.05), 0 2px 4px -2px rgba(26, 32, 44, 0.04);
--shadow-lg: 0 10px 15px -3px rgba(26, 32, 44, 0.06), 0 4px 6px -4px rgba(26, 32, 44, 0.05);
--shadow-xl: 0 20px 25px -5px rgba(26, 32, 44, 0.07), 0 8px 10px -6px rgba(26, 32, 44, 0.05);
--radius-card: 24px;
--radius-btn: 14px;
--radius-input: 12px;
--transition-smooth: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
--igadlm-alpha-color-primary: #5A67D8;
--igadlm-alpha-color-secondary: #805AD5;
--igadlm-alpha-color-primary-darker: #4C51BF;
--igadlm-alpha-color-secondary-darker: #6B46C1;
--igadlm-alpha-color-text-light: #4A5568;
--igadlm-alpha-color-warning-bg: #FFFBEB;
--igadlm-alpha-color-warning-border: #FBBF24;
--igadlm-alpha-color-warning-text: #B45309;
--igadlm-alpha-border-radius-md: 8px;
--igadlm-alpha-border-radius-lg: 12px;
}
@keyframes fadeIn { from { opacity: 0; transform: translateY(15px); } to { opacity: 1; transform: translateY(0); } }
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
@keyframes core-pulse { 0%, 100% { transform: scale(0.95); box-shadow: 0 0 25px var(--accent-primary-glow); } 50% { transform: scale(1.05); box-shadow: 0 0 50px rgba(74, 108, 250, 0.5); } }
@keyframes ring-rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
@keyframes background-pan { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }
@keyframes igadlmAlphaV2fadeInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
@keyframes badge-fade-in { from { opacity: 0; transform: translateY(-10px) scale(0.95); } to { opacity: 1; transform: translateY(0) scale(1); } }
body { font-family: var(--app-font); background-color: var(--app-bg); color: var(--text-primary); margin: 0; padding: 2.5rem 1rem; display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; }
.container { max-width: 820px; width: 100%; }
header { position: relative; text-align: center; margin-bottom: 2.5rem; padding: 2rem 0; animation: fadeIn 0.8s 0.1s ease-out backwards; overflow: hidden; }
#neural-network-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; }
.header-content { position: relative; z-index: 2; }
.ai-orb-container { width: 150px; height: 150px; margin: 0 auto 1rem; position: relative; display: flex; align-items: center; justify-content: center; }
.orb-background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(ellipse at center, rgba(74, 108, 250, 0.15) 0%, transparent 70%), linear-gradient(45deg, rgba(15, 212, 168, 0.05), rgba(74, 108, 250, 0.05)); border-radius: 50%; animation: background-pan 12s ease-in-out infinite; background-size: 200% 200%; }
.orb-core { width: 60px; height: 60px; border-radius: 50%; background: radial-gradient(circle, #394A7A 0%, #1A202C 70%); box-shadow: 0 0 25px var(--accent-primary-glow); display: flex; align-items: center; justify-content: center; position: relative; z-index: 2; animation: core-pulse 4s ease-in-out infinite; border: 1px solid rgba(74, 108, 250, 0.3); }
.play-icon { width: 24px; height: 24px; color: var(--accent-secondary); filter: drop-shadow(0 0 8px rgba(15, 212, 168, 0.7)); transition: var(--transition-smooth); }
.orb-core:hover .play-icon { transform: scale(1.1); color: #fff; filter: drop-shadow(0 0 12px rgba(15, 212, 168, 1)); }
.orb-ring { position: absolute; top: 50%; left: 50%; border-style: solid; border-color: transparent; border-radius: 50%; z-index: 1; mix-blend-mode: screen; }
.orb-ring.one { width: 100px; height: 100px; margin-top: -50px; margin-left: -50px; border-width: 2px; border-top-color: var(--accent-primary); border-right-color: var(--accent-primary); animation: ring-rotate 8s linear infinite; filter: blur(1px); }
.orb-ring.two { width: 120px; height: 120px; margin-top: -60px; margin-left: -60px; border-width: 1px; border-bottom-color: var(--accent-secondary); animation: ring-rotate 10s linear infinite reverse; }
.orb-ring.three { width: 140px; height: 140px; margin-top: -70px; margin-left: -70px; border-width: 2px; border-left-color: rgba(255, 255, 255, 0.5); border-right-color: rgba(255, 255, 255, 0.5); animation: ring-rotate 12s linear infinite; filter: blur(1px); opacity: 0.5; }
h1 { font-size: 2.8rem; font-weight: 800; margin: 0; background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: -1px; }
.subtitle { font-size: 1.1rem; color: var(--text-secondary); margin-top: 0.5rem; }
.instruction { font-size: 0.95rem; color: var(--text-tertiary); margin-top: 0.75rem; font-weight: 500; }
main { padding: 3rem; background-color: var(--panel-bg); border-radius: var(--radius-card); box-shadow: var(--shadow-xl); border: 1px solid var(--panel-border); animation: fadeIn 0.8s 0.3s ease-out backwards; }
.form-group { margin-bottom: 2.5rem; }
.form-group:last-child { margin-bottom: 0; }
.form-label { display: flex; align-items: center; gap: 0.75rem; font-weight: 700; color: var(--text-primary); font-size: 1.2em; margin-bottom: 1.2rem; }
.form-label svg { width: 24px; height: 24px; color: var(--accent-primary); }
.image-drop-zone { position: relative; border: 2px dashed var(--input-border); border-radius: var(--radius-input); padding: 2.5rem; text-align: center; cursor: pointer; transition: var(--transition-smooth); background-color: var(--input-bg); min-height: 200px; display: flex; flex-direction: column; justify-content: center; align-items: center; overflow: hidden; }
.image-drop-zone.drag-over, .image-drop-zone:hover:not(.has-image) { border-color: var(--accent-primary); background-color: #fff; box-shadow: 0 0 15px var(--accent-primary-glow); }
.image-drop-zone.has-image { border-style: solid; border-color: var(--success-color); padding: 0; cursor: default; }
.upload-content { display: flex; flex-direction: column; align-items: center; gap: 1rem; }
.upload-icon svg { width: 48px; height: 48px; color: var(--accent-primary); stroke-width: 1.5; opacity: 0.8; }
.image-drop-zone p { margin: 0; color: var(--text-secondary); font-weight: 500; }
.image-preview { display: none; width: 100%; height: 100%; object-fit: contain; position: absolute; top: 0; left: 0; }
.image-drop-zone.has-image .upload-content { display: none; }
.image-drop-zone.has-image .image-preview { display: block; }
textarea { width: 100%; padding: 1rem 1.2rem; border-radius: var(--radius-input); border: 1px solid var(--input-border); background-color: var(--input-bg); color: var(--text-primary); box-shadow: var(--shadow-sm) inset; font-family: var(--app-font); font-size: 1rem; box-sizing: border-box; transition: var(--transition-smooth); min-height: 120px; resize: vertical; }
textarea:focus { outline: none; border-color: var(--accent-primary); box-shadow: 0 0 0 3px var(--accent-primary-glow), var(--shadow-sm) inset; background-color: var(--panel-bg); }
.slider-group { margin-top: 2rem; margin-bottom: 1.5rem; }
.slider-label-container { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; }
.slider-label { font-weight: 600; color: var(--text-secondary); font-size: 0.95rem; }
.slider-value { font-weight: 700; font-size: 1rem; color: var(--accent-primary); background-color: var(--input-bg); padding: 0.25rem 0.75rem; border-radius: 8px; border: 1px solid var(--input-border); min-width: 80px; text-align: center; }
.slider-wrapper { display: flex; align-items: center; gap: 1rem; }
.slider-icon { width: 22px; height: 22px; color: var(--text-tertiary); flex-shrink: 0; opacity: 0.8; }
input[type="range"] { -webkit-appearance: none; appearance: none; flex-grow: 1; width: 100%; height: 12px; background: var(--input-bg); border-radius: var(--radius-input); outline: none; cursor: pointer; direction: rtl; box-shadow: inset 0 1px 3px rgba(0,0,0,0.1); transition: var(--transition-smooth); }
input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 24px; height: 24px; background: linear-gradient(145deg, var(--accent-primary), var(--accent-secondary)); border-radius: 50%; border: 3px solid white; box-shadow: var(--shadow-md); transition: all 0.2s ease-in-out; margin-top: -6px; }
input[type="range"]::-moz-range-thumb { width: 24px; height: 24px; background: linear-gradient(145deg, var(--accent-primary), var(--accent-secondary)); border-radius: 50%; border: 3px solid white; box-shadow: var(--shadow-md); transition: all 0.2s ease-in-out; }
input[type="range"]:hover { box-shadow: inset 0 1px 3px rgba(0,0,0,0.1), 0 0 0 4px var(--accent-primary-glow); }
input[type="range"]:hover::-webkit-slider-thumb { box-shadow: 0 0 0 10px var(--accent-primary-glow), var(--shadow-md); transform: scale(1.1); }
input[type="range"]:active::-webkit-slider-thumb { transform: scale(1.2); box-shadow: 0 0 0 12px var(--accent-primary-glow), var(--shadow-md); }
#generateButton { display: flex; align-items: center; justify-content: center; gap: 0.75rem; width: 100%; padding: 1.1rem; font-size: 1.2rem; font-weight: 700; background: linear-gradient(95deg, var(--accent-secondary) 0%, var(--accent-primary) 100%); color: #fff; border: none; border-radius: var(--radius-btn); cursor: pointer; transition: all 0.3s ease; box-shadow: 0 6px 12px -3px var(--accent-primary-glow), 0 6px 12px -3px rgba(15, 212, 168, 0.25); margin-top: 1rem; }
#generateButton svg { width: 24px; height: 24px; margin-left: 4px; filter: drop-shadow(0 0 5px rgba(255,255,255,0.5)); }
#generateButton:hover:not(:disabled) { transform: translateY(-5px) scale(1.02); box-shadow: 0 8px 20px -4px var(--accent-primary-glow), 0 8px 20px -4px rgba(15, 212, 168, 0.3); }
#generateButton:disabled { background: var(--text-tertiary); cursor: not-allowed; box-shadow: none; opacity: 0.7; }
#result-container { min-height: 350px; position: relative; padding: 1rem; background-color: var(--input-bg); border-radius: var(--radius-card); border: 2px dashed var(--input-border); box-shadow: var(--shadow-sm) inset; transition: var(--transition-smooth); display: flex; flex-direction: column; align-items: center; justify-content: center; }
#result-container.active { border-style: solid; border-color: var(--panel-border); }
#statusSection, #outputSection, #criticalErrorSection { display: none; width: 100%; }
#statusSection.active, #outputSection.active, #criticalErrorSection.active { display: block; animation: fadeIn 0.5s; }
#statusMessages { max-height: 150px; overflow-y: auto; width: 100%; padding: 0.5rem; margin-bottom: 1rem; }
.status-message { display: flex; align-items: center; gap: 0.75rem; padding: 0.6rem 1rem; margin-bottom: 0.5rem; border-radius: var(--radius-input); font-size: 0.9rem; background: var(--panel-bg); border: 1px solid var(--panel-border); color: var(--text-secondary); }
.status-message.success { border-left: 4px solid var(--success-color); color: var(--success-color); }
.status-message.error { border-left: 4px solid var(--danger-color); color: var(--danger-color); }
.status-icon { width: 18px; height: 18px; }
#aiLoader { display: none; align-items: center; justify-content: center; }
.generator-container { position: relative; width: 400px; max-width: 100%; height: 300px; border: 2px solid #38bdf8; border-radius: 20px; overflow: hidden; box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); animation: pulse-loader 5s infinite cubic-bezier(0.4, 0, 0.6, 1); background-color: #161b22; color: #f0f6fc; }
@keyframes pulse-loader { 0% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } 50% { box-shadow: 0 0 60px rgba(56, 189, 248, 0.7); } 100% { box-shadow: 0 0 40px rgba(56, 189, 248, 0.3); } }
.noise-layer, .sketch-layer, .building-layer { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
.noise-layer { background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect width="100" height="100" fill="none"/><filter id="noise"><feTurbulence type="fractalNoise" baseFrequency="0.5" numOctaves="4" stitchTiles="stitch"/></filter><rect width="100%" height="100%" filter="url(%23noise)" opacity="0.6"/></svg>') repeat; opacity: 1; animation: fade-noise 7s infinite ease-in-out; }
@keyframes fade-noise { 0% { opacity: 1; filter: blur(5px); } 30% { opacity: 0.8; filter: blur(2px); } 100% { opacity: 0; filter: blur(0px); } }
.sketch-layer { filter: grayscale(1) contrast(1.5) blur(3px); opacity: 0; animation: reveal-sketch 7s infinite ease-in-out; }
@keyframes reveal-sketch { 0% { opacity: 0; } 20% { opacity: 1; } 60% { opacity: 0.5; } 100% { opacity: 0; } }
.building-layer { filter: blur(15px); opacity: 0; animation: denoise-color 7s infinite ease-in-out; }
@keyframes denoise-color { 0% { opacity: 0; } 40% { opacity: 0.6; filter: blur(5px); } 100% { opacity: 1; filter: blur(0px); } }
.pixel-grid { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: repeating-linear-gradient(0deg, transparent 0 1px, rgba(255,255,255,0.1) 1px 2px), repeating-linear-gradient(90deg, transparent 0 1px, rgba(255,255,255,0.1) 1px 2px); opacity: 1; animation: dissolve-grid 7s infinite ease-in-out; }
@keyframes dissolve-grid { 0% { opacity: 1; } 70% { opacity: 0.5; } 100% { opacity: 0; } }
.particles { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(circle, rgba(56, 189, 248, 0.2) 0%, transparent 50%); animation: flow-particles 7s infinite cubic-bezier(0.4, 0, 0.6, 1); }
@keyframes flow-particles { 0% { transform: translate(0, 0) scale(1); opacity: 0.5; } 50% { transform: translate(10px, -15px) scale(1.05); opacity: 0.8; } 100% { transform: translate(0, 0) scale(1); opacity: 0.5; } }
.text-overlay { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); font-size: 24px; font-weight: 700; text-shadow: 0 0 20px rgba(56, 189, 248, 0.8); animation: glow-text 7s infinite ease-in-out; font-family: var(--app-font); width: 90%; text-align: center;}
@keyframes glow-text { 0% { opacity: 0.7; } 50% { opacity: 1; } 100% { opacity: 0.7; } }
.progress-bar { position: absolute; bottom: 0; left: 0; width: 0%; height: 6px; background: linear-gradient(to right, #38bdf8, #bb86fc, #facc15); transition: width 0.5s ease-out; }
#outputVideo { width: 100%; max-width: 500px; border-radius: var(--radius-input); margin: 1rem auto; display: block; background-color: #000; box-shadow: var(--shadow-md); }
#finalSeed { text-align: center; color: var(--text-tertiary); font-size: 0.85rem; margin-top: 1rem; }
.video-controls { display: flex; justify-content: center; gap: 1rem; margin-top: 1.5rem; }
.video-button { padding: 0.7rem 1.5rem; border-radius: var(--radius-btn); border: none; cursor: pointer; font-family: var(--app-font); font-weight: 600; font-size: 1rem; transition: var(--transition-smooth); display: flex; align-items: center; gap: 0.5rem; }
.video-button.primary { background-color: var(--accent-primary); color: white; }
.video-button.primary:hover { background-color: var(--accent-primary-hover); transform: translateY(-2px); }
.video-button:not(.primary) { background-color: var(--input-bg); color: var(--text-secondary); border: 1px solid var(--input-border); }
.video-button:not(.primary):hover { background-color: var(--panel-border); color: var(--text-primary); }
.gpu-error-message-container { text-align: right; background-color: var(--igadlm-alpha-color-warning-bg); padding: 25px; border-radius: var(--igadlm-alpha-border-radius-lg); box-shadow: var(--shadow-lg); border: 2px solid var(--igadlm-alpha-color-warning-border); animation: igadlmAlphaV2fadeInUp 0.5s cubic-bezier(0.4, 0, 0.2, 1) both; }
.gpu-error-message-container h2 { font-size: 1.2em; color: var(--igadlm-alpha-color-warning-text); margin-bottom: 15px; font-weight: 700; display: flex; align-items: center; border-bottom: 1px solid var(--igadlm-alpha-color-warning-border); padding-bottom: 12px; }
.gpu-error-message-container h2 .icon { margin-left: 10px; font-size: 1.3em; }
.gpu-error-message-container .error-content { font-size: 0.9rem; color: var(--igadlm-alpha-color-text-light); line-height: 1.7; word-break: break-word; white-space: pre-line; }
.gpu-error-message-container .error-content strong.error-message-title { font-weight: 600; color: var(--igadlm-alpha-color-warning-text); display: block; margin-bottom: 8px;}
.gpu-error-message-container .error-content ul { list-style-type: "▫️ "; padding-right: 20px; margin-top: 10px; }
.gpu-error-message-container .error-content li { margin-bottom: 6px; }
#subscription-status-badge { display: none; padding: 6px 16px; border-radius: 20px; font-size: 0.9em; font-weight: 700; margin-top: 1.25rem; letter-spacing: 0.5px; animation: badge-fade-in 0.6s 0.5s ease-out backwards; }
#subscription-status-badge.free-badge { background: linear-gradient(45deg, #6c757d, #495057); color: white; box-shadow: 0 4px 10px rgba(108, 117, 125, 0.3); }
#subscription-status-badge.paid-badge { background: linear-gradient(45deg, var(--accent-premium), #ffca2c); color: #333; box-shadow: 0 4px 10px var(--accent-premium-glow); }
#credit-info-section { margin-top: 1.5rem; margin-bottom: 0.5rem; padding: 1rem; background-color: var(--input-bg); border-radius: var(--radius-input); text-align: center; font-size: 0.95rem; font-weight: 500; color: var(--text-secondary); border: 1px solid var(--input-border); display: none; }
#upgrade-button { margin-top: 1rem; width: 100%; padding: 1rem; font-size: 1.1rem; font-weight: 700; background: linear-gradient(95deg, #FFD54F, #FFC107 100%); color: #212529; border: none; border-radius: var(--radius-btn); cursor: pointer; box-shadow: 0 8px 20px -5px rgba(255, 193, 7, 0.3); display: none; }
@media (max-width: 768px) { main { padding: 1.5rem; } h1 { font-size: 2.2rem; } .generator-container { height: 250px; } .text-overlay { font-size: 18px; } }
</style>
</head>
<body>
<div class="container">
<header>
<canvas id="neural-network-canvas"></canvas>
<div class="header-content">
<div class="ai-orb-container">
<div class="orb-background"></div>
<div class="orb-core">
<svg class="play-icon" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M8 5v14l11-7z"></path>
</svg>
</div>
<div class="orb-ring one"></div>
<div class="orb-ring two"></div>
<div class="orb-ring three"></div>
</div>
<h1>استودیو ویدیو هوش مصنوعی</h1>
<p class="subtitle">تصاویر خود را با قدرت هوش مصنوعی به ویدیو سینمایی تبدیل کنید</p>
<p class="instruction">دو تصویر برای شروع و پایان ویدیو انتخاب کرده و دستور ساخت را بنویسید.</p>
<div id="subscription-status-badge" style="display:inline-block;"></div>
</div>
</header>
<main>
<div class="form-group">
<div class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
۱. تصویر شروع را انتخاب کنید
</div>
<label id="image-drop-zone-start" class="image-drop-zone" for="imageFileStart">
<div class="upload-content">
<div class="upload-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg></div>
<p>فایل تصویر شروع را اینجا بکشید یا برای انتخاب کلیک کنید</p>
</div>
<img id="imagePreviewStart" class="image-preview" src="" alt="Preview Start">
</label>
<input type="file" id="imageFileStart" accept="image/jpeg, image/png, image/webp" hidden>
</div>
<div class="form-group">
<div class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4Z"/></svg>
۲. تصویر پایان را انتخاب کنید
</div>
<label id="image-drop-zone-end" class="image-drop-zone" for="imageFileEnd">
<div class="upload-content">
<div class="upload-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="17 8 12 3 7 8"></polyline><line x1="12" y1="3" x2="12" y2="15"></line></svg></div>
<p>فایل تصویر پایان را اینجا بکشید یا برای انتخاب کلیک کنید</p>
</div>
<img id="imagePreviewEnd" class="image-preview" src="" alt="Preview End">
</label>
<input type="file" id="imageFileEnd" accept="image/jpeg, image/png, image/webp" hidden>
</div>
<div class="form-group">
<label for="prompt" class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg>
۳. دستور ساخت ویدیو را بنویسید
</label>
<textarea id="prompt" rows="4" placeholder="مثال: مرد رو به دوربین می‌چرخد و لبخند می‌زند"></textarea>
<div class="slider-group">
<div class="slider-label-container">
<label for="durationSlider" class="slider-label">مدت زمان ویدیو</label>
<span id="durationValue" class="slider-value">2.1 ثانیه</span>
</div>
<div class="slider-wrapper">
<svg class="slider-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
<input type="range" id="durationSlider" min="0.5" max="5.0" value="2.1" step="0.1">
<svg class="slider-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
</div>
</div>
<div id="credit-info-section"></div>
<button id="upgrade-button">⭐️ ارتقا به نسخه کامل و نامحدود</button>
<button id="generateButton">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/></svg>
<span>ساخت ویدیو جادویی</span>
</button>
</div>
<div class="form-group">
<div class="form-label">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L12 8L17 10L12 12L10 17L8 12L3 10L8 8L10 3z"/><path d="M21 14l-1.5 3-3-1.5 3-3 1.5 3z"/><path d="M19.5 2.5l-3 1.5 1.5 3 3-1.5-1.5-3z"/></svg>
۴. نتیجه را ببینید
</div>
<div id="result-container">
<div id="statusSection">
<div id="statusMessages"></div>
<div id="aiLoader" style="display: none;">
<div class="generator-container">
<div class="noise-layer"></div>
<div class="sketch-layer"></div>
<div class="building-layer"></div>
<div class="pixel-grid"></div>
<div class="particles"></div>
<div class="text-overlay">در حال پردازش ویدیو...</div>
<div class="progress-bar"></div>
</div>
</div>
</div>
<div id="outputSection">
<video id="outputVideo" controls preload="metadata" playsinline></video>
<p id="finalSeed"></p>
<div class="video-controls">
<button id="btnDownloadVideo" class="video-button primary" style="display: none;">
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg>
دانلود ویدیو
</button>
<button id="btnRestart" class="video-button">
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>
ساخت ویدیو جدید
</button>
</div>
</div>
<div id="criticalErrorSection"></div>
</div>
</div>
</main>
</div>
<script type="module">
import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
(function() {
// === START: بخش مدیریت اعتبار و ارتباط با والد ===
let userSubscriptionStatus = 'free'; // 'free' or 'paid'
let userFingerprint = null;
let countdownInterval = null;
const PREMIUM_PAGE_ID = '1149636';
async function getBrowserFingerprint() {
const components = [navigator.userAgent, navigator.language, screen.width + 'x' + screen.height, new Date().getTimezoneOffset()];
try {
const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d');
ctx.fillText("a1b2c3d4e5f6g7h8i9j0", 2, 15);
components.push(canvas.toDataURL());
} catch (e) { components.push("canvas-error"); }
const fingerprintString = components.join('---');
let hash = 0;
for (let i = 0; i < fingerprintString.length; i++) {
hash = ((hash << 5) - hash) + fingerprintString.charCodeAt(i);
hash |= 0;
}
return 'fp_' + Math.abs(hash).toString(16);
}
function isUserPaid(userObject) {
return userObject && userObject.isLogin && userObject.accessible_pages &&
(userObject.accessible_pages.includes(PREMIUM_PAGE_ID) || userObject.accessible_pages.includes(parseInt(PREMIUM_PAGE_ID)));
}
function updateUIForSubscriptionStatus(status) {
userSubscriptionStatus = status;
const creditInfoDiv = document.getElementById('credit-info-section');
const upgradeBtn = document.getElementById('upgrade-button');
const genBtn = document.getElementById('generateButton');
const subscriptionBadge = document.getElementById('subscription-status-badge');
if (status === 'paid') {
subscriptionBadge.textContent = 'نسخه نامحدود';
subscriptionBadge.className = 'paid-badge';
creditInfoDiv.style.display = 'none';
upgradeBtn.style.display = 'none';
genBtn.disabled = false;
if(countdownInterval) clearInterval(countdownInterval);
} else {
subscriptionBadge.textContent = 'نسخه رایگان';
subscriptionBadge.className = 'free-badge';
checkFreeUserCredit();
}
subscriptionBadge.style.display = 'inline-block';
}
async function checkFreeUserCredit() {
if (!userFingerprint) return;
const creditInfoDiv = document.getElementById('credit-info-section');
const upgradeBtn = document.getElementById('upgrade-button');
const genBtn = document.getElementById('generateButton');
try {
const response = await fetch('/api/check-credit', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ fingerprint: userFingerprint })
});
const result = await response.json();
creditInfoDiv.style.display = 'block';
if (result.limit_reached) {
genBtn.disabled = true;
upgradeBtn.style.display = 'block';
startCountdown(result.reset_timestamp);
} else {
genBtn.disabled = false;
upgradeBtn.style.display = 'none';
if(countdownInterval) clearInterval(countdownInterval);
creditInfoDiv.textContent = `شما ${result.credits_remaining} اعتبار ساخت ویدیوی رایگان در این هفته دارید.`;
}
} catch (error) {
creditInfoDiv.textContent = "خطا در بررسی اعتبار.";
genBtn.disabled = true;
}
}
function startCountdown(resetTimestamp) {
if (countdownInterval) clearInterval(countdownInterval);
const creditInfoDiv = document.getElementById('credit-info-section');
const updateTimer = () => {
const timeLeft = Math.max(0, resetTimestamp - (Date.now() / 1000));
if (timeLeft === 0) {
clearInterval(countdownInterval);
creditInfoDiv.textContent = 'در حال بروزرسانی اعتبار...';
setTimeout(checkFreeUserCredit, 2000);
return;
}
const d = Math.floor(timeLeft / 86400);
const h = Math.floor((timeLeft % 86400) / 3600);
const m = Math.floor((timeLeft % 3600) / 60);
creditInfoDiv.textContent = `اعتبار شما تمام شده. زمان باقی‌مانده: ${d} روز و ${h} ساعت و ${m} دقیقه`;
};
updateTimer();
countdownInterval = setInterval(updateTimer, 60000);
}
window.addEventListener('message', (event) => {
if (event.data && event.data.type === 'USER_DATA_RESPONSE') {
if (event.data.error || !event.data.payload) {
updateUIForSubscriptionStatus('free');
return;
}
try {
const userObject = JSON.parse(event.data.payload);
const status = isUserPaid(userObject) ? 'paid' : 'free';
updateUIForSubscriptionStatus(status);
} catch (e) {
updateUIForSubscriptionStatus('free');
}
}
});
document.getElementById('upgrade-button').addEventListener('click', () => {
parent.postMessage({ type: 'NAVIGATE_TO_PREMIUM' }, '*');
});
// === END: بخش مدیریت اعتبار ===
// DOM Elements
const resultContainer = document.getElementById('result-container');
const imageFileInputStart = document.getElementById('imageFileStart');
const imagePreviewStart = document.getElementById('imagePreviewStart');
const imageDropZoneStart = document.getElementById('image-drop-zone-start');
const imageFileInputEnd = document.getElementById('imageFileEnd');
const imagePreviewEnd = document.getElementById('imagePreviewEnd');
const imageDropZoneEnd = document.getElementById('image-drop-zone-end');
const promptInput = document.getElementById('prompt');
const generateButton = document.getElementById('generateButton');
const outputVideo = document.getElementById('outputVideo');
const finalSeedElement = document.getElementById('finalSeed');
const criticalErrorSection = document.getElementById('criticalErrorSection');
const statusSection = document.getElementById('statusSection');
const statusMessagesDiv = document.getElementById('statusMessages');
const aiLoader = document.getElementById('aiLoader');
const loaderProgressBar = document.querySelector('#aiLoader .progress-bar');
const loaderTextOverlay = document.querySelector('#aiLoader .text-overlay');
const outputSection = document.getElementById('outputSection');
const btnRestart = document.getElementById('btnRestart');
const btnDownloadVideo = document.getElementById('btnDownloadVideo');
const durationSlider = document.getElementById('durationSlider');
const durationValueDisplay = document.getElementById('durationValue');
// ====== تنظیمات مدل‌ها ======
const VIDEO_SPACE_URL = "https://multimodalart-wan-2-2-first-last-frame.hf.space/";
const VIDEO_FN_INDEX = 0; // The /generate_video endpoint
const TRANSLATOR_SPACE_NAME = "hamed744/translate-tts-aloha";
const FN_INDEX_TRANSLATE_SPEAK = 1;
const DEFAULT_TTS_VOICE_TRANSLATOR = "انگلیسی (آمریکا) - جنی (زن)";
const DEFAULT_NEGATIVE_PROMPT = "色调艳丽, 过曝, 静态, 细节模糊不清, 字幕, 风格, 作品, 画作, 画面, 静止, 整体发灰, 最差质量, 低质量, JPEG压缩残留, 丑陋的, 残缺的, 多余的手指, 画得不好的手部, 画得不好的脸部, 畸形的, 毁容的, 形态畸形的肢体, 手指融合, 静止不动的画面, 杂乱的背景, 三条腿, 背景人很多, 倒着走,过曝,";
const DEFAULT_PROMPT_TEXT = "";
const TRANSPARENT_PIXEL_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
const DEFAULT_VIDEO_DURATION = 2.1;
const TRANSLATION_TIMEOUT = 20000;
let lastAttemptedVideoPayload = null;
let eventSource = null;
let isProcessCompleted = false;
const generateSessionHash = () => Math.random().toString(36).substring(2, 13);
function updateSliderStyle(slider) {
const percentage = ((slider.value - slider.min) / (slider.max - slider.min)) * 100;
const colorStops = `var(--accent-primary), var(--accent-secondary)`;
slider.style.background = `linear-gradient(to left, ${colorStops} ${percentage}%, var(--input-bg) ${percentage}%)`;
}
async function retryLastAttempt() {
if (!lastAttemptedVideoPayload || !lastAttemptedVideoPayload.startImageFile || !lastAttemptedVideoPayload.endImageFile || !lastAttemptedVideoPayload.persianPrompt) {
showCriticalError("اطلاعات کافی برای تلاش مجدد وجود ندارد. لطفاً از نو شروع کنید.");
return;
}
generateButton.click();
}
function showCriticalError(message, isGpuQuotaError = false) {
const lowerCaseMessage = (message || "").toLowerCase();
if (isGpuQuotaError || lowerCaseMessage.includes("gpu") || lowerCaseMessage.includes("quota") || lowerCaseMessage.includes("capacity")) {
const detailedGpuErrorHtml = `<div class="gpu-error-message-container"><h2><span class="icon">💡</span> راهنمای رفع محدودیت ویدیو</h2><div class="error-content"><strong class="error-message-title">ارور محدودیت استفاده از GPU (کارت گرافیک)</strong><p>این خطا به دلیل محدودیت‌های موقتی در سرویس‌دهنده ایجاد می‌شود. خبر خوب این است که این محدودیت‌ها معمولاً با یک ترفند ساده قابل رفع هستند.</p><p><strong>برای رفع محدودیت، مراحل زیر را دقیقاً انجام دهید:</strong></p><ul><li>اگر از اینترنت سیم‌کارت استفاده می‌کنید، فیلترشکن خود را حتما خاموش کنید.</li><li><strong>به مدت ۱۰ تا ۱۵ ثانیه، گوشی خود را در حالت هواپیما قرار دهید و سپس آن را غیرفعال کنید.</strong> این کار IP شما را تغییر داده و محدودیت را برطرف می‌کند.</li><li>اگر از وای فای استفاده می‌کنید، مودم خود را یک بار خاموش و روشن کنید. (توصیه می‌شود برای استفاده نامحدود از اینترنت سیم کارت استفاده کنید).</li></ul><p>خلاصه: هر بار با این خطا مواجه شدید، از اینترنت سیم‌کارت بدون فیلترشکن استفاده کرده و یک یا دو بار حالت هواپیما را روشن و خاموش کنید. سپس دکمه "تلاش مجدد" را بزنید. با این روش می‌توانید به صورت نامحدود ویدیو بسازید. ☘️</p></div><div class="video-controls"><button id="gpuErrorGoBackBtn" class="video-button">بازگشت</button><button id="gpuErrorRetryBtn" class="video-button primary">تلاش مجدد</button></div></div>`;
criticalErrorSection.innerHTML = detailedGpuErrorHtml;
document.getElementById('gpuErrorGoBackBtn').addEventListener('click', hideCriticalError);
document.getElementById('gpuErrorRetryBtn').addEventListener('click', retryLastAttempt);
} else {
criticalErrorSection.innerHTML = `<div style="text-align: center; color: var(--danger-color); font-weight: 500; margin-bottom: 1.5rem; line-height: 1.6;"><p>${message}</p></div><div class="video-controls"><button id="simpleErrorGoBackBtn" class="video-button">بازگشت</button><button id="simpleErrorRetryBtn" class="video-button primary">تلاش مجدد</button></div>`;
document.getElementById('simpleErrorGoBackBtn').addEventListener('click', hideCriticalError);
document.getElementById('simpleErrorRetryBtn').addEventListener('click', retryLastAttempt);
}
resultContainer.classList.add('active');
criticalErrorSection.classList.add('active');
statusSection.classList.remove('active');
outputSection.classList.remove('active');
aiLoader.style.display = 'none';
generateButton.disabled = false;
}
function hideCriticalError() {
criticalErrorSection.classList.remove('active');
criticalErrorSection.innerHTML = '';
}
function setAiLoaderText(text) { if (loaderTextOverlay) loaderTextOverlay.textContent = text; }
function setProgressBar(percentage) {
if(loaderProgressBar) {
const p = Math.max(0, Math.min(100, percentage));
loaderProgressBar.style.width = `${p}%`;
}
}
function addStatusMessage(message, type = 'info') {
if (criticalErrorSection.classList.contains('active') && type === 'error') return;
resultContainer.classList.add('active');
statusSection.classList.add('active');
const messageDiv = document.createElement('div');
messageDiv.className = `status-message ${type}`;
const iconSvg = type === 'success' ? '<svg class="status-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"/></svg>' : type === 'error' ? '<svg class="status-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/></svg>' : '<svg class="status-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>';
messageDiv.innerHTML = `${iconSvg}<span class="status-text">${message}</span>`;
statusMessagesDiv.insertBefore(messageDiv, statusMessagesDiv.firstChild);
}
function clearStatusMessages() {
statusMessagesDiv.innerHTML = '';
setProgressBar(0);
aiLoader.style.display = 'none';
if (outputVideo.src && outputVideo.src.startsWith('blob:')) {
URL.revokeObjectURL(outputVideo.src);
}
outputVideo.src = '';
finalSeedElement.textContent = '';
btnDownloadVideo.style.display = 'none';
}
function initializeForm() {
if (eventSource) {
eventSource.close();
eventSource = null;
}
isProcessCompleted = false;
hideCriticalError();
resultContainer.classList.remove('active');
statusSection.classList.remove('active');
outputSection.classList.remove('active');
clearStatusMessages();
lastAttemptedVideoPayload = null;
imageFileInputStart.value = '';
imagePreviewStart.src = TRANSPARENT_PIXEL_SRC;
imageDropZoneStart.classList.remove('has-image');
imageFileInputEnd.value = '';
imagePreviewEnd.src = TRANSPARENT_PIXEL_SRC;
imageDropZoneEnd.classList.remove('has-image');
promptInput.value = DEFAULT_PROMPT_TEXT;
generateButton.disabled = false;
durationSlider.value = DEFAULT_VIDEO_DURATION;
durationValueDisplay.textContent = `${parseFloat(DEFAULT_VIDEO_DURATION).toFixed(1)} ثانیه`;
updateSliderStyle(durationSlider);
updateUIForSubscriptionStatus(userSubscriptionStatus);
}
async function translatePersianToEnglish(persianText, { timeoutMs = TRANSLATION_TIMEOUT } = {}) {
if (!persianText?.trim()) {
return Promise.resolve("");
}
const translator = await Client.connect(TRANSLATOR_SPACE_NAME);
const predictPromise = translator.predict(FN_INDEX_TRANSLATE_SPEAK, [
persianText, DEFAULT_TTS_VOICE_TRANSLATOR, 0, 0, 0
]);
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Translation request timed out.")), timeoutMs)
);
const resp = await Promise.race([predictPromise, timeoutPromise]);
const english = resp?.data?.[0];
if (typeof english !== 'string') throw new Error("Invalid translation response.");
return english;
}
async function handleSuccessfulVideoGeneration(output) {
aiLoader.style.display = 'none';
if (!output?.data?.[0]?.video?.path) {
showCriticalError('پاسخ دریافتی از سرور ویدیو معتبر نیست.');
return;
}
if (userSubscriptionStatus === 'free') {
try {
addStatusMessage('ویدیو ساخته شد، در حال ثبت اعتبار...', 'info');
await fetch('/api/use-credit', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ fingerprint: userFingerprint })
});
checkFreeUserCredit();
} catch (creditError) {
console.error("Critical error deducting credit:", creditError);
}
}
addStatusMessage('ویدیو آماده شد! 🎉', 'success');
const videoPath = output.data[0].video.path;
const videoUrl = `${VIDEO_SPACE_URL}gradio_api/file=${videoPath}`;
const usedSeed = output.data[1];
setTimeout(() => {
statusSection.classList.remove('active');
outputSection.classList.add('active');
outputVideo.src = videoUrl;
finalSeedElement.textContent = `Seed: ${usedSeed}`;
prepareCustomDownloadLink(videoUrl);
}, 300);
generateButton.disabled = false;
}
function prepareCustomDownloadLink(videoUrl) {
btnDownloadVideo.style.display = 'flex';
btnDownloadVideo.onclick = () => {
parent.postMessage({ type: 'DOWNLOAD_REQUEST', url: videoUrl }, '*');
};
}
// --- UI Event Handlers ---
document.addEventListener('DOMContentLoaded', async () => {
initializeForm();
userFingerprint = await getBrowserFingerprint();
parent.postMessage({ type: 'REQUEST_USER_DATA' }, '*');
updateSliderStyle(durationSlider);
});
durationSlider.addEventListener('input', () => {
const value = parseFloat(durationSlider.value).toFixed(1);
durationValueDisplay.textContent = `${value} ثانیه`;
updateSliderStyle(durationSlider);
});
function setupImageInput(fileInput, dropZone, preview) {
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(e => dropZone.addEventListener(e, ev => ev.preventDefault()));
['dragenter', 'dragover'].forEach(e => dropZone.addEventListener(e, () => { if (!dropZone.classList.contains('has-image')) dropZone.classList.add('drag-over'); }));
['dragleave', 'drop'].forEach(e => dropZone.addEventListener(e, () => dropZone.classList.remove('drag-over')));
dropZone.addEventListener('drop', e => { if (e.dataTransfer.files.length > 0) { fileInput.files = e.dataTransfer.files; fileInput.dispatchEvent(new Event('change')); } });
fileInput.addEventListener('change', function(event) {
const file = event.target.files[0];
hideCriticalError();
if (file) {
if (!file.type.startsWith('image/')) {
addStatusMessage('فرمت نامعتبر', 'error');
} else {
const reader = new FileReader();
reader.onload = (e) => { preview.src = e.target.result; dropZone.classList.add('has-image'); };
reader.readAsDataURL(file);
}
} else {
preview.src = TRANSPARENT_PIXEL_SRC;
dropZone.classList.remove('has-image');
}
});
}
setupImageInput(imageFileInputStart, imageDropZoneStart, imagePreviewStart);
setupImageInput(imageFileInputEnd, imageDropZoneEnd, imagePreviewEnd);
btnRestart.addEventListener('click', initializeForm);
// --- START: NEW AND IMPROVED CODE ---
/**
* Attempts to fetch a resource with automatic retries on network errors.
* @param {string} url - The URL to fetch.
* @param {object} options - Fetch options.
* @param {number} retries - The number of times to retry.
* @param {number} delay - The initial delay between retries in ms.
* @param {number} backoff - The multiplier for the delay.
* @returns {Promise<Response>}
*/
async function fetchWithRetry(url, options, retries = 3, delay = 1000, backoff = 2) {
let lastError;
for (let i = 0; i < retries; i++) {
try {
return await fetch(url, options);
} catch (error) {
lastError = error;
// Only retry on specific, recoverable network errors
if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
if (i < retries - 1) { // Don't wait on the last attempt
await new Promise(resolve => setTimeout(resolve, delay));
delay *= backoff; // Exponential backoff
}
} else {
// Don't retry for other errors (e.g., HTTP 4xx/5xx). Throw immediately.
throw error;
}
}
}
throw lastError; // If all retries fail, throw the last captured error.
}
// --- END: NEW AND IMPROVED CODE ---
const proceedWithVideoGeneration = async () => {
const persianPrompt = promptInput.value.trim();
const startImageFile = imageFileInputStart.files[0];
const endImageFile = imageFileInputEnd.files[0];
const duration = parseFloat(durationSlider.value);
if (!persianPrompt) { addStatusMessage('لطفاً توضیحات را وارد کنید.', 'error'); return; }
if (!startImageFile) { addStatusMessage('لطفاً تصویر شروع را انتخاب کنید.', 'error'); return; }
if (!endImageFile) { addStatusMessage('لطفاً تصویر پایان را انتخاب کنید.', 'error'); return; }
clearStatusMessages();
hideCriticalError();
generateButton.disabled = true;
resultContainer.classList.add('active');
statusSection.classList.add('active');
aiLoader.style.display = 'flex';
setProgressBar(0);
outputSection.classList.remove('active');
addStatusMessage('در حال آماده سازی...', 'info');
lastAttemptedVideoPayload = { persianPrompt, startImageFile, endImageFile, duration };
isProcessCompleted = false;
let promptForVideo = persianPrompt;
try {
setAiLoaderText("در حال ترجمه دستور شما...");
const englishPrompt = await translatePersianToEnglish(persianPrompt);
if(englishPrompt){
addStatusMessage(`ترجمه: ${englishPrompt}`, 'info');
promptForVideo = englishPrompt;
}
} catch (e) {
console.warn("Translation failed:", e.message);
addStatusMessage('ترجمه ناموفق بود. با متن فارسی ادامه می‌دهیم.', 'error');
}
const sessionHash = generateSessionHash();
try {
const uploadFile = async (file, name) => {
const formData = new FormData();
formData.append('files', file);
// --- MODIFIED: Use fetchWithRetry instead of fetch ---
const response = await fetchWithRetry(`${VIDEO_SPACE_URL}gradio_api/upload`, { method: 'POST', body: formData });
if (!response.ok) throw new Error(`خطا در آپلود ${name}: ${response.statusText}`);
return (await response.json())[0];
};
setAiLoaderText("۱/۴: آپلود تصویر شروع...");
const startServerPath = await uploadFile(startImageFile, "تصویر شروع");
setProgressBar(5);
setAiLoaderText("۲/۴: آپلود تصویر پایان...");
const endServerPath = await uploadFile(endImageFile, "تصویر پایان");
setProgressBar(10);
setAiLoaderText("۳/۴: ارسال درخواست به صف...");
const joinPayload = {
"data": [
{ "path": startServerPath, "url": `${VIDEO_SPACE_URL}gradio_api/file=${startServerPath}` },
{ "path": endServerPath, "url": `${VIDEO_SPACE_URL}gradio_api/file=${endServerPath}` },
promptForVideo,
DEFAULT_NEGATIVE_PROMPT,
duration, 8, 1, 1, 42, true
],
"fn_index": VIDEO_FN_INDEX, "session_hash": sessionHash
};
// --- MODIFIED: Use fetchWithRetry instead of fetch ---
const joinResponse = await fetchWithRetry(`${VIDEO_SPACE_URL}gradio_api/queue/join`, {
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(joinPayload)
});
if (!joinResponse.ok) throw new Error(`خطا در اتصال به صف: ${joinResponse.statusText}`);
setAiLoaderText("۴/۴: منتظر دریافت نتیجه...");
eventSource = new EventSource(`${VIDEO_SPACE_URL}gradio_api/queue/data?session_hash=${sessionHash}`);
eventSource.onmessage = async (event) => {
const data = JSON.parse(event.data);
switch (data.msg) {
case 'estimation':
addStatusMessage(`در صف انتظار... زمان تخمینی: ${Math.round(data.rank_eta)} ثانیه`);
break;
case 'process_starts':
addStatusMessage('پردازش شروع شد...');
break;
case 'progress':
if (data.progress_data && data.progress_data.length > 0) {
const p = data.progress_data[0];
let percentage = 0;
let progressText = "در حال پردازش...";
if(p.desc && p.desc.includes("Generating")) {
percentage = 15 + (p.progress || 0) * 10; // 15% to 25%
progressText = "ساخت فریم‌ها...";
} else if (p.unit === "steps" && p.index !== null) {
percentage = 25 + ((p.index + 1) / p.length) * 65; // 25% to 90%
progressText = `ساخت ویدیو: ${Math.round(percentage)}%`;
} else if(p.desc && p.desc.includes("Encoding")) {
percentage = 90 + (p.progress || 0) * 10; // 90% to 100%
progressText = "ذخیره سازی نهایی...";
}
setProgressBar(percentage);
setAiLoaderText(progressText);
}
break;
case 'process_completed':
isProcessCompleted = true;
if (data.success) {
setProgressBar(100);
setAiLoaderText("پردازش کامل شد!");
await handleSuccessfulVideoGeneration(data.output);
} else {
const errorMessage = data.output?.error || "یک خطای نامشخص رخ داد.";
const isGpuQuotaError = /exceeded your gpu quota/i.test(errorMessage);
showCriticalError(errorMessage, isGpuQuotaError);
}
eventSource.close();
eventSource = null;
break;
}
};
eventSource.onerror = (error) => {
if (isProcessCompleted) {
eventSource.close();
return;
}
console.error('EventSource failed:', error);
showCriticalError("خطا در ارتباط با سرور. لطفاً اتصال اینترنت خود را بررسی کرده و مجدداً تلاش کنید.");
eventSource.close();
eventSource = null;
};
} catch (errorCaught) {
// --- MODIFIED: Improved error handling for fetch failures ---
if (errorCaught instanceof TypeError && errorCaught.message.includes('Failed to fetch')) {
showCriticalError("خطا در ارتباط با سرور رخ داد. لطفاً اتصال اینترنت خود را بررسی کرده و مجدداً تلاش کنید. این مشکل معمولاً موقتی است.");
} else {
showCriticalError(`خطای اولیه: ${errorCaught.message}`);
}
generateButton.disabled = false;
}
};
generateButton.addEventListener('click', async () => {
if (generateButton.disabled) return;
if (userSubscriptionStatus === 'paid') {
await proceedWithVideoGeneration();
} else {
try {
const response = await fetch('/api/check-credit', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ fingerprint: userFingerprint })
});
const result = await response.json();
if(result.limit_reached) {
updateUIForSubscriptionStatus('free');
return;
}
await proceedWithVideoGeneration();
} catch (err) {
showCriticalError(`خطا در سیستم اعتبار: ${err.message}`);
}
}
});
})();
</script>
<script>
// --- Header Animation Script ---
document.addEventListener('DOMContentLoaded', () => {
const canvas = document.getElementById('neural-network-canvas');
if (!canvas) return;
const header = canvas.parentElement;
const ctx = canvas.getContext('2d');
let particles = [];
const particleCount = 20; const maxDistance = 100;
const computedStyles = getComputedStyle(document.documentElement);
const particleColor = computedStyles.getPropertyValue('--accent-primary').trim();
const lineColor = computedStyles.getPropertyValue('--text-tertiary').trim();
function resizeCanvas() { canvas.width = header.clientWidth; canvas.height = header.clientHeight; init(); }
class Particle { constructor() { this.x = Math.random() * canvas.width; this.y = Math.random() * canvas.height; this.vx = (Math.random() - 0.5) * 0.3; this.vy = (Math.random() - 0.5) * 0.3; this.radius = 1.2; } update() { this.x += this.vx; this.y += this.vy; if (this.x < 0 || this.x > canvas.width) this.vx *= -1; if (this.y < 0 || this.y > canvas.height) this.vy *= -1; } draw() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2); ctx.fillStyle = particleColor; ctx.fill(); } }
function init() { particles = []; for (let i = 0; i < particleCount; i++) { particles.push(new Particle()); } }
function connectParticles() { for (let i = 0; i < particles.length; i++) { for (let j = i + 1; j < particles.length; j++) { const dx = particles[i].x - particles[j].x; const dy = particles[i].y - particles[j].y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < maxDistance) { ctx.beginPath(); ctx.moveTo(particles[i].x, particles[i].y); ctx.lineTo(particles[j].x, particles[j].y); ctx.strokeStyle = lineColor; ctx.lineWidth = 0.2; ctx.globalAlpha = 1 - distance / maxDistance; ctx.stroke(); } } } ctx.globalAlpha = 1; }
function animate() { ctx.clearRect(0, 0, canvas.width, canvas.height); particles.forEach(particle => { particle.update(); particle.draw(); }); connectParticles(); requestAnimationFrame(animate); }
window.addEventListener('resize', resizeCanvas); resizeCanvas(); animate();
});
</script>
</body>
</html>