File size: 33,854 Bytes
5f30414
 
 
 
 
 
 
 
 
 
 
 
7478cb5
 
 
5f30414
 
 
114ad9c
 
5f30414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114ad9c
5f30414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114ad9c
5f30414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a027b34
5f30414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114ad9c
5f30414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc7e8e9
5f30414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc7e8e9
5f30414
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a76c6b6
 
5f30414
 
 
 
a76c6b6
 
 
 
 
 
5f30414
 
 
 
 
a76c6b6
5f30414
a76c6b6
5f30414
 
a76c6b6
5f30414
 
114ad9c
a76c6b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114ad9c
5f30414
 
a76c6b6
114ad9c
 
a76c6b6
 
5f30414
114ad9c
5f30414
a76c6b6
5f30414
a76c6b6
114ad9c
5f30414
 
a76c6b6
 
5f30414
 
 
 
 
 
 
a76c6b6
 
 
 
 
 
5f30414
 
 
a76c6b6
5f30414
a76c6b6
5f30414
a76c6b6
114ad9c
a76c6b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f30414
a76c6b6
 
 
 
 
 
 
 
5f30414
a76c6b6
114ad9c
5f30414
 
 
 
 
 
a76c6b6
5f30414
 
a76c6b6
114ad9c
a76c6b6
 
 
 
 
 
 
 
 
114ad9c
a76c6b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114ad9c
5f30414
 
a76c6b6
114ad9c
 
a76c6b6
 
5f30414
114ad9c
5f30414
a76c6b6
5f30414
a76c6b6
114ad9c
5f30414
 
a76c6b6
 
5f30414
 
 
 
114ad9c
5f30414
 
a76c6b6
 
 
 
 
 
 
5f30414
 
 
a76c6b6
5f30414
a76c6b6
5f30414
a76c6b6
114ad9c
a76c6b6
 
 
 
 
 
 
 
5f30414
a76c6b6
 
114ad9c
5f30414
 
a76c6b6
 
 
 
 
 
 
 
 
5f30414
a76c6b6
114ad9c
5f30414
a76c6b6
 
5f30414
 
 
 
 
 
a76c6b6
5f30414
 
a76c6b6
5f30414
a76c6b6
 
 
 
 
 
 
 
 
 
 
 
 
 
5f30414
a76c6b6
5f30414
114ad9c
 
a76c6b6
 
114ad9c
5f30414
114ad9c
a76c6b6
 
 
 
 
 
 
 
 
 
 
114ad9c
 
a76c6b6
114ad9c
5f30414
 
a76c6b6
5f30414
 
a76c6b6
 
5f30414
 
 
 
 
a76c6b6
5f30414
a76c6b6
5f30414
a76c6b6
 
 
 
 
 
 
 
 
 
5f30414
 
a76c6b6
 
5f30414
a76c6b6
5f30414
a76c6b6
5f30414
 
a76c6b6
5f30414
 
a76c6b6
 
 
 
 
 
 
5f30414
a76c6b6
 
 
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
from flask import Flask, request, jsonify, render_template_string
from flask_cors import CORS
from google import genai
from google.genai import types
import os
import io
import httpx
import uuid
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv
import json

# Load environment variables
load_dotenv()

app = Flask(__name__)
CORS(app)

# Initialize Gemini client
client = genai.Client(api_key=os.getenv('GOOGLE_API_KEY'))

# In-memory storage for demo (in production, use a database)
document_caches = {}
user_sessions = {}

# HTML template for the web interface
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Document Analysis Platform</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            min-height: 100vh;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }
        
        .header h1 {
            font-size: 2.8em;
            font-weight: 700;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        
        .header p {
            font-size: 1.2em;
            opacity: 0.9;
            font-weight: 300;
        }
        
        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            height: calc(100vh - 200px);
        }
        
        .left-panel {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow-y: auto;
        }
        
        .right-panel {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }
        
        .panel-title {
            font-size: 1.5em;
            font-weight: 600;
            margin-bottom: 20px;
            color: #2d3748;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .upload-section {
            margin-bottom: 30px;
        }
        
        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 15px;
            padding: 40px;
            text-align: center;
            background: #f8fafc;
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }
        
        .upload-area:hover {
            border-color: #764ba2;
            background: #f0f2ff;
            transform: translateY(-2px);
        }
        
        .upload-area.dragover {
            border-color: #764ba2;
            background: #e8f0ff;
            transform: scale(1.02);
        }
        
        .upload-icon {
            font-size: 3em;
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .file-input {
            display: none;
        }
        
        .upload-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 1.1em;
            font-weight: 500;
            transition: all 0.3s ease;
            margin: 10px;
        }
        
        .upload-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }
        
        .url-input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 1em;
            margin-bottom: 15px;
            transition: border-color 0.3s ease;
        }
        
        .url-input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .chat-container {
            flex: 1;
            border: 1px solid #e2e8f0;
            border-radius: 15px;
            overflow-y: auto;
            padding: 20px;
            background: #f8fafc;
            margin-bottom: 20px;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 15px;
            border-radius: 12px;
            max-width: 85%;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .user-message {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin-left: auto;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .ai-message {
            background: white;
            color: #333;
            border: 1px solid #e2e8f0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .input-group {
            display: flex;
            gap: 10px;
        }
        
        .question-input {
            flex: 1;
            padding: 15px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 1em;
            transition: border-color 0.3s ease;
        }
        
        .question-input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .cache-info {
            background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            color: white;
            box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
        }
        
        .cache-info h3 {
            margin-bottom: 10px;
            font-weight: 600;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .loading-spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .error {
            background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
            border-radius: 12px;
            padding: 15px;
            color: white;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(245, 101, 101, 0.3);
        }
        
        .success {
            background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
            border-radius: 12px;
            padding: 15px;
            color: white;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
        }
        
        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .header h1 {
                font-size: 2em;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>πŸ“š Smart Document Analysis Platform</h1>
            <p>Upload PDF documents once, ask questions forever with Gemini API caching</p>
        </div>
        
        <div class="main-content">
            <!-- Left Panel - Upload Section -->
            <div class="left-panel">
                <div class="panel-title">
                    πŸ“€ Upload PDF Document
                </div>
                
                <div class="upload-section">
                    <div class="upload-area" id="uploadArea">
                        <div class="upload-icon">πŸ“„</div>
                        <p>Drag and drop your PDF file here, or click to select</p>
                        <input type="file" id="fileInput" class="file-input" accept=".pdf">
                        <button class="upload-btn" onclick="document.getElementById('fileInput').click()">
                            Choose PDF File
                        </button>
                    </div>
                    
                    <div style="margin-top: 20px;">
                        <h3>Or provide a URL:</h3>
                        <input type="url" id="urlInput" class="url-input" placeholder="https://example.com/document.pdf">
                        <button class="btn" onclick="uploadFromUrl()">Upload from URL</button>
                    </div>
                </div>
                
                <div id="loading" class="loading" style="display: none;">
                    <div class="loading-spinner"></div>
                    <p id="loadingText">Processing your PDF... This may take a moment.</p>
                </div>
                
                <div id="error" class="error" style="display: none;"></div>
                <div id="success" class="success" style="display: none;"></div>
            </div>
            
            <!-- Right Panel - Chat Section -->
            <div class="right-panel">
                <div class="panel-title">
                    πŸ’¬ Ask Questions
                </div>
                
                <div id="cacheInfo" class="cache-info" style="display: none;">
                    <h3>βœ… Document Cached Successfully!</h3>
                    <p>Your PDF has been cached using Gemini API. You can now ask multiple questions without re-uploading.</p>
                    <p><strong>Cache ID:</strong> <span id="cacheId"></span></p>
                    <p><strong>Tokens Cached:</strong> <span id="tokenCount"></span></p>
                </div>
                
                <div class="chat-container" id="chatContainer">
                    <div class="message ai-message">
                        πŸ‘‹ Hello! I'm ready to analyze your PDF documents. Upload a document to get started!
                    </div>
                </div>
                
                <div class="input-group">
                    <input type="text" id="questionInput" class="question-input" placeholder="Ask a question about your document...">
                    <button class="btn" onclick="askQuestion()" id="askBtn">Ask</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentCacheId = null;
        
        // File upload handling
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                uploadFile(files[0]);
            }
        });
        
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                uploadFile(e.target.files[0]);
            }
        });
        
        async function uploadFile(file) {
            if (!file.type.includes('pdf')) {
                showError('Please select a PDF file.');
                return;
            }
            
            showLoading('Uploading PDF...');
            
            const formData = new FormData();
            formData.append('file', file);
            
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    currentCacheId = result.cache_id;
                    document.getElementById('cacheId').textContent = result.cache_id;
                    document.getElementById('tokenCount').textContent = result.token_count;
                    document.getElementById('cacheInfo').style.display = 'block';
                    showSuccess('PDF uploaded and cached successfully!');
                    
                    // Add initial message
                    addMessage("I've analyzed your PDF document. What would you like to know about it?", 'ai');
                } else {
                    showError(result.error);
                }
            } catch (error) {
                showError('Error uploading file: ' + error.message);
            } finally {
                hideLoading();
            }
        }
        
        async function uploadFromUrl() {
            const url = document.getElementById('urlInput').value;
            if (!url) {
                showError('Please enter a valid URL.');
                return;
            }
            
            showLoading('Uploading PDF from URL...');
            
            try {
                const response = await fetch('/upload-url', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ url: url })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    currentCacheId = result.cache_id;
                    document.getElementById('cacheId').textContent = result.cache_id;
                    document.getElementById('tokenCount').textContent = result.token_count;
                    document.getElementById('cacheInfo').style.display = 'block';
                    showSuccess('PDF uploaded and cached successfully!');
                    
                    // Add initial message
                    addMessage("I've analyzed your PDF document. What would you like to know about it?", 'ai');
                } else {
                    showError(result.error);
                }
            } catch (error) {
                showError('Error uploading from URL: ' + error.message);
            } finally {
                hideLoading();
            }
        }
        
        async function askQuestion() {
            const question = document.getElementById('questionInput').value;
            if (!question.trim()) return;
            
            if (!currentCacheId) {
                showError('Please upload a PDF document first.');
                return;
            }
            
            // Add user message to chat
            addMessage(question, 'user');
            document.getElementById('questionInput').value = '';
            
            // Show loading state
            const askBtn = document.getElementById('askBtn');
            const originalText = askBtn.textContent;
            askBtn.textContent = 'Generating...';
            askBtn.disabled = true;
            
            try {
                const response = await fetch('/ask', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        question: question,
                        cache_id: currentCacheId
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    addMessage(result.answer, 'ai');
                } else {
                    addMessage('Error: ' + result.error, 'ai');
                }
            } catch (error) {
                addMessage('Error: ' + error.message, 'ai');
            } finally {
                askBtn.textContent = originalText;
                askBtn.disabled = false;
            }
        }
        
        function addMessage(text, sender) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}-message`;
            messageDiv.textContent = text;
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
        
        function showLoading(text = 'Processing...') {
            document.getElementById('loadingText').textContent = text;
            document.getElementById('loading').style.display = 'block';
        }
        
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }
        
        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            setTimeout(() => {
                errorDiv.style.display = 'none';
            }, 5000);
        }
        
        function showSuccess(message) {
            const successDiv = document.getElementById('success');
            successDiv.textContent = message;
            successDiv.style.display = 'block';
            setTimeout(() => {
                successDiv.style.display = 'none';
            }, 5000);
        }
        
        // Enter key to ask question
        document.getElementById('questionInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                askQuestion();
            }
        });
    </script>
</body>
</html>
"""

# ... (imports and initial setup) ...

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

# Add health check endpoint
@app.route('/health', methods=['GET'])
def health_check():
    # A simple endpoint to check if the application is running
    return jsonify({"status": "healthy"}), 200

@app.route('/upload', methods=['POST'])
def upload_file():
    try:
        if 'file' not in request.files:
            return jsonify({'success': False, 'error': 'No file provided'})

        file = request.files['file']

        if file.filename == '':
            return jsonify({'success': False, 'error': 'No file selected'})

        # Read file content
        file_content = file.read()
        file_io = io.BytesIO(file_content)

        # --- CORRECTED FILE UPLOAD CALL ---
        # Upload to Gemini File API using the correct method client.upload_file
        # Pass the file content as a tuple (filename, file-like object, mime_type)
        # This replaces the incorrect client.files.upload call
        try:
            document = client.upload_file(
                file=(file.filename, file_io, 'application/pdf'),
                display_name=file.filename # Optional: provide a display name
            )
            print(f"File uploaded successfully: {document.name}") # Log for debugging
        except Exception as upload_error:
             return jsonify({'success': False, 'error': f'Error uploading file to Gemini API: {str(upload_error)}'})
        # --- END CORRECTED FILE UPLOAD CALL ---

        # Create cache with system instruction
        try:
            system_instruction = "You are an expert document analyzer. Provide detailed, accurate answers based on the uploaded document content. Always be helpful and thorough in your responses."

            # Use the correct model format as per documentation
            model = 'models/gemini-2.0-flash-001'

            print(f"Attempting to create cache for file: {document.name}") # Log
            cache = client.caches.create(
                model=model,
                config=types.CreateCachedContentConfig(
                    display_name=f'pdf document cache: {file.filename}', # Use filename in display_name
                    system_instruction=system_instruction,
                    contents=[document], # document is the File object returned by upload_file
                    ttl="3600s",  # 1 hour TTL
                )
            )
            print(f"Cache created successfully: {cache.name}") # Log

            # Store cache info
            cache_id = str(uuid.uuid4())
            document_caches[cache_id] = {
                'cache_name': cache.name,
                'document_name': file.filename,
                'created_at': datetime.now().isoformat()
            }

            # Get token count from cache metadata if available
            token_count = 'Unknown'
            if hasattr(cache, 'usage_metadata') and cache.usage_metadata:
                 token_count = getattr(cache.usage_metadata, 'cached_token_count', 'Unknown')

            return jsonify({
                'success': True,
                'cache_id': cache_id,
                'token_count': token_count
            })

        except Exception as cache_error:
            print(f"Cache creation failed: {str(cache_error)}") # Log the cache error
            # If caching fails due to small content, provide alternative approach
            # Note: The exact error message might vary, checking substring is a bit fragile
            # A better way might be to count tokens first, but requires API call
            if "Cached content is too small" in str(cache_error) or "minimum" in str(cache_error).lower():
                 # Attempt to delete the uploaded file if caching failed (optional but good cleanup)
                 try:
                     client.files.delete(document.name)
                     print(f"Cleaned up uploaded file {document.name} after caching failure.")
                 except Exception as cleanup_error:
                      print(f"Failed to clean up file {document.name}: {cleanup_error}")

                 return jsonify({
                     'success': False,
                     'error': 'PDF content is too small for caching. Please upload a larger document. Minimum token count varies by model, but is typically 1024+.',
                     'suggestion': 'Try uploading a longer document or combine multiple documents.'
                 })
            else:
                # Attempt to delete the uploaded file if caching failed
                try:
                    client.files.delete(document.name)
                    print(f"Cleaned up uploaded file {document.name} after caching failure.")
                except Exception as cleanup_error:
                     print(f"Failed to clean up file {document.name}: {cleanup_error}")
                raise cache_error # Re-raise other errors

    except Exception as e:
        print(f"An unexpected error occurred during upload: {str(e)}") # Log general errors
        return jsonify({'success': False, 'error': str(e)})

@app.route('/upload-url', methods=['POST'])
def upload_from_url():
    try:
        data = request.get_json()
        url = data.get('url')

        if not url:
            return jsonify({'success': False, 'error': 'No URL provided'})

        # Download file from URL
        try:
            response = httpx.get(url)
            response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
        except httpx.HTTPStatusError as e:
             return jsonify({'success': False, 'error': f'HTTP error downloading file from URL: {e.response.status_code} - {e.response.text}'})
        except httpx.RequestError as e:
             return jsonify({'success': False, 'error': f'Error downloading file from URL: {e}'})


        file_io = io.BytesIO(response.content)

        # --- CORRECTED FILE UPLOAD CALL ---
        # Upload to Gemini File API using the correct method client.upload_file
        # Pass the file content as a tuple (filename, file-like object, mime_type)
        # Use a generic filename for the file-like object
        try:
            document = client.upload_file(
                file=('downloaded_document.pdf', file_io, 'application/pdf'), # Use a placeholder filename
                display_name=url # Use the URL as display name
            )
            print(f"File uploaded successfully: {document.name}") # Log
        except Exception as upload_error:
             return jsonify({'success': False, 'error': f'Error uploading file to Gemini API: {str(upload_error)}'})
        # --- END CORRECTED FILE UPLOAD CALL ---


        # Create cache with system instruction
        try:
            system_instruction = "You are an expert document analyzer. Provide detailed, accurate answers based on the uploaded document content. Always be helpful and thorough in your responses."

            # Use the correct model format as per documentation
            model = 'models/gemini-2.0-flash-001'

            print(f"Attempting to create cache for file: {document.name}") # Log
            cache = client.caches.create(
                model=model,
                config=types.CreateCachedContentConfig(
                    display_name=f'pdf document cache: {url}', # Use URL in display_name
                    system_instruction=system_instruction,
                    contents=[document], # document is the File object returned by upload_file
                    ttl="3600s",  # 1 hour TTL
                )
            )
            print(f"Cache created successfully: {cache.name}") # Log

            # Store cache info
            cache_id = str(uuid.uuid4())
            document_caches[cache_id] = {
                'cache_name': cache.name,
                'document_name': url,
                'created_at': datetime.now().isoformat()
            }

            # Get token count from cache metadata if available
            token_count = 'Unknown'
            if hasattr(cache, 'usage_metadata') and cache.usage_metadata:
                 token_count = getattr(cache.usage_metadata, 'cached_token_count', 'Unknown')


            return jsonify({
                'success': True,
                'cache_id': cache_id,
                'token_count': token_count
            })

        except Exception as cache_error:
            print(f"Cache creation failed: {str(cache_error)}") # Log the cache error
            # If caching fails due to small content, provide alternative approach
            if "Cached content is too small" in str(cache_error) or "minimum" in str(cache_error).lower():
                # Attempt to delete the uploaded file if caching failed (optional but good cleanup)
                try:
                     client.files.delete(document.name)
                     print(f"Cleaned up uploaded file {document.name} after caching failure.")
                except Exception as cleanup_error:
                     print(f"Failed to clean up file {document.name}: {cleanup_error}")

                return jsonify({
                    'success': False,
                    'error': 'PDF content is too small for caching. Please upload a larger document. Minimum token count varies by model, but is typically 1024+.',
                    'suggestion': 'Try uploading a longer document or combine multiple documents.'
                })
            else:
                # Attempt to delete the uploaded file if caching failed
                try:
                    client.files.delete(document.name)
                    print(f"Cleaned up uploaded file {document.name} after caching failure.")
                except Exception as cleanup_error:
                     print(f"Failed to clean up file {document.name}: {cleanup_error}")
                raise cache_error # Re-raise other errors


    except Exception as e:
        print(f"An unexpected error occurred during URL upload: {str(e)}") # Log general errors
        return jsonify({'success': False, 'error': str(e)})

# ... (ask_question, list_caches, delete_cache routes remain largely the same) ...

@app.route('/ask', methods=['POST'])
def ask_question():
    try:
        data = request.get_json()
        question = data.get('question')
        cache_id = data.get('cache_id')

        if not question or not cache_id:
            return jsonify({'success': False, 'error': 'Missing question or cache_id'})

        if cache_id not in document_caches:
            # Check if the cache still exists in Gemini API if it's not in our local map
            # This adds robustness if the server restarts or cache expires
            try:
                cache_info_api = client.caches.get(name=document_caches[cache_id]['cache_name']) # Need cache_name from stored info
                # If get succeeds, update local cache (or handle this differently)
                # For simplicity here, let's just fail if not in local map as it's in-memory
                 return jsonify({'success': False, 'error': 'Cache not found or expired. Please upload the document again.'})
            except Exception as get_error:
                 # If get fails, it's definitely gone
                 if cache_id in document_caches: # Clean up local entry if API confirms deletion/expiry
                     del document_caches[cache_id]
                 return jsonify({'success': False, 'error': 'Cache not found or expired. Please upload the document again.'})


        cache_info = document_caches[cache_id]

        # Generate response using cached content with correct model format
        response = client.models.generate_content(
            model='models/gemini-2.0-flash-001',
            contents=question, # User's question
            generation_config=types.GenerateContentConfig( # generation_config takes GenerateContentConfig
                cached_content=cache_info['cache_name']
            )
        )

        # Check if response has parts before accessing .text
        answer = "Could not generate response."
        if response and response.candidates and response.candidates[0].content and response.candidates[0].content.parts:
             answer = "".join(part.text for part in response.candidates[0].content.parts if hasattr(part, 'text'))
        elif response and response.prompt_feedback and response.prompt_feedback.block_reason:
             answer = f"Request blocked: {response.prompt_feedback.block_reason.name}"
        else:
             print(f"Unexpected response structure: {response}") # Log unexpected structure


        return jsonify({
            'success': True,
            'answer': answer
        })

    except Exception as e:
        print(f"An error occurred during question asking: {str(e)}") # Log errors
        return jsonify({'success': False, 'error': str(e)})

# ... (list_caches, delete_cache remain largely the same) ...

@app.route('/cache/<cache_id>', methods=['DELETE'])
def delete_cache(cache_id):
    try:
        if cache_id not in document_caches:
            return jsonify({'success': False, 'error': 'Cache not found'})

        cache_info = document_caches[cache_id]

        # Delete from Gemini API
        try:
            client.caches.delete(cache_info['cache_name'])
            print(f"Gemini cache deleted: {cache_info['cache_name']}") # Log
        except Exception as delete_error:
             print(f"Error deleting Gemini cache {cache_info['cache_name']}: {delete_error}") # Log
             # Decide if you want to fail if API deletion fails or just remove local entry
             # For robustness, maybe log and still remove local entry? Or return error?
             # Let's return an error for now.
             return jsonify({'success': False, 'error': f'Failed to delete cache from API: {str(delete_error)}'})

        # Remove from local storage
        del document_caches[cache_id]
        print(f"Local cache entry deleted for ID: {cache_id}") # Log

        return jsonify({'success': True, 'message': 'Cache deleted successfully'})

    except Exception as e:
        print(f"An unexpected error occurred during cache deletion: {str(e)}") # Log
        return jsonify({'success': False, 'error': str(e)})


if __name__ == '__main__':
    import os
    # Ensure GOOGLE_API_KEY is set
    if not os.getenv('GOOGLE_API_KEY'):
        print("Error: GOOGLE_API_KEY environment variable not set.")
        # exit(1) # Or handle appropriately
        # For local testing with debug=True, you might pass it directly or ensure your .env is loaded
        pass # Allow running without key for now if needed, but API calls will fail

    port = int(os.environ.get("PORT", 7860))
    print(f"Starting Flask app on port {port}") # Log start
    # In production, set debug=False
    app.run(debug=True, host='0.0.0.0', port=port)