File size: 14,432 Bytes
9f075f7
 
9ced414
a81b53c
9f075f7
 
 
9ced414
9f075f7
62ec48c
 
 
 
 
9f075f7
 
 
 
9ced414
cff6863
9f075f7
 
 
1412774
 
cff6863
 
 
 
 
 
 
 
 
 
 
e5af7f7
cff6863
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1412774
9f075f7
cdd27bb
 
e5af7f7
 
cdd27bb
4523429
 
cdd27bb
 
 
 
 
87c1f4c
4523429
87c1f4c
4523429
 
 
87c1f4c
 
 
4523429
87c1f4c
4523429
cdd27bb
 
 
 
 
 
 
 
87c1f4c
 
 
 
 
 
 
 
 
cdd27bb
 
 
 
 
87c1f4c
e5af7f7
 
1390bb8
cdd27bb
c9ea83a
 
 
 
 
1390bb8
cdd27bb
1390bb8
 
 
 
 
cdd27bb
1390bb8
 
cdd27bb
 
 
 
 
 
 
e5af7f7
 
cdd27bb
a80e545
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d97a914
87c1f4c
 
 
 
 
 
 
 
d97a914
 
 
a80e545
 
e5af7f7
 
 
 
 
 
 
 
 
 
 
c1893f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5af7f7
6c58c49
c1893f5
e5af7f7
c1893f5
 
 
e5af7f7
c1893f5
6c58c49
e5af7f7
 
c1893f5
 
e5af7f7
 
c1893f5
6c58c49
e5af7f7
 
c1893f5
 
e5af7f7
 
c1893f5
6c58c49
e5af7f7
 
c1893f5
 
e5af7f7
 
 
6c58c49
e5af7f7
 
 
 
 
 
 
 
 
 
 
4523429
e5af7f7
 
 
 
 
 
 
 
 
4523429
 
 
 
 
 
 
 
 
e5af7f7
 
 
 
 
 
4523429
e5af7f7
 
 
 
 
4523429
e5af7f7
 
4523429
 
e5af7f7
 
 
 
 
4523429
e5af7f7
4523429
e5af7f7
 
4523429
 
e5af7f7
 
 
 
 
4523429
 
 
e5af7f7
4523429
e5af7f7
 
4523429
 
e5af7f7
4523429
 
 
e5af7f7
 
4523429
 
 
 
 
 
 
e5af7f7
4523429
e5af7f7
 
4523429
 
e5af7f7
4523429
 
e5af7f7
 
4523429
 
 
 
e5af7f7
 
 
 
 
 
 
 
 
 
 
4523429
 
 
d97a914
 
 
 
 
 
87c1f4c
 
 
 
 
 
 
 
d97a914
4523429
e5af7f7
 
 
 
 
4523429
e5af7f7
87c1f4c
4523429
e5af7f7
 
 
 
 
4523429
e5af7f7
4523429
e5af7f7
87c1f4c
4523429
e5af7f7
 
 
 
 
4523429
e5af7f7
4523429
e5af7f7
87c1f4c
4523429
e5af7f7
4523429
 
e5af7f7
 
4523429
 
 
e5af7f7
4523429
e5af7f7
87c1f4c
d97a914
87c1f4c
 
4523429
 
 
 
87c1f4c
 
cdd27bb
 
 
6c58c49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f075f7
 
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
import marimo

__generated_with = "0.14.16"
app = marimo.App(width="medium")


@app.cell
def _():
    import marimo as mo

    # /// script
    # [tool.marimo.display]
    # theme = "dark"
    # ///
    return (mo,)


@app.cell
def _(mo):
    mo.center(mo.md("# πŸ“¦ Brazilian E-Commerce Dashboard"))
    return


@app.cell
def _(mo):
    mo.Html("<br><hr><br>")
    return


@app.cell
def _(mo):
    description = mo.md(r"""### πŸ›οΈ About the Dataset   

    This dashboard presents insights from the real-world [Brazilian E-Commerce Public Dataset by Olist](https://www.kaggle.com/datasets/olistbr/brazilian-ecommerce), which includes data on over **100,000 orders** placed between **2016 and 2018** across various online marketplaces in Brazil. It also integrates data from the [Public Holiday API](https://date.nager.at/Api) to analyze sales performance during national holidays.

    The dataset offers a detailed view of the e-commerce experience, including:

    * Order status, prices, and payment types
    * Freight and delivery performance
    * Customer locations and product categories
    * Customer reviews and satisfaction
    """)

    erd_diagram = mo.md("""### Entity Relationship Diagram
    <img src="public/erd-schema.png" />
    """)

    stack = mo.md(r"""### πŸ§‘β€πŸ’» Stack
    - [Marimo](https://github.com/marimo-team/marimo): A Python library for building interactive dashboards.
    - [Hugging Face Spaces](https://huggingface.co/docs/hub/spaces-config-reference): A platform for hosting and sharing interactive machine learning demos and applications.
    - [Pandas](https://pandas.pydata.org/): A Python library for data manipulation and analysis.
    - [Plotly](https://plotly.com/python/): A Python library for interactive data visualization.
    - [Matplotlib](https://matplotlib.org/): A Python library for creating static, animated, and interactive visualizations.
    - [Seaborn](https://seaborn.pydata.org/): A Python library for creating statistical graphics.
    - [SQLAlchemy](https://www.sqlalchemy.org/): A Python library for interacting with databases.
    - [Requests](https://requests.readthedocs.io/en/latest/): A Python library for making HTTP requests.
    - [Ruff](https://github.com/charliermarsh/ruff): An extremely fast Python linter and code formatter, written in Rust.
    - [uv](https://github.com/astral-sh/uv): An extremely fast Python package and project manager, written in Rust.

    """)

    mo.carousel(items=[description, erd_diagram, stack])
    return


@app.cell
def _():
    # πŸ“Œ IMPORT LIBRARIES AND PACKAGES

    from pathlib import Path

    from pandas import DataFrame
    from sqlalchemy import create_engine

    from src import config
    from src.extract import extract
    from src.load import load
    from src.plots import (
        plot_freight_value_weight_relationship,
        plot_global_amount_order_status,
        plot_order_amount_per_day_with_holidays,
        plot_real_vs_predicted_delivered_time,
        plot_revenue_by_month_year,
        plot_revenue_per_state,
        plot_top_10_least_revenue_categories,
        plot_top_10_revenue_categories,
        plot_top_10_revenue_categories_amount,
    )
    from src.transform import QueryEnum, run_queries
    return (
        DataFrame,
        Path,
        QueryEnum,
        config,
        create_engine,
        extract,
        load,
        plot_freight_value_weight_relationship,
        plot_global_amount_order_status,
        plot_order_amount_per_day_with_holidays,
        plot_real_vs_predicted_delivered_time,
        plot_revenue_by_month_year,
        plot_revenue_per_state,
        plot_top_10_least_revenue_categories,
        plot_top_10_revenue_categories,
        plot_top_10_revenue_categories_amount,
        run_queries,
    )


@app.cell
def _(DataFrame, Path, config, create_engine, extract, load, run_queries):
    # πŸ“Œ LOAD SQLITE DATABASE

    DB_PATH = Path(config.SQLITE_DB_ABSOLUTE_PATH)

    if DB_PATH.exists() and DB_PATH.stat().st_size > 0:
        print("Database found. Skipping ETL process.")
        ENGINE = create_engine(f"sqlite:///{DB_PATH}", echo=False)
    else:
        print("Database not found or empty. Starting ETL process...")
        ENGINE = create_engine(f"sqlite:///{DB_PATH}", echo=False)

        csv_dataframes = extract(
            csv_folder=config.DATASET_ROOT_PATH,
            csv_table_mapping=config.get_csv_to_table_mapping(),
            public_holidays_url=config.PUBLIC_HOLIDAYS_URL,
        )

        load(dataframes=csv_dataframes, database=ENGINE)
        print("ETL process complete.")

    query_results: dict[str, DataFrame] = run_queries(database=ENGINE)
    return (query_results,)


@app.cell
def _(QueryEnum, query_results: "dict[str, DataFrame]"):
    # πŸ“Œ RETRIEVE RELEVANT DATA FROM DATABASE

    revenue_by_month_year = query_results[QueryEnum.REVENUE_BY_MONTH_YEAR.value]

    top_10_revenue_categories = query_results[
        QueryEnum.TOP_10_REVENUE_CATEGORIES.value
    ]

    top_10_least_revenue_categories = query_results[
        QueryEnum.TOP_10_LEAST_REVENUE_CATEGORIES.value
    ]

    revenue_per_state = query_results[QueryEnum.REVENUE_PER_STATE.value]

    delivery_date_difference = query_results[
        QueryEnum.DELIVERY_DATE_DIFFERENCE.value
    ]

    real_vs_estimated_delivery_time = query_results[
        QueryEnum.REAL_VS_ESTIMATED_DELIVERED_TIME.value
    ]

    global_amount_order_status = query_results[
        QueryEnum.GLOBAL_AMOUNT_ORDER_STATUS.value
    ]

    orders_per_day_and_holidays = query_results[
        QueryEnum.ORDERS_PER_DAY_AND_HOLIDAYS_2017.value
    ]

    freight_value_weight_relationship = query_results[
        QueryEnum.GET_FREIGHT_VALUE_WEIGHT_RELATIONSHIP.value
    ]
    return (
        freight_value_weight_relationship,
        global_amount_order_status,
        orders_per_day_and_holidays,
        real_vs_estimated_delivery_time,
        revenue_by_month_year,
        revenue_per_state,
        top_10_least_revenue_categories,
        top_10_revenue_categories,
    )


@app.cell
def _(mo):
    mo.Html("<br><hr><br>")
    return


@app.cell
def _(mo):
    mo.md(r"""# πŸ“ˆ Insights""")
    return


@app.cell
def _(
    global_amount_order_status,
    revenue_by_month_year,
    top_10_revenue_categories,
):
    # πŸ“Œ RETRIEVE INSIGHTS VALUES

    # [1]
    total_2018 = revenue_by_month_year["Year2018"].sum()
    total_2017 = revenue_by_month_year["Year2017"].sum()

    # [2]
    delivered = global_amount_order_status.loc[
        global_amount_order_status["order_status"] == "delivered", "Amount"
    ].values[0]

    # Get total number of orders and delivery rate as a percentage string
    total_orders = global_amount_order_status["Amount"].sum()
    delivery_rate = delivered / total_orders
    percentage = f"{delivery_rate:.1%}"  # e.g., '85.2%'

    # [3]
    # Uncompleted orders = total - delivered
    uncompleted = total_orders - delivered
    uncompleted_pct = f"{(uncompleted / total_orders) * 100:.1f}%"

    # [4]
    top_cat = top_10_revenue_categories.iloc[0]

    cat_name = top_cat["Category"].replace("_", " ").title()
    cat_num_orders = int(top_cat["Num_order"])
    cat_revenue = top_cat["Revenue"]
    return (
        cat_name,
        cat_num_orders,
        cat_revenue,
        delivered,
        percentage,
        total_2017,
        total_2018,
        uncompleted,
        uncompleted_pct,
    )


@app.cell
def _(
    cat_name,
    cat_num_orders,
    cat_revenue,
    delivered,
    mo,
    percentage,
    total_2017,
    total_2018,
    uncompleted,
    uncompleted_pct,
):
    # πŸ“Œ DISPLAY INSIGHTS

    stat1 = mo.stat(
        label="Total Revenue 2018",
        bordered=True,
        value=f"${total_2018:,.0f}",
        caption=f"Previous year: ${total_2017:,.0f}",
        direction="increase" if total_2018 > total_2017 else "decrease",
    )

    stat2 = mo.stat(
        label="Successful Deliveries",
        bordered=True,
        value=f"{delivered:,}",
        caption=f"{percentage} of total orders",
        direction="increase",
    )

    stat3 = mo.stat(
        label="Uncompleted Orders",
        bordered=True,
        value=f"{uncompleted:,}",
        caption=f"{uncompleted_pct} of total orders",
        direction="decrease",
    )

    stat4 = mo.stat(
        label="Category with greater revenue",
        bordered=True,
        value=cat_name,
        caption=f"{cat_num_orders:,} orders β€’ Revenue: ${cat_revenue:,.0f}",
        direction="increase",
    )

    mo.hstack([stat1, stat2, stat3, stat4], widths="equal", gap=1)
    return


@app.cell
def _(mo):
    mo.Html("<br><hr><br>")
    return


@app.cell
def _(mo):
    mo.md(r"""# πŸ“Š Charts""")
    return


@app.cell
def _(
    freight_value_weight_relationship,
    global_amount_order_status,
    mo,
    orders_per_day_and_holidays,
    plot_freight_value_weight_relationship,
    plot_global_amount_order_status,
    plot_order_amount_per_day_with_holidays,
    plot_real_vs_predicted_delivered_time,
    plot_revenue_by_month_year,
    plot_revenue_per_state,
    plot_top_10_least_revenue_categories,
    plot_top_10_revenue_categories,
    plot_top_10_revenue_categories_amount,
    real_vs_estimated_delivery_time,
    revenue_by_month_year,
    revenue_per_state,
    top_10_least_revenue_categories,
    top_10_revenue_categories,
):
    overview_tab = mo.vstack(
        align="center",
        justify="center",
        gap=2,
        items=[
            mo.center(mo.md("## Global Order Status Overview")),
            plot_global_amount_order_status(df=global_amount_order_status),
        ],
    )

    revenue_tab = mo.vstack(
        align="center",
        justify="center",
        gap=2,
        items=[
            mo.center(mo.md("## Revenue by Month and Year")),
            plot_revenue_by_month_year(df=revenue_by_month_year, year=2017),
            mo.center(mo.md("## Revenue by State")),
            plot_revenue_per_state(revenue_per_state),
        ],
    )

    categories_tab = mo.vstack(
        align="center",
        justify="center",
        gap=2,
        items=[
            mo.center(mo.md("## Top 10 Revenue Categories")),
            plot_top_10_revenue_categories(top_10_revenue_categories),
            mo.center(mo.md("## Top 10 Revenue Categories by Amount")),
            plot_top_10_revenue_categories_amount(top_10_revenue_categories),
            mo.center(mo.md("## Bottom 10 Revenue Categories")),
            plot_top_10_least_revenue_categories(top_10_least_revenue_categories),
        ],
    )

    delivery_tab = mo.vstack(
        gap=2,
        justify="center",
        align="center",
        heights="equal",
        items=[
            mo.center(mo.md("## Real vs Estimated Delivery Time")),
            plot_real_vs_predicted_delivered_time(
                df=real_vs_estimated_delivery_time, year=2017
            ),
            mo.center(mo.md("## Freight Value vs Product Weight")),
            plot_freight_value_weight_relationship(
                freight_value_weight_relationship
            ),
            mo.center(mo.md("## Orders and Holidays")),
            plot_order_amount_per_day_with_holidays(orders_per_day_and_holidays),
        ],
    )
    return categories_tab, delivery_tab, overview_tab, revenue_tab


@app.cell
def _(categories_tab, delivery_tab, mo, overview_tab, revenue_tab):
    mo.ui.tabs(
        {
            "πŸ“Š Overview": overview_tab,
            "πŸ’° Revenue": revenue_tab,
            "πŸ“¦ Categories": categories_tab,
            "🚚 Freight & Delivery": delivery_tab,
        }
    )
    return


@app.cell
def _(mo):
    mo.Html("<br><hr><br>")
    return


@app.cell
def _(mo):
    mo.md(r"""# πŸ“‹ Tables""")
    return


@app.cell
def _(
    freight_value_weight_relationship,
    global_amount_order_status,
    mo,
    orders_per_day_and_holidays,
    real_vs_estimated_delivery_time,
    revenue_by_month_year,
    revenue_per_state,
    top_10_least_revenue_categories,
    top_10_revenue_categories,
):
    overview_table_tab = mo.vstack(
        align="center",
        justify="center",
        gap=2,
        items=[
            mo.center(mo.md("## Global Order Status Overview")),
            global_amount_order_status,
        ],
    )
    revenue_table_tab = mo.vstack(
        align="center",
        justify="center",
        gap=2,
        items=[
            mo.center(mo.md("## Revenue by Month and Year")),
            revenue_by_month_year,
            mo.center(mo.md("## Revenue by State")),
            revenue_per_state,
        ],
    )
    categories_table_tab = mo.vstack(
        align="center",
        justify="center",
        gap=2,
        items=[
            mo.center(mo.md("## Top 10 Revenue Categories")),
            top_10_revenue_categories,
            mo.center(mo.md("## Bottom 10 Revenue Categories")),
            top_10_least_revenue_categories,
        ],
    )
    delivery_table_tab = mo.vstack(
        align="center",
        justify="center",
        gap=2,
        items=[
            mo.center(mo.md("## Real vs Estimated Delivery Time")),
            real_vs_estimated_delivery_time,
            mo.center(mo.md("## Freight Value vs Product Weight")),
            freight_value_weight_relationship,
            mo.center(mo.md("## Orders and Holidays")),
            orders_per_day_and_holidays,
        ],
    )

    mo.ui.tabs(
        {
            "πŸ“Š Overview": overview_table_tab,
            "πŸ’° Revenue": revenue_table_tab,
            "πŸ“¦ Categories": categories_table_tab,
            "🚚 Freight & Delivery": delivery_table_tab,
        }
    )
    return


@app.cell
def _(mo):
    mo.callout(
        kind="info",
        value=mo.md(
            """πŸ’‘ **Want a step-by-step walkthrough instead?**   
    Check the Jupyter notebook version here: πŸ‘‰ [Jupyter notebook](https://huggingface.co/spaces/iBrokeTheCode/E-Commerce_ELT/blob/main/tutorial_app.ipynb)""",
        ),
    )
    return


@app.cell
def _(mo):
    mo.Html("<br><hr><br>")

    return


@app.cell
def _(mo):
    mo.center(
        mo.md(
            "**Connect with me:** πŸ’Ό [Linkedin](https://www.linkedin.com/in/alex-turpo/) β€’ 🐱 [GitHub](https://github.com/iBrokeTheCode) β€’ πŸ€— [Hugging Face](https://huggingface.co/iBrokeTheCode)"
        )
    )
    return


if __name__ == "__main__":
    app.run()