Upload folder using huggingface_hub
Browse filesFiles changed (5)
1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Local repro of the ML advisory wiring (in-process, no HTTP)."""import sysfrom pathlib import Pathfrom unittest.mock import AsyncMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parent))BACKEND = Path(r"C:\Users\Sitcd3\Documents\Rezerva DESIGN_Validator\Validator_Modul_X-test\email-validator\backend")
from app.config import settings # noqa: E402from app.ml.runtime import EmailRiskModel # noqa: E402from app.validator.engine import EmailValidationEngine # noqa: E402
MODEL_DIR = str(BACKEND / "app" / "ml" / "model")
# Real model, real flag — the exact production configuration.settings.ml_disposable_enabled = Truesettings.ml_model_repo = MODEL_DIRmodel = EmailRiskModel(repo=MODEL_DIR)loaded = model.load()print("model loaded:", loaded)if not loaded: sys.exit(1)
pred = model.predict(["john.smith [SEP] stripe.com", "john.smith [SEP] temp-mail-pro.xyz"])print("runtime predictions:", pred)
# Now the full engine path with DNS mocked to reach the mailbox stage.eng = EmailValidationEngine()dns = type(eng.mailbox) # noqa: F841 - keep import shape explicitfrom app.models import DNSResult # noqa: E402
dns_ok = DNSResult(domain_exists=True, has_mx_records=True, mx_records=[{"host": "mx1.stripe.com", "priority": 10}])
with patch("app.validator.engine.check_dns", new=AsyncMock(return_value=dns_ok)): res = asyncio_run = __import__("asyncio").run( eng.validate_batch(["someone@stripe.com"], deep=True) )
d = res[0].disposableprint("engine ml_label:", d.ml_label, "conf:", d.ml_confidence)print("warnings:", [w for w in res[0].scoring.warnings if "ML" in w])print("breakdown:", {k: v for k, v in res[0].scoring.breakdown.items() if "ML" in k})20 unmodified lines21222324252627282930313233343536373839401 unmodified line42434445464720 unmodified linesROLE_BASED_PREFIXES,)# Real, MX-having legitimate domains for the NORMAL class. Small businesses# commonly use these registrars/hosting providers; they are deliberately NOT# in the disposable blocklist.NORMAL_DOMAIN_SEEDS = {# major hosting/corporate mail platforms not in FREE_PROVIDERS"acme-corp.com", "northwind-traders.com", "contoso.com","ibm.com", "siemens.com", "bosch.de", "nokia.com", "ericsson.com","volkswagen.de", "bmwgroup.com", "samsung.com", "lg.com","coca-cola.com", "nestle.com", "unilever.com", "philips.com","abccomponents.test", "midwestmfg.test", "bluewater-logistics.test","harborview-law.test", "summit-clinic.test", "granite-construction.test",}# Name-like local-part seeds -> varied into dotted/joined/initial forms.NORMAL_LOCAL_SEEDS = {"john.smith", "maria.garcia", "kenji.tanaka", "amara.osei","pierre.dubois", "anna.kowalski", "carlos.silva", "fatima.al-sayed",1 unmodified line"yuki.sato", "elena.petrova", "omar.hassan", "ingrid.larsen","paul.kelly", "mei.chen", "tom.hansen", "lucie.moreau","r.kapoor", "sj.williams", "t.okafor", "m.vargas",}20 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697981 unmodified line10010110210310410510610710820 unmodified linesROLE_BASED_PREFIXES,)# Real, MX-having legitimate domains for the NORMAL class - the diversity is# the point: the model must learn "corporate/institutional-looking = NORMAL"# and generalize to unseen domains, not memorize a handful (the first version# used 26 seeds and flagged stripe.com as disposable at 0.977).# Spans corporates, industrials, banks, insurers, pharma, universities,# governments, NGOs, retail, media, telcos across 20+ TLDs.NORMAL_DOMAIN_SEEDS = {# --- global corporates / tech ---"apple.com", "microsoft.com", "google.com", "amazon.com", "meta.com","ibm.com", "oracle.com", "sap.com", "salesforce.com", "adobe.com","intel.com", "amd.com", "nvidia.com", "cisco.com", "dell.com","hp.com", "lenovo.com", "acer.com", "asus.com", "logitech.com","openai.com", "anthropic.com", "stripe.com", "shopify.com","atlassian.com", "gitlab.com", "dropbox.com", "zoom.com", "slack.com",# --- industrials / engineering (EU-heavy) ---"siemens.com", "siemens.de", "bosch.de", "abb.com", "philips.com","volkswagen.de", "bmwgroup.com", "daimler.com", "porsche.de","toyota.com", "honda.com", "volvo.com", "scania.com", "electrolux.com","kuka.com", "festo.com", "heraeus.com", "knippers-helbig.com","thyssenkrupp.com", "heidelberg.com", "wuerth.com", "trumpf.com",# --- banks / insurers / re-insurers ---"jpmorganchase.com", "goldmansachs.com", "hsbc.com", "barclays.co.uk","deutsche-bank.de", "ubs.com", "commerzbank.com", "ing.com","allianz.de", "axa.com", "zurich.com", "munichre.com", "swissre.com","generali.com", "nn-group.com", "baloise.ch",# --- pharma / healthcare ---"pfizer.com", "novartis.com", "roche.com", "jnj.com", "sanofi.com","astrazeneca.com", "bayer.com", "boehringer-ingelheim.com","fresenius.com", "merck.com", "gsk.com", "takeda.com",# --- universities / research ---"harvard.edu", "mit.edu", "stanford.edu", "yale.edu", "upenn.edu","oxford.ac.uk", "cambridge.ac.uk", "imperial.ac.uk", "ethz.ch","epfl.ch", "uzh.ch", "unibe.ch", "tum.de", "lmu.de", "hu-berlin.de","fu-berlin.de", "uva.nl", "tudelft.nl", "kth.se", "lu.se","uio.no", "dtu.dk", "aalto.fi", "unimelb.edu.au", "utoronto.ca",# --- governments / institutions ---"nasa.gov", "esa.int", "europa.eu", "un.org", "who.int", "oecd.org","worldbank.org", "bund.de", "admin.ch", "gov.uk",# --- NGOs ---"redcross.org", "unicef.org", "wwf.org", "greenpeace.org","amnesty.org", "msf.org",# --- consumer / retail / food ---"walmart.com", "target.com", "ikea.com", "carrefour.com", "tesco.com","aldi-sued.de", "lidl.com", "nestle.com", "danone.com", "barilla.com","ferrero.com", "unilever.com", "pandora.net", "hilti.com",# --- media / travel / energy ---"nytimes.com", "bbc.co.uk", "reuters.com", "spiegel.de","theguardian.com", "lufthansa.com", "ryanair.com", "airfrance.com","klm.com", "emirates.com", "shell.com", "bp.com","totalenergies.com", "rwe.com", "edf.fr", "vodafone.com","telekom.de", "swisscom.ch", "kpn.com", "telia.se",# --- more TLD diversity (.io/.ai/.co/.jp/.ca/.au/.in/.br/.se/.ch) ---"canva.io", "figma.ai", "notion.so", "linear.app", "vercel.com","dena.jp", "ricoh.co.jp", "shopify.ca", "atlassian.com.au","tcs.com", "infosys.com", "vale.com", "embraer.com","alstom.com", "thalesgroup.com", "legrand.fr", "schneider-electric.com","honeywell.com", "eaton.com", "emerson.com", "rockwellautomation.com",# --- logistics / construction / infra ---"ups.com", "fedex.com", "dhl.com", "maersk.com", "cma-cgm.com","sandvik.com", "atlascopco.com", "skanska.se", "ncc.se", "veolia.com","bouygues.com", "vinci.com", "skf.com", "alfalaval.com", "munters.com",# --- payments / media / retail EU ---"mastercard.com", "visa.com", "mediamarkt.de", "cewe.de", "dm.de","hornbach.de", "obi.de", "douglas.com",# --- more universities / research / finance institutions ---"berkeley.edu", "caltech.edu", "princeton.edu", "columbia.edu","uni-heidelberg.de", "wwu.de", "rub.de", "ecb.europa.eu", "imf.org","wto.org", "unil.ch", "ugent.be", "uclouvain.be",}# Name-like local-part seeds - varied by the generator into dotted / joined /# initial / year-suffixed formats that mirror real corporate address books.NORMAL_LOCAL_SEEDS = {"john.smith", "maria.garcia", "kenji.tanaka", "amara.osei","pierre.dubois", "anna.kowalski", "carlos.silva", "fatima.al-sayed",1 unmodified line"yuki.sato", "elena.petrova", "omar.hassan", "ingrid.larsen","paul.kelly", "mei.chen", "tom.hansen", "lucie.moreau","r.kapoor", "sj.williams", "t.okafor", "m.vargas","jsmith", "mgarcia", "ktanaka", "aosei","j.smith85", "m.garcia2024", "jsmith2024", "john_smith","d.miller.dev", "p.kelly_hr", "s.rossi.91", "t.hansen88",}
3 unmodified lines456789101112131417 unmodified lines32333435363738393 unmodified lines"DistilBertForSequenceClassification"],"attention_dropout": 0.1,"bos_token_id": null,"dim": 768,"dropout": 0.1,"dtype": "float32","eos_token_id": null,"hidden_dim": 3072,"id2label": {"0": "NORMAL",17 unmodified lines"seq_classif_dropout": 0.2,"sinusoidal_pos_embds": false,"tie_weights_": true,"tie_word_embeddings": true,"transformers_version": "5.19.0","use_cache": false,"vocab_size": 30522}3 unmodified lines45678910111217 unmodified lines3031323334353 unmodified lines"DistilBertForSequenceClassification"],"attention_dropout": 0.1,"dim": 768,"dropout": 0.1,"dtype": "float32","hidden_dim": 3072,"id2label": {"0": "NORMAL",17 unmodified lines"seq_classif_dropout": 0.2,"sinusoidal_pos_embds": false,"tie_weights_": true,"transformers_version": "4.57.6","vocab_size": 30522}
123version https://git-lfs.github.com/spec/v1oid sha256:212e338fe9e6d8cb89fce895dc21c306e6c61ab3d480922e82dd084e55283093size 267838720123version https://git-lfs.github.com/spec/v1oid sha256:f8d025a0fc91fe312766e00b65de76e956b071217601a7838db9e7e6ba86f201size 267838720
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import unittest
import disposable_email_domains
from app.ml.build_dataset import NORMAL_DOMAIN_SEEDS, NORMAL_LOCAL_SEEDS
class NormalSeedIntegrityTests(unittest.TestCase): """The NORMAL class teaches the model what legitimate looks like. A single disposable domain in the seeds would poison the decision boundary - the exact false-positive that flagged stripe.com as DISPOSABLE (0.977)."""
def test_no_normal_domain_is_in_the_disposable_blocklist(self): poisoned = sorted(d for d in NORMAL_DOMAIN_SEEDS if d in disposable_email_domains.blocklist) self.assertEqual(poisoned, [], f"disposable domains in NORMAL seeds: {poisoned}")
def test_seed_diversity_is_sufficient_to_generalize(self): # 26 seed domains taught the model "memorize these"; the stripe.com # false positive proved that generalizes badly. Hundreds across # industries/TLDs are needed to learn 'corporate-looking = normal'. self.assertGreaterEqual(len(NORMAL_DOMAIN_SEEDS), 200, f"only {len(NORMAL_DOMAIN_SEEDS)} NORMAL domains")
def test_seeds_span_many_distinct_tlds(self): tlds = {d.rsplit(".", 1)[-1] for d in NORMAL_DOMAIN_SEEDS} self.assertGreaterEqual(len(tlds), 12, f"NORMAL seeds concentrated in {sorted(tlds)}")
def test_all_seeds_are_wellformed_domains(self): bad = sorted(d for d in NORMAL_DOMAIN_SEEDS if "." not in d or " " in d or d != d.strip().lower()) self.assertEqual(bad, [], f"malformed seeds: {bad}")
def test_no_normal_seed_is_a_known_free_provider(self): # Free providers are classified by the FREE_PROVIDERS set, not by the # model - training them as NORMAL would blur two different signals. from app.validator.disposable import FREE_PROVIDERS overlap = sorted(d for d in NORMAL_DOMAIN_SEEDS if d in FREE_PROVIDERS) self.assertEqual(overlap, [], f"free providers in NORMAL seeds: {overlap}")
def test_local_seeds_are_name_like(self): digits_only = [s for s in NORMAL_LOCAL_SEEDS if s.replace(".", "").replace("_", "").isdigit()] self.assertEqual(digits_only, []) self.assertGreaterEqual(len(NORMAL_LOCAL_SEEDS), 20)
if __name__ == "__main__": unittest.main().deploy-local-repro.pyAdded+44
app/ml/build_dataset.py+72-11
app/ml/model/config.json+1-5
app/ml/model/model.safetensors+1-1
tests/test_ml_seeds.pyAdded+50