forked from Tkhaitan17/google-ai-hackathon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1662 lines (1406 loc) · 59.4 KB
/
app.js
File metadata and controls
1662 lines (1406 loc) · 59.4 KB
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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// API Configuration - Load from config.js or environment variables
const GEMINI_API_URL = window.CONFIG?.GEMINI_API_URL || 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent';
// Make API key available globally for backward compatibility
if (window.CONFIG?.GEMINI_API_KEY) {
window.GEMINI_API_KEY = window.CONFIG.GEMINI_API_KEY;
} else if (typeof process !== 'undefined' && process.env && process.env.GEMINI_API_KEY) {
// For production environment variables
window.GEMINI_API_KEY = process.env.GEMINI_API_KEY;
} else {
// Fallback - you can set this directly for production
window.GEMINI_API_KEY = 'AIzaSyCLWImqAa5u-7wqpwheMEaXf2rRAyfzHpw';
}
// Global variables
let currentDocument = null;
let analysisResults = null;
let currentUser = null;
let isUploading = false; // Flag to prevent multiple uploads
let uploadButtonClickCount = 0; // Debug counter
let userAnalytics = {
totalDocuments: 0,
totalRiskScore: 0,
riskScores: [],
analysisHistory: []
};
// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
initializeApp();
});
function initializeApp() {
console.log('Initializing app...');
const uploadBtn = document.getElementById('upload-btn');
const pdfUpload = document.getElementById('pdf-upload');
const askBtn = document.getElementById('ask-btn');
const negotiationBtn = document.getElementById('negotiation-btn');
const trendsBtn = document.getElementById('trends-btn');
const compareBtn = document.getElementById('compare-btn');
console.log('Elements found:', {
uploadBtn: !!uploadBtn,
pdfUpload: !!pdfUpload,
askBtn: !!askBtn,
negotiationBtn: !!negotiationBtn,
trendsBtn: !!trendsBtn,
compareBtn: !!compareBtn
});
if (uploadBtn) {
// Initialize button as disabled
uploadBtn.disabled = true;
uploadBtn.style.opacity = '0.6';
uploadBtn.addEventListener('click', (e) => {
uploadButtonClickCount++;
console.log(`=== Upload button clicked #${uploadButtonClickCount} ===`);
console.log('Button disabled state:', uploadBtn.disabled);
console.log('Files in input:', document.getElementById('pdf-upload').files);
console.log('Event details:', e);
handleDocumentUpload();
});
console.log('Upload button event listener attached');
} else {
console.error('Upload button not found!');
}
if (askBtn) askBtn.addEventListener('click', handleQuestion);
if (negotiationBtn) negotiationBtn.addEventListener('click', handleNegotiationTips);
if (trendsBtn) trendsBtn.addEventListener('click', handleViewTrends);
if (compareBtn) compareBtn.addEventListener('click', handleDocumentComparison);
// Main file input event listener (like comparison upload)
const mainFileInput = document.getElementById('pdf-upload');
if (mainFileInput) {
console.log('Setting up main file input listener');
mainFileInput.addEventListener('change', (e) => {
console.log('=== File input change event triggered ===');
console.log('File input changed:', e.target.files);
if (e.target.files.length > 0) {
console.log('File selected:', e.target.files[0].name);
updateUploadAreaDisplay(e.target.files[0]);
} else {
console.log('No file selected');
updateUploadAreaDisplay(null);
}
});
} else {
console.error('Main file input not found!');
}
// Comparison file input event listener
const compareFileInput = document.getElementById('compare-upload');
if (compareFileInput) {
// Initialize compare button as disabled
if (compareBtn) {
compareBtn.disabled = true;
compareBtn.style.opacity = '0.6';
}
compareFileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) {
updateComparisonFileDisplay(e.target.files[0]);
} else {
updateComparisonFileDisplay(null);
}
});
}
// Export functionality
const exportPdfBtn = document.getElementById('export-pdf-btn');
const exportTextBtn = document.getElementById('export-text-btn');
if (exportPdfBtn) exportPdfBtn.addEventListener('click', handleExportPDF);
if (exportTextBtn) exportTextBtn.addEventListener('click', handleExportText);
// Authentication
const loginBtn = document.getElementById('login-btn');
const signupBtn = document.getElementById('signup-btn');
const logoutBtn = document.getElementById('logout-btn');
if (loginBtn) loginBtn.addEventListener('click', handleLogin);
if (signupBtn) signupBtn.addEventListener('click', handleSignup);
if (logoutBtn) logoutBtn.addEventListener('click', handleLogout);
// Initialize Firebase Auth
initializeAuth();
// Setup upload functionality - handle click directly
const uploadContent = document.querySelector('.upload-content');
const fileInput = document.getElementById('pdf-upload');
console.log('Upload elements found:', {
uploadContent: !!uploadContent,
fileInput: !!fileInput
});
if (uploadContent && fileInput) {
// Make upload content clickable
uploadContent.addEventListener('click', (e) => {
console.log('Upload area clicked!');
console.log('Opening file dialog');
fileInput.click();
});
// Also make the file input itself clickable as fallback
fileInput.addEventListener('click', (e) => {
console.log('File input clicked directly');
});
console.log('Upload area click listener attached');
} else {
console.error('Upload elements not found!');
}
console.log('App initialization complete');
}
// Handle document upload
async function handleDocumentUpload() {
console.log('=== handleDocumentUpload called ===');
// Prevent multiple simultaneous uploads
if (isUploading) {
console.log('Upload already in progress, ignoring click');
return;
}
const fileInput = document.getElementById('pdf-upload');
const file = fileInput.files[0];
console.log('File input element:', fileInput);
console.log('Files in input:', fileInput.files);
console.log('Selected file:', file);
console.log('isUploading flag:', isUploading);
if (!file) {
console.log('No file found, showing alert');
alert('Please select a PDF file first!');
return;
}
if (file.type !== 'application/pdf') {
alert('Please upload a PDF file only!');
return;
}
console.log('File selected:', file.name);
console.log('API Key available:', !!(window.CONFIG?.GEMINI_API_KEY || window.GEMINI_API_KEY));
// Show privacy notice first
const privacyAccepted = await new Promise((resolve) => {
const privacyNotice = `
<div class="privacy-modal">
<div class="privacy-notice">
<div class="privacy-content">
<h3>🔒 Privacy & Security Notice</h3>
<div class="privacy-details">
<p><strong>Data Processing:</strong> Your document will be processed by Google's Gemini AI for analysis purposes only.</p>
<p><strong>Data Retention:</strong> Documents are processed in real-time and not permanently stored by our service.</p>
<p><strong>Security:</strong> All data transmission is encrypted using HTTPS.</p>
<p><strong>Your Rights:</strong> You can request data deletion at any time.</p>
</div>
<div class="privacy-actions">
<button id="accept-privacy" class="privacy-btn accept">I Understand & Accept</button>
<button id="decline-privacy" class="privacy-btn decline">Cancel Upload</button>
</div>
</div>
</div>
</div>
`;
const modal = document.createElement('div');
modal.innerHTML = privacyNotice;
document.body.appendChild(modal);
document.getElementById('accept-privacy').addEventListener('click', () => {
document.body.removeChild(modal);
resolve(true);
});
document.getElementById('decline-privacy').addEventListener('click', () => {
document.body.removeChild(modal);
resolve(false);
});
});
if (!privacyAccepted) {
return;
}
isUploading = true;
// Show upload confirmation first
showUploadConfirmation(file);
// Small delay to show upload confirmation
await new Promise(resolve => setTimeout(resolve, 800));
// Show document type detection loading
showDocumentTypeDetection();
try {
// Convert PDF to base64
console.log('Converting file to base64...');
const base64 = await fileToBase64(file);
console.log('Base64 conversion complete, length:', base64.length);
// Store current document for comparison
currentDocument = base64;
// Detect document type and language
console.log('Detecting document type and language...');
const detectionResult = await detectDocumentType(base64);
console.log('Detection result:', detectionResult);
// Show document type confirmation
showDocumentTypeConfirmation(detectionResult, base64);
} catch (error) {
console.error('Error detecting document type:', error);
alert('Error detecting document type: ' + error.message);
isUploading = false;
showLoading(false);
}
}
// Convert file to base64
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.split(',')[1]);
reader.onerror = error => reject(error);
});
}
// Security and Privacy Notice
function showPrivacyNotice() {
const privacyNotice = `
<div class="privacy-notice">
<div class="privacy-content">
<h3>🔒 Privacy & Security Notice</h3>
<div class="privacy-details">
<p><strong>Data Processing:</strong> Your document will be processed by Google's Gemini AI for analysis purposes only.</p>
<p><strong>Data Retention:</strong> Documents are processed in real-time and not permanently stored by our service.</p>
<p><strong>Security:</strong> All data transmission is encrypted using HTTPS.</p>
<p><strong>Your Rights:</strong> You can request data deletion at any time.</p>
</div>
<div class="privacy-actions">
<button id="accept-privacy" class="privacy-btn accept">I Understand & Accept</button>
<button id="decline-privacy" class="privacy-btn decline">Cancel Upload</button>
</div>
</div>
</div>
`;
// Show privacy notice as modal
const modal = document.createElement('div');
modal.className = 'privacy-modal';
modal.innerHTML = privacyNotice;
document.body.appendChild(modal);
// Handle privacy acceptance
document.getElementById('accept-privacy').addEventListener('click', () => {
document.body.removeChild(modal);
return true;
});
// Handle privacy decline
document.getElementById('decline-privacy').addEventListener('click', () => {
document.body.removeChild(modal);
return false;
});
}
// Document type detection with language support
async function detectDocumentType(base64Data) {
const detectionPrompt = `
Analyze this document and determine:
1. Document language (English, Spanish, French, German, Italian, Portuguese, Chinese, Japanese, Korean, Arabic, Hindi, or Other)
2. Document type from these categories:
- Rental/Housing Documents (lease agreements, rental contracts)
- Loan and Credit Agreements (loans, credit cards, financing)
- Employment Documents (employment contracts, NDAs, non-compete agreements)
- Terms of Service/Privacy Policies (website terms, privacy policies)
- Insurance Policies (health, auto, home, life insurance)
- General Legal Document (if none of the above match)
Respond in this exact format:
LANGUAGE: [detected language]
TYPE: [document type]
Be specific and accurate in your classification.
`;
try {
const apiKey = window.CONFIG?.GEMINI_API_KEY || window.GEMINI_API_KEY;
const response = await fetch(`${GEMINI_API_URL}?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: [
{ text: detectionPrompt },
{
inline_data: {
mime_type: "application/pdf",
data: base64Data
}
}
]
}]
})
});
const data = await response.json();
const responseText = data.candidates[0].content.parts[0].text.trim();
// Parse language and type
const languageMatch = responseText.match(/LANGUAGE:\s*(.+)/i);
const typeMatch = responseText.match(/TYPE:\s*(.+)/i);
const detectedLanguage = languageMatch ? languageMatch[1].trim() : 'English';
const detectedType = typeMatch ? typeMatch[1].trim() : 'General Legal Document';
console.log('Detected language:', detectedLanguage);
console.log('Detected document type:', detectedType);
return {
type: detectedType,
language: detectedLanguage
};
} catch (error) {
console.error('Error detecting document type:', error);
return {
type: 'General Legal Document',
language: 'English'
};
}
}
// Get specific prompt based on document type
function getDocumentSpecificPrompt(documentType) {
const prompts = {
'Rental/Housing Documents': `
You are analyzing a RENTAL/LEASE AGREEMENT. Focus on:
1. RENT TERMS: Monthly amount, due dates, late fees, grace periods
2. SECURITY DEPOSIT: Amount, return conditions, allowable deductions
3. TERMINATION: Notice requirements, penalties, 120-day transition periods
4. RESTRICTIONS: Pet policies, subletting rules, noise ordinances
5. MAINTENANCE: Who pays utilities, repair responsibilities, property modifications
6. RED FLAGS: Excessive fees, unreasonable restrictions, unfair termination clauses
Rate risk focusing on: tenant rights violations, excessive financial obligations, predatory clauses.
`,
'Loan and Credit Agreements': `
You are analyzing a LOAN/CREDIT AGREEMENT. Focus on:
1. INTEREST RATES: APR, variable vs. fixed, rate change conditions
2. PAYMENT TERMS: Monthly amounts, due dates, grace periods, late fees
3. FEES: Origination, processing, prepayment penalties, annual fees
4. DEFAULT: Conditions triggering default, acceleration clauses, consequences
5. INSURANCE: Required coverage, premium costs, beneficiaries
6. RED FLAGS: Predatory lending practices, excessive fees, confusing terms
Rate risk focusing on: debt trap potential, hidden costs, unfair collection practices.
`,
'Employment Documents': `
You are analyzing an EMPLOYMENT DOCUMENT. Focus on:
1. COMPENSATION: Base salary, bonuses, benefits, equity, expense reimbursement
2. RESPONSIBILITIES: Job duties, reporting structure, performance metrics
3. CONFIDENTIALITY: NDA scope, trade secrets, duration of obligations
4. TERMINATION: Notice periods, severance, return of company property
5. RESTRICTIONS: Non-compete geography/duration, non-solicitation clauses
6. RED FLAGS: Overly broad restrictions, unpaid obligations, unfair termination
Rate risk focusing on: career mobility limitations, unfair compensation, excessive obligations.
`,
'Terms of Service/Privacy Policies': `
You are analyzing a TERMS OF SERVICE or PRIVACY POLICY. Focus on:
1. DATA PRIVACY: Collection practices, sharing with third parties, user rights
2. SERVICE TERMS: Availability, feature changes, account suspension/termination
3. USER OBLIGATIONS: Acceptable use, prohibited activities, content guidelines
4. LIABILITY: Limitation of damages, indemnification, warranty disclaimers
5. DISPUTE RESOLUTION: Arbitration requirements, class action waivers, governing law
6. RED FLAGS: Excessive data collection, unfair termination, binding arbitration abuse
Rate risk focusing on: privacy violations, loss of legal rights, service dependency.
`,
'Insurance Policies': `
You are analyzing an INSURANCE POLICY. Focus on:
1. COVERAGE: What's included/excluded, benefit limits, geographic scope
2. COSTS: Premiums, deductibles, co-pays, out-of-pocket maximums
3. CLAIMS: Filing requirements, documentation needed, processing timelines
4. EXCLUSIONS: Pre-existing conditions, high-risk activities, coverage gaps
5. RENEWAL: Rate changes, policy modifications, cancellation rights
6. RED FLAGS: Hidden exclusions, excessive costs, claim denial patterns
Rate risk focusing on: coverage gaps, claim denial risks, affordability issues.
`
};
return prompts[documentType] || '';
}
// Proceed with analysis after document type confirmation
async function proceedWithAnalysis(documentType, language, base64Data) {
// Show analysis loading
showLoading(true);
try {
// Analyze document with confirmed type and language
console.log('Proceeding with analysis for document type:', documentType, 'language:', language);
const analysis = await analyzeDocumentWithGeminiWithType(base64Data, documentType, language);
console.log('Analysis complete:', analysis);
// Display results
displayResults(analysis);
// Update analytics
updateUserAnalytics(analysis);
} catch (error) {
console.error('Error analyzing document:', error);
alert('Error analyzing document: ' + error.message);
} finally {
isUploading = false;
showLoading(false);
}
}
// Reject document type and try again
async function rejectDocumentType() {
if (!currentDocument) {
alert('No document available to re-analyze');
return;
}
// Show detection loading again
showDocumentTypeDetection();
try {
// Try detecting document type again
console.log('Re-detecting document type...');
const documentType = await detectDocumentType(currentDocument);
console.log('Document type re-detected:', documentType);
// Show confirmation again
showDocumentTypeConfirmation(documentType, currentDocument);
} catch (error) {
console.error('Error re-detecting document type:', error);
alert('Error re-detecting document type: ' + error.message);
isUploading = false;
showLoading(false);
}
}
// Analyze document with Gemini API using specific document type and language
async function analyzeDocumentWithGeminiWithType(base64Data, documentType, language = 'English') {
// Get specific prompt for document type
const specificPrompt = getDocumentSpecificPrompt(documentType);
// Create language-specific instructions
const languageInstruction = language !== 'English' ?
`\n\nIMPORTANT: The document is in ${language}. Please provide your analysis in ${language} while maintaining the same format and structure.` : '';
// Create the main analysis prompt
const basePrompt = `
You are a legal document analysis AI. ${specificPrompt}
Please provide your analysis in the following format:
RISK SCORE: [Rate from 1-10, where 1=very safe, 10=very risky]
KEY ISSUES:
• [List 3-5 most important clauses that need attention, each on a new line with bullet points]
PLAIN ENGLISH SUMMARY:
[Explain the document in simple terms that a 12-year-old could understand. Use clear, conversational language without legal jargon.]
RED FLAGS:
• [List any predatory or unusual terms, each on a new line with bullet points. If none, write "No major red flags detected."]
IMPORTANT: Do not use JSON format. Provide clean, readable text with proper formatting.${languageInstruction}
`;
const response = await fetch(`${GEMINI_API_URL}?key=${window.GEMINI_API_KEY}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: [
{ text: basePrompt },
{
inline_data: {
mime_type: "application/pdf",
data: base64Data
}
}
]
}]
})
});
const data = await response.json();
const analysisText = data.candidates[0].content.parts[0].text;
// Parse the formatted text response and add document type and language
const analysis = parseFormattedAnalysis(analysisText);
analysis.document_type = documentType;
analysis.language = language;
return analysis;
}
// Analyze document with Gemini API (legacy function for backward compatibility)
async function analyzeDocumentWithGemini(base64Data) {
// First detect document type
const documentType = await detectDocumentType(base64Data);
// Use the new function with detected type
return await analyzeDocumentWithGeminiWithType(base64Data, documentType);
}
// Display analysis results
function displayResults(analysis) {
analysisResults = analysis;
// Show results section
document.getElementById('results').classList.remove('hidden');
// Update risk meter
updateRiskMeter(analysis.risk_score);
// Add enhanced risk breakdown
addRiskBreakdown(analysis.risk_score);
// Track risk trends using detected document type
const docType = analysis.document_type || 'General Legal Document';
trackRiskTrends(docType.toLowerCase().replace(/[^a-z0-9]/g, '_'), analysis.risk_score);
// Display key findings
displayKeyFindings(analysis.key_issues, analysis.red_flags);
// Display summary with document type
const documentTypeDisplay = analysis.document_type ?
`<div class="document-type-badge">📄 ${analysis.document_type}</div>` : '';
document.getElementById('summary-text').innerHTML =
`${documentTypeDisplay}<p>${analysis.plain_summary}</p>`;
}
// Update risk meter visualization
function updateRiskMeter(riskScore) {
const riskBar = document.getElementById('risk-bar');
const riskText = document.getElementById('risk-text');
const percentage = (riskScore / 10) * 100;
riskBar.style.width = percentage + '%';
// Set colors based on risk level
if (riskScore <= 3) {
riskBar.className = 'meter-bar risk-low';
riskText.textContent = `Risk Level: Low (${riskScore}/10)`;
} else if (riskScore <= 6) {
riskBar.className = 'meter-bar risk-medium';
riskText.textContent = `Risk Level: Medium (${riskScore}/10)`;
} else {
riskBar.className = 'meter-bar risk-high';
riskText.textContent = `Risk Level: High (${riskScore}/10)`;
}
}
// Add enhanced risk breakdown visualization
function addRiskBreakdown(riskScore) {
const riskScoreElement = document.querySelector('.risk-score');
// Remove existing breakdown if any
const existingBreakdown = document.querySelector('.risk-breakdown');
if (existingBreakdown) {
existingBreakdown.remove();
}
// Create risk breakdown
const breakdown = document.createElement('div');
breakdown.className = 'risk-breakdown';
// Determine risk level and create appropriate breakdown
let riskItems = [];
if (riskScore <= 3) {
riskItems = [
{ icon: '🟢', title: 'Low Risk', desc: 'Standard terms, minimal concerns', class: 'low' },
{ icon: '✅', title: 'Favorable', desc: 'Generally beneficial conditions', class: 'low' },
{ icon: '📋', title: 'Standard', desc: 'Typical legal language used', class: 'low' }
];
} else if (riskScore <= 6) {
riskItems = [
{ icon: '🟡', title: 'Medium Risk', desc: 'Some terms need attention', class: 'medium' },
{ icon: '⚠️', title: 'Caution', desc: 'Review specific clauses', class: 'medium' },
{ icon: '📝', title: 'Negotiable', desc: 'Consider discussing terms', class: 'medium' }
];
} else {
riskItems = [
{ icon: '🔴', title: 'High Risk', desc: 'Significant concerns identified', class: 'high' },
{ icon: '🚨', title: 'Urgent', desc: 'Immediate attention required', class: 'high' },
{ icon: '⚖️', title: 'Legal Review', desc: 'Consult with attorney', class: 'high' }
];
}
// Generate HTML for risk items
const itemsHTML = riskItems.map(item => `
<div class="risk-item ${item.class}">
<div class="risk-item-icon">${item.icon}</div>
<div class="risk-item-title">${item.title}</div>
<div class="risk-item-desc">${item.desc}</div>
</div>
`).join('');
breakdown.innerHTML = itemsHTML;
// Insert after risk score
riskScoreElement.parentNode.insertBefore(breakdown, riskScoreElement.nextSibling);
}
// Display key findings
function displayKeyFindings(keyIssues, redFlags) {
const findingsList = document.getElementById('findings-list');
let html = '';
// Add key issues
keyIssues.forEach(issue => {
html += `<div class="finding-item">
<span class="finding-icon">⚠️</span>
<span class="finding-text">${issue}</span>
</div>`;
});
// Add red flags with higher priority
redFlags.forEach(flag => {
html += `<div class="finding-item red-flag">
<span class="finding-icon">🚩</span>
<span class="finding-text"><strong>RED FLAG:</strong> ${flag}</span>
</div>`;
});
findingsList.innerHTML = html;
}
// Handle Q&A functionality
async function handleQuestion() {
const questionInput = document.getElementById('question-input');
const question = questionInput.value.trim();
if (!question) {
alert('Please enter a question!');
return;
}
if (!analysisResults) {
alert('Please analyze a document first!');
return;
}
// Add user question to chat
addChatMessage(question, 'user');
questionInput.value = '';
try {
// Get AI response
const response = await askQuestionAboutDocument(question);
addChatMessage(response, 'ai');
} catch (error) {
addChatMessage('Sorry, I had trouble understanding your question. Please try again.', 'ai');
}
}
// Ask question about the document
async function askQuestionAboutDocument(question) {
const prompt = `
Based on the legal document analysis, answer this question in simple terms:
Question: ${question}
Document Summary: ${analysisResults.plain_summary}
Provide a helpful, clear answer in 2-3 sentences.
`;
const response = await fetch(`${GEMINI_API_URL}?key=${window.GEMINI_API_KEY}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: [{ text: prompt }]
}]
})
});
const data = await response.json();
return data.candidates[0].content.parts[0].text;
}
// Add message to chat interface
function addChatMessage(message, sender) {
const chatResponses = document.getElementById('chat-responses');
const messageDiv = document.createElement('div');
messageDiv.className = `chat-bubble ${sender}`;
if (sender === 'user') {
messageDiv.innerHTML = `<strong>You:</strong> ${message}`;
} else {
messageDiv.innerHTML = `<strong>🤖 LegalLens:</strong> ${message}`;
}
chatResponses.appendChild(messageDiv);
chatResponses.scrollTop = chatResponses.scrollHeight;
}
// Show upload confirmation with file details
function showUploadConfirmation(file) {
const loading = document.getElementById('loading');
const results = document.getElementById('results');
// Create simple loading content
loading.innerHTML = `
<div class="loading-content">
<div class="simple-loading">
<div class="loading-spinner"></div>
<h3>✅ File uploaded: ${file.name} - Preparing for analysis...</h3>
</div>
</div>
`;
loading.classList.remove('hidden');
results.classList.add('hidden');
}
// Show document type detection loading
function showDocumentTypeDetection() {
const loading = document.getElementById('loading');
const results = document.getElementById('results');
loading.innerHTML = `
<div class="loading-content">
<div class="simple-loading">
<div class="loading-spinner"></div>
<h3>🔍 Detecting document type...</h3>
</div>
</div>
`;
loading.classList.remove('hidden');
results.classList.add('hidden');
}
// Show document type confirmation
function showDocumentTypeConfirmation(detectionResult, base64Data) {
const loading = document.getElementById('loading');
const results = document.getElementById('results');
const documentType = detectionResult.type;
const language = detectionResult.language;
loading.innerHTML = `
<div class="loading-content">
<div class="document-type-confirmation">
<div class="confirmation-icon">📄</div>
<h3>Document Analysis Ready</h3>
<div class="detection-results">
<div class="detected-type">
<span class="label">Type:</span>
<span class="value">${documentType}</span>
</div>
<div class="detected-language">
<span class="label">Language:</span>
<span class="value">${language}</span>
</div>
</div>
<p>Is this correct? We'll use specialized analysis for this document type and language.</p>
<div class="confirmation-buttons">
<button id="confirm-type-btn" class="confirm-btn" onclick="proceedWithAnalysis('${documentType}', '${language}', '${base64Data}')">
✅ Yes, Proceed
</button>
<button id="reject-type-btn" class="reject-btn" onclick="rejectDocumentType()">
❌ No, Try Again
</button>
</div>
</div>
</div>
`;
loading.classList.remove('hidden');
results.classList.add('hidden');
}
// Show/hide loading animation
function showLoading(show) {
const loading = document.getElementById('loading');
const results = document.getElementById('results');
if (show) {
// Update loading content for analysis phase
loading.innerHTML = `
<div class="loading-content">
<div class="simple-loading">
<div class="loading-spinner"></div>
<h3>🔍 Detecting document type and analyzing...</h3>
</div>
</div>
`;
loading.classList.remove('hidden');
results.classList.add('hidden');
} else {
loading.classList.add('hidden');
}
}
// Update upload area display when file is selected
function updateUploadAreaDisplay(file) {
console.log('=== updateUploadAreaDisplay called ===');
console.log('File parameter:', file);
const uploadContent = document.querySelector('.upload-content');
const uploadIcon = document.querySelector('.upload-icon');
const uploadTitle = uploadContent.querySelector('h3');
const uploadDesc = uploadContent.querySelector('p');
const analyzeBtn = document.getElementById('upload-btn');
console.log('Upload elements found:', {
uploadContent: !!uploadContent,
uploadIcon: !!uploadIcon,
uploadTitle: !!uploadTitle,
uploadDesc: !!uploadDesc,
analyzeBtn: !!analyzeBtn
});
if (file) {
console.log('File provided, updating UI with file:', file.name);
uploadIcon.className = 'fas fa-file-pdf upload-icon';
uploadIcon.style.color = '#ef4444';
uploadTitle.textContent = `Selected: ${file.name}`;
uploadDesc.textContent = `Size: ${(file.size / 1024 / 1024).toFixed(2)} MB`;
// Enable analyze button
if (analyzeBtn) {
console.log('Enabling analyze button');
analyzeBtn.disabled = false;
analyzeBtn.style.opacity = '1';
}
} else {
// Reset to default state
uploadIcon.className = 'fas fa-cloud-upload-alt upload-icon';
uploadIcon.style.color = '';
uploadTitle.textContent = 'Click to browse and select your PDF';
uploadDesc.textContent = 'Supports PDF files up to 10MB';
// Disable analyze button
if (analyzeBtn) {
analyzeBtn.disabled = true;
analyzeBtn.style.opacity = '0.6';
}
}
}
// Parse formatted analysis text
function parseFormattedAnalysis(text) {
const analysis = {
risk_score: 5,
key_issues: [],
plain_summary: '',
red_flags: []
};
try {
// Extract risk score
const riskMatch = text.match(/RISK SCORE:\s*(\d+)/i);
if (riskMatch) {
analysis.risk_score = parseInt(riskMatch[1]);
}
// Extract key issues
const keyIssuesMatch = text.match(/KEY ISSUES:([\s\S]*?)(?=PLAIN ENGLISH SUMMARY|RED FLAGS|$)/i);
if (keyIssuesMatch) {
const issuesText = keyIssuesMatch[1];
analysis.key_issues = issuesText
.split('\n')
.map(line => line
.replace(/^[•\-\*]\s*/, '') // Remove bullet points
.replace(/\*\*\*/g, '') // Remove triple asterisks
.replace(/\*\*/g, '') // Remove double asterisks
.replace(/\*/g, '') // Remove single asterisks
.trim()
)
.filter(line => line.length > 0);
}
// Extract plain summary
const summaryMatch = text.match(/PLAIN ENGLISH SUMMARY:([\s\S]*?)(?=RED FLAGS|$)/i);
if (summaryMatch) {
analysis.plain_summary = summaryMatch[1].trim();
}
// Extract red flags
const redFlagsMatch = text.match(/RED FLAGS:([\s\S]*?)$/i);
if (redFlagsMatch) {
const flagsText = redFlagsMatch[1];
analysis.red_flags = flagsText
.split('\n')
.map(line => line
.replace(/^[•\-\*]\s*/, '') // Remove bullet points
.replace(/\*\*\*/g, '') // Remove triple asterisks
.replace(/\*\*/g, '') // Remove double asterisks
.replace(/\*/g, '') // Remove single asterisks
.trim()
)
.filter(line => line.length > 0 && !line.toLowerCase().includes('no major red flags'));
}
// If parsing failed, use fallback
if (!analysis.plain_summary) {
analysis.plain_summary = text;
}
} catch (error) {
console.error('Error parsing analysis:', error);
analysis.plain_summary = text;
}
return analysis;
}
// Add to app.js
// Compare documents feature
async function compareDocuments(doc1, doc2) {
const prompt = `
Compare these two legal documents and provide a clear analysis.
Please provide your comparison in the following format:
DOCUMENT COMPARISON:
KEY DIFFERENCES:
• [List the main differences between the documents, each on a new line]
WHICH IS MORE FAVORABLE:
[Clearly state which document is more favorable to the user and why]