Kushalmanda commited on
Commit
940bfec
·
verified ·
1 Parent(s): 7062e47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -39
app.py CHANGED
@@ -2,11 +2,9 @@ import gradio as gr
2
  import pdfplumber
3
  import matplotlib.pyplot as plt
4
  import numpy as np
5
- import re
6
  from word2number import w2n
7
- from simple_salesforce import Salesforce
8
  from typing import Tuple, List, Dict
9
- import os
10
 
11
  # Custom CSS for styling
12
  css = """
@@ -112,11 +110,6 @@ css = """
112
  }
113
  """
114
 
115
- # Salesforce Authentication (Make sure your credentials are stored securely)
116
- sf = Salesforce(username='Kushalpavansekharm503@agentforce.com',
117
- password='Kushal@123',
118
- security_token='WwUIFWBVUjeKn9VPKyWJmawY0')
119
-
120
  def extract_text_from_pdf(pdf_path: str) -> str:
121
  """Extract text from PDF using pdfplumber"""
122
  text = ""
@@ -183,22 +176,90 @@ def calculate_risk_score(penalty_count: int, penalty_values: List[float], obliga
183
  else:
184
  return score, "High"
185
 
186
- def save_to_salesforce(risk_score: float, risk_level: str, penalty_examples: str, penalty_details: str, penalty_amounts: str, obligation_details: str, delay_details: str) -> str:
187
- """Save the results into Salesforce"""
188
- try:
189
- custom_risk = sf.Custom_Risk_Analysis__c.create({
190
- 'Sentiment_Score__c': risk_score,
191
- 'Risk_Score__c': risk_score,
192
- 'Risk_Level__c': risk_level,
193
- 'Penalty_Examples__c': penalty_examples,
194
- 'Penalty_Details__c': penalty_details,
195
- 'Penalty_Amounts__c': penalty_amounts,
196
- 'Obligation_Details__c': obligation_details,
197
- 'Delay_Details__c': delay_details
198
- })
199
- return f"Successfully saved to Salesforce with Record ID: {custom_risk['id']}"
200
- except Exception as e:
201
- return f"Error saving to Salesforce: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
  def analyze_pdf(file_obj) -> List:
204
  """Main analysis function for Gradio interface"""
@@ -229,32 +290,85 @@ def analyze_pdf(file_obj) -> List:
229
  total_penalties, penalty_values, total_obligations, total_delays
230
  )
231
 
232
- # Save to Salesforce
233
- save_message = save_to_salesforce(
234
- risk_score, risk_level, str(penalty_counts), str(penalty_values), str(penalty_values),
235
- str(obligation_counts), str(delay_counts)
236
- )
237
 
238
- # Return results
239
- return [f"Analysis complete! {save_message}"]
240
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  except Exception as e:
242
  return [f"Error: {str(e)}"] * 6
243
 
244
- # Create Gradio interface (updated with correct output component)
245
  with gr.Blocks(css=css, title="PDF Contract Risk Analyzer") as demo:
246
  gr.Markdown("# 📄 PDF Contract Risk Analyzer")
247
  gr.Markdown("Upload a contract PDF to analyze penalties, obligations, and delays.")
248
 
249
  with gr.Row():
250
- file_input = gr.File(label="Upload PDF", file_types=[".pdf"])
251
- submit_btn = gr.Button("Analyze PDF", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
  with gr.Row():
254
- # Update the output to use gr.HTML (or gr.Textbox depending on your needs)
255
- result_output = gr.HTML(label="Analysis Result")
256
 
257
- submit_btn.click(fn=analyze_pdf, inputs=file_input, outputs=result_output)
 
 
 
 
 
258
 
259
  if __name__ == "__main__":
260
- demo.launch()
 
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 = """
 
110
  }
111
  """
112
 
 
 
 
 
 
113
  def extract_text_from_pdf(pdf_path: str) -> str:
114
  """Extract text from PDF using pdfplumber"""
115
  text = ""
 
176
  else:
177
  return score, "High"
178
 
179
+ def generate_combined_risk_display(risk_score: float, risk_level: str) -> Tuple[str, plt.Figure]:
180
+ """Generate a combined display with all three risk levels in one layout"""
181
+ fig, ax = plt.subplots(figsize=(10, 3))
182
+ ax.axis('off')
183
+
184
+ risk_levels = ["Low", "Medium", "High"]
185
+ colors = ['#28a745', '#ffc107', '#dc3545']
186
+
187
+ # Create HTML for the text display
188
+ html_parts = []
189
+ html_parts.append("<div class='combined-risk-container'>")
190
+
191
+ for i, level in enumerate(risk_levels):
192
+ active = level == risk_level
193
+ score = risk_score if active else 0
194
+
195
+ # Add to HTML
196
+ html_parts.append(f"""
197
+ <div class='risk-row'>
198
+ <div class='risk-label risk-{level.lower()}'>{level} Risk</div>
199
+ <div class='risk-score risk-{level.lower()}'>{score:.1f}%</div>
200
+ <div class='heatmap-wrapper'>
201
+ <img src='data:image/png;base64,{create_mini_heatmap(score, colors[i])}' style='width:100%'>
202
+ </div>
203
+ </div>
204
+ """)
205
+
206
+ html_parts.append("</div>")
207
+
208
+ return "\n".join(html_parts), fig
209
+
210
+ def create_mini_heatmap(score: float, color: str) -> str:
211
+ """Create a small heatmap for one risk level"""
212
+ fig, ax = plt.subplots(figsize=(8, 0.5))
213
+
214
+ if score > 0:
215
+ gradient = np.linspace(0, score/100, 256).reshape(1, -1)
216
+ else:
217
+ gradient = np.zeros((1, 256))
218
+
219
+ gradient = np.vstack((gradient, gradient))
220
+
221
+ ax.imshow(gradient, aspect='auto', cmap=plt.cm.colors.LinearSegmentedColormap.from_list('custom', ['white', color]))
222
+ ax.set_axis_off()
223
+ plt.tight_layout()
224
+
225
+ # Save to base64 string
226
+ from io import BytesIO
227
+ buf = BytesIO()
228
+ plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
229
+ plt.close(fig)
230
+ import base64
231
+ return base64.b64encode(buf.getvalue()).decode('utf-8')
232
+
233
+ def format_warning_message(count: int, items: str, item_type: str) -> str:
234
+ """Format warning message based on count"""
235
+ if count == 0:
236
+ return f"""<div class="success-box">✓ No {item_type} clauses detected - Good!</div>"""
237
+ elif count < 5:
238
+ return f"""<div class="warning-box">⚠️ {count} {item_type} clauses detected</div>"""
239
+ else:
240
+ return f"""<div class="danger-box">⚠️⚠️ {count} {item_type} clauses detected - High Risk!</div>"""
241
+
242
+ def create_vertical_count_display(counts: Dict[str, int], total: int, section_type: str) -> str:
243
+ """Create a vertical display for counts with section styling"""
244
+ items_html = []
245
+ for kw, count in counts.items():
246
+ items_html.append(f"""
247
+ <div class="count-item">
248
+ <span class="count-label">{kw.title()}:</span>
249
+ <span class="count-value">{count}</span>
250
+ </div>
251
+ """)
252
+
253
+ return f"""
254
+ <div class="section-container {section_type}-box">
255
+ <div class="section-title">{section_type.title()} Analysis</div>
256
+ <div style="margin-bottom: 10px;">
257
+ <span style="font-weight: bold;">Total:</span>
258
+ <span style="margin-left: 10px;">{total}</span>
259
+ </div>
260
+ {"".join(items_html)}
261
+ </div>
262
+ """
263
 
264
  def analyze_pdf(file_obj) -> List:
265
  """Main analysis function for Gradio interface"""
 
290
  total_penalties, penalty_values, total_obligations, total_delays
291
  )
292
 
293
+ # Generate combined risk display
294
+ risk_display, _ = generate_combined_risk_display(risk_score, risk_level)
 
 
 
295
 
296
+ # Prepare warning/success messages
297
+ penalty_warning = format_warning_message(total_penalties, "penalty", "penalty")
298
+ obligation_warning = format_warning_message(total_obligations, "obligation", "obligation")
299
+ delay_warning = format_warning_message(total_delays, "delay", "delay")
300
+
301
+ # Create vertical displays
302
+ penalty_display = create_vertical_count_display(penalty_counts, total_penalties, "penalty")
303
+ obligation_display = create_vertical_count_display(obligation_counts, total_obligations, "obligation")
304
+ delay_display = create_vertical_count_display(delay_counts, total_delays, "delay")
305
+
306
+ # Combine warnings with displays
307
+ penalty_output = f"{penalty_warning}\n{penalty_display}"
308
+ obligation_output = f"{obligation_warning}\n{obligation_display}"
309
+ delay_output = f"{delay_warning}\n{delay_display}"
310
+
311
+ penalty_amounts = "\n".join([f"- ${amt:,.2f}" for amt in penalty_values[:5]]) if penalty_values else "No specific penalty amounts found"
312
+
313
+ # Find example sentences with penalties
314
+ penalty_sentences = []
315
+ for sentence in re.split(r'(?<=[.!?])\s+', text):
316
+ if any(kw.lower() in sentence.lower() for kw in penalty_keywords):
317
+ penalty_sentences.append(sentence.strip())
318
+
319
+ 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"
320
+
321
+ # Return all results
322
+ return [
323
+ risk_display,
324
+ penalty_output,
325
+ f"{len(penalty_values)} amounts found\n\n{penalty_amounts}",
326
+ obligation_output,
327
+ delay_output,
328
+ penalty_examples
329
+ ]
330
  except Exception as e:
331
  return [f"Error: {str(e)}"] * 6
332
 
333
+ # Create Gradio interface
334
  with gr.Blocks(css=css, title="PDF Contract Risk Analyzer") as demo:
335
  gr.Markdown("# 📄 PDF Contract Risk Analyzer")
336
  gr.Markdown("Upload a contract PDF to analyze penalties, obligations, and delays.")
337
 
338
  with gr.Row():
339
+ with gr.Column():
340
+ file_input = gr.File(label="Upload PDF", file_types=[".pdf"])
341
+ submit_btn = gr.Button("Analyze PDF", variant="primary")
342
+
343
+ with gr.Column():
344
+ gr.Markdown("### 🔍 Overall Risk Assessment")
345
+ risk_display = gr.HTML(label="Risk Analysis")
346
+
347
+ with gr.Row():
348
+ with gr.Column():
349
+ gr.Markdown("### 📊 Penalties Analysis")
350
+ penalty_count = gr.HTML(label="Penalty Clauses")
351
+ gr.Markdown("### Penalty Amounts")
352
+ penalty_amounts = gr.Textbox(label="", lines=5)
353
+
354
+ with gr.Column():
355
+ gr.Markdown("### ⚖️ Obligations Analysis")
356
+ obligation_count = gr.HTML(label="Obligation Clauses")
357
+
358
+ with gr.Column():
359
+ gr.Markdown("### ⏱️ Delays Analysis")
360
+ delay_count = gr.HTML(label="Delay Clauses")
361
 
362
  with gr.Row():
363
+ gr.Markdown("### 🔎 Extracted Penalty Clauses")
364
+ penalty_examples = gr.Textbox(label="Example Penalty Clauses", lines=5)
365
 
366
+ submit_btn.click(
367
+ fn=analyze_pdf,
368
+ inputs=file_input,
369
+ outputs=[risk_display, penalty_count, penalty_amounts,
370
+ obligation_count, delay_count, penalty_examples]
371
+ )
372
 
373
  if __name__ == "__main__":
374
+ demo.launch()