-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
230 lines (186 loc) · 7.01 KB
/
Copy pathapp.py
File metadata and controls
230 lines (186 loc) · 7.01 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
import os
import PyPDF2
import docx
from flask import Flask, request, jsonify, render_template, send_from_directory
from werkzeug.utils import secure_filename
from dotenv import load_dotenv
import openai
from langchain_openai import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema import HumanMessage, SystemMessage
from config import get_config
# Load environment variables
load_dotenv()
# Get configuration
config = get_config()
app = Flask(__name__)
app.config.from_object(config)
# Ensure upload directory exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# OpenAI configuration
openai.api_key = app.config['OPENAI_API_KEY']
llm = ChatOpenAI(
model=app.config['OPENAI_MODEL'],
temperature=app.config['OPENAI_TEMPERATURE'],
api_key=app.config['OPENAI_API_KEY']
)
def allowed_file(filename):
"""Check if file extension is allowed"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']
def extract_text_from_pdf(file_path):
"""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.strip()
except Exception as e:
raise ValueError(f"Error reading PDF: {str(e)}")
def extract_text_from_docx(file_path):
"""Extract text from DOCX file"""
try:
doc = docx.Document(file_path)
text = ""
for paragraph in doc.paragraphs:
text += paragraph.text + "\n"
return text.strip()
except Exception as e:
raise ValueError(f"Error reading DOCX: {str(e)}")
def extract_text_from_txt(file_path):
"""Extract text from TXT file"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
return file.read().strip()
except Exception as e:
raise ValueError(f"Error reading TXT: {str(e)}")
def extract_text_from_file(file_path, file_extension):
"""Extract text based on file extension"""
if file_extension.lower() == 'pdf':
return extract_text_from_pdf(file_path)
elif file_extension.lower() == 'docx':
return extract_text_from_docx(file_path)
elif file_extension.lower() == 'txt':
return extract_text_from_txt(file_path)
else:
raise ValueError("Unsupported file format")
def simplify_legal_text(text):
"""Use AI to simplify legal text"""
try:
system_prompt = app.config['SIMPLIFICATION_PROMPT']
human_prompt = f"Please simplify this legal text:\n\n{text[:4000]}" # Limit text length
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=human_prompt)
]
response = llm.invoke(messages)
return response.content
except Exception as e:
return f"Error processing text with AI: {str(e)}"
def explain_legal_term(term):
"""Use AI to explain a legal term"""
try:
system_prompt = app.config['TERM_EXPLANATION_PROMPT']
human_prompt = f"Please explain this legal term: {term}"
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=human_prompt)
]
response = llm.invoke(messages)
return response.content
except Exception as e:
return f"Error explaining term: {str(e)}"
def generate_document_summary(text):
"""Use AI to generate a document summary"""
try:
system_prompt = app.config['SUMMARY_PROMPT']
human_prompt = f"Please summarize this legal document:\n\n{text[:3000]}" # Limit text length
messages = [
SystemMessage(content=system_prompt),
HumanMessage(content=human_prompt)
]
response = llm.invoke(messages)
return response.content
except Exception as e:
return f"Error generating summary: {str(e)}"
@app.route('/')
def index():
"""Main page"""
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
"""Handle file upload and processing"""
if 'file' not in request.files:
return jsonify({'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'error': 'No file selected'}), 400
if file and allowed_file(file.filename):
try:
filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
# Extract text from file
file_extension = filename.rsplit('.', 1)[1].lower()
extracted_text = extract_text_from_file(file_path, file_extension)
# Process with AI
simplified_text = simplify_legal_text(extracted_text)
summary = generate_document_summary(extracted_text)
# Clean up uploaded file
os.remove(file_path)
return jsonify({
'success': True,
'original_text': extracted_text,
'simplified_text': simplified_text,
'summary': summary,
'filename': filename
})
except ValueError as e:
return jsonify({'error': str(e)}), 400
except Exception as e:
return jsonify({'error': f'Error processing file: {str(e)}'}), 500
return jsonify({'error': 'Invalid file type'}), 400
@app.route('/simplify', methods=['POST'])
def simplify_text():
"""Simplify legal text"""
data = request.get_json()
if not data or 'text' not in data:
return jsonify({'error': 'No text provided'}), 400
text = data['text']
simplified = simplify_legal_text(text)
return jsonify({
'success': True,
'simplified_text': simplified
})
@app.route('/explain', methods=['POST'])
def explain_term():
"""Explain a legal term"""
data = request.get_json()
if not data or 'term' not in data:
return jsonify({'error': 'No term provided'}), 400
term = data['term']
explanation = explain_legal_term(term)
return jsonify({
'success': True,
'explanation': explanation
})
@app.route('/summarize', methods=['POST'])
def summarize_document():
"""Generate document summary"""
data = request.get_json()
if not data or 'text' not in data:
return jsonify({'error': 'No text provided'}), 400
text = data['text']
summary = generate_document_summary(text)
return jsonify({
'success': True,
'summary': summary
})
@app.route('/health')
def health_check():
"""Health check endpoint"""
return jsonify({'status': 'healthy', 'message': 'Legal Document AI Simplifier is running'})
if __name__ == '__main__':
app.run(debug=os.getenv('FLASK_DEBUG', 'True').lower() == 'true', host='0.0.0.0', port=5000)