deveos commited on
Commit
0be9bd5
·
verified ·
1 Parent(s): 50a756d

Upload 4 files

Browse files
Files changed (3) hide show
  1. README.md +15 -3
  2. app.py +218 -164
  3. requirements.txt +3 -4
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Bank Statement JSON Extractor
3
  emoji: 📄
4
  colorFrom: blue
5
  colorTo: purple
@@ -10,6 +10,18 @@ app_file: app.py
10
  pinned: false
11
  ---
12
 
13
- # Bank Statement JSON Extractor
14
 
15
- Fast PDF bank statement to JSON transaction extractor.
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: MinerU Bank Statement JSON Extractor
3
  emoji: 📄
4
  colorFrom: blue
5
  colorTo: purple
 
10
  pinned: false
11
  ---
12
 
13
+ # MinerU Bank Statement JSON Extractor
14
 
15
+ Upload bank statement PDF and extract clean transaction JSON.
16
+
17
+ Output fields:
18
+
19
+ ```json
20
+ {
21
+ "date": "",
22
+ "narration": "",
23
+ "voucher_type": "Payment/Receipt",
24
+ "amount": "",
25
+ "closing_balance": ""
26
+ }
27
+ ```
app.py CHANGED
@@ -1,187 +1,241 @@
1
-
2
  import re
3
  import json
 
4
  import tempfile
5
- from datetime import datetime
6
- from typing import Any, List, Dict
7
 
8
  import gradio as gr
9
- import pdfplumber
10
-
11
-
12
- MONTHS = {
13
- "Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04",
14
- "May": "05", "Jun": "06", "Jul": "07", "Aug": "08",
15
- "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12",
16
- }
17
 
 
 
 
18
 
19
- def clean_cell(value: Any) -> str:
20
- if value is None:
21
- return ""
22
- return re.sub(r"\s+", " ", str(value).replace("\n", " ")).strip()
23
 
24
-
25
- def clean_date(value: str) -> str:
26
- value = clean_cell(value)
27
- # Fix Apr/01/202 4 -> Apr/01/2024
28
- value = re.sub(r"(\d{3})\s+(\d)$", r"\1\2", value)
29
- m = re.search(r"\b([A-Za-z]{3})/(\d{1,2})/(\d{4})\b", value)
30
  if not m:
31
- return ""
32
  mon, day, year = m.groups()
33
- mon = mon[:3].title()
34
- if mon not in MONTHS:
35
- return ""
36
- return f"{year}-{MONTHS[mon]}-{int(day):02d}"
37
 
38
 
39
- def clean_amount(value: str) -> str:
40
- """
41
- Fix:
42
- 650000 0.0 Dr -> 6500000.00
43
- 648820 2.04 Dr -> 6488202.04
44
- 11962.9 6 Cr -> 11962.96
45
- 45.0 Dr -> 45.00
46
- """
47
- value = clean_cell(value)
48
- value = re.sub(r"\b(Cr|Dr)\b", "", value, flags=re.I).strip()
49
- value = re.sub(r"[^0-9.\s,-]", "", value).replace(",", "")
50
- value = re.sub(r"\s+", "", value)
51
- if not value:
52
- return ""
53
- # keep first numeric-looking value after removing spaces
54
- m = re.search(r"-?\d+(?:\.\d+)?", value)
55
- if not m:
56
- return ""
57
- num = m.group(0)
58
  try:
59
- return f"{float(num):.2f}"
60
  except Exception:
61
- return num
62
-
63
-
64
- def clean_balance(value: str) -> str:
65
- raw = clean_cell(value)
66
- suffix = ""
67
- if re.search(r"\bDr\b", raw, re.I):
68
- suffix = " Dr"
69
- elif re.search(r"\bCr\b", raw, re.I):
70
- suffix = " Cr"
71
- amt = clean_amount(raw)
72
- return (amt + suffix).strip() if amt else ""
73
-
74
-
75
- def clean_narration(value: str) -> str:
76
- text = clean_cell(value)
77
- # Fix broken account holder name in this bank format
78
- text = text.replace("SHARDAP RASAD", "SHARDAPRASAD")
79
- text = text.replace("PARASHA R", "PARASHAR")
80
- text = text.replace("Maintainanc e", "Maintenance")
81
- text = re.sub(r"\b(\d+)\s+(\d+)\b", r"\1\2", text)
82
- text = re.sub(r"\s*/\s*", "/", text)
83
- return text.strip()
84
-
85
-
86
- def is_header_row(row: List[str]) -> bool:
87
- joined = " ".join(row).lower()
88
- return "txn date" in joined and "narration" in joined
89
-
90
-
91
- def parse_pdfplumber_tables(pdf_path: str) -> List[Dict[str, str]]:
92
- txns: List[Dict[str, str]] = []
93
-
94
- with pdfplumber.open(pdf_path) as pdf:
95
- for page in pdf.pages:
96
- tables = page.extract_tables({
97
- "vertical_strategy": "lines",
98
- "horizontal_strategy": "lines",
99
- "intersection_tolerance": 5,
100
- "snap_tolerance": 3,
101
- "join_tolerance": 3,
102
- }) or page.extract_tables()
103
-
104
- for table in tables or []:
105
- if not table:
106
- continue
107
-
108
- for row in table:
109
- cells = [clean_cell(c) for c in row]
110
- if not cells or is_header_row(cells):
111
- continue
112
-
113
- # Expected Vidarbha columns:
114
- # 0 TXN Date, 1 Value Date, 2 Narration, 3 Ref, 4 Mode, 5 Branch, 6 Debit, 7 Credit, 8 Balance
115
- if len(cells) < 9:
116
- continue
117
-
118
- date = clean_date(cells[0])
119
- if not date:
120
- continue
121
-
122
- narration = clean_narration(cells[2])
123
- if not narration or "opening balance" in narration.lower():
124
- continue
125
-
126
- debit = clean_amount(cells[6])
127
- credit = clean_amount(cells[7])
128
- balance = clean_balance(cells[8])
129
-
130
- if debit:
131
- voucher_type = "Payment"
132
- amount = debit
133
- elif credit:
134
- voucher_type = "Receipt"
135
- amount = credit
136
- else:
137
- continue
138
-
139
- txns.append({
140
- "date": date,
141
- "narration": narration,
142
- "voucher_type": voucher_type,
143
- "amount": amount,
144
- "closing_balance": balance,
145
- })
146
-
147
- return txns
148
-
149
-
150
- def extract_transactions(pdf_file):
151
- if pdf_file is None:
152
- return "[]", {"success": False, "error": "Upload PDF first"}
153
 
154
- try:
155
- pdf_path = pdf_file.name if hasattr(pdf_file, "name") else str(pdf_file)
156
- transactions = parse_pdfplumber_tables(pdf_path)
157
-
158
- result = {
159
- "success": True,
160
- "count": len(transactions),
161
- "transactions": transactions,
162
- }
163
- return json.dumps(transactions, ensure_ascii=False, indent=2), result
164
- except Exception as e:
165
- result = {
166
- "success": False,
167
- "error": str(e),
168
- "transactions": [],
169
- }
170
- return json.dumps([], indent=2), result
171
 
 
 
 
 
172
 
173
- with gr.Blocks(title="Bank Statement JSON Extractor") as demo:
174
- gr.Markdown("# Bank Statement PDF → Transaction JSON")
175
- gr.Markdown("Fast test app. Output fields: `date`, `narration`, `voucher_type`, `amount`, `closing_balance`.")
176
 
177
- with gr.Row():
178
- pdf = gr.File(label="Upload Bank Statement PDF", file_types=[".pdf"])
179
- btn = gr.Button("Extract Transactions", variant="primary")
 
 
 
 
 
 
 
 
180
 
181
- json_out = gr.Code(label="Transactions JSON", language="json", lines=20)
182
- status = gr.JSON(label="Status")
183
 
184
- btn.click(extract_transactions, inputs=[pdf], outputs=[json_out, status])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
  if __name__ == "__main__":
187
  demo.launch()
 
1
+ import os
2
  import re
3
  import json
4
+ import time
5
  import tempfile
6
+ from typing import Any, Dict, List, Optional, Tuple
 
7
 
8
  import gradio as gr
9
+ import requests
10
+ from pypdf import PdfReader
 
 
 
 
 
 
11
 
12
+ DATE_RE = re.compile(r"\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/\d{1,2}/\d{4}\b", re.I)
13
+ NUM_RE = re.compile(r"(?<!\d)(\d[\d,]*(?:\.\d+)?)\s*(Cr|Dr)?\b", re.I)
14
+ MONTHS = {"jan":1,"feb":2,"mar":3,"apr":4,"may":5,"jun":6,"jul":7,"aug":8,"sep":9,"oct":10,"nov":11,"dec":12}
15
 
 
 
 
 
16
 
17
+ def normalize_date(s: str) -> str:
18
+ m = re.match(r"([A-Za-z]{3})/(\d{1,2})/(\d{4})", s.strip())
 
 
 
 
19
  if not m:
20
+ return s.strip()
21
  mon, day, year = m.groups()
22
+ return f"{int(year):04d}-{MONTHS[mon.lower()]:02d}-{int(day):02d}"
 
 
 
23
 
24
 
25
+ def clean_number(s: str) -> str:
26
+ s = str(s or "").replace(",", "")
27
+ s = re.sub(r"\s+", "", s)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  try:
29
+ return f"{float(s):.2f}"
30
  except Exception:
31
+ return s
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ def clean_balance(num: str, sign: str = "") -> str:
35
+ val = clean_number(num)
36
+ sign = (sign or "").strip().title()
37
+ return f"{val} {sign}".strip()
38
 
 
 
 
39
 
40
+ def remove_noise(text: str) -> str:
41
+ text = re.sub(r"\s+", " ", text or " ").strip()
42
+ noise = [
43
+ "Vidarbha Merchants Urban Co-op Bank Ltd.", "Vidarbha Merchants Urban Co-op Bank", "Account Statement",
44
+ "TXN Date", "Value Date", "Narration", "ReferenceNo", "ChequeNo", "Refere nceNo", "Tr Mode",
45
+ "Branch Code", "Branc h Code", "Debit", "Credit", "Balance", "Balan ce", "Balanc e",
46
+ ]
47
+ for n in noise:
48
+ text = text.replace(n, " ")
49
+ text = re.sub(r"\s+", " ", text).strip()
50
+ return text
51
 
 
 
52
 
53
+ def extract_text_local(pdf_path: str) -> str:
54
+ reader = PdfReader(pdf_path)
55
+ pages = []
56
+ for p in reader.pages:
57
+ pages.append(p.extract_text() or "")
58
+ return "\n".join(pages)
59
+
60
+
61
+ def try_mineru_agent(pdf_path: str, base_url: str, timeout: int = 180) -> Tuple[Optional[str], str]:
62
+ """Call MinerU Agent style API. Base URL must be set by user.
63
+ Supports common response shapes and async polling URLs/ids.
64
+ """
65
+ base_url = (base_url or os.getenv("MINERU_API_BASE") or "").strip().rstrip("/")
66
+ if not base_url:
67
+ return None, "MinerU base URL not set. Used local fallback."
68
+
69
+ upload_url = base_url
70
+ if not upload_url.endswith("/api/v1/agent/parse/file"):
71
+ upload_url = base_url + "/api/v1/agent/parse/file"
72
+
73
+ try:
74
+ with open(pdf_path, "rb") as f:
75
+ files = {"file": (os.path.basename(pdf_path), f, "application/pdf")}
76
+ r = requests.post(upload_url, files=files, timeout=60)
77
+ r.raise_for_status()
78
+ data = r.json() if "json" in r.headers.get("content-type", "").lower() else {"text": r.text}
79
+ except Exception as e:
80
+ return None, f"MinerU upload failed: {e}. Used local fallback."
81
+
82
+ # Direct markdown/text response
83
+ direct = find_text_in_obj(data)
84
+ if direct and len(direct) > 80:
85
+ return direct, "MinerU direct result used."
86
+
87
+ task_id = data.get("task_id") or data.get("taskId") or data.get("id") or data.get("data", {}).get("task_id") or data.get("data", {}).get("taskId")
88
+ poll_url = data.get("poll_url") or data.get("result_url") or data.get("data", {}).get("poll_url") or data.get("data", {}).get("result_url")
89
+ if not poll_url and task_id:
90
+ poll_url = base_url.rsplit("/api/v1/agent/parse/file", 1)[0].rstrip("/") + f"/api/v1/agent/task/{task_id}"
91
+ if not poll_url:
92
+ return None, "MinerU did not return markdown or task id. Used local fallback."
93
+
94
+ start = time.time()
95
+ last = None
96
+ while time.time() - start < timeout:
97
+ try:
98
+ rr = requests.get(poll_url, timeout=30)
99
+ rr.raise_for_status()
100
+ last = rr.json() if "json" in rr.headers.get("content-type", "").lower() else {"text": rr.text}
101
+ status = str(last.get("status") or last.get("data", {}).get("status") or "").lower()
102
+ found = find_text_in_obj(last)
103
+ if found and (status in ("done", "completed", "success", "") or len(found) > 80):
104
+ return found, "MinerU async result used."
105
+ if status in ("failed", "error"):
106
+ return None, f"MinerU task failed: {last}. Used local fallback."
107
+ except Exception as e:
108
+ return None, f"MinerU polling failed: {e}. Used local fallback."
109
+ time.sleep(2)
110
+ return None, f"MinerU timeout. Last={last}. Used local fallback."
111
+
112
+
113
+ def find_text_in_obj(obj: Any) -> Optional[str]:
114
+ keys = {"markdown", "md", "text", "content", "result", "html"}
115
+ if isinstance(obj, str):
116
+ return obj
117
+ if isinstance(obj, dict):
118
+ for k, v in obj.items():
119
+ if k.lower() in keys and isinstance(v, str) and len(v.strip()) > 20:
120
+ return v
121
+ for v in obj.values():
122
+ res = find_text_in_obj(v)
123
+ if res:
124
+ return res
125
+ if isinstance(obj, list):
126
+ parts = [find_text_in_obj(x) for x in obj]
127
+ parts = [p for p in parts if p]
128
+ if parts:
129
+ return "\n".join(parts)
130
+ return None
131
+
132
+
133
+ def split_records(text: str) -> List[str]:
134
+ text = remove_noise(text)
135
+ matches = list(DATE_RE.finditer(text))
136
+ records = []
137
+ for i, m in enumerate(matches):
138
+ d = m.group(0)
139
+ # Skip account From/To date labels by checking context before date
140
+ before = text[max(0, m.start()-20):m.start()].lower()
141
+ if "to date" in before or "from date" in before:
142
+ continue
143
+ end = matches[i+1].start() if i + 1 < len(matches) else len(text)
144
+ rec = text[m.start():end].strip()
145
+ if "Opening Balance" in rec:
146
+ continue
147
+ records.append(rec)
148
+ return records
149
+
150
+
151
+ def parse_vidarbha_record(rec: str) -> Optional[Dict[str, str]]:
152
+ dates = DATE_RE.findall(rec)
153
+ if not dates:
154
+ return None
155
+ txn_date = normalize_date(dates[0])
156
+ # remove first two dates (txn + value date) when present
157
+ body = rec
158
+ for d in dates[:2]:
159
+ body = body.replace(d, " ", 1)
160
+ body = re.sub(r"\s+", " ", body).strip()
161
+
162
+ # Find amounts with Cr/Dr markers. Last is balance, previous is txn amount.
163
+ pairs = [(m.group(1), (m.group(2) or ""), m.start(), m.end()) for m in NUM_RE.finditer(body)]
164
+ signed = [p for p in pairs if p[1]]
165
+ if len(signed) < 2:
166
+ return None
167
+
168
+ bal_num, bal_sign, bal_start, bal_end = signed[-1]
169
+ amt_num, amt_sign, amt_start, amt_end = signed[-2]
170
+
171
+ voucher_type = "Receipt" if amt_sign.lower() == "cr" else "Payment"
172
+ amount = clean_number(amt_num)
173
+ closing_balance = clean_balance(bal_num, bal_sign)
174
+
175
+ narration = body[:amt_start].strip()
176
+ # remove common ref/mode/code fragments at end
177
+ narration = re.sub(r"\b(?:SC:\s*\d+|\d{1,6})\s+(?:By Clg|To Trf)\s+\d{3,6}\s*$", "", narration, flags=re.I).strip()
178
+ narration = re.sub(r"\s+", " ", narration).strip(" -")
179
+ if not narration or narration.lower().startswith(("name :-", "branch name", "account number", "to date", "from date")):
180
+ return None
181
+
182
+ return {
183
+ "date": txn_date,
184
+ "narration": narration,
185
+ "voucher_type": voucher_type,
186
+ "amount": amount,
187
+ "closing_balance": closing_balance,
188
+ }
189
+
190
+
191
+ def extract_transactions_from_text(text: str) -> List[Dict[str, str]]:
192
+ out = []
193
+ seen = set()
194
+ for rec in split_records(text):
195
+ tx = parse_vidarbha_record(rec)
196
+ if not tx:
197
+ continue
198
+ key = tuple(tx.values())
199
+ if key not in seen:
200
+ seen.add(key)
201
+ out.append(tx)
202
+ return out
203
+
204
+
205
+ def process_pdf(pdf_file, mineru_base_url: str, use_mineru: bool):
206
+ if not pdf_file:
207
+ return {"success": False, "error": "Upload PDF first"}, ""
208
+ path = pdf_file.name if hasattr(pdf_file, "name") else str(pdf_file)
209
+ status = []
210
+ text = None
211
+ if use_mineru:
212
+ text, msg = try_mineru_agent(path, mineru_base_url)
213
+ status.append(msg)
214
+ if not text:
215
+ text = extract_text_local(path)
216
+ status.append("Local pypdf text extraction used.")
217
+
218
+ txs = extract_transactions_from_text(text)
219
+ result = {
220
+ "success": True,
221
+ "count": len(txs),
222
+ "transactions": txs,
223
+ }
224
+ return result, "\n".join(status) + "\n\n--- extracted text preview ---\n" + text[:2500]
225
+
226
+
227
+ with gr.Blocks(title="MinerU Bank JSON Extractor") as demo:
228
+ gr.Markdown("# MinerU Bank Statement → Transaction JSON")
229
+ gr.Markdown("Output only: `date`, `narration`, `voucher_type`, `amount`, `closing_balance`.")
230
+ with gr.Row():
231
+ pdf = gr.File(label="Upload bank statement PDF", file_types=[".pdf"])
232
+ with gr.Row():
233
+ use_mineru = gr.Checkbox(value=True, label="Use MinerU Agent API first")
234
+ mineru_url = gr.Textbox(label="MinerU API Base URL", placeholder="https://your-mineru-host.com", value=os.getenv("MINERU_API_BASE", ""))
235
+ btn = gr.Button("Extract JSON", variant="primary")
236
+ output = gr.JSON(label="Transactions JSON")
237
+ logs = gr.Textbox(label="Logs / Text preview", lines=14)
238
+ btn.click(process_pdf, inputs=[pdf, mineru_url, use_mineru], outputs=[output, logs])
239
 
240
  if __name__ == "__main__":
241
  demo.launch()
requirements.txt CHANGED
@@ -1,4 +1,3 @@
1
- pdfplumber==0.11.4
2
- pypdfium2==4.30.0
3
- pillow
4
- pyaudioop
 
1
+ requests>=2.31.0
2
+ pypdf>=4.2.0
3
+ pyaudioop>=0.2.0