-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail_parser.py
More file actions
214 lines (176 loc) · 8.74 KB
/
Copy pathemail_parser.py
File metadata and controls
214 lines (176 loc) · 8.74 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
import re
from datetime import datetime
from typing import Optional, Tuple
from dataclasses import dataclass
@dataclass
class ParsedTransaction:
fecha: datetime
monto: float
comercio: str
tipo: str # 'gasto' o 'ingreso'
class EmailParser:
"""Parser para correos de notificaciones bancarias (Bancolombia)"""
# Regex patterns
# Ejemplo: "Bancolombia le informa compra por $25.000,00 en UBER el 15/01/2026 a las 14:30. Dudas 018000912345"
# Ejemplo Transferencia: "Bancolombia le informa transferencia por $50.000,00 ... "
# Ejemplo Transferencia QR: "ALEJANDRO CABARCAS PERDOMO pagaste $67,000.00 por codigo QR desde tu cuenta *7905 a la llave 0052994316 el 11/01/2026 a las 09:46."
# Regex patterns
# Ejemplo: "Bancolombia le informa compra por $25.000,00 en UBER..."
# Nuevo: "Bancolombia: Transferiste $30,110.00 por Boton Bancolombia a ALCANOS..."
# Nuevo: "Bancolombia: Compraste $3.000,00 en CENTRO COMERCIAL..."
# Nuevo: "Bancolombia: Recibiste un pago por $9,861,000.00 de OTT..."
# 1. Gastos Genéricos (Bancolombia le informa...)
PATTERN_GASTO_LEGACY = re.compile(
r"Bancolombia le informa (?:compra|pago|retiro|transferencia) por \$([\d\.,]+) en (.+?) el (\d{2}/\d{2}/\d{4}) a las (\d{2}:\d{2})",
re.IGNORECASE
)
# 2. QR (Pagaste via QR)
PATTERN_QR = re.compile(
r"pagaste \$([\d\.,]+) por.+?(?:a la llave|en) (.+?) el (\d{2}/\d{2}/\d{4}) a las (\d{2}:\d{2})",
re.IGNORECASE
)
# 3. Transferencias Enviadas (Transferiste...)
# Tipo A: "Transferiste $X por Boton... a DESTINO desde PRODUCTO. FECHA HORA"
PATTERN_TRANSFERENCIA_A = re.compile(
r"Transferiste \$([\d\.,]+) .+? a (.+?) desde .+? (\d{2}/\d{2}/\d{4}).*?(\d{2}:\d{2})",
re.IGNORECASE
)
# Tipo B: "Transferiste $X desde Z a la cuenta DESTINO el FECHA a las HORA"
PATTERN_TRANSFERENCIA_DESDE = re.compile(
r"Transferiste \$([\d\.,]+) desde .+? a la cuenta (.+?) el (\d{2}/\d{2}/\d{4}) a las (\d{2}:\d{2})",
re.IGNORECASE
)
# 4. Compras (Compraste...)
# "Compraste $X en Y con tu T.Deb Z, el FECHA a las HORA"
PATTERN_COMPRASTE = re.compile(
r"Compraste \$([\d\.,]+) en (.+?) con .+? el (\d{2}/\d{2}/\d{4}) a las (\d{2}:\d{2})",
re.IGNORECASE
)
# 5. Ingresos (Recibiste pago / Transferencia recibida)
# "Bancolombia le informa que recibio transferencia de JUAN... el FECHA a las HORA"
PATTERN_INGRESO_LEGACY = re.compile(
r"Bancolombia le informa que recibio transferencia d?e? (.+?) por \$([\d\.,]+) el (\d{2}/\d{2}/\d{4}) a las (\d{2}:\d{2})",
re.IGNORECASE
)
# "Recibiste un pago por $X de Y a tu cuenta Z, el HORA a las FECHA" (Formato invertido detectado)
PATTERN_RECIBISTE = re.compile(
r"Recibiste un pago por \$([\d\.,]+) de (.+?) a tu cuenta .+?, el (\d{2}:\d{2}) a las (\d{2}/\d{2}/\d{4})",
re.IGNORECASE
)
def parse_body(self, body: str) -> Optional[ParsedTransaction]:
"""Intenta parsear el cuerpo del correo. Retorna ParsedTransaction o None."""
if not body:
return None
# Limpieza básica HTML a texto simple (muy rudimentaria pero efectiva para este caso)
clean_body = re.sub(r'<[^>]+>', ' ', body)
clean_body = re.sub(r'\s+', ' ', clean_body).strip()
# --- INTENTO DE PARSING (Orden: Específicos -> Genéricos) ---
# 1. QR
match = self.PATTERN_QR.search(clean_body)
if match:
return self._build_transaction(match, tipo="gasto", comercio_index=2, monto_index=1, fecha_index=3, hora_index=4, prefix="QR: ")
# 2. Transferiste Tipo A (a ... desde ...)
match = self.PATTERN_TRANSFERENCIA_A.search(clean_body)
if match:
return self._build_transaction(match, tipo="gasto", comercio_index=2, monto_index=1, fecha_index=3, hora_index=4)
# 3. Transferiste Tipo B (desde ... a ...)
match = self.PATTERN_TRANSFERENCIA_DESDE.search(clean_body)
if match:
return self._build_transaction(match, tipo="gasto", comercio_index=2, monto_index=1, fecha_index=3, hora_index=4)
# 4. Compraste (Gasto)
match = self.PATTERN_COMPRASTE.search(clean_body)
if match:
return self._build_transaction(match, tipo="gasto", comercio_index=2, monto_index=1, fecha_index=3, hora_index=4)
# 5. Gasto Legacy
match = self.PATTERN_GASTO_LEGACY.search(clean_body)
if match:
return self._build_transaction(match, tipo="gasto", comercio_index=2, monto_index=1, fecha_index=3, hora_index=4)
# 5. Recibiste (Ingreso - Formato Invertido HORA/FECHA)
match = self.PATTERN_RECIBISTE.search(clean_body)
if match:
# Grupo 1: Monto, 2: Origen, 3: Hora, 4: Fecha <-- OJO indices
# Este es especial, usaremos lógica manual o un helper distinto,
# pero _build_transaction asume orden standar. Lo haremos manual aqui.
monto_str = match.group(1)
origen = match.group(2).strip()
hora_str = match.group(3)
fecha_str = match.group(4)
fecha = self._parse_datetime(fecha_str, hora_str)
monto = self._parse_monto(monto_str)
return ParsedTransaction(
fecha=fecha,
monto=monto,
comercio=f"Transferencia de {origen}",
tipo="ingreso"
)
# 6. Ingreso Legacy
match = self.PATTERN_INGRESO_LEGACY.search(clean_body)
if match:
origen = match.group(1).replace("transferencia de", "").strip()
return self._build_transaction(match, tipo="ingreso", comercio_index=None, monto_index=2, fecha_index=3, hora_index=4,
fixed_comercio=f"Transferencia de {origen}")
return None
def _build_transaction(self, match, tipo, comercio_index, monto_index, fecha_index, hora_index, prefix="", fixed_comercio=None):
"""Helper para construir la transacción desde un match regex estándar"""
monto_str = match.group(monto_index)
fecha_str = match.group(fecha_index)
hora_str = match.group(hora_index)
if fixed_comercio:
comercio = fixed_comercio
else:
comercio = match.group(comercio_index).strip()
if prefix:
comercio = f"{prefix}{comercio}"
# Refinar comercio: a veces captura "Cuenta *1234", quitamos asteriscos o 'a la cuenta'
comercio = comercio.replace("a la cuenta", "").strip()
fecha = self._parse_datetime(fecha_str, hora_str)
monto = self._parse_monto(monto_str)
return ParsedTransaction(
fecha=fecha,
monto=monto,
comercio=comercio,
tipo=tipo
)
def _parse_monto(self, monto_str: str) -> float:
"""Convierte string de monto '$1.234,56', '$25,000.00' o '$1,200' a float"""
clean = monto_str.replace('$', '').strip()
has_comma = ',' in clean
has_point = '.' in clean
if has_comma and has_point:
last_comma = clean.rfind(',')
last_point = clean.rfind('.')
if last_point > last_comma: # US: 1,000.00
return float(clean.replace(',', ''))
else: # EU: 1.000,00
return float(clean.replace('.', '').replace(',', '.'))
if has_comma:
# Solo coma: 1,200 (1200) o 25,00 (25)
# Heurística: si hay exactamente 3 dígitos al final, es miles.
# Bancolombia dificilmente mandará 3 decimales.
parts = clean.split(',')
if len(parts[-1]) == 3:
return float(clean.replace(',', ''))
else:
return float(clean.replace(',', '.'))
if has_point:
# Solo punto: 1.200 (1200) o 25.00 (25)
parts = clean.split('.')
if len(parts[-1]) == 3:
return float(clean.replace('.', ''))
else:
return float(clean)
return float(clean)
def _parse_datetime(self, fecha_str: str, hora_str: str) -> datetime:
dt_str = f"{fecha_str} {hora_str}"
# Intentar formato corto HH:MM
try:
return datetime.strptime(dt_str, "%d/%m/%Y %H:%M")
except ValueError:
pass
# Intentar con segundos HH:MM:SS
try:
return datetime.strptime(dt_str, "%d/%m/%Y %H:%M:%S")
except ValueError:
# Si falla, retornar hoy como fallback (o re-raise)
print(f"Error parsing date: {dt_str}")
return datetime.now()