| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import json |
| import os |
| from types import SimpleNamespace |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
|
|
| import duckdb |
| import polars |
| from diskcache import Cache |
| from openai import OpenAI |
| from pydantic import BaseModel |
| from tenacity import retry, stop_after_attempt, wait_exponential |
| from tqdm import tqdm |
|
|
| config = SimpleNamespace( |
| db_path="duckdb/fineweb2_bagaco.duckdb", |
| cache_dir=".edu_cache", |
| sample_size=30_000, |
| sample_seed=42, |
| text_truncate_chars=1500, |
| text_preview_chars=120, |
| model="qwen/qwen3-235b-a22b-2507", |
| extra_body={ |
| "provider": { |
| "order": ["deepinfra", "wandb"], |
| "allow_fallbacks": False, |
| }, |
| }, |
| max_workers=15, |
| n_preview_samples=15, |
| ) |
|
|
| EDU_PROMPT = """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. Points are accumulated based on the satisfaction of each criterion: |
| |
| - Add 1 point if the extract provides some basic information relevant to educational topics, even if it includes some irrelevant or non-academic content like advertisements and promotional material. |
| - Add another point if the extract addresses certain elements pertinent to education but does not align closely with educational standards. It might mix educational content with non-educational material, offering a superficial overview of potentially useful topics, or presenting information in a disorganized manner and incoherent writing style. |
| - Award a third point if the extract is appropriate for educational use and introduces key concepts relevant to school curricula. It is coherent though it may not be comprehensive or could include some extraneous information. It may resemble an introductory section of a textbook or a basic tutorial that is suitable for learning but has notable limitations like treating concepts that are too complex for grade school students. |
| - Grant a fourth point if the extract highly relevant and beneficial for educational purposes for a level not higher than grade school, exhibiting a clear and consistent writing style. It could be similar to a chapter from a textbook or a tutorial, offering substantial educational content, including exercises and solutions, with minimal irrelevant information, and the concepts aren't too advanced for grade school students. The content is coherent, focused, and valuable for structured learning. |
| - Bestow a fifth point if the extract is outstanding in its educational value, perfectly suited for teaching either at primary school or grade school. It follows detailed reasoning, the writing style is easy to follow and offers profound and thorough insights into the subject matter, devoid of any non-educational or complex content. |
| |
| The extract: |
| <extract> |
| {text} |
| </extract> |
| |
| After examining the extract, briefly justify your total score (up to 100 words) and provide the educational score (0-5).""" |
|
|
|
|
| class EduClassification(BaseModel): |
| justification: str |
| educational_score: int |
|
|
|
|
| disk_cache = Cache(config.cache_dir) |
| openrouter_client = OpenAI( |
| base_url="https://openrouter.ai/api/v1", |
| api_key=os.environ["OPENROUTER_API_KEY"], |
| ) |
|
|
|
|
| @disk_cache.memoize() |
| @retry(stop=stop_after_attempt(2), wait=wait_exponential(min=1, max=10)) |
| def classify_edu( |
| text: str, |
| model: str, |
| extra_body_json: str = "null", |
| cache_seed: int = 1, |
| ) -> str: |
| extra_body = json.loads(extra_body_json) |
| truncated = text[: config.text_truncate_chars].strip() |
| response = openrouter_client.beta.chat.completions.parse( |
| model=model, |
| messages=[{"role": "user", "content": EDU_PROMPT.format(text=truncated)}], |
| response_format=EduClassification, |
| temperature=0.0, |
| timeout=15, |
| extra_body=extra_body, |
| ) |
| return response.choices[0].message.parsed.model_dump_json() |
|
|
|
|
| def classify_edu_batch(text_list: list[str]) -> list[str | None]: |
| results: list[str | None] = [None] * len(text_list) |
| with ThreadPoolExecutor(max_workers=config.max_workers) as executor: |
| futures = { |
| executor.submit( |
| classify_edu, |
| text=text, |
| model=config.model, |
| extra_body_json=json.dumps(config.extra_body, sort_keys=True), |
| ): i |
| for i, text in enumerate(text_list) |
| } |
| for future in tqdm(as_completed(futures), total=len(text_list), desc="Scoring"): |
| idx = futures[future] |
| try: |
| results[idx] = future.result() |
| except Exception as e: |
| print(f"Error scoring text at index {idx}: {e}") |
| return results |
|
|
|
|
| def main(): |
| conn = duckdb.connect(config.db_path) |
| print(f"Connected to DuckDB at {config.db_path}, making sample query...") |
| sample = conn.sql(f""" |
| SELECT * |
| FROM bagaco |
| USING SAMPLE reservoir({config.sample_size} ROWS) REPEATABLE ({config.sample_seed}) |
| """).pl() |
| print(f"Sampled {len(sample)} rows") |
|
|
| texts = sample.select("text").to_series().to_list() |
| scores = classify_edu_batch(text_list=texts) |
|
|
| result = sample.with_columns( |
| polars.Series(name="edu_classification", values=scores) |
| ) |
| model_name = config.model.split("/")[-1].replace("-", "_") |
| sample_size = f"sample_{config.sample_size}" if config.sample_size else len(result) |
| output_path = ( |
| f"reference/fineweb2_edu_classification_{sample_size}_{model_name}.parquet" |
| ) |
|
|
| result.write_parquet(output_path) |
| print(f"Saved {len(result)} rows to {output_path}") |
|
|
| import statistics |
|
|
| parsed_scores = result.select("edu_classification").to_series().to_list() |
| score_values = [json.loads(s)["educational_score"] for s in parsed_scores if s] |
| total = len(score_values) |
| counts = {s: score_values.count(s) for s in range(6)} |
|
|
| print("\n" + "=" * 60) |
| print("SCORE DISTRIBUTION") |
| print("=" * 60) |
| print(f"Total docs: {total}") |
| print(f"Mean score: {statistics.mean(score_values):.1f}") |
| print(f"Median score: {statistics.median(score_values):.0f}") |
| print() |
| for score in range(6): |
| count = counts[score] |
| pct = count / total * 100 if total else 0 |
| print(f" {score}/5 — {count} docs ({pct:.1f}%)") |
|
|
| print("\n" + "=" * 60) |
| print(f"SAMPLE CLASSIFICATIONS ({config.n_preview_samples})") |
| print("=" * 60) |
| for i, row in enumerate( |
| result.sample(n=config.n_preview_samples, seed=config.sample_seed).iter_rows( |
| named=True |
| ), |
| 1, |
| ): |
| classification = ( |
| json.loads(row["edu_classification"]) if row["edu_classification"] else None |
| ) |
| score = classification["educational_score"] if classification else "N/A" |
| justification = classification["justification"] if classification else "N/A" |
| url = row.get("url", "N/A") |
| text_preview = row["text"][: config.text_preview_chars].replace("\n", " ") |
| print(f"\n [{i}] Score: {score}/5 | {url}") |
| print(f" {justification}") |
| print(f" >>> {text_preview}...") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|