File size: 9,709 Bytes
ce190ee
 
 
 
c40855a
ce190ee
7d48feb
c40855a
 
 
ae61fe0
c40855a
 
 
 
 
 
 
 
 
 
 
 
bed8309
c40855a
cd31093
c40855a
ed4f2d1
c40855a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed4f2d1
 
c40855a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed4f2d1
 
 
 
 
 
 
 
 
 
 
c40855a
 
 
 
 
 
 
 
 
ed4f2d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c40855a
 
 
 
 
 
 
 
 
ed4f2d1
 
 
 
 
 
 
c40855a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce190ee
 
ae61fe0
ce190ee
bed8309
c40855a
 
 
ce190ee
c40855a
ce190ee
c40855a
ce190ee
 
 
 
 
bed8309
ce190ee
bed8309
ce190ee
fe58151
 
e2d1ef3
fe58151
e2d1ef3
fe58151
bed8309
0776dea
 
 
 
 
 
 
 
 
 
 
ae61fe0
 
 
 
 
51920a8
9da944e
ae61fe0
 
 
18e383c
ae61fe0
 
 
18e383c
ae61fe0
 
 
18e383c
ae61fe0
 
 
18e383c
ae61fe0
 
 
 
 
9da944e
 
ae61fe0
 
 
 
 
 
 
ce190ee
 
 
 
 
 
7d48feb
 
 
ce190ee
 
 
 
 
b75254c
 
95ba8da
b75254c
ae61fe0
ce190ee
c40855a
 
 
ac09955
c40855a
 
 
 
ed4f2d1
c40855a
7e7950a
c40855a
ed4f2d1
c40855a
 
ae61fe0
c40855a
 
 
 
 
 
 
 
 
 
ae61fe0
 
 
 
 
 
c40855a
ae61fe0
 
c40855a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae61fe0
 
 
c40855a
 
 
 
 
 
 
 
 
 
 
 
ed4f2d1
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# based on https://huggingface.co/spaces/NimaBoscarino/climategan/blob/main/app.py # noqa: E501
# thank you @NimaBoscarino

import os
from textwrap import dedent
from urllib import parse
from requests import get

import googlemaps
import gradio as gr
import numpy as np
from gradio.components import (
    HTML,
    Button,
    Column,
    Dropdown,
    Image,
    Markdown,
    Radio,
    Row,
    Textbox,
)
from skimage import io
from datetime import datetime

from climategan_wrapper import ClimateGAN

TEXTS = [
    dedent(
        """
        <p>
            Climate change does not impact everyone equally.
            This Space shows the effects of the climate emergency,
            "one address at a time".
            Visit the original experience at
            <a href="https://thisclimatedoesnotexist.com/">
                ThisClimateDoesNotExist.com
            </a>
        </p>
        <br>
        <p>
            Enter an address or upload a Street View image, and ClimateGAN
            will generate images showing how the location could be impacted
            by flooding, wildfires, or smog if it happened there.
        </p>
        <br>
        <p>
            This is <strong>NOT</strong> an exercise in climate prediction,
            rather an exercise of empathy, to put yourself in others' shoes,
            as if Climate Change came crushing on your doorstep.
        </p>
        <br>
        <p>
            After you have selected an image and started the inference you
            will see all the outputs of ClimateGAN, including intermediate
            outputs such as the flood mask, the segmentation map and the
            depth maps used to produce the 3 events.
        </p>
        <br>
        <p>
            This Space makes use of recent Stable Diffusion in-painting
            pipelines to replace ClimateGAN's original Painter. If you
            select 'Both' painters, you will see a comparison
        </p>
        <br>
        <p style='text-align: center'>
            Visit
            <a href='https://thisclimatedoesnotexist.com/'>
                ThisClimateDoesNotExist.com</a>
            &nbsp;for more information
            &nbsp;&nbsp;|&nbsp;&nbsp;
            Original
            <a href='https://github.com/cc-ai/climategan'>
                ClimateGAN GitHub Repo
            </a>
            &nbsp;&nbsp;|&nbsp;&nbsp;
            Read the original
            <a
                href='https://openreview.net/forum?id=EZNOb_uNpJk'
                target='_blank'>
            ICLR 2021 ClimateGAN paper
            </a>
        </p>
        """
    ),
    dedent(
        """
        ## How to use this Space

        1. Enter an address or upload a Street View image
        2. Select the type of Painter you'd like to use for the flood renderings
        3. Click on the "See for yourself!" button
        4. Wait for the inference to complete, typically around 30 seconds
            (plus queue time)
        5. Enjoy the results!

            1. The prompt for Stable Diffusion is `An HD picture of a street with
            dirty water after a heavy flood`
            2. Pay attention to potential "inventions" by Stable Diffusion's in-painting
            3. The "restricted to masked area" SD output is the result of:
            `y = mask * flooded + (1-mask) * input`

        """
    ),
]
CSS = dedent(
    """
    a {
        color: #0088ff;
        text-decoration: underline;
    }
    strong {
        color: #c34318;
        font-weight: bolder;
    }
    #how-to-use-md li {
        margin: 0.1em;
    }
    #how-to-use-md li p {
        margin: 0.1em;
    }
    """
)


def toggle(radio):
    if "address" in radio.lower():
        return [
            gr.update(visible=True),
            gr.update(visible=False),
            gr.update(visible=True),
        ]
    else:
        return [
            gr.update(visible=False),
            gr.update(visible=True),
            gr.update(visible=True),
        ]


def predict(cg: ClimateGAN, api_key):
    def _predict(*args):
        print(f"Starting inference ({str(datetime.now())})")
        image = place = painter = radio = None
        if api_key:
            radio, image, place, painter = args
        else:
            image, painter = args

        if api_key and place and "address" in radio.lower():
            geocode_result = gmaps.geocode(place)

            address = geocode_result[0]["formatted_address"]
            static_map_url = f"https://maps.googleapis.com/maps/api/streetview?size=640x640&location={parse.quote(address)}&source=outdoor&key={api_key}"
            img_np = io.imread(static_map_url)
            print("Using GSV image")
        else:
            print("Using user image")
            img_np = image

        painters = {
            "ClimateGAN Painter": "climategan",
            "Stable Diffusion Painter": "stable_diffusion",
            "Both": "both",
        }
        print("Using painter", painters[painter])
        output_dict = cg.infer_single(
            img_np,
            painters[painter],
            concats=[
                "input",
                "masked_input",
                "climategan_flood",
                "stable_copy_flood",
            ],
            as_pil_image=True,
        )

        input_image = output_dict["input"]
        masked_input = output_dict["masked_input"]
        wildfire = output_dict["wildfire"]
        smog = output_dict["smog"]
        depth = np.repeat(output_dict["depth"], 3, axis=-1)
        segmentation = output_dict["segmentation"]

        climategan_flood = output_dict.get(
            "climategan_flood",
            np.ones(input_image.shape, dtype=np.uint8) * 255,
        )
        stable_flood = output_dict.get(
            "stable_flood",
            np.ones(input_image.shape, dtype=np.uint8) * 255,
        )
        stable_copy_flood = output_dict.get(
            "stable_copy_flood",
            np.ones(input_image.shape, dtype=np.uint8) * 255,
        )
        concat = output_dict.get(
            "concat",
            np.ones(input_image.shape, dtype=np.uint8) * 255,
        )

        return (
            input_image,
            masked_input,
            segmentation,
            depth,
            climategan_flood,
            stable_flood,
            stable_copy_flood,
            concat,
            wildfire,
            smog,
        )

    return _predict


if __name__ == "__main__":

    ip = get("https://api.ipify.org").content.decode("utf8")
    print("My public IP address is: {}".format(ip))

    api_key = os.environ.get("GMAPS_API_KEY")
    gmaps = None
    if api_key is not None:
        gmaps = googlemaps.Client(key=api_key)

    cg = ClimateGAN(
        model_path="config/model/masker",
        dev_mode=os.environ.get("CG_DEV_MODE", "").lower() == "true",
    )
    cg._setup_stable_diffusion()

    radio = address = None
    pred_ins = []
    pred_outs = []

    with gr.Blocks(css=CSS) as app:
        with Row():
            with Column():
                Markdown("# ClimateGAN: Visualize Climate Change")
                HTML(TEXTS[0])
            with Column():
                Markdown(TEXTS[1], elem_id="how-to-use-md")
        with Row():
            HTML("<hr><br><h2 style='font-size: 1.5rem;'>Choose Inputs</h2>")
        with Row():
            with Column():
                if api_key:
                    radio = Radio(["From Address", "From Image"], label="Input Type")
                    pred_ins += [radio]
                im_inp = Image(label="Input Image", visible=not api_key)
                pred_ins += [im_inp]
                if api_key:
                    address = Textbox(label="Address or place name", visible=False)
                    pred_ins += [address]
            with Column():
                pred_ins += [
                    Dropdown(
                        choices=[
                            "ClimateGAN Painter",
                            "Stable Diffusion Painter",
                            "Both",
                        ],
                        label="Choose Flood Painter",
                        value="Both",
                    )
                ]
                btn = Button(
                    "See for yourself!",
                    label="Run",
                    variant="primary",
                    visible=not api_key,
                )
        with Row():
            Markdown("## Outputs")
        with Row():
            pred_outs += [Image(type="numpy", label="Original image")]
            pred_outs += [Image(type="numpy", label="Masked input image")]
            pred_outs += [Image(type="numpy", label="Segmentation map")]
            pred_outs += [Image(type="numpy", label="Depth map")]
        with Row():
            pred_outs += [Image(type="numpy", label="ClimateGAN-Flooded image")]
            pred_outs += [Image(type="numpy", label="Stable Diffusion-Flooded image")]
            pred_outs += [
                Image(
                    type="numpy",
                    label="Stable Diffusion-Flooded image (restricted to masked area)",
                )
            ]
        with Row():
            pred_outs += [Image(type="numpy", label="Comparison of flood images")]
        with Row():
            pred_outs += [Image(type="numpy", label="Wildfire")]
            pred_outs += [Image(type="numpy", label="Smog")]
            Image(type="numpy", label="Empty on purpose", interactive=False)
        btn.click(predict(cg, api_key), inputs=pred_ins, outputs=pred_outs)

        if api_key:
            radio.change(toggle, inputs=[radio], outputs=[address, im_inp, btn])

    app.launch(show_api=False)