-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathData_Analyst_Agent.py
More file actions
3591 lines (3015 loc) · 146 KB
/
Data_Analyst_Agent.py
File metadata and controls
3591 lines (3015 loc) · 146 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
'''
If for privacy reason you don't trust the app use your own API key.
Change the API key at ".env"
If you can`t contact the team at support@archusers.com (we'll send you the key)
'''
import os
import io
import json
import base64
import sys
import warnings
import time
from typing import Dict, List, Any, Optional, Union
warnings.filterwarnings('ignore')
# Load environment variables
try:
from dotenv import load_dotenv
load_dotenv()
print("✅ Environment variables loaded")
except ImportError:
print("⚠️ python-dotenv not found. Please install: pip install python-dotenv")
except Exception as e:
print(f"⚠️ Error loading .env file: {e}")
# Core data processing imports with error handling
try:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
print("✅ Core data libraries loaded successfully")
except ImportError as e:
print(f"❌ Error importing data libraries: {e}")
print("\n🔧 To fix this issue, please run one of the following:")
print(" pip uninstall numpy pandas -y")
print(" pip install numpy==1.24.3")
print(" pip install pandas==1.5.3")
print(" pip install -r requirements.txt")
input("Press Enter to exit...")
sys.exit(1)
# File processing imports with graceful fallback for problematic packages
try:
import PyPDF2
import docx
from PIL import Image
import requests
import openai
import re
from datetime import datetime, timedelta
import hashlib
from dataclasses import dataclass
from enum import Enum
import difflib
except ImportError as e:
print(f"Error importing core libraries: {e}")
print("Please run: pip install PyPDF2 python-docx Pillow requests openai")
sys.exit(1)
# Optional OCR import (may not work on all deployments)
try:
import pytesseract
PYTESSERACT_AVAILABLE = True
except ImportError:
PYTESSERACT_AVAILABLE = False
print("⚠️ pytesseract not available. OCR features will be disabled.")
# NLP imports with graceful fallback
try:
import spacy
SPACY_AVAILABLE = True
try:
# Try to load the English model
nlp = spacy.load("en_core_web_sm")
except OSError:
# Model not installed, try to install it at runtime
print("🔧 Attempting to download spaCy English model...")
try:
import subprocess
subprocess.run([sys.executable, "-m", "spacy", "download", "en_core_web_sm"],
check=True, capture_output=True)
nlp = spacy.load("en_core_web_sm")
print("✅ spaCy English model downloaded successfully")
except Exception as install_error:
nlp = None
print(f"⚠️ Could not install spaCy model: {install_error}")
print("Some NLP features will be limited.")
except ImportError:
SPACY_AVAILABLE = False
nlp = None
print("⚠️ spaCy not available. NLP features will be limited.")
def ensure_spacy_model():
"""Ensure spaCy model is available, with runtime installation fallback"""
global nlp, SPACY_AVAILABLE, spacy
if not SPACY_AVAILABLE:
return False
if nlp is None:
try:
import spacy
nlp = spacy.load("en_core_web_sm")
return True
except OSError:
# Try installing at runtime (for Streamlit Cloud)
try:
import subprocess
subprocess.run([sys.executable, "-m", "spacy", "download", "en_core_web_sm"],
check=True, capture_output=True)
nlp = spacy.load("en_core_web_sm")
return True
except:
return False
return True
# UI imports
try:
import streamlit as st
import subprocess
except ImportError as e:
print(f"Error importing UI libraries: {e}")
print("Please run: pip install streamlit")
sys.exit(1)
def test_api_key(api_key: str) -> tuple[bool, str]:
"""Test an API key without full agent initialization"""
try:
client = openai.OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key,
default_headers={
"HTTP-Referer": os.getenv('OPENROUTER_APP_URL', 'https://github.com/DevanshSrajput/Dataa_Analyst_Agent'),
"X-Title": os.getenv('OPENROUTER_APP_NAME', 'AI Document Analyst v2.0')
}
)
response = client.chat.completions.create(
model='meta-llama/llama-3.1-8b-instruct:free',
messages=[{"role": "user", "content": "Test"}],
max_tokens=5,
temperature=0.1
)
return True, "✅ API key is valid!"
except Exception as e:
if "401" in str(e):
return False, "❌ Invalid or expired API key"
elif "429" in str(e):
return False, "⏰ Rate limit reached, but key appears valid"
else:
return False, f"❌ Connection error: {str(e)}"
class DocumentAnalystAgent:
"""
An intelligent document analysis agent that can process multiple file formats,
perform data analysis, generate visualizations, and answer questions.
"""
def __init__(self, api_key: str):
try:
if not api_key or api_key.strip() == "":
raise ValueError("API key cannot be empty")
# Initialize OpenRouter client
self.client = openai.OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key,
default_headers={
"HTTP-Referer": os.getenv('OPENROUTER_APP_URL', 'https://github.com/DevanshSrajput/Dataa_Analyst_Agent'),
"X-Title": os.getenv('OPENROUTER_APP_NAME', 'AI Document Analyst v2.0')
}
)
# Set default model - using a reliable free model
self.model = os.getenv('DEFAULT_MODEL', 'meta-llama/llama-3.1-8b-instruct:free')
self.backup_model = os.getenv('BACKUP_MODEL', 'openai/gpt-4o-mini')
self.document_content = {}
self.data_frames = {}
self.analysis_results = {}
self.conversation_history = []
# Initialize legal analyzer
self.legal_analyzer = LegalDocumentAnalyzer(api_key)
self.legal_analysis_results = {}
self.security_manager = LegalSecurityManager()
# Set up plotting style
plt.style.use('default')
sns.set_palette("husl")
# Test API connection
self._test_api_connection()
except Exception as e:
raise Exception(f"Failed to initialize DocumentAnalystAgent: {str(e)}")
def _test_api_connection(self):
"""Test API connection with a minimal request"""
try:
response = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": "Test"}],
max_tokens=5,
temperature=0.1
)
return True
except Exception as e:
# Try backup model if primary fails
try:
response = self.client.chat.completions.create(
model=self.backup_model,
messages=[{"role": "user", "content": "Test"}],
max_tokens=5,
temperature=0.1
)
self.model = self.backup_model # Switch to backup model
print(f"Primary model failed, switched to backup model: {self.backup_model}")
return True
except Exception as backup_error:
raise Exception(f"API connection test failed for both models. Primary: {str(e)}, Backup: {str(backup_error)}")
def extract_text_from_pdf(self, file_path: str) -> str:
"""Extract text from PDF file"""
try:
with open(file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text
except Exception as e:
return f"Error reading PDF: {str(e)}"
def extract_text_from_docx(self, file_path: str) -> str:
"""Extract text from DOCX file"""
try:
doc = docx.Document(file_path)
text = ""
for paragraph in doc.paragraphs:
text += paragraph.text + "\n"
return text
except Exception as e:
return f"Error reading DOCX: {str(e)}"
def extract_text_from_image(self, file_path: str) -> str:
"""Extract text from image using OCR"""
try:
if not PYTESSERACT_AVAILABLE:
return "OCR functionality not available. Please install pytesseract and tesseract-ocr system package."
image = Image.open(file_path)
import pytesseract
text = pytesseract.image_to_string(image)
return text
except Exception as e:
return f"Error processing image: {str(e)}"
def load_structured_data(self, file_path: str) -> pd.DataFrame:
"""Load structured data from CSV or Excel files"""
try:
if file_path.endswith('.csv'):
return pd.read_csv(file_path)
elif file_path.endswith(('.xlsx', '.xls')):
return pd.read_excel(file_path)
else:
raise ValueError("Unsupported structured data format")
except Exception as e:
print(f"Error loading structured data: {str(e)}")
return pd.DataFrame()
def process_document(self, file_path: str, file_name: str) -> Dict[str, Any]:
"""
Process a document based on its type and extract relevant information
Args:
file_path: Path to the file
file_name: Name of the file
Returns:
Dictionary containing processed information
"""
file_extension = file_name.lower().split('.')[-1]
result = {
'file_name': file_name,
'file_type': file_extension,
'content': '',
'data_frame': None,
'summary': ''
}
try:
if file_extension == 'pdf':
result['content'] = self.extract_text_from_pdf(file_path)
elif file_extension == 'docx':
result['content'] = self.extract_text_from_docx(file_path)
elif file_extension == 'txt':
with open(file_path, 'r', encoding='utf-8') as f:
result['content'] = f.read()
elif file_extension in ['csv', 'xlsx', 'xls']:
df = self.load_structured_data(file_path)
result['data_frame'] = df
result['content'] = df.to_string()
self.data_frames[file_name] = df
elif file_extension in ['jpg', 'jpeg', 'png', 'tiff', 'bmp']:
result['content'] = self.extract_text_from_image(file_path)
# Store processed content
self.document_content[file_name] = result
# Generate initial summary
result['summary'] = self.generate_document_summary(result)
# Perform legal analysis if document contains legal content
if self.is_legal_document(result['content']):
legal_analysis = self.legal_analyzer.analyze_legal_document(
result['content'],
self.detect_legal_document_type(result['content'])
)
result['legal_analysis'] = legal_analysis
self.legal_analysis_results[file_name] = legal_analysis
return result
except Exception as e:
result['content'] = f"Error processing file: {str(e)}"
return result
def _extract_response_content(self, response) -> str:
"""Extract content from Together API response"""
try:
# Handle Together API response format
if hasattr(response, 'choices') and response.choices:
choice = response.choices[0]
if hasattr(choice, 'message') and hasattr(choice.message, 'content'):
content = choice.message.content
# Handle case where content is a list
if isinstance(content, list):
return ' '.join(str(item) for item in content)
return str(content) if content else ""
elif hasattr(choice, 'text'):
return str(choice.text)
# Fallback to string conversion
return str(response)
except Exception as e:
print(f"Error extracting response content: {e}")
return f"Error processing response: {str(e)}"
def generate_document_summary(self, document_info: Dict[str, Any]) -> str:
"""Generate a summary of the document using the LLM"""
try:
content_preview = document_info['content'][:2000] # Limit content length
prompt = f"""
Analyze the following document and provide a comprehensive summary:
File Name: {document_info['file_name']}
File Type: {document_info['file_type']}
Content Preview:
{content_preview}
Please provide:
1. A brief overview of the document
2. Key topics or themes identified
3. If it contains data, describe the structure and main variables
4. Any notable patterns or insights
Keep the summary concise but informative.
"""
return self._make_api_call_with_retry(prompt, max_tokens=500)
except Exception as e:
return f"Error generating summary: {str(e)}"
def perform_data_analysis(self, df: pd.DataFrame, file_name: str) -> Dict[str, Any]:
"""
Perform comprehensive data analysis on structured data
Args:
df: DataFrame to analyze
file_name: Name of the source file
Returns:
Dictionary containing analysis results
"""
analysis = {
'basic_info': {
'shape': df.shape,
'columns': df.columns.tolist(),
'dtypes': df.dtypes.to_dict(),
'memory_usage': df.memory_usage(deep=True).sum()
},
'summary_statistics': {},
'missing_values': df.isnull().sum().to_dict(),
'unique_values': {},
'correlations': None
}
# Summary statistics for numeric columns
numeric_columns = df.select_dtypes(include=[np.number]).columns
if len(numeric_columns) > 0:
analysis['summary_statistics'] = df[numeric_columns].describe().to_dict()
# Correlation matrix for numeric columns
if len(numeric_columns) > 1:
analysis['correlations'] = df[numeric_columns].corr().to_dict()
# Unique values for categorical columns
categorical_columns = df.select_dtypes(include=['object']).columns
for col in categorical_columns:
analysis['unique_values'][col] = df[col].nunique()
# Store analysis results
self.analysis_results[file_name] = analysis
return analysis
def create_visualizations(self, df: pd.DataFrame, file_name: str) -> List[str]:
"""
Create various visualizations for the data
Args:
df: DataFrame to visualize
file_name: Name of the source file
Returns:
List of paths to saved visualization files
"""
visualization_paths = []
numeric_columns = df.select_dtypes(include=[np.number]).columns
categorical_columns = df.select_dtypes(include=['object']).columns
# Create output directory
output_dir = f"visualizations_{file_name.replace('.', '_')}"
os.makedirs(output_dir, exist_ok=True)
try:
# 1. Distribution plots for numeric columns
if len(numeric_columns) > 0:
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
axes = axes.ravel()
for i, col in enumerate(numeric_columns[:4]):
if i < len(axes):
df[col].hist(bins=30, ax=axes[i])
axes[i].set_title(f'Distribution of {col}')
axes[i].set_xlabel(col)
axes[i].set_ylabel('Frequency')
plt.tight_layout()
dist_path = os.path.join(output_dir, 'distributions.png')
plt.savefig(dist_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(dist_path)
# 2. Correlation heatmap
if len(numeric_columns) > 1:
plt.figure(figsize=(10, 8))
correlation_matrix = df[numeric_columns].corr()
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('Correlation Heatmap')
corr_path = os.path.join(output_dir, 'correlation_heatmap.png')
plt.savefig(corr_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(corr_path)
# 3. Box plots for numeric columns
if len(numeric_columns) > 0:
n_plots = min(3, len(numeric_columns))
# Always create a figure with at least one subplot
fig, ax_array = plt.subplots(1, n_plots, figsize=(15, 5), squeeze=False)
axes = ax_array.flatten()
for i, col in enumerate(numeric_columns[:n_plots]):
df.boxplot(column=col, ax=axes[i])
axes[i].set_title(f'Box Plot of {col}')
plt.tight_layout()
box_path = os.path.join(output_dir, 'box_plots.png')
plt.savefig(box_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(box_path)
# 4. Bar charts for categorical columns
if len(categorical_columns) > 0:
n_cat_plots = min(2, len(categorical_columns))
fig, ax_array = plt.subplots(1, n_cat_plots, figsize=(15, 6), squeeze=False)
axes = ax_array.flatten()
for i, col in enumerate(categorical_columns[:n_cat_plots]):
if df[col].nunique() <= 20:
value_counts = df[col].value_counts().head(10)
value_counts.plot(kind='bar', ax=axes[i])
axes[i].set_title(f'Top Values in {col}')
axes[i].set_xlabel(col)
axes[i].set_ylabel('Count')
axes[i].tick_params(axis='x', rotation=45)
plt.tight_layout()
bar_path = os.path.join(output_dir, 'categorical_bars.png')
plt.savefig(bar_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(bar_path)
except Exception as e:
print(f"Error creating visualizations: {str(e)}")
return visualization_paths
def answer_question(self, question: str, context_files: Optional[List[str]] = None) -> str:
"""
Answer a question based on the processed documents
Args:
question: User's question
context_files: Specific files to use as context (if None, uses all files)
Returns:
Answer to the question
"""
try:
# Prepare context from documents
context = ""
if context_files is None:
context_files = list(self.document_content.keys())
for file_name in context_files:
if file_name in self.document_content:
doc_info = self.document_content[file_name]
context += f"\n--- {file_name} ---\n"
context += f"File Type: {doc_info['file_type']}\n"
context += f"Summary: {doc_info['summary']}\n"
# Add relevant content (truncated for API limits)
content_preview = doc_info['content'][:1500]
context += f"Content: {content_preview}\n"
# Add analysis results if available
if file_name in self.analysis_results:
analysis = self.analysis_results[file_name]
context += f"Data Analysis Summary:\n"
context += f"Shape: {analysis['basic_info']['shape']}\n"
context += f"Columns: {analysis['basic_info']['columns']}\n"
if analysis['summary_statistics']:
context += f"Key Statistics Available: {list(analysis['summary_statistics'].keys())}\n"
# Create the prompt
prompt = f"""
You are an intelligent data analyst. Based on the following document(s) and analysis, please answer the user's question accurately and comprehensively.
CONTEXT FROM DOCUMENTS:
{context[:4000]} # Limit context length
CONVERSATION HISTORY:
{self._format_conversation_history()}
USER QUESTION: {question}
Please provide a detailed answer based on the available data and documents. If the question involves specific data analysis, calculations, or comparisons, please be precise and cite relevant statistics or findings from the documents.
If you cannot answer the question based on the available information, please explain what additional information would be needed.
"""
answer = self._make_api_call_with_retry(prompt, max_tokens=1000)
# Store in conversation history
self.conversation_history.append({
'question': question,
'answer': answer,
'context_files': context_files
})
return answer
except Exception as e:
return f"Error answering question: {str(e)}"
def _format_conversation_history(self) -> str:
"""Format conversation history for context"""
if not self.conversation_history:
return "No previous conversation."
formatted = ""
for i, item in enumerate(self.conversation_history[-3:]): # Last 3 exchanges
formatted += f"Q{i+1}: {item['question']}\n"
formatted += f"A{i+1}: {item['answer'][:200]}...\n\n"
return formatted
def generate_comprehensive_report(self, file_name: str) -> str:
"""
Generate a comprehensive analysis report for a file
Args:
file_name: Name of the file to generate report for
Returns:
Comprehensive report string
"""
if file_name not in self.document_content:
return f"File {file_name} not found in processed documents."
try:
doc_info = self.document_content[file_name]
report_prompt = f"""
Generate a comprehensive analytical report for the following document:
File: {file_name}
Type: {doc_info['file_type']}
Summary: {doc_info['summary']}
Content Sample: {doc_info['content'][:2000]}
Please provide:
1. Executive Summary
2. Key Findings
3. Data Quality Assessment (if applicable)
4. Trends and Patterns
5. Recommendations
6. Areas for Further Investigation
Make the report professional and actionable.
"""
return self._make_api_call_with_retry(report_prompt, max_tokens=1500)
except Exception as e:
return f"Error generating report: {str(e)}"
def get_file_info(self) -> Dict[str, Any]:
"""Get information about all processed files"""
info = {}
for file_name, doc_info in self.document_content.items():
info[file_name] = {
'type': doc_info['file_type'],
'has_data': file_name in self.data_frames,
'summary': doc_info['summary'][:100] + "..." if len(doc_info['summary']) > 100 else doc_info['summary']
}
return info
def _make_api_call_with_retry(self, prompt: str, max_tokens: int = 500, max_retries: int = 3) -> str:
"""Make API call with retry logic and exponential backoff"""
# Use session settings if available
try:
import streamlit as st
if hasattr(st, 'session_state'):
max_tokens = getattr(st.session_state, 'max_tokens', max_tokens)
max_retries = getattr(st.session_state, 'max_retries', max_retries)
temperature = getattr(st.session_state, 'temperature', 0.3)
else:
temperature = 0.3
except:
temperature = 0.3
for attempt in range(max_retries):
try:
if not self.client:
return "API client not initialized properly"
response = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
temperature=temperature,
stream=False
)
return self._extract_response_content(response)
except Exception as e:
error_str = str(e)
print(f"API call error (attempt {attempt + 1}/{max_retries}): {error_str}")
if "rate limit" in error_str.lower() or "429" in error_str:
wait_time = (2 ** attempt) * 30 # Exponential backoff: 30s, 60s, 120s
print(f"Rate limit hit. Waiting {wait_time} seconds before retry {attempt + 1}/{max_retries}...")
time.sleep(wait_time)
if attempt == max_retries - 1:
return f"Rate limit exceeded. Please try again in a few minutes. Error: {error_str}"
elif "authentication" in error_str.lower() or "unauthorized" in error_str.lower() or "401" in error_str:
return f"Authentication Error: Please check your API key. Error: {error_str}"
elif "invalid" in error_str.lower() and "model" in error_str.lower():
return f"Model Error: The model '{self.model}' may not be available. Error: {error_str}"
else:
# For other errors, wait a bit before retrying if we have retries left
if attempt < max_retries - 1:
wait_time = (attempt + 1) * 5 # 5s, 10s, 15s
print(f"General error, waiting {wait_time}s before retry...")
time.sleep(wait_time)
else:
return f"API Error: {error_str}"
return "Maximum retries exceeded. Please try again later."
def is_legal_document(self, content: str) -> bool:
"""Detect if document contains legal content"""
legal_indicators = [
'agreement', 'contract', 'party', 'whereas', 'plaintiff', 'defendant',
'court', 'statute', 'regulation', 'cfr', 'usc', 'whereas', 'breach',
'liability', 'indemnification', 'termination', 'compliance', 'legal',
'attorney', 'counsel', 'jurisdiction', 'patent', 'copyright', 'trademark'
]
content_lower = content.lower()
legal_term_count = sum(1 for term in legal_indicators if term in content_lower)
# If more than 3 legal terms found, consider it a legal document
return legal_term_count >= 3
def detect_legal_document_type(self, content: str) -> str:
"""Detect the specific type of legal document"""
return self.legal_analyzer.classify_legal_document(content)
def perform_legal_analysis(self, file_name: str) -> Dict[str, Any]:
"""Perform comprehensive legal analysis on a document"""
if file_name not in self.document_content:
return {"error": "Document not found"}
content = self.document_content[file_name]['content']
return self.legal_analyzer.analyze_legal_document(content)
def compare_legal_documents(self, file1: str, file2: str) -> Dict[str, Any]:
"""Compare two legal documents for differences"""
if file1 not in self.document_content or file2 not in self.document_content:
return {"error": "One or both documents not found"}
content1 = self.document_content[file1]['content']
content2 = self.document_content[file2]['content']
return self.legal_analyzer.compare_legal_documents(content1, content2)
def extract_legal_summary(self, file_name: str) -> str:
"""Generate a legal-focused summary"""
if file_name not in self.legal_analysis_results:
return "No legal analysis available for this document"
analysis = self.legal_analysis_results[file_name]
summary_parts = []
summary_parts.append(f"Document Type: {analysis.get('document_type', 'Unknown')}")
if analysis.get('risk_assessment'):
risk = analysis['risk_assessment']
summary_parts.append(f"Risk Level: {risk.get('overall_risk', 'Unknown')}")
if analysis.get('entities'):
entities = analysis['entities'][:3] # Top 3 entities
entity_names = [e.name for e in entities]
summary_parts.append(f"Key Parties: {', '.join(entity_names)}")
if analysis.get('key_obligations'):
obligations = analysis['key_obligations'][:2] # Top 2 obligations
summary_parts.append(f"Key Obligations: {'; '.join(obligations)}")
return '\n'.join(summary_parts)
def create_legal_visualizations(self, file_name: str) -> List[str]:
"""Create legal-specific visualizations"""
if file_name not in self.legal_analysis_results:
return []
analysis = self.legal_analysis_results[file_name]
visualization_paths = []
try:
output_dir = f"legal_visualizations_{file_name.replace('.', '_')}"
os.makedirs(output_dir, exist_ok=True)
# 1. Risk Assessment Chart
if analysis.get('risk_assessment'):
risk_data = analysis['risk_assessment']
risk_factors = risk_data.get('risk_factors', [])
if risk_factors:
risk_levels = [factor['level'] for factor in risk_factors]
risk_counts = {'high': 0, 'medium': 0, 'low': 0}
for level in risk_levels:
risk_counts[level] += 1
plt.figure(figsize=(10, 6))
colors = ['red', 'orange', 'green']
plt.bar(list(risk_counts.keys()), list(risk_counts.values()), color=colors)
plt.title('Legal Risk Assessment')
plt.xlabel('Risk Level')
plt.ylabel('Number of Risk Factors')
risk_path = os.path.join(output_dir, 'risk_assessment.png')
plt.savefig(risk_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(risk_path)
# 2. Entity Relationship Chart
if analysis.get('entities'):
entities = analysis['entities']
entity_types = {}
for entity in entities:
entity_type = entity.entity_type
if entity_type in entity_types:
entity_types[entity_type] += 1
else:
entity_types[entity_type] = 1
if entity_types:
plt.figure(figsize=(8, 8))
plt.pie(list(entity_types.values()), labels=list(entity_types.keys()), autopct='%1.1f%%')
plt.title('Legal Entities Distribution')
entities_path = os.path.join(output_dir, 'entities_distribution.png')
plt.savefig(entities_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(entities_path)
# 3. Compliance Score Gauge
if analysis.get('compliance_check'):
compliance = analysis['compliance_check']
score = compliance.get('score', 0)
fig, ax = plt.subplots(figsize=(8, 6))
# Create gauge chart
theta = np.linspace(0, np.pi, 100)
r = np.ones_like(theta)
ax = plt.subplot(111, polar=True)
ax.plot(theta, r, color='lightgray', linewidth=10)
# Color based on score
if score >= 80:
color = 'green'
elif score >= 60:
color = 'orange'
else:
color = 'red'
score_theta = np.linspace(0, np.pi * (score / 100), 50)
ax.plot(score_theta, np.ones_like(score_theta), color=color, linewidth=10)
ax.set_ylim(0, 1.2)
ax.set_title(f'Compliance Score: {score}%', pad=20)
ax.set_ylim(0, 1.2)
ax.grid(True)
compliance_path = os.path.join(output_dir, 'compliance_score.png')
plt.savefig(compliance_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(compliance_path)
# 4. Timeline Visualization
if analysis.get('dates'):
dates = analysis['dates']
if dates:
plt.figure(figsize=(12, 6))
date_types = [date.date_type for date in dates]
importance_levels = [date.importance for date in dates]
# Create timeline
y_pos = range(len(dates))
colors = ['red' if imp == 'critical' else 'orange' if imp == 'important' else 'blue'
for imp in importance_levels]
plt.barh(y_pos, [1] * len(dates), color=colors)
plt.yticks(y_pos, [f"{date.date_type}: {date.date_text}" for date in dates])
plt.xlabel('Timeline')
plt.title('Legal Dates and Deadlines')
timeline_path = os.path.join(output_dir, 'legal_timeline.png')
plt.savefig(timeline_path, dpi=300, bbox_inches='tight')
plt.close()
visualization_paths.append(timeline_path)
except Exception as e:
print(f"Error creating legal visualizations: {str(e)}")
return visualization_paths
def generate_legal_report(self, file_name: str) -> str:
"""Generate comprehensive legal analysis report"""
if file_name not in self.legal_analysis_results:
return "No legal analysis available for this document"
analysis = self.legal_analysis_results[file_name]
try:
report_prompt = f"""
Generate a comprehensive legal analysis report based on the following analysis:
Document: {file_name}
Document Type: {analysis.get('document_type', 'Unknown')}
Risk Assessment: {analysis.get('risk_assessment', {})}
Entities Found: {len(analysis.get('entities', []))}
Citations Found: {len(analysis.get('citations', []))}
Legal Clauses: {len(analysis.get('clauses', []))}
Key Obligations: {analysis.get('key_obligations', [])}
Compliance Score: {analysis.get('compliance_check', {}).get('score', 'N/A')}
Plain English Summary: {analysis.get('plain_english_summary', '')}
Please provide:
1. Executive Summary
2. Legal Risk Analysis
3. Key Findings and Recommendations
4. Compliance Assessment
5. Action Items and Next Steps
Make the report suitable for legal professionals and decision makers.
"""
return self._make_api_call_with_retry(report_prompt, max_tokens=2000)
except Exception as e:
return f"Error generating legal report: {str(e)}"
class LegalSecurityManager:
"""Handle security and privacy for legal documents"""
def __init__(self):
self.access_logs = []
self.privilege_markers = [
'attorney-client privilege', 'privileged and confidential',
'work product', 'attorney work product', 'confidential',
'privileged communication'
]
def check_privilege(self, content: str) -> Dict[str, Any]:
"""Check for attorney-client privilege indicators"""
content_lower = content.lower()
privilege_found = []
for marker in self.privilege_markers:
if marker in content_lower:
privilege_found.append(marker)
return {
'is_privileged': len(privilege_found) > 0,
'privilege_markers': privilege_found,
'warning': 'This document may contain privileged information' if privilege_found else None
}
def log_access(self, user_id: str, document_name: str, action: str):
"""Log document access for audit trail"""
timestamp = datetime.now().isoformat()
log_entry = {
'timestamp': timestamp,
'user_id': user_id,
'document': document_name,
'action': action,
'hash': hashlib.md5(f"{timestamp}{user_id}{document_name}".encode()).hexdigest()[:8]
}
self.access_logs.append(log_entry)
def encrypt_sensitive_data(self, data: str) -> str:
"""Basic encryption for sensitive legal data (placeholder)"""
# In production, use proper encryption libraries
encoded = base64.b64encode(data.encode()).decode()
return f"ENCRYPTED:{encoded}"
def decrypt_sensitive_data(self, encrypted_data: str) -> str:
"""Basic decryption for sensitive legal data (placeholder)"""
if encrypted_data.startswith("ENCRYPTED:"):
encoded = encrypted_data[10:]
return base64.b64decode(encoded).decode()
return encrypted_data
def generate_confidentiality_notice(self) -> str:
"""Generate a confidentiality notice for legal documents"""
return """
CONFIDENTIALITY NOTICE:
This document may contain attorney-client privileged information and/or
attorney work product. If you are not the intended recipient, please
notify the sender immediately and delete this document. Any unauthorized
review, use, disclosure or distribution is prohibited.
"""
# Legal Document Analysis Classes
class LegalDocumentType(Enum):
CONTRACT = "contract"
STATUTE = "statute"
CASE_LAW = "case_law"
REGULATION = "regulation"
PATENT = "patent"
LEGAL_BRIEF = "legal_brief"
GENERAL = "general"
@dataclass
class LegalEntity: