angelsg213 commited on
Commit
5f57a8c
·
verified ·
1 Parent(s): 4b977ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +355 -196
app.py CHANGED
@@ -25,6 +25,66 @@ def extraer_texto_pdf(pdf_file):
25
  except Exception as e:
26
  return f"Error: {str(e)}"
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # ============= ASISTENTE IA CONVERSACIONAL =============
29
  def asistente_ia_factura(texto, pregunta_usuario):
30
  """Asistente IA que explica conceptos, responde preguntas y da consejos sobre facturas"""
@@ -88,52 +148,6 @@ Responde ahora:"""
88
 
89
  return "❌ No se pudo obtener respuesta del asistente IA", None
90
 
91
- # ============= GENERAR AUDIO DE LA RESPUESTA CON MODELO MEJORADO =============
92
- def generar_audio_respuesta(texto, client):
93
- """Convierte la respuesta de texto a audio usando TTS avanzado"""
94
-
95
- modelos_tts = [
96
- "facebook/mms-tts-spa",
97
- "microsoft/speecht5_tts",
98
- "suno/bark",
99
- "facebook/fastspeech2-en-200_speaker-cv4",
100
- ]
101
-
102
- # Limitar texto para TTS
103
- texto_corto = texto[:400] if len(texto) > 400 else texto
104
-
105
- for modelo in modelos_tts:
106
- try:
107
- print(f"🔊 Generando audio con: {modelo}")
108
-
109
- # Intentar generar audio
110
- audio_bytes = client.text_to_speech(
111
- text=texto_corto,
112
- model=modelo
113
- )
114
-
115
- # Guardar audio
116
- timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
117
- audio_path = f"respuesta_audio_{timestamp}.wav"
118
-
119
- with open(audio_path, "wb") as f:
120
- if isinstance(audio_bytes, bytes):
121
- f.write(audio_bytes)
122
- else:
123
- # Si es un generador, escribir el contenido
124
- for chunk in audio_bytes:
125
- f.write(chunk)
126
-
127
- print(f"✅ Audio generado exitosamente: {audio_path}")
128
- return audio_path
129
-
130
- except Exception as e:
131
- print(f"❌ Error con {modelo}: {str(e)}")
132
- continue
133
-
134
- print("⚠️ No se pudo generar audio con ningún modelo")
135
- return None
136
-
137
  # ============= ANÁLISIS DE SENTIMIENTO DE FACTURA =============
138
  def analizar_sentimiento_factura(texto, client):
139
  """Analiza si la factura tiene alertas, urgencias o problemas"""
@@ -233,9 +247,9 @@ Responde solo con el nombre de la categoría:"""
233
  except:
234
  return "📁 **Categoría:** No clasificada"
235
 
236
- # ============= TRADUCTOR MULTIIDIOMA =============
237
- def traducir_factura(texto, idioma_destino, client):
238
- """Traduce el contenido de la factura a otro idioma"""
239
 
240
  idiomas = {
241
  "Inglés": "English",
@@ -247,23 +261,280 @@ def traducir_factura(texto, idioma_destino, client):
247
 
248
  idioma = idiomas.get(idioma_destino, "English")
249
 
250
- prompt = f"""Traduce este resumen de factura al {idioma}. Mantén el formato y estructura:
 
251
 
252
  {texto[:2000]}
253
 
254
  Traducción:"""
255
 
256
  try:
257
- response = client.chat.completions.create(
258
  model="Qwen/Qwen2.5-72B-Instruct",
259
- messages=[{"role": "user", "content": prompt}],
260
  max_tokens=1000,
261
  temperature=0.3
262
  )
263
-
264
- return response.choices[0].message.content
265
  except:
266
- return "❌ Error en la traducción"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
  # ============= DETECTOR DE FRAUDE =============
269
  def detectar_fraude_factura(datos_json, texto, client):
@@ -636,6 +907,7 @@ Responde en JSON:
636
  pass
637
 
638
  return {"es_valida": True, "errores": [], "advertencias": [], "nivel_cumplimiento": "completo"}
 
639
  def extraer_gastos_deducibles(datos_json, texto, client):
640
  """Identifica qué parte de la factura es deducible fiscalmente"""
641
 
@@ -895,109 +1167,6 @@ def json_a_csv(datos_json):
895
 
896
  return pd.DataFrame(filas)
897
 
898
- # ============= GENERAR CSV TABULAR DE TRADUCCIÓN =============
899
- def traduccion_a_csv(datos_json, traduccion_texto, idioma):
900
- """Convierte la factura traducida en un CSV tabular estructurado"""
901
-
902
- if not datos_json:
903
- return None
904
-
905
- timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
906
- csv_filename = f"factura_traducida_{idioma}_{timestamp}.csv"
907
-
908
- filas = []
909
-
910
- # Intentar traducir cada campo
911
- token = os.getenv("aa")
912
- if token:
913
- client = InferenceClient(token=token)
914
-
915
- # Traducir secciones
916
- try:
917
- # Información general
918
- filas.append({
919
- 'Sección': 'INFORMACIÓN GENERAL' if idioma == 'Español' else 'GENERAL INFORMATION',
920
- 'Campo': 'Número de Factura' if idioma == 'Español' else 'Invoice Number',
921
- 'Valor': datos_json.get('numero_factura', 'N/A'),
922
- 'Tipo': 'Identificador' if idioma == 'Español' else 'Identifier'
923
- })
924
- filas.append({
925
- 'Sección': 'INFORMACIÓN GENERAL' if idioma == 'Español' else 'GENERAL INFORMATION',
926
- 'Campo': 'Fecha' if idioma == 'Español' else 'Date',
927
- 'Valor': datos_json.get('fecha', 'N/A'),
928
- 'Tipo': 'Fecha' if idioma == 'Español' else 'Date'
929
- })
930
-
931
- # Emisor
932
- if 'emisor' in datos_json:
933
- emisor = datos_json['emisor']
934
- if isinstance(emisor, dict):
935
- for key, value in emisor.items():
936
- filas.append({
937
- 'Sección': 'EMISOR' if idioma == 'Español' else 'ISSUER',
938
- 'Campo': key.replace('_', ' ').title(),
939
- 'Valor': str(value),
940
- 'Tipo': 'Información' if idioma == 'Español' else 'Information'
941
- })
942
-
943
- # Cliente
944
- if 'cliente' in datos_json:
945
- cliente = datos_json['cliente']
946
- if isinstance(cliente, dict):
947
- for key, value in cliente.items():
948
- filas.append({
949
- 'Sección': 'CLIENTE' if idioma == 'Español' else 'CLIENT',
950
- 'Campo': key.replace('_', ' ').title(),
951
- 'Valor': str(value),
952
- 'Tipo': 'Información' if idioma == 'Español' else 'Information'
953
- })
954
-
955
- # Productos
956
- productos = datos_json.get('productos', [])
957
- if productos:
958
- for i, prod in enumerate(productos, 1):
959
- filas.append({
960
- 'Sección': 'PRODUCTOS' if idioma == 'Español' else 'PRODUCTS',
961
- 'Campo': f'Producto {i}' if idioma == 'Español' else f'Product {i}',
962
- 'Valor': prod.get('descripcion', 'N/A'),
963
- 'Tipo': 'Descripción' if idioma == 'Español' else 'Description'
964
- })
965
- filas.append({
966
- 'Sección': 'PRODUCTOS' if idioma == 'Español' else 'PRODUCTS',
967
- 'Campo': f'Cantidad P{i}' if idioma == 'Español' else f'Quantity P{i}',
968
- 'Valor': str(prod.get('cantidad', '')),
969
- 'Tipo': 'Numérico' if idioma == 'Español' else 'Numeric'
970
- })
971
-
972
- # Totales
973
- totales = datos_json.get('totales', {})
974
- if totales:
975
- filas.append({
976
- 'Sección': 'TOTALES' if idioma == 'Español' else 'TOTALS',
977
- 'Campo': 'Base Imponible' if idioma == 'Español' else 'Taxable Base',
978
- 'Valor': str(totales.get('base_imponible', 0)),
979
- 'Tipo': 'Monetario' if idioma == 'Español' else 'Monetary'
980
- })
981
- filas.append({
982
- 'Sección': 'TOTALES' if idioma == 'Español' else 'TOTALS',
983
- 'Campo': 'IVA' if idioma == 'Español' else 'VAT',
984
- 'Valor': str(totales.get('iva', 0)),
985
- 'Tipo': 'Monetario' if idioma == 'Español' else 'Monetary'
986
- })
987
- filas.append({
988
- 'Sección': 'TOTALES' if idioma == 'Español' else 'TOTALS',
989
- 'Campo': 'TOTAL',
990
- 'Valor': str(totales.get('total', 0)),
991
- 'Tipo': 'Monetario' if idioma == 'Español' else 'Monetary'
992
- })
993
- except:
994
- pass
995
-
996
- df = pd.DataFrame(filas)
997
- df.to_csv(csv_filename, index=False, encoding='utf-8-sig', sep=',')
998
-
999
- return csv_filename
1000
-
1001
  # ============= GENERAR PDF TEMPLATES =============
1002
  def generar_pdf_clasico(csv_file, datos_json):
1003
  timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
@@ -1391,11 +1560,11 @@ with gr.Blocks(title="Extractor de Facturas con IA Avanzada") as demo:
1391
  - ✅ Recomendaciones de negociación
1392
  """)
1393
 
1394
- # ============= TAB 4: TRADUCCIÓN MULTIIDIOMA =============
1395
  with gr.Tab("🌍 Traducción Internacional"):
1396
  gr.Markdown("""
1397
  # 🌐 Traductor Profesional de Facturas
1398
- ### Traduce tu factura a 5 idiomas y exporta a CSV
1399
  """)
1400
 
1401
  with gr.Row():
@@ -1410,23 +1579,29 @@ with gr.Blocks(title="Extractor de Facturas con IA Avanzada") as demo:
1410
 
1411
  gr.Markdown("---")
1412
  gr.Markdown("### Exportar Traducción")
1413
- btn_csv_traduccion = gr.Button("📥 Descargar CSV Tabular Traducido", variant="secondary")
1414
- csv_traduccion_output = gr.File(label="📊 CSV Traducido (Formato Tabular)")
1415
 
1416
  with gr.Column():
1417
- gr.Markdown("### 📝 Resultado de la Traducción")
 
 
 
 
 
 
 
1418
  resultado_traduccion = gr.Textbox(
1419
- label="Texto traducido",
1420
- lines=15,
1421
  placeholder="La traducción aparecerá aquí..."
1422
  )
1423
 
1424
  gr.Markdown("""
1425
  💡 **Características:**
1426
  - 🌍 Traducción profesional automática
1427
- - 📊 Exporta la traducción a formato CSV
 
1428
  - ✅ Mantiene la estructura original
1429
- - 🚀 Traducción en segundos
1430
  """)
1431
 
1432
  gr.Markdown("---")
@@ -1435,7 +1610,7 @@ with gr.Blocks(title="Extractor de Facturas con IA Avanzada") as demo:
1435
 
1436
  1. **📄 Extracción Automática:** Sube tu PDF y obtén datos estructurados en CSV tabular (separado por comas)
1437
  2. **🤖 Asistente IA con Avatar:** Pregunta cualquier duda y escucha la respuesta con voz robótica
1438
- 3. **🔬 Análisis Avanzado:** 7 herramientas profesionales de análisis
1439
  4. **🌍 Traducción:** Traduce y exporta a CSV en 5 idiomas
1440
 
1441
  ---
@@ -1468,6 +1643,7 @@ with gr.Blocks(title="Extractor de Facturas con IA Avanzada") as demo:
1468
 
1469
  **🌐 Traducción Avanzada:**
1470
  - Traduce a 5 idiomas
 
1471
  - Exporta traducciones a CSV
1472
  - Mantiene formato profesional
1473
 
@@ -1617,28 +1793,16 @@ with gr.Blocks(title="Extractor de Facturas con IA Avanzada") as demo:
1617
  client = InferenceClient(token=token)
1618
  return f"### 📊 Resumen Ejecutivo - Dashboard\n\n{generar_resumen_ejecutivo(datos_json, client)}"
1619
 
1620
- def ejecutar_traduccion(texto, idioma):
 
1621
  if not texto:
1622
- return "❌ Procesa una factura primero"
1623
  token = os.getenv("aa")
1624
  if not token:
1625
- return "❌ Error de configuración"
1626
  client = InferenceClient(token=token)
1627
- return traducir_factura(texto, idioma, client)
1628
-
1629
- # Variable de estado para la traducción
1630
- traduccion_texto_state = gr.State()
1631
- idioma_actual_state = gr.State()
1632
-
1633
- def ejecutar_traduccion_con_estado(texto, idioma):
1634
- resultado = ejecutar_traduccion(texto, idioma)
1635
- return resultado, resultado, idioma
1636
-
1637
- def generar_csv_traduccion(traduccion, idioma):
1638
- if not traduccion or traduccion.startswith("❌"):
1639
- return None
1640
- csv_file = traduccion_a_csv(traduccion, idioma)
1641
- return csv_file
1642
 
1643
  def ejecutar_duplicados(datos_json):
1644
  if not datos_json:
@@ -1749,7 +1913,7 @@ with gr.Blocks(title="Extractor de Facturas con IA Avanzada") as demo:
1749
  **Advertencias:**
1750
  {chr(10).join([f"- ⚠️ {a}" for a in resultado.get('advertencias', [])]) if resultado.get('advertencias') else '- No hay advertencias'}"""
1751
 
1752
- # Conectar nuevas funcionalidades
1753
  btn_duplicados.click(fn=ejecutar_duplicados, inputs=[datos_json_state], outputs=[resultado_duplicados])
1754
  btn_impacto.click(fn=ejecutar_impacto, inputs=[datos_json_state], outputs=[resultado_impacto])
1755
  btn_recordatorios.click(fn=ejecutar_recordatorios, inputs=[datos_json_state], outputs=[resultado_recordatorios])
@@ -1764,16 +1928,11 @@ with gr.Blocks(title="Extractor de Facturas con IA Avanzada") as demo:
1764
  btn_prediccion.click(fn=ejecutar_prediccion, inputs=[datos_json_state], outputs=[resultado_prediccion])
1765
  btn_ejecutivo.click(fn=ejecutar_ejecutivo, inputs=[datos_json_state], outputs=[resultado_ejecutivo])
1766
 
 
1767
  btn_traducir.click(
1768
- fn=ejecutar_traduccion_con_estado,
1769
- inputs=[texto_extraido, idioma_selector],
1770
- outputs=[resultado_traduccion, traduccion_texto_state, idioma_actual_state]
1771
- )
1772
-
1773
- btn_csv_traduccion.click(
1774
- fn=generar_csv_traduccion,
1775
- inputs=[traduccion_texto_state, idioma_actual_state],
1776
- outputs=[csv_traduccion_output]
1777
  )
1778
 
1779
  if __name__ == "__main__":
 
25
  except Exception as e:
26
  return f"Error: {str(e)}"
27
 
28
+ # ============= GENERAR AUDIO CON EMOCIÓN MEJORADO =============
29
+ def generar_audio_respuesta(texto, client):
30
+ """Convierte la respuesta de texto a audio usando modelos TTS con emoción"""
31
+
32
+ # Lista de modelos TTS con mejor calidad emocional
33
+ modelos_tts = [
34
+ "facebook/mms-tts-spa", # Mejor para español
35
+ "espnet/kan-bayashi_ljspeech_vits", # VITS con emoción
36
+ "suno/bark-small", # Bark tiene mejor expresividad
37
+ "microsoft/speecht5_tts",
38
+ ]
39
+
40
+ # Limitar y optimizar texto para TTS
41
+ texto_limpio = texto.replace("*", "").replace("#", "").replace("`", "")
42
+ texto_corto = texto_limpio[:500] if len(texto_limpio) > 500 else texto_limpio
43
+
44
+ # Agregar puntuación para mejor prosodia
45
+ if not texto_corto.endswith(('.', '!', '?')):
46
+ texto_corto += "."
47
+
48
+ print(f"🎤 Generando audio: {texto_corto[:100]}...")
49
+
50
+ for modelo in modelos_tts:
51
+ try:
52
+ print(f"🔊 Intentando con: {modelo}")
53
+
54
+ # Generar audio con el modelo
55
+ audio_bytes = client.text_to_speech(
56
+ text=texto_corto,
57
+ model=modelo
58
+ )
59
+
60
+ # Guardar audio
61
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
62
+ audio_path = f"respuesta_audio_{timestamp}.wav"
63
+
64
+ with open(audio_path, "wb") as f:
65
+ if isinstance(audio_bytes, bytes):
66
+ f.write(audio_bytes)
67
+ else:
68
+ # Si es un generador, escribir el contenido
69
+ for chunk in audio_bytes:
70
+ if isinstance(chunk, bytes):
71
+ f.write(chunk)
72
+
73
+ # Verificar que el archivo se creó correctamente
74
+ if os.path.exists(audio_path) and os.path.getsize(audio_path) > 0:
75
+ print(f"✅ Audio generado exitosamente con {modelo}: {audio_path}")
76
+ return audio_path
77
+ else:
78
+ print(f"⚠️ Archivo vacío o no creado con {modelo}")
79
+ continue
80
+
81
+ except Exception as e:
82
+ print(f"❌ Error con {modelo}: {str(e)}")
83
+ continue
84
+
85
+ print("⚠️ No se pudo generar audio con ningún modelo")
86
+ return None
87
+
88
  # ============= ASISTENTE IA CONVERSACIONAL =============
89
  def asistente_ia_factura(texto, pregunta_usuario):
90
  """Asistente IA que explica conceptos, responde preguntas y da consejos sobre facturas"""
 
148
 
149
  return "❌ No se pudo obtener respuesta del asistente IA", None
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  # ============= ANÁLISIS DE SENTIMIENTO DE FACTURA =============
152
  def analizar_sentimiento_factura(texto, client):
153
  """Analiza si la factura tiene alertas, urgencias o problemas"""
 
247
  except:
248
  return "📁 **Categoría:** No clasificada"
249
 
250
+ # ============= TRADUCTOR MULTIIDIOMA CON CSV TABULAR =============
251
+ def traducir_factura_con_csv(datos_json, texto, idioma_destino, client):
252
+ """Traduce la factura y genera tanto texto como CSV tabular"""
253
 
254
  idiomas = {
255
  "Inglés": "English",
 
261
 
262
  idioma = idiomas.get(idioma_destino, "English")
263
 
264
+ # 1. Traducir el texto completo
265
+ prompt_texto = f"""Traduce este resumen de factura al {idioma}. Mantén el formato y estructura:
266
 
267
  {texto[:2000]}
268
 
269
  Traducción:"""
270
 
271
  try:
272
+ response_texto = client.chat.completions.create(
273
  model="Qwen/Qwen2.5-72B-Instruct",
274
+ messages=[{"role": "user", "content": prompt_texto}],
275
  max_tokens=1000,
276
  temperature=0.3
277
  )
278
+ texto_traducido = response_texto.choices[0].message.content
 
279
  except:
280
+ texto_traducido = "❌ Error en la traducción del texto"
281
+
282
+ # 2. Crear DataFrame traducido
283
+ if not datos_json:
284
+ return texto_traducido, None, None
285
+
286
+ # Traducir etiquetas según el idioma
287
+ traducciones = {
288
+ "Inglés": {
289
+ "seccion": "Section",
290
+ "campo": "Field",
291
+ "valor": "Value",
292
+ "tipo": "Type",
293
+ "info_general": "GENERAL INFORMATION",
294
+ "numero_factura": "Invoice Number",
295
+ "fecha": "Date",
296
+ "identificador": "Identifier",
297
+ "emisor": "ISSUER",
298
+ "nombre": "Name",
299
+ "nif": "Tax ID",
300
+ "direccion": "Address",
301
+ "cliente": "CLIENT",
302
+ "productos": "PRODUCTS",
303
+ "producto": "Product",
304
+ "cantidad": "Quantity",
305
+ "precio_unitario": "Unit Price",
306
+ "total_producto": "Total",
307
+ "descripcion": "Description",
308
+ "numerico": "Numeric",
309
+ "monetario": "Monetary",
310
+ "totales": "TOTALS",
311
+ "base_imponible": "Taxable Base",
312
+ "iva": "VAT",
313
+ "total": "TOTAL",
314
+ "informacion": "Information"
315
+ },
316
+ "Francés": {
317
+ "seccion": "Section",
318
+ "campo": "Champ",
319
+ "valor": "Valeur",
320
+ "tipo": "Type",
321
+ "info_general": "INFORMATIONS GÉNÉRALES",
322
+ "numero_factura": "Numéro de Facture",
323
+ "fecha": "Date",
324
+ "identificador": "Identifiant",
325
+ "emisor": "ÉMETTEUR",
326
+ "nombre": "Nom",
327
+ "nif": "NIF",
328
+ "direccion": "Adresse",
329
+ "cliente": "CLIENT",
330
+ "productos": "PRODUITS",
331
+ "producto": "Produit",
332
+ "cantidad": "Quantité",
333
+ "precio_unitario": "Prix Unitaire",
334
+ "total_producto": "Total",
335
+ "descripcion": "Description",
336
+ "numerico": "Numérique",
337
+ "monetario": "Monétaire",
338
+ "totales": "TOTAUX",
339
+ "base_imponible": "Base Imposable",
340
+ "iva": "TVA",
341
+ "total": "TOTAL",
342
+ "informacion": "Information"
343
+ },
344
+ "Alemán": {
345
+ "seccion": "Abschnitt",
346
+ "campo": "Feld",
347
+ "valor": "Wert",
348
+ "tipo": "Typ",
349
+ "info_general": "ALLGEMEINE INFORMATIONEN",
350
+ "numero_factura": "Rechnungsnummer",
351
+ "fecha": "Datum",
352
+ "identificador": "Kennung",
353
+ "emisor": "AUSSTELLER",
354
+ "nombre": "Name",
355
+ "nif": "Steuernummer",
356
+ "direccion": "Adresse",
357
+ "cliente": "KUNDE",
358
+ "productos": "PRODUKTE",
359
+ "producto": "Produkt",
360
+ "cantidad": "Menge",
361
+ "precio_unitario": "Stückpreis",
362
+ "total_producto": "Gesamt",
363
+ "descripcion": "Beschreibung",
364
+ "numerico": "Numerisch",
365
+ "monetario": "Monetär",
366
+ "totales": "SUMMEN",
367
+ "base_imponible": "Steuerbemessungsgrundlage",
368
+ "iva": "MwSt",
369
+ "total": "GESAMT",
370
+ "informacion": "Information"
371
+ },
372
+ "Italiano": {
373
+ "seccion": "Sezione",
374
+ "campo": "Campo",
375
+ "valor": "Valore",
376
+ "tipo": "Tipo",
377
+ "info_general": "INFORMAZIONI GENERALI",
378
+ "numero_factura": "Numero Fattura",
379
+ "fecha": "Data",
380
+ "identificador": "Identificatore",
381
+ "emisor": "EMITTENTE",
382
+ "nombre": "Nome",
383
+ "nif": "Partita IVA",
384
+ "direccion": "Indirizzo",
385
+ "cliente": "CLIENTE",
386
+ "productos": "PRODOTTI",
387
+ "producto": "Prodotto",
388
+ "cantidad": "Quantità",
389
+ "precio_unitario": "Prezzo Unitario",
390
+ "total_producto": "Totale",
391
+ "descripcion": "Descrizione",
392
+ "numerico": "Numerico",
393
+ "monetario": "Monetario",
394
+ "totales": "TOTALI",
395
+ "base_imponible": "Imponibile",
396
+ "iva": "IVA",
397
+ "total": "TOTALE",
398
+ "informacion": "Informazione"
399
+ },
400
+ "Portugués": {
401
+ "seccion": "Seção",
402
+ "campo": "Campo",
403
+ "valor": "Valor",
404
+ "tipo": "Tipo",
405
+ "info_general": "INFORMAÇÃO GERAL",
406
+ "numero_factura": "Número da Fatura",
407
+ "fecha": "Data",
408
+ "identificador": "Identificador",
409
+ "emisor": "EMISSOR",
410
+ "nombre": "Nome",
411
+ "nif": "NIF",
412
+ "direccion": "Endereço",
413
+ "cliente": "CLIENTE",
414
+ "productos": "PRODUTOS",
415
+ "producto": "Produto",
416
+ "cantidad": "Quantidade",
417
+ "precio_unitario": "Preço Unitário",
418
+ "total_producto": "Total",
419
+ "descripcion": "Descrição",
420
+ "numerico": "Numérico",
421
+ "monetario": "Monetário",
422
+ "totales": "TOTAIS",
423
+ "base_imponible": "Base Tributável",
424
+ "iva": "IVA",
425
+ "total": "TOTAL",
426
+ "informacion": "Informação"
427
+ }
428
+ }
429
+
430
+ t = traducciones.get(idioma_destino, traducciones["Inglés"])
431
+
432
+ filas = []
433
+
434
+ # Información general
435
+ filas.append({
436
+ t["seccion"]: t["info_general"],
437
+ t["campo"]: t["numero_factura"],
438
+ t["valor"]: datos_json.get('numero_factura', 'N/A'),
439
+ t["tipo"]: t["identificador"]
440
+ })
441
+ filas.append({
442
+ t["seccion"]: t["info_general"],
443
+ t["campo"]: t["fecha"],
444
+ t["valor"]: datos_json.get('fecha', 'N/A'),
445
+ t["tipo"]: t["fecha"]
446
+ })
447
+
448
+ # Emisor
449
+ if 'emisor' in datos_json:
450
+ emisor = datos_json['emisor']
451
+ if isinstance(emisor, dict):
452
+ for key, value in emisor.items():
453
+ campo_traducido = t.get(key, key.replace('_', ' ').title())
454
+ filas.append({
455
+ t["seccion"]: t["emisor"],
456
+ t["campo"]: campo_traducido,
457
+ t["valor"]: str(value),
458
+ t["tipo"]: t["informacion"]
459
+ })
460
+
461
+ # Cliente
462
+ if 'cliente' in datos_json:
463
+ cliente = datos_json['cliente']
464
+ if isinstance(cliente, dict):
465
+ for key, value in cliente.items():
466
+ campo_traducido = t.get(key, key.replace('_', ' ').title())
467
+ filas.append({
468
+ t["seccion"]: t["cliente"],
469
+ t["campo"]: campo_traducido,
470
+ t["valor"]: str(value),
471
+ t["tipo"]: t["informacion"]
472
+ })
473
+
474
+ # Productos
475
+ productos = datos_json.get('productos', datos_json.get('conceptos', datos_json.get('items', [])))
476
+ if productos and len(productos) > 0:
477
+ for i, prod in enumerate(productos, 1):
478
+ filas.append({
479
+ t["seccion"]: t["productos"],
480
+ t["campo"]: f'{t["producto"]} {i}',
481
+ t["valor"]: prod.get('descripcion', 'N/A'),
482
+ t["tipo"]: t["descripcion"]
483
+ })
484
+ filas.append({
485
+ t["seccion"]: t["productos"],
486
+ t["campo"]: f'{t["cantidad"]} P{i}',
487
+ t["valor"]: str(prod.get('cantidad', '')),
488
+ t["tipo"]: t["numerico"]
489
+ })
490
+ filas.append({
491
+ t["seccion"]: t["productos"],
492
+ t["campo"]: f'{t["precio_unitario"]} P{i}',
493
+ t["valor"]: f"{prod.get('precio_unitario', 0)}",
494
+ t["tipo"]: t["monetario"]
495
+ })
496
+ filas.append({
497
+ t["seccion"]: t["productos"],
498
+ t["campo"]: f'{t["total_producto"]} P{i}',
499
+ t["valor"]: f"{prod.get('total', 0)}",
500
+ t["tipo"]: t["monetario"]
501
+ })
502
+
503
+ # Totales
504
+ totales = datos_json.get('totales', {})
505
+ if totales or 'base_imponible' in datos_json or 'total' in datos_json:
506
+ base = totales.get('base_imponible', datos_json.get('base_imponible', 0))
507
+ iva = totales.get('iva', datos_json.get('iva', 0))
508
+ porcentaje_iva = totales.get('porcentaje_iva', datos_json.get('porcentaje_iva', 0))
509
+ total = totales.get('total', datos_json.get('total', 0))
510
+
511
+ filas.append({
512
+ t["seccion"]: t["totales"],
513
+ t["campo"]: t["base_imponible"],
514
+ t["valor"]: f"{base}",
515
+ t["tipo"]: t["monetario"]
516
+ })
517
+ filas.append({
518
+ t["seccion"]: t["totales"],
519
+ t["campo"]: f'{t["iva"]} ({porcentaje_iva}%)',
520
+ t["valor"]: f"{iva}",
521
+ t["tipo"]: t["monetario"]
522
+ })
523
+ filas.append({
524
+ t["seccion"]: t["totales"],
525
+ t["campo"]: t["total"],
526
+ t["valor"]: f"{total}",
527
+ t["tipo"]: t["monetario"]
528
+ })
529
+
530
+ df_traducido = pd.DataFrame(filas)
531
+
532
+ # Guardar CSV
533
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
534
+ csv_filename = f"factura_traducida_{idioma_destino}_{timestamp}.csv"
535
+ df_traducido.to_csv(csv_filename, index=False, encoding='utf-8-sig', sep=',')
536
+
537
+ return texto_traducido, df_traducido, csv_filename
538
 
539
  # ============= DETECTOR DE FRAUDE =============
540
  def detectar_fraude_factura(datos_json, texto, client):
 
907
  pass
908
 
909
  return {"es_valida": True, "errores": [], "advertencias": [], "nivel_cumplimiento": "completo"}
910
+
911
  def extraer_gastos_deducibles(datos_json, texto, client):
912
  """Identifica qué parte de la factura es deducible fiscalmente"""
913
 
 
1167
 
1168
  return pd.DataFrame(filas)
1169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1170
  # ============= GENERAR PDF TEMPLATES =============
1171
  def generar_pdf_clasico(csv_file, datos_json):
1172
  timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
 
1560
  - ✅ Recomendaciones de negociación
1561
  """)
1562
 
1563
+ # ============= TAB 4: TRADUCCIÓN MULTIIDIOMA CON TABLA =============
1564
  with gr.Tab("🌍 Traducción Internacional"):
1565
  gr.Markdown("""
1566
  # 🌐 Traductor Profesional de Facturas
1567
+ ### Traduce tu factura a 5 idiomas con vista tabular y exporta a CSV
1568
  """)
1569
 
1570
  with gr.Row():
 
1579
 
1580
  gr.Markdown("---")
1581
  gr.Markdown("### Exportar Traducción")
1582
+ csv_traduccion_output = gr.File(label="📊 Descargar CSV Tabular Traducido")
 
1583
 
1584
  with gr.Column():
1585
+ gr.Markdown("### 📊 Vista Tabular Traducida")
1586
+ tabla_traduccion = gr.DataFrame(
1587
+ label="Factura traducida en formato tabular",
1588
+ wrap=True
1589
+ )
1590
+
1591
+ gr.Markdown("---")
1592
+ gr.Markdown("### 📝 Texto Traducido")
1593
  resultado_traduccion = gr.Textbox(
1594
+ label="Resumen en texto",
1595
+ lines=10,
1596
  placeholder="La traducción aparecerá aquí..."
1597
  )
1598
 
1599
  gr.Markdown("""
1600
  💡 **Características:**
1601
  - 🌍 Traducción profesional automática
1602
+ - 📊 Vista tabular igual que la factura original
1603
+ - 📥 Exporta a CSV con el mismo formato
1604
  - ✅ Mantiene la estructura original
 
1605
  """)
1606
 
1607
  gr.Markdown("---")
 
1610
 
1611
  1. **📄 Extracción Automática:** Sube tu PDF y obtén datos estructurados en CSV tabular (separado por comas)
1612
  2. **🤖 Asistente IA con Avatar:** Pregunta cualquier duda y escucha la respuesta con voz robótica
1613
+ 3. **🔬 Análisis Avanzado:** 12 herramientas profesionales de análisis
1614
  4. **🌍 Traducción:** Traduce y exporta a CSV en 5 idiomas
1615
 
1616
  ---
 
1643
 
1644
  **🌐 Traducción Avanzada:**
1645
  - Traduce a 5 idiomas
1646
+ - Vista tabular traducida
1647
  - Exporta traducciones a CSV
1648
  - Mantiene formato profesional
1649
 
 
1793
  client = InferenceClient(token=token)
1794
  return f"### 📊 Resumen Ejecutivo - Dashboard\n\n{generar_resumen_ejecutivo(datos_json, client)}"
1795
 
1796
+ # Traducción completa con tabla
1797
+ def ejecutar_traduccion_completa(texto, datos_json, idioma):
1798
  if not texto:
1799
+ return "❌ Procesa una factura primero", None, None
1800
  token = os.getenv("aa")
1801
  if not token:
1802
+ return "❌ Error de configuración", None, None
1803
  client = InferenceClient(token=token)
1804
+ texto_traducido, df_traducido, csv_filename = traducir_factura_con_csv(datos_json, texto, idioma, client)
1805
+ return texto_traducido, df_traducido, csv_filename
 
 
 
 
 
 
 
 
 
 
 
 
 
1806
 
1807
  def ejecutar_duplicados(datos_json):
1808
  if not datos_json:
 
1913
  **Advertencias:**
1914
  {chr(10).join([f"- ⚠️ {a}" for a in resultado.get('advertencias', [])]) if resultado.get('advertencias') else '- No hay advertencias'}"""
1915
 
1916
+ # Conectar funcionalidades
1917
  btn_duplicados.click(fn=ejecutar_duplicados, inputs=[datos_json_state], outputs=[resultado_duplicados])
1918
  btn_impacto.click(fn=ejecutar_impacto, inputs=[datos_json_state], outputs=[resultado_impacto])
1919
  btn_recordatorios.click(fn=ejecutar_recordatorios, inputs=[datos_json_state], outputs=[resultado_recordatorios])
 
1928
  btn_prediccion.click(fn=ejecutar_prediccion, inputs=[datos_json_state], outputs=[resultado_prediccion])
1929
  btn_ejecutivo.click(fn=ejecutar_ejecutivo, inputs=[datos_json_state], outputs=[resultado_ejecutivo])
1930
 
1931
+ # Traducción con tabla
1932
  btn_traducir.click(
1933
+ fn=ejecutar_traduccion_completa,
1934
+ inputs=[texto_extraido, datos_json_state, idioma_selector],
1935
+ outputs=[resultado_traduccion, tabla_traduccion, csv_traduccion_output]
 
 
 
 
 
 
1936
  )
1937
 
1938
  if __name__ == "__main__":