Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,206 +1,211 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
-
import numpy as np
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
-
|
| 6 |
-
import
|
| 7 |
-
import
|
| 8 |
-
import
|
| 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 |
-
ax.barh(range(len(sections)), [r[2] for r in risks], color='red', height=0.4)
|
| 67 |
|
| 68 |
-
ax.
|
| 69 |
-
ax.
|
| 70 |
-
|
| 71 |
-
ax.set_title('Risk Heatmap of Contract Sections')
|
| 72 |
|
|
|
|
| 73 |
plt.tight_layout()
|
| 74 |
return fig
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
sf = get_salesforce_connection()
|
| 79 |
-
if not sf:
|
| 80 |
-
logger.error("Salesforce connection failed. Cannot upload file.")
|
| 81 |
-
return None
|
| 82 |
-
|
| 83 |
-
with open(file_path, "rb") as f:
|
| 84 |
-
file_data = f.read()
|
| 85 |
-
|
| 86 |
-
encoded_file_data = base64.b64encode(file_data).decode('utf-8')
|
| 87 |
-
content_version_data = {
|
| 88 |
-
"Title": file_name,
|
| 89 |
-
"PathOnClient": file_name,
|
| 90 |
-
"VersionData": encoded_file_data,
|
| 91 |
-
}
|
| 92 |
-
|
| 93 |
-
if record_id:
|
| 94 |
-
content_version_data["FirstPublishLocationId"] = record_id
|
| 95 |
-
|
| 96 |
-
content_version = sf.ContentVersion.create(content_version_data)
|
| 97 |
-
return content_version["id"]
|
| 98 |
-
|
| 99 |
-
# Function to generate a PDF report
|
| 100 |
-
def generate_pdf_report(project_title, risk_tags, ai_plan_score, estimated_duration, location, weather, gantt_chart_path=None):
|
| 101 |
-
pdf_file = BytesIO()
|
| 102 |
-
doc = SimpleDocTemplate(pdf_file, pagesize=letter)
|
| 103 |
-
styles = getSampleStyleSheet()
|
| 104 |
-
elements = []
|
| 105 |
-
|
| 106 |
-
title_style = ParagraphStyle('Title', parent=styles['Heading1'], fontSize=18, alignment=1, spaceAfter=20)
|
| 107 |
-
elements.append(Paragraph(f"Project Report: {project_title}", title_style))
|
| 108 |
-
|
| 109 |
-
details_style = styles['BodyText']
|
| 110 |
-
details = [
|
| 111 |
-
f"<b>Location:</b> {location}",
|
| 112 |
-
f"<b>Weather:</b> {weather.capitalize()}",
|
| 113 |
-
f"<b>Estimated Duration:</b> {estimated_duration} days",
|
| 114 |
-
f"<b>AI Plan Score:</b> {ai_plan_score:.1f}%",
|
| 115 |
-
]
|
| 116 |
-
for detail in details:
|
| 117 |
-
elements.append(Paragraph(detail, details_style))
|
| 118 |
-
|
| 119 |
-
elements.append(Spacer(1, 12))
|
| 120 |
-
elements.append(Paragraph("<b>Risk Assessment:</b>", styles['Heading2']))
|
| 121 |
-
|
| 122 |
-
for risk in risk_tags.split("\n"):
|
| 123 |
-
elements.append(Paragraph(f"• {risk}", details_style))
|
| 124 |
-
|
| 125 |
-
if gantt_chart_path:
|
| 126 |
-
elements.append(Spacer(1, 24))
|
| 127 |
-
elements.append(Paragraph("<b>Project Timeline:</b>", styles['Heading2']))
|
| 128 |
-
img = Image(gantt_chart_path, width=6 * inch, height=4 * inch)
|
| 129 |
-
elements.append(img)
|
| 130 |
-
|
| 131 |
-
doc.build(elements)
|
| 132 |
-
pdf_file.seek(0)
|
| 133 |
-
return pdf_file
|
| 134 |
-
|
| 135 |
-
# Function to send project data to Salesforce
|
| 136 |
-
def send_to_salesforce(project_title, gantt_chart_url, ai_plan_score, estimated_duration, risk_tags, status="Draft", record_id=None, location="", weather_type=""):
|
| 137 |
-
sf = get_salesforce_connection()
|
| 138 |
-
if not sf:
|
| 139 |
-
logger.error("Salesforce connection failed. Cannot proceed with record creation/update.")
|
| 140 |
-
return None
|
| 141 |
-
|
| 142 |
-
sf_data = {
|
| 143 |
-
"Name": project_title[:80],
|
| 144 |
-
"Project_Title__c": project_title,
|
| 145 |
-
"Estimated_Duration__c": estimated_duration,
|
| 146 |
-
"AI_Plan_Score__c": ai_plan_score,
|
| 147 |
-
"Status__c": status,
|
| 148 |
-
"Location__c": location,
|
| 149 |
-
"Weather_Type__c": weather_type,
|
| 150 |
-
"Risk_Tags__c": risk_tags,
|
| 151 |
-
}
|
| 152 |
-
|
| 153 |
-
if gantt_chart_url:
|
| 154 |
-
sf_data["Gantt_Chart_PDF__c"] = gantt_chart_url
|
| 155 |
-
|
| 156 |
-
if record_id:
|
| 157 |
-
sf.AI_Project_Timeline__c.update(record_id, sf_data)
|
| 158 |
-
return record_id
|
| 159 |
-
else:
|
| 160 |
-
project_record = sf.AI_Project_Timeline__c.create(sf_data)
|
| 161 |
-
return project_record['id']
|
| 162 |
-
|
| 163 |
-
# Gradio interface function
|
| 164 |
-
def gradio_interface(contract_file, weather, location, project_title):
|
| 165 |
try:
|
| 166 |
-
|
| 167 |
-
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
-
#
|
| 174 |
-
|
|
|
|
|
|
|
| 175 |
|
| 176 |
-
|
| 177 |
-
pdf_content_id, pdf_url = upload_file_to_salesforce(pdf_report, project_title)
|
| 178 |
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
except Exception as e:
|
| 181 |
-
|
| 182 |
-
return None, f"Error in Gradio interface: {str(e)}", None, None
|
| 183 |
|
| 184 |
-
# Gradio interface
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
gr.Markdown("
|
| 188 |
-
gr.Markdown("Upload a contract, and the system will generate a heatmap and PDF report highlighting risk-prone clauses.")
|
| 189 |
|
| 190 |
with gr.Row():
|
| 191 |
with gr.Column():
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
location = gr.Textbox(label="Location", placeholder="Enter project location")
|
| 195 |
-
project_title = gr.Textbox(label="Project Title", placeholder="Enter project title")
|
| 196 |
-
submit_btn = gr.Button("Analyze Contract")
|
| 197 |
|
| 198 |
with gr.Column():
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
if __name__ == "__main__":
|
| 206 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import pdfplumber
|
|
|
|
| 3 |
import matplotlib.pyplot as plt
|
| 4 |
+
import numpy as np
|
| 5 |
+
from word2number import w2n
|
| 6 |
+
import re
|
| 7 |
+
from typing import Tuple, List, Dict
|
| 8 |
+
|
| 9 |
+
# Custom CSS for styling
|
| 10 |
+
css = """
|
| 11 |
+
.risk-low { color: #28a745; font-weight: bold; }
|
| 12 |
+
.risk-medium { color: #ffc107; font-weight: bold; }
|
| 13 |
+
.risk-high { color: #dc3545; font-weight: bold; }
|
| 14 |
+
.result-box { padding: 20px; border-radius: 5px; margin-bottom: 20px; }
|
| 15 |
+
.penalty-box { background-color: #f8f9fa; }
|
| 16 |
+
.obligation-box { background-color: #f8f9fa; }
|
| 17 |
+
.delay-box { background-color: #f8f9fa; }
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def extract_text_from_pdf(pdf_path: str) -> str:
|
| 21 |
+
"""Extract text from PDF using pdfplumber"""
|
| 22 |
+
text = ""
|
| 23 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 24 |
+
for page in pdf.pages:
|
| 25 |
+
text += page.extract_text() or ""
|
| 26 |
+
return text
|
| 27 |
+
|
| 28 |
+
def count_keywords(text: str, keywords: List[str]) -> Dict[str, int]:
|
| 29 |
+
"""Count occurrences of keywords in text"""
|
| 30 |
+
counts = {}
|
| 31 |
+
for keyword in keywords:
|
| 32 |
+
counts[keyword] = len(re.findall(r'\b' + re.escape(keyword) + r'\b', text, flags=re.IGNORECASE))
|
| 33 |
+
return counts
|
| 34 |
+
|
| 35 |
+
def find_penalty_values(text: str) -> List[float]:
|
| 36 |
+
"""Find penalty amounts in the text"""
|
| 37 |
+
patterns = [
|
| 38 |
+
r'\$\s*[\d,]+(?:\.\d+)?',
|
| 39 |
+
r'(?:USD|usd)\s*[\d,]+(?:\.\d+)?',
|
| 40 |
+
r'\d+\s*(?:percent|%)',
|
| 41 |
+
r'(?:\b[a-z]+\s*)+dollars',
|
| 42 |
+
]
|
| 43 |
|
| 44 |
+
penalties = []
|
| 45 |
+
for pattern in patterns:
|
| 46 |
+
matches = re.finditer(pattern, text, flags=re.IGNORECASE)
|
| 47 |
+
for match in matches:
|
| 48 |
+
penalty_text = match.group()
|
| 49 |
+
try:
|
| 50 |
+
if any(word in penalty_text.lower() for word in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'hundred', 'thousand', 'million']):
|
| 51 |
+
penalty_value = w2n.word_to_num(penalty_text.split('dollars')[0].strip())
|
| 52 |
+
else:
|
| 53 |
+
penalty_value = float(re.sub(r'[^\d.]', '', penalty_text))
|
| 54 |
+
penalties.append(penalty_value)
|
| 55 |
+
except:
|
| 56 |
+
continue
|
| 57 |
+
return penalties
|
| 58 |
+
|
| 59 |
+
def calculate_risk_score(penalty_count: int, penalty_values: List[float], obligation_count: int, delay_count: int) -> Tuple[float, str]:
|
| 60 |
+
"""Calculate risk score based on various factors"""
|
| 61 |
+
score = 0
|
| 62 |
+
score += min(penalty_count * 5, 30)
|
| 63 |
|
| 64 |
+
if penalty_values:
|
| 65 |
+
avg_penalty = sum(penalty_values) / len(penalty_values)
|
| 66 |
+
if avg_penalty > 1000000:
|
| 67 |
+
score += 40
|
| 68 |
+
elif avg_penalty > 100000:
|
| 69 |
+
score += 25
|
| 70 |
+
elif avg_penalty > 10000:
|
| 71 |
+
score += 15
|
| 72 |
+
else:
|
| 73 |
+
score += 5
|
| 74 |
|
| 75 |
+
score += min(obligation_count * 2, 20)
|
| 76 |
+
score += min(delay_count * 10, 30)
|
| 77 |
+
score = min(score, 100)
|
| 78 |
|
| 79 |
+
if score < 30:
|
| 80 |
+
return score, "Low"
|
| 81 |
+
elif score < 70:
|
| 82 |
+
return score, "Medium"
|
| 83 |
+
else:
|
| 84 |
+
return score, "High"
|
| 85 |
|
| 86 |
+
def generate_heatmap(risk_level: str):
|
| 87 |
+
"""Generate a simple heatmap based on risk level"""
|
| 88 |
+
fig, ax = plt.subplots(figsize=(8, 2))
|
| 89 |
+
|
| 90 |
+
if risk_level == "Low":
|
| 91 |
+
cmap = plt.cm.Greens
|
| 92 |
+
elif risk_level == "Medium":
|
| 93 |
+
cmap = plt.cm.Oranges
|
| 94 |
+
else:
|
| 95 |
+
cmap = plt.cm.Reds
|
| 96 |
|
| 97 |
+
gradient = np.linspace(0, 1, 256).reshape(1, -1)
|
| 98 |
+
gradient = np.vstack((gradient, gradient))
|
|
|
|
| 99 |
|
| 100 |
+
ax.imshow(gradient, aspect='auto', cmap=cmap)
|
| 101 |
+
ax.text(128, 0.5, f"{risk_level} Risk", color='white' if risk_level == "High" else 'black',
|
| 102 |
+
ha='center', va='center', fontsize=24, fontweight='bold')
|
|
|
|
| 103 |
|
| 104 |
+
ax.set_axis_off()
|
| 105 |
plt.tight_layout()
|
| 106 |
return fig
|
| 107 |
|
| 108 |
+
def analyze_pdf(file_obj) -> List:
|
| 109 |
+
"""Main analysis function for Gradio interface"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
try:
|
| 111 |
+
# Extract text from the uploaded file
|
| 112 |
+
text = extract_text_from_pdf(file_obj.name)
|
| 113 |
|
| 114 |
+
# Define keywords to search for
|
| 115 |
+
penalty_keywords = ["penalty", "fine", "forfeit", "liquidated damages", "breach"]
|
| 116 |
+
obligation_keywords = ["shall", "must", "required to", "obligated to", "duty"]
|
| 117 |
+
delay_keywords = ["delay", "late", "overdue", "extension", "time is of the essence"]
|
| 118 |
+
|
| 119 |
+
# Count keyword occurrences
|
| 120 |
+
penalty_counts = count_keywords(text, penalty_keywords)
|
| 121 |
+
obligation_counts = count_keywords(text, obligation_keywords)
|
| 122 |
+
delay_counts = count_keywords(text, delay_keywords)
|
| 123 |
+
|
| 124 |
+
# Find penalty values
|
| 125 |
+
penalty_values = find_penalty_values(text)
|
| 126 |
+
|
| 127 |
+
# Calculate total counts
|
| 128 |
+
total_penalties = sum(penalty_counts.values())
|
| 129 |
+
total_obligations = sum(obligation_counts.values())
|
| 130 |
+
total_delays = sum(delay_counts.values())
|
| 131 |
+
|
| 132 |
+
# Calculate risk score
|
| 133 |
+
risk_score, risk_level = calculate_risk_score(
|
| 134 |
+
total_penalties, penalty_values, total_obligations, total_delays
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Generate heatmap
|
| 138 |
+
heatmap = generate_heatmap(risk_level)
|
| 139 |
|
| 140 |
+
# Prepare results
|
| 141 |
+
penalty_details = "\n".join([f"- {kw}: {count}" for kw, count in penalty_counts.items()])
|
| 142 |
+
obligation_details = "\n".join([f"- {kw}: {count}" for kw, count in obligation_counts.items()])
|
| 143 |
+
delay_details = "\n".join([f"- {kw}: {count}" for kw, count in delay_counts.items()])
|
| 144 |
|
| 145 |
+
penalty_amounts = "\n".join([f"- ${amt:,.2f}" for amt in penalty_values[:5]]) if penalty_values else "No specific penalty amounts found"
|
|
|
|
| 146 |
|
| 147 |
+
# Find example sentences with penalties
|
| 148 |
+
penalty_sentences = []
|
| 149 |
+
for sentence in re.split(r'(?<=[.!?])\s+', text):
|
| 150 |
+
if any(kw.lower() in sentence.lower() for kw in penalty_keywords):
|
| 151 |
+
penalty_sentences.append(sentence.strip())
|
| 152 |
+
|
| 153 |
+
penalty_examples = "\n\n".join([f"{i+1}. {sent}" for i, sent in enumerate(penalty_sentences[:3])]) if penalty_sentences else "No penalty clauses found"
|
| 154 |
+
|
| 155 |
+
# Return all results
|
| 156 |
+
return [
|
| 157 |
+
f"<div class='risk-{risk_level.lower()}'>{risk_score:.1f}/100</div>",
|
| 158 |
+
f"<div class='risk-{risk_level.lower()}'>{risk_level}</div>",
|
| 159 |
+
heatmap,
|
| 160 |
+
f"Total: {total_penalties}\n\n{penalty_details}",
|
| 161 |
+
f"{len(penalty_values)} amounts found\n\n{penalty_amounts}",
|
| 162 |
+
f"Total: {total_obligations}\n\n{obligation_details}",
|
| 163 |
+
f"Total: {total_delays}\n\n{delay_details}",
|
| 164 |
+
penalty_examples
|
| 165 |
+
]
|
| 166 |
except Exception as e:
|
| 167 |
+
return [f"Error: {str(e)}"] * 8
|
|
|
|
| 168 |
|
| 169 |
+
# Create Gradio interface
|
| 170 |
+
with gr.Blocks(css=css, title="PDF Contract Risk Analyzer") as demo:
|
| 171 |
+
gr.Markdown("# 📄 PDF Contract Risk Analyzer")
|
| 172 |
+
gr.Markdown("Upload a contract PDF to analyze penalties, obligations, and delays.")
|
|
|
|
| 173 |
|
| 174 |
with gr.Row():
|
| 175 |
with gr.Column():
|
| 176 |
+
file_input = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 177 |
+
submit_btn = gr.Button("Analyze PDF", variant="primary")
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
with gr.Column():
|
| 180 |
+
gr.Markdown("### 🔍 Overall Risk Assessment")
|
| 181 |
+
risk_score = gr.HTML(label="Risk Score")
|
| 182 |
+
risk_level = gr.HTML(label="Risk Level")
|
| 183 |
+
heatmap = gr.Plot(label="Risk Heatmap")
|
| 184 |
+
|
| 185 |
+
with gr.Row():
|
| 186 |
+
with gr.Column():
|
| 187 |
+
gr.Markdown("### 📊 Penalties Analysis")
|
| 188 |
+
penalty_count = gr.Textbox(label="Penalty Clauses", lines=5)
|
| 189 |
+
penalty_amounts = gr.Textbox(label="Penalty Amounts", lines=5)
|
| 190 |
+
|
| 191 |
+
with gr.Column():
|
| 192 |
+
gr.Markdown("### ⚖️ Obligations Analysis")
|
| 193 |
+
obligation_count = gr.Textbox(label="Obligation Clauses", lines=5)
|
| 194 |
+
|
| 195 |
+
with gr.Column():
|
| 196 |
+
gr.Markdown("### ⏱️ Delays Analysis")
|
| 197 |
+
delay_count = gr.Textbox(label="Delay Clauses", lines=5)
|
| 198 |
+
|
| 199 |
+
with gr.Row():
|
| 200 |
+
gr.Markdown("### 🔎 Extracted Penalty Clauses")
|
| 201 |
+
penalty_examples = gr.Textbox(label="Example Penalty Clauses", lines=5)
|
| 202 |
+
|
| 203 |
+
submit_btn.click(
|
| 204 |
+
fn=analyze_pdf,
|
| 205 |
+
inputs=file_input,
|
| 206 |
+
outputs=[risk_score, risk_level, heatmap, penalty_count, penalty_amounts,
|
| 207 |
+
obligation_count, delay_count, penalty_examples]
|
| 208 |
+
)
|
| 209 |
|
| 210 |
if __name__ == "__main__":
|
| 211 |
+
demo.launch()
|