File size: 5,781 Bytes
2422cca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc748c9
 
 
98caf17
badbe89
 
a72f261
88889bf
badbe89
 
 
 
fc748c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
badbe89
98caf17
 
779f1f6
 
 
 
 
8fb31e9
a72f261
bb98708
badbe89
a72f261
 
badbe89
2422cca
 
 
fc748c9
 
 
 
 
2422cca
fc748c9
 
 
 
 
2422cca
 
fc748c9
 
 
2422cca
 
 
 
 
 
 
 
 
 
 
 
 
bb98708
 
 
 
 
2422cca
 
bb98708
2422cca
 
 
 
fc748c9
 
 
ac33c23
1f04e63
bb98708
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
import gspread
from google.oauth2 import service_account
import gradio as gr
import pandas as pd
from fpdf import FPDF
from datetime import datetime
import os
from pathlib import Path

# Caminho para o arquivo JSON de credenciais
SERVICE_ACCOUNT_FILE = "credenciais.json"

# Escopos da API do Google Sheets
SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]

# Carregar credenciais
gcredentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES
)

# Autenticar com gspread
gc = gspread.authorize(gcredentials)

# ID da planilha
SPREADSHEET_ID = "1AnSQ1qHdf6vy0rC0_mgKo2gCzH1EhVumgcagPS2TRAI"

# Função para buscar imóveis
def consultar_imoveis(bairro, valor_maximo, metragem_minima, estagio):
    try:
        sheet = gc.open_by_key(SPREADSHEET_ID).sheet1
        dados = sheet.get_all_records()

        bairro_informado = bairro.strip().lower()
        valor_maximo = float(valor_maximo)
        metragem_minima = float(metragem_minima)
        estagio = estagio.strip().lower()

        resultado = []
        for imovel in dados:
            imovel_bairro = imovel.get("bairro", "").strip().lower()
            imovel_valor = float(imovel.get("valor", 0))
            imovel_metragem = float(imovel.get("metragem", 0))
            imovel_estagio = imovel.get("estagio", "").strip().lower()

            if bairro_informado in imovel_bairro and \
               imovel_valor <= valor_maximo and \
               imovel_metragem >= metragem_minima and \
               (estagio == "todos" or imovel_estagio == estagio):
                resultado.append(imovel)

        if not resultado:
            return pd.DataFrame([{"Mensagem": "Nenhum imóvel encontrado para os critérios informados."}])

        df = pd.DataFrame(resultado)
        colunas_longas = ["Região", "lazer", "diferenciais"]
        for col in colunas_longas:
            if col in df.columns:
                df[col] = df[col].apply(lambda x: str(x).replace(". ", ".\n").replace(", ", ",\n"))

        return df
    except Exception as e:
        return pd.DataFrame([{"Erro": str(e)}])

# Função para gerar PDF com nome personalizado e melhor formatação
from collections import defaultdict

def gerar_pdf_com_nome(dados, bairro_usuario):
    try:
        if not isinstance(dados, pd.DataFrame) or dados.empty:
            return None

        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=10)

        agrupados = defaultdict(list)
        for _, row in dados.iterrows():
            id_imovel = row.get("ID", row.get("id", _))
            agrupados[id_imovel].append(row)

        for id_, imoveis in agrupados.items():
            primeiro = imoveis[0]

            pdf.multi_cell(0, 8, f"ID: {id_}")
            pdf.multi_cell(0, 8, f"Bairro: {primeiro.get('bairro', '')}")
            pdf.multi_cell(0, 8, f"Valor: {primeiro.get('valor', '')}")

            for imovel in imoveis:
                pdf.multi_cell(0, 8, f"Metragem: {imovel.get('metragem', '')} m²")
            pdf.ln(2)

            if "Região" in primeiro:
                pdf.multi_cell(0, 8, f"Região: {primeiro['Região']}")
            if "lazer" in primeiro:
                pdf.multi_cell(0, 8, f"Lazer: {primeiro['lazer']}")
            if "diferenciais" in primeiro:
                pdf.multi_cell(0, 8, f"Diferenciais: {primeiro['diferenciais']}")
            if "estagio" in primeiro:
                pdf.multi_cell(0, 8, f"Estágio: {primeiro['estagio']}")

            pdf.ln(5)

        bairro_slug = bairro_usuario.strip().lower().replace(" ", "_")
        data_str = datetime.now().strftime("%Y-%m-%d")

        output_dir = Path("/mnt/data")
        output_dir.mkdir(parents=True, exist_ok=True)

        output_path = output_dir / f"imoveis_{bairro_slug}_{data_str}.pdf"
        pdf.output(str(output_path))

        return str(output_path) if output_path.exists() else None
    except Exception as e:
        print("Erro ao gerar PDF:", e)
        return None

# Interface Gradio
estagios_opcoes = ["Todos", "na planta", "em construção", "pronto para morar"]

with gr.Blocks(css="""
    .gr-box { background-color: #f9f9f9; padding: 20px; border-radius: 12px; box-shadow: 0px 2px 5px rgba(0,0,0,0.1); }
    label { font-weight: bold; }
    .gr-button { margin-top: 10px; }
""") as demo:
    with gr.Row():
        with gr.Column():
            bairro = gr.Textbox(label="Bairro")
            valor = gr.Number(label="Valor Máximo")
            metragem = gr.Number(label="Metragem Mínima")
            estagio_dropdown = gr.Dropdown(choices=estagios_opcoes, value="Todos", label="Estágio da Obra")

    with gr.Row():
        buscar_btn = gr.Button("Buscar", elem_classes="gr-button")
        limpar_btn = gr.Button("Limpar", elem_classes="gr-button")
        exportar_btn = gr.Button("Gerar PDF", elem_classes="gr-button")

    resultado = gr.Dataframe(headers=None, interactive=False)
    pdf_output = gr.File(label="Download PDF")

    def limpar_campos():
        return "", 0, 0, "Todos", pd.DataFrame()

    buscar_btn.click(fn=consultar_imoveis, 
                    inputs=[bairro, valor, metragem, estagio_dropdown], 
                    outputs=resultado)

    limpar_btn.click(fn=limpar_campos, inputs=[], outputs=[bairro, valor, metragem, estagio_dropdown, resultado])

    def gerar_e_verificar_pdf(dados, bairro):
        caminho = gerar_pdf_com_nome(dados, bairro)
        if caminho:
            return gr.File.update(value=caminho, visible=True)
        return gr.File.update(value=None, visible=False)

    exportar_btn.click(
        fn=gerar_e_verificar_pdf,
        inputs=[resultado, bairro],
        outputs=pdf_output
    )


if __name__ == "__main__":
    demo.launch(server_port=7860)