File size: 12,834 Bytes
1375ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5fca88
1375ba2
 
 
 
 
 
9a0f415
1375ba2
b5fca88
9a0f415
1375ba2
9a0f415
b5fca88
 
 
 
1eb05b5
1375ba2
 
b5fca88
 
a5ec458
1375ba2
9a0f415
1375ba2
 
 
 
1eb05b5
1375ba2
 
b5fca88
 
 
 
 
 
 
 
 
 
 
9a0f415
b5fca88
 
 
 
1eb05b5
b5fca88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a0f415
1eb05b5
 
 
b5fca88
 
 
 
 
 
 
1eb05b5
b5fca88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a0f415
1eb05b5
 
 
b5fca88
 
 
 
 
 
 
1eb05b5
9a0f415
b5fca88
9a0f415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5fca88
 
9a0f415
 
 
 
 
 
 
 
 
b5fca88
 
 
 
9a0f415
 
 
 
 
 
b5fca88
 
9a0f415
1eb05b5
 
 
9a0f415
 
 
 
 
 
 
 
 
 
 
 
b5fca88
9a0f415
 
b5fca88
9a0f415
 
b5fca88
 
 
 
 
 
1eb05b5
9a0f415
b5fca88
 
9a0f415
 
 
 
 
 
 
b5fca88
a5ec458
1375ba2
1eb05b5
 
 
 
 
 
1375ba2
 
 
 
1eb05b5
1375ba2
 
b5fca88
 
 
 
 
 
 
 
 
 
1375ba2
 
 
 
1eb05b5
 
 
b5fca88
 
1375ba2
b5fca88
1375ba2
9a0f415
 
1375ba2
 
 
 
 
 
 
9a0f415
 
 
 
1375ba2
b5fca88
 
 
 
 
 
 
 
 
 
 
9a0f415
b5fca88
 
 
 
1eb05b5
 
 
 
 
 
 
1375ba2
b5fca88
1375ba2
 
 
 
1eb05b5
b5fca88
 
 
 
 
1375ba2
 
b5fca88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1375ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5fca88
1eb05b5
 
 
1375ba2
 
 
 
 
 
 
1eb05b5
b5fca88
1375ba2
b5fca88
 
9a0f415
 
b5fca88
 
 
 
 
 
a5ec458
1375ba2
 
b5fca88
9a0f415
1375ba2
1eb05b5
 
 
b5fca88
9a0f415
b5fca88
9a0f415
1375ba2
b5fca88
 
 
9a0f415
b5fca88
9a0f415
 
 
 
 
1eb05b5
 
 
b5fca88
 
1375ba2
 
 
 
1eb05b5
9a0f415
 
1eb05b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a0f415
 
 
1375ba2
 
 
1eb05b5
 
 
 
 
1375ba2
 
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
# /// script
# dependencies = [
#     "diskcache==5.6.3",
#     "duckdb==1.4.4",
#     "marimo",
#     "matplotlib==3.10.8",
#     "numpy",
#     "openai",
#     "pandas==3.0.0",
#     "polars[pyarrow]==1.38.1",
#     "pydantic-ai==1.59.0",
#     "scikit-learn==1.8.0",
#     "sqlglot==28.10.1",
#     "tqdm",
# ]
# requires-python = ">=3.14"
# ///

import marimo

__generated_with = "0.20.1"
app = marimo.App()


@app.cell
def _():
    import duckdb
    import marimo as mo
    import matplotlib.pyplot as plt
    import numpy
    import polars as pl

    conn = duckdb.connect(database="bagaco.duckdb")
    return conn, mo, numpy, pl, plt


@app.cell
def _(bagaco, conn, mo):
    _df = mo.sql(
        f"""
    SELECT COUNT(*) AS total_docs FROM bagaco;
    """,
        engine=conn,
    )
    mo.vstack(items=[mo.md(text="### Total document count"), _df])
    return


@app.cell
def _(bagaco, conn, mo):
    _df = mo.sql(
        f"""
    SELECT
      regexp_replace(lower(regexp_extract(url, '^(?:https?://)?(?:[^@/\\n]+@)?([^:/?\\n]+)', 1)), '^www\\.', '') AS domain,
      COUNT(*) AS n_docs
    FROM bagaco
    WHERE url IS NOT NULL AND url <> ''
    GROUP BY 1
    ORDER BY n_docs DESC
    LIMIT 10;
    """,
        engine=conn,
    )
    mo.vstack(items=[mo.md(text="### Top 10 domains by document count"), _df])
    return


@app.cell
def _(bagaco, conn, mo):
    _df = mo.sql(
        f"""
    SELECT
        regexp_replace(lower(regexp_extract(url, '^(?:https?://)?(?:[^@/\\n]+@)?([^:/?\\n]+)', 1)), '^www\\.', '') AS domain,
        ROUND(AVG(educational_score), 2) AS avg_edu_score,
        COUNT(*) AS n_docs
    FROM bagaco
    WHERE url IS NOT NULL AND url <> '' AND educational_score IS NOT NULL
    GROUP BY 1
    HAVING COUNT(*) >= 100
    ORDER BY avg_edu_score DESC
    LIMIT 15;
    """,
        engine=conn,
    )
    mo.vstack(
        items=[
            mo.md(
                text="### Domains with highest avg educational score (min 100 docs)"
            ),
            _df,
        ]
    )
    return


@app.cell
def _(bagaco, conn, mo):
    _df = mo.sql(
        f"""
    SELECT
        regexp_replace(lower(regexp_extract(url, '^(?:https?://)?(?:[^@/\\n]+@)?([^:/?\\n]+)', 1)), '^www\\.', '') AS domain,
        ROUND(AVG(educational_score), 2) AS avg_edu_score,
        COUNT(*) AS n_docs
    FROM bagaco
    WHERE url IS NOT NULL AND url <> '' AND educational_score IS NOT NULL
    GROUP BY 1
    HAVING COUNT(*) >= 100
    ORDER BY avg_edu_score ASC
    LIMIT 15;
    """,
        engine=conn,
    )
    mo.vstack(
        items=[
            mo.md(
                text="### Domains with lowest avg educational score (min 100 docs)"
            ),
            _df,
        ]
    )
    return


@app.cell
def _(bagaco, conn, mo, plt):
    _domain_scatter_df = mo.sql(
        f"""
    WITH domain_stats AS (
        SELECT
            regexp_replace(lower(regexp_extract(url, '^(?:https?://)?(?:[^@/\\n]+@)?([^:/?\\n]+)', 1)), '^www\\.', '') AS domain,
            COUNT(*) AS total_docs,
            AVG(educational_score) AS avg_edu_score
        FROM bagaco
        WHERE url IS NOT NULL
          AND url <> ''
          AND educational_score IS NOT NULL
        GROUP BY 1
        HAVING COUNT(*) > 10
    ),
    domain_categories AS (
        SELECT
            domain,
            category,
            ROW_NUMBER() OVER (PARTITION BY domain ORDER BY n_docs DESC, category ASC) AS row_number
        FROM (
            SELECT
                regexp_replace(lower(regexp_extract(url, '^(?:https?://)?(?:[^@/\\n]+@)?([^:/?\\n]+)', 1)), '^www\\.', '') AS domain,
                category,
                COUNT(*) AS n_docs
            FROM bagaco
            WHERE url IS NOT NULL
              AND url <> ''
              AND category IS NOT NULL
            GROUP BY 1, 2
        )
    )
    SELECT
        domain_stats.domain,
        domain_stats.total_docs,
        ROUND(domain_stats.avg_edu_score, 3) AS avg_edu_score,
        COALESCE(domain_categories.category, 'Unknown') AS category
    FROM domain_stats
    LEFT JOIN domain_categories
        ON domain_stats.domain = domain_categories.domain
       AND domain_categories.row_number = 1
    ORDER BY domain_stats.total_docs DESC;
    """,
        engine=conn,
    )

    _categories = sorted(_domain_scatter_df["category"].unique().to_list())
    _colors = plt.cm.tab10.colors
    _category_colors = {
        _category: _colors[_index % len(_colors)]
        for _index, _category in enumerate(_categories)
    }

    _, _ax = plt.subplots(figsize=(12, 6))
    for _category in _categories:
        _subset = _domain_scatter_df.filter(
            _domain_scatter_df["category"] == _category
        )
        _ax.scatter(
            x=_subset["total_docs"].to_list(),
            y=_subset["avg_edu_score"].to_list(),
            s=16,
            alpha=0.65,
            color=_category_colors[_category],
            label=_category,
        )

    _ax.set_xscale(value="log")
    _ax.set_xlabel(xlabel="Total documents (log scale)")
    _ax.set_ylabel(ylabel="Average educational score")
    _ax.set_title(
        label="Domain Scatter: Total Documents (Log) vs Avg Educational Score",
        fontweight="bold",
    )
    _ax.grid(visible=True, axis="both", linestyle="-", linewidth=0.5, alpha=0.35)
    _ax.legend(loc="best", fontsize=8, ncols=2)
    plt.tight_layout()
    _ax
    return


@app.cell
def _(bagaco, conn, mo):
    _fast_total_words = mo.sql(
        f"""
    SELECT
        SUM(
            CASE
                WHEN text IS NULL OR text = '' THEN 0
                ELSE len(trim(text)) - len(replace(trim(text), ' ', '')) + 1
            END
        ) AS total_words_fast
    FROM bagaco;
    """,
        engine=conn,
    )
    mo.vstack(
        items=[
            mo.md(text="### Total words in dataset (fast computation)"),
            _fast_total_words,
        ]
    )
    return


@app.cell
def _(bagaco, conn, mo, plt):
    df_per_halfyear = mo.sql(
        f"""
    SELECT
        EXTRACT(YEAR FROM CAST(date AS TIMESTAMP)) || ' H' ||
        CASE WHEN EXTRACT(MONTH FROM CAST(date AS TIMESTAMP)) <= 6 THEN 1 ELSE 2 END AS year_half,
        COUNT(*) / 1000000.0 AS total_doc_count_millions,
        ROUND(AVG(educational_score), 3) AS avg_edu_score
    FROM bagaco
    WHERE date IS NOT NULL
    GROUP BY 1
    ORDER BY 1;
    """,
        engine=conn,
    )

    year_half = df_per_halfyear["year_half"].to_list()
    total_doc_count_millions = df_per_halfyear[
        "total_doc_count_millions"
    ].to_list()
    _avg_edu = df_per_halfyear["avg_edu_score"].to_list()
    _x_positions = list(range(len(year_half)))

    _fig, ax = plt.subplots(figsize=(12, 6))
    ax.bar(
        x=_x_positions,
        height=total_doc_count_millions,
        width=0.65,
        color="#449DE3",
        edgecolor="#4a4a4a",
        linewidth=0.6,
        alpha=0.85,
        label="Total Document Count (M)",
    )
    ax.set_xticks(ticks=_x_positions)
    ax.set_xticklabels(labels=year_half, rotation=45, ha="right")
    ax.set_xlabel(xlabel="Half-Year")
    ax.set_ylabel(ylabel="Total Document Count (Millions)")
    ax.grid(axis="y", linestyle="-", linewidth=0.5, alpha=0.35)

    _ax2 = ax.twinx()
    _ax2.plot(
        _x_positions,
        _avg_edu,
        color="#d73027",
        linewidth=2,
        marker="o",
        markersize=4,
        label="Avg Edu Score",
    )
    _ax2.set_ylabel(ylabel="Avg Educational Score", color="#d73027")
    _ax2.tick_params(axis="y", labelcolor="#d73027")

    _lines1, _labels1 = ax.get_legend_handles_labels()
    _lines2, _labels2 = _ax2.get_legend_handles_labels()
    ax.legend(
        handles=_lines1 + _lines2, labels=_labels1 + _labels2, loc="upper left"
    )
    ax.set_title(
        label="Document Volume & Avg Educational Score Over Time",
        fontweight="bold",
    )
    plt.tight_layout()
    _fig
    return


@app.cell
def _(bagaco, conn, mo, plt):
    df_word_count_distribution = mo.sql(
        f"""
    WITH wc AS (
        SELECT len(string_split(text, ' ')) AS word_count FROM bagaco WHERE text IS NOT NULL
    ), bucketed AS (
        SELECT
            CASE
                WHEN word_count <= 150 THEN 'Note (0-150)'
                WHEN word_count <= 600 THEN 'Short Article (151-600)'
                WHEN word_count <= 1500 THEN 'Standard Article (601-1500)'
                WHEN word_count <= 5000 THEN 'Longform (1501-5000)'
                WHEN word_count <= 20000 THEN 'Deep Report (5001-20000)'
                ELSE 'Book (20001+)'
            END AS length_band,
            COUNT(*) / 1000000.0 AS doc_count_millions
        FROM wc
        GROUP BY 1
    )
    SELECT
        CASE
            WHEN length_band = 'Note (0-150)' THEN 1
            WHEN length_band = 'Short Article (151-600)' THEN 2
            WHEN length_band = 'Standard Article (601-1500)' THEN 3
            WHEN length_band = 'Longform (1501-5000)' THEN 4
            WHEN length_band = 'Deep Report (5001-20000)' THEN 5
            ELSE 6
        END AS bucket_order,
        length_band,
        doc_count_millions
    FROM bucketed
    ORDER BY 1;
    """,
        engine=conn,
    )

    length_band_labels = df_word_count_distribution["length_band"].to_list()
    doc_count_millions = df_word_count_distribution["doc_count_millions"].to_list()
    y_positions = list(range(len(length_band_labels)))

    _, word_count_ax = plt.subplots(figsize=(12, 4.8))
    word_count_ax.barh(
        y=y_positions,
        width=doc_count_millions,
        color="#449DE3",
        edgecolor="#4a4a4a",
        linewidth=0.6,
        alpha=0.85,
        label="Total Document Count (M)",
    )
    word_count_ax.set_yticks(ticks=y_positions)
    word_count_ax.set_yticklabels(labels=length_band_labels)
    word_count_ax.set_xlabel(xlabel="Total Document Count (Millions)")
    word_count_ax.set_ylabel(ylabel="Word Count Band")
    word_count_ax.set_title(label="Word Count Distribution", fontweight="bold")
    word_count_ax.grid(
        visible=True, axis="x", linestyle="-", linewidth=0.5, alpha=0.35
    )
    word_count_ax.legend(loc="lower right")
    plt.tight_layout()
    word_count_ax
    return


@app.cell
def _(bagaco, conn, mo, numpy, pl, plt):
    _df_heatmap = mo.sql(
        f"""
    SELECT
        category,
        EXTRACT(YEAR FROM CAST(date AS TIMESTAMP)) || ' H' ||
        CASE WHEN EXTRACT(MONTH FROM CAST(date AS TIMESTAMP)) <= 6 THEN 1 ELSE 2 END AS year_half,
        ROUND(AVG(educational_score), 3) AS avg_edu_score
    FROM bagaco
    WHERE date IS NOT NULL AND category IS NOT NULL AND educational_score IS NOT NULL
    GROUP BY 1, 2
    ORDER BY 1, 2;
    """,
        engine=conn,
    )

    _categories = sorted(_df_heatmap["category"].unique().to_list())
    _periods = sorted(_df_heatmap["year_half"].unique().to_list())

    _grid = numpy.full(
        shape=(len(_categories), len(_periods)), fill_value=numpy.nan
    )
    for _i, _cat in enumerate(_categories):
        for _j, _period in enumerate(_periods):
            _match = _df_heatmap.filter(
                (pl.col("category") == _cat) & (pl.col("year_half") == _period)
            )
            if len(_match) > 0:
                _grid[_i, _j] = _match["avg_edu_score"][0]

    _fig, _ax = plt.subplots(figsize=(14, 6))
    _im = _ax.imshow(_grid, aspect="auto", cmap="RdYlGn", interpolation="nearest")
    plt.colorbar(mappable=_im, ax=_ax, label="Avg Educational Score")
    _ax.set_yticks(ticks=range(len(_categories)))
    _ax.set_yticklabels(labels=_categories)
    _ax.set_xticks(ticks=range(len(_periods)))
    _ax.set_xticklabels(labels=_periods, rotation=45, ha="right")
    _ax.set_title(
        label="Avg Educational Score by Category and Half-Year", fontweight="bold"
    )
    plt.tight_layout()
    _fig
    return


@app.cell
def _(bagaco, conn, mo):
    _category_summary_df = mo.sql(
        f"""
        SELECT
    category,
    COUNT(*) AS total_documents,
    ROUND(AVG(educational_score), 3) AS average_educational_score,
    ROUND(AVG(educational_score), 3) AS mean_educational_score,
    ROUND(
        SUM(CASE WHEN educational_score >= 3 THEN 1 ELSE 0 END) * 100.0 / COUNT(*),
        2
    ) AS pct_high_educational_score_documents,
    COUNT(
        DISTINCT regexp_replace(
            lower(regexp_extract(url, '^(?:https?://)?(?:[^@/\\n]+@)?([^:/?\\n]+)', 1)),
            '^www\\.',
            ''
        )
    ) AS total_different_domains
        FROM bagaco
        WHERE category IS NOT NULL
          AND educational_score IS NOT NULL
        GROUP BY 1
        ORDER BY total_documents DESC;
        """,
        engine=conn,
    )
    mo.vstack(items=[mo.md(text="### Category summary"), _category_summary_df])
    return


@app.cell
def _():
    return


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