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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import polars as pl
|
| 3 |
+
import re
|
| 4 |
+
import argparse
|
| 5 |
+
import os
|
| 6 |
+
import logging
|
| 7 |
+
import hashlib
|
| 8 |
+
from blingfire import text_to_sentences
|
| 9 |
+
from lingua import Language, LanguageDetectorBuilder
|
| 10 |
+
import nltk
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# ===================================================================
|
| 14 |
+
# ========================== CONFIG =================================
|
| 15 |
+
# ===================================================================
|
| 16 |
+
|
| 17 |
+
EXPORT_SPLIT = False
|
| 18 |
+
EXPORT_CSV = False
|
| 19 |
+
|
| 20 |
+
ADD_ID = True
|
| 21 |
+
ADD_CATEGORY = True
|
| 22 |
+
ADD_SHA = True
|
| 23 |
+
REMOVE_DUPLICATES = True
|
| 24 |
+
|
| 25 |
+
ROW_LIMIT = 100_000_000
|
| 26 |
+
TEXT_COLUMN = "text"
|
| 27 |
+
|
| 28 |
+
LAST_ID_FILE = "last_id.txt" # contém o último ID processado
|
| 29 |
+
FILE_PATTERN = "train-"
|
| 30 |
+
CLEAN_SUFFIX = "_clean_full.parquet"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ===================================================================
|
| 34 |
+
# ====================== NLTK RESOURCES ===============================
|
| 35 |
+
# ===================================================================
|
| 36 |
+
|
| 37 |
+
def ensure_nltk():
|
| 38 |
+
required = ["punkt", "punkt_tab"]
|
| 39 |
+
for r in required:
|
| 40 |
+
try:
|
| 41 |
+
nltk.data.find(f"tokenizers/{r}")
|
| 42 |
+
except LookupError:
|
| 43 |
+
nltk.download(r, quiet=True)
|
| 44 |
+
ensure_nltk()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# ===================================================================
|
| 48 |
+
# ========================= CLASSIFICAÇÃO =============================
|
| 49 |
+
# ===================================================================
|
| 50 |
+
|
| 51 |
+
INSTRUCT_PREFIX = re.compile(
|
| 52 |
+
r"^(escreva|explique|resuma|liste|crie|gere|monte|defina|descreva|faça|produza|formule|por favor.*(explique|resuma|liste))",
|
| 53 |
+
re.IGNORECASE
|
| 54 |
+
)
|
| 55 |
+
QUESTION_PATTERN = re.compile(
|
| 56 |
+
r"\?$|^(quem|o que|qual|quando|por que|como)\b",
|
| 57 |
+
re.IGNORECASE
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def is_factual(text: str):
|
| 61 |
+
if not isinstance(text, str):
|
| 62 |
+
return False
|
| 63 |
+
return (
|
| 64 |
+
len(text.split()) > 40
|
| 65 |
+
and not INSTRUCT_PREFIX.search(text)
|
| 66 |
+
and not QUESTION_PATTERN.search(text)
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
def classify_text(text: str):
|
| 70 |
+
if not isinstance(text, str):
|
| 71 |
+
return "other"
|
| 72 |
+
t = text.strip()
|
| 73 |
+
if INSTRUCT_PREFIX.search(t):
|
| 74 |
+
return "instruct"
|
| 75 |
+
if QUESTION_PATTERN.search(t):
|
| 76 |
+
return "question"
|
| 77 |
+
if is_factual(t):
|
| 78 |
+
return "factual"
|
| 79 |
+
return "other"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ===================================================================
|
| 83 |
+
# ========================== IDIOMA ==================================
|
| 84 |
+
# ===================================================================
|
| 85 |
+
|
| 86 |
+
DETECTOR = (
|
| 87 |
+
LanguageDetectorBuilder
|
| 88 |
+
.from_languages(Language.PORTUGUESE, Language.ENGLISH, Language.SPANISH)
|
| 89 |
+
.with_preloaded_language_models()
|
| 90 |
+
.build()
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def is_portuguese(text: str) -> bool:
|
| 94 |
+
if not isinstance(text, str) or len(text) < 20:
|
| 95 |
+
return False
|
| 96 |
+
try:
|
| 97 |
+
lang = DETECTOR.detect_language_of(text)
|
| 98 |
+
conf = DETECTOR.compute_language_confidence(text, lang)
|
| 99 |
+
return lang == Language.PORTUGUESE and conf >= 0.80
|
| 100 |
+
except:
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# ===================================================================
|
| 105 |
+
# ========================= REGEX / LIMPEZA ===========================
|
| 106 |
+
# ===================================================================
|
| 107 |
+
|
| 108 |
+
PORN = re.compile(r"pelad|sexo|porn|novinha|xvideos|boquete|anal ", re.IGNORECASE)
|
| 109 |
+
CODE = re.compile(r"function\s*\(|</?script|var\s+|document\.write", re.IGNORECASE)
|
| 110 |
+
SPAM = re.compile(r"bet365|promo|cadastre-se|inscreva|orçamento|ligue ", re.IGNORECASE)
|
| 111 |
+
META = re.compile(r"visualizado|publicado em|conteúdo recente|mostra idioma", re.IGNORECASE)
|
| 112 |
+
|
| 113 |
+
PATTERNS = [PORN, CODE, SPAM, META]
|
| 114 |
+
|
| 115 |
+
CPF = re.compile(r"\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b")
|
| 116 |
+
RG = re.compile(r"\b\d{2}\.?\d{3}\.?\d{3}-?[A-Za-z0-9]{1,2}\b")
|
| 117 |
+
PHONE = re.compile(r"\b(\(?\d{2}\)?\s?)?\d{4,5}-?\d{4}\b")
|
| 118 |
+
EMAIL = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
|
| 119 |
+
URL = re.compile(r"https?://\S+|www\.\S+|\b\S+\.(com|net|org|gov|edu)\b")
|
| 120 |
+
|
| 121 |
+
HEADINGS = re.compile(
|
| 122 |
+
r"^(Categoria:|Veja também:|Leia mais:|Últimas notícias:|Para saber mais:|Este artigo|Esta categoria)",
|
| 123 |
+
re.IGNORECASE
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def remove_personal(text):
|
| 127 |
+
text = CPF.sub("", text)
|
| 128 |
+
text = RG.sub("", text)
|
| 129 |
+
text = PHONE.sub("", text)
|
| 130 |
+
text = EMAIL.sub("", text)
|
| 131 |
+
text = URL.sub("", text)
|
| 132 |
+
return text
|
| 133 |
+
|
| 134 |
+
def remove_patterns_func(text):
|
| 135 |
+
if not isinstance(text, str):
|
| 136 |
+
return None
|
| 137 |
+
for p in PATTERNS:
|
| 138 |
+
if p.search(text):
|
| 139 |
+
return None
|
| 140 |
+
return text
|
| 141 |
+
|
| 142 |
+
def remove_headings_func(text):
|
| 143 |
+
return None if HEADINGS.search(text) else text
|
| 144 |
+
|
| 145 |
+
def normalize(text):
|
| 146 |
+
if not isinstance(text, str):
|
| 147 |
+
return None
|
| 148 |
+
text = re.sub(r'^[\s\u00A0\u1680\u180E\u2000-\u200A\u202F\u205F\u3000]+', '', text)
|
| 149 |
+
text = remove_personal(text)
|
| 150 |
+
if remove_headings_func(text) is None:
|
| 151 |
+
return None
|
| 152 |
+
text = re.sub(r'\s+', ' ', text)
|
| 153 |
+
text = re.sub(r'[^\w\s.,!?()\-–]', '', text)
|
| 154 |
+
text = text.strip()
|
| 155 |
+
return text if len(text) >= 25 else None
|
| 156 |
+
|
| 157 |
+
def remove_truncated(text):
|
| 158 |
+
if not isinstance(text, str):
|
| 159 |
+
return None
|
| 160 |
+
if re.match(r"pr[oó]s:|contras:|leia mais|clique|assine", text.lower()):
|
| 161 |
+
return None
|
| 162 |
+
return text
|
| 163 |
+
|
| 164 |
+
def split_sentences(text):
|
| 165 |
+
raw = text_to_sentences(text)
|
| 166 |
+
return [s.strip() for s in raw.split("\n") if len(s.strip()) > 25]
|
| 167 |
+
|
| 168 |
+
def compute_sha(text: str):
|
| 169 |
+
if not isinstance(text, str):
|
| 170 |
+
return None
|
| 171 |
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# ===================================================================
|
| 175 |
+
# ====================== ID MANAGEMENT ================================
|
| 176 |
+
# ===================================================================
|
| 177 |
+
|
| 178 |
+
def load_last_id():
|
| 179 |
+
if not os.path.exists(LAST_ID_FILE):
|
| 180 |
+
with open(LAST_ID_FILE, "w") as f:
|
| 181 |
+
f.write("0")
|
| 182 |
+
return 0
|
| 183 |
+
|
| 184 |
+
with open(LAST_ID_FILE, "r") as f:
|
| 185 |
+
try:
|
| 186 |
+
return int(f.read().strip())
|
| 187 |
+
except:
|
| 188 |
+
return 0
|
| 189 |
+
|
| 190 |
+
def save_last_id(value):
|
| 191 |
+
with open(LAST_ID_FILE, "w") as f:
|
| 192 |
+
f.write(str(value))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# ===================================================================
|
| 196 |
+
# ======================= PROCESSAR UM ARQUIVO ========================
|
| 197 |
+
# ===================================================================
|
| 198 |
+
|
| 199 |
+
def process_file(filepath, id_start):
|
| 200 |
+
|
| 201 |
+
filename = os.path.basename(filepath)
|
| 202 |
+
base = os.path.splitext(filename)[0]
|
| 203 |
+
|
| 204 |
+
# =============== Logger individual por arquivo ===================
|
| 205 |
+
log_name = f"{base}_clean.log"
|
| 206 |
+
|
| 207 |
+
logger = logging.getLogger(base)
|
| 208 |
+
logger.setLevel(logging.INFO)
|
| 209 |
+
|
| 210 |
+
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
| 211 |
+
|
| 212 |
+
fh = logging.FileHandler(log_name, encoding="utf-8")
|
| 213 |
+
fh.setFormatter(fmt)
|
| 214 |
+
fh.setLevel(logging.INFO)
|
| 215 |
+
|
| 216 |
+
sh = logging.StreamHandler()
|
| 217 |
+
sh.setFormatter(fmt)
|
| 218 |
+
sh.setLevel(logging.INFO)
|
| 219 |
+
|
| 220 |
+
if logger.hasHandlers():
|
| 221 |
+
logger.handlers.clear()
|
| 222 |
+
|
| 223 |
+
logger.addHandler(fh)
|
| 224 |
+
logger.addHandler(sh)
|
| 225 |
+
|
| 226 |
+
# ================================================================
|
| 227 |
+
logger.info("\n====================================================")
|
| 228 |
+
logger.info(f"📦 Processando arquivo: {filename}")
|
| 229 |
+
logger.info(f"📍 ID inicial: {id_start}")
|
| 230 |
+
logger.info("====================================================")
|
| 231 |
+
|
| 232 |
+
df = pl.read_parquet(filepath)
|
| 233 |
+
|
| 234 |
+
if ROW_LIMIT > 0:
|
| 235 |
+
df = df.head(ROW_LIMIT)
|
| 236 |
+
|
| 237 |
+
if TEXT_COLUMN not in df.columns:
|
| 238 |
+
logger.error(f"❌ Arquivo {filename} sem coluna 'text'. Ignorando.")
|
| 239 |
+
return id_start
|
| 240 |
+
|
| 241 |
+
# ======================= CRIAR IDS ==============================
|
| 242 |
+
if ADD_ID:
|
| 243 |
+
new_ids = list(range(id_start, id_start + df.height))
|
| 244 |
+
df = df.with_columns(pl.Series("id", new_ids))
|
| 245 |
+
cols = ["id"] + [c for c in df.columns if c != "id"]
|
| 246 |
+
df = df.select(cols)
|
| 247 |
+
|
| 248 |
+
logger.info(f"🆔 ID intervalo: {new_ids[0]} → {new_ids[-1]}")
|
| 249 |
+
|
| 250 |
+
removals = {
|
| 251 |
+
"remove_patterns": [],
|
| 252 |
+
"remove_lang": [],
|
| 253 |
+
"remove_normalize": [],
|
| 254 |
+
"remove_truncated": [],
|
| 255 |
+
"remove_duplicates_sha": []
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
def track(stage, old, new):
|
| 259 |
+
old_ids = set(old["id"])
|
| 260 |
+
new_ids = set(new["id"])
|
| 261 |
+
removed = sorted(list(old_ids - new_ids))
|
| 262 |
+
removals[stage].extend(removed)
|
| 263 |
+
logger.info(f"🗑️ {stage}: {len(removed)} removidos → {removed}")
|
| 264 |
+
|
| 265 |
+
# ==================== 1) PATTERNS ==============================
|
| 266 |
+
old = df
|
| 267 |
+
df = df.with_columns(pl.col(TEXT_COLUMN).map_elements(remove_patterns_func))
|
| 268 |
+
df = df.drop_nulls(subset=[TEXT_COLUMN])
|
| 269 |
+
track("remove_patterns", old, df)
|
| 270 |
+
|
| 271 |
+
# ==================== 2) Língua ================================
|
| 272 |
+
old = df
|
| 273 |
+
df = df.with_columns(pl.col(TEXT_COLUMN).map_elements(lambda x: x if is_portuguese(x) else None))
|
| 274 |
+
df = df.drop_nulls(subset=[TEXT_COLUMN])
|
| 275 |
+
track("remove_lang", old, df)
|
| 276 |
+
|
| 277 |
+
# ==================== 3) Normalize =============================
|
| 278 |
+
old = df
|
| 279 |
+
df = df.with_columns(pl.col(TEXT_COLUMN).map_elements(normalize))
|
| 280 |
+
df = df.drop_nulls(subset=[TEXT_COLUMN])
|
| 281 |
+
track("remove_normalize", old, df)
|
| 282 |
+
|
| 283 |
+
# ==================== 4) Truncated =============================
|
| 284 |
+
old = df
|
| 285 |
+
df = df.with_columns(pl.col(TEXT_COLUMN).map_elements(remove_truncated))
|
| 286 |
+
df = df.drop_nulls(subset=[TEXT_COLUMN])
|
| 287 |
+
track("remove_truncated", old, df)
|
| 288 |
+
|
| 289 |
+
# ==================== 5) SHA ==================================
|
| 290 |
+
if ADD_SHA:
|
| 291 |
+
df = df.with_columns(pl.col(TEXT_COLUMN).map_elements(compute_sha).alias("sha"))
|
| 292 |
+
|
| 293 |
+
# ==================== 6) Duplicados SHA ========================
|
| 294 |
+
if ADD_SHA and REMOVE_DUPLICATES:
|
| 295 |
+
old = df
|
| 296 |
+
df = df.unique(subset=["sha"])
|
| 297 |
+
track("remove_duplicates_sha", old, df)
|
| 298 |
+
|
| 299 |
+
# ==================== 7) CATEGORIA =============================
|
| 300 |
+
if ADD_CATEGORY:
|
| 301 |
+
df = df.with_columns(
|
| 302 |
+
pl.col(TEXT_COLUMN).map_elements(classify_text).alias("category")
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
df = df.sort("id")
|
| 306 |
+
|
| 307 |
+
# ==================== Salvar FULL ==============================
|
| 308 |
+
output_name = f"{base}{CLEAN_SUFFIX}"
|
| 309 |
+
df.write_parquet(output_name)
|
| 310 |
+
|
| 311 |
+
logger.info(f"💾 Salvo: {output_name}")
|
| 312 |
+
|
| 313 |
+
# ==================== Atualizar last_id ========================
|
| 314 |
+
final_last_id = df["id"].max()
|
| 315 |
+
logger.info(f"🔢 Último ID deste arquivo: {final_last_id}")
|
| 316 |
+
|
| 317 |
+
return final_last_id + 1
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
# ===================================================================
|
| 321 |
+
# =============================== MAIN ===============================
|
| 322 |
+
# ===================================================================
|
| 323 |
+
|
| 324 |
+
def main():
|
| 325 |
+
|
| 326 |
+
last_id = load_last_id()
|
| 327 |
+
next_id = last_id + 1
|
| 328 |
+
|
| 329 |
+
# listar arquivos
|
| 330 |
+
files = [
|
| 331 |
+
f for f in os.listdir(".")
|
| 332 |
+
if f.startswith(FILE_PATTERN) and f.endswith(".parquet")
|
| 333 |
+
]
|
| 334 |
+
|
| 335 |
+
if not files:
|
| 336 |
+
print("❌ Nenhum parquet encontrado.")
|
| 337 |
+
return
|
| 338 |
+
|
| 339 |
+
# ordenar numericamente
|
| 340 |
+
def extract_num(fname):
|
| 341 |
+
try:
|
| 342 |
+
return int(fname.split("-")[1])
|
| 343 |
+
except:
|
| 344 |
+
return 0
|
| 345 |
+
|
| 346 |
+
files = sorted(files, key=extract_num)
|
| 347 |
+
|
| 348 |
+
print(f"📚 Arquivos encontrados: {files}")
|
| 349 |
+
print(f"🔢 last_id carregado: {last_id}")
|
| 350 |
+
|
| 351 |
+
for file in files:
|
| 352 |
+
final_id_next = process_file(file, next_id)
|
| 353 |
+
next_id = final_id_next
|
| 354 |
+
save_last_id(final_id_next - 1)
|
| 355 |
+
|
| 356 |
+
print("\n==================== FINALIZADO (v76) ====================")
|
| 357 |
+
print(f"🔢 Novo last_id salvo: {next_id - 1}")
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
if __name__ == "__main__":
|
| 361 |
+
main()
|