Persano commited on
Commit
2d23850
·
verified ·
1 Parent(s): d42c419

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -52
app.py CHANGED
@@ -2,9 +2,12 @@ import gradio as gr
2
  from fpdf import FPDF
3
  import tempfile
4
  import os
 
 
5
  import matplotlib.pyplot as plt
6
  import numpy as np
7
  from datetime import datetime
 
8
 
9
  # Função para formatar moeda manualmente em formato brasileiro
10
  def formatar_moeda(valor):
@@ -48,14 +51,15 @@ def calcular_roi(valor_imovel, investimento_proprio, aluguel, anos, selic, desco
48
  ganho_total = saldo + (valor_futuro_imovel - valor_imovel)
49
 
50
  anos_array = list(range(1, anos + 1))
51
- plt.figure(figsize=(6, 4))
52
  plt.plot(anos_array, roi_acumulado, marker='o', label="ROI Acumulado (%)")
53
  plt.title('Crescimento do ROI ao longo dos anos')
54
  plt.xlabel('Ano')
55
  plt.ylabel('ROI (%)')
56
  plt.grid(True)
 
57
  plt.legend()
58
- graph_path = os.path.join(tempfile.gettempdir(), 'roi_plot.png')
59
  plt.savefig(graph_path)
60
  plt.close()
61
 
@@ -84,36 +88,36 @@ Tabela de Valorização do Imóvel:
84
  """
85
 
86
  explicacao = """
87
- ---
88
  📘 Explicações e Fórmulas Utilizadas:
89
 
90
- 1️⃣ **Financiamento Price (Sistema Francês de Amortização)**:
91
- \[ PMT = P \cdot \frac{i \cdot (1 + i)^n}{(1 + i)^n - 1} \]
92
  - Onde:
93
- - \( P \): valor financiado
94
- - \( i \): taxa de juros mensal
95
- - \( n \): número total de parcelas
96
-
97
- 2️⃣ **Financiamento SAC (Sistema de Amortização Constante)**:
98
- \[ A = \frac{P}{n} \]
99
- - Parcela mensal: \( A + j \), onde \( j \) são os juros sobre saldo devedor
100
-
101
- 3️⃣ **ROI Mensal (%):**
102
- \[ ROI_{mensal} = \left( \frac{R_m - PMT}{I} \right) \times 100 \]
103
- - \( R_m \): Receita mensal líquida
104
- - \( PMT \): Parcela do financiamento
105
- - \( I \): Investimento próprio
106
-
107
- 4️⃣ **ROI Anual (%):**
108
- \[ ROI_{anual} = \left( \frac{R_a - \sum PMT}{I} \right) \times 100 \]
109
- - \( R_a \): Receita anual líquida
110
-
111
- 5️⃣ **Valorização do Imóvel:**
112
- \[ VF = VI \cdot (1 + v)^t \]
113
- - \( VF \): Valor futuro
114
- - \( VI \): Valor inicial
115
- - \( v \): taxa de valorização anual
116
- - \( t \): anos
117
  ---
118
  """
119
 
@@ -134,11 +138,15 @@ def gerar_pdf(valor_imovel, investimento_proprio, aluguel, anos, selic, desconto
134
  for linha in resultados.split("\n"):
135
  if linha.strip():
136
  pdf.multi_cell(0, 8, linha)
137
- if os.path.exists(graph_path):
138
- pdf.ln(5)
139
- pdf.image(graph_path, x=10, w=180)
140
 
141
- temp_pdf_path = os.path.join(tempfile.gettempdir(), "roi_relatorio.pdf")
 
 
 
 
 
 
 
142
  pdf.output(temp_pdf_path)
143
  return temp_pdf_path
144
 
@@ -155,32 +163,23 @@ with gr.Blocks() as demo:
155
  anos = gr.Slider(1, 30, step=1, value=10, label="Anos de Financiamento")
156
 
157
  with gr.Row():
158
- selic = gr.Slider(0.0, 20.0, step=0.1, value=10.75, label="Taxa SELIC (%)")
159
- desconto_aluguel = gr.Slider(0, 50, step=1, value=20, label="Desconto sobre o Aluguel (%)")
160
-
161
- valorizacao = gr.Slider(0, 15, step=0.1, value=5.0, label="Valorização Anual do Imóvel (%)")
162
- tipo_financiamento = gr.Radio(["Price", "SAC"], label="Tipo de Financiamento", value="Price")
163
-
164
- gerar_button = gr.Button("📊 Calcular ROI")
165
- pdf_button = gr.Button("📄 Gerar Relatório em PDF")
166
 
167
- resultados_output = gr.Textbox(label="Resultado da Simulação", lines=20)
168
- graph_output = gr.Image(label="Gráfico Comparativo de ROI")
169
- pdf_output = gr.File(label="Download do Relatório PDF")
170
 
171
- gerar_button.click(
172
- fn=lambda *args: calcular_roi(*args)[:2],
173
- inputs=[valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento],
174
- outputs=[resultados_output, graph_output]
175
- )
176
 
177
- pdf_button.click(
178
  fn=gerar_pdf,
179
  inputs=[valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento],
180
- outputs=pdf_output
181
  )
182
 
183
- demo.launch(server_port=7860)
 
184
 
185
 
186
 
 
2
  from fpdf import FPDF
3
  import tempfile
4
  import os
5
+ import matplotlib
6
+ matplotlib.use('Agg')
7
  import matplotlib.pyplot as plt
8
  import numpy as np
9
  from datetime import datetime
10
+ import uuid
11
 
12
  # Função para formatar moeda manualmente em formato brasileiro
13
  def formatar_moeda(valor):
 
51
  ganho_total = saldo + (valor_futuro_imovel - valor_imovel)
52
 
53
  anos_array = list(range(1, anos + 1))
54
+ plt.figure(figsize=(8, 5))
55
  plt.plot(anos_array, roi_acumulado, marker='o', label="ROI Acumulado (%)")
56
  plt.title('Crescimento do ROI ao longo dos anos')
57
  plt.xlabel('Ano')
58
  plt.ylabel('ROI (%)')
59
  plt.grid(True)
60
+ plt.tight_layout()
61
  plt.legend()
62
+ graph_path = os.path.join(tempfile.gettempdir(), f'roi_plot_{uuid.uuid4().hex}.png')
63
  plt.savefig(graph_path)
64
  plt.close()
65
 
 
88
  """
89
 
90
  explicacao = """
91
+ \n---
92
  📘 Explicações e Fórmulas Utilizadas:
93
 
94
+ 1 **Financiamento Price (Sistema Francês de Amortização)**:
95
+ PMT = P × [i × (1 + i)^n] / [(1 + i)^n - 1]
96
  - Onde:
97
+ - P: valor financiado
98
+ - i: taxa de juros mensal
99
+ - n: número total de parcelas
100
+
101
+ 2 **Financiamento SAC (Sistema de Amortização Constante)**:
102
+ A = P / n
103
+ - Parcela mensal: A + juros sobre saldo devedor
104
+
105
+ 3 **ROI Mensal (%)**:
106
+ ROI_mensal = [(R_m - PMT) / I] × 100
107
+ - R_m: Receita mensal líquida
108
+ - PMT: Parcela do financiamento
109
+ - I: Investimento próprio
110
+
111
+ 4 **ROI Anual (%)**:
112
+ ROI_anual = [(R_a - ΣPMT) / I] × 100
113
+ - R_a: Receita anual líquida
114
+
115
+ 5 **Valorização do Imóvel:**
116
+ VF = VI × (1 + v)^t
117
+ - VF: Valor futuro
118
+ - VI: Valor inicial
119
+ - v: taxa de valorização anual
120
+ - t: anos
121
  ---
122
  """
123
 
 
138
  for linha in resultados.split("\n"):
139
  if linha.strip():
140
  pdf.multi_cell(0, 8, linha)
 
 
 
141
 
142
+ if os.path.exists(graph_path) and os.path.getsize(graph_path) > 0:
143
+ pdf.add_page()
144
+ try:
145
+ pdf.image(graph_path, x=10, w=180)
146
+ except RuntimeError as e:
147
+ pdf.multi_cell(0, 10, f"[Erro ao adicionar imagem: {e}]")
148
+
149
+ temp_pdf_path = os.path.join(tempfile.gettempdir(), f"roi_relatorio_{uuid.uuid4().hex}.pdf")
150
  pdf.output(temp_pdf_path)
151
  return temp_pdf_path
152
 
 
163
  anos = gr.Slider(1, 30, step=1, value=10, label="Anos de Financiamento")
164
 
165
  with gr.Row():
166
+ selic = gr.Slider(0.0, 20.0, value=5.0, step=0.1, label="Taxa SELIC (%)")
167
+ desconto_aluguel = gr.Slider(0.0, 100.0, value=0.0, step=1, label="Desconto sobre aluguel (%)")
 
 
 
 
 
 
168
 
169
+ with gr.Row():
170
+ valorizacao = gr.Slider(0.0, 15.0, value=5.0, step=0.1, label="Valorização Anual (%)")
171
+ tipo_financiamento = gr.Dropdown(["Price", "SAC"], value="Price", label="Tipo de Financiamento")
172
 
173
+ botao_gerar_pdf = gr.Button("Gerar Relatório em PDF")
 
 
 
 
174
 
175
+ botao_gerar_pdf.click(
176
  fn=gerar_pdf,
177
  inputs=[valor_imovel, investimento_proprio, aluguel, anos, selic, desconto_aluguel, valorizacao, tipo_financiamento],
178
+ outputs=gr.File(label="Relatório PDF")
179
  )
180
 
181
+ demo.launch()
182
+
183
 
184
 
185