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
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
import gradio as gr
import requests
import json

API_URL = "https://ia.nebuia.com/api/v1/integrator/extractor/from/excel"
API_KEY = "2J7NFWQ-236PGAM-2S9RD3C-2DG54CY"
API_SECRET = "a47abf97-866b-4154-b29c-346c9b02919e"

import re
import json

def extract_json_from_response(response_text):
    """
    Detecta si la respuesta contiene un bloque JSON con formato markdown ```json ```
    y extrae su contenido, o devuelve el texto original si no se encuentra ese patrón.
    
    Args:
        response_text (str): El texto de respuesta que puede contener bloques JSON
        
    Returns:
        str: El contenido JSON extraído o el texto original
    """
    # Patrón para encontrar bloques de código JSON con formato markdown
    json_pattern = r"```json\s+([\s\S]*?)\s+```"
    
    # Buscar coincidencias
    match = re.search(json_pattern, response_text)
    
    if match:
        # Extraer el contenido JSON del bloque
        json_content = match.group(1).strip()
        
        # Verificar que sea un JSON válido
        try:
            # Intentar cargar el JSON para validarlo
            json.loads(json_content)
            return json_content
        except json.JSONDecodeError:
            # Si no es un JSON válido, devolver el texto original
            return response_text
    
    # Si no hay coincidencias, devolver el texto original
    return response_text

# Modificación de la función send_excel_to_api para usar la función de extracción
def send_excel_to_api(file_path, json_structure):
    headers = {
        'key': API_KEY,
        'secret': API_SECRET
    }
    
    files = {
        'file': open(file_path, 'rb')
    }
    
    data = {
        'structure': json_structure
    }
    
    try:
        response = requests.post(API_URL, headers=headers, files=files, data=data)
        
        if response.status_code == 200:
            result = response.json()
            # Si la respuesta contiene un payload, formatearla como JSON
            if "payload" in result:
                response_json = json.dumps(result["payload"], indent=2, ensure_ascii=False)
                # Extraer JSON de la respuesta si está en formato markdown
                return extract_json_from_response(response_json)
            else:
                return json.dumps(result, indent=2, ensure_ascii=False)
        else:
            return f"Error: Received status code {response.status_code}\n{response.text}"
    except requests.RequestException as e:
        return f"Error sending request: {e}"
    finally:
        files['file'].close()

def gradio_interface(file, json_structure):
    if file is None:
        return "Please upload an Excel file."
    return send_excel_to_api(file.name, json_structure)

# Custom color for the theme
custom_purple = "#7f56d9"

# Create the Gradio interface using Blocks
with gr.Blocks(theme=gr.themes.Default(primary_hue="purple", secondary_hue="purple")) as demo:
    gr.Markdown(
        """
        <div style="text-align: center;">
            <img src="https://copilot.nebuia.com/images/logo_white.png" style="max-height: 400px; max-width: 120px; object-fit: contain;">
        </div>
        
        ## NebuIA Excel Structure Extractor
        Upload an Excel file and provide a JSON structure to send to the API.
        """
    )
    with gr.Row():
        file_input = gr.File(label="Upload Excel File")
        json_input = gr.Code(
            label="JSON Structure", 
            language="json", 
            lines=15, 
            value='''{
  "total de activo a_corto_plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "efectivo y equivalentes de efectivo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "instrumentos financieros de negociacion": [
    {
      "año": "",
      "total": ""
    }
  ],
  "clientes": [
    {
      "año": "",
      "total": ""
    }
  ],
  "cuentas y documentos por cobrar": [
    {
      "año": "",
      "total": ""
    }
  ],
  "deudores diversos": [
    {
      "año": "",
      "total": ""
    }
  ],
  "estimaciones de cuentas incobrables": [
    {
      "año": "",
      "total": ""
    }
  ],
  "impuestos por recuperar": [
    {
      "año": "",
      "total": ""
    }
  ],
  "inventarios": [
    {
      "año": "",
      "total": ""
    }
  ],
  "pagos anticipados": [
    {
      "año": "",
      "total": ""
    }
  ],
  "activos disponibles para venta": [
    {
      "año": "",
      "total": ""
    }
  ],
  "otros activos a corto plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "total de activo a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "propiedades, plantas y equipo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "anticipo a proveedores": [
    {
      "año": "",
      "total": ""
    }
  ],
  "crédito mercantil": [
    {
      "año": "",
      "total": ""
    }
  ],
  "activos intangibles": [
    {
      "año": "",
      "total": ""
    }
  ],
  "inversiones asociadas": [
    {
      "año": "",
      "total": ""
    }
  ],
  "instrumentos financieros por cobrar a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "otros activos a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "total de activo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "total de pasivo a corto plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "prestamos bancarios": [
    {
      "año": "",
      "total": ""
    }
  ],
  "proveedores": [
    {
      "año": "",
      "total": ""
    }
  ],
  "cuentas y documentos por pagar": [
    {
      "año": "",
      "total": ""
    }
  ],
  "instrumentos financieros": [
    {
      "año": "",
      "total": ""
    }
  ],
  "acreedores diversos": [
    {
      "año": "",
      "total": ""
    }
  ],
  "impuestos a la utilidad por pagar": [
    {
      "año": "",
      "total": ""
    }
  ],
  "anticipo de clientes": [
    {
      "año": "",
      "total": ""
    }
  ],
  "provisiones": [
    {
      "año": "",
      "total": ""
    }
  ],
  "impuestos por pagar": [
    {
      "año": "",
      "total": ""
    }
  ],
  "otros pasivos a corto plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "total de pasivo a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "cuentas y documentos por pagar a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "instrumentos financieros a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "rentas cobradas por anticipado": [
    {
      "año": "",
      "total": ""
    }
  ],
  "aportaciones para futuros aumentos de capital": [
    {
      "año": "",
      "total": ""
    }
  ],
  "impuesto a la utilidad diferido por pagar": [
    {
      "año": "",
      "total": ""
    }
  ],
  "beneficio a empleados": [
    {
      "año": "",
      "total": ""
    }
  ],
  "provisiones a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "otros pasivos a largo plazo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "total de pasivo": [
    {
      "año": "",
      "total": ""
    }
  ],
  "total de capital contable": [
    {
      "año": "",
      "total": ""
    }
  ],
  "capital social": [
    {
      "año": "",
      "total": ""
    }
  ],
  "reserva legal": [
    {
      "año": "",
      "total": ""
    }
  ],
  "exceso en la actualización del capital": [
    {
      "año": "",
      "total": ""
    }
  ],
  "insuficiencia en la actualización de capital": [
    {
      "año": "",
      "total": ""
    }
  ],
  "reservas de capital": [
    {
      "año": "",
      "total": ""
    }
  ],
  "primas en venta de acciones": [
    {
      "año": "",
      "total": ""
    }
  ],
  "utilidades acumuladas": [
    {
      "año": "",
      "total": ""
    }
  ],
  "utilidad neta": [
    {
      "año": "",
      "total": ""
    }
  ],
  "perdidas acumuladas": [
    {
      "año": "",
      "total": ""
    }
  ],
  "participación controladora": [
    {
      "año": "",
      "total": ""
    }
  ],
  "ingresos netos": [
    {
      "año": "",
      "total": ""
    }
  ],
  "costo de ventas": [
    {
      "año": "",
      "total": ""
    }
  ],
  "costo de servicios": [
    {
      "año": "",
      "total": ""
    }
  ]
}'''
        )
    
    output = gr.Code(label="API Response", lines=10, language="json")
    submit_btn = gr.Button("Submit")
    
    submit_btn.click(fn=gradio_interface, inputs=[file_input, json_input], outputs=output)

# Launch the interface
demo.launch()