// MHarr AI Sort (formerly HAPPID) - web text filter for AI training data. Single-file C++ edition. // Copyright (c) 2026 Michael Hugh Harrington. All rights reserved. // Patent Pending: U.S. Provisional Patent Application No. 64/205,973, filed 24 November 2026. // Allowed for testing, verification, and peer review. No other rights are granted. // Line-type sort (Harrington's Sets), cascade junk screen, Line 0 guard, anchor-line duplicate finder. // Build: g++ -O2 -std=c++17 -pthread -o mharr_ai_sort mharr_ai_sort.cpp -lz // Usage: mharr_ai_sort wet_dir out_dir threads (wet_dir = Common Crawl .warc.wet.gz files) #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include typedef std::u32string U32; typedef std::u32string_view V32; // ---- character classes and lower-case map, same as Python str methods (zlib+base64 table, built once at start) static const char *TAB = "eNp9VmuIXVcV3mudc+7dZ91znzOZ98ydJNN5v5xJ05fobdMm1JZxQIxUUBLEZwtaWgURtKmNg4/4Q9IWShmHWNMhbSWtpTqKONpKsVqNqPlpq+IDDC0+EUTit9bZc2emlv7YZ++z99rr+a21duoSqmBUnWRF1ycFDHFEfRipIyk69oQ5cuRJyEX468bcxHghkthlgusg00OSE4QfcizsYtso2EFka3KdGO/A+CKJd2d1ZxSUSjUhR1w/2MUy46ZkD7SJwYXc++xmFWtoIpJFRl8zbkMy6G6TEtYV0O+VFBQx/hLXZXOa6y3drhe3S9jvwa2C1N2kXOsO2lnDbBTQS0auhtlDgurfBdqi5LbHRqtSy6ZVZPRKVfCqjwfXeNctbo9m8ERRb+BmzaXBIztpk7Y2VbNCMtW+9H/abNMO7dDEPO1L5pUCTpW76szB72xr3Y8QsC7sqYcj3wD/XBeNac349rncxxz08K5oCIh30Upbj2awM9eD4d0t+ybasUrsv+hzbVOvWiaugfsakdS0ZNjXxGndzRu/DP8p/sfaViiyesJajCa1e4ntpebfWIZNJ8nEZ6bxiPSD4i6gqhMnkhUsVnlEI8OValWGPOOL81HjlxjvKaxfZHMnBzjk64kw732dsyrma8L6EMDZ6SM4t+aOKmAg9JIe1AV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GUuYG5ifvwbhIx4KR2n5fM0QsubVKKlrEpLtSIteaalS+VFwGCtB5Fde4zw3fwn7aMb/wfbihO8"; static uint8_t FL[0x110000]; static char32_t LOWT[0x110000]; enum { SP = 1, AL = 2, DE = 4, AN = 8 }; static void init_lower() { std::vector z; int v = 0, b = 0; const char *A = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (const char *p = TAB; *p; p++) { const char *q = strchr(A, *p); if (!q || *p == '=') continue; v = (v << 6 | (int)(q - A)) & 0xFFFFFF; b += 6; if (b >= 8) { b -= 8; z.push_back((uint8_t)(v >> b)); } } std::vector o(8192); uLongf ol = o.size(); uncompress(o.data(), &ol, z.data(), z.size()); size_t i = 0; auto vi = [&]() { uint64_t n = 0; int sh = 0; while (o[i] & 128) { n |= (uint64_t)(o[i++] & 127) << sh; sh += 7; } n |= (uint64_t)o[i++] << sh; return n; }; uint32_t c = 0; for (int k = 0; k < 1572; k++) { uint32_t len = (uint32_t)vi(); uint8_t f = o[i++]; for (uint32_t j = 0; j < len; j++) FL[c++] = f; } for (uint32_t k = 0; k < 0x110000; k++) LOWT[k] = k; c = 0; for (int k = 0; k < 181; k++) { c += (uint32_t)vi(); uint32_t cnt = (uint32_t)vi(); uint8_t stp = o[i++]; uint64_t e = vi(); int64_t d = (e & 1) ? -(int64_t)(e >> 1) : (int64_t)(e >> 1); for (uint32_t j = 0; j < cnt; j++) LOWT[c + j * stp] = (char32_t)((int64_t)(c + j * stp) + d); } } static inline uint8_t cflags(char32_t c) { return c < 0x110000 ? FL[c] : 0; } static inline bool is_space(char32_t c) { return c < 128 ? (c == ' ' || (c >= 9 && c <= 13) || (c >= 28 && c <= 31)) : (cflags(c) & SP); } static inline bool is_alpha(char32_t c) { return c < 128 ? ((c | 32) >= 'a' && (c | 32) <= 'z') : (cflags(c) & AL); } static inline bool is_dec(char32_t c) { return c < 128 ? (c >= '0' && c <= '9') : (cflags(c) & DE); } static inline bool is_alnum(char32_t c) { return c < 128 ? (((c | 32) >= 'a' && (c | 32) <= 'z') || (c >= '0' && c <= '9')) : (cflags(c) & AN); } static inline bool is_word(char32_t c) { return c == '_' || is_alnum(c); } static inline bool is_letterrun(char32_t c) { return c != '_' && is_alnum(c) && !is_dec(c); } // [^\W\d_] static void lower_into(V32 s, U32 &out) { out.clear(); out.reserve(s.size()); for (char32_t c : s) { if (c < 128) out.push_back((c >= 'A' && c <= 'Z') ? c + 32 : c); else if (c == 0x130) { out.push_back('i'); out.push_back(0x307); } else out.push_back(c < 0x110000 ? LOWT[c] : c); } } // UTF-8 (decode with replacement, like Python errors="replace") static size_t utf8_decode(const char *p, size_t n, U32 &out, size_t maxcp = SIZE_MAX) { out.clear(); out.reserve(std::min(n, maxcp)); const unsigned char *s = (const unsigned char *)p; size_t i = 0; while (i < n && out.size() < maxcp) { unsigned c = s[i]; if (c < 0x80) { // run of plain ASCII size_t rem = maxcp - out.size(), j = i, lim = rem >= n - i ? n : i + rem; while (j < lim && s[j] < 0x80) j++; size_t at = out.size(); out.resize(at + (j - i)); char32_t *o = &out[at]; for (size_t k = i; k < j; k++) *o++ = s[k]; i = j; continue; } int need; unsigned cp, lo = 0x80, hi = 0xBF; if (c >= 0xC2 && c <= 0xDF) { need = 1; cp = c & 0x1F; } else if (c >= 0xE0 && c <= 0xEF) { need = 2; cp = c & 0x0F; if (c == 0xE0) lo = 0xA0; if (c == 0xED) hi = 0x9F; } else if (c >= 0xF0 && c <= 0xF4) { need = 3; cp = c & 0x07; if (c == 0xF0) lo = 0x90; if (c == 0xF4) hi = 0x8F; } else { out.push_back(0xFFFD); i++; continue; } size_t j = i + 1; bool ok = true; for (int k = 0; k < need; k++, j++) { unsigned b = j < n ? s[j] : 0x100; unsigned l = k == 0 ? lo : 0x80, h = k == 0 ? hi : 0xBF; if (b < l || b > h) { ok = false; break; } cp = (cp << 6) | (b & 0x3F); } if (ok) { out.push_back(cp); i = j; } else { out.push_back(0xFFFD); i = j; } } return i; } static void utf8_append(char32_t c, std::string &o) { if (c < 0x80) o.push_back((char)c); else if (c < 0x800) { o.push_back((char)(0xC0 | (c >> 6))); o.push_back((char)(0x80 | (c & 0x3F))); } else if (c < 0x10000) { o.push_back((char)(0xE0 | (c >> 12))); o.push_back((char)(0x80 | ((c >> 6) & 0x3F))); o.push_back((char)(0x80 | (c & 0x3F))); } else { o.push_back((char)(0xF0 | (c >> 18))); o.push_back((char)(0x80 | ((c >> 12) & 0x3F))); o.push_back((char)(0x80 | ((c >> 6) & 0x3F))); o.push_back((char)(0x80 | (c & 0x3F))); } } static std::string utf8(V32 s) { std::string o; o.reserve(s.size()); for (char32_t c : s) utf8_append(c, o); return o; } // BLAKE2b, 8-byte digest (same as hashlib.blake2b(digest_size=8)) static const uint64_t B2IV[8] = {0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL}; static const uint8_t B2S[12][16] = {{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},{14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3}, {11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4},{7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8},{9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13}, {2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9},{12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11},{13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10}, {6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5},{10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0},{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}, {14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3}}; static inline uint64_t rotr(uint64_t x, int n) { return (x >> n) | (x << (64 - n)); } static void b2compress(uint64_t h[8], const uint8_t *blk, uint64_t t, bool last) { uint64_t m[16], v[16]; for (int i = 0; i < 16; i++) { uint64_t x = 0; for (int b = 7; b >= 0; b--) x = (x << 8) | blk[i * 8 + b]; m[i] = x; } for (int i = 0; i < 8; i++) { v[i] = h[i]; v[i + 8] = B2IV[i]; } v[12] ^= t; if (last) v[14] = ~v[14]; #define G(a, b, c, d, x, y) a = a + b + x; d = rotr(d ^ a, 32); c = c + d; b = rotr(b ^ c, 24); a = a + b + y; d = rotr(d ^ a, 16); c = c + d; b = rotr(b ^ c, 63); for (int r = 0; r < 12; r++) { const uint8_t *s = B2S[r]; G(v[0], v[4], v[8], v[12], m[s[0]], m[s[1]]) G(v[1], v[5], v[9], v[13], m[s[2]], m[s[3]]) G(v[2], v[6], v[10], v[14], m[s[4]], m[s[5]]) G(v[3], v[7], v[11], v[15], m[s[6]], m[s[7]]) G(v[0], v[5], v[10], v[15], m[s[8]], m[s[9]]) G(v[1], v[6], v[11], v[12], m[s[10]], m[s[11]]) G(v[2], v[7], v[8], v[13], m[s[12]], m[s[13]]) G(v[3], v[4], v[9], v[14], m[s[14]], m[s[15]]) } #undef G for (int i = 0; i < 8; i++) h[i] ^= v[i] ^ v[i + 8]; } static uint64_t h8(const std::string &s) { uint64_t h[8]; for (int i = 0; i < 8; i++) h[i] = B2IV[i]; h[0] ^= 0x01010000ULL ^ 8; // digest length 8, no key, fanout 1, depth 1 const uint8_t *p = (const uint8_t *)s.data(); size_t n = s.size(), off = 0; uint8_t blk[128]; while (n - off > 128) { b2compress(h, p + off, off + 128, false); off += 128; } size_t r = n - off; memset(blk, 0, 128); if (r) memcpy(blk, p + off, r); b2compress(h, blk, n, true); return h[0]; // first 8 bytes, little-endian = Python int.from_bytes(..., "little") } // word sets struct V32Hash { size_t operator()(V32 v) const { return std::hash()(v); } }; typedef std::unordered_set WordSet; static WordSet mkset(const char *words) { WordSet s; U32 w; std::string all(words); size_t i = 0; while (i < all.size()) { while (i < all.size() && all[i] == ' ') i++; size_t j = i; while (j < all.size() && all[j] != ' ') j++; if (j > i) { U32 u; utf8_decode(all.data() + i, j - i, u); s.insert(u); } i = j; } return s; } static WordSet STOP, OTHER, ADULT, MED; static size_t STOPMAX = 0, OTHERMAX = 0; static const char *STOP_W = "the of and to is that for it with was this are from have not but they you his her she their which has were been " "will would there about what your when also than them these into other some only any may more our who can all " "one out how just most after over by at as or an be he we if its so up new"; static const char *OTHER_W = "der die das und ist nicht mit sich auf für dem den ein eine zu von im auch es wir ich sie bei aus " "le la les et des du une est pour que qui dans sur pas au avec ce sont par " "el los las y en del se por con una para es lo su al como más pero " "il di che è per non della una sono con gli nel anche alla " "o os da do em um uma não com são mais " "het een van en op voor niet met zijn dat ook naar " "och att är som av för med jag inte på till " "og er det til på med ikke som af " "és az a hogy nem egy meg is " "w na się nie jest z do że to " "ve bir bu ile için da de"; static const char *ADULT_W = "porn porno pornhub xxx sex sexy sexual nude nudes naked fuck fucked fucking fucks cock cocks dick dicks pussy pussies cunt " "tits titties boobs boob nipple nipples anal blowjob blowjobs handjob cumshot cum creampie milf bdsm femdom fetish horny slut sluts whore " "escort escorts hooker hookers callgirl prostitute prostitutes erotic hardcore orgasm masturbation masturbate threesome gangbang " "shemale lesbian lesbians stripper camgirl webcam strapon dildo vibrator"; static const char *MED_W = "treatment treatments doctor doctors clinic clinical symptom symptoms medicine medical diagnosis disorder disorders therapy patient patients health infection std sti"; static const std::vector PLACE = {"lorem ipsum", "dolor sit amet", "consectetur adipiscing", "sed do eiusmod", "this is where the project description goes", "add your own, or import content", "create your first project", "start adding your projects", "this is a title"}; static const std::vector FORUM = {"this policy explains in detail how", "delete all board cookies", "are you sure you want to delete all cookies set by this board", "by accessing \xe2\x80\x9c", "hereinafter \xe2\x80\x9cwe\xe2\x80\x9d", "the board requires you to be registered and logged in", "to continue with the registration procedure", "you agree not to post any abusive, obscene"}; static const std::vector SHOP = {"add to cart", "add to basket", "add to bag", "buy now", "purchase now", "shop now", "checkout", "check out now", "in stock", "out of stock", "regular price", "sale price", "unit price", "sku:", "sku ", "quantity", "free shipping", "add to wishlist", "add to wish list", "view cart", "your cart"}; // Python-equivalent string helpers static inline V32 py_strip(V32 s) { size_t a = 0, b = s.size(); while (a < b && is_space(s[a])) a++; while (b > a && is_space(s[b - 1])) b--; return s.substr(a, b - a); } static inline size_t count_sp(V32 s) { size_t n = 0; for (char32_t c : s) n += (c == ' '); return n; } static inline bool is_term(char32_t c) { return c == '.' || c == '!' || c == '?' || c == '"' || c == '\''; } // English and other-language shares over the whitespace-split words of s (already lower-cased) struct PackSet { // open-addressing table of packed words uint64_t slot[1024]; PackSet() { memset(slot, 0, sizeof slot); } static inline uint64_t mix(uint64_t k) { k ^= k >> 29; k *= 0xbf58476d1ce4e5b9ULL; return k ^ (k >> 32); } void add(uint64_t k) { size_t h = mix(k) & 1023; while (slot[h] && slot[h] != k) h = (h + 1) & 1023; slot[h] = k; } inline bool has(uint64_t k) const { size_t h = mix(k) & 1023; while (slot[h]) { if (slot[h] == k) return true; h = (h + 1) & 1023; } return false; } }; static inline uint64_t pack(const char32_t *w, size_t L) { // 0 = cannot be in either set if (L == 0 || L > 5) return 0; uint64_t k = L; for (size_t i = 0; i < L; i++) { if (w[i] >= 0x200) return 0; k = (k << 9) | w[i]; } return k; } static PackSet PSTOP, POTHER; static void lang_counts(V32 s, size_t &words, size_t &en, size_t &ot) { words = en = ot = 0; size_t i = 0, n = s.size(); const char32_t *d = s.data(); while (i < n) { while (i < n && is_space(d[i])) i++; if (i >= n) break; size_t j = i; while (j < n && !is_space(d[j])) j++; words++; uint64_t k = pack(d + i, j - i); if (k) { en += PSTOP.has(k); ot += POTHER.has(k); } i = j; } } static void init_sets() { STOP = mkset(STOP_W); OTHER = mkset(OTHER_W); ADULT = mkset(ADULT_W); MED = mkset(MED_W); for (const char *w : {"to", "a", "is", "do", "per", "met", "till", "die", "den"}) { U32 u; utf8_decode(w, strlen(w), u); OTHER.erase(u); } for (auto &w : STOP) { uint64_t k = pack(w.data(), w.size()); if (!k) { fprintf(stderr, "word set packing failed\n"); exit(1); } PSTOP.add(k); } for (auto &w : OTHER) { uint64_t k = pack(w.data(), w.size()); if (!k) { fprintf(stderr, "word set packing failed\n"); exit(1); } POTHER.add(k); } } static inline double frac(size_t a, size_t n) { return n ? (double)a / (double)n : 0.0; } // letters vs numbers/symbols (TOK pattern of happid.py) struct TokBuf { std::vector ns_end, lastk, a_end, b_end, c_end, l_end, d_end; }; static double tok_alpha(V32 t, TokBuf &B) { size_t N = t.size(); if (!N) return 0.0; auto &nsE = B.ns_end, &lk = B.lastk, &aE = B.a_end, &bE = B.b_end, &cE = B.c_end, &lE = B.l_end, &dE = B.d_end; nsE.assign(N + 1, 0); lk.assign(N + 1, 0); aE.assign(N + 1, 0); bE.assign(N + 1, 0); cE.assign(N + 1, 0); lE.assign(N + 1, 0); dE.assign(N + 1, 0); for (size_t k = N; k-- > 0;) { char32_t c = t[k]; bool w = is_word(c); nsE[k] = is_space(c) ? (uint32_t)k : (k + 1 < N && !is_space(t[k + 1]) ? nsE[k + 1] : (uint32_t)(k + 1)); aE[k] = (w || c == '.' || c == '+' || c == '-') ? (k + 1 < N ? std::max(aE[k + 1], k + 1) : k + 1) : (uint32_t)k; bE[k] = (w || c == '-') ? (k + 1 < N ? std::max(bE[k + 1], k + 1) : k + 1) : (uint32_t)k; cE[k] = (w || c == '.') ? (k + 1 < N ? std::max(cE[k + 1], k + 1) : k + 1) : (uint32_t)k; lE[k] = is_letterrun(c) ? (k + 1 < N ? std::max(lE[k + 1], k + 1) : k + 1) : (uint32_t)k; dE[k] = is_dec(c) ? (k + 1 < N ? std::max(dE[k + 1], k + 1) : k + 1) : (uint32_t)k; } // last "://" in each non-space run that still has a character after it for (size_t s = 0; s < N;) { if (is_space(t[s])) { s++; continue; } size_t e = nsE[s]; uint32_t best = UINT32_MAX; for (size_t k = s; k + 3 < e; k++) if (t[k] == ':' && t[k + 1] == '/' && t[k + 2] == '/') best = (uint32_t)k; for (size_t k = s; k < e; k++) lk[k] = best; s = e; } size_t n = 0, a = 0, i = 0; while (i < N) { char32_t c = t[i]; if (is_space(c)) { i++; continue; } // 1: \S+://\S+ if (lk[i] != UINT32_MAX && lk[i] >= i + 1) { n++; a++; i = nsE[i]; continue; } // 2: [\w.+-]+@[\w-]+\.[\w.]+ if (aE[i] > i) { size_t j = aE[i]; if (j < N && t[j] == '@' && j + 1 < N && bE[j + 1] > j + 1) { size_t b = bE[j + 1]; if (b < N && t[b] == '.' && b + 1 < N && cE[b + 1] > b + 1) { n++; a++; i = cE[b + 1]; continue; } } } // 3: letter runs joined by apostrophes if (is_letterrun(c)) { size_t j = lE[i]; while (j + 1 < N && (t[j] == '\'' || t[j] == 0x2019) && is_letterrun(t[j + 1])) j = lE[j + 1]; n++; if (is_alpha(c)) a++; i = j; continue; } // 4: numbers with . , : inside if (is_dec(c)) { size_t j = dE[i]; while (j + 1 < N && (t[j] == '.' || t[j] == ',' || t[j] == ':') && is_dec(t[j + 1])) j = dE[j + 1]; n++; i = j; continue; } // 5: a mark and its repeats if (!is_word(c)) { size_t j = i + 1; while (j < N && t[j] == c) j++; n++; if (c == '@') a++; i = j; continue; } i++; // '_' that starts nothing } return n ? (double)a / (double)n : 0.0; } // repeated phrases (5-word runs seen before) static double repeated_phrase_share(const std::vector &cl, U32 &low) { U32 joined; for (size_t i = 0; i < cl.size(); i++) { if (i) joined.push_back(' '); joined.append(cl[i]); } lower_into(joined, low); std::vector wh; size_t i = 0, n = low.size(); while (i < n) { while (i < n && is_space(low[i])) i++; if (i >= n) break; size_t j = i; while (j < n && !is_space(low[j])) j++; wh.push_back(std::hash()(V32(low.data() + i, j - i))); i = j; } if (wh.size() < 20) return 0.0; std::unordered_set seen; seen.reserve(wh.size() * 2); long covered = 0, last = -5; for (long k = 0; k + 4 < (long)wh.size(); k++) { uint64_t g = 1469598103934665603ULL; for (int q = 0; q < 5; q++) { g ^= wh[k + q] + 0x9e3779b97f4a7c15ULL + (g << 6) + (g >> 2); g *= 1099511628211ULL; } if (seen.count(g)) { covered += (k - last >= 5) ? 5 : (k - last); last = k; } else seen.insert(g); } return (double)covered / (double)wh.size(); } // Line 0 guard static size_t count_sub(const std::string &h, const std::string &n) { size_t c = 0, p = 0; while ((p = h.find(n, p)) != std::string::npos) { c++; p += n.size(); } return c; } static bool adult_url(V32 url) { U32 u; lower_into(url, u); std::string s = utf8(u); for (const char *k : {"porn", "xxx", "sex", "escort", "hooker", "nude", "fuck", "milf"}) if (s.find(k) != std::string::npos) return true; for (size_t p = 0; (p = s.find("cam", p)) != std::string::npos; p++) { // cam(girl|s)?\b - the character before the boundary is a letter, so the next one must not be a word character U32 rest; utf8_decode(s.data() + p, s.size() - p, rest); auto bnd = [&](size_t q) { return q >= rest.size() || !is_word(rest[q]); }; if (rest.compare(0, 7, U"camgirl") == 0 && bnd(7)) return true; if (rest.compare(0, 4, U"cams") == 0 && bnd(4)) return true; if (bnd(3)) return true; } return false; } static bool guard(V32 url, V32 text) { U32 tl; lower_into(text, tl); std::string t = utf8(tl); size_t n = 0, med = 0; { size_t i = 0, N = tl.size(); U32 w; while (i < N) { if (tl[i] >= 'a' && tl[i] <= 'z') { size_t j = i; while (j < N && tl[j] >= 'a' && tl[j] <= 'z') j++; n++; w.assign(tl.data() + i, j - i); if (MED.count(w)) med++; i = j; } else i++; } } if (!n) n = 1; size_t na = 0; std::unordered_set distinct; { size_t i = 0, N = text.size(); U32 w; auto az = [](char32_t c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }; while (i < N) { if (az(text[i])) { size_t j = i; while (j < N && az(text[j])) j++; w.assign(text.data() + i, j - i); if (ADULT.count(w)) { na++; distinct.insert(w); } i = j; } else i++; } } size_t d = distinct.size(); double share = (double)na / (double)n; if (share >= 0.02 || count_sub(t, "call girl") >= 2) med = 0; if (d >= 2 && med < 3 && adult_url(url)) return true; if (d >= 4 && share >= 0.005 && med < 3) return true; size_t pc = 0; for (auto &p : PLACE) if (t.find(p) != std::string::npos) pc++; if (pc >= 1 && (t.find("lorem") != std::string::npos || pc >= 2)) return true; for (auto &p : FORUM) if (t.find(p) != std::string::npos) return true; // shop page: flagged by shop phrases, second chance if 150+ words sit in real sentence lines size_t hits = 0; for (auto &p : SHOP) if (t.find(p) != std::string::npos) hits++; bool strong = t.find("add to cart") != std::string::npos || t.find("purchase now") != std::string::npos || t.find("buy now") != std::string::npos; if ((strong && hits >= 2) || hits >= 3) { size_t art = 0, s = 0, N = text.size(); while (s <= N) { size_t e = text.find(U'\n', s); if (e == V32::npos) e = N; V32 l = py_strip(text.substr(s, e - s)); size_t sp = count_sp(l); if (sp >= 11 && !l.empty() && (l.back() == '.' || l.back() == '!' || l.back() == '?' || l.back() == '"' || l.back() == '\'')) art += sp + 1; s = e + 1; } if (art < 150) return true; } return false; } // the cascade judge struct Scratch { U32 low; std::vector lines, cl, ws; TokBuf tb; std::unordered_set seen; }; // line 1 on the first 20,000 characters (head); total = whether head is the whole page static bool judge_head(V32 head, bool total, Scratch &S, double &wordshare) { if (total && head.size() < 300) return false; size_t w, en, ot; V32 text = head; // line 1 - quick screen on the head of the page lower_into(text.substr(0, 4000), S.low); lang_counts(S.low, w, en, ot); double he = frac(en, w); if (he < 0.08 || he - frac(ot, w) < 0.02) return false; V32 t20 = text.substr(0, 20000); { size_t a = 0, n = 0; for (char32_t c : t20) if (is_alpha(c)) { n++; if (c < 0x250) a++; } if (frac(a, n) < 0.90) return false; } S.ws.clear(); { size_t i = 0, N = t20.size(); while (i < N) { while (i < N && is_space(t20[i])) i++; if (i >= N) break; size_t j = i; while (j < N && !is_space(t20[j])) j++; S.ws.push_back(t20.substr(i, j - i)); i = j; } } if (S.ws.empty()) return false; size_t withletters = 0, wl = 0; for (V32 x : S.ws) { wl += x.size(); for (char32_t c : x) if (is_alpha(c)) { withletters++; break; } } wordshare = (double)withletters / (double)S.ws.size(); if (wordshare < 0.85) return false; double mwl = (double)wl / (double)S.ws.size(); if (mwl < 3.5 || mwl > 7) return false; return true; } static bool judge_rest(V32 text, V32 url, Scratch &S, double wordshare) { size_t w, en, ot; // line 2 - Harrington line sort S.lines.clear(); { size_t s = 0, N = text.size(); while (s <= N) { size_t e = text.find(U'\n', s); if (e == V32::npos) e = N; V32 l = py_strip(text.substr(s, e - s)); if (!l.empty()) S.lines.push_back(l); s = e + 1; } } size_t nl = S.lines.size(); if (!nl) return false; S.seen.clear(); size_t dl = 0, dch = 0, tch = 0; for (V32 l : S.lines) { tch += l.size(); if (!S.seen.insert(l).second) { dl++; dch += l.size(); } } if ((double)dl / nl > 0.30 || (double)dch / tch > 0.30) return false; S.cl.clear(); size_t cw = 0; for (V32 l : S.lines) { size_t sp = count_sp(l); if (sp >= 2) { S.cl.push_back(l); cw += sp + 1; } } if (S.cl.empty() || cw < 50) return false; S.seen.clear(); size_t cd = 0, ct = 0, term = 0, shrt = 0; for (V32 l : S.cl) { ct += l.size(); if (!S.seen.insert(l).second) cd += l.size(); if (is_term(l.back())) term++; if (l.size() <= 30) shrt++; } size_t n = S.cl.size(); if ((double)cd / ct > 0.01 || (double)term / n < 0.12 || (double)shrt / n > 0.67) return false; // language on each third of the content { size_t parts = n >= 3 ? 3 : 1; U32 j; for (size_t p = 0; p < parts; p++) { size_t a = parts == 3 ? p * n / 3 : 0, b = parts == 3 ? (p + 1) * n / 3 : n; j.clear(); for (size_t k = a; k < b && j.size() < 3000; k++) { if (k > a) j.push_back(' '); j.append(S.cl[k]); } if (j.size() > 3000) j.resize(3000); lower_into(j, S.low); lang_counts(S.low, w, en, ot); if (w >= 20 && frac(en, w) - frac(ot, w) < 0) return false; } } // line 3 - slow checks only for pages still in doubt bool sure = (double)dl / nl <= 0.10 && (double)term / n >= 0.30 && cd == 0 && wordshare >= 0.95; if (!sure) { if (tok_alpha(text, S.tb) < 0.79) return false; if (repeated_phrase_share(S.cl, S.low) > 0.20) return false; } if (guard(url, text)) return false; return true; } // own WET reader: split one gzip file across all cores // Common Crawl WET files store every record as its own gzip member. A file is cut into chunks; each thread finds the first // real member at or after its chunk start (a 1f 8b 08 header that inflates cleanly, passes its CRC check and starts with // "WARC/"), then reads members until it passes the end of its chunk. Records keep their file order through the byte offset. struct Rec { uint64_t key; std::string rid, url; const char *body; size_t blen; }; struct Inflater { z_stream z; std::vector out; bool init = false; Inflater() { memset(&z, 0, sizeof z); out.resize(1 << 20); } ~Inflater() { if (init) inflateEnd(&z); } // inflate one member at p; returns bytes consumed (0 if not a clean member), output in out[0..olen) size_t member(const unsigned char *p, size_t avail, size_t &olen) { if (!init) { inflateInit2(&z, 16 + MAX_WBITS); init = true; } else inflateReset(&z); z.next_in = (Bytef *)p; z.avail_in = (uInt)std::min(avail, 0x7fffffff); olen = 0; for (;;) { if (olen == out.size()) out.resize(out.size() * 2); z.next_out = (Bytef *)out.data() + olen; z.avail_out = (uInt)(out.size() - olen); int r = inflate(&z, Z_NO_FLUSH); olen = out.size() - z.avail_out; if (r == Z_STREAM_END) return (size_t)z.total_in; if (r != Z_OK) return 0; if (z.avail_in == 0) return 0; } } }; static std::string bstrip(const char *a, const char *b) { auto ws = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v' || c == '\f'; }; while (a < b && ws(*a)) a++; while (b > a && ws(b[-1])) b--; return std::string(a, b); } // parse the WARC records inside one member buffer; calls fn for each conversion record template static void parse_member(const char *buf, size_t n, uint64_t keybase, F &&fn) { const char *p = buf, *end = buf + n; unsigned idx = 0; auto next_line = [&](const char *&s) -> const char * { const char *nl = (const char *)memchr(s, '\n', end - s); const char *l = s; s = nl ? nl + 1 : end; return l; }; while (p < end) { const char *l = next_line(p); if (p - l < 5 || memcmp(l, "WARC/", 5) != 0) continue; std::string type, rid, url; long clen = 0; while (p < end) { const char *h = next_line(p); size_t hl = p - h; if ((hl == 2 && h[0] == '\r' && h[1] == '\n') || (hl == 1 && h[0] == '\n')) break; const char *c = (const char *)memchr(h, ':', hl); std::string key = bstrip(h, c ? c : p); for (auto &ch : key) ch = (char)tolower((unsigned char)ch); std::string val = c ? bstrip(c + 1, p) : std::string(); if (key == "content-length") clen = atol(val.c_str()); else if (key == "warc-type") type = val; else if (key == "warc-record-id") rid = val; else if (key == "warc-target-uri") url = val; } size_t take = std::min((size_t)clen, end - p); const char *body = p; p += take; if (type == "conversion") { Rec r{keybase | std::min(idx, 15u), rid, url, body, take}; fn(r); } idx++; } } struct MFile { std::string path; const unsigned char *data = nullptr; size_t size = 0; }; static bool map_file(MFile &f) { int fd = open(f.path.c_str(), O_RDONLY); if (fd < 0) return false; struct stat st; fstat(fd, &st); f.size = st.st_size; f.data = f.size ? (const unsigned char *)mmap(nullptr, f.size, PROT_READ, MAP_PRIVATE, fd, 0) : nullptr; close(fd); if (f.data == MAP_FAILED) return false; madvise((void *)f.data, f.size, MADV_SEQUENTIAL); return true; } // read the members of file fi that start inside [s, e) template static void read_chunk(const MFile &f, uint32_t fi, size_t s, size_t e, Inflater &I, F &&fn) { size_t pos = s, olen; if (s > 0) { // find the first real member at or after s for (;; pos++) { const unsigned char *q = (const unsigned char *)memchr(f.data + pos, 0x1f, f.size - pos); if (!q) return; pos = q - f.data; if (pos >= e) return; if (pos + 3 < f.size && f.data[pos + 1] == 0x8b && f.data[pos + 2] == 8) { size_t used = I.member(f.data + pos, f.size - pos, olen); if (used && olen >= 5 && memcmp(I.out.data(), "WARC/", 5) == 0) break; } } } while (pos < e && pos < f.size) { size_t used = I.member(f.data + pos, f.size - pos, olen); if (!used) { fprintf(stderr, "bad gzip data in %s at %zu\n", f.path.c_str(), pos); return; } parse_member(I.out.data(), olen, ((uint64_t)fi << 48) | ((uint64_t)pos << 4), fn); pos += used; } } // duplicates: anchor lines struct Kept { uint64_t key; std::string rid, url, clean; }; struct Fp { uint64_t key, whole; std::vector anchors; }; static std::unordered_set find_dups(const std::vector &fps) { std::unordered_map parent; std::function root = [&](uint64_t x) { for (;;) { auto it = parent.find(x); if (it == parent.end() || it->second == x) return x; auto it2 = parent.find(it->second); uint64_t gp = (it2 == parent.end()) ? it->second : it2->second; it->second = gp; x = gp; } }; auto join = [&](uint64_t a, uint64_t b) { uint64_t ra = root(a), rb = root(b); if (ra != rb) { if (rb < ra) std::swap(ra, rb); parent[rb] = ra; if (!parent.count(ra)) parent[ra] = ra; } }; std::unordered_map whole; for (auto &f : fps) { auto it = whole.find(f.whole); if (it != whole.end()) join(it->second, f.key); else whole[f.whole] = f.key; } std::unordered_map nanch; std::unordered_map> index; for (auto &f : fps) { nanch[f.key] = f.anchors.size(); for (uint64_t a : f.anchors) index[a].push_back(f.key); } struct PH { size_t operator()(const std::pair &p) const { return std::hash()(p.first * 0x9e3779b97f4a7c15ULL ^ p.second); } }; std::unordered_map, int, PH> shared; for (auto &kv : index) { auto keys = kv.second; if (keys.size() < 2 || keys.size() > 100) continue; std::sort(keys.begin(), keys.end()); for (size_t i = 0; i < keys.size(); i++) for (size_t j = i + 1; j < keys.size(); j++) shared[{keys[i], keys[j]}]++; } for (auto &kv : shared) { int c = kv.second; size_t m = std::max(nanch[kv.first.first], nanch[kv.first.second]); if (c >= 2 && (double)c >= 0.8 * (double)m) join(kv.first.first, kv.first.second); } std::unordered_set drop; for (auto &kv : parent) if (root(kv.first) != kv.first) drop.insert(kv.first); return drop; } // JSON like Python json.dumps (ensure_ascii) static void json_str(V32 s, std::string &o) { static const char *hex = "0123456789abcdef"; o.push_back('"'); auto u4 = [&](unsigned v) { o += "\\u"; o.push_back(hex[(v >> 12) & 15]); o.push_back(hex[(v >> 8) & 15]); o.push_back(hex[(v >> 4) & 15]); o.push_back(hex[v & 15]); }; for (char32_t c : s) { if (c == '"') o += "\\\""; else if (c == '\\') o += "\\\\"; else if (c == '\n') o += "\\n"; else if (c == '\r') o += "\\r"; else if (c == '\t') o += "\\t"; else if (c == '\b') o += "\\b"; else if (c == '\f') o += "\\f"; else if (c >= 0x20 && c < 0x7f) o.push_back((char)c); else if (c < 0x10000) u4(c); else { unsigned v = c - 0x10000; u4(0xD800 | (v >> 10)); u4(0xDC00 | (v & 0x3FF)); } } o.push_back('"'); } #ifndef HAPPID_NO_MAIN int main(int argc, char **argv) { if (argc < 4) { fprintf(stderr, "usage: happid wet_dir out_dir threads\n"); return 1; } std::string wet = argv[1], out = argv[2]; int nw = std::max(1, atoi(argv[3])); init_lower(); init_sets(); std::vector files; if (DIR *d = opendir(wet.c_str())) { while (dirent *e = readdir(d)) { std::string n = e->d_name; if (n.size() > 7 && n.compare(n.size() - 7, 7, ".wet.gz") == 0) files.push_back(wet + "/" + n); } closedir(d); } std::sort(files.begin(), files.end()); mkdir(out.c_str(), 0755); auto T = [] { return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); }; double t0 = T(); std::vector mf(files.size()); for (size_t i = 0; i < files.size(); i++) { mf[i].path = files[i]; if (!map_file(mf[i])) { fprintf(stderr, "cannot open %s\n", files[i].c_str()); return 1; } } const size_t CH = 4u << 20; // 4 MB of compressed data per task struct Task { uint32_t fi; size_t s, e; }; std::vector tasks; for (uint32_t i = 0; i < mf.size(); i++) for (size_t s = 0; s < mf[i].size; s += CH) tasks.push_back({i, s, std::min(mf[i].size, s + CH)}); std::atomic next_task(0); std::vector> kept(nw); std::vector> fps(nw); std::vector ndocs(nw, 0); std::vector workers; for (int wid = 0; wid < nw; wid++) workers.emplace_back([&, wid] { Scratch S; Inflater I; U32 text, urlu, low, clean; auto on_rec = [&](Rec &r) { ndocs[wid]++; if (memchr(r.body, '{', r.blen)) return; // a "{" anywhere sets the page aside size_t used = utf8_decode(r.body, r.blen, text, 20000); double wordshare; if (!judge_head(text, used == r.blen, S, wordshare)) return; if (used < r.blen) utf8_decode(r.body, r.blen, text); utf8_decode(r.url.data(), r.url.size(), urlu); if (!judge_rest(text, urlu, S, wordshare)) return; clean.clear(); for (size_t i = 0; i < S.cl.size(); i++) { if (i) clean.push_back('\n'); clean.append(S.cl[i]); } Fp f; f.key = r.key; f.whole = h8(utf8(clean)); std::vector an; for (V32 p : S.cl) if (count_sp(p) >= 7 && is_term(p.back())) { lower_into(p, low); an.push_back(h8(utf8(low))); } std::sort(an.begin(), an.end()); an.erase(std::unique(an.begin(), an.end()), an.end()); if (an.size() > 64) an.resize(64); f.anchors = std::move(an); std::string js = "{\"id\": "; json_str(U32(r.rid.begin(), r.rid.end()), js); js += ", \"url\": "; json_str(urlu, js); js += ", \"text\": "; json_str(clean, js); js += "}\n"; kept[wid].push_back({f.key, r.rid, std::string(), std::move(js)}); fps[wid].push_back(std::move(f)); }; for (size_t t; (t = next_task++) < tasks.size();) read_chunk(mf[tasks[t].fi], tasks[t].fi, tasks[t].s, tasks[t].e, I, on_rec); }); for (auto &t : workers) t.join(); double t1 = T(); std::vector all; size_t total_docs = 0; for (int i = 0; i < nw; i++) { total_docs += ndocs[i]; for (auto &f : fps[i]) all.push_back(f); } auto drop = find_dups(all); double t2 = T(); std::vector nout(nw, 0); std::vector writers; for (int wid = 0; wid < nw; wid++) writers.emplace_back([&, wid] { auto &K = kept[wid]; std::sort(K.begin(), K.end(), [](const Kept &a, const Kept &b) { return a.key < b.key; }); char name[64]; snprintf(name, sizeof name, "/%05d.jsonl.gz", wid); gzFile g = gzopen((out + name).c_str(), "wb6"); for (auto &k : K) { if (drop.count(k.key)) continue; gzwrite(g, k.clean.data(), (unsigned)k.clean.size()); nout[wid]++; } gzclose(g); }); for (auto &t : writers) t.join(); double t3 = T(); size_t docs_out = 0; for (size_t x : nout) docs_out += x; { std::string ids = "["; bool first = true; for (int i = 0; i < nw; i++) for (auto &k : kept[i]) { if (!first) ids += ", "; first = false; json_str(U32(k.rid.begin(), k.rid.end()), ids); } ids += "]"; FILE *f = fopen((out + "/kept_ids.json").c_str(), "w"); fwrite(ids.data(), 1, ids.size(), f); fclose(f); } char res[512]; snprintf(res, sizeof res, "{\"mode\": \"cascade-c++\", \"files\": %zu, \"workers\": %d, \"docs_in\": %zu, \"kept_after_screen\": %zu, \"dups_removed\": %zu, " "\"docs_out\": %zu, \"screen_s\": %.2f, \"dedup_s\": %.2f, \"write_s\": %.2f, \"total_s\": %.2f}", files.size(), nw, total_docs, all.size(), drop.size(), docs_out, t1 - t0, t2 - t1, t3 - t2, t3 - t0); FILE *f = fopen((out + "/times.json").c_str(), "w"); fputs(res, f); fclose(f); printf("%s\n", res); return 0; } #endif