|
import os |
|
import logging |
|
import pyarrow as pa |
|
import pyarrow.parquet as pq |
|
from datasets import load_dataset |
|
|
|
|
|
logging.basicConfig( |
|
level=logging.INFO, |
|
format="%(asctime)s - %(levelname)s - %(message)s" |
|
) |
|
|
|
|
|
WORD_THRESHOLD = 4_000_000_000 |
|
|
|
|
|
def count_words(text: str) -> int: |
|
""" |
|
Conta a quantidade de palavras em `text` de forma eficiente, |
|
usando contagem de espaços para evitar alocações de lista. |
|
|
|
Args: |
|
text (str): Texto a ser analisado. |
|
|
|
Returns: |
|
int: Número de palavras. |
|
""" |
|
return text.count(" ") + 1 if text else 0 |
|
|
|
|
|
def process_and_write( |
|
dataset, |
|
output_folder: str, |
|
batch_size: int = 100_000 |
|
) -> None: |
|
""" |
|
Itera em um `IterableDataset` streaming registro a registro, agrupa em batches, |
|
conta palavras e escreve cada batch em um arquivo Parquet separado. |
|
Para evitar gerar arquivos além do limite, interrompe ao alcançar 1 bilhão de palavras. |
|
|
|
Args: |
|
dataset: HuggingFace streaming Dataset. |
|
output_folder (str): Diretório onde serão salvos os arquivos .parquet. |
|
batch_size (int): Número de registros por batch. |
|
""" |
|
|
|
os.makedirs(output_folder, exist_ok=True) |
|
|
|
batch_records = [] |
|
batch_idx = 0 |
|
cumulative_words = 0 |
|
stop_processing = False |
|
|
|
for record in dataset: |
|
batch_records.append(record) |
|
|
|
if len(batch_records) >= batch_size: |
|
batch_idx += 1 |
|
texts = [rec["text"] for rec in batch_records] |
|
word_counts = [count_words(t) for t in texts] |
|
batch_word_sum = sum(word_counts) |
|
|
|
table = pa.Table.from_pydict({ |
|
"text": texts, |
|
"word_count": word_counts, |
|
}) |
|
|
|
|
|
file_path = os.path.join(output_folder, f"batch_{batch_idx}.parquet") |
|
pq.write_table(table, file_path) |
|
cumulative_words += batch_word_sum |
|
logging.info( |
|
f"Batch {batch_idx} salvo em '{file_path}': " |
|
f"{len(texts)} registros, {batch_word_sum} palavras, total acumulado: {cumulative_words}" |
|
) |
|
|
|
|
|
if cumulative_words >= WORD_THRESHOLD: |
|
logging.info( |
|
f"Limite de {WORD_THRESHOLD} palavras atingido. " |
|
f"Parando processamento.") |
|
stop_processing = True |
|
break |
|
|
|
batch_records = [] |
|
|
|
|
|
if not stop_processing and batch_records: |
|
batch_idx += 1 |
|
texts = [rec["text"] for rec in batch_records] |
|
word_counts = [count_words(t) for t in texts] |
|
batch_word_sum = sum(word_counts) |
|
|
|
table = pa.Table.from_pydict({ |
|
"text": texts, |
|
"word_count": word_counts, |
|
}) |
|
|
|
file_path = os.path.join(output_folder, f"batch_{batch_idx}.parquet") |
|
pq.write_table(table, file_path) |
|
cumulative_words += batch_word_sum |
|
logging.info( |
|
f"Batch {batch_idx} (restante) salvo em '{file_path}': " |
|
f"{len(texts)} registros, {batch_word_sum} palavras, total acumulado: {cumulative_words}" |
|
) |
|
|
|
logging.info(f"Processamento finalizado. Total de batches: {batch_idx}, palavras totais: {cumulative_words}") |
|
|
|
|
|
def main() -> None: |
|
""" |
|
Ponto de entrada: carrega o dataset em streaming e chama o processamento. |
|
""" |
|
logging.info("Iniciando processamento e escrita de dados em streaming...") |
|
ds = load_dataset("Itau-Unibanco/aroeira", split="train", streaming=True) |
|
|
|
script_dir = os.path.dirname(os.path.abspath(__file__)) |
|
output_folder = os.path.join(script_dir, "data") |
|
|
|
process_and_write(ds, output_folder) |
|
logging.info("Processamento concluído com sucesso.") |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |
|
|