DePol1 commited on
Commit
e3df6c8
·
verified ·
1 Parent(s): 8c5f849

Update frontend/web/modules/api_generator.py

Browse files
Files changed (1) hide show
  1. frontend/web/modules/api_generator.py +358 -2
frontend/web/modules/api_generator.py CHANGED
@@ -120,6 +120,24 @@ def show():
120
 
121
  modules = []
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
124
  if st.session_state.get('global_df') is not None:
125
  df = st.session_state.global_df
@@ -281,6 +299,7 @@ def show():
281
  st.metric("Tecnología", technology.split(" ")[0])
282
 
283
  with summary_col2:
 
284
  st.metric("Base de datos", database.split(" ")[0])
285
  st.metric("Autenticación", "Sí" if include_auth else "No")
286
 
@@ -341,7 +360,6 @@ def show():
341
  file_name=f"{project_name}.zip",
342
  mime="application/zip",
343
  use_container_width=True
344
- # ❌ NO usar on_click - ya registramos la métrica al generar
345
  )
346
 
347
  with st.expander("🔗 Endpoints Generados", expanded=True):
@@ -350,6 +368,344 @@ def show():
350
  except Exception as e:
351
  st.error(f"❌ Error generando API: {str(e)}")
352
  st.error("💡 Revisa la configuración y vuelve a intentar")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
  # CONTINUARÁ EN LA SIGUIENTE PARTE...
355
  # CONTINUACIÓN DE api_generator.py
@@ -359,7 +715,7 @@ def infer_entity_name(filename):
359
  name = filename.split('.')[0].lower()
360
 
361
  entity_map = {
362
- 'clientes': 'usuarios',
363
  'users': 'usuarios',
364
  'products': 'productos',
365
  'items': 'productos',
 
120
 
121
  modules = []
122
 
123
+ # ✅✅✅ CORRECCIÓN: AGREGAR MÓDULO USUARIOS AUTOMÁTICAMENTE SI JWT ESTÁ ACTIVADO
124
+ if include_auth:
125
+ # Verificar que no exista ya un módulo 'usuarios' en los módulos que se agregarán
126
+ existing_module_names = [m['name'] for m in modules]
127
+ if 'usuarios' not in existing_module_names:
128
+ modules.append({
129
+ 'name': 'usuarios',
130
+ 'route': '/api/usuarios',
131
+ 'source': 'system', # Nuevo tipo para módulos del sistema
132
+ 'type': 'usuarios',
133
+ 'record_count': 50,
134
+ 'include_images': False,
135
+ 'image_source': None,
136
+ 'categorias_seleccionadas': []
137
+ })
138
+ st.success("✅ Módulo de usuarios creado automáticamente para autenticación JWT")
139
+
140
+ # EL RESTO DEL CÓDIGO SE MANTIENE IGUAL...
141
  if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
142
  if st.session_state.get('global_df') is not None:
143
  df = st.session_state.global_df
 
299
  st.metric("Tecnología", technology.split(" ")[0])
300
 
301
  with summary_col2:
302
+ # ✅✅✅ CORRECCIÓN: Error de sintaxis corregido - faltaba cerrar el paréntesis
303
  st.metric("Base de datos", database.split(" ")[0])
304
  st.metric("Autenticación", "Sí" if include_auth else "No")
305
 
 
360
  file_name=f"{project_name}.zip",
361
  mime="application/zip",
362
  use_container_width=True
 
363
  )
364
 
365
  with st.expander("🔗 Endpoints Generados", expanded=True):
 
368
  except Exception as e:
369
  st.error(f"❌ Error generando API: {str(e)}")
370
  st.error("💡 Revisa la configuración y vuelve a intentar")
371
+ # def show():
372
+ # st.header("⚡ Generador de API Profesional - E-commerce")
373
+
374
+ # # Configuración de API Keys - ACTUALIZADA CON PIXABAY
375
+ # with st.expander("🔑 Configuración de APIs Externas", expanded=False):
376
+ # # Valores por defecto para ambas APIs
377
+ # if 'pixabay_api_key' not in st.session_state:
378
+ # st.session_state['pixabay_api_key'] = "52812318-583c94721ffbb74a4f0c5684d"
379
+
380
+ # if 'pexels_api_key' not in st.session_state:
381
+ # st.session_state['pexels_api_key'] = "jPUxO9Zkb1OzitGkAmI9PeTe3oxqipfsYI3vdfCm0pg8QHFpUeSqVsNS"
382
+
383
+ # col1, col2 = st.columns(2)
384
+
385
+ # with col1:
386
+ # pixabay_api_key = st.text_input(
387
+ # "API Key de Pixabay 🥇:",
388
+ # value=st.session_state['pixabay_api_key'],
389
+ # type="password",
390
+ # help="Obtén tu API key gratis en https://pixabay.com/api/docs/"
391
+ # )
392
+ # st.session_state['pixabay_api_key'] = pixabay_api_key
393
+
394
+ # with col2:
395
+ # pexels_api_key = st.text_input(
396
+ # "API Key de Pexels 🥈:",
397
+ # value=st.session_state['pexels_api_key'],
398
+ # type="password",
399
+ # help="Obtén tu API key gratis en https://www.pexels.com/api/"
400
+ # )
401
+ # st.session_state['pexels_api_key'] = pexels_api_key
402
+
403
+ # # ✅✅✅ CORREGIDO: Inyectar AMBAS API keys ANTES de generar cualquier dato
404
+ # from utils.image_generator import configure_image_generator
405
+ # configure_image_generator(
406
+ # pexels_api_key=st.session_state['pexels_api_key'],
407
+ # pixabay_api_key=st.session_state['pixabay_api_key']
408
+ # )
409
+
410
+ # # ✅ Verificar que las API keys se configuraron correctamente
411
+ # from utils.image_generator import image_generator
412
+ # apis_configuradas = []
413
+
414
+ # if image_generator.pixabay_api_key and image_generator.pixabay_api_key != "TU_API_KEY_PIXABAY_AQUI":
415
+ # apis_configuradas.append("🥈 Pixabay") # Cambiado a 🥈
416
+
417
+ # if image_generator.pexels_api_key and image_generator.pexels_api_key != "TU_API_KEY_PEXELS_AQUI":
418
+ # apis_configuradas.append("🥉 Pexels") # Cambiado a 🥉
419
+
420
+ # # ✅ AGREGADO: Verificar Lexica (siempre disponible)
421
+ # apis_configuradas.append("🥇 Lexica")
422
+
423
+ # if apis_configuradas:
424
+ # st.success(f"✅ APIs configuradas: {', '.join(apis_configuradas)}")
425
+ # else:
426
+ # st.warning("⚠️ No hay APIs configuradas - Se usarán placeholders e IA")
427
+
428
+ # # Verificar datos globales
429
+ # if st.session_state.get('global_df') is None:
430
+ # st.warning("📤 No hay datos cargados en el sistema")
431
+ # st.info("💡 Carga un archivo en la barra lateral para generar API desde datos reales, o usa datos mock")
432
+
433
+ # st.subheader("🎯 Configuración de la API")
434
+
435
+ # # CONFIGURACIÓN PRINCIPAL
436
+ # col1, col2 = st.columns(2)
437
+
438
+ # with col1:
439
+ # api_type = st.radio(
440
+ # "Tipo de API:",
441
+ # ["🚀 Desde datos cargados", "🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"],
442
+ # help="Genera API desde tus datos, con datos de prueba, o combinando ambos"
443
+ # )
444
+
445
+ # technology = st.selectbox(
446
+ # "Tecnología del backend:",
447
+ # ["FastAPI (Python - Recomendado)", "Flask (Python)", "Django (Python)", "Spring Boot (Java)", "Express.js (Node.js)"],
448
+ # index=0
449
+ # )
450
+
451
+ # database = st.selectbox(
452
+ # "Base de datos:",
453
+ # ["SQLite (Desarrollo)", "PostgreSQL (Producción)", "MySQL (Producción)", "MongoDB (NoSQL)"],
454
+ # index=0
455
+ # )
456
+
457
+ # with col2:
458
+ # project_name = st.text_input(
459
+ # "Nombre del proyecto:",
460
+ # value="mi_api_ecommerce",
461
+ # help="Nombre de la carpeta y proyecto"
462
+ # )
463
+
464
+ # api_version = st.text_input(
465
+ # "Versión de la API:",
466
+ # value="1.0.0",
467
+ # help="Versión semántica (ej: 1.0.0)"
468
+ # )
469
+
470
+ # include_auth = st.checkbox("🔐 Incluir autenticación JWT", value=True)
471
+ # include_docs = st.checkbox("📚 Incluir documentación Swagger", value=True)
472
+ # include_docker = st.checkbox("🐳 Incluir Docker y Docker Compose", value=True)
473
+
474
+ # # CONFIGURACIÓN DE MÓDULOS/ENTIDADES
475
+ # st.subheader("🏗️ Módulos de la API E-commerce")
476
+
477
+ # modules = []
478
+
479
+ # if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
480
+ # if st.session_state.get('global_df') is not None:
481
+ # df = st.session_state.global_df
482
+ # filename = st.session_state.global_filename
483
+
484
+ # st.success(f"📊 Datos cargados: {filename}")
485
+
486
+ # main_entity = infer_entity_name(filename)
487
+
488
+ # with st.expander(f"🔧 Configurar módulo: {main_entity}", expanded=True):
489
+ # module_name = st.text_input("Nombre del módulo:", value=main_entity, key="main_module")
490
+ # base_route = st.text_input("Ruta base:", value=f"/{main_entity}", key="main_route")
491
+
492
+ # st.write("**Configuración de campos:**")
493
+ # field_config = {}
494
+ # for col in df.columns:
495
+ # col1, col2, col3 = st.columns([2, 2, 1])
496
+ # with col1:
497
+ # field_name = st.text_input("Nombre campo:", value=col, key=f"field_{col}_name")
498
+ # with col2:
499
+ # field_type = st.selectbox(
500
+ # "Tipo:",
501
+ # ["string", "integer", "float", "boolean", "datetime", "email", "url"],
502
+ # key=f"field_{col}_type"
503
+ # )
504
+ # with col3:
505
+ # required = st.checkbox("Requerido", value=True, key=f"field_{col}_req")
506
+
507
+ # field_config[col] = {
508
+ # 'name': field_name,
509
+ # 'type': field_type,
510
+ # 'required': required
511
+ # }
512
+
513
+ # modules.append({
514
+ # 'name': module_name,
515
+ # 'route': base_route,
516
+ # 'source': 'file',
517
+ # 'data': df,
518
+ # 'fields': field_config
519
+ # })
520
+
521
+ # # Agregar módulos adicionales para API Mock
522
+ # if api_type in ["🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"]:
523
+ # st.write("---")
524
+ # st.write("**➕ Agregar módulos mock para E-commerce**")
525
+
526
+ # # MÓDULOS ESENCIALES vs OPCIONALES
527
+ # essential_modules = ["usuarios", "productos", "categorias", "pedidos", "carrito"]
528
+ # optional_modules = ["pagos", "reseñas", "direcciones", "cupones"]
529
+
530
+ # col_ess, col_opt = st.columns(2)
531
+
532
+ # with col_ess:
533
+ # st.write("**🎯 Módulos Esenciales**")
534
+ # essential_selected = st.multiselect(
535
+ # "Seleccionar módulos esenciales:",
536
+ # essential_modules,
537
+ # default=essential_modules,
538
+ # label_visibility="collapsed"
539
+ # )
540
+
541
+ # with col_opt:
542
+ # st.write("**🔧 Módulos Opcionales**")
543
+ # optional_selected = st.multiselect(
544
+ # "Seleccionar módulos opcionales:",
545
+ # optional_modules,
546
+ # default=["pagos", "reseñas"],
547
+ # label_visibility="collapsed"
548
+ # )
549
+
550
+ # mock_modules = essential_selected + optional_selected
551
+
552
+ # for module in mock_modules:
553
+ # with st.expander(f"🎭 Configurar módulo: {module}", expanded=False):
554
+ # module_name = st.text_input("Nombre:", value=module, key=f"mock_{module}_name")
555
+ # base_route = st.text_input("Ruta:", value=f"/{module}", key=f"mock_{module}_route")
556
+ # record_count = st.slider("Número de registros:", 10, 1000, 50, key=f"mock_{module}_count")
557
+
558
+ # # Configuración específica por módulo
559
+ # if module in ["productos"]:
560
+ # include_images = st.checkbox("🖼️ Incluir imágenes reales", value=True, key=f"mock_{module}_images")
561
+ # image_source = st.selectbox(
562
+ # "Fuente de imágenes:",
563
+ # [
564
+ # "🥇 Lexica (Búsquedas específicas con IA)", # PRIMERA
565
+ # "🥈 Pollinations AI (Generadas por IA)", # SEGUNDA
566
+ # "🥉 Pixabay (Precisas, libres de derechos)", # TERCERA
567
+ # "📸 Pexels (Alta calidad)", # CUARTA
568
+ # "🪄 Placeholder (Último recurso)",
569
+ # "🎯 Orden de prioridad automático"
570
+ # ],
571
+ # key=f"mock_{module}_imgsrc"
572
+ # )
573
+
574
+ # categorias_disponibles = [
575
+ # 'Electrónica', 'Tecnología', 'Hogar', 'Ropa', 'Deportes',
576
+ # 'Juguetes', 'Libros', 'Música', 'Belleza', 'Salud',
577
+ # 'Alimentos', 'Bebidas', 'Automotriz', 'Jardín', 'Oficina',
578
+ # 'Comidas Dulces', 'Comidas Saladas', 'Bebidas'
579
+ # ]
580
+
581
+ # categorias_seleccionadas = st.multiselect(
582
+ # f"Categorías de {module}:",
583
+ # categorias_disponibles,
584
+ # default=categorias_disponibles[:5],
585
+ # key=f"mock_{module}_cats"
586
+ # )
587
+
588
+ # if categorias_seleccionadas and any(cat in ['Comidas Dulces', 'Comidas Saladas', 'Bebidas'] for cat in categorias_seleccionadas):
589
+ # st.success("🍽️ **Modo Restaurante Activado**: Se generarán productos especializados (tortas, hamburguesas, bebidas, etc.)")
590
+ # else:
591
+ # include_images = False
592
+ # image_source = None
593
+ # categorias_seleccionadas = []
594
+
595
+ # modules.append({
596
+ # 'name': module_name,
597
+ # 'route': base_route,
598
+ # 'source': 'mock',
599
+ # 'type': module,
600
+ # 'record_count': record_count,
601
+ # 'include_images': include_images,
602
+ # 'image_source': image_source,
603
+ # 'categorias_seleccionadas': categorias_seleccionadas
604
+ # })
605
+
606
+ # # CONFIGURACIÓN AVANZADA
607
+ # st.subheader("⚙️ Configuración Avanzada")
608
+
609
+ # adv_col1, adv_col2 = st.columns(2)
610
+
611
+ # with adv_col1:
612
+ # cors_enabled = st.checkbox("🌐 Habilitar CORS", value=True)
613
+ # rate_limiting = st.checkbox("⏱️ Rate Limiting", value=True)
614
+ # file_uploads = st.checkbox("📁 Manejo de archivos", value=True)
615
+ # include_migrations = st.checkbox("🔄 Migraciones Alembic", value=True)
616
+ # pagination_size = st.slider("Tamaño de paginación:", 10, 100, 25)
617
+
618
+ # with adv_col2:
619
+ # logging_level = st.selectbox("Nivel de logging:", ["DEBUG", "INFO", "WARNING", "ERROR"])
620
+ # include_tests = st.checkbox("🧪 Incluir tests automatizados", value=True)
621
+ # generate_sdk = st.checkbox("📦 Generar SDK cliente", value=True)
622
+ # populate_db = st.checkbox("🌱 Poblar BD con datos mock", value=True)
623
+
624
+ # # GENERACIÓN DE LA API
625
+ # st.subheader("🎉 Generar API")
626
+
627
+ # if not modules:
628
+ # st.warning("Agrega al menos un módulo para generar la API")
629
+ # return
630
+
631
+ # # Mostrar resumen
632
+ # st.write("### 📋 Resumen de la API")
633
+ # summary_col1, summary_col2, summary_col3 = st.columns(3)
634
+
635
+ # with summary_col1:
636
+ # st.metric("Módulos", len(modules))
637
+ # st.metric("Tecnología", technology.split(" ")[0])
638
+
639
+ # with summary_col2:
640
+ # st.metric("Base de datos", database.split(" ")[0])
641
+ # st.metric("Autenticación", "Sí" if include_auth else "No")
642
+
643
+ # with summary_col3:
644
+ # total_records = sum([mod.get('record_count', len(mod.get('data', []))) for mod in modules])
645
+ # st.metric("Registros totales", total_records)
646
+ # st.metric("Docker", "Sí" if include_docker else "No")
647
+
648
+ # # Información del sistema de imágenes - ACTUALIZADA CON LEXICA
649
+ # with st.expander("📸 Sistema de Imágenes Configurado", expanded=False):
650
+ # st.write("**🎯 Orden de Prioridad:**")
651
+ # st.write("1. 🥇 **Lexica** - Búsquedas específicas con AI (Siempre disponible)")
652
+ # st.write("2. 🥈 **Pollinations** - Imágenes generadas por IA coherentes")
653
+ # st.write("3. 🥉 **Pixabay** - Fotos reales libres de derechos")
654
+ # st.write("4. 📸 **Pexels** - Backup con calidad alta")
655
+ # st.write("5. 🪄 **Placeholder** - Último recurso (Siempre disponible)")
656
+
657
+ # st.info("**💡 Orden automático:** Lexica → Pollinations → Pixabay → Pexels → Placeholder")
658
+
659
+ # if apis_configuradas:
660
+ # st.success(f"**APIs Configuradas:** {', '.join(apis_configuradas)}")
661
+ # else:
662
+ # st.info("**Modo automático:** Se usará Lexica + Pollinations + Placeholders")
663
+
664
+ # if st.button("⚡ Generar API Completa", type="primary", use_container_width=True):
665
+ # with st.spinner("🚀 Generando API profesional para E-commerce..."):
666
+ # try:
667
+ # api_structure = generate_complete_api(
668
+ # project_name=project_name,
669
+ # technology=technology,
670
+ # database=database,
671
+ # modules=modules,
672
+ # include_auth=include_auth,
673
+ # include_docs=include_docs,
674
+ # include_docker=include_docker,
675
+ # api_version=api_version,
676
+ # cors_enabled=cors_enabled,
677
+ # rate_limiting=rate_limiting,
678
+ # file_uploads=file_uploads,
679
+ # include_migrations=include_migrations,
680
+ # pagination_size=pagination_size,
681
+ # include_tests=include_tests,
682
+ # generate_sdk=generate_sdk,
683
+ # logging_level=logging_level,
684
+ # populate_db=populate_db
685
+ # )
686
+
687
+ # zip_buffer = create_api_zip(api_structure, project_name)
688
+
689
+ # st.success("✅ API generada exitosamente!")
690
+
691
+ # with st.expander("🚀 Instrucciones de Despliegue", expanded=True):
692
+ # show_deployment_instructions(technology, database, project_name)
693
+
694
+ # st.download_button(
695
+ # label="📥 Descargar API Completa",
696
+ # data=zip_buffer,
697
+ # file_name=f"{project_name}.zip",
698
+ # mime="application/zip",
699
+ # use_container_width=True
700
+ # # ❌ NO usar on_click - ya registramos la métrica al generar
701
+ # )
702
+
703
+ # with st.expander("🔗 Endpoints Generados", expanded=True):
704
+ # show_generated_endpoints(modules)
705
+
706
+ # except Exception as e:
707
+ # st.error(f"❌ Error generando API: {str(e)}")
708
+ # st.error("💡 Revisa la configuración y vuelve a intentar")
709
 
710
  # CONTINUARÁ EN LA SIGUIENTE PARTE...
711
  # CONTINUACIÓN DE api_generator.py
 
715
  name = filename.split('.')[0].lower()
716
 
717
  entity_map = {
718
+ # 'clientes': 'usuarios',
719
  'users': 'usuarios',
720
  'products': 'productos',
721
  'items': 'productos',