roundb commited on
Commit
4a9de48
Β·
verified Β·
1 Parent(s): ad05bb5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -27
app.py CHANGED
@@ -27,8 +27,20 @@ import gradio as gr
27
  # ── Paths ──────────────────────────────────────────────────────────────────────
28
  BASE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'upload')
29
  BASE = os.path.abspath(BASE)
30
- OUTPUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')
31
- os.makedirs(OUTPUT_DIR, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  # ── SLA fixo por TIPO (tabela da imagem) ──────────────────────────────────────
34
  SLA_MAP = {
@@ -455,31 +467,66 @@ def render_kpi_html(stats: dict, categoria: str) -> str:
455
  # ── ExportaΓ§Γ΅es ────────────────────────────────────────────────────────────────
456
 
457
  def exportar_csv_pivot(categoria: str) -> str:
458
- pivot = build_pivot(DF_GLOBAL, categoria)
459
- ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
460
- nome = f"sla_pivot_{categoria.lower().replace(' ', '_')}_{ts}.csv"
461
- path = os.path.join(OUTPUT_DIR, nome)
462
- pivot.to_csv(path, index=False, encoding='utf-8-sig', sep=';')
463
- return path
 
 
 
 
 
 
 
 
 
 
464
 
465
  def exportar_csv_fact(categoria: str) -> str:
466
- sub = DF_GLOBAL.copy() if categoria == 'GLOBAL' else DF_GLOBAL[DF_GLOBAL['CATEGORIA'] == categoria].copy()
467
- fact = sub[[
468
- 'SUB-CIP', 'PROJETO', 'TIPO', 'TIPO_LABEL', 'RB STATUS', 'CATEGORIA',
469
- 'DATA_ADJ_CLIENTE', 'DATA_PREVISTA', 'TEMPO_EXECUCAO',
470
- 'ATUAL', 'DIFDIAS', 'SLA_FIXO', 'PCT_SLA', 'FAIXA_SLA', 'DATA_CALCULO'
471
- ]].copy()
472
- fact['DATA_ADJ_CLIENTE'] = fact['DATA_ADJ_CLIENTE'].dt.strftime('%d/%m/%Y')
473
- fact['DATA_PREVISTA'] = fact['DATA_PREVISTA'].dt.strftime('%d/%m/%Y')
474
- ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
475
- nome = f"sla_fact_{categoria.lower().replace(' ', '_')}_{ts}.csv"
476
- path = os.path.join(OUTPUT_DIR, nome)
477
- fact.to_csv(path, index=False, encoding='utf-8-sig', sep=';')
478
- return path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
 
480
  def exportar_excel_powerbi() -> str:
 
481
  ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
482
- path = os.path.join(OUTPUT_DIR, f'modelo_sla_powerbi_{ts}.xlsx')
 
 
 
 
 
 
 
483
 
484
  with pd.ExcelWriter(path, engine='openpyxl') as writer:
485
  fact = DF_GLOBAL[[
@@ -702,10 +749,10 @@ with gr.Blocks(title="Dashboard SLA") as demo:
702
  btn_fact = gr.Button("⬇ CSV β€” Dados Calculados", variant="secondary", elem_classes=["btn-export"])
703
  file_fact = gr.File(label="", show_label=False)
704
 
705
- #with gr.Column(scale=1):
706
- #gr.Markdown("**Modelo Power BI** β€” Excel com 6 sheets (Fact + Dims + Pivots)")
707
- #btn_excel = gr.Button("⬇ Excel β€” Power BI", variant="primary", elem_classes=["btn-export"])
708
- #file_excel = gr.File(label="", show_label=False)
709
 
710
  # ── Legenda ──────────────────────────────────────────────────────────────
711
  gr.HTML("""
@@ -744,4 +791,4 @@ if __name__ == '__main__':
744
  share=False,
745
  css=CSS,
746
  theme=gr.themes.Base(),
747
- )
 
27
  # ── Paths ──────────────────────────────────────────────────────────────────────
28
  BASE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'upload')
29
  BASE = os.path.abspath(BASE)
30
+
31
+ # /tmp Γ© sempre gravΓ‘vel no Hugging Face Spaces e localmente
32
+ # Fallback: se /tmp nΓ£o existir, usa pasta output/ local
33
+ _tmp_dir = '/tmp/sla_output'
34
+ try:
35
+ os.makedirs(_tmp_dir, exist_ok=True)
36
+ # Testar escrita
37
+ _test = os.path.join(_tmp_dir, '.write_test')
38
+ open(_test, 'w').close()
39
+ os.remove(_test)
40
+ OUTPUT_DIR = _tmp_dir
41
+ except Exception:
42
+ OUTPUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')
43
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
44
 
45
  # ── SLA fixo por TIPO (tabela da imagem) ──────────────────────────────────────
46
  SLA_MAP = {
 
467
  # ── ExportaΓ§Γ΅es ────────────────────────────────────────────────────────────────
468
 
469
  def exportar_csv_pivot(categoria: str) -> str:
470
+ try:
471
+ pivot = build_pivot(DF_GLOBAL, categoria)
472
+ ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
473
+ nome = f"sla_pivot_{categoria.lower().replace(' ', '_')}_{ts}.csv"
474
+ path = os.path.join(OUTPUT_DIR, nome)
475
+ pivot.to_csv(path, index=False, encoding='utf-8-sig', sep=';')
476
+ return path
477
+ except Exception as e:
478
+ # Fallback: gravar em /tmp directamente
479
+ import tempfile
480
+ tmp = tempfile.NamedTemporaryFile(
481
+ delete=False, suffix='.csv',
482
+ prefix=f"sla_pivot_{categoria.lower().replace(' ','_')}_"
483
+ )
484
+ build_pivot(DF_GLOBAL, categoria).to_csv(tmp.name, index=False, encoding='utf-8-sig', sep=';')
485
+ return tmp.name
486
 
487
  def exportar_csv_fact(categoria: str) -> str:
488
+ try:
489
+ sub = DF_GLOBAL.copy() if categoria == 'GLOBAL' else DF_GLOBAL[DF_GLOBAL['CATEGORIA'] == categoria].copy()
490
+ fact = sub[[
491
+ 'SUB-CIP', 'PROJETO', 'TIPO', 'TIPO_LABEL', 'RB STATUS', 'CATEGORIA',
492
+ 'DATA_ADJ_CLIENTE', 'DATA_PREVISTA', 'TEMPO_EXECUCAO',
493
+ 'ATUAL', 'DIFDIAS', 'SLA_FIXO', 'PCT_SLA', 'FAIXA_SLA', 'DATA_CALCULO'
494
+ ]].copy()
495
+ fact['DATA_ADJ_CLIENTE'] = fact['DATA_ADJ_CLIENTE'].dt.strftime('%d/%m/%Y')
496
+ fact['DATA_PREVISTA'] = fact['DATA_PREVISTA'].dt.strftime('%d/%m/%Y')
497
+ ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
498
+ nome = f"sla_fact_{categoria.lower().replace(' ', '_')}_{ts}.csv"
499
+ path = os.path.join(OUTPUT_DIR, nome)
500
+ fact.to_csv(path, index=False, encoding='utf-8-sig', sep=';')
501
+ return path
502
+ except Exception as e:
503
+ import tempfile
504
+ sub = DF_GLOBAL.copy() if categoria == 'GLOBAL' else DF_GLOBAL[DF_GLOBAL['CATEGORIA'] == categoria].copy()
505
+ fact = sub[[
506
+ 'SUB-CIP', 'PROJETO', 'TIPO', 'TIPO_LABEL', 'RB STATUS', 'CATEGORIA',
507
+ 'DATA_ADJ_CLIENTE', 'DATA_PREVISTA', 'TEMPO_EXECUCAO',
508
+ 'ATUAL', 'DIFDIAS', 'SLA_FIXO', 'PCT_SLA', 'FAIXA_SLA', 'DATA_CALCULO'
509
+ ]].copy()
510
+ fact['DATA_ADJ_CLIENTE'] = fact['DATA_ADJ_CLIENTE'].dt.strftime('%d/%m/%Y')
511
+ fact['DATA_PREVISTA'] = fact['DATA_PREVISTA'].dt.strftime('%d/%m/%Y')
512
+ tmp = tempfile.NamedTemporaryFile(
513
+ delete=False, suffix='.csv',
514
+ prefix=f"sla_fact_{categoria.lower().replace(' ','_')}_"
515
+ )
516
+ fact.to_csv(tmp.name, index=False, encoding='utf-8-sig', sep=';')
517
+ return tmp.name
518
 
519
  def exportar_excel_powerbi() -> str:
520
+ import tempfile
521
  ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
522
+ # Tentar OUTPUT_DIR; se falhar, usar tempfile
523
+ try:
524
+ path = os.path.join(OUTPUT_DIR, f'modelo_sla_powerbi_{ts}.xlsx')
525
+ open(path, 'wb').close() # testar escrita
526
+ except Exception:
527
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx', prefix='modelo_sla_powerbi_')
528
+ path = tmp.name
529
+ tmp.close()
530
 
531
  with pd.ExcelWriter(path, engine='openpyxl') as writer:
532
  fact = DF_GLOBAL[[
 
749
  btn_fact = gr.Button("⬇ CSV β€” Dados Calculados", variant="secondary", elem_classes=["btn-export"])
750
  file_fact = gr.File(label="", show_label=False)
751
 
752
+ with gr.Column(scale=1):
753
+ gr.Markdown("**Modelo Power BI** β€” Excel com 6 sheets (Fact + Dims + Pivots)")
754
+ btn_excel = gr.Button("⬇ Excel β€” Power BI", variant="primary", elem_classes=["btn-export"])
755
+ file_excel = gr.File(label="", show_label=False)
756
 
757
  # ── Legenda ──────────────────────────────────────────────────────────────
758
  gr.HTML("""
 
791
  share=False,
792
  css=CSS,
793
  theme=gr.themes.Base(),
794
+ )