karthikeyan-r commited on
Commit
a48b255
1 Parent(s): 450bd79

Create findUpdate.py

Browse files
Files changed (1) hide show
  1. findUpdate.py +754 -0
findUpdate.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ import json
4
+ import time
5
+ import fitz
6
+ import difflib
7
+ import secrets
8
+ import openai
9
+ import string
10
+ import logging
11
+ import requests
12
+ import streamlit as st
13
+ from pandas import DataFrame
14
+ from openai import AzureOpenAI
15
+ from difflib import SequenceMatcher
16
+ from tempfile import NamedTemporaryFile
17
+ from typing import Tuple, Dict, List, Union
18
+ from diff_match_patch import diff_match_patch
19
+ import base64
20
+ import pandas as pd
21
+
22
+ class FindUpdate:
23
+ @staticmethod
24
+ def clean_string(text: str, stem: str = "None") -> str:
25
+ """Clean the input text by removing punctuation, numbers, and optionally stemming or lemmatizing the words.
26
+
27
+ Args:
28
+ text (str): The input text to be cleaned.
29
+ stem (str, optional): The stemming method to be used. Options are "None" (default), "Stem", "Lem", or "Spacy".
30
+
31
+ Returns:
32
+ str: The cleaned text.
33
+
34
+ Raises:
35
+ None
36
+ """
37
+ try:
38
+ final_string = ""
39
+ # Replace any characters with nothing or a space
40
+ text = re.sub(r'\n', ' ', text)
41
+ text = re.sub(r' +', ' ', text)
42
+ text = re.sub(r'[^\x00-\x7f]',r'', text)
43
+ # Remove punctuation
44
+ translator = str.maketrans('', '', string.punctuation)
45
+ text = text.translate(translator)
46
+ # Remove numbers
47
+ text_filtered = [re.sub(r'\w*\d\w*\s+', '', w) for w in text]
48
+ text_filtered = [re.sub('[0-9]', '', w) for w in text_filtered]
49
+ # Stem or Lemmatize
50
+ if stem == 'Stem':
51
+ stemmer = PorterStemmer()
52
+ text_stemmed = [stemmer.stem(y) for y in text_filtered]
53
+ elif stem == 'Lem':
54
+ lem = WordNetLemmatizer()
55
+ text_stemmed = [lem.lemmatize(y) for y in text_filtered]
56
+ elif stem == 'Spacy':
57
+ text_filtered = nlp(' '.join(text_filtered))
58
+ text_stemmed = [y.lemma_ for y in text_filtered]
59
+ else:
60
+ text_stemmed = text_filtered
61
+
62
+ final_string = ''.join(text_stemmed)
63
+ except Exception as e:
64
+ # Handle the exception here
65
+ logging.error(f"An error occurred in clean_string: {e}")
66
+ return None
67
+
68
+ return final_string
69
+ @staticmethod
70
+ def extract_text_without_header_footer(page: fitz.Page, page_height: float, header_height: float, footer_height: float) -> str:
71
+ """
72
+ Extract the text from a page of a PDF document, excluding the header and footer.
73
+
74
+ Args:
75
+ page (fitz.Page): The page object from the PyMuPDF library.
76
+ page_height (float): The height of the page.
77
+ header_height (float): The height of the header to be excluded.
78
+ footer_height (float): The height of the footer to be excluded.
79
+
80
+ Returns:
81
+ str: The extracted text.
82
+
83
+ Raises:
84
+ None
85
+ """
86
+ try:
87
+ exclude_top = header_height
88
+ exclude_bottom = page_height - footer_height
89
+ text = ""
90
+ for text_block in page.get_text_blocks():
91
+ bbox = fitz.Rect(text_block[:4]) # Get bounding box of text block
92
+ if bbox.y0 >= exclude_top and bbox.y1 <= exclude_bottom:
93
+ text += text_block[4] + "\n" # Add text content to result
94
+ return text
95
+ except Exception as e:
96
+ # Handle the exception here
97
+ logging.error(f"An error occurred in extract_text_without_header_footer: {e}")
98
+ return ""
99
+ @staticmethod
100
+ def rect_to_dict(rect: fitz.Rect) -> Dict[str, float]:
101
+ """
102
+ Convert a PyMuPDF Rect object to a dictionary.
103
+
104
+ Args:
105
+ rect (fitz.Rect): The Rect object from the PyMuPDF library.
106
+
107
+ Returns:
108
+ Dict[str, float]: The dictionary representation of the Rect object.
109
+
110
+ Raises:
111
+ None
112
+ """
113
+ return {
114
+ "x1": rect[0],
115
+ "y1": rect[1],
116
+ "x2": rect[2],
117
+ "y2": rect[3]
118
+ }
119
+ @staticmethod
120
+ def extract_sections(pdf_path: str, header_height: float, footer_height: float) -> Dict[str, Dict[str, List[str]]]:
121
+ """
122
+ Extract sections from a PDF document, excluding the header and footer.
123
+
124
+ Args:
125
+ pdf_path (str): The path to the PDF document.
126
+ header_height (float): The height of the header to be excluded.
127
+ footer_height (float): The height of the footer to be excluded.
128
+
129
+ Returns:
130
+ Dict[str, Dict[str, List[str]]]: A dictionary containing the extracted sections.
131
+
132
+ Raises:
133
+ None
134
+ """
135
+ try:
136
+ doc = fitz.open(pdf_path)
137
+ sections = {}
138
+ current_section = None
139
+ for page_num in range(2, len(doc)):
140
+ page = doc.load_page(page_num)
141
+ page_height = page.rect.height
142
+ text = FindUpdate.extract_text_without_header_footer(page, page_height, header_height, footer_height)
143
+ lines = text.split('\n')
144
+ print("start")
145
+ for line in lines:
146
+ match = re.match(r'^(?:\d+\.\d*(?:\.\d+)*)|AT&T ALLIANCE PROGRAM AGREEMENT', line.strip())
147
+ if match:
148
+ print("line:",line)
149
+ section_num = match.group()
150
+ if section_num != current_section:
151
+ current_section = section_num
152
+ sections[current_section] = {'page_num': str(page_num + 1), 'coords': [], 'content': []}
153
+
154
+ if current_section:
155
+ sections[current_section]['content'].append(line)
156
+ bbox = page.search_for(line)
157
+ if bbox:
158
+ for cord in bbox:
159
+ sections[current_section]['coords'].append(FindUpdate.rect_to_dict(cord))
160
+ print("section-keys:",sections.keys())
161
+ for key in sections.keys():
162
+ if 'content' in sections[key]:
163
+ sections[key]['content'] = (' '.join(sections[key]['content']))[len(key):].lstrip()
164
+ print("Content:",sections)
165
+ return sections
166
+ except Exception as e:
167
+ # Handle the exception here
168
+ logging.error(f"An error occurred in extract_sections: {e}")
169
+ return {}
170
+ @staticmethod
171
+ def check_identify_changes(template_text: str, contract_text: str) -> str:
172
+ """
173
+ Compare the template text with the contract text and identify the changes made.
174
+
175
+ Args:
176
+ template_text (str): The template text.
177
+ contract_text (str): The contract text.
178
+
179
+ Returns:
180
+ str: A sentence prompt describing the changes made.
181
+
182
+ Raises:
183
+ None
184
+ """
185
+ try:
186
+ dmp = diff_match_patch()
187
+ diff = dmp.diff_main(template_text, contract_text)
188
+ dmp.diff_cleanupSemantic(diff)
189
+
190
+ if all([True if each[0] == 0 or each[1] == ' ' else False for each in diff]):
191
+ return('no_change')
192
+ else:
193
+ deleted = []
194
+ added = []
195
+ for each in diff:
196
+ if each[0] == -1:
197
+ deleted.append(each[1])
198
+ elif each[0] == 1:
199
+ added.append(each[1])
200
+ sentence_prompt = f"""
201
+ template text = {template_text}
202
+ contract_text = {contract_text}
203
+ deleted from template --- {deleted}
204
+ added to the actual contract -- {added}
205
+ """
206
+ return(sentence_prompt)
207
+ except Exception as e:
208
+ # Handle the exception here
209
+ logging.error(f"An error occurred in check_identify_changes: {e}")
210
+ return ""
211
+ @staticmethod
212
+ def open_ai(prompt: str) -> str:
213
+ """
214
+ Generate AI response using OpenAI GPT-4 model.
215
+
216
+ Args:
217
+ prompt (str): The prompt for the AI model.
218
+
219
+ Returns:
220
+ str: The generated AI response.
221
+
222
+ Raises:
223
+ None
224
+ """
225
+ stat = 0
226
+ while stat == 0:
227
+ try:
228
+ client = AzureOpenAI(api_key="5c68e66b7eb3470987c9088b6602c6c7",
229
+ api_version="2023-07-01-preview",
230
+ azure_endpoint="https://azureadople.openai.azure.com/")
231
+ conversation = []
232
+ conversation.append({"role": "user", "content": prompt})
233
+ response = client.chat.completions.create(
234
+ model="GPT-3",
235
+ messages=conversation,
236
+ temperature=0,
237
+ max_tokens=3000,
238
+ stop=None
239
+ )
240
+ stat = 1
241
+ except openai.RateLimitError as e:
242
+ logging.error(f"Rate limit error occurred: {e}")
243
+ stat = 0
244
+ time.sleep(60)
245
+ except Exception as e:
246
+ logging.error(f"An error occurred in open_ai: {e}")
247
+ stat = 0
248
+
249
+ output = response.choices[0].message.content
250
+ return output
251
+
252
+ @staticmethod
253
+ def compare_strings(string1: str, string2: str) -> float:
254
+ """
255
+ Compare two strings and return their similarity ratio.
256
+
257
+ Args:
258
+ string1 (str): The first string.
259
+ string2 (str): The second string.
260
+
261
+ Returns:
262
+ float: The similarity ratio between the two strings.
263
+
264
+ Raises:
265
+ None
266
+ """
267
+ matcher = SequenceMatcher(None, string1, string2)
268
+ similarity_ratio = matcher.ratio()
269
+ return similarity_ratio
270
+ @staticmethod
271
+ def get_main_section(section_number: str) -> str:
272
+ """
273
+ Get the main section number from a given section number.
274
+
275
+ Args:
276
+ section_number (str): The section number.
277
+
278
+ Returns:
279
+ str: The main section number.
280
+
281
+ Raises:
282
+ None+
283
+ """
284
+ parts = section_number.split('.')
285
+ if len(parts) > 1:
286
+ parts.pop()
287
+
288
+ return ".".join(parts)
289
+ @staticmethod
290
+ def increment_section(section_number: str) -> str:
291
+ """
292
+ Increment a section number by one.
293
+
294
+ Args:
295
+ section_number (str): The section number.
296
+
297
+ Returns:
298
+ str: The incremented section number.
299
+
300
+ Raises:
301
+ None
302
+ """
303
+ parts = section_number.split('.')
304
+ last_part = '0' if not parts[-1] else parts[-1] # Get the last part of the section number
305
+ # Check if the last part is numeric
306
+ if last_part.isdigit():
307
+ # Convert the last part to an integer and increment it by one
308
+ incremented_last_part = str(int(last_part) + 1)
309
+ # Replace the last part in the parts list
310
+ parts[-1] = incremented_last_part
311
+ else:
312
+ # If the last part is not numeric, return the original section number
313
+ return section_number
314
+
315
+ # Join the parts back together with '.'
316
+ incremented_section = '.'.join(parts)
317
+ return incremented_section
318
+ @staticmethod
319
+ def count_subsections(dictionary: Dict[str, Union[str, Dict]]) -> Dict[str, int]:
320
+ """
321
+ Count the number of subsections in a dictionary.
322
+
323
+ Args:
324
+ dictionary (Dict[str, Union[str, Dict]]): The dictionary containing the subsections.
325
+
326
+ Returns:
327
+ Dict[str, int]: A dictionary with the main section numbers as keys and the count of subsections as values.
328
+
329
+ Raises:
330
+ None
331
+ """
332
+ section_counts = {}
333
+ for key in dictionary:
334
+ # Split the key by '.' and take the first part as the section number
335
+ section_number = FindUpdate.get_main_section(key)
336
+
337
+ # Check if the section number is already in the section_counts dictionary
338
+ if section_number in section_counts:
339
+ # Increment the count for the section
340
+ section_counts[section_number] += 1
341
+ else:
342
+ # Initialize the count for the section
343
+ section_counts[section_number] = 1
344
+
345
+ return section_counts
346
+ @staticmethod
347
+ def split_page_section(page_no: str, sec_no: str) -> Tuple[str, Tuple[int]]:
348
+ """
349
+ Split the page number and section number into separate components.
350
+
351
+ Args:
352
+ page_no (str): The page number.
353
+ sec_no (str): The section number.
354
+
355
+ Returns:
356
+ Tuple[str, Tuple[int]]: A tuple containing the page number and section number.
357
+
358
+ Raises:
359
+ None
360
+ """
361
+ try:
362
+ page_number = page_no
363
+ section_numbers = sec_no
364
+ section_numbers = [int(num) if num and num.isdigit() else 0 for num in section_numbers]
365
+ section_number = tuple(section_numbers)
366
+ return (page_number, section_number)
367
+ except Exception as e:
368
+ logging.error(f"An error occurred in split_page_section: {e}")
369
+ return ("", ())
370
+ @staticmethod
371
+ def process_comparisons(result_agreement: Dict[str, Dict], result_template: Dict[str, Dict]) -> Tuple[List[Dict], List[Dict], List[Dict]]:
372
+ """
373
+ Process the comparisons between the agreement and template texts.
374
+
375
+ Args:
376
+ result_agreement (Dict[str, Dict]): The agreement text.
377
+ result_template (Dict[str, Dict]): The template text.
378
+
379
+ Returns:
380
+ Tuple[List[Dict], List[Dict], List[Dict]]: A tuple containing the changes list, actual list, and changes_ui list.
381
+
382
+ Raises:
383
+ None
384
+ """
385
+ # Initialize a flag to track if there are any changes
386
+ changes = {}
387
+ changes_ui = {}
388
+ actual = {}
389
+ compared_sections = []
390
+ actual_list = []
391
+ changes_list = []
392
+ changes_ui_list = []
393
+ sections_added = False
394
+ current_section = 0
395
+ prev_section = 0
396
+
397
+ # Iterate through the keys and values of the dictionaries
398
+ for key in result_template:
399
+ current_section = FindUpdate.get_main_section(key)
400
+ if sections_added and current_section == prev_section:
401
+ contract_key = FindUpdate.increment_section(current_section)
402
+ else:
403
+ contract_key = key
404
+
405
+ if prev_section != current_section:
406
+ sections_added = False
407
+
408
+ if contract_key in result_agreement:
409
+ if FindUpdate.count_subsections(result_agreement)[current_section] != FindUpdate.count_subsections(result_template)[current_section]:
410
+ if FindUpdate.compare_strings(result_template[key]['content'], result_agreement[contract_key]['content']) < .1:
411
+ # Actual JSON
412
+ actual = {}
413
+ actual["actual"] = ""
414
+ actual["page_number"] = result_template[key]['page_num']
415
+ actual["section_number"] = key
416
+ actual["actual_coords"] = ""
417
+ actual_list.append(actual)
418
+ # Changes JSON
419
+ changes = {}
420
+ changes["changed"] = result_agreement[contract_key]['content'] + ' Analysis:New clause added' + '~!~addition'
421
+ changes["changed_page_number"] = result_agreement[contract_key]['page_num']
422
+ changes["changed_section_number"] = key
423
+ changes["changed_coords"] = result_agreement[contract_key]['coords']
424
+ changes_list.append(changes)
425
+ # changes_ui JSON
426
+ changes_ui = {}
427
+ changes_ui["changed"] = result_agreement[contract_key]['content'] + ' Analysis:New clause added' + '~!~addition'
428
+ changes_ui["changed_page_number"] = result_agreement[contract_key]['page_num']
429
+ changes_ui["changed_section_number"] = key
430
+ changes_ui["changed_coords"] = result_agreement[contract_key]['coords']
431
+ changes_ui_list.append(changes_ui)
432
+
433
+ contract_key = FindUpdate.increment_section(contract_key)
434
+ sections_added = True
435
+
436
+ compared_sections.append(contract_key)
437
+
438
+ if contract_key in result_agreement:
439
+ try:
440
+ prompt = f""""
441
+ As an attorney representing your client, your task is to compare the template text and the contract text provided and identify any changes that may impact the agreement or the involved parties. Specifically, you need to analyze the legal implications and considerations of the word 'subcontractors' when it appears in the changed text. Instead of focusing solely on the addition or removal of the letters 'or,' provide a comprehensive analysis based on the complete word 'subcontractors.' Classify the changes as either "minor_change" or "major_change."
442
+ Please provide the changed text alone as a separate paragraph under the "Changed:" subheading, and the analysis of the changes as a separate paragraph under the "Analysis:" subheading. At the end, add ~!~ and classification like ~!~minor_change or ~!~major_change.
443
+ EXAMPLES -
444
+ 1.
445
+ Contract text:
446
+ Verify identification credentials including Social Security number, driver’s license, educational credentials, employment history, home address, and citizenship indicia;
447
+ In connection with providing access to a customer’s facilities or systems, comply with any additional investigation or screening requirements required by such customer as communicated in advance; test for use of illicit drugs including opiates, cocaine, cannabinoids, amphetamines, and phencyclidine.
448
+ Template text:
449
+ Verify identification credentials including Social Security number, driver’s license, educational credentials, employment history, home address, and citizenship indicia.
450
+ In connection with providing access to a customer’s facilities or systems, comply with any additional investigation or screening requirements required by such customer as communicated in advance. Test for use of illicit drugs including opiates, cocaine, cannabinoids, amphetamines, and phencyclidine.
451
+ Differences Observed -
452
+ Changed: "When (i) the customer or end user is a federal, state, or local government entity"
453
+ Analysis:
454
+ A new sentence is added: "When (i) the customer or end user is a federal, state, or local government entity" in the template text. This clause specifies a condition under which the drug testing requirement applies. In the template text, this condition is excluded, meaning that the drug testing requirement would apply regardless of whether the customer or end user is a government entity. This could potentially change the scope and applicability of the drug testing provision.~!~major_change
455
+ 2.
456
+ Contract text:
457
+ Perform a criminal background check to determine, in the counties, states, and federal court districts where the candidate has lived, worked, or attended school in the previous ten years, whether the candidate has been: (1) convicted of any felony; (2) convicted of a misdemeanor involving violence, theft, computer crimes, fraud, financial crimes, drug distribution, unlawful possession or use of a dangerous weapon, or sexual misconduct; or, (3) listed on any government registry as a sex offender (together, “Conviction”); and in connection with providing access to a customer’s facilities or systems, comply with any additional investigation or screening requirements required by such customer as communicated in advance.
458
+ Template text:
459
+ Perform a criminal background check to determine, in the counties, states, and federal court districts where the candidate has lived, worked, or attended school in the previous ten years, whether the candidate has been: (1) convicted of any felony; (2) convicted of a misdemeanor involving violence, theft, computer crimes, fraud, financial crimes, drug distribution, unlawful possession or use of a dangerous weapon, or sexual misconduct; or, (3) listed on any government registry as a sex offender (together, “Conviction”). In connection with providing access to a customer’s facilities or systems, comply with any additional investigation or screening requirements required by such customer as communicated in advance.
460
+ Differences Observed -
461
+ Changed: "and"
462
+ Analysis:
463
+ The contract text includes the word "and," which isn't in the template. This could potentially change the interpretation of the agreement, as it could be read as each clause being a separate requirement, rather than a list of requirements.~!~major_change
464
+ 3.
465
+ Contract text:
466
+ The service provider may not assign, delegate, or otherwise transfer its rights or obligations under this Agreement, voluntarily or involuntarily, without the prior written consent of the other party except that the service provider may delegate certain obligations hereunder to its subcontractors as contemplated by this Agreement. Any attempted assignment, delegation, or transfer not consented to in writing will be void. Notwithstanding the foregoing, with notice to the other party, either party may assign this Agreement, in whole or in part, to any affiliate, successor-in-interest or without securing the consent of the other party. Any assignment of money will be void if (i) the assignor fails to give the non-assigning party at least thirty (30) days prior written notice, or (ii) the assignment purports to impose upon the non-assigning party additional costs or obligations in addition to the payment of such money, or (iii) the assignment purports to preclude the other party from dealing solely and directly with the service provider in all matters pertaining to this Agreement. This Agreement binds and benefits both parties and their permitted successors and assigns.
467
+ Template text:
468
+ The service provider may not assign, delegate, or otherwise transfer its rights or obligations under this Agreement, voluntarily or involuntarily, without the prior written consent of the other party except that the service provider may delegate certain obligations hereunder to its subcontracts as contemplated by this Agreement. Any attempted assignment, delegation, or transfer not consented to in writing will be void. Notwithstanding the foregoing, with notice to the other party, either party may assign this Agreement, in whole or in part, to any affiliate, successor-in-interest or without securing the consent of the other party. Any assignment of money will be void if (i) the assignor fails to give the non-assigning party at least thirty (30) days prior written notice, or (ii) the assignment purports to impose upon the non-assigning party additional costs or obligations in addition to the payment of such money, or (iii) the assignment purports to preclude the other party from dealing solely and directly with the service provider in all matters pertaining to this Agreement. This Agreement binds and benefits both parties and their permitted successors and assigns.
469
+ Differences Observed -
470
+ Changed: "Subcontractors"
471
+ Analysis: The contract text includes the word "Subcontractors" instead of "Subcontracts" as in the template. This change could potentially alter the meaning of the agreement as it specifies a different entity (Subcontractors vs Subcontracts). However, given the context, it seems likely that this is a typographical error in the template text, and the intended meaning remains the same.~!~minor_change
472
+ 4.
473
+ Contract text:
474
+ This AGREEMENT is entered into between [Company Name], a [State] corporation, which sometimes does business as [DBA Name], (“Company”) and [Other Party Name], a [State] LLC (“Solution Provider” or “SP”). The company and solution provider may be referred to collectively as the “Parties” or individually as a “Party.”
475
+ Template text:
476
+ ALLIANCE PROGRAM AGREEMENT This AGREEMENT is entered into between [Company Name], a [State] corporation, which sometimes does business as [DBA Name], (“Company”) and ________________________, a __________ corporation (“Solution Provider” or “SP”). The company and solution provider may be referred to collectively as the “Parties” or individually as a “Party.”
477
+ Differences Observed -
478
+ Changed:"[Other Party Name], a [State] LLC"
479
+ Analysis: The contract text includes the specific name of the corporation "[Other Party Name], a [State] LLC" instead of a placeholder as in the template. This is a minor change as it is expected that the specific name of the corporation would be filled in the actual contract.~!~minor_change
480
+ """
481
+ res = FindUpdate.check_identify_changes(FindUpdate.clean_string(result_template[key]['content']), FindUpdate.clean_string(result_agreement[contract_key]['content']))
482
+ if res != 'no_change':
483
+ final_prompt =prompt + res
484
+ llm_res = FindUpdate.open_ai(final_prompt)
485
+ # Actual JSON
486
+ actual = {}
487
+ actual["actual"] = result_template[key]['content']
488
+ actual["page_number"] = result_template[key]['page_num']
489
+ actual["section_number"] = key
490
+ actual["actual_coords"] = result_template[key]['coords']
491
+ actual_list.append(actual)
492
+ # Changes JSON
493
+ changes = {}
494
+ changes["changed"] = llm_res
495
+ changes["changed_page_number"] = result_agreement[contract_key]['page_num']
496
+ changes["changed_section_number"] = key
497
+ changes["changed_coords"] = result_agreement[contract_key]['coords']
498
+ changes_list.append(changes)
499
+ # changes_ui JSON
500
+ changes_ui = {}
501
+ changes_ui["changed"] = llm_res
502
+ changes_ui["changed_page_number"] = result_agreement[contract_key]['page_num']
503
+ changes_ui["changed_section_number"] = key
504
+ changes_ui["changed_coords"] = result_agreement[contract_key]['coords']
505
+ changes_ui_list.append(changes_ui)
506
+ except Exception as e:
507
+ logging.error(f"An error occurred in check_identify_changes: {e}")
508
+
509
+ else:
510
+ # Actual JSON
511
+ actual = {}
512
+ actual["actual"] = result_template[key]['content']
513
+ actual["page_number"] = result_template[key]['page_num']
514
+ actual["section_number"] = key
515
+ actual["actual_coords"] = result_template[key]['coords']
516
+ actual_list.append(actual)
517
+
518
+ prev_section = current_section
519
+
520
+ for key in result_template:
521
+ if key not in result_agreement:
522
+ actual = {}
523
+ # Actual JSON
524
+ actual["actual"] = result_template[key]['content']
525
+ actual["page_number"] = result_template[key]['page_num']
526
+ actual["section_number"] = key
527
+ actual['actual_coords'] = ''
528
+ actual_list.append(actual)
529
+
530
+ #Changes JSON
531
+ changes ={}
532
+ changes["changed"] = result_template[key]['content']+' Analysis:missing'+'~!~missing'
533
+ changes["changed_page_number"] = result_template[key]['page_num']
534
+ changes["changed_section_number"] = key
535
+ changes["changed_coords"] = result_template[key]['coords']
536
+ changes_list.append(changes)
537
+
538
+ #changes_ui JSON
539
+ changes_ui = {}
540
+ changes_ui["changed"] = result_template[key]['content']+' Analysis:missing'+'~!~missing'
541
+ changes_ui["changed_page_number"] = result_template[key]['page_num']
542
+ changes_ui["changed_section_number"] = key
543
+ changes_ui["changed_coords"] = result_template[key]['coords']
544
+ changes_ui_list.append(changes_ui)
545
+
546
+ for key in result_agreement:
547
+ if key not in result_template and key not in compared_sections:
548
+ actual ={}
549
+ #Actual JSON
550
+ actual["actual"] = ""
551
+ actual["page_number"] = result_agreement[key]['page_num']
552
+ actual["section_number"] = key
553
+ actual["actual_coords"] = ""
554
+ actual_list.append(actual)
555
+ changes = {}
556
+ #Changes JSON
557
+ changes["changed"] = result_agreement[key]['content']+' Analysis:New clause added'+'~!~addition'
558
+ changes["changed_page_number"] = result_agreement[key]['page_num']
559
+ changes["changed_section_number"] = key
560
+ changes["changed_coords"] = result_agreement[key]['coords']
561
+ changes_list.append(changes)
562
+
563
+ #changes_ui JSON
564
+ changes_ui ={}
565
+ changes_ui["changed"] = result_agreement[key]['content']+' Analysis:New clause added'+'~!~addition'
566
+ changes_ui["changed_page_number"] = result_agreement[key]['page_num']
567
+ changes_ui["changed_section_number"] = key
568
+ changes_ui["changed_coords"] = result_agreement[key]['coords']
569
+ changes_ui_list.append(changes_ui)
570
+
571
+ return changes_list,actual_list,changes_ui_list
572
+
573
+ @staticmethod
574
+ def remove_analysis(text: str) -> str:
575
+ """
576
+ Remove the analysis portion from the given text.
577
+
578
+ Args:
579
+ text (str): The text to remove the analysis from.
580
+
581
+ Returns:
582
+ str: The text with the analysis portion removed.
583
+ """
584
+ new_text = re.sub(r"(Analysis.*)", "", text)
585
+ return new_text
586
+ @staticmethod
587
+ def json_output(actual: List[Dict[str, str]], changes_ui: List[Dict[str, str]], file: str, template_files: str, result_template: str, result_agreement: str) -> Dict[str, any]:
588
+ """
589
+ Generate a JSON output based on the provided inputs.
590
+
591
+ Args:
592
+ actual (List[Dict[str, str]]): The list of actual changes.
593
+ changes_ui (List[Dict[str, str]]): The list of UI changes.
594
+ file (str): The file path.
595
+ template_files (str): The template path.
596
+ result_template (str): The template result.
597
+ result_agreement (str): The agreement result.
598
+
599
+ Returns:
600
+ Dict[str, any]: The generated JSON output.
601
+ """
602
+ deletion_prompt = """
603
+ {} : This clause has been deleted from the existing contract. what is the impact? provide me short analysis in 1 single paragraph should not exceed 100 words.
604
+ """
605
+
606
+ addition_prompt = """
607
+ {} : This clause has been added in the existing contract. what is the impact? provide me short analysis in 1 single paragraph should not exceed 100 words.
608
+ """
609
+ json_output = {}
610
+
611
+ json_output["input_file_path"] = file
612
+ comparison_list = []
613
+
614
+ for i in range(len(actual)):
615
+ actual_changes = '{}'
616
+ actual_changes_json = json.loads(actual_changes)
617
+ analysis_final = re.sub(r'\n', ' ', changes_ui[i]['changed'].split("~!~")[0].split("Analysis:")[1])
618
+ if changes_ui[i]['changed'].split('~!~')[-1] == 'addition' or changes_ui[i]['changed'].split('~!~')[-1] == 'missing':
619
+ continue
620
+ actual_changes_json.update({"actual": actual[i]['actual']})
621
+ actual_changes_json.update({"page_number": actual[i]['page_number']})
622
+ actual_changes_json.update({"section_number": actual[i]['section_number']})
623
+ actual_changes_json.update({"actual_coords": actual[i]['actual_coords']})
624
+ actual_changes_json.update({"changed": FindUpdate.remove_analysis(changes_ui[i]["changed"])})
625
+ actual_changes_json.update({"changed_page_number": changes_ui[i]["changed_page_number"]})
626
+ actual_changes_json.update({"changed_section_number": changes_ui[i]["changed_section_number"]})
627
+ actual_changes_json.update({"changed_coords": changes_ui[i]["changed_coords"]})
628
+ actual_changes_json.update({"analysis": analysis_final})
629
+ actual_changes_json.update({"type_of_change": changes_ui[i]['changed'].split("~!~")[1]})
630
+ comparison_list.append(actual_changes_json)
631
+
632
+ for i in range(len(changes_ui)):
633
+ actual_changes = '{}'
634
+ actual_changes_json = json.loads(actual_changes)
635
+ if changes_ui[i]['changed'].split('~!~')[-1] == 'missing':
636
+ actual_changes_json.update({"actual": actual[i]['actual']})
637
+ actual_changes_json.update({"page_number": actual[i]['page_number']})
638
+ actual_changes_json.update({"section_number": actual[i]['section_number']})
639
+ actual_changes_json.update({"actual_coords": actual[i]['actual_coords']})
640
+ actual_changes_json.update({"changed": FindUpdate.remove_analysis(changes_ui[i]["changed"])})
641
+ actual_changes_json.update({"changed_page_number": changes_ui[i]["changed_page_number"]})
642
+ actual_changes_json.update({"changed_section_number": changes_ui[i]["changed_section_number"]})
643
+ actual_changes_json.update({"changed_coords": changes_ui[i]["changed_coords"]})
644
+ final_deletion_prompt = deletion_prompt.format(actual[i]['actual'])
645
+ actual_changes_json.update({"analysis": FindUpdate.open_ai(final_deletion_prompt)})
646
+ actual_changes_json.update({"type_of_change": "missing"})
647
+ comparison_list.append(actual_changes_json)
648
+ if changes_ui[i]['changed'].split('~!~')[-1] == 'addition':
649
+ actual_changes_json.update({"actual": actual[i]['actual']})
650
+ actual_changes_json.update({"page_number": actual[i]['page_number']})
651
+ actual_changes_json.update({"section_number": actual[i]['section_number']})
652
+ actual_changes_json.update({"actual_coords": actual[i]['actual_coords']})
653
+ actual_changes_json.update({"changed": FindUpdate.remove_analysis(changes_ui[i]["changed"])})
654
+ actual_changes_json.update({"changed_page_number": changes_ui[i]["changed_page_number"]})
655
+ actual_changes_json.update({"changed_section_number": changes_ui[i]["changed_section_number"]})
656
+ actual_changes_json.update({"changed_coords": changes_ui[i]["changed_coords"]})
657
+ final_addition_prompt =addition_prompt.format(changes_ui[i]["changed"])
658
+ actual_changes_json.update({"analysis": FindUpdate.open_ai(final_addition_prompt)})
659
+ actual_changes_json.update({"type_of_change": "addition"})
660
+ comparison_list.append(actual_changes_json)
661
+
662
+ json_output["changes"] = comparison_list
663
+
664
+ # Sort the data based on the "actual" key in ascending order
665
+ sorted_data = sorted(json_output["changes"], key=lambda x: FindUpdate.split_page_section(x["page_number"], x["section_number"]))
666
+
667
+ # Update the JSON data with the sorted_data
668
+ json_output["changes"] = sorted_data
669
+ return json_output
670
+ @staticmethod
671
+ def process_files_template(file: str) -> List[str]:
672
+ """
673
+ Process the template file and extract sections.
674
+
675
+ Args:
676
+ file (str): The path of the template file.
677
+
678
+ Returns:
679
+ List[str]: The extracted sections from the template file.
680
+ """
681
+ try:
682
+ # Set the header and footer heights
683
+ header_height = 50
684
+ footer_height = 80
685
+
686
+ # Extract sections from the file
687
+ sections = FindUpdate.extract_sections(file, header_height, footer_height)
688
+ print("Template:",sections)
689
+ return sections
690
+
691
+ except Exception as e:
692
+ # Create a logger
693
+ logger = logging.getLogger(__name__)
694
+ logger.error(f"Error processing template file: {str(e)}")
695
+ raise
696
+ @staticmethod
697
+ def process_files_original(file: str) -> List[str]:
698
+ """
699
+ Process the original file and extract sections.
700
+
701
+ Args:
702
+ file (str): The path of the original file.
703
+
704
+ Returns:
705
+ List[str]: The extracted sections from the original file.
706
+ """
707
+ try:
708
+ # Set the header and footer heights
709
+ header_height = 50
710
+ footer_height = 80
711
+
712
+ # Extract sections from the file
713
+ sections = FindUpdate.extract_sections(file, header_height, footer_height)
714
+ print("Original:",sections)
715
+ return sections
716
+
717
+ except Exception as e:
718
+ # Create a logger
719
+ logger = logging.getLogger(__name__)
720
+ logger.error(f"Error processing original file: {str(e)}")
721
+ raise
722
+
723
+ @staticmethod
724
+ def main_processing_function(file_path: str, template_path: str):
725
+ """
726
+ Processes the provided PDF file and its template to identify and report changes.
727
+
728
+ Args:
729
+ file_path (str): Path to the PDF file to be processed.
730
+ template_path (str): Path to the corresponding template PDF file.
731
+
732
+ Returns:
733
+ dict: A dictionary containing the processed results and change analysis.
734
+ """
735
+ logger = logging.getLogger(__name__)
736
+
737
+ try:
738
+ # Process the original PDF file
739
+ result_agreement = FindUpdate.process_files_original(file_path)
740
+
741
+ # Process the template PDF file
742
+ result_template = FindUpdate.process_files_template(template_path)
743
+
744
+ # Compare the sections extracted from the original and template files
745
+ changes, actual, changes_ui = FindUpdate.process_comparisons(result_agreement, result_template)
746
+
747
+ # Generate a JSON output summarizing the changes
748
+ final_output = FindUpdate.json_output(actual, changes_ui, file_path, template_path, result_template, result_agreement)
749
+
750
+ return final_output
751
+
752
+ except Exception as e:
753
+ logger.error(f"Error processing files: {e}")
754
+ raise Exception(f"Error during file processing: {str(e)}")