# /// 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()