Madras1 commited on
Commit
ed69745
·
verified ·
1 Parent(s): d4163f9

Upload 9 files

Browse files
.gitattributes CHANGED
@@ -1,60 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.avro filter=lfs diff=lfs merge=lfs -text
4
- *.bin filter=lfs diff=lfs merge=lfs -text
5
- *.bz2 filter=lfs diff=lfs merge=lfs -text
6
- *.ckpt filter=lfs diff=lfs merge=lfs -text
7
- *.ftz filter=lfs diff=lfs merge=lfs -text
8
- *.gz filter=lfs diff=lfs merge=lfs -text
9
- *.h5 filter=lfs diff=lfs merge=lfs -text
10
- *.joblib filter=lfs diff=lfs merge=lfs -text
11
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
12
- *.lz4 filter=lfs diff=lfs merge=lfs -text
13
- *.mds filter=lfs diff=lfs merge=lfs -text
14
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
15
- *.model filter=lfs diff=lfs merge=lfs -text
16
- *.msgpack filter=lfs diff=lfs merge=lfs -text
17
- *.npy filter=lfs diff=lfs merge=lfs -text
18
- *.npz filter=lfs diff=lfs merge=lfs -text
19
- *.onnx filter=lfs diff=lfs merge=lfs -text
20
- *.ot filter=lfs diff=lfs merge=lfs -text
21
  *.parquet filter=lfs diff=lfs merge=lfs -text
22
- *.pb filter=lfs diff=lfs merge=lfs -text
23
- *.pickle filter=lfs diff=lfs merge=lfs -text
24
- *.pkl filter=lfs diff=lfs merge=lfs -text
25
- *.pt filter=lfs diff=lfs merge=lfs -text
26
- *.pth filter=lfs diff=lfs merge=lfs -text
27
- *.rar filter=lfs diff=lfs merge=lfs -text
28
- *.safetensors filter=lfs diff=lfs merge=lfs -text
29
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
30
- *.tar.* filter=lfs diff=lfs merge=lfs -text
31
- *.tar filter=lfs diff=lfs merge=lfs -text
32
- *.tflite filter=lfs diff=lfs merge=lfs -text
33
- *.tgz filter=lfs diff=lfs merge=lfs -text
34
- *.wasm filter=lfs diff=lfs merge=lfs -text
35
- *.xz filter=lfs diff=lfs merge=lfs -text
36
- *.zip filter=lfs diff=lfs merge=lfs -text
37
- *.zst filter=lfs diff=lfs merge=lfs -text
38
- *tfevents* filter=lfs diff=lfs merge=lfs -text
39
- # Audio files - uncompressed
40
- *.pcm filter=lfs diff=lfs merge=lfs -text
41
- *.sam filter=lfs diff=lfs merge=lfs -text
42
- *.raw filter=lfs diff=lfs merge=lfs -text
43
- # Audio files - compressed
44
- *.aac filter=lfs diff=lfs merge=lfs -text
45
- *.flac filter=lfs diff=lfs merge=lfs -text
46
- *.mp3 filter=lfs diff=lfs merge=lfs -text
47
- *.ogg filter=lfs diff=lfs merge=lfs -text
48
- *.wav filter=lfs diff=lfs merge=lfs -text
49
- # Image files - uncompressed
50
- *.bmp filter=lfs diff=lfs merge=lfs -text
51
- *.gif filter=lfs diff=lfs merge=lfs -text
52
  *.png filter=lfs diff=lfs merge=lfs -text
53
- *.tiff filter=lfs diff=lfs merge=lfs -text
54
- # Image files - compressed
55
- *.jpg filter=lfs diff=lfs merge=lfs -text
56
- *.jpeg filter=lfs diff=lfs merge=lfs -text
57
- *.webp filter=lfs diff=lfs merge=lfs -text
58
- # Video files - compressed
59
- *.mp4 filter=lfs diff=lfs merge=lfs -text
60
- *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.parquet filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  *.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,3 +1,156 @@
1
  ---
2
  license: odc-by
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: odc-by
3
+ language:
4
+ - pt
5
+ pretty_name: Corpus PT-BR v2
6
+ tags:
7
+ - portuguese
8
+ - pt-br
9
+ - brazilian-portuguese
10
+ - brasil
11
+ - português
12
+ - nlp
13
+ - llm
14
+ - pretraining
15
+ - fine-tuning
16
+ - text-generation
17
+ - synthetic-data
18
+ - corpus
19
+ - parquet
20
+ task_categories:
21
+ - text-generation
22
+ - fill-mask
23
+ - text-classification
24
+ size_categories:
25
+ - 1M<n<10M
26
  ---
27
+
28
+ # Corpus PT-BR v2
29
+
30
+ Um corpus em Portugues Brasileiro voltado para pre-treinamento, continuacao de pre-treinamento e fine-tuning de LLMs. Esta versao mantem a base e o pipeline geral do `Madras1/corpus-ptbr-v1`, com uma expansao adicional da camada sintetica gerada principalmente por modelos Mistral.
31
+
32
+ ## O que mudou na v2
33
+
34
+ A v2 preserva o desenho da v1 e adiciona um novo bloco sintetico local:
35
+
36
+ | Componente novo | Valor |
37
+ |---|---:|
38
+ | Documentos sinteticos adicionados | 371,002 |
39
+ | Palavras adicionadas | 590,143,768 |
40
+ | Tokens estimados adicionados | ~767,186,898 |
41
+ | Tamanho JSONL local original | ~4.01 GB |
42
+ | Tamanho Parquet do incremento | ~1.53 GB |
43
+ | Shards Parquet novos | 4 |
44
+ | Provider principal | Mistral |
45
+ | Modelos principais | `mistral-small-latest`, `mistral-medium-latest` |
46
+
47
+ ## Estatisticas estimadas
48
+
49
+ As estatisticas abaixo combinam os numeros publicos da v1 com o novo bloco sintetico local convertido para Parquet.
50
+
51
+ | Metrica | Valor |
52
+ |---|---:|
53
+ | Total de documentos | ~8,770,859 |
54
+ | Total de palavras | ~5.43B |
55
+ | Tokens estimados | ~7.06B |
56
+ | Idioma | Portugues Brasileiro (`pt-br`) |
57
+ | Licenca | ODC-By 1.0 |
58
+
59
+ ### Subsets
60
+
61
+ | Subset | Documentos | Palavras | Tokens estimados |
62
+ |---|---:|---:|---:|
63
+ | `real` | 6,813,702 | ~4.10B | ~5.33B |
64
+ | `synthetic` | ~1,957,157 | ~1.33B | ~1.73B |
65
+
66
+ ## Fontes
67
+
68
+ ### Subset `real`
69
+
70
+ Dados de pretraining limpos e filtrados de fontes publicas, herdados da v1:
71
+
72
+ | Fonte | Documentos | Descricao |
73
+ |---|---:|---|
74
+ | `c4_pt` | 3,070,868 | Common Crawl (C4), subset em portugues |
75
+ | `fineweb2_pt` | 3,742,834 | FineWeb2 filtrado para portugues |
76
+
77
+ ### Subset `synthetic`
78
+
79
+ A v2 inclui todo o conjunto sintetico da v1 e adiciona 371,002 documentos gerados localmente em abril/maio de 2026.
80
+
81
+ Novo bloco v2:
82
+
83
+ | Provider/model | Documentos |
84
+ |---|---:|
85
+ | `mistral-small-latest` | 288,189 |
86
+ | `mistral-medium-latest` | 74,407 |
87
+ | `nvidia/nemotron-3-super-120b-a12b:free` | 8,406 |
88
+
89
+ Nos shards v2, o campo `source` representa a origem sintetica normalizada:
90
+
91
+ | `source` | Significado |
92
+ |---|---|
93
+ | `v2_synthetic_mistral_small_latest` | Texto sintetico gerado com Mistral Small |
94
+ | `v2_synthetic_mistral_medium_latest` | Texto sintetico gerado com Mistral Medium |
95
+ | `v2_synthetic_openrouter_nvidia_nemotron_3_super_120b_a12b_free` | Texto sintetico gerado via OpenRouter/Nemotron |
96
+
97
+ ## Schema
98
+
99
+ O schema principal foi mantido compativel com a v1 para permitir carregamento como um unico split `train`.
100
+
101
+ | Campo | Tipo | Descricao |
102
+ |---|---|---|
103
+ | `text` | `string` | Conteudo do documento |
104
+ | `source` | `string` | Fonte/origem normalizada |
105
+ | `subset` | `string` | `real` ou `synthetic` |
106
+ | `word_count` | `int32` | Contagem de palavras |
107
+ | `char_count` | `int32` | Contagem de caracteres |
108
+ | `language` | `string` | `pt-br` |
109
+
110
+ ## Como usar
111
+
112
+ ```python
113
+ from datasets import load_dataset
114
+
115
+ ds = load_dataset("Madras1/corpus-ptbr-v2", split="train", streaming=True)
116
+
117
+ for row in ds.take(1):
118
+ print(row["text"][:500])
119
+ ```
120
+
121
+ Para filtrar apenas a camada sintetica:
122
+
123
+ ```python
124
+ from datasets import load_dataset
125
+
126
+ ds = load_dataset("Madras1/corpus-ptbr-v2", split="train", streaming=True)
127
+ synthetic = (row for row in ds if row["subset"] == "synthetic")
128
+ ```
129
+
130
+ ## Limitações
131
+
132
+ - Dados sinteticos podem conter alucinacoes factuais.
133
+ - O subset real herda vieses, ruidos e limitacoes das fontes originais.
134
+ - O corpus nao deve ser tratado como fonte factual autoritativa.
135
+ - Estimativas de tokens usam fator aproximado de `1.3x` sobre contagem de palavras.
136
+ - A v2 aumenta a proporcao de texto sintetico; para pre-treinamento mais conservador, recomenda-se misturar pesos por `subset` e `source`.
137
+
138
+ ## Licenca e termos
139
+
140
+ O Corpus PT-BR v2 e distribuido sob ODC-By 1.0, seguindo a base da v1. O subset sintetico contem outputs de modelos de linguagem e deve ser usado com atencao aos termos dos provedores usados na geracao. Segundo a documentacao publica da Mistral AI, usuarios possuem seus outputs ate onde permitido pela lei aplicavel, mas continuam responsaveis por avaliar precisao, adequacao e direitos de uso do conteudo gerado.
141
+
142
+ ## Citacao
143
+
144
+ ```bibtex
145
+ @dataset{madras1_corpus_ptbr_v2,
146
+ title = {Corpus PT-BR v2},
147
+ author = {Gabriel Yogi},
148
+ year = {2026},
149
+ publisher = {Hugging Face},
150
+ url = {https://huggingface.co/datasets/Madras1/corpus-ptbr-v2}
151
+ }
152
+ ```
153
+
154
+ ## Autor
155
+
156
+ Gabriel Yogi (MadrasLe) - Hugging Face
data/v2-synthetic-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34f15ad8c9f4c66d952d7d95d634f44f195056c2a86b3e8ab98219be427dbb87
3
+ size 421327562
data/v2-synthetic-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17b5dcc6df907b86ef0b47f31d8b84bc33e06839f9bdba08239d2f0e651468a1
3
+ size 424618319
data/v2-synthetic-00002.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc4516bfcc4911ed1cdc13d0a6cd3e9c06f0e412c3f3ffe1ec7155d049312ddf
3
+ size 484016248
data/v2-synthetic-00003.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfa44107b16895397e3a6665213939be081f1b8417031f0939e51322c0eba617
3
+ size 315068755
manifests/v2_synthetic_addition_manifest.json ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "created_at": "2026-05-24T18:36:21.998022+00:00",
3
+ "input_dir": "CORPUS",
4
+ "output_dir": "corpus-ptbr-v2/data",
5
+ "schema": [
6
+ {
7
+ "name": "text",
8
+ "type": "string"
9
+ },
10
+ {
11
+ "name": "source",
12
+ "type": "string"
13
+ },
14
+ {
15
+ "name": "subset",
16
+ "type": "string"
17
+ },
18
+ {
19
+ "name": "word_count",
20
+ "type": "int32"
21
+ },
22
+ {
23
+ "name": "char_count",
24
+ "type": "int32"
25
+ },
26
+ {
27
+ "name": "language",
28
+ "type": "string"
29
+ }
30
+ ],
31
+ "settings": {
32
+ "rows_per_shard": 100000,
33
+ "min_words": 1,
34
+ "max_words": 0,
35
+ "limit": 0,
36
+ "compression": "zstd",
37
+ "dedupe_exact_text": true
38
+ },
39
+ "counts": {
40
+ "jsonl_files": 35,
41
+ "records_seen": 371002,
42
+ "records_written": 371002,
43
+ "records_skipped_empty": 0,
44
+ "records_skipped_parse_error": 0,
45
+ "records_skipped_duplicate_text": 0,
46
+ "records_skipped_too_short": 0,
47
+ "records_skipped_too_long": 0,
48
+ "total_words": 590143768,
49
+ "total_chars": 4002358291,
50
+ "approx_tokens_1_3x_words": 767186898
51
+ },
52
+ "provider_counts": {
53
+ "mistral": 362596,
54
+ "openrouter": 8406
55
+ },
56
+ "model_counts": {
57
+ "mistral-small-latest": 288189,
58
+ "mistral-medium-latest": 74407,
59
+ "nvidia/nemotron-3-super-120b-a12b:free": 8406
60
+ },
61
+ "source_counts": {
62
+ "v2_synthetic_mistral_small_latest": 288189,
63
+ "v2_synthetic_mistral_medium_latest": 74407,
64
+ "v2_synthetic_openrouter_nvidia_nemotron_3_super_120b_a12b_free": 8406
65
+ },
66
+ "file_counts": {
67
+ "corpus11 (2).jsonl": 25985,
68
+ "cropus10 (1).jsonl": 25985,
69
+ "corpus11 (1).jsonl": 24984,
70
+ "corpus13.jsonl": 24982,
71
+ "cropus10 (2).jsonl": 21775,
72
+ "corpus8.jsonl": 19194,
73
+ "corpus20 (2).jsonl": 15983,
74
+ "corpus18 (1).jsonl": 15930,
75
+ "corpus18 (2).jsonl": 15891,
76
+ "corpus15 (1).jsonl": 14992,
77
+ "corpus15 (2).jsonl": 14992,
78
+ "corpus3.jsonl": 14933,
79
+ "corpus19.jsonl": 11769,
80
+ "corpus9.jsonl": 11721,
81
+ "corpus6.jsonl": 10568,
82
+ "corpus12.jsonl": 10453,
83
+ "corpus5.jsonl": 10019,
84
+ "corpus4.jsonl": 8266,
85
+ "corpus7 (2).jsonl": 7990,
86
+ "corpus16.jsonl": 7498,
87
+ "corpus17 (1).jsonl": 6874,
88
+ "corpus17 (2).jsonl": 6729,
89
+ "corpus (2).jsonl": 6231,
90
+ "corpus1.jsonl": 6202,
91
+ "corpus7 (1).jsonl": 6015,
92
+ "vl1.jsonl": 5997,
93
+ "corpus20 (1).jsonl": 5621,
94
+ "synthetic_corpus_mistral_single.jsonl": 5017,
95
+ "corpus21.jsonl": 1434,
96
+ "synthetic_corpus_openrouter_single.jsonl": 1348,
97
+ "corpus11.jsonl": 1225,
98
+ "corpus14.jsonl": 1203,
99
+ "opencorpus1.jsonl": 1130,
100
+ "synthetic_corpus_openrouter_single (1).jsonl": 1038,
101
+ "corpus (1).jsonl": 1028
102
+ },
103
+ "shards": [
104
+ {
105
+ "path": "corpus-ptbr-v2/data/v2-synthetic-00000.parquet",
106
+ "rows": 100000,
107
+ "bytes": 421327562
108
+ },
109
+ {
110
+ "path": "corpus-ptbr-v2/data/v2-synthetic-00001.parquet",
111
+ "rows": 100000,
112
+ "bytes": 424618319
113
+ },
114
+ {
115
+ "path": "corpus-ptbr-v2/data/v2-synthetic-00002.parquet",
116
+ "rows": 100000,
117
+ "bytes": 484016248
118
+ },
119
+ {
120
+ "path": "corpus-ptbr-v2/data/v2-synthetic-00003.parquet",
121
+ "rows": 71002,
122
+ "bytes": 315068755
123
+ }
124
+ ]
125
+ }
scripts/prepare_v2_synthetic_parquet.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import re
7
+ from collections import Counter
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import pyarrow as pa
13
+ import pyarrow.parquet as pq
14
+
15
+
16
+ DEFAULT_INPUT_DIR = Path("CORPUS")
17
+ DEFAULT_OUTPUT_DIR = Path("corpus-ptbr-v2/data")
18
+ DEFAULT_MANIFEST = Path("corpus-ptbr-v2/manifests/v2_synthetic_addition_manifest.json")
19
+
20
+ SCHEMA = pa.schema(
21
+ [
22
+ ("text", pa.string()),
23
+ ("source", pa.string()),
24
+ ("subset", pa.string()),
25
+ ("word_count", pa.int32()),
26
+ ("char_count", pa.int32()),
27
+ ("language", pa.string()),
28
+ ]
29
+ )
30
+
31
+
32
+ def parse_args() -> argparse.Namespace:
33
+ parser = argparse.ArgumentParser(
34
+ description="Convert local synthetic JSONL corpus files into v1-compatible Parquet shards for corpus-ptbr-v2."
35
+ )
36
+ parser.add_argument("--input-dir", type=Path, default=DEFAULT_INPUT_DIR)
37
+ parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
38
+ parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)
39
+ parser.add_argument("--rows-per-shard", type=int, default=100_000)
40
+ parser.add_argument("--min-words", type=int, default=1)
41
+ parser.add_argument("--max-words", type=int, default=0, help="0 means no upper limit.")
42
+ parser.add_argument("--limit", type=int, default=0, help="0 means no limit.")
43
+ parser.add_argument("--compression", default="zstd")
44
+ parser.add_argument("--basename", default="v2-synthetic")
45
+ parser.add_argument("--overwrite", action="store_true")
46
+ parser.add_argument("--no-dedupe", action="store_true")
47
+ return parser.parse_args()
48
+
49
+
50
+ def normalize_slug(value: str) -> str:
51
+ value = value.strip().lower()
52
+ value = value.replace("/", "_").replace(":", "_")
53
+ value = re.sub(r"[^a-z0-9]+", "_", value)
54
+ value = re.sub(r"_+", "_", value).strip("_")
55
+ return value or "unknown"
56
+
57
+
58
+ def source_from_metadata(provider: Any, model: Any) -> str:
59
+ provider_slug = normalize_slug(str(provider or "unknown"))
60
+ model_slug = normalize_slug(str(model or "unknown"))
61
+ if provider_slug == "mistral" and model_slug.startswith("mistral_"):
62
+ return f"v2_synthetic_{model_slug}"
63
+ return f"v2_synthetic_{provider_slug}_{model_slug}"
64
+
65
+
66
+ def safe_int(value: Any, fallback: int) -> int:
67
+ try:
68
+ return int(value)
69
+ except (TypeError, ValueError):
70
+ return fallback
71
+
72
+
73
+ def iter_jsonl_files(input_dir: Path) -> list[Path]:
74
+ return sorted(path for path in input_dir.rglob("*.jsonl") if path.is_file())
75
+
76
+
77
+ def write_shard(
78
+ rows: list[dict[str, Any]],
79
+ output_dir: Path,
80
+ basename: str,
81
+ shard_idx: int,
82
+ compression: str,
83
+ ) -> dict[str, Any]:
84
+ table = pa.Table.from_pylist(rows, schema=SCHEMA)
85
+ output_path = output_dir / f"{basename}-{shard_idx:05d}.parquet"
86
+ pq.write_table(
87
+ table,
88
+ output_path,
89
+ compression=compression,
90
+ row_group_size=min(len(rows), 10_000),
91
+ )
92
+ return {
93
+ "path": output_path.as_posix(),
94
+ "rows": len(rows),
95
+ "bytes": output_path.stat().st_size,
96
+ }
97
+
98
+
99
+ def main() -> None:
100
+ args = parse_args()
101
+
102
+ if args.rows_per_shard <= 0:
103
+ raise ValueError("--rows-per-shard must be positive.")
104
+ if not args.input_dir.exists():
105
+ raise FileNotFoundError(f"Input directory not found: {args.input_dir}")
106
+
107
+ args.output_dir.mkdir(parents=True, exist_ok=True)
108
+ args.manifest.parent.mkdir(parents=True, exist_ok=True)
109
+
110
+ existing = sorted(args.output_dir.glob(f"{args.basename}-*.parquet"))
111
+ if existing and not args.overwrite:
112
+ raise FileExistsError(
113
+ f"Found existing shards in {args.output_dir}. Use --overwrite to replace them."
114
+ )
115
+ if existing and args.overwrite:
116
+ for path in existing:
117
+ path.unlink()
118
+
119
+ files = iter_jsonl_files(args.input_dir)
120
+ rows: list[dict[str, Any]] = []
121
+ seen_text_hashes: set[str] = set()
122
+ shard_idx = 0
123
+ shard_infos: list[dict[str, Any]] = []
124
+
125
+ provider_counts: Counter[str] = Counter()
126
+ model_counts: Counter[str] = Counter()
127
+ source_counts: Counter[str] = Counter()
128
+ file_counts: Counter[str] = Counter()
129
+
130
+ total_records_seen = 0
131
+ total_records_written = 0
132
+ total_words = 0
133
+ total_chars = 0
134
+ skipped_empty = 0
135
+ skipped_parse_error = 0
136
+ skipped_duplicate = 0
137
+ skipped_too_short = 0
138
+ skipped_too_long = 0
139
+
140
+ for file_path in files:
141
+ with file_path.open("r", encoding="utf-8") as handle:
142
+ for line_number, line in enumerate(handle, start=1):
143
+ if args.limit and total_records_written >= args.limit:
144
+ break
145
+ if not line.strip():
146
+ continue
147
+
148
+ total_records_seen += 1
149
+ try:
150
+ obj = json.loads(line)
151
+ except json.JSONDecodeError:
152
+ skipped_parse_error += 1
153
+ continue
154
+
155
+ text = str(obj.get("text") or "").strip()
156
+ if not text:
157
+ skipped_empty += 1
158
+ continue
159
+
160
+ text_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
161
+ if not args.no_dedupe and text_hash in seen_text_hashes:
162
+ skipped_duplicate += 1
163
+ continue
164
+ seen_text_hashes.add(text_hash)
165
+
166
+ word_count = safe_int(obj.get("word_count"), len(text.split()))
167
+ char_count = safe_int(obj.get("char_count"), len(text))
168
+ if word_count < args.min_words:
169
+ skipped_too_short += 1
170
+ continue
171
+ if args.max_words and word_count > args.max_words:
172
+ skipped_too_long += 1
173
+ continue
174
+
175
+ provider = str(obj.get("provider") or "unknown")
176
+ model = str(obj.get("model") or "unknown")
177
+ source = source_from_metadata(provider, model)
178
+
179
+ rows.append(
180
+ {
181
+ "text": text,
182
+ "source": source,
183
+ "subset": "synthetic",
184
+ "word_count": word_count,
185
+ "char_count": char_count,
186
+ "language": "pt-br",
187
+ }
188
+ )
189
+
190
+ provider_counts[provider] += 1
191
+ model_counts[model] += 1
192
+ source_counts[source] += 1
193
+ file_counts[file_path.name] += 1
194
+ total_records_written += 1
195
+ total_words += word_count
196
+ total_chars += char_count
197
+
198
+ if len(rows) >= args.rows_per_shard:
199
+ shard_infos.append(
200
+ write_shard(rows, args.output_dir, args.basename, shard_idx, args.compression)
201
+ )
202
+ shard_idx += 1
203
+ rows = []
204
+
205
+ if args.limit and total_records_written >= args.limit:
206
+ break
207
+
208
+ if rows:
209
+ shard_infos.append(write_shard(rows, args.output_dir, args.basename, shard_idx, args.compression))
210
+
211
+ manifest = {
212
+ "created_at": datetime.now(timezone.utc).isoformat(),
213
+ "input_dir": args.input_dir.as_posix(),
214
+ "output_dir": args.output_dir.as_posix(),
215
+ "schema": [
216
+ {"name": field.name, "type": str(field.type)}
217
+ for field in SCHEMA
218
+ ],
219
+ "settings": {
220
+ "rows_per_shard": args.rows_per_shard,
221
+ "min_words": args.min_words,
222
+ "max_words": args.max_words,
223
+ "limit": args.limit,
224
+ "compression": args.compression,
225
+ "dedupe_exact_text": not args.no_dedupe,
226
+ },
227
+ "counts": {
228
+ "jsonl_files": len(files),
229
+ "records_seen": total_records_seen,
230
+ "records_written": total_records_written,
231
+ "records_skipped_empty": skipped_empty,
232
+ "records_skipped_parse_error": skipped_parse_error,
233
+ "records_skipped_duplicate_text": skipped_duplicate,
234
+ "records_skipped_too_short": skipped_too_short,
235
+ "records_skipped_too_long": skipped_too_long,
236
+ "total_words": total_words,
237
+ "total_chars": total_chars,
238
+ "approx_tokens_1_3x_words": int(total_words * 1.3),
239
+ },
240
+ "provider_counts": dict(provider_counts.most_common()),
241
+ "model_counts": dict(model_counts.most_common()),
242
+ "source_counts": dict(source_counts.most_common()),
243
+ "file_counts": dict(file_counts.most_common()),
244
+ "shards": shard_infos,
245
+ }
246
+
247
+ args.manifest.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
248
+
249
+ print("V2 synthetic Parquet preparation complete.")
250
+ print(f"Records written : {total_records_written}")
251
+ print(f"Shards written : {len(shard_infos)}")
252
+ print(f"Total words : {total_words}")
253
+ print(f"Approx tokens : {int(total_words * 1.3)}")
254
+ print(f"Manifest : {args.manifest}")
255
+
256
+
257
+ if __name__ == "__main__":
258
+ main()
scripts/upload_v2_after_duplicate.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from huggingface_hub import HfApi
8
+
9
+
10
+ def parse_args() -> argparse.Namespace:
11
+ parser = argparse.ArgumentParser(
12
+ description=(
13
+ "Upload the local corpus-ptbr-v2 package to a Hugging Face dataset repo. "
14
+ "Recommended flow: duplicate Madras1/corpus-ptbr-v1 to Madras1/corpus-ptbr-v2 first, "
15
+ "then run this script to replace README.md and add the v2 synthetic shards."
16
+ )
17
+ )
18
+ parser.add_argument("--repo-id", default="Madras1/corpus-ptbr-v2")
19
+ parser.add_argument("--folder", type=Path, default=Path("corpus-ptbr-v2"))
20
+ parser.add_argument("--create-repo", action="store_true")
21
+ parser.add_argument("--private", action="store_true")
22
+ parser.add_argument("--revision", default="main")
23
+ parser.add_argument("--commit-message", default="Add Corpus PT-BR v2 synthetic extension")
24
+ return parser.parse_args()
25
+
26
+
27
+ def main() -> None:
28
+ args = parse_args()
29
+ if not args.folder.exists():
30
+ raise FileNotFoundError(f"Folder not found: {args.folder}")
31
+ if not os.getenv("HF_TOKEN"):
32
+ print("Warning: HF_TOKEN is not set. The Hugging Face Hub client may use cached login credentials.")
33
+
34
+ api = HfApi()
35
+ if args.create_repo:
36
+ api.create_repo(
37
+ repo_id=args.repo_id,
38
+ repo_type="dataset",
39
+ private=args.private,
40
+ exist_ok=True,
41
+ )
42
+
43
+ api.upload_folder(
44
+ repo_id=args.repo_id,
45
+ repo_type="dataset",
46
+ folder_path=str(args.folder),
47
+ revision=args.revision,
48
+ commit_message=args.commit_message,
49
+ ignore_patterns=[
50
+ "scripts/__pycache__/*",
51
+ "test-output/*",
52
+ "*.tmp",
53
+ ],
54
+ )
55
+ print(f"Uploaded {args.folder} to dataset repo {args.repo_id}.")
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()