File size: 14,730 Bytes
4abfe80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
let processingMethod = '';
let currentSummaryVersion = 0;
let totalSummaryVersions = 1;
let summaryVersions = [];
let currentVideoTitle = '';
let currentVideoUrl = '';

window.updateSummaryDisplay = function() {
    if (summaryVersions.length > 0 && summaryVersions[currentSummaryVersion]) {
        document.getElementById('finalSummary').innerHTML = linkifyText(summaryVersions[currentSummaryVersion]);
        document.getElementById('summaryVersion').textContent = `版本:${currentSummaryVersion + 1}/${totalSummaryVersions}`;
        document.getElementById('prevVersion').disabled = currentSummaryVersion === 0;
        document.getElementById('nextVersion').disabled = currentSummaryVersion === totalSummaryVersions - 1;
    } else {
        console.error('No summary available for the current version');
        document.getElementById('finalSummary').innerHTML = '暫無可用摘要';
    }
}
document.addEventListener('DOMContentLoaded', (event) => {

    document.getElementById('refineSummary').addEventListener('click', showSummaryLightbox);
    document.getElementById('submitFeedback').addEventListener('click', submitFeedback);
    document.getElementById('prevVersion').addEventListener('click', () => changeSummaryVersion(-1));
    document.getElementById('nextVersion').addEventListener('click', () => changeSummaryVersion(1));
    
    // 點擊 Lightbox 外部關閉
    document.getElementById('summaryLightbox').addEventListener('click', function(e) {
        if (e.target === this) {
            hideSummaryLightbox();
        }
    });

    function updateSummaryDisplay() {
        console.log("Updating summary display", { currentSummaryVersion, totalSummaryVersions, summaryVersions });
        if (summaryVersions.length > 0 && summaryVersions[currentSummaryVersion]) {
            document.getElementById('finalSummary').innerHTML = linkifyText(summaryVersions[currentSummaryVersion]);
            document.getElementById('summaryVersion').textContent = `版本:${currentSummaryVersion + 1}/${totalSummaryVersions}`;
            document.getElementById('prevVersion').disabled = currentSummaryVersion === 0;
            document.getElementById('nextVersion').disabled = currentSummaryVersion === totalSummaryVersions - 1;
        } else {
            console.error('No summary available for the current version');
            document.getElementById('finalSummary').innerHTML = '暫無可用摘要';
        }
    }
    
    function showSummaryLightbox() {
        document.getElementById('summaryLightbox').classList.remove('hidden');
        document.getElementById('submitFeedback').disabled = false;
        document.getElementById('feedbackLoading').classList.add('hidden');
    }

    function hideSummaryLightbox() {
        document.getElementById('summaryLightbox').classList.add('hidden');
    }

    function submitFeedback() {
    console.log("開始提交反饋");
    console.log("當前摘要版本:", currentSummaryVersion);
    console.log("總摘要版本數:", totalSummaryVersions);
    const feedback = document.getElementById('userFeedback').value;
    const originalSummary = summaryVersions[currentSummaryVersion];
    const videoInfoContent = document.getElementById('videoInfoContent').textContent;
    let videoTitle = currentVideoTitle;
    let videoUrl = currentVideoUrl;

    // 顯示 loading 效果,禁用提交按鈕
    document.getElementById('submitFeedback').disabled = true;
    document.getElementById('feedbackLoading').classList.remove('hidden');
    
    // 禁用點擊外部關閉
    document.getElementById('summaryLightbox').style.pointerEvents = 'none';

    // 移除原始摘要中的視頻信息
    const summaryWithoutInfo = originalSummary.split('\n').slice(2).join('\n').trim();

    console.log("Submitting feedback:", {
        original_summary: summaryWithoutInfo,
        user_feedback: feedback,
        video_title: videoTitle,
        video_url: videoUrl
    });

    fetch('/refine_summary', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            original_summary: summaryWithoutInfo,
            user_feedback: feedback,
            video_title: videoTitle,
            video_url: videoUrl,
            processed_description: document.getElementById('videoInfoContent').textContent
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log("Received data from server:", data);
        if (data.error) {
            throw new Error(data.error);
        }
        if (data.refined_summary) {
            console.log("收到新的摘要:", data.refined_summary);
            
            // 添加新摘要到陣列
            summaryVersions.push(data.refined_summary);
            
            // 更新當前版本為最新版本
            currentSummaryVersion = summaryVersions.length - 1;
            
            // 更新總版本數
            totalSummaryVersions = summaryVersions.length;
            
            console.log("更新後的版本信息:", {
                currentSummaryVersion: currentSummaryVersion,
                totalSummaryVersions: totalSummaryVersions,
                summaryVersionsLength: summaryVersions.length
            });
        
            // 更新顯示
            window.updateSummaryDisplay();
        
            console.log("摘要顯示已更新");
        
            // 隱藏反饋輸入框
            hideSummaryLightbox();
        } else {
            console.error("收到的摘要為空");
            throw new Error("收到的摘要為空");
        }
        hideSummaryLightbox();
    })
    .catch(error => {
        console.error('Error during feedback submission:', error);
        alert('提交反饋時出錯: ' + error.message);
    })
    .finally(() => {
        // 恢復提交按鈕,隱藏 loading 效果
        document.getElementById('submitFeedback').disabled = false;
        document.getElementById('feedbackLoading').classList.add('hidden');
        // 恢復點擊外部關閉
        document.getElementById('summaryLightbox').style.pointerEvents = 'auto';
    });
}
    
    

    function changeSummaryVersion(delta) {
        currentSummaryVersion += delta;
        if (currentSummaryVersion < 0) currentSummaryVersion = 0;
        if (currentSummaryVersion >= totalSummaryVersions) currentSummaryVersion = totalSummaryVersions - 1;
        window.updateSummaryDisplay(); // 使用 window.updateSummaryDisplay
    }
    

    document.getElementById('youtubeBtn').addEventListener('click', () => {
        processingMethod = 'youtube';
        document.getElementById('youtubeInput').classList.remove('hidden');
        document.getElementById('localVideoInput').classList.add('hidden');
    });

    document.getElementById('localVideoBtn').addEventListener('click', () => {
        processingMethod = 'local';
        document.getElementById('localVideoInput').classList.remove('hidden');
        document.getElementById('youtubeInput').classList.add('hidden');
    });

    document.getElementById('startProcessing').addEventListener('click', () => {
        let url_or_path = '';
        if (processingMethod === 'youtube') {
            url_or_path = document.getElementById('youtubeUrl').value;
        } else if (processingMethod === 'local') {
            const fileInput = document.getElementById('localVideoFile');
            if (fileInput.files.length > 0) {
                url_or_path = fileInput.files[0].name;
            }
        }

        if (!url_or_path) {
            alert('請選擇處理方式並輸入 URL 或選擇文件');
            return;
        }

        if (hasExistingContent()) {
            if (confirm('開始新的處理任務將清空當前內容。是否繼續?')) {
                clearPreviousContent();
                startProcessing(url_or_path);
            }
        } else {
            startProcessing(url_or_path);
        }
    });

    document.getElementById('toggleTranscript').addEventListener('click', () => {
        const transcript = document.getElementById('transcript');
        transcript.style.display = transcript.style.display === 'none' ? 'block' : 'none';
    });
});

function hasExistingContent() {
    return !document.getElementById('videoInfo').classList.contains('hidden') ||
        !document.getElementById('summary').classList.contains('hidden') ||
        !document.getElementById('segmentSummaries').classList.contains('hidden') ||
        document.getElementById('transcript').textContent.trim() !== '';
}

function clearPreviousContent() {
    // 清空 UI 內容
    document.getElementById('videoInfo').classList.add('hidden');
    document.getElementById('videoInfoContent').textContent = '';
    document.getElementById('status').classList.add('hidden');
    document.getElementById('status').textContent = '';
    document.getElementById('summary').classList.add('hidden');
    document.getElementById('finalSummary').innerHTML = '';
    document.getElementById('segmentSummaries').classList.add('hidden');
    document.getElementById('summaries').innerHTML = '';
    document.getElementById('transcript').textContent = '';

    // 重置全局變量
    currentSummaryVersion = 0;
    totalSummaryVersions = 1;  // 重置為 1
    summaryVersions = [];
    
    // 重置版本顯示
    document.getElementById('summaryVersion').textContent = '版本:1/1';
    
    // 禁用版本切換按鈕
    document.getElementById('prevVersion').disabled = true;
    document.getElementById('nextVersion').disabled = true;
    
    // 清空反饋輸入框
    document.getElementById('userFeedback').value = '';
}

function startProcessing(url_or_path) {
    clearPreviousContent(); 
    currentVideoTitle = '';
    currentVideoUrl = url_or_path;
    document.getElementById('status').classList.remove('hidden');
    document.getElementById('status').textContent = '⌛️ 處理中...';
    
    const formData = new FormData();
    formData.append('url_or_path', url_or_path);
    if (processingMethod === 'local') {
        const fileInput = document.getElementById('localVideoFile');
        if (fileInput.files.length > 0) {
            formData.append('file', fileInput.files[0]);
            currentVideoTitle = fileInput.files[0].name;
        }
        formData.append('localVideoDescription', document.getElementById('localVideoDescription').value);
    } else {
        currentVideoTitle = ''; // 將在收到視頻信息時更新
    }

    fetch('/process', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        
        function readStream() {
            return reader.read().then(({ done, value }) => {
                if (done) {
                    console.log('Stream complete');
                    return;
                }
                const chunk = decoder.decode(value);
                handleServerSentEvent(chunk);
                return readStream();
            });
        }
        
        return readStream();
    })
    .catch(error => {
        console.error('Error:', error);
        document.getElementById('status').textContent = `錯誤: ${error.message}`;
    });
}

function handleServerSentEvent(chunk) {
    const lines = chunk.split('\n');
    lines.forEach(line => {
        if (line.startsWith('data: ')) {
            const data = JSON.parse(line.slice(6));
            updateUI(data);
        }
    });
}

function updateUI(data) {
    document.getElementById('status').textContent = data.status;
    
    
    if (data.video_info) {
        document.getElementById('videoInfo').classList.remove('hidden');
        let videoInfoContent = `標題:${data.video_info.title}\n`;
        videoInfoContent += `時長:${data.video_info.duration}\n`;
        videoInfoContent += `觀看次數:${data.video_info.view_count}\n`;
        videoInfoContent += `喜歡數:${data.video_info.like_count}\n`;
        videoInfoContent += `描述:${data.video_info.description}`;
        
        if (videoInfoContent.length > 300) {
            videoInfoContent = videoInfoContent.substring(0, 300) + '... ...';
        }
        
        document.getElementById('videoInfoContent').textContent = videoInfoContent;
        // 更新當前視頻標題
        currentVideoTitle = data.video_info.title;
    }
    
    console.log("Received data:", data);

    if (data.final_summary) {
        console.log("Updating final summary");
        document.getElementById('summary').classList.remove('hidden');
        const summaryWithInfo = `影片名稱:${currentVideoTitle}\n網址或路徑:${currentVideoUrl}\n\n${data.final_summary}`;

        /* // 從視頻信息中獲取標題和 URL/路徑

        const videoTitle = document.getElementById('videoInfoContent').textContent.split('\n')[0].replace('標題:', '').trim();

        const videoUrl = document.getElementById('youtubeUrl').value || document.getElementById('localVideoFile').value;

        

        // 在摘要前添加影片名稱和 URL/路徑信息

        const summaryWithInfo = `影片名稱:${videoTitle}\n網址或路徑:${videoUrl}\n\n${data.final_summary}`; */
        
        summaryVersions = [summaryWithInfo];
        currentSummaryVersion = 0;
        totalSummaryVersions = 1;  // 重置為 1
        console.log("Calling updateSummaryDisplay");
        window.updateSummaryDisplay();
        console.log("updateSummaryDisplay called");
    }
    
    if (data.summary) {
        document.getElementById('segmentSummaries').classList.remove('hidden');
        document.getElementById('summaries').innerHTML += linkifyText(data.summary) + '\n\n';
    }
    
    if (data.transcript) {
        document.getElementById('transcript').textContent = data.transcript;
    }
    
    if (data.error) {
        alert(data.error);
    }
}

function linkifyText(text) {
    const urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return `<a href="${url}" target="_blank" class="text-blue-600 hover:underline">${url}</a>`;
    });
}