karthikeyan-r commited on
Commit
b4db35d
1 Parent(s): b66a9af

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +851 -0
app.py ADDED
@@ -0,0 +1,851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ import json
4
+ import time
5
+ import fitz
6
+ import pymongo
7
+ import difflib
8
+ import secrets
9
+ import openai
10
+ import string
11
+ import logging
12
+ import requests
13
+ import streamlit as st
14
+ from pandas import DataFrame
15
+ from openai import AzureOpenAI
16
+ from bson.json_util import dumps
17
+ from difflib import SequenceMatcher
18
+ from tempfile import NamedTemporaryFile
19
+ from typing import Tuple, Dict, List, Union
20
+ from diff_match_patch import diff_match_patch
21
+
22
+ import base64
23
+ import pandas as pd
24
+
25
+
26
+ # Your existing functions go here
27
+
28
+ def clean_string(text: str, stem: str = "None") -> str:
29
+ """
30
+ Clean the input text by removing punctuation, numbers, and optionally stemming or lemmatizing the words.
31
+
32
+ Args:
33
+ text (str): The input text to be cleaned.
34
+ stem (str, optional): The stemming method to be used. Options are "None" (default), "Stem", "Lem", or "Spacy".
35
+
36
+ Returns:
37
+ str: The cleaned text.
38
+
39
+ Raises:
40
+ None
41
+ """
42
+ try:
43
+ final_string = ""
44
+ # Replace any characters with nothing or a space
45
+ text = re.sub(r'\n', ' ', text)
46
+ text = re.sub(r' +', ' ', text)
47
+ text = re.sub(r'[^\x00-\x7f]',r'', text)
48
+ # Remove punctuation
49
+ translator = str.maketrans('', '', string.punctuation)
50
+ text = text.translate(translator)
51
+ # Remove numbers
52
+ text_filtered = [re.sub(r'\w*\d\w*\s+', '', w) for w in text]
53
+ text_filtered = [re.sub('[0-9]', '', w) for w in text_filtered]
54
+ # Stem or Lemmatize
55
+ if stem == 'Stem':
56
+ stemmer = PorterStemmer()
57
+ text_stemmed = [stemmer.stem(y) for y in text_filtered]
58
+ elif stem == 'Lem':
59
+ lem = WordNetLemmatizer()
60
+ text_stemmed = [lem.lemmatize(y) for y in text_filtered]
61
+ elif stem == 'Spacy':
62
+ text_filtered = nlp(' '.join(text_filtered))
63
+ text_stemmed = [y.lemma_ for y in text_filtered]
64
+ else:
65
+ text_stemmed = text_filtered
66
+
67
+ final_string = ''.join(text_stemmed)
68
+ except Exception as e:
69
+ # Handle the exception here
70
+ logging.error(f"An error occurred in clean_string: {e}")
71
+ return None
72
+
73
+ return final_string
74
+
75
+ def extract_text_without_header_footer(page: fitz.Page, page_height: float, header_height: float, footer_height: float) -> str:
76
+ """
77
+ Extract the text from a page of a PDF document, excluding the header and footer.
78
+
79
+ Args:
80
+ page (fitz.Page): The page object from the PyMuPDF library.
81
+ page_height (float): The height of the page.
82
+ header_height (float): The height of the header to be excluded.
83
+ footer_height (float): The height of the footer to be excluded.
84
+
85
+ Returns:
86
+ str: The extracted text.
87
+
88
+ Raises:
89
+ None
90
+ """
91
+ try:
92
+ exclude_top = header_height
93
+ exclude_bottom = page_height - footer_height
94
+ text = ""
95
+ for text_block in page.get_text_blocks():
96
+ bbox = fitz.Rect(text_block[:4]) # Get bounding box of text block
97
+ if bbox.y0 >= exclude_top and bbox.y1 <= exclude_bottom:
98
+ text += text_block[4] + "\n" # Add text content to result
99
+ return text
100
+ except Exception as e:
101
+ # Handle the exception here
102
+ logging.error(f"An error occurred in extract_text_without_header_footer: {e}")
103
+ return ""
104
+
105
+ def rect_to_dict(rect: fitz.Rect) -> Dict[str, float]:
106
+ """
107
+ Convert a PyMuPDF Rect object to a dictionary.
108
+
109
+ Args:
110
+ rect (fitz.Rect): The Rect object from the PyMuPDF library.
111
+
112
+ Returns:
113
+ Dict[str, float]: The dictionary representation of the Rect object.
114
+
115
+ Raises:
116
+ None
117
+ """
118
+ return {
119
+ "x1": rect[0],
120
+ "y1": rect[1],
121
+ "x2": rect[2],
122
+ "y2": rect[3]
123
+ }
124
+
125
+ def extract_sections(pdf_path: str, header_height: float, footer_height: float) -> Dict[str, Dict[str, List[str]]]:
126
+ """
127
+ Extract sections from a PDF document, excluding the header and footer.
128
+
129
+ Args:
130
+ pdf_path (str): The path to the PDF document.
131
+ header_height (float): The height of the header to be excluded.
132
+ footer_height (float): The height of the footer to be excluded.
133
+
134
+ Returns:
135
+ Dict[str, Dict[str, List[str]]]: A dictionary containing the extracted sections.
136
+
137
+ Raises:
138
+ None
139
+ """
140
+ try:
141
+ doc = fitz.open(pdf_path)
142
+ sections = {}
143
+ current_section = None
144
+ for page_num in range(2, len(doc)):
145
+ page = doc.load_page(page_num)
146
+ page_height = page.rect.height
147
+ text = extract_text_without_header_footer(page, page_height, header_height, footer_height)
148
+ lines = text.split('\n')
149
+ print("start")
150
+ for line in lines:
151
+ match = re.match(r'^(?:\d+\.\d*(?:\.\d+)*)|AT&T ALLIANCE PROGRAM AGREEMENT', line.strip())
152
+ if match:
153
+ print("line:",line)
154
+ section_num = match.group()
155
+ if section_num != current_section:
156
+ current_section = section_num
157
+ sections[current_section] = {'page_num': str(page_num + 1), 'coords': [], 'content': []}
158
+
159
+ if current_section:
160
+ sections[current_section]['content'].append(line)
161
+ bbox = page.search_for(line)
162
+ if bbox:
163
+ for cord in bbox:
164
+ sections[current_section]['coords'].append(rect_to_dict(cord))
165
+ print("section-keys:",sections.keys())
166
+ for key in sections.keys():
167
+ if 'content' in sections[key]:
168
+ sections[key]['content'] = (' '.join(sections[key]['content']))[len(key):].lstrip()
169
+ print("Content:",sections)
170
+ return sections
171
+ except Exception as e:
172
+ # Handle the exception here
173
+ logging.error(f"An error occurred in extract_sections: {e}")
174
+ return {}
175
+
176
+ def check_identify_changes(template_text: str, contract_text: str) -> str:
177
+ """
178
+ Compare the template text with the contract text and identify the changes made.
179
+
180
+ Args:
181
+ template_text (str): The template text.
182
+ contract_text (str): The contract text.
183
+
184
+ Returns:
185
+ str: A sentence prompt describing the changes made.
186
+
187
+ Raises:
188
+ None
189
+ """
190
+ try:
191
+ dmp = diff_match_patch()
192
+ diff = dmp.diff_main(template_text, contract_text)
193
+ dmp.diff_cleanupSemantic(diff)
194
+
195
+ if all([True if each[0] == 0 or each[1] == ' ' else False for each in diff]):
196
+ return('no_change')
197
+ else:
198
+ deleted = []
199
+ added = []
200
+ for each in diff:
201
+ if each[0] == -1:
202
+ deleted.append(each[1])
203
+ elif each[0] == 1:
204
+ added.append(each[1])
205
+ sentence_prompt = f"""
206
+ template text = {template_text}
207
+ contract_text = {contract_text}
208
+ deleted from template --- {deleted}
209
+ added to the actual contract -- {added}
210
+ """
211
+ return(sentence_prompt)
212
+ except Exception as e:
213
+ # Handle the exception here
214
+ logging.error(f"An error occurred in check_identify_changes: {e}")
215
+ return ""
216
+
217
+
218
+
219
+ def open_ai(prompt: str) -> str:
220
+ """
221
+ Generate AI response using OpenAI GPT-4 model.
222
+
223
+ Args:
224
+ prompt (str): The prompt for the AI model.
225
+
226
+ Returns:
227
+ str: The generated AI response.
228
+
229
+ Raises:
230
+ None
231
+ """
232
+ stat = 0
233
+ while stat == 0:
234
+ try:
235
+ client = AzureOpenAI(api_key=os.getenv("AZURE_API_KEY"),
236
+ api_version="2023-07-01-preview",
237
+ azure_endpoint="https://azureadople.openai.azure.com/")
238
+ conversation = []
239
+ conversation.append({"role": "user", "content": prompt})
240
+ response = client.chat.completions.create(
241
+ model="GPT-3",
242
+ messages=conversation,
243
+ temperature=0,
244
+ max_tokens=3000,
245
+ stop=None
246
+ )
247
+ stat = 1
248
+ except openai.RateLimitError as e:
249
+ logging.error(f"Rate limit error occurred: {e}")
250
+ stat = 0
251
+ time.sleep(60)
252
+ except Exception as e:
253
+ logging.error(f"An error occurred in open_ai: {e}")
254
+ stat = 0
255
+
256
+ output = response.choices[0].message.content
257
+ return output
258
+
259
+ prompt = f""""
260
+ As an attorney representing AT&T, your task is to compare the template text and the contract text provided and identify any changes that may impact the agreement or AT&T. Specifically, you need to
261
+ 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."
262
+
263
+
264
+ 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 and at the end add ~!~ and classification like ~!~minor_change or ~!~major_change.
265
+
266
+
267
+ EXAMPLES -
268
+ 1.
269
+ Contract text-
270
+ Verify identification credentials including Social Security number, driver’s license, educational credentials, employment history, home address and citizenship indicia;
271
+ 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 by AT&T; When (i) the Customer or end user is a federal, state or local government entity, test for use of illicit drugs including opiates, cocaine, cannabinoids, amphetamines, and phencyclidine.
272
+ Template text- Verify identification credentials including Social Security number, driver’s license, educational credentials, employment history, home address and citizenship indicia.
273
+ 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 by AT&T. Test for use of illicit drugs including opiates, cocaine, cannabinoids, amphetamines, and phencyclidine
274
+
275
+ Differences Observed -
276
+
277
+ Changed: "When (i) the Customer or end user is a federal, state or local government entity"
278
+
279
+ analysis:
280
+ 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
281
+
282
+
283
+
284
+
285
+
286
+
287
+ 2.
288
+ Contract text-
289
+ Perform a criminal background check to determine, in the counties, states, and federal court districts where Candidate has lived, worked, or attended school in the previous ten years, whether 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 by AT&T.
290
+ Template text-
291
+ Perform a criminal background check to determine, in the counties, states, and federal court districts where Candidate has lived, worked, or attended school in the previous ten years, whether 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 by AT&T.
292
+
293
+
294
+ Differences Observed -
295
+
296
+ Changed: "and"
297
+
298
+ Analysis:
299
+ 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
300
+
301
+ 3.
302
+ Contract text-
303
+ SP may not assign, delegate, or otherwise transfer its rights or obligations under this Agreement, voluntarily or involuntarily, without the prior written consent of AT&T except that
304
+ SP may delegate certain obligations hereunder to its Subcontractors as contemplated by this Agreement.
305
+ 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 wi t h o u t 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 AT&T from dealing solely and directly with SP in all matters pertaining to this Agreement. This Agreement binds and benefits both Parties and their permitted successors and assigns.
306
+
307
+ Template text-
308
+ SP may not assign, delegate, or otherwise transfer its rights or obligations under this Agreement, voluntarily or involuntarily, without the prior written consent of AT&T except that SP 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 w i t h o u t 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 AT&T from dealing solely and directly with SP in all matters pertaining to this Agreement. This Agreement binds and benefits both Parties and their permitted successors and assigns.
309
+
310
+ Differences Observed -
311
+ Changed: "Subcontractors"
312
+
313
+ 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
314
+
315
+
316
+ 4.
317
+ Contract text-
318
+ This AGREEMENT is entered into between AT&T Corp., a New York corporation, which sometimes does
319
+ business as ACC Business, (“AT&T”) and 3OS Technologies, a NJ LLC (“Solution Provider” or “SP”).
320
+ AT&T and Solution Provider may be referred to collectively as the “Parties” or individually as a “Party”.
321
+
322
+ Template text-
323
+ ALLIANCE PROGRAM AGREEMENT This AGREEMENT is entered into between AT&T Corp., a New York corporation, which sometimes does business as ACC Business, (“AT&T”) and ________________________, a __________ corporation (“Solution Provider” or “SP”). AT&T and Solution Provider may be referred to collectively as the “Parties” or individually as a “Party.”
324
+
325
+ Differences Observed -
326
+ Changed:"3OS Technologies, a NJ LLC"
327
+
328
+ Analysis: " The contract text includes the specific name of the corporation "3OS Technologies, a NJ 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
329
+
330
+
331
+
332
+
333
+
334
+ """
335
+
336
+ def compare_strings(string1: str, string2: str) -> float:
337
+ """
338
+ Compare two strings and return their similarity ratio.
339
+
340
+ Args:
341
+ string1 (str): The first string.
342
+ string2 (str): The second string.
343
+
344
+ Returns:
345
+ float: The similarity ratio between the two strings.
346
+
347
+ Raises:
348
+ None
349
+ """
350
+ matcher = SequenceMatcher(None, string1, string2)
351
+ similarity_ratio = matcher.ratio()
352
+ return similarity_ratio
353
+
354
+ def get_main_section(section_number: str) -> str:
355
+ """
356
+ Get the main section number from a given section number.
357
+
358
+ Args:
359
+ section_number (str): The section number.
360
+
361
+ Returns:
362
+ str: The main section number.
363
+
364
+ Raises:
365
+ None+
366
+ """
367
+ parts = section_number.split('.')
368
+ if len(parts) > 1:
369
+ parts.pop()
370
+
371
+ return ".".join(parts)
372
+
373
+ def increment_section(section_number: str) -> str:
374
+ """
375
+ Increment a section number by one.
376
+
377
+ Args:
378
+ section_number (str): The section number.
379
+
380
+ Returns:
381
+ str: The incremented section number.
382
+
383
+ Raises:
384
+ None
385
+ """
386
+ parts = section_number.split('.')
387
+ last_part = '0' if not parts[-1] else parts[-1] # Get the last part of the section number
388
+ # Check if the last part is numeric
389
+ if last_part.isdigit():
390
+ # Convert the last part to an integer and increment it by one
391
+ incremented_last_part = str(int(last_part) + 1)
392
+ # Replace the last part in the parts list
393
+ parts[-1] = incremented_last_part
394
+ else:
395
+ # If the last part is not numeric, return the original section number
396
+ return section_number
397
+
398
+ # Join the parts back together with '.'
399
+ incremented_section = '.'.join(parts)
400
+ return incremented_section
401
+
402
+ def count_subsections(dictionary: Dict[str, Union[str, Dict]]) -> Dict[str, int]:
403
+ """
404
+ Count the number of subsections in a dictionary.
405
+
406
+ Args:
407
+ dictionary (Dict[str, Union[str, Dict]]): The dictionary containing the subsections.
408
+
409
+ Returns:
410
+ Dict[str, int]: A dictionary with the main section numbers as keys and the count of subsections as values.
411
+
412
+ Raises:
413
+ None
414
+ """
415
+ section_counts = {}
416
+ for key in dictionary:
417
+ # Split the key by '.' and take the first part as the section number
418
+ section_number = get_main_section(key)
419
+
420
+ # Check if the section number is already in the section_counts dictionary
421
+ if section_number in section_counts:
422
+ # Increment the count for the section
423
+ section_counts[section_number] += 1
424
+ else:
425
+ # Initialize the count for the section
426
+ section_counts[section_number] = 1
427
+
428
+ return section_counts
429
+
430
+ def split_page_section(page_no: str, sec_no: str) -> Tuple[str, Tuple[int]]:
431
+ """
432
+ Split the page number and section number into separate components.
433
+
434
+ Args:
435
+ page_no (str): The page number.
436
+ sec_no (str): The section number.
437
+
438
+ Returns:
439
+ Tuple[str, Tuple[int]]: A tuple containing the page number and section number.
440
+
441
+ Raises:
442
+ None
443
+ """
444
+ try:
445
+ page_number = page_no
446
+ section_numbers = sec_no
447
+ section_numbers = [int(num) if num and num.isdigit() else 0 for num in section_numbers]
448
+ section_number = tuple(section_numbers)
449
+ return (page_number, section_number)
450
+ except Exception as e:
451
+ logging.error(f"An error occurred in split_page_section: {e}")
452
+ return ("", ())
453
+
454
+ def process_comparisons(result_agreement: Dict[str, Dict], result_template: Dict[str, Dict]) -> Tuple[List[Dict], List[Dict], List[Dict]]:
455
+ """
456
+ Process the comparisons between the agreement and template texts.
457
+
458
+ Args:
459
+ result_agreement (Dict[str, Dict]): The agreement text.
460
+ result_template (Dict[str, Dict]): The template text.
461
+
462
+ Returns:
463
+ Tuple[List[Dict], List[Dict], List[Dict]]: A tuple containing the changes list, actual list, and changes_ui list.
464
+
465
+ Raises:
466
+ None
467
+ """
468
+ # Initialize a flag to track if there are any changes
469
+ changes = {}
470
+ changes_ui = {}
471
+ actual = {}
472
+ compared_sections = []
473
+ actual_list = []
474
+ changes_list = []
475
+ changes_ui_list = []
476
+ sections_added = False
477
+ current_section = 0
478
+ prev_section = 0
479
+
480
+ # Iterate through the keys and values of the dictionaries
481
+ for key in result_template:
482
+ current_section = get_main_section(key)
483
+ if sections_added and current_section == prev_section:
484
+ contract_key = increment_section(current_section)
485
+ else:
486
+ contract_key = key
487
+
488
+ if prev_section != current_section:
489
+ sections_added = False
490
+
491
+ if contract_key in result_agreement:
492
+ if count_subsections(result_agreement)[current_section] != count_subsections(result_template)[current_section]:
493
+ if compare_strings(result_template[key]['content'], result_agreement[contract_key]['content']) < .1:
494
+ # Actual JSON
495
+ actual = {}
496
+ actual["actual"] = ""
497
+ actual["page_number"] = result_template[key]['page_num']
498
+ actual["section_number"] = key
499
+ actual["actual_coords"] = ""
500
+ actual_list.append(actual)
501
+ # Changes JSON
502
+ changes = {}
503
+ changes["changed"] = result_agreement[contract_key]['content'] + ' Analysis:New clause added' + '~!~addition'
504
+ changes["changed_page_number"] = result_agreement[contract_key]['page_num']
505
+ changes["changed_section_number"] = key
506
+ changes["changed_coords"] = result_agreement[contract_key]['coords']
507
+ changes_list.append(changes)
508
+ # changes_ui JSON
509
+ changes_ui = {}
510
+ changes_ui["changed"] = result_agreement[contract_key]['content'] + ' Analysis:New clause added' + '~!~addition'
511
+ changes_ui["changed_page_number"] = result_agreement[contract_key]['page_num']
512
+ changes_ui["changed_section_number"] = key
513
+ changes_ui["changed_coords"] = result_agreement[contract_key]['coords']
514
+ changes_ui_list.append(changes_ui)
515
+
516
+ contract_key = increment_section(contract_key)
517
+ sections_added = True
518
+
519
+ compared_sections.append(contract_key)
520
+
521
+ if contract_key in result_agreement:
522
+ try:
523
+ res = check_identify_changes(clean_string(result_template[key]['content']), clean_string(result_agreement[contract_key]['content']))
524
+ if res != 'no_change':
525
+ final_prompt = prompt + res
526
+ llm_res = open_ai(final_prompt)
527
+ # Actual JSON
528
+ actual = {}
529
+ actual["actual"] = result_template[key]['content']
530
+ actual["page_number"] = result_template[key]['page_num']
531
+ actual["section_number"] = key
532
+ actual["actual_coords"] = result_template[key]['coords']
533
+ actual_list.append(actual)
534
+ # Changes JSON
535
+ changes = {}
536
+ changes["changed"] = llm_res
537
+ changes["changed_page_number"] = result_agreement[contract_key]['page_num']
538
+ changes["changed_section_number"] = key
539
+ changes["changed_coords"] = result_agreement[contract_key]['coords']
540
+ changes_list.append(changes)
541
+ # changes_ui JSON
542
+ changes_ui = {}
543
+ changes_ui["changed"] = llm_res
544
+ changes_ui["changed_page_number"] = result_agreement[contract_key]['page_num']
545
+ changes_ui["changed_section_number"] = key
546
+ changes_ui["changed_coords"] = result_agreement[contract_key]['coords']
547
+ changes_ui_list.append(changes_ui)
548
+ except Exception as e:
549
+ logging.error(f"An error occurred in check_identify_changes: {e}")
550
+
551
+ else:
552
+ # Actual JSON
553
+ actual = {}
554
+ actual["actual"] = result_template[key]['content']
555
+ actual["page_number"] = result_template[key]['page_num']
556
+ actual["section_number"] = key
557
+ actual["actual_coords"] = result_template[key]['coords']
558
+ actual_list.append(actual)
559
+
560
+ prev_section = current_section
561
+
562
+ for key in result_template:
563
+ if key not in result_agreement:
564
+ actual = {}
565
+ # Actual JSON
566
+ actual["actual"] = result_template[key]['content']
567
+ actual["page_number"] = result_template[key]['page_num']
568
+ actual["section_number"] = key
569
+ actual['actual_coords'] = ''
570
+ actual_list.append(actual)
571
+
572
+ #Changes JSON
573
+ changes ={}
574
+ changes["changed"] = result_template[key]['content']+' Analysis:missing'+'~!~missing'
575
+ changes["changed_page_number"] = result_template[key]['page_num']
576
+ changes["changed_section_number"] = key
577
+ changes["changed_coords"] = result_template[key]['coords']
578
+ changes_list.append(changes)
579
+
580
+ #changes_ui JSON
581
+ changes_ui = {}
582
+ changes_ui["changed"] = result_template[key]['content']+' Analysis:missing'+'~!~missing'
583
+ changes_ui["changed_page_number"] = result_template[key]['page_num']
584
+ changes_ui["changed_section_number"] = key
585
+ changes_ui["changed_coords"] = result_template[key]['coords']
586
+ changes_ui_list.append(changes_ui)
587
+
588
+ for key in result_agreement:
589
+ if key not in result_template and key not in compared_sections:
590
+ actual ={}
591
+ #Actual JSON
592
+ actual["actual"] = ""
593
+ actual["page_number"] = result_agreement[key]['page_num']
594
+ actual["section_number"] = key
595
+ actual["actual_coords"] = ""
596
+ actual_list.append(actual)
597
+ changes = {}
598
+ #Changes JSON
599
+ changes["changed"] = result_agreement[key]['content']+' Analysis:New clause added'+'~!~addition'
600
+ changes["changed_page_number"] = result_agreement[key]['page_num']
601
+ changes["changed_section_number"] = key
602
+ changes["changed_coords"] = result_agreement[key]['coords']
603
+ changes_list.append(changes)
604
+
605
+ #changes_ui JSON
606
+ changes_ui ={}
607
+ changes_ui["changed"] = result_agreement[key]['content']+' Analysis:New clause added'+'~!~addition'
608
+ changes_ui["changed_page_number"] = result_agreement[key]['page_num']
609
+ changes_ui["changed_section_number"] = key
610
+ changes_ui["changed_coords"] = result_agreement[key]['coords']
611
+ changes_ui_list.append(changes_ui)
612
+
613
+ return changes_list,actual_list,changes_ui_list
614
+
615
+
616
+ deletion_prompt = """
617
+ {} : 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.
618
+ """
619
+
620
+ addition_prompt = """
621
+ {} : 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.
622
+ """
623
+
624
+
625
+ def remove_analysis(text: str) -> str:
626
+ """
627
+ Remove the analysis portion from the given text.
628
+
629
+ Args:
630
+ text (str): The text to remove the analysis from.
631
+
632
+ Returns:
633
+ str: The text with the analysis portion removed.
634
+ """
635
+ new_text = re.sub(r"(Analysis.*)", "", text)
636
+ return new_text
637
+
638
+ 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]:
639
+ """
640
+ Generate a JSON output based on the provided inputs.
641
+
642
+ Args:
643
+ actual (List[Dict[str, str]]): The list of actual changes.
644
+ changes_ui (List[Dict[str, str]]): The list of UI changes.
645
+ file (str): The file path.
646
+ template_files (str): The template path.
647
+ result_template (str): The template result.
648
+ result_agreement (str): The agreement result.
649
+
650
+ Returns:
651
+ Dict[str, any]: The generated JSON output.
652
+ """
653
+ json_output = {}
654
+
655
+ json_output["input_file_path"] = file
656
+ comparison_list = []
657
+
658
+ for i in range(len(actual)):
659
+ actual_changes = '{}'
660
+ actual_changes_json = json.loads(actual_changes)
661
+ analysis_final = re.sub(r'\n', ' ', changes_ui[i]['changed'].split("~!~")[0].split("Analysis:")[1])
662
+ if changes_ui[i]['changed'].split('~!~')[-1] == 'addition' or changes_ui[i]['changed'].split('~!~')[-1] == 'missing':
663
+ continue
664
+ actual_changes_json.update({"actual": actual[i]['actual']})
665
+ actual_changes_json.update({"page_number": actual[i]['page_number']})
666
+ actual_changes_json.update({"section_number": actual[i]['section_number']})
667
+ actual_changes_json.update({"actual_coords": actual[i]['actual_coords']})
668
+ actual_changes_json.update({"changed": remove_analysis(changes_ui[i]["changed"])})
669
+ actual_changes_json.update({"changed_page_number": changes_ui[i]["changed_page_number"]})
670
+ actual_changes_json.update({"changed_section_number": changes_ui[i]["changed_section_number"]})
671
+ actual_changes_json.update({"changed_coords": changes_ui[i]["changed_coords"]})
672
+ actual_changes_json.update({"analysis": analysis_final})
673
+ actual_changes_json.update({"type_of_change": changes_ui[i]['changed'].split("~!~")[1]})
674
+ comparison_list.append(actual_changes_json)
675
+
676
+ for i in range(len(changes_ui)):
677
+ actual_changes = '{}'
678
+ actual_changes_json = json.loads(actual_changes)
679
+ if changes_ui[i]['changed'].split('~!~')[-1] == 'missing':
680
+ actual_changes_json.update({"actual": actual[i]['actual']})
681
+ actual_changes_json.update({"page_number": actual[i]['page_number']})
682
+ actual_changes_json.update({"section_number": actual[i]['section_number']})
683
+ actual_changes_json.update({"actual_coords": actual[i]['actual_coords']})
684
+ actual_changes_json.update({"changed": remove_analysis(changes_ui[i]["changed"])})
685
+ actual_changes_json.update({"changed_page_number": changes_ui[i]["changed_page_number"]})
686
+ actual_changes_json.update({"changed_section_number": changes_ui[i]["changed_section_number"]})
687
+ actual_changes_json.update({"changed_coords": changes_ui[i]["changed_coords"]})
688
+ final_deletion_prompt = deletion_prompt.format(actual[i]['actual'])
689
+ actual_changes_json.update({"analysis": open_ai(final_deletion_prompt)})
690
+ actual_changes_json.update({"type_of_change": "missing"})
691
+ comparison_list.append(actual_changes_json)
692
+ if changes_ui[i]['changed'].split('~!~')[-1] == 'addition':
693
+ actual_changes_json.update({"actual": actual[i]['actual']})
694
+ actual_changes_json.update({"page_number": actual[i]['page_number']})
695
+ actual_changes_json.update({"section_number": actual[i]['section_number']})
696
+ actual_changes_json.update({"actual_coords": actual[i]['actual_coords']})
697
+ actual_changes_json.update({"changed": remove_analysis(changes_ui[i]["changed"])})
698
+ actual_changes_json.update({"changed_page_number": changes_ui[i]["changed_page_number"]})
699
+ actual_changes_json.update({"changed_section_number": changes_ui[i]["changed_section_number"]})
700
+ actual_changes_json.update({"changed_coords": changes_ui[i]["changed_coords"]})
701
+ final_addition_prompt = addition_prompt.format(changes_ui[i]["changed"])
702
+ actual_changes_json.update({"analysis": open_ai(final_addition_prompt)})
703
+ actual_changes_json.update({"type_of_change": "addition"})
704
+ comparison_list.append(actual_changes_json)
705
+
706
+ json_output["changes"] = comparison_list
707
+
708
+ # Sort the data based on the "actual" key in ascending order
709
+ sorted_data = sorted(json_output["changes"], key=lambda x: split_page_section(x["page_number"], x["section_number"]))
710
+
711
+ # Update the JSON data with the sorted_data
712
+ json_output["changes"] = sorted_data
713
+ return json_output
714
+
715
+ def process_files_template(file: str) -> List[str]:
716
+ """
717
+ Process the template file and extract sections.
718
+
719
+ Args:
720
+ file (str): The path of the template file.
721
+
722
+ Returns:
723
+ List[str]: The extracted sections from the template file.
724
+ """
725
+ try:
726
+ # Set the header and footer heights
727
+ header_height = 50
728
+ footer_height = 80
729
+
730
+ # Extract sections from the file
731
+ sections = extract_sections(file, header_height, footer_height)
732
+ print("Template:",sections)
733
+ return sections
734
+
735
+ except Exception as e:
736
+ # Create a logger
737
+ logger = logging.getLogger(__name__)
738
+ logger.error(f"Error processing template file: {str(e)}")
739
+ raise
740
+
741
+ def process_files_original(file: str) -> List[str]:
742
+ """
743
+ Process the original file and extract sections.
744
+
745
+ Args:
746
+ file (str): The path of the original file.
747
+
748
+ Returns:
749
+ List[str]: The extracted sections from the original file.
750
+ """
751
+ try:
752
+ # Set the header and footer heights
753
+ header_height = 50
754
+ footer_height = 80
755
+
756
+ # Extract sections from the file
757
+ sections = extract_sections(file, header_height, footer_height)
758
+ print("Original:",sections)
759
+ return sections
760
+
761
+ except Exception as e:
762
+ # Create a logger
763
+ logger = logging.getLogger(__name__)
764
+ logger.error(f"Error processing original file: {str(e)}")
765
+ raise
766
+
767
+
768
+
769
+
770
+ def main_processing_function(file_path: str, template_path: str):
771
+ """
772
+ Processes the provided PDF file and its template to identify and report changes.
773
+
774
+ Args:
775
+ file_path (str): Path to the PDF file to be processed.
776
+ template_path (str): Path to the corresponding template PDF file.
777
+
778
+ Returns:
779
+ dict: A dictionary containing the processed results and change analysis.
780
+ """
781
+ logger = logging.getLogger(__name__)
782
+
783
+ try:
784
+ # Process the original PDF file
785
+ result_agreement = process_files_original(file_path)
786
+
787
+ # Process the template PDF file
788
+ result_template = process_files_template(template_path)
789
+
790
+ # Compare the sections extracted from the original and template files
791
+ changes, actual, changes_ui = process_comparisons(result_agreement, result_template)
792
+
793
+ # Generate a JSON output summarizing the changes
794
+ final_output = json_output(actual, changes_ui, file_path, template_path, result_template, result_agreement)
795
+
796
+ return final_output
797
+
798
+ except Exception as e:
799
+ logger.error(f"Error processing files: {e}")
800
+ raise Exception(f"Error during file processing: {str(e)}")
801
+
802
+
803
+ # Streamlit UI integration for the application
804
+
805
+
806
+ def main():
807
+ st.set_page_config(layout="wide") # Set the layout to wide mode
808
+ st.title('PDF Document Processor')
809
+
810
+ # File uploaders for the agreement and template documents
811
+ uploaded_agreement = st.file_uploader("Upload the PDF Agreement", type=['pdf'])
812
+ uploaded_template = st.file_uploader("Upload the PDF Template", type=['pdf'])
813
+
814
+ if uploaded_agreement and uploaded_template:
815
+ # Save the uploaded files temporarily for processing
816
+ with NamedTemporaryFile(delete=False, suffix=".pdf", mode='wb') as temp_agreement:
817
+ temp_agreement.write(uploaded_agreement.read())
818
+ agreement_path = temp_agreement.name
819
+
820
+ with NamedTemporaryFile(delete=False, suffix=".pdf", mode='wb') as temp_template:
821
+ temp_template.write(uploaded_template.read())
822
+ template_path = temp_template.name
823
+
824
+ # Process the files and display the results
825
+ try:
826
+ result = main_processing_function(agreement_path, template_path)
827
+ st.success("Files successfully processed!")
828
+
829
+ # Convert the result dictionary to a DataFrame
830
+ df_changes = pd.DataFrame(result['changes'])
831
+ df_changes = df_changes[['section_number', 'page_number', 'actual', 'changed', 'analysis', 'type_of_change']]
832
+
833
+ # Display the DataFrame in the UI
834
+ st.dataframe(df_changes, height=600) # You can adjust height based on your needs
835
+
836
+ # Convert DataFrame to CSV for download
837
+ csv = df_changes.to_csv(index=False)
838
+ b64 = base64.b64encode(csv.encode()).decode() # some browsers need base64 encoding
839
+ href = f'<a href="data:file/csv;base64,{b64}" download="document_changes.csv">Download CSV File</a>'
840
+ st.markdown(href, unsafe_allow_html=True)
841
+
842
+ except Exception as e:
843
+ st.error(f"Error processing files: {e}")
844
+ finally:
845
+ # Clean up temporary files after processing
846
+ os.remove(agreement_path)
847
+ os.remove(template_path)
848
+
849
+ if __name__ == "__main__":
850
+ main()
851
+