File size: 12,370 Bytes
874bf5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

/*
  document.addEventListener('DOMContentLoaded', () => {
   var GotitB = document.querySelector(".explainChoix button")
var explain = document.querySelector(".explainChoix")
var SummarizeInput = document.querySelector(".SummarizeInput")
var CaptionInput = document.querySelector(".CaptionInput")
GotitB.addEventListener("click",()=>{
   explain.style.opacity="0"
})

document.querySelectorAll('.select-options input[type="radio"]').forEach(radio => {
    radio.addEventListener('change', (e) => {
      if (e.target.checked) {
        const selectedValue = e.target.value;
        if(selectedValue=="Summarize"){
          SummarizeInput.classList.add("active")
          SummarizeInput.classList.remove("innactive")
          CaptionInput.classList.remove("active")
          CaptionInput.classList.add("innactive")
        }
        else{
          SummarizeInput.classList.add("innactive")
          SummarizeInput.classList.remove("active")
          CaptionInput.classList.remove("innactive")
          CaptionInput.classList.add("active")
        }
      }
    });
  });
    const fileUpload = document.getElementById('file-upload');
    const imageUpload = document.getElementById('image-upload');
    
    // Get the icon buttons
    const fileBtn = document.getElementById('file-btn');
    const imageBtn = document.getElementById('image-btn');
    
    // Set up file input for documents (PDF, DOCX, PPTX, XLSX)
    fileBtn.addEventListener('click', () => {
      fileUpload.click();
    });
    
    fileUpload.addEventListener('change', (e) => {
      if (e.target.files.length > 0) {
        const file = e.target.files[0];
        const validDocTypes = [
          'application/pdf',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.openxmlformats-officedocument.presentationml.presentation',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ];
        
        if (validDocTypes.includes(file.type)) {
          console.log('Valid document selected:', file.name);
          // Handle the document file here
        } else {
          alert('Please select a valid document (PDF, DOCX, PPTX, or XLSX)');
          fileUpload.value = ''; // Reset the input
        }
      }
    });
    
    // Set up file input for images
    imageBtn.addEventListener('click', () => {
      imageUpload.click();
    });
    
    imageUpload.addEventListener('change', (e) => {
      if (e.target.files.length > 0) {
        const file = e.target.files[0];
        const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        
        if (validImageTypes.includes(file.type)) {
          console.log('Valid image selected:', file.name);
          // Handle the image file here
        } else {
          alert('Please select a valid image (JPEG, PNG, GIF, or WEBP)');
          imageUpload.value = ''; // Reset the input
        }
      }
    });
  });*/
document.addEventListener('DOMContentLoaded', () => {
    // UI Elements
    const GotitB = document.querySelector(".explainChoix button");
    const explain = document.querySelector(".explainChoix");
    const SummarizeInput = document.querySelector(".SummarizeInput");
    const CaptionInput = document.querySelector(".CaptionInput");
    const fileUpload = document.getElementById('file-upload');
    const imageUpload = document.getElementById('image-upload');
    const fileBtn = document.getElementById('file-btn');
    const imageBtn = document.getElementById('image-btn');
    const convo = document.querySelector('.convo');

    // Hide explanation after click
    GotitB.addEventListener("click", () => {
        explain.style.opacity = "0";
    });

    // Handle mode switching
    document.querySelectorAll('.select-options input[type="radio"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            if (e.target.checked) {
                const selectedValue = e.target.value;
                if (selectedValue === "Summarize") {
                    SummarizeInput.classList.add("active");
                    SummarizeInput.classList.remove("innactive");
                    CaptionInput.classList.remove("active");
                    CaptionInput.classList.add("innactive");
                } else {
                    SummarizeInput.classList.add("innactive");
                    SummarizeInput.classList.remove("active");
                    CaptionInput.classList.remove("innactive");
                    CaptionInput.classList.add("active");
                }
            }
        });
    });

    // File upload handlers
    fileBtn.addEventListener('click', () => fileUpload.click());
    imageBtn.addEventListener('click', () => imageUpload.click());

    // Send button handlers
    document.querySelectorAll('.sendingQA').forEach(button => {
        button.addEventListener('click', async () => {
            const isSummarizeMode = document.querySelector('input[name="option"]:checked').value === 'Summarize';
            
            if (isSummarizeMode) {
                await handleSummarize();
            } else {
                await handleCaption();
            }
        });
    });

    // Drag and drop functionality
    convo.addEventListener('dragover', (e) => {
        e.preventDefault();
        convo.classList.add('drag-over');
    });

    convo.addEventListener('dragleave', () => {
        convo.classList.remove('drag-over');
    });

    convo.addEventListener('drop', async (e) => {
        e.preventDefault();
        convo.classList.remove('drag-over');
        
        if (e.dataTransfer.files.length) {
            const file = e.dataTransfer.files[0];
            const isSummarizeMode = document.querySelector('input[name="option"]:checked').value === 'Summarize';
            
            if (isSummarizeMode) {
                fileUpload.files = e.dataTransfer.files;
                await handleSummarize();
            } else {
                imageUpload.files = e.dataTransfer.files;
                await handleCaption();
            }
        }
    });

    // Handle document summarization
    async function handleSummarize() {
        const file = fileUpload.files[0];
        if (!file) {
            displayError('Please upload a document first');
            return;
        }

        const length = document.querySelector('input[name="optionS"]:checked').value;
        
        try {
            // Show loading state
            convo.innerHTML = '';
            displayFileInfo(file.name, 'document');
            displayThinkingMessage();
            
            // Call API
            const result = await summarizeDocument(file, length);
            
            // Display results
            displaySummaryResult(file.name, result.summary, result.audioUrl, result.pdfUrl);
        } catch (error) {
            displayError(error.message || 'Failed to summarize document');
        }
    }

    // Handle image captioning
    async function handleCaption() {
        const file = imageUpload.files[0];
        if (!file) {
            displayError('Please upload an image first');
            return;
        }

        try {
            // Show loading state
            convo.innerHTML = '';
            displayFileInfo(file.name, 'image');
            displayThinkingMessage();
            
            // Call API
            const caption = await captionImage(file);
            
            // Display results
            displayCaptionResult(file.name, caption);
        } catch (error) {
            displayError(error.message || 'Failed to generate caption');
        }
    }

    // API Functions
    async function summarizeDocument(file, length) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('length', length);

        const response = await fetch('/summarize', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.detail || 'Summarization failed');
        }
        
        return await response.json();
    }

    async function captionImage(file) {
        const formData = new FormData();
        formData.append('file', file);

        const response = await fetch('/caption', {
            method: 'POST',
            body: formData
        });
        
        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.detail || 'Captioning failed');
        }
        
        const result = await response.json();
        return result.caption;
    }

    // UI Helper Functions
    function displayFileInfo(filename, type) {
        const bubble = document.createElement('div');
        bubble.className = 'bubble right';
        bubble.innerHTML = `
            <div class="label">You</div>
            <div class="text">${type === 'document' ? '๐Ÿ“„' : '๐Ÿ–ผ๏ธ'} ${filename}</div>
        `;
        convo.appendChild(bubble);
    }

    function displayThinkingMessage() {
        const bubble = document.createElement('div');
        bubble.className = 'bubble left';
        bubble.innerHTML = `
            <div class="label">Aidan</div>
            <div class="text">
                <div style="display:flex;align-items:center;gap:8px">
                    <span>Processing your ${document.querySelector('input[name="option"]:checked').value.toLowerCase()}...</span>
                    <div class="loader"></div>
                </div>
            </div>
        `;
        convo.appendChild(bubble);
        convo.scrollTop = convo.scrollHeight;
    }

    function displaySummaryResult(filename, summary, audioUrl, pdfUrl) {
        // Remove thinking message
        convo.removeChild(convo.lastChild);
        
        const bubble = document.createElement('div');
        bubble.className = 'bubble left';
        bubble.innerHTML = `
            <div class="label">Aidan</div>
            <div class="text">
                <strong>Summary:</strong><br><br>
                ${summary.replace(/\n/g, '<br>')}
                ${audioUrl ? `<br><br><audio controls src="${audioUrl}" style="width: 100%;"></audio>` : ''}
                ${pdfUrl ? `<br><a href="${pdfUrl}" download="${filename.split('.')[0]}_summary.pdf" class="download-link">๐Ÿ“ฅ Download PDF Summary</a>` : ''}
            </div>
        `;
        convo.appendChild(bubble);
        convo.scrollTop = convo.scrollHeight;
    }

    function displayCaptionResult(filename, caption) {
        // Remove thinking message
        convo.removeChild(convo.lastChild);
        
        const bubble = document.createElement('div');
        bubble.className = 'bubble left';
        bubble.innerHTML = `
            <div class="label">Aidan</div>
            <div class="text">
                <strong>Caption:</strong><br><br>
                ${caption}
            </div>
        `;
        convo.appendChild(bubble);
        convo.scrollTop = convo.scrollHeight;
    }

    function displayError(message) {
        const bubble = document.createElement('div');
        bubble.className = 'bubble left';
        bubble.innerHTML = `
            <div class="label">Aidan</div>
            <div class="text" style="color: #ef4444;">
                โš ๏ธ ${message}
            </div>
        `;
        convo.appendChild(bubble);
        convo.scrollTop = convo.scrollHeight;
    }

    // Add loader CSS
    const style = document.createElement('style');
    style.textContent = `
        .loader {
            border: 2px solid #f3f3f3;
            border-top: 2px solid #3b82f6;
            border-radius: 50%;
            width: 16px;
            height: 16px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .download-link {
            display: inline-block;
            margin-top: 10px;
            padding: 5px 10px;
            background: #3b82f6;
            color: white;
            border-radius: 5px;
            text-decoration: none;
        }
        .download-link:hover {
            background: #2563eb;
        }
    `;
    document.head.appendChild(style);
});