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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
demo.launch()
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
|
| 5 |
import gradio as gr
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
|
| 8 |
+
|
| 9 |
+
# --------- MODELO QA (Kaleidoscope) ----------
|
| 10 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
+
qa_model_id = "2KKLabs/Kaleidoscope_small_v1"
|
| 12 |
+
|
| 13 |
+
tokenizer = AutoTokenizer.from_pretrained(qa_model_id)
|
| 14 |
+
model = AutoModelForQuestionAnswering.from_pretrained(qa_model_id)
|
| 15 |
+
model.to(device)
|
| 16 |
+
model.eval()
|
| 17 |
+
|
| 18 |
+
TIPOS = [
|
| 19 |
+
"coche",
|
| 20 |
+
"comidas",
|
| 21 |
+
"envio postal",
|
| 22 |
+
"estacionamiento",
|
| 23 |
+
"hoteles",
|
| 24 |
+
"peaje",
|
| 25 |
+
"taxis",
|
| 26 |
+
"telefono/celular/internet",
|
| 27 |
+
"tren",
|
| 28 |
+
"vuelos",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
# --------- OCR: imagen -> texto (placeholder) ----------
|
| 32 |
+
def ocr_image_to_text(image):
|
| 33 |
+
"""
|
| 34 |
+
Sustituye esto por tu OCR real (easyocr, paddleocr, etc.).
|
| 35 |
+
De momento devuelve un stub para poder probar el flujo.
|
| 36 |
+
"""
|
| 37 |
+
return "stub text from OCR with date 2024-11-01 amount 23.50 EUR bar Velodromo comidas"
|
| 38 |
+
|
| 39 |
+
# --------- Utilidades de post-procesado ----------
|
| 40 |
+
def normalize_date(text):
|
| 41 |
+
patterns = [
|
| 42 |
+
r"(\d{4})-(\d{2})-(\d{2})", # 2024-11-01
|
| 43 |
+
r"(\d{2})/(\d{2})/(\d{4})", # 01/11/2024
|
| 44 |
+
r"(\d{2})-(\d{2})-(\d{4})", # 01-11-2024
|
| 45 |
+
]
|
| 46 |
+
for p in patterns:
|
| 47 |
+
m = re.search(p, text)
|
| 48 |
+
if m:
|
| 49 |
+
g = m.groups()
|
| 50 |
+
try:
|
| 51 |
+
if len(g) == 4: # YYYY-MM-DD
|
| 52 |
+
dt = datetime(int(g), int(g[5]), int(g[6]))
|
| 53 |
+
else: # DD/MM/YYYY o DD-MM-YYYY
|
| 54 |
+
dt = datetime(int(g[6]), int(g[5]), int(g))
|
| 55 |
+
return dt.strftime("%Y-%m-%d")
|
| 56 |
+
except Exception:
|
| 57 |
+
pass
|
| 58 |
+
return ""
|
| 59 |
+
|
| 60 |
+
def normalize_amount(text):
|
| 61 |
+
m = re.search(r"(\d+[.,]\d{2})", text)
|
| 62 |
+
if not m:
|
| 63 |
+
return ""
|
| 64 |
+
return m.group(1).replace(",", ".")
|
| 65 |
+
|
| 66 |
+
def best_tipo_from_text(text):
|
| 67 |
+
t = text.lower()
|
| 68 |
+
if "parking" in t or "aparcamiento" in t:
|
| 69 |
+
return "estacionamiento"
|
| 70 |
+
if "peaje" in t or "toll" in t:
|
| 71 |
+
return "peaje"
|
| 72 |
+
if "taxi" in t:
|
| 73 |
+
return "taxis"
|
| 74 |
+
if "hotel" in t:
|
| 75 |
+
return "hoteles"
|
| 76 |
+
if "train" in t or "renfe" in t or "tren" in t:
|
| 77 |
+
return "tren"
|
| 78 |
+
if "flight" in t or "vueling" in t or "iberia" in t:
|
| 79 |
+
return "vuelos"
|
| 80 |
+
if "diesel" in t or "fuel" in t or "gasolina" in t:
|
| 81 |
+
return "coche"
|
| 82 |
+
if "internet" in t or "movistar" in t or "vodafone" in t:
|
| 83 |
+
return "telefono/celular/internet"
|
| 84 |
+
return "comidas"
|
| 85 |
+
|
| 86 |
+
def truncate_desc(desc, max_words=6):
|
| 87 |
+
words = desc.split()
|
| 88 |
+
if len(words) <= max_words:
|
| 89 |
+
return desc
|
| 90 |
+
return " ".join(words[:max_words])
|
| 91 |
+
|
| 92 |
+
# --------- Llamada al modelo QA ----------
|
| 93 |
+
def qa_answer(context, question, max_length=384):
|
| 94 |
+
inputs = tokenizer(
|
| 95 |
+
question,
|
| 96 |
+
context,
|
| 97 |
+
return_tensors="pt",
|
| 98 |
+
truncation=True,
|
| 99 |
+
max_length=max_length
|
| 100 |
+
)
|
| 101 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 102 |
+
|
| 103 |
+
with torch.no_grad():
|
| 104 |
+
outputs = model(**inputs)
|
| 105 |
+
|
| 106 |
+
start_index = int(torch.argmax(outputs.start_logits))
|
| 107 |
+
end_index = int(torch.argmax(outputs.end_logits))
|
| 108 |
+
|
| 109 |
+
answer_tokens = inputs["input_ids"][start_index : end_index + 1]
|
| 110 |
+
answer = tokenizer.decode(answer_tokens, skip_special_tokens=True)
|
| 111 |
+
return answer.strip()
|
| 112 |
+
|
| 113 |
+
# --------- Pipeline principal ----------
|
| 114 |
+
def process_receipt(image):
|
| 115 |
+
# 1) Imagen -> texto
|
| 116 |
+
context = ocr_image_to_text(image)
|
| 117 |
+
|
| 118 |
+
# 2) Pregunta al modelo para obtener JSON bruto
|
| 119 |
+
question = (
|
| 120 |
+
"From this receipt text extract: "
|
| 121 |
+
"fecha (date), tipo (one of coche, comidas, envio postal, estacionamiento, hoteles, peaje, "
|
| 122 |
+
"taxis, telefono/celular/internet, tren, vuelos), "
|
| 123 |
+
"description (<=6 words), amount (numeric), comments (business name). "
|
| 124 |
+
"Return only a JSON object with keys: fecha, tipo, description, amount, comments."
|
| 125 |
+
)
|
| 126 |
+
raw_answer = qa_answer(context, question)
|
| 127 |
+
|
| 128 |
+
# 3) Parseo / fallback
|
| 129 |
+
fecha = ""
|
| 130 |
+
tipo = ""
|
| 131 |
+
descripcion = ""
|
| 132 |
+
amount = ""
|
| 133 |
+
comments = ""
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
obj = json.loads(raw_answer)
|
| 137 |
+
fecha = obj.get("fecha", "")
|
| 138 |
+
tipo = obj.get("tipo", "")
|
| 139 |
+
descripcion = obj.get("description", "")
|
| 140 |
+
amount = str(obj.get("amount", ""))
|
| 141 |
+
comments = obj.get("comments", "")
|
| 142 |
+
except Exception:
|
| 143 |
+
fecha = normalize_date(context)
|
| 144 |
+
amount = normalize_amount(context)
|
| 145 |
+
tipo = best_tipo_from_text(context)
|
| 146 |
+
descripcion = "expense item"
|
| 147 |
+
first_line = context.splitlines() if context.splitlines() else ""
|
| 148 |
+
comments = first_line[:60]
|
| 149 |
+
|
| 150 |
+
# 4) Normalizaci贸n
|
| 151 |
+
if not fecha:
|
| 152 |
+
fecha = normalize_date(context)
|
| 153 |
+
|
| 154 |
+
if tipo not in TIPOS:
|
| 155 |
+
tipo = best_tipo_from_text(context)
|
| 156 |
+
|
| 157 |
+
descripcion = truncate_desc(descripcion, 6)
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
amount_val = float(amount)
|
| 161 |
+
except Exception:
|
| 162 |
+
amount_val = 0.0
|
| 163 |
+
|
| 164 |
+
return fecha, tipo, descripcion, amount_val, comments
|
| 165 |
+
|
| 166 |
+
# --------- Interfaz Gradio ----------
|
| 167 |
+
with gr.Blocks(title="Receiptesting - Kaleidoscope") as demo:
|
| 168 |
+
gr.Markdown(
|
| 169 |
+
"## Receiptesting con Kaleidoscope_small_v1\n\n"
|
| 170 |
+
"Sube una imagen de un recibo y se extraer谩n: **fecha**, **tipo**, "
|
| 171 |
+
"**descripci贸n corta**, **amount** y **comentarios (nombre del negocio)**."
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
with gr.Row():
|
| 175 |
+
with gr.Column():
|
| 176 |
+
image_in = gr.Image(
|
| 177 |
+
type="pil",
|
| 178 |
+
label="Imagen del recibo",
|
| 179 |
+
)
|
| 180 |
+
btn = gr.Button("Extraer")
|
| 181 |
+
with gr.Column():
|
| 182 |
+
fecha_out = gr.Textbox(label="Fecha (YYYY-MM-DD)")
|
| 183 |
+
tipo_out = gr.Dropdown(
|
| 184 |
+
choices=TIPOS,
|
| 185 |
+
label="Tipo",
|
| 186 |
+
)
|
| 187 |
+
desc_out = gr.Textbox(label="Descripci贸n (<= 6 palabras)")
|
| 188 |
+
amount_out = gr.Number(label="Amount")
|
| 189 |
+
comments_out = gr.Textbox(label="Comentarios (nombre del negocio)")
|
| 190 |
|
| 191 |
+
btn.click(
|
| 192 |
+
process_receipt,
|
| 193 |
+
inputs=[image_in],
|
| 194 |
+
outputs=[fecha_out, tipo_out, desc_out, amount_out, comments_out],
|
| 195 |
+
)
|
| 196 |
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
demo.launch()
|
requirements.txt
ADDED
|
Binary file (4.58 kB). View file
|
|
|