File size: 13,186 Bytes
0a6b0fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# azure_ocr_processor.py
# Procesador OCR usando Azure Document Intelligence

import json
import numpy as np
from io import BytesIO
from typing import Dict, List

try:
    from azure.core.credentials import AzureKeyCredential
    from azure.ai.documentintelligence import DocumentIntelligenceClient
    AZURE_AVAILABLE = True
except ImportError:
    AZURE_AVAILABLE = False
    print("ADVERTENCIA: azure-ai-documentintelligence no est谩 disponible.")


class AzureOCRProcessor:
    """Procesador usando Azure Document Intelligence"""
    
    def __init__(self, endpoint: str = None, key: str = None):
        if not AZURE_AVAILABLE:
            raise RuntimeError("Azure Document Intelligence no est谩 disponible")
        
        # Usar credenciales desde variables de entorno o par谩metros
        import os
        
        # Prioridad: par谩metros > variables de entorno > valores por defecto
        self.endpoint = endpoint or os.environ.get(
            "AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT",
            "https://invoicerecog.cognitiveservices.azure.com/"
        )
        
        self.key = key or os.environ.get(
            "AZURE_DOCUMENT_INTELLIGENCE_KEY",
            "BnvYqZbBSscFxbxZurfTEj9H6ZP4anDzvE2gQTB8fvau0wzlAk0TJQQJ99BKACYeBjFXJ3w3AAALACOGyauB"
        )
        
        if not self.endpoint or not self.key:
            raise ValueError(
                "Se requieren credenciales de Azure. "
                "Define las variables de entorno AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT "
                "y AZURE_DOCUMENT_INTELLIGENCE_KEY, o p谩salas como par谩metros."
            )
        
        print(f"INFO: Inicializando Azure Document Intelligence")
        print(f"INFO: Endpoint: {self.endpoint}")
        
        self.client = DocumentIntelligenceClient(
            endpoint=self.endpoint,
            credential=AzureKeyCredential(self.key)
        )
    
    def process(self, image: np.ndarray, ocr_config: Dict) -> List[Dict]:
        """
        Procesa la imagen usando Azure Document Intelligence.
        Retorna text_blocks simulando el formato de otros OCR pero con datos estructurados.
        """
        model = ocr_config.get("model", "prebuilt-invoice")
        
        print(f"INFO: Procesando con Azure Document Intelligence, modelo: {model}")
        
        # === NUEVO: COMPRESI脫N DE IMAGEN PARA AZURE (PROCESO INDEPENDIENTE) ===
        # Esta compresi贸n se ejecuta antes del procesamiento normal y no afecta la funcionalidad original
        image_to_process = self._compress_image_for_azure(image)
        # === FIN COMPRESI脫N ===
        
        # Convertir numpy array a bytes (formato PNG) - C脫DIGO ORIGINAL INTACTO
        import cv2
        success, encoded_image = cv2.imencode('.png', image_to_process)
        if not success:
            raise RuntimeError("No se pudo codificar la imagen")
        
        image_bytes = encoded_image.tobytes()
        
        print(f"INFO: Imagen codificada: {len(image_bytes)} bytes")
        
        # Analizar con Azure - C脫DIGO ORIGINAL INTACTO
        try:
            print("INFO: Enviando imagen a Azure Document Intelligence...")
            
            poller = self.client.begin_analyze_document(
                model,
                body=BytesIO(image_bytes),
                content_type="image/png"
            )
            
            print("INFO: Esperando respuesta de Azure...")
            result = poller.result()
            
            print(f"INFO: An谩lisis completado. Documentos encontrados: {len(result.documents) if result.documents else 0}")
            
            # Convertir resultado de Azure a formato de texto estructurado
            formatted_text = self._format_azure_result_as_text(result)
            
            # Retornar como un 煤nico text_block con flag especial
            return [{
                'text': formatted_text,
                'x': 0,
                'y': 0,
                'width': 0,
                'height': 0,
                'confidence': 95.0,
                'engine': 'azure',
                'is_azure_structured': True
            }]
        
        except Exception as e:
            print(f"ERROR en Azure Document Intelligence: {e}")
            import traceback
            traceback.print_exc()
            raise
    
    def _compress_image_for_azure(self, image: np.ndarray) -> np.ndarray:
        """
        COMPRESI脫N INDEPENDIENTE: Comprime la imagen para Azure sin afectar el procesamiento original.
        Esta funci贸n es completamente independiente y no modifica la l贸gica existente.
        """
        import cv2
        
        # Obtener informaci贸n de la imagen original
        height, width = image.shape[:2]
        original_size_mb = image.nbytes / (1024 * 1024)
        print(f"INFO: Compresi贸n Azure - Imagen original: {width}x{height}, {original_size_mb:.2f}MB")
        
        # Si la imagen ya es peque帽a, no comprimir
        if original_size_mb <= 4.5:
            print("INFO: Compresi贸n Azure - Imagen ya est谩 dentro del l铆mite, no se requiere compresi贸n")
            return image
        
        print("INFO: Compresi贸n Azure - Aplicando compresi贸n...")
        
        # Redimensionar si es muy grande (manteniendo relaci贸n de aspecto)
        max_dimension = 2000
        if width > max_dimension or height > max_dimension:
            if width > height:
                new_width = max_dimension
                new_height = int((max_dimension / width) * height)
            else:
                new_height = max_dimension
                new_width = int((max_dimension / height) * width)
            
            print(f"INFO: Compresi贸n Azure - Redimensionando a {new_width}x{new_height}")
            compressed_image = cv2.resize(image, (new_width, new_height), interpolation=cv2.INTER_AREA)
            compressed_size_mb = compressed_image.nbytes / (1024 * 1024)
            print(f"INFO: Compresi贸n Azure - Despu茅s de redimensionar: {compressed_size_mb:.2f}MB")
            
            # Verificar si despu茅s de redimensionar ya est谩 dentro del l铆mite
            if compressed_size_mb <= 4.5:
                return compressed_image
        else:
            compressed_image = image
        
        # Si a煤n es grande despu茅s de redimensionar, aplicar compresi贸n JPEG temporal
        temp_quality = 85
        while temp_quality >= 50:
            # Codificar temporalmente como JPEG para ver el tama帽o
            success, jpeg_encoded = cv2.imencode('.jpg', compressed_image, [cv2.IMWRITE_JPEG_QUALITY, temp_quality])
            if success:
                jpeg_size_mb = len(jpeg_encoded.tobytes()) / (1024 * 1024)
                print(f"INFO: Compresi贸n Azure - Calidad {temp_quality}: {jpeg_size_mb:.2f}MB")
                
                if jpeg_size_mb <= 4.5:
                    print(f"INFO: Compresi贸n Azure - Calidad {temp_quality} aceptada")
                    # Decodificar de vuelta a numpy array para mantener compatibilidad
                    decoded_image = cv2.imdecode(jpeg_encoded, cv2.IMREAD_COLOR)
                    if decoded_image is not None:
                        final_size_mb = decoded_image.nbytes / (1024 * 1024)
                        print(f"INFO: Compresi贸n Azure - Imagen final: {final_size_mb:.2f}MB")
                        return decoded_image
            
            temp_quality -= 10
        
        # Si llegamos aqu铆, usar la imagen redimensionada sin compresi贸n JPEG
        print("INFO: Compresi贸n Azure - Usando imagen redimensionada sin compresi贸n JPEG adicional")
        return compressed_image
    
    def _format_azure_result_as_text(self, result) -> str:
        """
        Convierte el resultado de Azure a un texto formateado limpio (sin l铆neas de confianza).
        """
        output_lines = []
        
        if not result.documents:
            return "ERROR: No se encontraron documentos en la factura"
        
        # Procesar el primer documento
        document = result.documents[0]
        fields = document.fields
        
        output_lines.append("-------- An谩lisis de Azure Document Intelligence --------")
        output_lines.append("")
        
        # Informaci贸n del proveedor
        vendor_name = fields.get("VendorName")
        if vendor_name:
            output_lines.append(f"Proveedor: {vendor_name.content}")
        
        vendor_address = fields.get("VendorAddress")
        if vendor_address:
            output_lines.append(f"Direcci贸n: {vendor_address.content}")
        
        vendor_tax = fields.get("VendorTaxId")
        if vendor_tax:
            output_lines.append(f"GST/HST: {vendor_tax.content}")
        
        output_lines.append("")
        
        # Informaci贸n de la factura
        invoice_id = fields.get("InvoiceId")
        if invoice_id:
            output_lines.append(f"Invoice ID: {invoice_id.content}")
        
        invoice_date = fields.get("InvoiceDate")
        if invoice_date:
            output_lines.append(f"Fecha: {invoice_date.content}")
        
        customer_name = fields.get("CustomerName")
        if customer_name:
            output_lines.append(f"Cliente: {customer_name.content}")
        
        output_lines.append("")
        output_lines.append("=" * 60)
        output_lines.append("脥TEMS DE LA FACTURA")
        output_lines.append("=" * 60)
        output_lines.append("")
        
        # Extraer items
        items_field = fields.get("Items")
        total_items = 0
        
        if items_field and hasattr(items_field, "value_array"):
            total_items = len(items_field.value_array)
            print(f"INFO: Procesando {total_items} items...")
            
            for item_idx, item in enumerate(items_field.value_array):
                item_obj = item.value_object if hasattr(item, "value_object") else {}
                
                output_lines.append(f"--- 脥tem #{item_idx + 1} ---")
                
                # C贸digo de producto
                product_code = item_obj.get("ProductCode")
                if product_code and product_code.content:
                    output_lines.append(f"C贸digo: {product_code.content}")
                
                # Descripci贸n
                description = item_obj.get("Description")
                if description and description.content:
                    output_lines.append(f"Descripci贸n: {description.content}")
                
                # Cantidad
                quantity = item_obj.get("Quantity")
                if quantity and quantity.content:
                    output_lines.append(f"Cantidad: {quantity.content}")
                
                # Precio unitario
                unit_price = item_obj.get("UnitPrice")
                if unit_price and unit_price.content:
                    output_lines.append(f"Precio unitario: {unit_price.content}")
                
                # Impuesto por 铆tem - SOLO si es > 0
                tax = item_obj.get("Tax")
                if tax and tax.content:
                    try:
                        # Extraer el valor num茅rico del tax
                        tax_value_str = tax.content.replace('$', '').replace(',', '').strip()
                        tax_value = float(tax_value_str)
                        
                        # Solo incluir si es mayor a 0
                        if tax_value > 0:
                            output_lines.append(f"Impuesto (H): {tax.content}")
                    except (ValueError, AttributeError):
                        pass
                
                # Total por 铆tem
                amount = item_obj.get("Amount")
                if amount and amount.content:
                    output_lines.append(f"Total por 铆tem: {amount.content}")
                
                output_lines.append("")
        else:
            output_lines.append("No se encontraron items en la factura")
        
        # Totales
        output_lines.append("=" * 60)
        output_lines.append("TOTALES")
        output_lines.append("=" * 60)
        output_lines.append("")
        
        subtotal = fields.get("SubTotal")
        if subtotal and subtotal.content:
            output_lines.append(f"Subtotal: {subtotal.content}")
        
        total_tax = fields.get("TotalTax")
        if total_tax and total_tax.content:
            output_lines.append(f"Total impuestos: {total_tax.content}")
        
        invoice_total = fields.get("InvoiceTotal")
        if invoice_total and invoice_total.content:
            output_lines.append(f"Total de la factura: {invoice_total.content}")
        
        output_lines.append("")
        output_lines.append("=" * 60)
        output_lines.append(f"Total de items extra铆dos: {total_items}")
        output_lines.append("=" * 60)
        
        formatted_text = "\n".join(output_lines)
        
        print(f"\n{'='*60}")
        print("TEXTO FORMATEADO GENERADO:")
        print(f"{'='*60}")
        print(formatted_text[:800] + "..." if len(formatted_text) > 800 else formatted_text)
        print(f"{'='*60}\n")
        
        return formatted_text