Komal133 commited on
Commit
ea76d38
·
verified ·
1 Parent(s): 40b3240

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -63
app.py CHANGED
@@ -1,35 +1,65 @@
1
- import streamlit as st
2
- import requests
3
- import json
 
4
  from transformers import pipeline
5
  import PyPDF2
6
  import docx
7
  import matplotlib.pyplot as plt
 
 
 
 
8
  from simple_salesforce import Salesforce
9
 
10
  # Initialize the BERT-based NLP pipeline
11
  model_name = "dbmdz/bert-large-cased-finetuned-conll03-english" # Example, replace with your model
12
  nlp_pipeline = pipeline("ner", model=model_name)
13
 
14
- # Salesforce Integration (optional - uncomment if needed)
15
- # sf = Salesforce(username='your_username', password='your_password', security_token='your_token')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  # Function to analyze contract text
18
  def analyze_contract(contract_text):
19
  try:
20
  # Run the contract through the NLP pipeline
21
  results = nlp_pipeline(contract_text)
22
-
23
  # Parse and score clauses (this is a simplified version)
24
  risk_score = 0
25
  high_risk_clauses = []
26
-
27
  for result in results:
28
  # This assumes 'labels' are risk-related; adjust as per model output
29
  if result['label'] in ["PENALTY", "OBLIGATION", "DELAY"]: # Customize as per your model's tags
30
  high_risk_clauses.append(result['word'])
31
  risk_score += 10 # Example scoring logic, modify as needed
32
-
33
  return {
34
  "high_risk_clauses": high_risk_clauses,
35
  "risk_score": risk_score
@@ -37,72 +67,84 @@ def analyze_contract(contract_text):
37
  except Exception as e:
38
  return {"error": str(e)}
39
 
40
- # Streamlit UI
41
- st.title("Contract Risk Analyzer")
42
 
43
- # File upload
44
- contract_file = st.file_uploader("Upload Contract", type=["pdf", "docx", "txt"])
45
-
46
- if contract_file is not None:
47
  contract_text = ""
48
- if contract_file.type == "application/pdf":
49
- # Read PDF
50
  try:
51
- pdf_reader = PyPDF2.PdfReader(contract_file)
52
  for page in pdf_reader.pages:
53
  contract_text += page.extract_text()
54
  except Exception as e:
55
- st.error(f"Error reading PDF: {str(e)}")
56
-
57
- elif contract_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
58
- # Read DOCX
59
  try:
60
- doc = docx.Document(contract_file)
61
  for para in doc.paragraphs:
62
  contract_text += para.text
63
  except Exception as e:
64
- st.error(f"Error reading DOCX: {str(e)}")
65
-
66
- elif contract_file.type == "text/plain":
67
- # Read TXT
68
- contract_text = contract_file.read().decode("utf-8")
69
-
70
- # Analyze the contract text
71
- if contract_text:
72
- analysis_results = analyze_contract(contract_text)
73
-
74
- if "error" in analysis_results:
75
- st.error(f"An error occurred during analysis: {analysis_results['error']}")
76
- else:
77
- # Display the high-risk clauses and risk score
78
- st.subheader("High Risk Clauses")
79
- st.write(", ".join(analysis_results["high_risk_clauses"]))
80
-
81
- st.subheader("Overall Risk Score")
82
- st.write(analysis_results["risk_score"])
83
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  # Generate the risk heatmap (simplified here)
85
- st.subheader("Risk Heatmap")
86
-
87
- # Create a simple bar chart to visualize the risk score
88
  fig, ax = plt.subplots()
89
- ax.barh(['Contract'], [analysis_results["risk_score"]], color='red')
90
  ax.set_xlim(0, 100) # Assuming risk score ranges from 0 to 100
91
  ax.set_xlabel("Risk Score")
92
- st.pyplot(fig)
93
-
94
- # Optionally save the results to Salesforce
95
- # Uncomment the following block if you want to integrate with Salesforce
96
- """
97
- try:
98
- contract_risk_scan = sf.Contract_Risk_Scan__c.create({
99
- 'Contract_Title__c': 'Sample Contract',
100
- 'Overall_Risk_Score__c': analysis_results['risk_score'],
101
- 'High_Risk_Clauses__c': ', '.join(analysis_results['high_risk_clauses']),
102
- 'Risk_Map_URL__c': 'generated_map_url', # You can generate a URL for the heatmap if required
103
- 'Evaluation_Date__c': '2025-06-05' # You can adjust this to current date
104
- })
105
- st.success("Contract analysis results saved to Salesforce.")
106
- except Exception as e:
107
- st.error(f"Failed to save to Salesforce: {str(e)}")
108
- """
 
 
 
 
 
 
1
+ import dash
2
+ from dash import dcc, html
3
+ import dash_bootstrap_components as dbc
4
+ import gradio as gr
5
  from transformers import pipeline
6
  import PyPDF2
7
  import docx
8
  import matplotlib.pyplot as plt
9
+ import numpy as np
10
+ import pandas as pd
11
+ import requests
12
+ import json
13
  from simple_salesforce import Salesforce
14
 
15
  # Initialize the BERT-based NLP pipeline
16
  model_name = "dbmdz/bert-large-cased-finetuned-conll03-english" # Example, replace with your model
17
  nlp_pipeline = pipeline("ner", model=model_name)
18
 
19
+ # Initialize Dash App
20
+ app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
21
+
22
+ # Define app layout
23
+ app.layout = html.Div([
24
+ dbc.Row([
25
+ dbc.Col(html.H1("Contract Risk Analyzer", style={'textAlign': 'center'})),
26
+ ]),
27
+ dbc.Row([
28
+ dbc.Col(html.Div([
29
+ html.Label("Upload Contract"),
30
+ dcc.Upload(
31
+ id='upload-data',
32
+ children=html.Button('Upload File'),
33
+ multiple=False
34
+ ),
35
+ html.Div(id='file-upload-status'),
36
+ ]), width=12),
37
+ ]),
38
+ dbc.Row([
39
+ dbc.Col(html.Div(id='output-text'), width=12),
40
+ ]),
41
+ dbc.Row([
42
+ dbc.Col(dcc.Graph(id='risk-heatmap'), width=12),
43
+ ]),
44
+ ])
45
+
46
 
47
  # Function to analyze contract text
48
  def analyze_contract(contract_text):
49
  try:
50
  # Run the contract through the NLP pipeline
51
  results = nlp_pipeline(contract_text)
52
+
53
  # Parse and score clauses (this is a simplified version)
54
  risk_score = 0
55
  high_risk_clauses = []
56
+
57
  for result in results:
58
  # This assumes 'labels' are risk-related; adjust as per model output
59
  if result['label'] in ["PENALTY", "OBLIGATION", "DELAY"]: # Customize as per your model's tags
60
  high_risk_clauses.append(result['word'])
61
  risk_score += 10 # Example scoring logic, modify as needed
62
+
63
  return {
64
  "high_risk_clauses": high_risk_clauses,
65
  "risk_score": risk_score
 
67
  except Exception as e:
68
  return {"error": str(e)}
69
 
 
 
70
 
71
+ # Function to parse uploaded contract
72
+ def parse_contract(file_content, file_type):
 
 
73
  contract_text = ""
74
+ if file_type == "application/pdf":
 
75
  try:
76
+ pdf_reader = PyPDF2.PdfReader(file_content)
77
  for page in pdf_reader.pages:
78
  contract_text += page.extract_text()
79
  except Exception as e:
80
+ return f"Error reading PDF: {str(e)}"
81
+
82
+ elif file_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
 
83
  try:
84
+ doc = docx.Document(file_content)
85
  for para in doc.paragraphs:
86
  contract_text += para.text
87
  except Exception as e:
88
+ return f"Error reading DOCX: {str(e)}"
89
+
90
+ elif file_type == "text/plain":
91
+ contract_text = file_content.decode("utf-8")
92
+
93
+ return contract_text
94
+
95
+
96
+ # Callback to handle file upload
97
+ @app.callback(
98
+ [dash.dependencies.Output('file-upload-status', 'children'),
99
+ dash.dependencies.Output('output-text', 'children'),
100
+ dash.dependencies.Output('risk-heatmap', 'figure')],
101
+ [dash.dependencies.Input('upload-data', 'contents'),
102
+ dash.dependencies.State('upload-data', 'filename'),
103
+ dash.dependencies.State('upload-data', 'type')]
104
+ )
105
+ def update_output(file_contents, filename, file_type):
106
+ if file_contents is not None:
107
+ # Parse the contract
108
+ contract_text = parse_contract(file_contents, file_type)
109
+
110
+ if contract_text:
111
+ # Analyze the contract
112
+ analysis_results = analyze_contract(contract_text)
113
+
114
+ if "error" in analysis_results:
115
+ return "Error", f"An error occurred during analysis: {analysis_results['error']}", {}
116
+
117
+ # Display high-risk clauses and overall risk score
118
+ high_risk_clauses = analysis_results["high_risk_clauses"]
119
+ risk_score = analysis_results["risk_score"]
120
+
121
+ high_risk_text = f"High Risk Clauses: {', '.join(high_risk_clauses)}"
122
+ risk_score_text = f"Overall Risk Score: {risk_score}"
123
+
124
  # Generate the risk heatmap (simplified here)
 
 
 
125
  fig, ax = plt.subplots()
126
+ ax.barh(['Contract'], [risk_score], color='red')
127
  ax.set_xlim(0, 100) # Assuming risk score ranges from 0 to 100
128
  ax.set_xlabel("Risk Score")
129
+
130
+ # Returning results for display
131
+ return "File Uploaded Successfully", [high_risk_text, risk_score_text], {
132
+ 'data': [{
133
+ 'x': ['Contract'],
134
+ 'y': [risk_score],
135
+ 'type': 'bar',
136
+ 'name': 'Risk Score',
137
+ 'marker': {'color': 'red'}
138
+ }],
139
+ 'layout': {
140
+ 'title': 'Risk Heatmap',
141
+ 'xaxis': {'title': 'Risk Score'},
142
+ 'yaxis': {'title': 'Contract'}
143
+ }
144
+ }
145
+
146
+ return "No File Uploaded", "", {}
147
+
148
+
149
+ if __name__ == '__main__':
150
+ app.run_server(debug=True)