File size: 13,914 Bytes
acc7584
 
7f3891d
acc7584
 
24dcdf9
acc7584
 
 
966f06e
 
 
 
 
7f3891d
966f06e
acc7584
7f3891d
 
 
966f06e
 
 
 
 
 
 
 
 
7f3891d
 
966f06e
7f3891d
e4ffd46
 
966f06e
24dcdf9
 
 
7f3891d
24dcdf9
 
 
 
966f06e
 
 
 
 
 
 
 
7f3891d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
966f06e
7f3891d
966f06e
7f3891d
 
8d91400
7f3891d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
966f06e
 
 
 
 
 
 
 
 
8d91400
7f3891d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d91400
7f3891d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
966f06e
7f3891d
 
 
966f06e
 
 
7f3891d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d91400
7f3891d
966f06e
7f3891d
 
 
 
 
 
 
 
 
 
 
 
 
8d91400
 
 
 
7f3891d
8d91400
 
7f3891d
8d91400
7f3891d
 
 
8d91400
7f3891d
 
 
8d91400
7f3891d
8d91400
 
 
7f3891d
966f06e
 
7f3891d
8d91400
 
 
7f3891d
8d91400
 
7f3891d
8d91400
7f3891d
 
 
8d91400
7f3891d
 
 
8d91400
7f3891d
8d91400
 
7f3891d
 
966f06e
7f3891d
8d91400
 
 
966f06e
 
 
7f3891d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d91400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f3891d
 
 
 
966f06e
 
7f3891d
 
 
 
 
 
 
 
 
966f06e
 
 
 
7f3891d
966f06e
 
 
 
 
 
 
7f3891d
 
 
 
 
966f06e
 
 
7f3891d
966f06e
7f3891d
966f06e
 
 
acc7584
e4ffd46
 
966f06e
 
 
7f3891d
 
 
 
 
 
 
 
 
 
 
acc7584
 
 
966f06e
 
 
acc7584
966f06e
acc7584
 
966f06e
 
 
 
7f3891d
966f06e
 
 
 
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
from pathlib import Path

import faicons as fa
import polars as pl
from shiny import reactive, render
from shiny.express import app_opts, ui
from shiny.express import input as app_input
from shinywidgets import render_widget

from src.calcs import (
    get_comp_radar,
    get_comp_summary,
    get_comparison_employment,
    get_occ_ai_exposure,
    get_occ_employment,
    get_occ_summary,
)
from src.constants import FIRST_COLS, METRICS
from src.data import INTRO_MD, OCC_CHOICES, OCCS, YEAR_MAX, YEAR_MIN, YEARS, lf
from src.utils import (
    as_great_table_html,
    download_extension,
    download_media_type,
    export_filtered_data,
)
from src.visuals import (
    build_ai_exposure_bar,
    build_comp_radar_plot,
    build_comparison_employment_plot,
    build_employment_chart,
    build_employment_count_chart,
    build_value_boxes,
    export_fig,
)

LOGOS_PATH = Path(__file__).parent / "logos"
app_opts(static_assets={"/logos": LOGOS_PATH})

ui.page_opts(
    # title="AI Exposure & Monthly Employment Explorer",
    fillable=True,
    theme=ui.Theme.from_brand(__file__),
)

_DEFAULT_OCC = OCCS[0] if OCCS else None


# ── Tab navigation ────────────────────────────────────────────

with ui.navset_pill(id="main_tabs"):
    # ── Tab 1: Occupation View ────────────────────────────────

    with ui.nav_panel("Occupation View"), ui.layout_sidebar():
        with ui.sidebar(title="Occupation View", width=280):
            ui.div(
                ui.img(
                    src="/logos/lab.svg",
                    alt="AI-Econ Lab logo",
                    style="width:100%; max-width:180px;",
                ),
                style="text-align:center; margin-bottom:1rem;",
            )
            ui.markdown(INTRO_MD)
            ui.hr()
            ui.input_selectize(
                "occ_occupation",
                "Occupation",
                choices=OCC_CHOICES,
                selected=_DEFAULT_OCC,
            )
            ui.input_select(
                "occ_year",
                "Year (snapshot)",
                choices={str(y): str(y) for y in YEARS},
                selected=str(YEAR_MAX),
            )
            ui.hr()
            ui.p("Employment trend filters:", class_="fw-semibold mb-1 small")
            ui.input_slider(
                "occ_year_range",
                "Year Range",
                min=YEAR_MIN,
                max=YEAR_MAX,
                value=[YEAR_MIN, YEAR_MAX],
                sep="",
            )

        # Value boxes
        @render.ui
        def occ_value_boxes():
            summary = occ_summary()
            if summary is None:
                return ui.p(
                    "No data for the selected occupation and year.",
                    class_="text-muted p-3",
                )
            return build_value_boxes(summary, app_input.occ_occupation())

        # Stacked cards (full width)
        with ui.layout_columns(col_widths=12):
            with ui.card(full_screen=True, height="700px"):
                with ui.card_header(class_="d-flex align-items-center"):
                    ui.span("AI Exposure by Sub-Domain")
                    with ui.span(class_="ms-auto"):

                        @render.download(
                            filename="ai_exposure.png",
                            media_type="image/png",
                            label=fa.icon_svg("download"),
                        )
                        async def dl_ai_bar():
                            yield export_fig(
                                build_ai_exposure_bar(
                                    occ_ai_exposure().to_pandas(),
                                    app_input.occ_occupation(),
                                    int(app_input.occ_year()),
                                ),
                            )

                @render_widget
                def occ_ai_bar():
                    df = occ_ai_exposure().to_pandas()
                    return build_ai_exposure_bar(
                        df,
                        app_input.occ_occupation(),
                        int(app_input.occ_year()),
                    )

            with ui.card(full_screen=True, height="700px"):
                with ui.card_header(class_="d-flex align-items-center"):
                    ui.span("Monthly Employment Count")
                    with ui.span(class_="ms-auto"):

                        @render.download(
                            filename="monthly_employment_count.png",
                            media_type="image/png",
                            label=fa.icon_svg("download"),
                        )
                        async def dl_occ_employment_count():
                            yield export_fig(
                                build_employment_count_chart(
                                    occ_employment().to_pandas(),
                                    app_input.occ_occupation(),
                                ),
                            )

                @render_widget
                def occ_employment_count_chart():
                    df = occ_employment().to_pandas()
                    return build_employment_count_chart(df, app_input.occ_occupation())

            with ui.card(full_screen=True, height="700px"):
                with ui.card_header(class_="d-flex align-items-center"):
                    ui.span("Monthly Employment Change")
                    with ui.span(class_="ms-auto"):

                        @render.download(
                            filename="monthly_employment.png",
                            media_type="image/png",
                            label=fa.icon_svg("download"),
                        )
                        async def dl_occ_employment():
                            yield export_fig(
                                build_employment_chart(
                                    occ_employment().to_pandas(),
                                    app_input.occ_occupation(),
                                ),
                            )

                @render_widget
                def occ_employment_chart():
                    df = occ_employment().to_pandas()
                    return build_employment_chart(df, app_input.occ_occupation())

    # ── Tab 2: Comparison View ────────────────────────────────

    with ui.nav_panel("Comparison View"), ui.layout_sidebar():
        with ui.sidebar(title="Comparison View", width=280):
            ui.input_selectize(
                "comp_occupations",
                "Occupations (up to 5)",
                choices=OCC_CHOICES,
                multiple=True,
                options={"maxItems": 5, "placeholder": "Select occupations..."},
            )
            ui.input_select(
                "comp_year",
                "Year (AI snapshot)",
                choices={str(y): str(y) for y in YEARS},
                selected=str(YEAR_MAX),
            )

        # Employment summary table
        with ui.card(fill=True, fillable=True):
            ui.card_header("Occupations Summary")

            @render.ui
            def comp_summary_table():
                occs = list(app_input.comp_occupations() or [])
                if not occs:
                    return ui.p(
                        "Select at least one occupation.",
                        class_="text-muted p-3",
                    )
                df = get_comp_summary(
                    lf,
                    occs,
                    int(app_input.comp_year()),
                ).to_pandas()
                return ui.div(
                    as_great_table_html(df, METRICS),
                    style="overflow: auto; width: 100%; height: 100%;",
                )

        # AI percentile radar chart
        with ui.card(full_screen=True, height="700px"):
            with ui.card_header(class_="d-flex align-items-center"):
                ui.span("AI Percentile Radar Comparison")
                with ui.span(class_="ms-auto"):

                    @render.download(
                        filename="ai_radar.png",
                        media_type="image/png",
                        label=fa.icon_svg("download"),
                    )
                    async def dl_comp_radar():
                        yield export_fig(
                            build_comp_radar_plot(
                                comp_radar_data().to_pandas(),
                                METRICS,
                            ),
                        )

            @render_widget
            def comp_radar_chart():
                df = comp_radar_data().to_pandas()
                return build_comp_radar_plot(df, METRICS)

        # Employment comparison line chart
        with ui.card(full_screen=True, height="700px"):
            with ui.card_header(class_="d-flex align-items-center"):
                ui.span("Monthly Employment Change")
                with ui.span(class_="ms-auto"):

                    @render.download(
                        filename="comparison_employment.png",
                        media_type="image/png",
                        label=fa.icon_svg("download"),
                    )
                    async def dl_comp_employment():
                        yield export_fig(
                            build_comparison_employment_plot(
                                comparison_data().to_pandas(),
                            ),
                        )

            @render_widget
            def comp_employment_chart():
                df = comparison_data().to_pandas()
                return build_comparison_employment_plot(df)

    # ── Tab 3: Download ───────────────────────────────────────

    with ui.nav_panel("Download"), ui.layout_sidebar():
        with ui.sidebar(title="Download Filters", width=280):
            ui.input_slider(
                "dl_year_range",
                "Year Range",
                min=YEAR_MIN,
                max=YEAR_MAX,
                value=[YEAR_MIN, YEAR_MAX],
                sep="",
            )
            ui.input_selectize(
                "dl_occupations",
                "Occupation (blank = all)",
                choices=OCC_CHOICES,
                multiple=True,
            )
            ui.input_select(
                "dl_format",
                "Format",
                choices={"csv": "CSV", "parquet": "Parquet", "excel": "Excel"},
                selected="csv",
            )

            @render.download(
                filename=lambda: (
                    f"daioe_months.{download_extension(app_input.dl_format())}"
                ),
                media_type=lambda: download_media_type(app_input.dl_format()),
            )
            async def download_data():
                df = download_frame().to_pandas()
                yield export_filtered_data(df, app_input.dl_format())

        ui.p(
            "Export the filtered row-level dataset or inspect a compact preview before downloading.",
            class_="text-muted mb-3",
        )

        with ui.layout_columns(col_widths=[6, 6]):
            with ui.value_box(theme="primary"):
                "Rows"

                @render.text
                def dl_row_count():
                    return f"{len(download_frame()):,}"

            with ui.value_box(theme="primary"):
                "Columns"

                @render.text
                def dl_col_count():
                    return f"{len(download_frame().columns):,}"

        # Data preview
        with ui.card(full_screen=True):
            ui.card_header("Data Preview (first 50 rows)")

            @render.ui
            def dl_preview():
                df = download_frame().head(50)
                all_cols = df.columns
                ordered = [c for c in FIRST_COLS if c in all_cols]
                rest = [c for c in all_cols if c not in ordered]
                return as_great_table_html(
                    df.select(ordered + rest).to_pandas(),
                    METRICS,
                )


# ── Reactive calculations ─────────────────────────────────────


@reactive.calc
def occ_summary():
    return get_occ_summary(lf, app_input.occ_occupation(), int(app_input.occ_year()))


@reactive.calc
def occ_ai_exposure():
    return get_occ_ai_exposure(
        lf,
        app_input.occ_occupation(),
        int(app_input.occ_year()),
    )


@reactive.calc
def occ_employment():
    yr = app_input.occ_year_range()
    return get_occ_employment(
        lf,
        app_input.occ_occupation(),
        (yr[0], yr[1]),
    )


@reactive.calc
def comparison_data():
    occs = list(app_input.comp_occupations() or [])
    if not occs:
        return pl.DataFrame(
            schema={
                "year": pl.Int64,
                "month": pl.String,
                "occupation": pl.String,
                "emp_count": pl.Float64,
                "pct_chg_1m": pl.Float64,
            },
        )
    return get_comparison_employment(lf, occs)


@reactive.calc
def comp_radar_data():
    occs = list(app_input.comp_occupations() or [])
    if not occs:
        return pl.DataFrame()
    return get_comp_radar(lf, occs, int(app_input.comp_year()))


@reactive.calc
def download_frame():
    yr = app_input.dl_year_range()
    q = lf.filter(
        (pl.col("year") >= yr[0]) & (pl.col("year") <= yr[1]),
    )
    if app_input.dl_occupations():
        q = q.filter(pl.col("occupation").is_in(list(app_input.dl_occupations())))
    return q.collect()