File size: 12,179 Bytes
b4475e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
"""
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 ──────────────────────────────────────────────────────────

@app.route("/ab-assign", methods=["GET"])
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)})


@app.route("/track", methods=["POST", "OPTIONS"])
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


@app.route("/data/events.csv")
def download_csv():
    return send_from_directory(DATA_DIR, "events.csv", as_attachment=True, mimetype="text/csv")


@app.route("/stats")
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:]],
    })


@app.route("/dashboard")
def dashboard():
    return send_from_directory("static", "dashboard.html")


@app.route("/")
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)