Spaces:
Sleeping
Sleeping
Download app.py from Daaviid354541/mindstack-tracker: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/Daaviid354541/mindstack-tracker/resolve/main/app.py
- Command line
-
hf download hf://spaces/Daaviid354541/mindstack-tracker/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Daaviid354541/mindstack-tracker/resolve/main/app.py
12.2 kB
| """ | |
| app.py β Backend Flask Mindstack Tracker v2 β CORRIGΓ | |
| Corrections vs version originale : | |
| 1. Assignation A/B cΓ΄tΓ© BACKEND (plus cΓ΄tΓ© client) β Γ©limine le confounding | |
| 2. Persistance HF Dataset optionnelle via huggingface_hub | |
| 3. Timestamp ISO avec timezone UTC explicite | |
| 4. Validation stricte des types entrants | |
| 5. Route /ab-assign sΓ©parΓ©e pour assignation propre | |
| 6. Headers CORS restreints (pas wildcard en prod) | |
| """ | |
| import os, csv, json, pathlib, hashlib, secrets | |
| from datetime import datetime, timezone | |
| from flask import Flask, request, jsonify, send_from_directory | |
| from flask_cors import CORS | |
| app = Flask(__name__, static_folder="static") | |
| # ββ CORS : restreindre Γ ton domaine en prod ββββββββββββββββββββββββ | |
| ALLOWED_ORIGINS = os.environ.get( | |
| "ALLOWED_ORIGINS", | |
| "*" # remplacer par "https://ton-site.com" en production | |
| ) | |
| CORS(app, origins=ALLOWED_ORIGINS) | |
| # ββ Persistance βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| DATA_DIR = pathlib.Path("data") | |
| DATA_DIR.mkdir(exist_ok=True) | |
| CSV_PATH = DATA_DIR / "events.csv" | |
| # Persistance HuggingFace Dataset (optionnelle) | |
| HF_TOKEN = os.environ.get("HF_TOKEN") | |
| HF_DATASET_REPO = os.environ.get("HF_DATASET_REPO") # ex: "username/mindstack-data" | |
| HF_PUSH_EVERY = int(os.environ.get("HF_PUSH_EVERY", "50")) # push toutes les N lignes | |
| _event_counter = 0 | |
| COLUMNS = [ | |
| "timestamp", "session_id", "event", | |
| "os", "source", | |
| "scroll_depth", "temps_page_s", | |
| "est_retour", "multi_session", "nav_profonde", | |
| "panier_abandonne", "nb_clics", | |
| "multiplicateur", "segment", "ab_variant", | |
| "product_id", "prix", "prix_base", | |
| "ip_hash", | |
| ] | |
| def init_csv(): | |
| if not CSV_PATH.exists(): | |
| with open(CSV_PATH, "w", newline="", encoding="utf-8") as f: | |
| csv.DictWriter(f, fieldnames=COLUMNS).writeheader() | |
| init_csv() | |
| # ββ Utilitaires βββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def anonymize_ip(ip: str) -> str: | |
| """Hash les 2 premiers octets uniquement (RGPD-compatible).""" | |
| parts = ip.split(".") | |
| prefix = ".".join(parts[:2]) if len(parts) == 4 else ip[:8] | |
| return hashlib.sha256(prefix.encode()).hexdigest()[:8] # sha256 > md5 | |
| def safe_bool(val) -> bool: | |
| if isinstance(val, bool): return val | |
| if isinstance(val, str): return val.lower() in ("true", "1", "yes") | |
| return bool(val) | |
| def safe_float(val, default=0.0, lo=None, hi=None) -> float: | |
| try: | |
| v = float(val) | |
| except (TypeError, ValueError): | |
| v = default | |
| if lo is not None: v = max(lo, v) | |
| if hi is not None: v = min(hi, v) | |
| return v | |
| def safe_int(val, default=0, lo=None, hi=None) -> int: | |
| try: | |
| v = int(val) | |
| except (TypeError, ValueError): | |
| v = default | |
| if lo is not None: v = max(lo, v) | |
| if hi is not None: v = min(hi, v) | |
| return v | |
| def push_to_hf(): | |
| """Push le CSV vers HuggingFace Dataset pour persistance cross-restart.""" | |
| if not HF_TOKEN or not HF_DATASET_REPO: | |
| return | |
| try: | |
| from huggingface_hub import HfApi | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=str(CSV_PATH), | |
| path_in_repo="events.csv", | |
| repo_id=HF_DATASET_REPO, | |
| repo_type="dataset", | |
| token=HF_TOKEN, | |
| commit_message=f"auto-push {datetime.now(timezone.utc).isoformat()}" | |
| ) | |
| except Exception as e: | |
| app.logger.warning(f"HF push failed: {e}") | |
| # ββ A/B assignment : CΓTΓ BACKEND βββββββββββββββββββββββββββββββββββ | |
| # L'assignation est dΓ©terministe par session_id (pas alΓ©atoire Γ chaque req) | |
| # mais indΓ©pendante de tout signal comportemental β pas de confounding | |
| AB_VARIANTS = ["A", "B", "C"] | |
| AB_WEIGHTS = [0.40, 0.40, 0.20] # 40% A, 40% B, 20% C | |
| _ab_cache: dict[str, str] = {} # session_id β variant (in-memory, suffit) | |
| def assign_ab(session_id: str) -> str: | |
| """Assignation stable et non-biaisΓ©e par session_id.""" | |
| if session_id in _ab_cache: | |
| return _ab_cache[session_id] | |
| # Hash dΓ©terministe du session_id β bucket 0-99 | |
| h = int(hashlib.sha256(session_id.encode()).hexdigest(), 16) % 100 | |
| cumul = 0 | |
| for variant, w in zip(AB_VARIANTS, [int(x*100) for x in AB_WEIGHTS]): | |
| cumul += w | |
| if h < cumul: | |
| _ab_cache[session_id] = variant | |
| return variant | |
| _ab_cache[session_id] = AB_VARIANTS[-1] | |
| return AB_VARIANTS[-1] | |
| # ββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def ab_assign(): | |
| """ | |
| Le frontend appelle cette route AU CHARGEMENT pour obtenir son variant. | |
| GET /ab-assign?session_id=<uuid> | |
| Retourne : {"ab_variant": "A"} | |
| """ | |
| session_id = request.args.get("session_id", "")[:36] | |
| if not session_id: | |
| return jsonify({"error": "session_id required"}), 400 | |
| return jsonify({"ab_variant": assign_ab(session_id)}) | |
| def track(): | |
| global _event_counter | |
| if request.method == "OPTIONS": | |
| return jsonify({}), 200 | |
| try: | |
| data = request.get_json(force=True, silent=True) or {} | |
| except Exception: | |
| return jsonify({"error": "invalid json"}), 400 | |
| session_id = str(data.get("session_id", ""))[:36] | |
| # ββ RΓ©cupΓ©rer le variant depuis le backend (source de vΓ©ritΓ©) ββ | |
| # Le client peut envoyer ab_variant mais on l'Γ©crase par la valeur backend | |
| ab_variant_backend = assign_ab(session_id) if session_id else "A" | |
| row = { | |
| "timestamp" : datetime.now(timezone.utc).isoformat(), | |
| "session_id" : session_id, | |
| "event" : str(data.get("event", "unknown"))[:32], | |
| "os" : str(data.get("os", ""))[:16], | |
| "source" : str(data.get("source", "direct"))[:32], | |
| "scroll_depth" : round(safe_float(data.get("scroll_depth"), 0.0, 0.0, 1.0), 3), | |
| "temps_page_s" : safe_int(data.get("temps_page_s"), 0, 0, 7200), | |
| "est_retour" : safe_bool(data.get("est_retour", False)), | |
| "multi_session" : safe_bool(data.get("multi_session", False)), | |
| "nav_profonde" : safe_int(data.get("nav_profonde"), 1, 1, 100), | |
| "panier_abandonne": safe_bool(data.get("panier_abandonne", False)), | |
| "nb_clics" : safe_int(data.get("nb_clics"), 0, 0, 9999), | |
| "multiplicateur" : round(safe_float(data.get("multiplicateur"), 1.0, 0.5, 3.0), 3), | |
| "segment" : str(data.get("segment", "standard"))[:32], | |
| "ab_variant" : ab_variant_backend, # β BACKEND, pas client | |
| "product_id" : str(data.get("product_id", ""))[:32], | |
| "prix" : round(safe_float(data.get("prix"), 0.0, 0.0, 9999.0), 2), | |
| "prix_base" : round(safe_float(data.get("prix_base"), 0.0, 0.0, 9999.0), 2), | |
| "ip_hash" : anonymize_ip(request.remote_addr or "0.0.0.0"), | |
| } | |
| with open(CSV_PATH, "a", newline="", encoding="utf-8") as f: | |
| csv.DictWriter(f, fieldnames=COLUMNS).writerow(row) | |
| _event_counter += 1 | |
| if _event_counter % HF_PUSH_EVERY == 0: | |
| push_to_hf() | |
| return jsonify({"status": "ok", "ab_variant": ab_variant_backend}), 200 | |
| def download_csv(): | |
| return send_from_directory(DATA_DIR, "events.csv", as_attachment=True, mimetype="text/csv") | |
| def stats(): | |
| if not CSV_PATH.exists(): | |
| return jsonify({"total": 0}) | |
| rows = [] | |
| with open(CSV_PATH, "r", encoding="utf-8") as f: | |
| rows = list(csv.DictReader(f)) | |
| if not rows: | |
| return jsonify({"total": 0}) | |
| from collections import Counter, defaultdict | |
| sessions = {} | |
| for r in rows: | |
| sid = r["session_id"] | |
| if sid not in sessions: | |
| sessions[sid] = { | |
| "os": r["os"], "source": r["source"], | |
| "est_retour": r["est_retour"] == "True", | |
| "segment": r["segment"], | |
| "ab_variant": r["ab_variant"], | |
| "scroll_max": 0, "temps_max": 0, | |
| "panier": False, "achat": False, | |
| "mult_max": 1.0, "prix_max": 0, | |
| "first_ts": r["timestamp"], | |
| } | |
| s = sessions[sid] | |
| s["scroll_max"] = max(s["scroll_max"], float(r["scroll_depth"] or 0)) | |
| s["temps_max"] = max(s["temps_max"], int(r["temps_page_s"] or 0)) | |
| s["mult_max"] = max(s["mult_max"], float(r["multiplicateur"] or 1)) | |
| if r["event"] == "panier": s["panier"] = True | |
| if r["event"] == "achat": | |
| s["achat"] = True | |
| s["prix_max"] = float(r["prix"] or 0) | |
| sess_list = list(sessions.values()) | |
| n = len(sess_list) | |
| n_panier = sum(1 for s in sess_list if s["panier"]) | |
| n_achat = sum(1 for s in sess_list if s["achat"]) | |
| revenu = sum(s["prix_max"] for s in sess_list if s["achat"]) | |
| os_counts = dict(Counter(s["os"] for s in sess_list)) | |
| src_counts = dict(Counter(s["source"] for s in sess_list)) | |
| seg_counts = dict(Counter(s["segment"] for s in sess_list)) | |
| ab_counts = dict(Counter(s["ab_variant"] for s in sess_list)) | |
| # Taux de conversion par variant A/B (mΓ©trique principale anti-biais) | |
| ab_sessions = defaultdict(int) | |
| ab_achats = defaultdict(int) | |
| ab_rev = defaultdict(list) | |
| for s in sess_list: | |
| v = s["ab_variant"] | |
| ab_sessions[v] += 1 | |
| if s["achat"]: | |
| ab_achats[v] += 1 | |
| ab_rev[v].append(s["prix_max"]) | |
| ab_taux_conv = { | |
| k: round(ab_achats[k] / ab_sessions[k] * 100, 2) | |
| for k in ab_sessions if ab_sessions[k] > 0 | |
| } | |
| ab_rev_avg = {k: round(sum(v)/len(v), 2) for k, v in ab_rev.items() if v} | |
| scroll_avg = sum(s["scroll_max"] for s in sess_list) / n if n else 0 | |
| temps_avg = sum(s["temps_max"] for s in sess_list) / n if n else 0 | |
| mult_avg = sum(s["mult_max"] for s in sess_list) / n if n else 1.0 | |
| hourly = defaultdict(int) | |
| for r in rows: | |
| try: hourly[r["timestamp"][:13]] += 1 | |
| except: pass | |
| product_rev = defaultdict(float) | |
| product_cnt = defaultdict(int) | |
| for r in rows: | |
| if r["event"] == "achat" and r["product_id"]: | |
| product_rev[r["product_id"]] += float(r["prix"] or 0) | |
| product_cnt[r["product_id"]] += 1 | |
| return jsonify({ | |
| "total_sessions" : n, | |
| "total_events" : len(rows), | |
| "n_panier" : n_panier, | |
| "n_achat" : n_achat, | |
| "taux_panier" : round(n_panier/n*100, 1) if n else 0, | |
| "taux_achat" : round(n_achat/n*100, 1) if n else 0, | |
| "revenu_total" : round(revenu, 2), | |
| "scroll_moyen" : round(scroll_avg*100, 1), | |
| "temps_moyen_s" : round(temps_avg), | |
| "mult_moyen" : round(mult_avg, 3), | |
| "os_distribution" : os_counts, | |
| "src_distribution": src_counts, | |
| "seg_distribution": seg_counts, | |
| "ab_distribution" : ab_counts, | |
| "ab_taux_conv" : ab_taux_conv, # β nouveau : taux conv par variant | |
| "ab_rev_moyen" : ab_rev_avg, | |
| "product_revenue" : dict(product_rev), | |
| "product_count" : dict(product_cnt), | |
| "hourly" : [{"h": k, "n": v} for k, v in sorted(hourly.items())[-48:]], | |
| }) | |
| def dashboard(): | |
| return send_from_directory("static", "dashboard.html") | |
| def index(): | |
| return jsonify({ | |
| "status": "ok", | |
| "version": "2.1-antibiais", | |
| "routes": ["/ab-assign", "/track", "/stats", "/dashboard", "/data/events.csv"] | |
| }) | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 7860)) | |
| app.run(host="0.0.0.0", port=port, debug=False) | |