"""Build a random, prompt-ready sample from the bagaco3 dataset.""" import json import os import random import urllib.request from concurrent.futures import ThreadPoolExecutor, as_completed from types import SimpleNamespace import polars as polars from tqdm import tqdm config = SimpleNamespace( dataset="duarteocarmo/bagaco3", text_column="text", truncate_chars=1500, n_shards=300, rows_per_shard=100, max_workers=12, output_file="to_annotate_30K.jsonl", seed=42, ) PROMPT: str = """ Below is an extract from a web page. Evaluate whether the page has a high educational value and could be useful in an educational setting for teaching from primary school to grade school levels using the additive 5-point scoring system described below. The text will be in Portuguese. Evaluate its educational value based on content quality, not language. - 1 point: basic information relevant to educational topics, even with ads/promotional material. - 2 points: addresses elements pertinent to education but doesn't align closely with standards. - 3 points: appropriate for educational use, introduces key concepts relevant to school curricula. - 4 points: highly relevant for grade school education, clear writing, substantial content. - 5 points: outstanding educational value, perfectly suited for primary/grade school teaching. The extract: {} After examining the extract, briefly justify your total score (up to 100 words) and provide the educational score (0-5). Also classify the extract into one category: Society, Arts, Business, Science, Sports, Lifestyle, Health, Games, or News. Respond ONLY with a JSON object in this format: {{"justification": "up to 100 words", "educational_score": 0, "category": "category"}} Examples of good responses: {{"justification": "The extract clearly explains photosynthesis and its role in plant growth, with useful scientific concepts for students.", "educational_score": 4, "category": "Science"}} {{"justification": "The extract is mainly a product listing and offers little explanation beyond basic promotional information.", "educational_score": 1, "category": "Lifestyle"}} """.strip() def shard_urls(token: str | None) -> list[str]: """Return dataset parquet shard URLs.""" api_url = f"https://huggingface.co/api/datasets/{config.dataset}" headers = {"Authorization": f"Bearer {token}"} if token else {} request = urllib.request.Request(url=api_url, headers=headers) with urllib.request.urlopen(request) as response: filenames = [shard["rfilename"] for shard in json.load(response)["siblings"]] return [ f"hf://datasets/{config.dataset}/{filename}" for filename in filenames if filename.endswith(".parquet") ] def fetch_window( url: str, seed: int, storage_options: dict[str, str] | None ) -> polars.DataFrame: """Fetch one random, truncated shard window.""" scan = polars.scan_parquet(source=url, storage_options=storage_options) rows = scan.select(polars.len()).collect().item() rng = random.Random(x=seed) offset = rng.randint(0, max(rows - config.rows_per_shard, 0)) return ( scan.slice(offset=offset, length=config.rows_per_shard) .select( polars.col(config.text_column) .str.slice(offset=0, length=config.truncate_chars) .alias("text_concat"), polars.col("source"), ) .with_columns( polars.format(PROMPT, polars.col("text_concat")).alias("prompt") ) .collect() ) def fetch_windows( urls: list[str], seeds: list[int], storage_options: dict[str, str] | None ) -> list[polars.DataFrame]: """Fetch shard windows concurrently.""" windows: list[polars.DataFrame | None] = [None] * len(urls) with ThreadPoolExecutor(max_workers=config.max_workers) as executor: futures = { executor.submit( fetch_window, url=url, seed=seed, storage_options=storage_options, ): index for index, (url, seed) in enumerate(zip(urls, seeds, strict=True)) } for future in tqdm( as_completed(futures), total=len(futures), desc="Fetching shard windows" ): windows[futures[future]] = future.result() return [window for window in windows if window is not None] def main() -> None: """Save the sampled rows as NDJSON.""" token = os.getenv("HF_TOKEN") storage_options = {"token": token} if token else None rng = random.Random(x=config.seed) urls = rng.sample(population=shard_urls(token=token), k=config.n_shards) seeds = [rng.getrandbits(64) for _ in urls] samples = polars.concat( items=fetch_windows(urls=urls, seeds=seeds, storage_options=storage_options) ) expected_rows = config.n_shards * config.rows_per_shard if samples.height != expected_rows: raise RuntimeError(f"Expected {expected_rows} rows, got {samples.height}") print(samples["source"].value_counts(sort=True)) samples.write_ndjson(file=config.output_file) if __name__ == "__main__": main()