-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
6272 lines (5597 loc) · 267 KB
/
app.py
File metadata and controls
6272 lines (5597 loc) · 267 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, request, jsonify, g, url_for, send_from_directory, send_file
import pdfplumber
import re
import json
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv() # Load environment variables from .env file
import os
from flask_cors import CORS
from werkzeug.middleware.proxy_fix import ProxyFix
import io
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, Frame, PageTemplate, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.lib.units import inch
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
from datetime import datetime
from reportlab.pdfgen import canvas
from extractors import index_and_extract, extract_and_store_from_indexed
from llm_sections import run_report_sections, compute_goal_sip, compute_regime_comparison
from db import (
list_sections,
list_metrics,
get_document_by_sha,
create_questionnaire,
update_questionnaire_status,
save_personal_info,
save_family_info,
save_goals,
save_risk_profile,
save_insurance,
save_estate,
save_lifestyle,
get_questionnaire,
get_latest_questionnaire_for_user,
link_questionnaire_upload,
list_questionnaire_uploads,
insert_metric,
delete_metrics_for_doc_keys,
update_questionnaire_upload_metadata,
get_user_by_firebase_uid,
create_or_update_user,
list_all_users,
delete_user,
set_user_credits,
get_user_count,
get_payment_history,
)
# Auth and Payment modules
from auth import require_auth, require_payment, consume_credit, verify_firebase_token, optional_auth, require_admin
from payment import (
create_razorpay_order,
verify_razorpay_signature,
verify_webhook_signature,
process_payment_captured,
get_payment_status,
get_report_price_paise,
)
# --- Logging Configuration ---
import logging
import uuid
# Configure basic logging (simplified for compatibility)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def _redact_pii(text: str) -> str:
"""Redact PII like PAN, account numbers, names from log output."""
if not text or not isinstance(text, str):
return str(text) if text else ""
redacted = text
# Redact PAN (format: ABCDE1234F)
redacted = re.sub(r'\b[A-Z]{5}\d{4}[A-Z]\b', 'PAN-XXXX', redacted)
# Redact account numbers (8-20 digits, possibly with X or *)
redacted = re.sub(r'\b[Xx\*\d]{8,20}\b', 'ACCT-XXXX', redacted)
# Redact Aadhaar (12 digits)
redacted = re.sub(r'\b\d{4}\s?\d{4}\s?\d{4}\b', 'AADHAAR-XXXX', redacted)
# Redact email addresses
redacted = re.sub(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', 'EMAIL-REDACTED', redacted)
# Redact phone numbers (10 digits, possibly with country code)
redacted = re.sub(r'(\+91[-\s]?)?\b\d{10}\b', 'PHONE-XXXX', redacted)
return redacted
def _log_extraction(doc_type: str, field: str, value, confidence: float = None, extra: dict = None):
"""Structured logging for extraction events with optional confidence."""
log_data = {
"doc_type": doc_type,
"field": field,
"value_preview": _redact_pii(str(value)[:100]) if value else None,
"confidence": confidence
}
if extra:
log_data.update(extra)
logger.info(f"Extracted {field}: {log_data}")
# --- Extraction Confidence Scoring ---
def _create_extraction_meta(field: str, value, source: str, pattern_idx: int = 0,
total_patterns: int = 1) -> dict:
"""
Create confidence metadata for an extracted field.
Args:
field: Field name being extracted
value: Extracted value
source: Source of extraction ('regex', 'llm', 'fallback')
pattern_idx: Index of matching pattern (0 = primary pattern, higher = fallback)
total_patterns: Total number of patterns tried
Returns:
Dict with confidence score (0.0-1.0) and needs_review flag
"""
if value is None or value == "N/A" or value == "":
return {
"confidence": 0.0,
"source": source,
"needs_review": True,
"reason": "No value extracted"
}
# Base confidence based on source
if source == "regex":
# Primary patterns = high confidence, fallback patterns = decreasing confidence
base_confidence = 0.95 - (pattern_idx * 0.1)
elif source == "llm":
base_confidence = 0.80 # LLM extractions are less certain
else:
base_confidence = 0.60 # Fallback/derived values
# Clamp to valid range
confidence = max(0.1, min(0.99, base_confidence))
return {
"confidence": round(confidence, 2),
"source": source,
"needs_review": confidence < 0.70,
"pattern_position": f"{pattern_idx + 1}/{total_patterns}" if source == "regex" else None
}
def _add_extraction_metadata(data: dict, field_meta: dict) -> None:
"""
Add extraction metadata to a data dict, creating _extraction_meta if needed.
Args:
data: The extraction result dict to modify
field_meta: Dict mapping field names to their confidence metadata
"""
if "_extraction_meta" not in data:
data["_extraction_meta"] = {}
data["_extraction_meta"].update(field_meta)
# --- Initialization ---
load_dotenv()
app = Flask(__name__)
CORS(app)
# Respect reverse proxy headers on Render (scheme/host) for correct external URLs
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
app.config['PREFERRED_URL_SCHEME'] = 'https'
openai_api_key = os.getenv("OPENAI_API_KEY")
if not openai_api_key:
raise RuntimeError("OPENAI_API_KEY is not set")
client = OpenAI(api_key=openai_api_key)
OUTPUT_DIR = os.getenv("OUTPUT_DIR", "output")
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Storage behavior:
# STORE_REPORTS = "disk" (default) -> write to OUTPUT_DIR and serve via /download/<file>
# STORE_REPORTS = "memory" -> do not persist; generate to disk, read once, delete, and offer one-time memory download via /download-temp/<token>
STORE_REPORTS = os.getenv("STORE_REPORTS", "disk").lower()
# SAVE_TX_JSON = "true"/"false" -> whether to persist extracted bank tx JSON artifacts
SAVE_TX_JSON = os.getenv("SAVE_TX_JSON", "false").lower() == "true"
# Simple in-memory store for ephemeral downloads
TEMP_REPORTS = {}
# --- Security: PDF Validation ---
MAX_PDF_SIZE_BYTES = 10 * 1024 * 1024 # 10MB limit
def _validate_pdf_file(file_bytes: bytes, filename: str = "upload.pdf") -> tuple:
"""
Validate a PDF file for security concerns.
Args:
file_bytes: Raw file content
filename: Original filename for logging
Returns:
(is_valid, error_message) tuple
"""
# Check file size
if len(file_bytes) > MAX_PDF_SIZE_BYTES:
return False, f"File too large ({len(file_bytes) / 1024 / 1024:.1f}MB). Maximum size is 10MB."
if len(file_bytes) < 4:
return False, "File is too small to be a valid PDF."
# Check PDF magic bytes (%PDF)
if not file_bytes[:4] == b'%PDF':
return False, "Invalid PDF format. File does not start with PDF header."
# Basic check for PDF end marker (%%EOF)
# Note: Some PDFs have trailing content after %%EOF, so we check the last 1024 bytes
if b'%%EOF' not in file_bytes[-1024:]:
logger.warning(f"PDF {_redact_pii(filename)} may be incomplete (no %%EOF marker found)")
# Don't fail validation, just log warning - some PDFs are valid without this
return True, None
def _sanitize_text_for_llm(text: str, max_length: int = 20000) -> str:
"""
Sanitize text before sending to LLM to prevent prompt injection.
Args:
text: Raw extracted text
max_length: Maximum text length to send to LLM
Returns:
Sanitized text string
"""
if not text:
return ""
# Truncate to max length
sanitized = text[:max_length]
# Remove potential prompt injection patterns (basic heuristic)
injection_patterns = [
r'(?i)ignore\s+(?:all\s+)?(?:previous|above)\s+instructions?',
r'(?i)you\s+are\s+now\s+(?:a|in)\s+(?:new|different)',
r'(?i)system\s*:\s*you\s+(?:are|will)',
r'(?i)<\s*/?system\s*>',
]
for pattern in injection_patterns:
sanitized = re.sub(pattern, '[FILTERED]', sanitized)
return sanitized
# Logo path - uses app directory for production compatibility
LOGO_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logo.png")
def _format_indian_amount(amount: float) -> str:
"""Format amount in Indian currency style (lakhs/crores) for compact display in PDFs."""
if amount is None or amount == 0:
return "0"
# Preserve negative sign for deficit/negative values
is_negative = amount < 0
amount = abs(amount)
prefix = "-" if is_negative else ""
if amount >= 1_00_00_000: # 1 crore
return f"{prefix}{amount / 1_00_00_000:.1f} Cr"
elif amount >= 1_00_000: # 1 lakh
return f"{prefix}{amount / 1_00_000:.1f} L"
elif amount >= 1000:
return f"{prefix}{amount / 1000:.1f} K"
else:
return f"{prefix}{int(round(amount))}"
def _register_temp_download(data: bytes, filename: str, mimetype: str = "application/pdf") -> str:
token = os.urandom(16).hex()
TEMP_REPORTS[token] = (filename, data, mimetype)
return token
def _persist_metrics_for_doc(document_id: int, data: dict):
"""
Persist key numeric insights from extracted data into metrics for aggregation/prefill.
Keys stored:
- opening_balance, closing_balance, total_inflows, total_outflows (bank)
- gross_total_income, taxable_income, total_tax_paid (ITR)
- sum_assured_or_insured (insurance)
- portfolio_equity/debt/gold/realEstate/insuranceLinked/cash (CAS allocation)
"""
if not isinstance(data, dict):
return
def n(v):
try:
if isinstance(v, (int, float)):
return float(v)
if v in (None, "", "N/A"):
return None
cv = clean_and_convert_to_float(str(v))
return cv if cv != "N/A" else None
except Exception:
return None
to_store = {}
# Bank account summary
acct = data.get("account_summary") or {}
for k in ["opening_balance", "closing_balance", "total_inflows", "total_outflows"]:
v = acct.get(k)
nv = n(v)
if nv is not None:
to_store[k] = nv
# ITR numbers (top-level or under tax_computation)
itr_top = {k: data.get(k) for k in ["gross_total_income", "taxable_income", "total_tax_paid"]}
tax_comp = data.get("tax_computation") or {}
for k in ["gross_total_income", "taxable_income", "total_tax_paid"]:
v = itr_top.get(k, None)
if v in (None, "", "N/A"):
v = tax_comp.get(k)
nv = n(v)
if nv is not None:
to_store[k] = nv
# Insurance
ins_sum = data.get("sum_assured_or_insured")
ins_nv = n(ins_sum)
if ins_nv is not None:
to_store["sum_assured_or_insured"] = ins_nv
# CAS allocation
alloc = data.get("asset_allocation") or {}
mapping = {
"equity_percentage": "portfolio_equity",
"debt_percentage": "portfolio_debt",
"gold_percentage": "portfolio_gold",
"real_estate_percentage": "portfolio_realEstate",
"insurance_linked_percentage": "portfolio_insuranceLinked",
"cash_percentage": "portfolio_cash",
# Support alternate keys if present
"equity": "portfolio_equity",
"debt": "portfolio_debt",
"gold": "portfolio_gold",
"realEstate": "portfolio_realEstate",
"insuranceLinked": "portfolio_insuranceLinked",
"cash": "portfolio_cash",
}
for src, dst in mapping.items():
if src in alloc:
nv = n(alloc.get(src))
if nv is not None:
to_store[dst] = nv
if to_store:
try:
delete_metrics_for_doc_keys(document_id, list(to_store.keys()))
except Exception:
pass
for k, v in to_store.items():
try:
insert_metric(document_id, k, v, None)
except Exception:
continue
# --- Utility Function for Cleaning Numbers ---
def clean_and_convert_to_float(value_str):
"""Cleans currency symbols, commas, and parentheses, then converts to float."""
if not value_str or value_str == "N/A":
return "N/A"
if isinstance(value_str, (int, float)):
return float(value_str)
if not isinstance(value_str, str):
return "N/A"
try:
# Remove currency symbols, commas, and whitespace
cleaned_str = re.sub(r'[₹$,\s]', '', value_str).strip()
# Handle negative numbers represented with parentheses
cleaned_str = re.sub(r'[\(\)]', '', cleaned_str)
if cleaned_str.endswith('-'):
cleaned_str = '-' + cleaned_str[:-1]
return float(cleaned_str) if cleaned_str else "N/A"
except (ValueError, TypeError):
return "N/A"
# PDF text sanitization helper to avoid unsupported glyphs
def sanitize_pdf_text(s):
try:
if s is None:
return ""
t = str(s)
# Normalize common unicode symbols to ASCII
t = (t.replace("•", "-")
.replace("–", "-")
.replace("—", "-")
.replace("×", "x")
.replace("₹", "Rs.")
.replace("“", '"')
.replace("”", '"')
.replace("’", "'")
.replace("‘", "'")
.replace("≈", "~"))
# Remove non-printable/non-ASCII chars (preserve tab/newline/carriage return + printable ASCII 0x20-0x7E)
t = re.sub(r"[^\t\n\r -~]", "", t)
# Collapse repeated dashes from earlier bullet normalization
t = re.sub(r"-{2,}", "-", t)
# Soft-break very long unbroken tokens to allow wrapping in PDF tables/paras
t = re.sub(r"([A-Za-z0-9:/\.\-_]{30})(?=[A-Za-z0-9:/\.\-_])", r"\1 ", t)
# Collapse whitespace
t = re.sub(r"\s+", " ", t).strip()
return t
except Exception:
return str(s) if s is not None else ""
# --- Helpers for Dates and Header Normalization ---
def _normalize_header(h):
if not h:
return ""
h = re.sub(r"\s+", " ", str(h)).strip().lower()
# direct canonicalizations
direct = {
"txn date": "date",
"transaction date": "date",
"value date": "value_date",
"post date": "date",
"description": "description",
"narration": "description",
"particulars": "description",
"ref no": "reference",
"reference no": "reference",
"cheque no": "reference",
"chq/ ref no": "reference",
"instrument no": "reference",
"debit": "debit",
"withdrawal": "debit",
"dr": "debit",
"credit": "credit",
"deposit": "credit",
"cr": "credit",
"amount": "amount",
"balance": "balance",
"closing balance": "balance",
}
if h in direct:
return direct[h]
# fuzzy rules
if "date" in h and "value" in h:
return "value_date"
if "date" in h:
return "date"
if any(k in h for k in ["narration", "description", "particular"]):
return "description"
if any(k in h for k in ["ref", "cheque", "chq", "instrument", "utr"]):
return "reference"
if any(k in h for k in ["debit", "withdraw"] ) or "(dr" in h or h.endswith(" dr") or h == "dr":
return "debit"
if any(k in h for k in ["credit", "deposit"]) or "(cr" in h or h.endswith(" cr") or h == "cr":
return "credit"
if "amount" in h:
return "amount"
if "balance" in h:
return "balance"
return h
def _parse_date(s):
if not s:
return None
s = str(s).strip()
# try multiple common formats
fmts = [
"%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y",
"%d/%m/%y", "%d-%m-%y", "%d.%m.%y",
"%d %b %Y", "%d-%b-%Y", "%d/%b/%Y",
"%d %b %y", "%d-%b-%y", "%d/%b/%y",
"%Y-%m-%d",
]
for f in fmts:
try:
return datetime.strptime(s, f).date().isoformat()
except Exception:
continue
# sometimes date is like 01JAN2024 or 01-Jan-24
try:
return datetime.strptime(s.replace(" ", "-"), "%d-%b-%Y").date().isoformat()
except Exception:
pass
return None
def _to_float_or_none(x):
v = clean_and_convert_to_float(x)
return None if v == "N/A" else v
def _extract_bank_statement_end_summary(text):
"""
Extracts the final 'Statement Summary' style numbers from the raw text,
preferring the last occurrence in the document.
Returns dict with any of: opening_balance, closing_balance, total_inflows, total_outflows.
"""
if not text:
return {}
summary = {}
def last_value(patterns):
last = None
for pat in patterns:
for m in re.finditer(pat, text, flags=re.IGNORECASE):
candidate = m.group(1)
val = clean_and_convert_to_float(candidate)
if val != "N/A":
last = val
return last
summary["opening_balance"] = last_value([
r"opening\s+balance[^\d\-]*\(?([\d,]+\-?)\)?",
r"opening\s+bal\.?[^\d\-]*\(?([\d,]+\-?)\)?",
])
summary["closing_balance"] = last_value([
r"closing\s+balance[^\d\-]*\(?([\d,]+\-?)\)?",
r"closing\s+bal\.?[^\d\-]*\(?([\d,]+\-?)\)?",
])
inflow = last_value([
r"(?:total\s+)?credits?\s*[:\-]?\s*\(?([\d,]+\-?)\)?",
r"total\s+deposit[s]?\s*[:\-]?\s*\(?([\d,]+\-?)\)?",
r"total\s+inflow[s]?\s*[:\-]?\s*\(?([\d,]+\-?)\)?",
])
outflow = last_value([
r"(?:total\s+)?debits?\s*[:\-]?\s*\(?([\d,]+\-?)\)?",
r"total\s+withdrawal[s]?\s*[:\-]?\s*\(?([\d,]+\-?)\)?",
r"total\s+outflow[s]?\s*[:\-]?\s*\(?([\d,]+\-?)\)?",
])
if inflow is not None:
summary["total_inflows"] = inflow
if outflow is not None:
summary["total_outflows"] = outflow
return {k: v for k, v in summary.items() if v is not None}
def _extract_investment_snapshot(text):
"""
Extracts 'Investment Snapshot' style summaries often present in portfolio PDFs.
Returns dict with keys like investment, switch_in, switch_out, redemption, div_payout_fd_interest,
net_investment, current_value, net_gain, xirr_percent. Only includes fields found.
"""
if not text:
return None
def find_last(label_pattern):
last = None
for m in re.finditer(label_pattern, text, flags=re.IGNORECASE):
val = m.group(1)
num = clean_and_convert_to_float(val)
if num != "N/A":
last = num
return last
fields = {}
fields["investment"] = find_last(r"investment\s*\(A\)\s*([0-9,]+)")
fields["switch_in"] = find_last(r"switch\s*in\s*\(B\)\s*([0-9,]+)")
fields["switch_out"] = find_last(r"switch\s*out\s*\(C\)\s*([0-9,]+)")
fields["redemption"] = find_last(r"redemption\s*\(D\)\s*([0-9,]+)")
fields["div_payout_fd_interest"] = find_last(r"div\.\s*payout/FD\s*interest\s*\(E\)\s*([0-9,]+)")
if fields.get("div_payout_fd_interest") is None:
fields["div_payout_fd_interest"] = find_last(r"div(?:idend)?\s*payout.*?\(E\)\s*([0-9,]+)")
fields["net_investment"] = find_last(r"net\s*investment\s*\(F[^\)]*\)\s*([0-9,]+)")
fields["current_value"] = find_last(r"current\s*value\s*\(G\)\s*([0-9,]+)")
fields["net_gain"] = find_last(r"net\s*gain\s*\(H[^\)]*\)\s*([0-9,]+)")
xirr_last = None
for m in re.finditer(r"\bXIRR\b\s*([0-9]+(?:\.[0-9]+)?)\s*%", text, flags=re.IGNORECASE):
try:
xirr_last = float(m.group(1))
except Exception:
continue
if xirr_last is not None:
fields["xirr_percent"] = xirr_last
filtered = {k: v for k, v in fields.items() if v is not None}
return filtered or None
# --- Bank Statement Structured Extraction ---
def extract_bank_statement_transactions(file_like):
"""Extract transactions as structured rows from a bank statement PDF using pdfplumber.
Returns dict with keys: transactions: [..], totals: {...}
Heuristics: detect tables with date/description and debit/credit/amount columns,
handle wrapped rows (blank date implies continuation), and numeric cleaning.
"""
transactions = []
try:
with pdfplumber.open(file_like) as pdf:
for page in pdf.pages:
tables = page.extract_tables() or []
for table in tables:
if not table or len(table) < 2:
continue
header = [_normalize_header(h) for h in table[0]]
cols = {name: idx for idx, name in enumerate(header) if name}
# must have a date+description and at least one of debit/credit/amount
if not any(h in cols for h in ("date", "value_date")) or "description" not in cols:
continue
has_debit = "debit" in cols
has_credit = "credit" in cols
has_amount = "amount" in cols
# Likely a transaction table only if amount-like present
if not (has_debit or has_credit or has_amount):
continue
last_txn = None
for row in table[1:]:
if row is None:
continue
# guard against ragged rows
row = [ (str(c) if c is not None else "").replace("\n"," ").strip() for c in row ]
# pad to header length
if len(row) < len(header):
row += [""] * (len(header) - len(row))
date_str = row[cols.get("date", cols.get("value_date"))] if any(k in cols for k in ("date","value_date")) else ""
description = row[cols["description"]] if "description" in cols else ""
ref = row[cols["reference"]] if "reference" in cols else ""
debit = _to_float_or_none(row[cols["debit"]]) if has_debit else None
credit = _to_float_or_none(row[cols["credit"]]) if has_credit else None
amount = _to_float_or_none(row[cols["amount"]]) if has_amount else None
balance = _to_float_or_none(row[cols["balance"]]) if "balance" in cols else None
# Handle wrapped/continuation lines: no date but more description
if (not date_str) and last_txn and description:
last_txn["description"] = (last_txn["description"] + " " + description).strip()
# merge reference if provided
if ref:
last_txn["reference"] = (last_txn.get("reference") or "") + ("; " if last_txn.get("reference") else "") + ref
# fill missing numeric cells if present only here
if debit is not None and last_txn.get("debit") is None:
last_txn["debit"] = debit
if credit is not None and last_txn.get("credit") is None:
last_txn["credit"] = credit
if amount is not None and last_txn.get("amount") is None:
last_txn["amount"] = amount
if balance is not None and last_txn.get("balance") is None:
last_txn["balance"] = balance
continue
iso_date = _parse_date(date_str)
# If the row clearly doesn't look like a txn, skip
if not iso_date and not description:
continue
# derive amount/type if only debit/credit available
txn_type = None
if amount is None:
if debit is not None and (credit is None or debit > 0):
amount = debit
txn_type = "debit"
elif credit is not None and (debit is None or credit > 0):
amount = credit
txn_type = "credit"
else:
# If both debit/credit present, prefer sign via non-null
if debit not in (None, 0) and (credit in (None, 0)):
txn_type = "debit"
elif credit not in (None, 0) and (debit in (None, 0)):
txn_type = "credit"
txn = {
"date": iso_date or date_str or None,
"description": description or None,
"reference": ref or None,
"debit": debit,
"credit": credit,
"amount": amount,
"type": txn_type,
"balance": balance,
}
transactions.append(txn)
last_txn = txn
except Exception as e:
logger.error(f"Error extracting bank transactions: {e}")
# post-process: clean None-only rows
clean_txns = []
for t in transactions:
# valid if has date+desc or amount
if (t.get("date") or t.get("description")) and (t.get("amount") is not None or t.get("debit") is not None or t.get("credit") is not None):
clean_txns.append(t)
# compute totals
total_debit = sum([v for v in [(tx.get("debit") or (tx.get("amount") if tx.get("type") == "debit" else None)) for tx in clean_txns] if isinstance(v,(int,float))])
total_credit = sum([v for v in [(tx.get("credit") or (tx.get("amount") if tx.get("type") == "credit" else None)) for tx in clean_txns] if isinstance(v,(int,float))])
opening_balance = None
closing_balance = None
# try derive from balances if present
balances = [tx.get("balance") for tx in clean_txns if tx.get("balance") is not None]
if balances:
opening_balance = balances[0]
closing_balance = balances[-1]
return {
"transactions": clean_txns,
"totals": {
"total_inflows": total_credit,
"total_outflows": total_debit,
"opening_balance": opening_balance,
"closing_balance": closing_balance,
"count": len(clean_txns),
}
}
# --- Hybrid Extraction Functions (Refactored) ---
def extract_bank_statement_hybrid(text, transactions_payload=None, save_json_path=None):
data = {}
patterns = {
"account_number": [
r"(?i)Account\s*(?:No\.?|Number)[\s:\-]*([Xx\*\d]{8,20})",
r"(?i)A/C\s*(?:No\.?|Number)[\s:\-]*([Xx\*\d]{8,20})",
r"(?i)Account[\s:\-]*([Xx\*\d]{8,20})"
],
"ifsc": [
r"\b([A-Z]{4}0[A-Z0-9]{6})\b"
],
"statement_period": [
r"(?i)Statement\s+(?:Period|From)[\s:\-]*(\d{1,2}[-/]\w{3}[-/]\d{2,4})\s*(?:to|-)\s*(\d{1,2}[-/]\w{3}[-/]\d{2,4})",
r"(?i)Period[\s:\-]*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})\s*(?:to|-)\s*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})",
r"(?i)From[\s:\-]*(\d{1,2}[-/]\w{3}[-/]\d{2,4})\s*To[\s:\-]*(\d{1,2}[-/]\w{3}[-/]\d{2,4})"
]
}
for key, pattern_list in patterns.items():
for pattern in pattern_list:
match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
if match:
if key == "statement_period" and match.lastindex >= 2:
data[key] = f"{match.group(1)} to {match.group(2)}"
else:
data[key] = match.group(1).strip() if match.group(1) else "N/A"
break
if key not in data:
data[key] = "N/A"
# Prepare a concise prompt relying on structured JSON if provided
tx_json_str = None
if transactions_payload and isinstance(transactions_payload, dict):
try:
# limit size to keep within token budget
tx_copy = {
"totals": transactions_payload.get("totals", {}),
# include only essential fields from first 2000 txns to reduce size
"transactions": [
{
"date": t.get("date"),
"description": t.get("description"),
"amount": t.get("amount"),
"type": t.get("type"),
"debit": t.get("debit"),
"credit": t.get("credit"),
}
for t in transactions_payload.get("transactions", [])[:2000]
],
}
tx_json_str = json.dumps(tx_copy)
except Exception:
tx_json_str = None
llm_prompt = f"""
You are given a bank statement. Prefer the provided structured JSON of transactions if available, otherwise infer from raw text.
Extract the following information in JSON format:
1. account_summary:
- account_holder_name: Full name of the account holder (look for "Account Holder", "Customer Name", "Name", etc.)
- opening_balance
- closing_balance
- total_inflows
- total_outflows
- average_monthly_balance
2. recurring_credits: Array of objects with description, amount, frequency, dates
3. recurring_debits: Array of objects with:
- description: Transaction description
- amount: Numeric amount (no currency symbols)
- frequency: Monthly/Quarterly/Yearly/Ad-hoc
- dates: Array of dates when this recurring debit occurred
- is_emi: Boolean - true if this is an EMI/loan payment, false otherwise
**EMI IDENTIFICATION RULES (IMPORTANT):**
Mark is_emi=true for transactions that match ANY of these patterns:
- Contains "EMI", "LOAN", "LN", "MORTGAGE", "INSTALMENT", "INSTALLMENT", "REPAYMENT"
- Contains bank-specific loan codes: "ELM" (ICICI EMI), "HDFC LN", "SBI LN", "AXIS LN"
- Contains "NACH" (National Automated Clearing House - often used for auto-debit EMIs/loans)
- Contains "SI/" or "STANDING INSTRUCTION" for loan payments
- Contains "ECS" (Electronic Clearing Service) for recurring loan debits
- Contains "AUTO DEBIT" or "AUTODEBIT" for loan/EMI payments
- Contains "HOME LOAN", "CAR LOAN", "PERSONAL LOAN", "VEHICLE LOAN", "HOUSING LOAN", "EDUCATION LOAN"
- Same amount debited on or around the same date each month (±3 days) - likely an EMI
Common EMI transaction patterns in Indian banks:
- ICICI: "BIL/INFT/ELM...", "NACH/..."
- HDFC: "HDFC LN...", "NACH/HDFC..."
- SBI: "EMI DED/...", "NACH/SBI..."
- Axis: "AXIS LN...", "NACH/AXIS..."
4. high_value_transactions: Array with date, description, type, amount (threshold: 100000)
5. bounce_penalty_charges: Array with date, description, amount
Notes:
- Use the structured JSON transactions as the source of truth when present.
- Use exact numeric values; do not include currency symbols.
- Frequency can be Monthly/Quarterly/Yearly/Ad-hoc.
- For recurring_debits, ALWAYS include the is_emi boolean field.
Structured Transactions JSON (optional):
{tx_json_str if tx_json_str else "<none>"}
Raw Bank Statement Text (truncated):
{text[:8000]}
"""
try:
response = client.chat.completions.create(
model="gpt-5.2",
messages=[
{"role": "system", "content": "You are a financial analyst expert at extracting structured data from Indian bank statements. All monetary values are in Indian Rupees (INR). Return valid JSON only."},
{"role": "user", "content": llm_prompt}
],
response_format={"type": "json_object"},
temperature=0.05
)
llm_data = json.loads(response.choices[0].message.content)
# Add confidence metadata for LLM-extracted fields
for llm_field in llm_data.keys():
_add_extraction_metadata(data, {
llm_field: _create_extraction_meta(llm_field, llm_data[llm_field], "llm")
})
data.update(llm_data)
except Exception as e:
logger.error(f"LLM extraction error for bank statement: {str(e)}")
data['extraction_error'] = str(e)
_add_extraction_metadata(data, {
"_llm_extraction": {"confidence": 0.0, "source": "llm", "needs_review": True, "reason": str(e)}
})
# Merge in any precomputed totals from structured parsing when LLM omitted
if transactions_payload and isinstance(transactions_payload, dict):
totals = transactions_payload.get("totals", {})
account_summary = data.get("account_summary", {}) or {}
for k in ["opening_balance","closing_balance","total_inflows","total_outflows"]:
if account_summary.get(k) in (None, "N/A") and totals.get(k) is not None:
account_summary[k] = totals.get(k)
data["account_summary"] = account_summary
# Prefer the explicit end-of-document statement summary if detected
try:
bank_summary = _extract_bank_statement_end_summary(text)
if bank_summary:
account_summary = data.get("account_summary", {}) or {}
account_summary.update({k: v for k, v in bank_summary.items() if v is not None})
data["account_summary"] = account_summary
except Exception as _:
pass
# Add Investment Snapshot if present (common in portfolio summaries)
try:
inv_snapshot = _extract_investment_snapshot(text)
if inv_snapshot:
data["investment_snapshot"] = inv_snapshot
except Exception as _:
pass
# attach a reference to saved JSON artifact if available
if save_json_path:
data["transactions_json_path"] = save_json_path
return data
def extract_itr_hybrid(text):
data = {}
patterns = {
"assessee_name": [
r"(?i)(?:Name|Assessee)(?:\s+of\s+(?:the\s+)?(?:Assessee|Tax\s*Payer))?[\s:\-]*([A-Z][A-Za-z\s\.]+?)(?:\n|PAN)",
r"(?i)Name\s+as\s+per\s+PAN[\s:\-]*([A-Z][A-Za-z\s\.]+)",
r"(?i)Full\s+Name[\s:\-]*([A-Z][A-Za-z\s\.]+)"
],
"date_of_birth": [
r"(?i)(?:Date\s+of\s+Birth|DOB|D\.O\.B)[\s:\-]*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})",
r"(?i)Birth\s+Date[\s:\-]*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})"
],
"assessment_year": [
r"(?i)Assessment\s*Year[\s:\-]*(\d{4}[\s\-]+\d{2,4})",
r"(?i)A\.?Y\.?[\s:\-]*(\d{4}[\s\-]+\d{2,4})"
],
"filing_date": [
r"(?i)Date\s*of\s*Filing[\s:\-]*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})",
r"(?i)Filed\s*on[\s:\-]*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})",
r"(?i)e-Filing\s*Date[\s:\-]*(\d{1,2}[-/]\d{1,2}[-/]\d{2,4})"
],
"pan": [
r"(?i)PAN[\s:\-]*([A-Z]{5}\d{4}[A-Z])",
r"\b([A-Z]{5}\d{4}[A-Z])\b"
],
"gross_total_income": [
r"(?i)Gross\s+Total\s+Income[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)",
r"(?i)Total\s+Gross\s+Income[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)"
],
"taxable_income": [
r"(?i)(?:Total\s+)?Taxable\s+Income[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)",
r"(?i)Net\s+Taxable\s+Income[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)"
],
"total_tax_paid": [
r"(?i)(?:Total\s+)?Tax\s+(?:Paid|Payable)[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)",
r"(?i)Tax\s+Amount[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)"
],
"refund_status": [
r"(?i)Refund[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)",
r"(?i)Tax\s+Payable[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)"
]
}
for key, pattern_list in patterns.items():
for pattern in pattern_list:
match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
if match:
if key in ["gross_total_income", "taxable_income", "total_tax_paid", "refund_status"]:
data[key] = clean_and_convert_to_float(match.group(1))
else:
data[key] = match.group(1).strip() if match.group(1) else "N/A"
break
if key not in data:
data[key] = "N/A"
deduction_patterns = [
(r"(?i)(?:Section\s*)?80C[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)", "80C"),
(r"(?i)(?:Section\s*)?80D[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)", "80D"),
(r"(?i)(?:Section\s*)?80E[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)", "80E"),
(r"(?i)(?:Section\s*)?80G[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)", "80G"),
(r"(?i)NPS.*?(?:80CCD|Deduction)[\s:\-]*(?:Rs\.?|₹)?\s*([\d,]+)", "80CCD (NPS)")
]
deductions = []
for pattern, section in deduction_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
amount = clean_and_convert_to_float(match.group(1))
if amount != "N/A" and amount > 0:
deductions.append({"section": section, "amount": amount})
if deductions:
data["deductions_claimed"] = deductions
llm_prompt = f"""
Analyze this ITR document and extract the following information in JSON format:
1. income_sources: Object with keys and their amounts:
- salary: Income from salary
- business_income: Income from business/profession
- capital_gains: Capital gains (short term + long term)
- house_property: Income from house property
- other_sources: Income from other sources
2. deductions_claimed: Array of objects with:
- section: Section name (e.g., "80C", "80D", "80CCD")
- amount: Deduction amount
3. carry_forward_losses: Object with types of losses carried forward:
- business_loss: Amount
- capital_loss_short: Short term capital loss
- capital_loss_long: Long term capital loss
- house_property_loss: House property loss
4. assets_and_liabilities: Object with:
- immovable_assets: Total value of immovable assets
- movable_assets: Total value of movable assets (bank deposits, shares, etc.)
- total_liabilities: Total liabilities
5. tax_computation: Object with:
- gross_total_income: Total income before deductions
- total_deductions: Sum of all deductions
- taxable_income: Income after deductions
- tax_before_rebate: Tax calculated
- rebate_87a: Rebate under 87A if applicable
- total_tax_paid: Final tax paid
- tds_collected: TDS amount
- advance_tax: Advance tax paid
- self_assessment_tax: Self assessment tax paid
All amounts should be numbers without currency symbols. Use 0 for not found/not applicable.
ITR Document Text:
{text[:20000]}
"""
try:
response = client.chat.completions.create(
model="gpt-5.2",
messages=[
{"role": "system", "content": "You are a tax expert analyzing Indian ITR documents. All monetary values are in Indian Rupees (INR). Extract all financial data accurately. Return valid JSON only."},
{"role": "user", "content": llm_prompt}
],
response_format={"type": "json_object"},
temperature=0.05
)
llm_data = json.loads(response.choices[0].message.content)
# Merge LLM data intelligently
for key in ["income_sources", "carry_forward_losses", "assets_and_liabilities", "tax_computation"]:
if key in llm_data and llm_data[key]:
data[key] = llm_data[key]
if "deductions_claimed" in llm_data and llm_data["deductions_claimed"]:
existing_deductions = data.get("deductions_claimed", [])
existing_sections = {d["section"] for d in existing_deductions}
for d in llm_data["deductions_claimed"]:
if d.get("section") not in existing_sections:
existing_deductions.append(d)
data["deductions_claimed"] = existing_deductions
# Add confidence metadata for LLM-extracted fields
for key in ["income_sources", "carry_forward_losses", "assets_and_liabilities", "tax_computation", "deductions_claimed"]: