File size: 14,962 Bytes
da54c91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تولیدکننده ویدیو LongCat-Video-Avatar 1.5</title>
    <!-- استفاده از Tailwind CSS برای طراحی رابط کاربری -->
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;700&display=swap');
        body {
            font-family: 'Vazirmatn', sans-serif;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen p-4 md:p-8">
    <div class="max-w-4xl mx-auto bg-white rounded-xl shadow-md overflow-hidden p-6">
        <h1 class="text-2xl font-bold text-center text-gray-800 mb-6">اتصال به API ابزار LongCat-Video-Avatar 1.5</h1>
        
        <form id="generator-form" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- آپلود تصویر -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">تصویر مرجع (Image)</label>
                    <input type="file" id="image-input" accept="image/*" required class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-orange-50 file:text-orange-700 hover:file:bg-orange-100 border border-gray-300 rounded-md p-2" />
                </div>
                
                <!-- آپلود صدا -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">فایل صوتی (Audio)</label>
                    <input type="file" id="audio-input" accept="audio/*" required class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-orange-50 file:text-orange-700 hover:file:bg-orange-100 border border-gray-300 rounded-md p-2" />
                </div>
            </div>

            <!-- پرامپت متن -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">پرامپت متنی (Prompt)</label>
                <textarea id="prompt-input" rows="3" class="w-full p-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-orange-500 focus:border-orange-500" placeholder="توصیف رفتار کاراکتر...">A person is speaking expressively, looking at the camera.</textarea>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <!-- رزولوشن -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">رزولوشن (Resolution)</label>
                    <select id="resolution-input" class="w-full p-2 border border-gray-300 rounded-md">
                        <option value="480p" selected>480p</option>
                        <option value="720p">720p</option>
                    </select>
                </div>

                <!-- سید عددی -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">سید (Seed)</label>
                    <input type="number" id="seed-input" value="42" class="w-full p-2 border border-gray-300 rounded-md" />
                </div>

                <!-- پیش‌پردازش صدا -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">پیش‌پردازش صدا</label>
                    <select id="vocal-mode-input" class="w-full p-2 border border-gray-300 rounded-md">
                        <option value="Clean speech (fast)" selected>Clean speech (fast)</option>
                        <option value="Isolate vocals (quality)">Isolate vocals (quality)</option>
                    </select>
                </div>
            </div>

            <!-- شتاب‌دهنده سخت‌افزار -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">شتاب‌دهنده شبیه‌ساز (Acceleration)</label>
                <select id="acceleration-input" class="w-full p-2 border border-gray-300 rounded-md">
                    <option value="DBCache faster" selected>DBCache faster</option>
                    <option value="DBCache fast">DBCache fast</option>
                    <option value="Exact 8-step">Exact 8-step</option>
                </select>
            </div>

            <!-- دکمه تولید -->
            <button type="submit" id="submit-btn" class="w-full bg-orange-600 hover:bg-orange-700 text-white font-bold py-3 px-4 rounded-md transition duration-200">
                تولید ویدیو (Generate)
            </button>
        </form>

        <!-- بخش وضعیت و خروجی -->
        <div class="mt-8 border-t pt-6">
            <h2 class="text-lg font-bold text-gray-800 mb-4">وضعیت پردازش و خروجی</h2>
            
            <div id="status-box" class="hidden p-4 rounded-md mb-4 bg-gray-100 text-sm text-gray-700 space-y-1">
                <p id="status-text" class="font-semibold"></p>
                <div class="w-full bg-gray-300 rounded-full h-2.5 mt-2 overflow-hidden">
                    <div id="progress-bar" class="bg-orange-600 h-2.5" style="width: 0%"></div>
                </div>
            </div>

            <div id="result-box" class="hidden space-y-4">
                <p class="text-green-600 font-bold">ویدیو با موفقیت ساخته شد!</p>
                <video id="output-video" controls class="w-full rounded-md border shadow"></video>
            </div>
        </div>
    </div>

    <script>
        const BASE_SPACE_URL = "https://velocityaipartners-longcat-video-avatar-1-5-2nd.hf.space";

        const form = document.getElementById('generator-form');
        const submitBtn = document.getElementById('submit-btn');
        const statusBox = document.getElementById('status-box');
        const statusText = document.getElementById('status-text');
        const progressBar = document.getElementById('progress-bar');
        const resultBox = document.getElementById('result-box');
        const outputVideo = document.getElementById('output-video');

        // تولید Session Hash تصادفی برای Gradio
        function generateSessionHash() {
            return Math.random().toString(36).substring(2, 13);
        }

        // آپلود فایل در سرور Gradio
        async function uploadFile(file) {
            const formData = new FormData();
            formData.append('files', file);
            
            const response = await fetch(`${BASE_SPACE_URL}/gradio_api/upload`, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error('خطا در آپلود فایل');
            }

            const result = await response.json();
            return {
                path: result[0],
                meta: { _type: "gradio.FileData" },
                orig_name: file.name
            };
        }

        // یافتن شناسه تابع (fn_index) اصلی متناسب با داده‌های ورودی
        async function getFnIndex() {
            try {
                const response = await fetch(`${BASE_SPACE_URL}/config`);
                const config = await response.json();
                // پیدا کردن تابعی در کانفیگ که دقیقاً ۷ ورودی دارد
                const dependency = config.dependencies.find(dep => dep.inputs && dep.inputs.length === 7);
                return dependency ? dependency.id : 2; // در صورت پیدا نشدن، پیش‌فرض ۲
            } catch (e) {
                console.warn("خطا در خواندن خودکار کانفیگ، استفاده از پیش‌فرض ۲", e);
                return 2;
            }
        }

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            submitBtn.disabled = true;
            statusBox.classList.remove('hidden');
            resultBox.classList.add('hidden');
            progressBar.style.width = '0%';
            
            const imageFile = document.getElementById('image-input').files[0];
            const audioFile = document.getElementById('audio-input').files[0];
            const prompt = document.getElementById('prompt-input').value;
            const resolution = document.getElementById('resolution-input').value;
            const seed = parseInt(document.getElementById('seed-input').value);
            const vocalMode = document.getElementById('vocal-mode-input').value;
            const acceleration = document.getElementById('acceleration-input').value;

            try {
                // مرحله ۱: آپلود تصویر
                statusText.innerText = "در حال آپلود تصویر مرجع...";
                progressBar.style.width = '10%';
                const uploadedImage = await uploadFile(imageFile);

                // مرحله ۲: آپلود صدا
                statusText.innerText = "در حال آپلود فایل صوتی...";
                progressBar.style.width = '20%';
                const uploadedAudio = await uploadFile(audioFile);

                // مرحله ۳: استخراج دقیق fn_index
                statusText.innerText = "در حال اتصال به سرور اسپیس...";
                progressBar.style.width = '30%';
                const fnIndex = await getFnIndex();

                // مرحله ۴: پیوستن به صف پردازش
                statusText.innerText = "در حال پیوستن به صف پردازش...";
                progressBar.style.width = '40%';
                const sessionHash = generateSessionHash();

                const payload = {
                    data: [
                        uploadedImage,
                        uploadedAudio,
                        prompt,
                        resolution,
                        seed,
                        vocalMode,
                        acceleration
                    ],
                    fn_index: fnIndex,
                    session_hash: sessionHash
                };

                const joinResponse = await fetch(`${BASE_SPACE_URL}/gradio_api/queue/join`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });

                if (!joinResponse.ok) {
                    throw new Error('خطا در الحاق به صف پردازش');
                }

                // مرحله ۵: گوش دادن به وب‌سوکت/SSE برای دریافت رویدادها
                const eventSource = new EventSource(`${BASE_SPACE_URL}/gradio_api/queue/data?session_hash=${sessionHash}`);
                
                eventSource.onmessage = (event) => {
                    const data = JSON.parse(event.data);
                    
                    if (data.msg === 'estimation') {
                        const queueSize = data.queue_size || 0;
                        const rank = data.rank !== undefined ? data.rank : '?';
                        statusText.innerText = `در صف انتظار. رتبه شما در صف: ${rank} (تعداد کل صف: ${queueSize})`;
                        progressBar.style.width = '50%';
                    } 
                    else if (data.msg === 'progress') {
                        if (data.progress_data && data.progress_data.length > 0) {
                            const prog = data.progress_data[0];
                            const unit = prog.unit || '';
                            const desc = prog.desc || 'در حال پردازش نسل ویدیو';
                            const index = prog.index || 0;
                            const total = prog.length || 8; // معمولاً ۸ استپ dmd2
                            const percentage = Math.min(50 + Math.round((index / total) * 45), 95);
                            statusText.innerText = `${desc} (مرحله ${index} از ${total} ${unit})`;
                            progressBar.style.width = `${percentage}%`;
                        } else {
                            statusText.innerText = "سیستم در حال آماده‌سازی و پردازش مدل در GPU است...";
                            progressBar.style.width = '60%';
                        }
                    } 
                    else if (data.msg === 'process_generating') {
                        statusText.innerText = "پردازش نهایی و تولید خروجی...";
                        progressBar.style.width = '90%';
                    }
                    else if (data.msg === 'process_completed') {
                        eventSource.close();
                        progressBar.style.width = '100%';
                        
                        if (data.success && data.output && data.output.data) {
                            const videoData = data.output.data[0];
                            // ویدیو در خروجی اول ذخیره می‌شود
                            if (videoData && videoData.url) {
                                statusText.innerText = "تولید با موفقیت انجام شد.";
                                outputVideo.src = videoData.url;
                                resultBox.classList.remove('hidden');
                            } else {
                                throw new Error('ویدیو تولید شد اما آدرس فایل یافت نشد.');
                            }
                        } else {
                            const errorMsg = data.output?.error || 'خطای نامشخص در حین پردازش مدل';
                            throw new Error(errorMsg);
                        }
                        submitBtn.disabled = false;
                    }
                    else if (data.msg === 'queue_full') {
                        eventSource.close();
                        throw new Error('صف سرور در حال حاضر پر است. مجدداً تلاش کنید.');
                    }
                };

                eventSource.onerror = (err) => {
                    eventSource.close();
                    throw new Error('ارتباط با سرور در صف قطع شد.');
                };

            } catch (error) {
                console.error(error);
                statusText.innerHTML = `<span class="text-red-600">خطا: ${error.message}</span>`;
                progressBar.style.width = '0%';
                submitBtn.disabled = false;
            }
        });
    </script>
</body>
</html>