HaiderAUT commited on
Commit
0e1a3bd
Β·
verified Β·
1 Parent(s): cfc4f6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -98
app.py CHANGED
@@ -17,47 +17,43 @@ from PyPDF2 import PdfReader # plain text extraction
17
  import gradio as gr # UI
18
  from dotenv import load_dotenv # optional .env support
19
 
 
20
  # ─────────────────────────────────────────────────────────────────────────────
21
- # 1. PDF & TEXT PROCESSING (LOGIC MODIFIED HERE)
22
  # ─────────────────────────────────────────────────────────────────────────────
23
 
24
  def extract_pdf_text(pdf_file) -> str:
25
  """Extracts text from a PDF file using PyPDF2."""
26
  reader = PdfReader(pdf_file)
27
- # MODIFICATION: Skips the first 4 pages (ToC/List of Rules)
28
- return "\n".join(p.extract_text() or "" for i, p in enumerate(reader.pages) if i >= 4)
29
 
30
 
31
  def extract_pdf_word(pdf_file) -> str:
32
  """Extracts text from PDF using PyMuPDF (fitz) for better layout preservation."""
33
  doc = fitz.open(pdf_file)
34
- # MODIFICATION: Skips the first 4 pages (ToC)
35
- text_blocks = [page.get_text("text") for i, page in enumerate(doc) if i >= 4]
36
  return "\n".join(filter(None, text_blocks))
37
 
38
 
39
  def merge_pdf_wrapped_lines(raw_text: str) -> list[str]:
40
- """Re-join hard-wrapped lines from PDF extraction based on grammatical context."""
41
  merged = []
42
  for ln in raw_text.splitlines():
43
  ln_stripped = ln.strip()
44
- if not ln_stripped:
45
- continue
46
-
47
  if merged:
48
  prev = merged[-1]
49
- # Merge if previous line ends with 'β€”' or lacks closing punctuation,
50
- # and the next line appears to be a continuation.
51
- if prev.endswith('β€”') or \
52
- (not re.search(r'[.:;)]\s*$', prev) and re.match(r'^[a-z\(]', ln_stripped)):
53
- merged[-1] = prev + ' ' + ln_stripped
54
  continue
55
  merged.append(ln_stripped)
56
  return merged
57
 
58
 
59
  # ─────────────────────────────────────────────────────────────────────────────
60
- # 2. RULE PARSING & CLEANING (LOGIC MODIFIED HERE)
61
  # ─────────────────────────────────────────────────────────────────────────────
62
 
63
  # --- Regex for rule structure ---
@@ -73,9 +69,6 @@ subpart_pat = re.compile(
73
  r'^\s*\d+\.\s*Subpart\s+([A-Z]{1,2})\s*[β€”-]\s*(.+)$',
74
  re.IGNORECASE
75
  )
76
- # NEW: Regex to specifically identify sub-rule paragraphs like (a), (1), (i)
77
- sub_rule_pat = re.compile(r'^\s*(\((?:[a-z]{1,2}|[ivx]+|\d+)\))\s*(.*)', re.IGNORECASE)
78
-
79
 
80
  # --- Regex for cleaning ---
81
  page_pat = re.compile(r'Page\s+\d+\s*/\s*\d+', re.IGNORECASE)
@@ -104,89 +97,53 @@ def clean_line(line: str, source: str) -> str:
104
  line = re.sub(r'\s{2,}', ' ', line)
105
  return line.strip()
106
 
107
- def get_rule_level(paren_str):
108
- """Determines nesting level of a sub-rule, e.g., (1) is 1, (a) is 2, (i) is 3."""
109
- content = paren_str.strip('()').lower()
110
- if not content: return 99
111
- if content.isdigit(): return 1
112
- if all(c in 'ivxlmc' for c in content): return 3 # roman numerals
113
- if content.isalpha(): return 2 # alphabetical
114
- return 4 # Unknown level, treat as deeply nested
115
 
116
  def parse_rules(text: str, source: str) -> dict[str, str]:
117
- """
118
- Parses raw text into a dictionary of {rule_id: rule_text}.
119
- This version is stateful and context-aware to handle hierarchies correctly.
120
- """
121
- rules = {}
122
- parent_parts = [] # Tracks the current rule hierarchy, e.g., ['108.51', '(3)']
123
- lines_buffer = []
124
-
125
- def commit_buffer():
126
- """Saves the buffered lines to the current rule ID."""
127
- if parent_parts and lines_buffer:
128
- rule_id = "".join(parent_parts)
129
- existing_text = rules.get(rule_id, "")
130
- new_text = " ".join(lines_buffer)
131
- rules[rule_id] = (existing_text + " " + new_text).strip()
132
- lines_buffer.clear()
133
 
134
  lines = merge_pdf_wrapped_lines(text)
135
 
136
- for line in lines:
137
- cleaned = clean_line(line, source)
138
- if not cleaned: continue
139
-
140
- m_main = rule_pat.match(cleaned)
141
- m_sub = sub_rule_pat.match(cleaned)
142
- m_sp = subpart_pat.match(cleaned)
143
-
144
- if m_sp:
145
- commit_buffer()
146
- parent_parts = [f"subpart-{m_sp.group(1).upper()}"]
147
- rules["".join(parent_parts)] = f"Subpart {m_sp.group(1).upper()} β€” {m_sp.group(2).strip()}"
148
-
149
- elif m_main:
150
- new_base_id = m_main.group('base_rule')
151
- current_base_id = parent_parts[0] if parent_parts and not parent_parts[0].startswith("subpart") else None
152
-
153
- if new_base_id == current_base_id:
154
- lines_buffer.append(cleaned)
155
- continue
156
-
157
- commit_buffer()
158
- parent_parts = [new_base_id]
159
- title = m_main.group('title').strip()
 
 
 
 
 
160
  if title:
161
- rules["".join(parent_parts)] = title
162
-
163
- elif m_sub and parent_parts and not parent_parts[0].startswith("subpart"):
164
- commit_buffer()
165
- paren_part = m_sub.group(1)
166
- text_part = m_sub.group(2).strip()
167
- new_level = get_rule_level(paren_part)
168
-
169
- while len(parent_parts) > 1:
170
- last_part = parent_parts[-1]
171
- last_level = get_rule_level(last_part)
172
- if last_level >= new_level:
173
- parent_parts.pop()
174
- else:
175
- break
176
-
177
- parent_parts.append(paren_part)
178
- if text_part:
179
- lines_buffer.append(text_part)
180
 
181
- else:
182
- lines_buffer.append(cleaned)
183
-
184
- commit_buffer()
185
- return {k: v for k, v in rules.items() if v}
186
 
187
 
188
  # ─────────────────────────────────────────────────────────────────────────────
189
- # 3. COMPARISON & UI LOGIC (LOGIC MODIFIED HERE)
190
  # ─────────────────────────────────────────────────────────────────────────────
191
 
192
  def diff_unified(one: str, caa: str) -> str:
@@ -223,16 +180,14 @@ def combined_sort_key(key: str):
223
  else:
224
  return (4, key)
225
 
226
- # MODIFICATION: More robust splitting for hierarchical keys like "108.51(3)(i)"
227
- parts = re.split(r'(\d+\.\d+)|(\([a-zA-Z0-9]+\))', key)
228
  parts = [p for p in parts if p]
229
 
230
  for part in parts:
231
- num_match = re.match(r'^\d+\.\d+$', part)
232
- if num_match:
233
- sortable_tuple += tuple( (1, int(x)) for x in part.split('.'))
234
  else:
235
- sortable_tuple += ((2, part.lower()),)
236
  return sortable_tuple
237
 
238
 
@@ -263,6 +218,7 @@ def save_clean_and_dirty_versions(dirty_one, dirty_caa, clean_one, clean_caa, fi
263
  return filename
264
 
265
 
 
266
  def stage1_process_and_review(part, onereg_pdf, caa_pdf):
267
  if not (onereg_pdf and caa_pdf):
268
  raise gr.Error("Please upload both PDF files.")
@@ -306,6 +262,7 @@ def stage1_process_and_review(part, onereg_pdf, caa_pdf):
306
  raise gr.Error(f"Failed during initial processing: {e}")
307
 
308
 
 
309
  def stage2_finalize_and_compare(review_df, original_one, original_caa):
310
  if review_df is None or review_df.empty:
311
  raise gr.Error("No data to compare. Please process the files first.")
@@ -360,7 +317,7 @@ def stage2_finalize_and_compare(review_df, original_one, original_caa):
360
 
361
 
362
  # ─────────────────────────────────────────────────────────────────────────────
363
- # 4. GRADIO UI LAYOUT (UI IS IDENTICAL TO YOUR ORIGINAL SCRIPT)
364
  # ─────────────────────────────────────────────────────────────────────────────
365
 
366
  with gr.Blocks(theme=gr.themes.Soft(), title="Dual Rule Cleaning Tool") as demo:
 
17
  import gradio as gr # UI
18
  from dotenv import load_dotenv # optional .env support
19
 
20
+
21
  # ─────────────────────────────────────────────────────────────────────────────
22
+ # 1. PDF & TEXT PROCESSING
23
  # ─────────────────────────────────────────────────────────────────────────────
24
 
25
  def extract_pdf_text(pdf_file) -> str:
26
  """Extracts text from a PDF file using PyPDF2."""
27
  reader = PdfReader(pdf_file)
28
+ return "\n".join(p.extract_text() or "" for p in reader.pages)
 
29
 
30
 
31
  def extract_pdf_word(pdf_file) -> str:
32
  """Extracts text from PDF using PyMuPDF (fitz) for better layout preservation."""
33
  doc = fitz.open(pdf_file)
34
+ text_blocks = [page.get_text("text") for page in doc]
 
35
  return "\n".join(filter(None, text_blocks))
36
 
37
 
38
  def merge_pdf_wrapped_lines(raw_text: str) -> list[str]:
39
+ """Re-join hard-wrapped lines from PDF extraction."""
40
  merged = []
41
  for ln in raw_text.splitlines():
42
  ln_stripped = ln.strip()
43
+ if not ln_stripped: continue
 
 
44
  if merged:
45
  prev = merged[-1]
46
+ if (re.search(r'[a-z]$', prev) and re.match(r'^[\(a-z]', ln_stripped)) or \
47
+ (re.search(r'\b(?:rule|may|and|or)$', prev, re.I) and re.match(r'^\d+\.\d+', ln_stripped)) or \
48
+ (re.search(r'\brule\s+\d+\.$', prev, re.I) and re.match(r'^\d', ln_stripped)):
49
+ merged[-1] = prev + (' ' if re.search(r'[a-z]$', prev) else '') + ln_stripped
 
50
  continue
51
  merged.append(ln_stripped)
52
  return merged
53
 
54
 
55
  # ─────────────────────────────────────────────────────────────────────────────
56
+ # 2. RULE PARSING & CLEANING (Initial Automated Pass)
57
  # ─────────────────────────────────────────────────────────────────────────────
58
 
59
  # --- Regex for rule structure ---
 
69
  r'^\s*\d+\.\s*Subpart\s+([A-Z]{1,2})\s*[β€”-]\s*(.+)$',
70
  re.IGNORECASE
71
  )
 
 
 
72
 
73
  # --- Regex for cleaning ---
74
  page_pat = re.compile(r'Page\s+\d+\s*/\s*\d+', re.IGNORECASE)
 
97
  line = re.sub(r'\s{2,}', ' ', line)
98
  return line.strip()
99
 
 
 
 
 
 
 
 
 
100
 
101
  def parse_rules(text: str, source: str) -> dict[str, str]:
102
+ """Parses raw text into a dictionary of {rule_id: rule_text}."""
103
+ rules, current, title = {}, None, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  lines = merge_pdf_wrapped_lines(text)
106
 
107
+ for raw_line in lines:
108
+ line = clean_line(raw_line, source)
109
+ if not line: continue
110
+
111
+ m_ap_item = appendix_item_pat.match(line)
112
+ m_sp = subpart_pat.match(line)
113
+ m_rule = rule_pat.match(line)
114
+
115
+ new_key = None
116
+ new_title = ""
117
+
118
+ if m_ap_item:
119
+ key_parts = [m_ap_item.group(1).upper(), m_ap_item.group(2)]
120
+ if m_ap_item.group(3): key_parts.append(f"({m_ap_item.group(3).strip()})")
121
+ new_key = ".".join(key_parts)
122
+ new_title = m_ap_item.group('title').strip()
123
+ elif m_sp:
124
+ new_key = f"subpart-{m_sp.group(1).upper()}"
125
+ new_title = f"Subpart {m_sp.group(1).upper()} β€” {m_sp.group(2).strip()}"
126
+ elif m_rule:
127
+ base = m_rule.group('base_rule')
128
+ parens_str = m_rule.group('parens') or ""
129
+ new_key = base + "".join(re.findall(r'\([^)]+\)', parens_str))
130
+ new_title = m_rule.group('title').strip()
131
+
132
+ if new_key:
133
+ current = new_key
134
+ title = new_title
135
+ rules.setdefault(current, [])
136
  if title:
137
+ rules[current].append(title)
138
+ elif current:
139
+ if not title or line.lower() != title.lower():
140
+ rules[current].append(line)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
+ return {k: " ".join(v).strip() for k, v in rules.items()}
 
 
 
 
143
 
144
 
145
  # ─────────────────────────────────────────────────────────────────────────────
146
+ # 3. COMPARISON & UI LOGIC
147
  # ─────────────────────────────────────────────────────────────────────────────
148
 
149
  def diff_unified(one: str, caa: str) -> str:
 
180
  else:
181
  return (4, key)
182
 
183
+ parts = re.split(r'[.()]', key)
 
184
  parts = [p for p in parts if p]
185
 
186
  for part in parts:
187
+ if part.isdigit():
188
+ sortable_tuple += ((1, int(part)),)
 
189
  else:
190
+ sortable_tuple += ((2, part.lower()),)
191
  return sortable_tuple
192
 
193
 
 
218
  return filename
219
 
220
 
221
+ # --- STAGE 1: Process PDFs and prepare for user review ---
222
  def stage1_process_and_review(part, onereg_pdf, caa_pdf):
223
  if not (onereg_pdf and caa_pdf):
224
  raise gr.Error("Please upload both PDF files.")
 
262
  raise gr.Error(f"Failed during initial processing: {e}")
263
 
264
 
265
+ # --- STAGE 2: Take user-cleaned text and perform the final comparison ---
266
  def stage2_finalize_and_compare(review_df, original_one, original_caa):
267
  if review_df is None or review_df.empty:
268
  raise gr.Error("No data to compare. Please process the files first.")
 
317
 
318
 
319
  # ─────────────────────────────────────────────────────────────────────────────
320
+ # 4. GRADIO UI LAYOUT
321
  # ─────────────────────────────────────────────────────────────────────────────
322
 
323
  with gr.Blocks(theme=gr.themes.Soft(), title="Dual Rule Cleaning Tool") as demo: