103 lines
3.4 KiB
Python
103 lines
3.4 KiB
Python
import os
|
|
import json
|
|
import fitz # PyMuPDF
|
|
import urllib.parse
|
|
import requests
|
|
import re
|
|
|
|
# Configuración
|
|
CARPETA_TICKETS = 'tickets'
|
|
CARPETA_JSON = 'apis/json_generados'
|
|
URL_BASE = 'https://tecnologia-facil.es/apis/procesar_ticket_json.php'
|
|
|
|
# Crear carpeta para los JSON si no existe
|
|
os.makedirs(CARPETA_JSON, exist_ok=True)
|
|
|
|
def extraer_texto_pdf(ruta_pdf):
|
|
"""Extraer el texto de un PDF"""
|
|
doc = fitz.open(ruta_pdf)
|
|
texto = ""
|
|
for pagina in doc:
|
|
texto += pagina.get_text()
|
|
return texto
|
|
|
|
def obtener_fecha(texto):
|
|
"""Buscar la fecha en el texto (formato DD/MM/YYYY)"""
|
|
match = re.search(r'\d{2}/\d{2}/\d{4}', texto)
|
|
if match:
|
|
return match.group(0)
|
|
return None
|
|
|
|
def obtener_supermercado(texto):
|
|
"""Detectar el nombre del supermercado o tienda"""
|
|
# Se puede ajustar este patrón dependiendo de cómo aparece el nombre de la tienda en el ticket
|
|
patrones_tienda = [
|
|
r"(Mercadona|ALDI|Lidl|Supercor|Costco|Ahorramas)", # Añadir más patrones si es necesario
|
|
]
|
|
for patron in patrones_tienda:
|
|
match = re.search(patron, texto)
|
|
if match:
|
|
return match.group(0)
|
|
return "Desconocido" # Si no se encuentra la tienda
|
|
|
|
def parsear_ticket(texto):
|
|
"""Parsear el texto del ticket en un diccionario"""
|
|
lineas = texto.splitlines()
|
|
productos = []
|
|
|
|
# Detectar la fecha y el supermercado en las primeras líneas
|
|
fecha = obtener_fecha(texto)
|
|
supermercado = obtener_supermercado(texto)
|
|
|
|
for linea in lineas:
|
|
partes = linea.strip().split()
|
|
if len(partes) >= 3 and partes[0].isdigit():
|
|
try:
|
|
cantidad = int(partes[0])
|
|
precio = float(partes[-1].replace(',', '.'))
|
|
nombre = ' '.join(partes[1:-1])
|
|
productos.append({
|
|
"nombre": nombre,
|
|
"cantidad": cantidad,
|
|
"precio": precio,
|
|
"codigo_barras": "",
|
|
"marca_id": None
|
|
})
|
|
except:
|
|
continue
|
|
|
|
ticket = {
|
|
"tienda_id": 1, # Puedes cambiar esto o extraerlo según el supermercado
|
|
"fecha": fecha or "2025-01-01", # Fecha extraída o una predeterminada
|
|
"total": sum(p["precio"] * p["cantidad"] for p in productos),
|
|
"metodo_pago": "tarjeta", # Puedes ajustar según el ticket
|
|
"supermercado": supermercado,
|
|
"productos": productos
|
|
}
|
|
return ticket
|
|
|
|
# Procesar cada PDF en la carpeta
|
|
for archivo in os.listdir(CARPETA_TICKETS):
|
|
if archivo.lower().endswith('.pdf'):
|
|
ruta_pdf = os.path.join(CARPETA_TICKETS, archivo)
|
|
nombre_sin_ext = os.path.splitext(archivo)[0]
|
|
ruta_json = os.path.join(CARPETA_JSON, f"{nombre_sin_ext}.json")
|
|
|
|
texto = extraer_texto_pdf(ruta_pdf)
|
|
ticket_dict = parsear_ticket(texto)
|
|
|
|
# Guardar JSON
|
|
with open(ruta_json, 'w', encoding='utf-8') as f:
|
|
json.dump(ticket_dict, f, indent=2, ensure_ascii=False)
|
|
|
|
print(f"✅ JSON generado: {ruta_json}")
|
|
|
|
# Enviar GET simulando que el JSON está ya en el servidor
|
|
url_final = f"{URL_BASE}?file={urllib.parse.quote(nombre_sin_ext + '.json')}"
|
|
try:
|
|
r = requests.get(url_final)
|
|
print(f"🌐 GET enviado: {url_final}")
|
|
print(f"🟢 Respuesta: {r.text}")
|
|
except Exception as e:
|
|
print(f"❌ Error al enviar: {e}")
|