Datasets:
v1.0.0 - Initial release: EU-Retail-UX-Feedback-Live (4,998 GDPR-anonymised records, UK/FR/DE, en-GB/fr-FR/de-DE, UTF-8)
3a016ca verified | #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| EU-Retail-UX-Feedback-Live - Synthetic live UX feedback dataset generator | |
| ========================================================================= | |
| This script produces a realistic, *synthetic* real-time user-experience (UX) | |
| feedback dataset for a large European e-commerce retail company (1000+ employees) | |
| operating in the United Kingdom, France and Germany. | |
| The pipeline has two stages: | |
| Stage 1 - RAW generation: | |
| Simulates records as they would arrive from real collection systems | |
| (e-commerce website, mobile app, customer service platform). RAW records | |
| contain direct personal data (user email, name, phone number, address) | |
| to illustrate what must NEVER be published. | |
| Stage 2 - GDPR anonymisation (pseudonymisation): | |
| * Deletes all direct identifiers (email, name, phone, address). | |
| * Replaces the real user identifier with a pseudonymous ID | |
| (HMAC-SHA256 over the raw user id with a secret salt). | |
| * Replaces session identifiers with pseudonymous session tokens. | |
| * Scrubs free-text feedback for residual PII patterns | |
| (emails, phone numbers, UK/FR/DE postcodes, common personal data). | |
| * Every record is encoded as UTF-8 and tagged with a BCP-47 language | |
| identifier (en-GB, fr-FR, de-DE). | |
| Only the anonymised output is ever uploaded to the Hugging Face Hub. | |
| Versioning | |
| ---------- | |
| The dataset is refreshed every 30 minutes. Each refresh produces an immutable, | |
| cumulative snapshot (v1.0.0, v1.1.0, ...) with a SHA-256 checksum recorded in | |
| a version manifest so every published version is auditable and rollback-able. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import hmac | |
| import json | |
| import os | |
| import random | |
| import re | |
| import secrets | |
| import string | |
| from datetime import datetime, timedelta, timezone | |
| import pandas as pd | |
| # --------------------------------------------------------------------------- | |
| # Configuration | |
| # --------------------------------------------------------------------------- | |
| BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| DATA_DIR = os.path.join(BASE_DIR, "data") | |
| SNAPSHOT_DIR = os.path.join(BASE_DIR, "snapshots") | |
| VERSION_DIR = os.path.join(BASE_DIR, "versions") | |
| RAW_DIR = os.path.join(BASE_DIR, "raw_deleted_never_upload") | |
| PSEUDO_SALT = os.environ.get("UX_PSEUDO_SALT", "EU-Retail-UX-2026-kdf-salt") | |
| DIMENSIONS = [ | |
| "page_load_speed", | |
| "search_relevance", | |
| "product_recommendations", | |
| "checkout_flow", | |
| "delivery_experience", | |
| "after_sales_support", | |
| ] | |
| MARKETS = [ | |
| {"country_code": "GB", "region": "United Kingdom", "language": "en-GB"}, | |
| {"country_code": "FR", "region": "France", "language": "fr-FR"}, | |
| {"country_code": "DE", "region": "Germany", "language": "de-DE"}, | |
| ] | |
| DEVICE_TYPES = ["desktop", "mobile", "tablet"] | |
| SOURCE_CHANNELS = ["website", "mobile_app", "customer_service"] | |
| DIMENSION_LABELS = { | |
| "page_load_speed": "Page load speed", | |
| "search_relevance": "Search relevance", | |
| "product_recommendations": "Product recommendations", | |
| "checkout_flow": "Checkout flow", | |
| "delivery_experience": "Delivery experience", | |
| "after_sales_support": "After-sales support", | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Multi-language feedback content (UTF-8) | |
| # --------------------------------------------------------------------------- | |
| # Each entry: lang -> dimension -> rating band -> list of template sentences. | |
| FEEDBACK = { | |
| "en-GB": { | |
| "page_load_speed": { | |
| "pos": [ | |
| "The site loaded instantly and the product pages felt really snappy.", | |
| "Page loading speed has improved a lot, everything opens quickly.", | |
| "Lovely fast experience, the homepage loaded in under a second.", | |
| "Search and category pages load very quickly on both mobile and desktop.", | |
| ], | |
| "neu": [ | |
| "Loading speed is acceptable but could be a bit faster on the homepage.", | |
| "Pages take a few seconds to load on my connection, not terrible though.", | |
| "The site works fine most of the time, with the occasional slow image.", | |
| "Reasonable loading times, though the product gallery is a little heavy.", | |
| ], | |
| "neg": [ | |
| "The checkout page took ages to load and I nearly gave up.", | |
| "Product pages are painfully slow on mobile data, very frustrating.", | |
| "The site kept spinning during the sale and pages timed out.", | |
| "Loading speed is poor, images appear seconds after the text.", | |
| ], | |
| }, | |
| "search_relevance": { | |
| "pos": [ | |
| "Search results were spot on, exactly what I was looking for.", | |
| "The search function understands what I type and returns great matches.", | |
| "Great search relevance, the filters helped me narrow down quickly.", | |
| "I found the exact item in seconds thanks to smart search suggestions.", | |
| ], | |
| "neu": [ | |
| "Search results are okay but a couple of items were not relevant.", | |
| "The search works, though it sometimes ignores my spelling mistakes.", | |
| "Results were acceptable, but I had to scroll to find the right size.", | |
| "Search is decent, the category filters helped a little.", | |
| ], | |
| "neg": [ | |
| "Search returned mostly irrelevant products, I wasted time scrolling.", | |
| "The search engine seems to ignore my keywords entirely.", | |
| "Search relevance is poor, none of the results matched my query.", | |
| "I searched a specific brand and got unrelated items first.", | |
| ], | |
| }, | |
| "product_recommendations": { | |
| "pos": [ | |
| "The recommendations on the homepage were genuinely useful.", | |
| "Loved the 'you might also like' section, it suggested perfect items.", | |
| "Recommendations matched my taste and I added two extra products.", | |
| "The personalised recommendations felt relevant and helpful.", | |
| ], | |
| "neu": [ | |
| "Recommendations were hit and miss, some useful and some not.", | |
| "The suggested items are fine but nothing really caught my eye.", | |
| "Reasonable recommendations, though a few were repeats of my history.", | |
| "The 'related items' were okay, I expected something more tailored.", | |
| ], | |
| "neg": [ | |
| "The recommendations are always the same items I already viewed.", | |
| "Suggested products were completely unrelated to what I bought.", | |
| "Recommendations feel generic and irrelevant, I ignored them all.", | |
| "Poor recommendations, they kept pushing items out of stock.", | |
| ], | |
| }, | |
| "checkout_flow": { | |
| "pos": [ | |
| "Checkout was smooth, only a few steps and payment worked first time.", | |
| "The checkout flow is simple and I paid with Apple Pay in seconds.", | |
| "Very easy checkout, the address was pre-filled and everything was clear.", | |
| "Smooth and quick checkout, exactly how online shopping should feel.", | |
| ], | |
| "neu": [ | |
| "Checkout worked but I had to create an account to finish.", | |
| "The flow is fine, though there were a couple of extra steps.", | |
| "Checkout was straightforward but the page reloaded a few times.", | |
| "Decent checkout, the delivery options could have been clearer.", | |
| ], | |
| "neg": [ | |
| "Checkout kept failing at the payment step, very frustrating.", | |
| "I had to re-enter my card details three times before it worked.", | |
| "The checkout flow is too long and I almost abandoned the order.", | |
| "Payment errors and no clear error message, a really poor experience.", | |
| ], | |
| }, | |
| "delivery_experience": { | |
| "pos": [ | |
| "Delivery arrived earlier than promised and was well packaged.", | |
| "Excellent delivery, tracking updated regularly and on time.", | |
| "My parcel arrived the next day, brilliant service.", | |
| "Delivery was quick and the courier was friendly and careful.", | |
| ], | |
| "neu": [ | |
| "Delivery took a couple of days longer than the estimate.", | |
| "The parcel arrived fine but the tracking stopped updating.", | |
| "Delivery was okay, packaging was a little damaged on the outside.", | |
| "Delivery was within the expected window, nothing special.", | |
| ], | |
| "neg": [ | |
| "My order was delayed by a week with no explanation at all.", | |
| "Tracking never updated and the parcel was left in the rain.", | |
| "The delivery arrived damaged and the box was completely crushed.", | |
| "Poor delivery experience, the courier did not even knock.", | |
| ], | |
| }, | |
| "after_sales_support": { | |
| "pos": [ | |
| "Customer support resolved my issue quickly and politely.", | |
| "The after-sales team replied within minutes and fixed everything.", | |
| "Excellent support, the agent went above and beyond to help me.", | |
| "My refund was processed fast and the support chat was helpful.", | |
| ], | |
| "neu": [ | |
| "Support answered my query but it took two days.", | |
| "The agent was polite but could not solve my problem directly.", | |
| "Support was okay, though I had to repeat my details a few times.", | |
| "Reasonable help, but the reply was a bit generic.", | |
| ], | |
| "neg": [ | |
| "I waited on hold for 40 minutes and then got cut off.", | |
| "After-sales support was useless, nobody responded to my email.", | |
| "My complaint was ignored for weeks and I got no refund.", | |
| "The support agent was unhelpful and I had to contact them three times.", | |
| ], | |
| }, | |
| }, | |
| "fr-FR": { | |
| "page_load_speed": { | |
| "pos": [ | |
| "Le site se charge instantanément, c'est vraiment très fluide.", | |
| "Les pages produits s'ouvrent très rapidement, bravo.", | |
| "La vitesse de chargement est excellente, même sur mobile.", | |
| "Le site est rapide et agréable à utiliser au quotidien.", | |
| ], | |
| "neu": [ | |
| "Le chargement est correct mais un peu lent sur la page d'accueil.", | |
| "Les pages mettent quelques secondes à s'afficher, ce n'est pas terrible.", | |
| "La vitesse est acceptable même si les images sont parfois lourdes.", | |
| "Les temps de chargement sont corrects, sans plus.", | |
| ], | |
| "neg": [ | |
| "La page de paiement a mis une éternité à charger, j'ai failli abandonner.", | |
| "Les pages produits sont très lentes en 4G, c'est frustrant.", | |
| "Le site a planté pendant les soldes, les pages ne se chargeaient pas.", | |
| "Le chargement est vraiment lent, les images arrivent trop tard.", | |
| ], | |
| }, | |
| "search_relevance": { | |
| "pos": [ | |
| "Les résultats de recherche étaient parfaits, exactement ce que je cherchais.", | |
| "La recherche comprend bien ce que je tape et propose d'excellents résultats.", | |
| "La pertinence des résultats est excellente, les filtres m'ont bien aidé.", | |
| "J'ai trouvé l'article en quelques secondes grâce aux suggestions.", | |
| ], | |
| "neu": [ | |
| "Les résultats sont corrects mais certains articles n'étaient pas pertinents.", | |
| "La recherche fonctionne mais ignore parfois mes fautes de frappe.", | |
| "Les résultats étaient acceptables, il a fallu chercher un peu.", | |
| "La recherche est correcte, sans plus.", | |
| ], | |
| "neg": [ | |
| "La recherche m'a renvoyé surtout des produits hors sujet.", | |
| "Le moteur de recherche semble ignorer complètement mes mots-clés.", | |
| "La pertinence est mauvaise, aucun résultat ne correspondait à ma demande.", | |
| "J'ai cherché une marque précise et j'ai eu des articles sans rapport.", | |
| ], | |
| }, | |
| "product_recommendations": { | |
| "pos": [ | |
| "Les recommandations sur la page d'accueil étaient vraiment utiles.", | |
| "J'ai adoré la section 'vous aimerez aussi', les suggestions étaient parfaites.", | |
| "Les recommandations correspondaient à mes goûts, j'ai ajouté deux articles.", | |
| "Les recommandations personnalisées étaient pertinentes et utiles.", | |
| ], | |
| "neu": [ | |
| "Les recommandations sont inégales, certaines utiles et d'autres non.", | |
| "Les suggestions sont correctes mais rien ne m'a vraiment attiré.", | |
| "Des recommandations raisonnables, bien que répétitives.", | |
| "Les articles associés étaient corrects, je m'attendais à mieux.", | |
| ], | |
| "neg": [ | |
| "Les recommandations sont toujours les mêmes articles déjà consultés.", | |
| "Les produits suggérés n'avaient rien à voir avec mon achat.", | |
| "Les recommandations sont génériques et sans intérêt.", | |
| "Mauvaises recommandations, on me proposait des articles en rupture.", | |
| ], | |
| }, | |
| "checkout_flow": { | |
| "pos": [ | |
| "Le paiement s'est fait en quelques clics, très simple et rapide.", | |
| "Le processus de commande est fluide, j'ai payé avec Apple Pay.", | |
| "Commande très facile, l'adresse était pré-remplie et tout était clair.", | |
| "Un parcours d'achat rapide et agréable, bravo.", | |
| ], | |
| "neu": [ | |
| "La commande a fonctionné mais j'ai dû créer un compte pour finir.", | |
| "Le parcours est correct avec quelques étapes de plus que prévu.", | |
| "Le paiement était simple mais la page s'est rechargée plusieurs fois.", | |
| "Un achat correct, les options de livraison étaient peu claires.", | |
| ], | |
| "neg": [ | |
| "Le paiement a échoué plusieurs fois, c'est très frustrant.", | |
| "J'ai dû saisir mes coordonnées bancaires trois fois.", | |
| "Le processus de commande est trop long, j'ai failli abandonner.", | |
| "Erreurs de paiement sans message clair, mauvaise expérience.", | |
| ], | |
| }, | |
| "delivery_experience": { | |
| "pos": [ | |
| "La livraison est arrivée en avance et bien emballée.", | |
| "Excellente livraison, le suivi était à jour et ponctuel.", | |
| "Mon colis est arrivé le lendemain, service impeccable.", | |
| "Livraison rapide et livreur très aimable.", | |
| ], | |
| "neu": [ | |
| "La livraison a pris quelques jours de plus que prévu.", | |
| "Le colis est arrivé mais le suivi ne se mettait plus à jour.", | |
| "Livraison correcte, l'emballage était un peu abîmé.", | |
| "Livraison dans les délais annoncés, sans surprise.", | |
| ], | |
| "neg": [ | |
| "Ma commande a été retardée d'une semaine sans aucune explication.", | |
| "Le suivi n'a jamais été mis à jour et le colis a été laissé sous la pluie.", | |
| "La livraison est arrivée endommagée, le carton était écrasé.", | |
| "Mauvaise expérience, le livreur n'a même pas sonné.", | |
| ], | |
| }, | |
| "after_sales_support": { | |
| "pos": [ | |
| "Le service client a répondu rapidement et résolu mon problème.", | |
| "L'équipe après-vente m'a répondu en quelques minutes.", | |
| "Excellent support, l'agent a fait tout son possible pour m'aider.", | |
| "Mon remboursement a été traité très vite, service réactif.", | |
| ], | |
| "neu": [ | |
| "Le support a répondu à ma demande mais après deux jours.", | |
| "L'agent était poli mais n'a pas pu résoudre mon problème.", | |
| "Le support était correct, même si j'ai dû répéter mes informations.", | |
| "Une aide correcte, mais la réponse était un peu générique.", | |
| ], | |
| "neg": [ | |
| "J'ai attendu 40 minutes au téléphone puis on m'a raccroché au nez.", | |
| "Le service après-vente est inutile, personne ne répond à mes e-mails.", | |
| "Ma réclamation a été ignorée pendant des semaines.", | |
| "L'agent n'était pas serviable, j'ai dû le contacter trois fois.", | |
| ], | |
| }, | |
| }, | |
| "de-DE": { | |
| "page_load_speed": { | |
| "pos": [ | |
| "Die Seite lädt sofort, wirklich sehr flüssig.", | |
| "Die Produktseiten öffnen sich sehr schnell, super.", | |
| "Die Ladezeit ist ausgezeichnet, auch mobil.", | |
| "Die Website ist schnell und angenehm zu nutzen.", | |
| ], | |
| "neu": [ | |
| "Das Laden ist in Ordnung, aber die Startseite könnte schneller sein.", | |
| "Die Seiten brauchen ein paar Sekunden, nicht schlimm aber ausbaufähig.", | |
| "Die Geschwindigkeit ist akzeptabel, die Bilder sind manchmal schwer.", | |
| "Die Ladezeiten sind okay, mehr aber auch nicht.", | |
| ], | |
| "neg": [ | |
| "Die Checkout-Seite hat eine Ewigkeit zum Laden gebraucht.", | |
| "Produktseiten sind im Mobilfunknetz extrem langsam, sehr nervig.", | |
| "Die Seite hing während des Sale und Seiten liefen in Timeouts.", | |
| "Das Laden ist richtig langsam, die Bilder kommen viel zu spät.", | |
| ], | |
| }, | |
| "search_relevance": { | |
| "pos": [ | |
| "Die Suchergebnisse waren punktgenau, genau was ich suchte.", | |
| "Die Suche versteht meine Eingaben und liefert tolle Treffer.", | |
| "Die Suchtreffer sind sehr relevant, die Filter haben mir geholfen.", | |
| "Ich habe den Artikel dank Suchvorschlägen in Sekunden gefunden.", | |
| ], | |
| "neu": [ | |
| "Die Ergebnisse sind okay, aber ein paar Artikel passten nicht.", | |
| "Die Suche funktioniert, ignoriert aber manchmal Tippfehler.", | |
| "Die Ergebnisse waren annehmbar, ich musste etwas suchen.", | |
| "Die Suche ist ganz ordentlich, aber nichts Besonderes.", | |
| ], | |
| "neg": [ | |
| "Die Suche lieferte überwiegend irrelevante Produkte.", | |
| "Die Suchmaschine scheint meine Suchbegriffe komplett zu ignorieren.", | |
| "Die Trefferqualität ist schlecht, kein Ergebnis passte zu meiner Anfrage.", | |
| "Ich suchte eine bestimmte Marke und bekam völlig andere Artikel.", | |
| ], | |
| }, | |
| "product_recommendations": { | |
| "pos": [ | |
| "Die Empfehlungen auf der Startseite waren wirklich nützlich.", | |
| "Ich liebe die Rubrik 'Das könnte Ihnen auch gefallen', perfekte Vorschläge.", | |
| "Die Empfehlungen passten zu meinem Geschmack, ich habe zwei Artikel ergänzt.", | |
| "Die personalisierten Empfehlungen waren relevant und hilfreich.", | |
| ], | |
| "neu": [ | |
| "Die Empfehlungen waren gemischt, manche nützlich, manche nicht.", | |
| "Die Vorschläge sind in Ordnung, aber nichts hat mich begeistert.", | |
| "Akzeptable Empfehlungen, auch wenn sich manche wiederholen.", | |
| "Die verwandten Artikel waren okay, ich hatte mehr erwartet.", | |
| ], | |
| "neg": [ | |
| "Die Empfehlungen sind immer dieselben Artikel, die ich schon angesehen habe.", | |
| "Die vorgeschlagenen Produkte hatten nichts mit meinem Kauf zu tun.", | |
| "Die Empfehlungen sind generisch und uninteressant.", | |
| "Schlechte Empfehlungen, mir wurden ständig ausverkaufte Artikel gezeigt.", | |
| ], | |
| }, | |
| "checkout_flow": { | |
| "pos": [ | |
| "Der Checkout war flüssig, wenige Schritte und die Zahlung klappte sofort.", | |
| "Der Bestellprozess ist einfach, ich habe mit Apple Pay in Sekunden bezahlt.", | |
| "Sehr einfache Bestellung, die Adresse war vorausgefüllt und alles klar.", | |
| "Schneller und angenehmer Checkout, so muss Online-Shopping sein.", | |
| ], | |
| "neu": [ | |
| "Die Bestellung funktionierte, aber ich musste ein Konto anlegen.", | |
| "Der Ablauf ist in Ordnung, auch wenn es ein paar Schritte mehr waren.", | |
| "Der Checkout war einfach, aber die Seite lud ein paar Mal neu.", | |
| "Ordentlicher Kauf, die Lieferoptionen waren aber unklar.", | |
| ], | |
| "neg": [ | |
| "Die Zahlung scheiterte mehrfach, sehr frustrierend.", | |
| "Ich musste meine Kartendaten dreimal eingeben.", | |
| "Der Bestellprozess ist zu lang, ich hätte fast abgebrochen.", | |
| "Zahlungsfehler ohne klare Meldung, eine wirklich schlechte Erfahrung.", | |
| ], | |
| }, | |
| "delivery_experience": { | |
| "pos": [ | |
| "Die Lieferung kam früher als erwartet und war gut verpackt.", | |
| "Ausgezeichnete Lieferung, die Sendungsverfolgung war aktuell.", | |
| "Mein Paket kam am nächsten Tag, großartiger Service.", | |
| "Schnelle Lieferung und ein freundlicher, sorgfältiger Bote.", | |
| ], | |
| "neu": [ | |
| "Die Lieferung dauerte ein paar Tage länger als angekündigt.", | |
| "Das Paket kam an, aber die Sendungsverfolgung blieb stehen.", | |
| "Die Lieferung war okay, die Verpackung war außen etwas beschädigt.", | |
| "Die Lieferung kam im erwarteten Zeitraum, nichts Besonderes.", | |
| ], | |
| "neg": [ | |
| "Meine Bestellung kam eine Woche zu spät ohne jede Erklärung.", | |
| "Die Sendungsverfolgung aktualisierte sich nie und das Paket lag im Regen.", | |
| "Die Lieferung kam beschädigt an, der Karton war völlig zerdrückt.", | |
| "Schlechte Lieferung, der Bote hat nicht einmal geklingelt.", | |
| ], | |
| }, | |
| "after_sales_support": { | |
| "pos": [ | |
| "Der Kundenservice hat mein Problem schnell und freundlich gelöst.", | |
| "Das After-Sales-Team antwortete innerhalb weniger Minuten.", | |
| "Ausgezeichneter Support, der Mitarbeiter hat sich sehr eingesetzt.", | |
| "Meine Erstattung wurde schnell bearbeitet, hilfreicher Chat.", | |
| ], | |
| "neu": [ | |
| "Der Support hat geantwortet, aber erst nach zwei Tagen.", | |
| "Der Mitarbeiter war freundlich, konnte mein Problem aber nicht lösen.", | |
| "Der Support war okay, ich musste meine Daten mehrfach wiederholen.", | |
| "Ordentliche Hilfe, aber die Antwort war etwas generisch.", | |
| ], | |
| "neg": [ | |
| "Ich hing 40 Minuten in der Warteschleife und wurde dann getrennt.", | |
| "Der After-Sales-Support ist nutzlos, niemand antwortet auf E-Mails.", | |
| "Meine Beschwerde wurde wochenlang ignoriert.", | |
| "Der Mitarbeiter war nicht hilfreich, ich musste dreimal anrufen.", | |
| ], | |
| }, | |
| }, | |
| } | |
| # Optional follow-up sentences (added ~35% of the time) for extra variety. | |
| FOLLOW_UPS = { | |
| "en-GB": [ | |
| "I use the site a few times a week on my phone.", | |
| "This is the second order I have placed this month.", | |
| "I would recommend the store to friends and family.", | |
| "I mainly shop during the weekend sales.", | |
| "The mobile app is my preferred way to order.", | |
| ], | |
| "fr-FR": [ | |
| "Je commande sur le site plusieurs fois par semaine.", | |
| "C'est ma deuxième commande ce mois-ci.", | |
| "Je recommande volontiers cette boutique à mes proches.", | |
| "Je fais mes achats surtout pendant les ventes du week-end.", | |
| "J'utilise surtout l'application mobile pour commander.", | |
| ], | |
| "de-DE": [ | |
| "Ich bestelle mehrmals pro Woche über die Website.", | |
| "Das ist meine zweite Bestellung in diesem Monat.", | |
| "Ich würde den Shop an Freunde und Familie weiterempfehlen.", | |
| "Ich kaufe vor allem an den Wochenenden im Sale ein.", | |
| "Ich bestelle am liebsten über die Mobile-App.", | |
| ], | |
| } | |
| # --------------------------------------------------------------------------- | |
| # PII scrubbing for free-text (GDPR) | |
| # --------------------------------------------------------------------------- | |
| PII_PATTERNS = [ | |
| re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}"), # email | |
| re.compile(r"(?<!\d)(?:\+?\d[\d\s().\-/]{7,}\d)(?!\d)"), # phone | |
| re.compile(r"\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b"), # UK postcode | |
| re.compile(r"\b\d{5}\b"), # FR postcode | |
| re.compile(r"\b\d{5}\b"), # DE postcode | |
| re.compile(r"\b(?:\d{4}[ -]?){3}\d{4}\b"), # card-like number | |
| ] | |
| PII_REDACTION = "[REDACTED]" | |
| def scrub_text(text: str) -> str: | |
| """Remove residual personal data from free text.""" | |
| scrubbed = text | |
| for pattern in PII_PATTERNS: | |
| scrubbed = pattern.sub(PII_REDACTION, scrubbed) | |
| return scrubbed | |
| # --------------------------------------------------------------------------- | |
| # Pseudonymisation helpers | |
| # --------------------------------------------------------------------------- | |
| def pseudonym(value: str, namespace: str) -> str: | |
| """Deterministic HMAC-SHA256 pseudonym (non-reversible without salt).""" | |
| digest = hmac.new( | |
| PSEUDO_SALT.encode("utf-8"), | |
| f"{namespace}:{value}".encode("utf-8"), | |
| hashlib.sha256, | |
| ).hexdigest() | |
| return digest[:16] | |
| def random_token(prefix: str, length: int = 12) -> str: | |
| alphabet = string.ascii_lowercase + string.digits | |
| return f"{prefix}-" + "".join(secrets.choice(alphabet) for _ in range(length)) | |
| # --------------------------------------------------------------------------- | |
| # Raw record generation (with fake PII - never published) | |
| # --------------------------------------------------------------------------- | |
| FIRST_NAMES = { | |
| "en-GB": ["Oliver", "Amelia", "George", "Sophie", "Jack", "Emily", "Harry", "Grace", "Charlie", "Freya"], | |
| "fr-FR": ["Lucas", "Emma", "Louis", "Jade", "Gabriel", "Louise", "Hugo", "Chloé", "Arthur", "Léa"], | |
| "de-DE": ["Jonas", "Mia", "Leon", "Emma", "Finn", "Lena", "Paul", "Hannah", "Elias", "Lea"], | |
| } | |
| LAST_NAMES = { | |
| "en-GB": ["Smith", "Jones", "Taylor", "Brown", "Williams", "Davies", "Evans", "Wilson"], | |
| "fr-FR": ["Martin", "Bernard", "Dubois", "Thomas", "Robert", "Richard", "Petit", "Durand"], | |
| "de-DE": ["Müller", "Schmidt", "Schneider", "Fischer", "Weber", "Meyer", "Wagner", "Becker"], | |
| } | |
| CITIES = { | |
| "en-GB": ["London", "Manchester", "Birmingham", "Leeds", "Glasgow", "Bristol", "Edinburgh"], | |
| "fr-FR": ["Paris", "Lyon", "Marseille", "Toulouse", "Nice", "Nantes", "Strasbourg"], | |
| "de-DE": ["Berlin", "München", "Hamburg", "Köln", "Frankfurt", "Stuttgart", "Düsseldorf"], | |
| } | |
| DOMAINS = ["example.com", "mail.test", "webmail.eu"] | |
| def fake_pii(lang: str, idx: int) -> dict: | |
| fn = random.choice(FIRST_NAMES[lang]) | |
| ln = random.choice(LAST_NAMES[lang]) | |
| email = f"{fn.lower()}.{ln.lower()}{idx}@{random.choice(DOMAINS)}" | |
| phone = "+44 7" + "".join(random.choices(string.digits, k=8)) | |
| if lang == "fr-FR": | |
| phone = "+33 6 " + "".join(random.choices(string.digits, k=8)) | |
| elif lang == "de-DE": | |
| phone = "+49 15" + "".join(random.choices(string.digits, k=8)) | |
| city = random.choice(CITIES[lang]) | |
| address = f"{random.randint(1, 240)} {random.choice(['High', 'Green', 'Station', 'Church', 'Market'])} {random.choice(['Street', 'Road', 'Lane', 'Avenue'])}, {city}" | |
| return { | |
| "user_email": email, | |
| "user_name": f"{fn} {ln}", | |
| "phone_number": phone, | |
| "address": address, | |
| } | |
| def generate_batch(lang: str, n: int, start_ts: datetime, end_ts: datetime, global_start_idx: int) -> list[dict]: | |
| """Generate n raw records for a language in a time window.""" | |
| market = next(m for m in MARKETS if m["language"] == lang) | |
| rows = [] | |
| delta = (end_ts - start_ts).total_seconds() | |
| for i in range(n): | |
| ts = start_ts + timedelta(seconds=random.random() * delta) | |
| dim = random.choice(DIMENSIONS) | |
| rating = random.choices([1, 2, 3, 4, 5], weights=[7, 12, 22, 33, 26])[0] | |
| band = "pos" if rating >= 4 else ("neu" if rating == 3 else "neg") | |
| text = random.choice(FEEDBACK[lang][dim][band]) | |
| if random.random() < 0.35: | |
| text += " " + random.choice(FOLLOW_UPS[lang]) | |
| pii = fake_pii(lang, global_start_idx + i) | |
| rows.append( | |
| { | |
| "user_id": f"user-{global_start_idx + i:07d}", | |
| "user_email": pii["user_email"], | |
| "user_name": pii["user_name"], | |
| "phone_number": pii["phone_number"], | |
| "address": pii["address"], | |
| "session_id_raw": f"session-{secrets.token_hex(8)}", | |
| "market_region": market["region"], | |
| "country_code": market["country_code"], | |
| "language": lang, | |
| "timestamp": ts.isoformat(timespec="seconds"), | |
| "experience_dimension": dim, | |
| "rating": rating, | |
| "feedback_text": text, | |
| "device_type": random.choice(DEVICE_TYPES), | |
| "source_channel": random.choice(SOURCE_CHANNELS), | |
| } | |
| ) | |
| return rows | |
| def anonymise(raw_rows: list[dict]) -> pd.DataFrame: | |
| """GDPR pipeline: drop direct PII, pseudonymise IDs, scrub free text.""" | |
| out = [] | |
| for r in raw_rows: | |
| out.append( | |
| { | |
| "feedback_id": random_token("F", 12).upper(), | |
| "user_pseudo_id": pseudonym(r["user_id"], "user"), | |
| "session_id": pseudonym(r["session_id_raw"], "session"), | |
| "market_region": r["market_region"], | |
| "country_code": r["country_code"], | |
| "language": r["language"], | |
| "timestamp": r["timestamp"], | |
| "experience_dimension": r["experience_dimension"], | |
| "rating": int(r["rating"]), | |
| "feedback_text": scrub_text(r["feedback_text"]), | |
| "device_type": r["device_type"], | |
| "source_channel": r["source_channel"], | |
| } | |
| ) | |
| df = pd.DataFrame(out) | |
| # Enforce column order and UTF-8 | |
| cols = [ | |
| "feedback_id", "user_pseudo_id", "session_id", "market_region", | |
| "country_code", "language", "timestamp", "experience_dimension", | |
| "rating", "feedback_text", "device_type", "source_channel", | |
| ] | |
| df = df[cols] | |
| # Ensure feedback_text is truly str and UTF-8 clean | |
| df["feedback_text"] = df["feedback_text"].astype(str).apply( | |
| lambda s: s.encode("utf-8", errors="replace").decode("utf-8") | |
| ) | |
| return df | |
| def sha256_file(path: str) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for chunk in iter(lambda: f.read(65536), b""): | |
| h.update(chunk) | |
| return h.hexdigest() | |
| def write_snapshot(df: pd.DataFrame, version: str, window_label: str, window_start: str, window_end: str, added: int): | |
| os.makedirs(os.path.join(SNAPSHOT_DIR, version), exist_ok=True) | |
| parquet_path = os.path.join(SNAPSHOT_DIR, version, f"ux_feedback_{version}.parquet") | |
| csv_path = os.path.join(SNAPSHOT_DIR, version, f"ux_feedback_{version}.csv") | |
| df.to_parquet(parquet_path, index=False) | |
| df.to_csv(csv_path, index=False, encoding="utf-8") | |
| # canonical 'current' files at data/ | |
| os.makedirs(DATA_DIR, exist_ok=True) | |
| df.to_parquet(os.path.join(DATA_DIR, "ux_feedback_live.parquet"), index=False) | |
| df.to_csv(os.path.join(DATA_DIR, "ux_feedback_live.csv"), index=False, encoding="utf-8") | |
| return { | |
| "version": version, | |
| "window_label": window_label, | |
| "window_start_utc": window_start, | |
| "window_end_utc": window_end, | |
| "records_added": added, | |
| "total_records": int(len(df)), | |
| "sha256_parquet": sha256_file(parquet_path), | |
| "sha256_csv": sha256_file(csv_path), | |
| "parquet_path": f"snapshots/{version}/ux_feedback_{version}.parquet", | |
| "csv_path": f"snapshots/{version}/ux_feedback_{version}.csv", | |
| "canonical_parquet": "data/ux_feedback_live.parquet", | |
| "canonical_csv": "data/ux_feedback_live.csv", | |
| "gdpr_anonymised": True, | |
| "pii_fields_dropped": ["user_id", "user_email", "user_name", "phone_number", "address"], | |
| } | |
| def main(): | |
| random.seed(20260813) | |
| rng_state = random.getstate() | |
| now = datetime.now(timezone.utc) | |
| base_now = now.replace(second=0, microsecond=0) | |
| # Version schedule (30-minute refresh cadence) | |
| schedule = [ | |
| # (version, window_label, start, end, records_to_generate) | |
| ("v1.0.0", "initial_release", base_now - timedelta(hours=24), base_now, 5000), | |
| ("v1.1.0", "update_30min", base_now, base_now + timedelta(minutes=30), 750), | |
| ("v1.2.0", "update_60min", base_now + timedelta(minutes=30), base_now + timedelta(minutes=60), 750), | |
| ] | |
| # Raw records per language so each market is represented in every window | |
| manifest_versions = [] | |
| cumulative_raw: list[dict] = [] | |
| # Also keep a raw (PII) dump ONLY to demonstrate the pipeline internally. | |
| os.makedirs(RAW_DIR, exist_ok=True) | |
| raw_log_path = os.path.join(RAW_DIR, "raw_with_pii_sample.jsonl") | |
| with open(raw_log_path, "w", encoding="utf-8") as raw_log: | |
| for version, label, wstart, wend, total in schedule: | |
| n_per_lang = total // len(MARKETS) | |
| raw_batch = [] | |
| for m in MARKETS: | |
| raw_batch.extend(generate_batch(m["language"], n_per_lang, wstart, wend, len(cumulative_raw) + len(raw_batch))) | |
| random.setstate(rng_state) | |
| random.shuffle(raw_batch) | |
| cumulative_raw.extend(raw_batch) | |
| for row in raw_batch: | |
| raw_log.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| df = anonymise(cumulative_raw) | |
| info = write_snapshot( | |
| df, version, label, | |
| wstart.isoformat(timespec="seconds"), | |
| wend.isoformat(timespec="seconds"), | |
| added=len(raw_batch), | |
| ) | |
| manifest_versions.append(info) | |
| print(f"[{version}] window={label} added={info['records_added']} total={info['total_records']}") | |
| # Write the version manifest + changelog | |
| os.makedirs(VERSION_DIR, exist_ok=True) | |
| manifest = { | |
| "dataset": "EU-Retail-UX-Feedback-Live", | |
| "description": "Live, GDPR-anonymised user-experience feedback from EU e-commerce retail (UK, FR, DE).", | |
| "refresh_cadence_minutes": 30, | |
| "encoding": "UTF-8", | |
| "languages": ["en-GB", "fr-FR", "de-DE"], | |
| "markets": ["United Kingdom", "France", "Germany"], | |
| "pii_handling": "deleted_and_pseudonymised", | |
| "latest_version": manifest_versions[-1]["version"], | |
| "versions": manifest_versions, | |
| } | |
| with open(os.path.join(VERSION_DIR, "manifest.json"), "w", encoding="utf-8") as f: | |
| json.dump(manifest, f, ensure_ascii=False, indent=2) | |
| changelog_lines = [ | |
| "# Changelog - EU-Retail-UX-Feedback-Live", | |
| "", | |
| "This dataset is refreshed every 30 minutes. Every published snapshot is", | |
| "immutable, checksummed (SHA-256) and tagged so that any previous version", | |
| "can be restored (rollback).", | |
| "", | |
| ] | |
| for v in manifest_versions: | |
| changelog_lines.append( | |
| f"## {v['version']} - {v['window_label']}\n" | |
| f"- Window: {v['window_start_utc']} -> {v['window_end_utc']} UTC\n" | |
| f"- Records added: {v['records_added']} | Total records: {v['total_records']}\n" | |
| f"- SHA-256 (parquet): `{v['sha256_parquet']}`\n" | |
| f"- SHA-256 (csv): `{v['sha256_csv']}`\n" | |
| ) | |
| with open(os.path.join(VERSION_DIR, "CHANGELOG.md"), "w", encoding="utf-8") as f: | |
| f.write("\n".join(changelog_lines)) | |
| # Summary printout | |
| print("\n=== SUMMARY ===") | |
| print(json.dumps(manifest, indent=2, ensure_ascii=False)) | |
| print("\nFiles written under:", BASE_DIR) | |
| if __name__ == "__main__": | |
| main() | |