-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstreamlit_app.py
More file actions
623 lines (487 loc) Β· 19.7 KB
/
Copy pathstreamlit_app.py
File metadata and controls
623 lines (487 loc) Β· 19.7 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
import os
import uuid
import streamlit as st
from dotenv import load_dotenv
load_dotenv()
st.set_page_config(
page_title="Contract Analyzer",
page_icon="π",
layout="wide",
initial_sidebar_state="expanded"
)
st.markdown("""
<style>
/* Main container styling */
.main > div {
padding-top: 2rem;
}
/* Header styling */
.main-header {
background: linear-gradient(135deg, #1e3a5f 0%, #2d5a87 100%);
padding: 2rem;
border-radius: 12px;
margin-bottom: 2rem;
color: white;
text-align: center;
}
.main-header h1 {
margin: 0;
font-size: 2.5rem;
font-weight: 700;
}
.main-header p {
margin: 0.5rem 0 0 0;
opacity: 0.9;
font-size: 1.1rem;
}
/* Card styling */
.analysis-card {
background: white;
border-radius: 12px;
padding: 1.5rem;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 1rem;
border-left: 4px solid #2d5a87;
}
.risk-high {
border-left-color: #dc3545;
background: #fff5f5;
}
.risk-medium {
border-left-color: #ffc107;
background: #fffdf5;
}
.risk-low {
border-left-color: #28a745;
background: #f5fff5;
}
/* Metric styling */
.metric-container {
display: flex;
gap: 1rem;
flex-wrap: wrap;
}
.metric-box {
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
border-radius: 8px;
padding: 1rem;
text-align: center;
flex: 1;
min-width: 120px;
}
.metric-value {
font-size: 1.8rem;
font-weight: 700;
color: #2d5a87;
}
.metric-label {
font-size: 0.85rem;
color: #6c757d;
}
/* Chat styling */
.chat-message {
padding: 1rem;
border-radius: 12px;
margin-bottom: 0.5rem;
max-width: 85%;
}
.user-message {
background: #e3f2fd;
margin-left: auto;
margin-right: 0;
}
.assistant-message {
background: #f5f5f5;
margin-left: 0;
margin-right: auto;
}
/* Button styling */
.stButton > button {
background: linear-gradient(135deg, #2d5a87 0%, #1e3a5f 100%);
color: white;
border: none;
padding: 0.5rem 1.5rem;
border-radius: 8px;
font-weight: 600;
transition: transform 0.2s, box-shadow 0.2s;
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(45, 90, 135, 0.3);
}
/* Sidebar styling */
.css-1d391kg {
background: #f8f9fa;
}
/* Tab styling */
.stTabs [data-baseweb="tab-list"] {
gap: 8px;
}
.stTabs [data-baseweb="tab"] {
background: #f0f2f6;
border-radius: 8px 8px 0 0;
padding: 0.5rem 1rem;
}
.stTabs [aria-selected="true"] {
background: #2d5a87;
color: white;
}
</style>
""", unsafe_allow_html=True)
def extract_text_from_pdf(file_content: bytes) -> str:
"""Extract text from a PDF file."""
try:
from PyPDF2 import PdfReader
from io import BytesIO
reader = PdfReader(BytesIO(file_content))
text_parts = []
for page in reader.pages:
text = page.extract_text()
if text:
text_parts.append(text)
return "\n\n".join(text_parts)
except ImportError:
st.error("PyPDF2 is required for PDF support. Install with: pip install PyPDF2")
return ""
except Exception as e:
st.error(f"Error reading PDF: {e}")
return ""
def extract_text_from_docx(file_content: bytes) -> str:
"""Extract text from a DOCX file."""
try:
from docx import Document
from io import BytesIO
doc = Document(BytesIO(file_content))
paragraphs = [p.text for p in doc.paragraphs if p.text.strip()]
return "\n\n".join(paragraphs)
except ImportError:
st.error("python-docx is required for DOCX support. Install with: pip install python-docx")
return ""
except Exception as e:
st.error(f"Error reading DOCX: {e}")
return ""
def initialize_session_state():
"""Initialize Streamlit session state variables."""
if "session_id" not in st.session_state:
st.session_state.session_id = str(uuid.uuid4())[:8]
if "contract_text" not in st.session_state:
st.session_state.contract_text = ""
if "analysis_result" not in st.session_state:
st.session_state.analysis_result = None
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "agent" not in st.session_state:
st.session_state.agent = None
def get_or_create_agent():
"""Get existing agent or create a new one."""
if st.session_state.agent is None:
from contract_analyzer.agent import create_contract_analyzer_agent
st.session_state.agent = create_contract_analyzer_agent(
session_id=st.session_state.session_id
)
return st.session_state.agent
def render_header():
"""Render the main header."""
st.markdown("""
<div class="main-header">
<h1>π Contract Analyzer</h1>
<p>AI-powered contract analysis for legal and business insights</p>
</div>
""", unsafe_allow_html=True)
def render_sidebar():
"""Render the sidebar with upload and settings."""
with st.sidebar:
st.markdown("### π Upload Contract")
uploaded_file = st.file_uploader(
"Choose a file",
type=["pdf", "docx", "txt"],
help="Upload a contract in PDF, Word, or text format"
)
if uploaded_file is not None:
file_content = uploaded_file.read()
file_type = uploaded_file.name.split(".")[-1].lower()
if file_type == "pdf":
text = extract_text_from_pdf(file_content)
elif file_type == "docx":
text = extract_text_from_docx(file_content)
else:
text = file_content.decode("utf-8")
if text:
st.session_state.contract_text = text
st.success(f"β
Loaded: {uploaded_file.name}")
st.info(f"π {len(text):,} characters extracted")
st.divider()
st.markdown("### βοΈ Or Paste Contract")
pasted_text = st.text_area(
"Paste contract text",
height=150,
placeholder="Paste your contract text here..."
)
if pasted_text and pasted_text != st.session_state.contract_text:
if st.button("Use Pasted Text", use_container_width=True):
st.session_state.contract_text = pasted_text
st.rerun()
st.divider()
st.markdown("### βοΈ Settings")
analysis_type = st.selectbox(
"Analysis Type",
options=["full", "summary", "risk", "extraction"],
format_func=lambda x: {
"full": "π Full Analysis",
"summary": "π Executive Summary",
"risk": "β οΈ Risk Assessment",
"extraction": "π Data Extraction"
}.get(x, x)
)
st.divider()
if st.button("ποΈ Clear Session", use_container_width=True):
st.session_state.contract_text = ""
st.session_state.analysis_result = None
st.session_state.chat_history = []
st.session_state.agent = None
st.session_state.session_id = str(uuid.uuid4())[:8]
st.rerun()
return analysis_type
def render_analysis_tab(analysis_type: str):
"""Render the main analysis tab."""
if not st.session_state.contract_text:
st.info("π Upload a contract or paste text to begin analysis")
if st.button("π Load Sample Contract"):
st.session_state.contract_text = get_sample_contract()
st.rerun()
return
with st.expander("π Contract Preview", expanded=False):
st.text_area(
"Contract Text",
value=st.session_state.contract_text[:5000] + ("..." if len(st.session_state.contract_text) > 5000 else ""),
height=200,
disabled=True
)
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
analyze_button = st.button(
"π Analyze Contract",
use_container_width=True,
type="primary"
)
if analyze_button:
with st.spinner("Analyzing contract... This may take a moment."):
try:
from contract_analyzer.agent import create_analysis_task
agent = get_or_create_agent()
task = create_analysis_task(
st.session_state.contract_text,
analysis_type
)
result = agent.do(task)
st.session_state.analysis_result = str(result)
except Exception as e:
st.error(f"Analysis failed: {e}")
st.session_state.analysis_result = None
if st.session_state.analysis_result:
st.markdown("---")
st.markdown("### π Analysis Results")
st.markdown(st.session_state.analysis_result)
st.markdown("---")
col1, col2 = st.columns(2)
with col1:
st.download_button(
"π₯ Download as Text",
data=st.session_state.analysis_result,
file_name="contract_analysis.txt",
mime="text/plain"
)
with col2:
md_content = f"""# Contract Analysis Report
Generated by Contract Analyzer
---
{st.session_state.analysis_result}
"""
st.download_button(
"π₯ Download as Markdown",
data=md_content,
file_name="contract_analysis.md",
mime="text/markdown"
)
def render_chat_tab():
"""Render the interactive chat tab."""
st.markdown("### π¬ Ask Questions About Your Contract")
if not st.session_state.contract_text:
st.info("π Upload a contract first to start asking questions")
return
for message in st.session_state.chat_history:
role = message["role"]
content = message["content"]
if role == "user":
with st.chat_message("user"):
st.write(content)
else:
with st.chat_message("assistant"):
st.write(content)
user_question = st.chat_input("Ask a question about your contract...")
if user_question:
st.session_state.chat_history.append({
"role": "user",
"content": user_question
})
with st.chat_message("user"):
st.write(user_question)
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
try:
from upsonic import Task
agent = get_or_create_agent()
task = Task(
description=f"""Based on the following contract, please answer this question:
Question: {user_question}
<contract>
{st.session_state.contract_text}
</contract>
Provide a helpful, accurate answer based on the contract content."""
)
result = agent.do(task)
response = str(result)
st.write(response)
st.session_state.chat_history.append({
"role": "assistant",
"content": response
})
except Exception as e:
error_msg = f"Sorry, I encountered an error: {e}"
st.error(error_msg)
st.session_state.chat_history.append({
"role": "assistant",
"content": error_msg
})
def render_tools_tab():
"""Render the quick extraction tools tab."""
st.markdown("### π§ Quick Extraction Tools")
if not st.session_state.contract_text:
st.info("π Upload a contract first to use extraction tools")
return
col1, col2 = st.columns(2)
with col1:
if st.button("π₯ Extract Parties", use_container_width=True):
with st.spinner("Extracting parties..."):
from contract_analyzer.tools import ContractAnalyzerToolKit
toolkit = ContractAnalyzerToolKit()
result = toolkit.extract_parties(st.session_state.contract_text)
st.json(result)
if st.button("π
Extract Dates", use_container_width=True):
with st.spinner("Extracting dates..."):
from contract_analyzer.tools import ContractAnalyzerToolKit
toolkit = ContractAnalyzerToolKit()
result = toolkit.extract_key_dates(st.session_state.contract_text)
st.json(result)
if st.button("π° Extract Financial Terms", use_container_width=True):
with st.spinner("Extracting financial terms..."):
from contract_analyzer.tools import ContractAnalyzerToolKit
toolkit = ContractAnalyzerToolKit()
result = toolkit.extract_financial_terms(st.session_state.contract_text)
st.json(result)
with col2:
if st.button("π Extract Obligations", use_container_width=True):
with st.spinner("Extracting obligations..."):
from contract_analyzer.tools import ContractAnalyzerToolKit
toolkit = ContractAnalyzerToolKit()
result = toolkit.identify_obligations(st.session_state.contract_text)
st.json(result)
if st.button("β οΈ Detect Risks", use_container_width=True):
with st.spinner("Detecting risks..."):
from contract_analyzer.tools import ContractAnalyzerToolKit
toolkit = ContractAnalyzerToolKit()
result = toolkit.detect_risk_clauses(st.session_state.contract_text)
st.json(result)
if st.button("π Generate Summary", use_container_width=True):
with st.spinner("Generating summary..."):
from contract_analyzer.tools import ContractAnalyzerToolKit
toolkit = ContractAnalyzerToolKit()
result = toolkit.summarize_contract(st.session_state.contract_text)
st.code(result, language=None)
def get_sample_contract() -> str:
"""Return a sample contract for testing."""
return """SERVICE AGREEMENT
This Service Agreement ("Agreement") is entered into as of January 15, 2024 ("Effective Date") by and between:
ABC Technology Solutions Inc., a Delaware corporation ("Provider"), and
XYZ Enterprises LLC, a California limited liability company ("Client").
RECITALS
WHEREAS, Provider is in the business of providing software development and IT consulting services; and
WHEREAS, Client desires to engage Provider to provide certain services as described herein;
NOW, THEREFORE, in consideration of the mutual covenants and agreements hereinafter set forth, the parties agree as follows:
1. SERVICES
Provider agrees to provide the following services to Client:
- Custom software development
- System integration consulting
- Technical support and maintenance
- Training and documentation
2. TERM
This Agreement shall commence on the Effective Date and continue for a period of two (2) years ("Initial Term"), unless earlier terminated in accordance with Section 8. This Agreement shall automatically renew for successive one (1) year periods unless either party provides written notice of non-renewal at least sixty (60) days prior to the end of the then-current term.
3. COMPENSATION
3.1 Fees. Client shall pay Provider the following fees:
- Monthly retainer: $15,000
- Additional development work: $175 per hour
- Emergency support: $250 per hour
3.2 Payment Terms. All invoices are due within thirty (30) days of receipt. Late payments shall accrue interest at 1.5% per month.
4. CONFIDENTIALITY
Each party agrees to maintain the confidentiality of all Confidential Information disclosed by the other party. This obligation shall survive for a period of five (5) years following termination of this Agreement.
5. INTELLECTUAL PROPERTY
5.1 Pre-existing IP. Each party retains ownership of its pre-existing intellectual property.
5.2 Work Product. All work product created by Provider specifically for Client shall be owned by Client upon full payment.
6. WARRANTIES
Provider warrants that all services will be performed in a professional and workmanlike manner. Provider makes no other warranties, express or implied, including any implied warranty of merchantability or fitness for a particular purpose.
7. LIMITATION OF LIABILITY
IN NO EVENT SHALL EITHER PARTY BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES. PROVIDER'S TOTAL LIABILITY SHALL NOT EXCEED THE FEES PAID BY CLIENT IN THE TWELVE (12) MONTHS PRECEDING THE CLAIM.
8. TERMINATION
8.1 For Cause. Either party may terminate this Agreement upon thirty (30) days written notice if the other party materially breaches this Agreement and fails to cure such breach within the notice period.
8.2 For Convenience. Either party may terminate this Agreement without cause upon ninety (90) days written notice.
9. INDEMNIFICATION
Client shall indemnify and hold harmless Provider from any claims arising from Client's use of the services or Client's breach of this Agreement.
10. GOVERNING LAW
This Agreement shall be governed by the laws of the State of Delaware, without regard to its conflict of laws principles. Any disputes shall be resolved through binding arbitration in Wilmington, Delaware.
11. ENTIRE AGREEMENT
This Agreement constitutes the entire agreement between the parties and supersedes all prior negotiations, representations, and agreements.
IN WITNESS WHEREOF, the parties have executed this Agreement as of the Effective Date.
ABC TECHNOLOGY SOLUTIONS INC.
By: ________________________
Name: John Smith
Title: Chief Executive Officer
Date: January 15, 2024
XYZ ENTERPRISES LLC
By: ________________________
Name: Jane Doe
Title: Managing Director
Date: January 15, 2024
"""
def main():
"""Main application entry point."""
if not os.getenv("OPENAI_API_KEY"):
st.error("""
β οΈ **OpenAI API Key Required**
Please set your `OPENAI_API_KEY` environment variable or create a `.env` file.
See `.env.example` for reference.
""")
st.stop()
initialize_session_state()
render_header()
analysis_type = render_sidebar()
tab1, tab2, tab3 = st.tabs([
"π Analysis",
"π¬ Chat",
"π§ Tools"
])
with tab1:
render_analysis_tab(analysis_type)
with tab2:
render_chat_tab()
with tab3:
render_tools_tab()
st.markdown("---")
st.markdown(
"<div style='text-align: center; color: #888;'>"
"Built with <a href='https://github.com/Upsonic/Upsonic'>Upsonic AI Agent Framework</a> | "
f"Session: {st.session_state.session_id}"
"</div>",
unsafe_allow_html=True
)
if __name__ == "__main__":
main()