Download platform/modules/pdp_search_rivals.py from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 21.5 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/platform/modules/pdp_search_rivals.py
- Command line
-
hf download hf://spaces/fsanyoto/loopable/platform/modules/pdp_search_rivals.py
-
curl -L -o pdp_search_rivals.py https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/platform/modules/pdp_search_rivals.py
21.5 kB
| """Build PDP rival research from scoped search history and injected stored-page readers.""" | |
| import calendar | |
| import contextlib | |
| import datetime as dt | |
| import math | |
| import re | |
| from modules import pdp_search_model as model | |
| BA_TABLE = "amzn_brand_analytics" | |
| LISTINGS = "amzn_listings" | |
| F9 = model.FIELDS[:9] | |
| FILL84 = set("your more with this that from have each also these their they will into only than very " | |
| "make made over most every what when just other".split()) | |
| PROMO = {model.stemW(w) for w in "clearance sale discount cheap cheapest free best bestseller deal offer guarantee".split()} | |
| ACTIONS = { | |
| "WinBoth": "Keep it.", "LoseClick": "Win the click: main image, price, title start.", | |
| "LoseSale": "Fix the page: price, reviews, bullets.", "LoseBoth": "Price and reviews first.", | |
| "Thin": "Pick a longer time frame for a verdict.", "NotSeen": "Ranking or ads, not words.", | |
| } | |
| DESCRIPTION_LIMIT = "Stored competitor pages provide titles and bullets, but no description." | |
| WEEKLY = ("isfinite(TRY_CAST(_period_start AS TIMESTAMP)) AND " | |
| "isfinite(TRY_CAST(_period_end AS TIMESTAMP)) AND " | |
| "date_diff('day', TRY_CAST(_period_start AS DATE), TRY_CAST(_period_end AS DATE))=6") | |
| def _scoped_reader(cur, source_scope=None): | |
| from core.perm_scope import app_source_cursor | |
| from harness.runtime import mirror_cursor | |
| owned = not hasattr(cur, "execute") | |
| raw = mirror_cursor(cur) if owned else cur | |
| try: | |
| with app_source_cursor(raw, (BA_TABLE, LISTINGS), source_scope) as scoped: | |
| yield scoped | |
| finally: | |
| if owned: | |
| raw.close() | |
| def _own_asins(cur, candidates): | |
| if not candidates: | |
| return set() | |
| candidates = sorted(set(candidates)) | |
| placeholders = ",".join("?" for _ in candidates) | |
| return {str(a).strip() for (a,) in cur.execute( | |
| f"SELECT DISTINCT asin1 FROM {LISTINGS} WHERE asin1 IN ({placeholders})", candidates).fetchall()} | |
| def _read_ba(cur, queries, start, end): | |
| if not queries: | |
| return [] | |
| placeholders = ",".join("?" for _ in queries) | |
| return cur.execute( | |
| f"SELECT search_term, clicked_asin, clicked_item_name, " | |
| f"CAST(_period_start AS DATE), CAST(_period_end AS DATE), " | |
| f"TRY_CAST(click_share AS DOUBLE), TRY_CAST(conversion_share AS DOUBLE) " | |
| f"FROM {BA_TABLE} WHERE search_term IN ({placeholders}) AND {WEEKLY} " | |
| "AND TRY_CAST(_period_start AS DATE)>=CAST(? AS DATE) AND TRY_CAST(_period_end AS DATE)<=CAST(? AS DATE) " | |
| "AND TRY_CAST(click_share_rank AS INTEGER) BETWEEN 1 AND 3 AND clicked_asin IS NOT NULL " | |
| "ORDER BY search_term, _period_start, click_share_rank, clicked_asin", | |
| [*queries, start, end]).fetchall() | |
| def _average_top(records, own): | |
| searches = {} | |
| for query, asin, name, start, end, cs, vs in records: | |
| search = searches.setdefault(query, {"weeks": set(), "ends": [], "asins": {}}) | |
| search["weeks"].add(str(start)) | |
| search["ends"].append(str(end)) | |
| item = search["asins"].setdefault(asin, {"asin": asin, "name": name or "", "cs": [], "vs": [], "in": set()}) | |
| item["name"] = name or item["name"] | |
| item["in"].add(str(start)) | |
| for key, value in (("cs", cs), ("vs", vs)): | |
| if value is not None and math.isfinite(value): | |
| item[key].append(float(value) / 100) | |
| out = {} | |
| for query, search in searches.items(): | |
| items = [{**item, **{k: sum(item[k]) / len(item[k]) if item[k] else None for k in ("cs", "vs")}, | |
| "in": len(item["in"]), "ours": item["asin"] in own} for item in search["asins"].values()] | |
| items = sorted((x for x in items if x["cs"] is not None), key=lambda x: (-x["cs"], x["asin"])) | |
| out[query] = {"week": [min(search["weeks"]), max(search["ends"])], "weeks": len(search["weeks"]), | |
| "top": [{**item, "n": i + 1} for i, item in enumerate(items[:3])]} | |
| return out | |
| def top_clicked(cur, queries, start, end, *, source_scope=None): | |
| """Average each clicked ASIN's reported shares over every complete week inside the window.""" | |
| with _scoped_reader(cur, source_scope) as scoped: | |
| records = _read_ba(scoped, queries, start, end) | |
| return _average_top(records, _own_asins(scoped, [r[1] for r in records])) | |
| def validate_top(cur, q, weeks, *, source_scope=None): | |
| """Tie each ASIN's click share to an independent SQL AVG for the exact requested weeks.""" | |
| weeks = sorted(set(weeks)) | |
| if not weeks: | |
| return {"ok": False, "checks": {"top clicked ties": False}, "actual": {}, "expected": {}} | |
| with _scoped_reader(cur, source_scope) as scoped: | |
| end = str(dt.date.fromisoformat(weeks[-1]) + dt.timedelta(days=6)) | |
| records = [r for r in _read_ba(scoped, [q], weeks[0], end) if str(r[3]) in weeks] | |
| averaged = _average_top(records, set()).get(q, {}) | |
| actual = {r["asin"]: r["cs"] for r in averaged.get("top", [])} | |
| placeholders = ",".join("?" for _ in weeks) | |
| expected_rows = scoped.execute( | |
| f"SELECT clicked_asin, AVG(TRY_CAST(click_share AS DOUBLE))/100, " | |
| f"COUNT(DISTINCT TRY_CAST(_period_start AS DATE)) FROM {BA_TABLE} " | |
| f"WHERE search_term=? AND {WEEKLY} AND TRY_CAST(_period_start AS DATE) IN ({placeholders}) " | |
| "AND TRY_CAST(click_share_rank AS INTEGER) BETWEEN 1 AND 3 AND clicked_asin IS NOT NULL " | |
| "GROUP BY clicked_asin ORDER BY 2 DESC NULLS LAST, clicked_asin LIMIT 3", [q, *weeks]).fetchall() | |
| expected = {a: share for a, share, _ in expected_rows} | |
| counts = {r["asin"]: r["in"] for r in averaged.get("top", [])} | |
| ties = bool(actual) and actual.keys() == expected.keys() and all( | |
| value is not None and abs(actual[a] - value) <= 1e-9 for a, value in expected.items()) | |
| ties = ties and all(counts[a] == count for a, _, count in expected_rows) | |
| return {"ok": ties, "checks": {"top clicked ties": ties}, "actual": actual, "expected": expected} | |
| def _span(ba): | |
| if not ba: | |
| return "" | |
| days = [dt.date.fromisoformat(x) for x in ba["week"]] | |
| return " to ".join(f"{calendar.month_abbr[d.month]} {d.day}" for d in days) + f", {ba['weeks']} weeks averaged" | |
| def Versus61(listing, rows, context): | |
| ba = context.get("BA57", {}) | |
| selected = sorted((r for r in rows if ba.get(r["q"], {}).get("top")), key=lambda r: -r["vol"]) | |
| return {"list": [{"q": r["q"], "vol": r["vol"], "cs": r["cs"], "ps": r["ps"], **ba[r["q"]]} for r in selected], | |
| "tot": sum(r["vol"] for r in rows), "top": max([1, *(r["vol"] for r in rows)]), | |
| "span": _span(ba[selected[0]["q"]]) if selected else ""} | |
| def titleText84(listing, asin, context): | |
| source = context.get("live", {}) if asin == listing["asin"] else context.get("meta", {}) | |
| return source.get(asin, {}).get("title", "") | |
| def pageText84(listing, asin, context): | |
| source = context.get("live", {}) if asin == listing["asin"] else context.get("meta", {}) | |
| return " ".join([titleText84(listing, asin, context), *source.get(asin, {}).get("bullets", [])]) | |
| def carry84(q, title, page): | |
| keys = model.qWords(q) | |
| if not keys: | |
| return "none" | |
| title_words, page_words = model.wordsOf(title), model.wordsOf(page) | |
| return "title" if all(k in title_words for k in keys) else "page" if all(k in page_words for k in keys) else ( | |
| "some" if any(k in page_words for k in keys) else "none") | |
| def rank84(q, asin, context): | |
| return next((r for r in context.get("BA57", {}).get(q, {}).get("top", []) if r["asin"] == asin), None) | |
| def _picks(picks, context): | |
| return [a for a in picks if a in context.get("meta", {})] | |
| def Targets84(listing, rows, picks, context): | |
| ps, ba = _picks(picks, context), context.get("BA57", {}) | |
| sellers = [listing["asin"], *ps] | |
| carry = lambda q, a: carry84(q, titleText84(listing, a, context), pageText84(listing, a, context)) | |
| queries = [q for q in ba if any(r["q"] == q for r in rows)] | |
| ranked = [carry84(q, c.get("name", ""), c.get("name", "")) for q in queries for c in ba[q].get("top", [])] | |
| pairs = [(carry(q, a), rank84(q, a, context) is not None) for q in queries for a in ps] | |
| rates = [[top for c, top in pairs if (c == "title") == inside] for inside in (True, False)] | |
| selected = sorted((r for r in rows if model.fitState63(listing, r["q"], context) == "fit"), key=lambda r: -r["vol"])[:25] | |
| out = [] | |
| for row in selected: | |
| q = row["q"] | |
| n = sum(carry(q, a) == "title" for a in ps) | |
| verdict = (["Contested", "is-mid"] if n else ["Only you", "is-good"]) if carry(q, listing["asin"]) == "title" else ( | |
| ["Gap: they target it", "is-act"] if n >= 2 else ["One of them targets it", "is-watch"] if n == 1 else ["Open", "is-good"]) | |
| out.append({"q": q, "vol": row["vol"], "ranksRead": q in ba, "verdict": verdict, | |
| "cells": [{"a": a, "c": carry(q, a), "rank": rank84(q, a, context)} for a in sellers]}) | |
| return {"list": out, "sellers": sellers, "tot": sum(r["vol"] for r in rows), | |
| "top": max([1, *(r["vol"] for r in rows)]), "ranked": len(ranked), "rTitle": ranked.count("title"), | |
| **{k: [sum(xs), len(xs)] if xs else None for k, xs in zip(("rIn", "rOut"), rates)}} | |
| def Cannibal84(listing, per, context): | |
| own, groups = context["rows"], [] | |
| for q in own.get(listing["asin"], []): | |
| sources = [(a, next((r for r in rows if r["q"] == q["q"]), None)) for a, rows in own.items()] | |
| rs = [{"a": a, **model.rate55(v)} for a, src in sources if src is not None | |
| and (v := model.v55(src, per, context)) is not None] | |
| if len(rs) < 2: | |
| continue | |
| best = sorted(rs, key=lambda r: (-(r["ps"] or 0), -(r["cs"] or 0)))[0] | |
| sold, mine = (best["ps"] or best["cs"] or 0) > 0, best["a"] == listing["asin"] | |
| action = "Watch: none of them sells on it yet" if not sold else "Keep it. Keep the others off it in ads" if mine else ( | |
| f"Leave it to {best['a']}, or make this title answer a different search") | |
| groups.append({"q": q["q"], "vol": rs[0]["vol"], "rs": rs, "best": best["a"], "sold": sold, "do": action, | |
| **{k: sum(r[k] or 0 for r in rs) for k in ("cs", "ps")}}) | |
| groups.sort(key=lambda g: -g["vol"]) | |
| return {"groups": groups, "wins": sum(g["best"] == listing["asin"] and g["sold"] for g in groups)} | |
| def fitWhy(listing, key, context): | |
| if key in PROMO: | |
| return "Amazon does not allow promotional words" | |
| return None if key in model.fit_words(listing, context) else "Check fit" | |
| def wordFits(listing, key, context): | |
| return fitWhy(listing, key, context) is None | |
| def brandW84(listing, picks, context): | |
| return {key for a in [listing["asin"], *picks] | |
| for key in model.wordsOf(context.get("meta", {}).get(a, {}).get("brand", ""))} | |
| def _word_set(listing, asin, skip, context): | |
| return [k for k in dict.fromkeys(model.stemW(w) for w in re.split("[^a-z0-9]+", model.foldTea(pageText84(listing, asin, context))) | |
| if len(w) > 3) if k not in skip and k not in FILL84 and not k.isdigit()] | |
| def wordMoney84(listing, context): | |
| cached = context.get("_word_money84", {}).get(listing["asin"]) | |
| if cached is not None: | |
| return cached | |
| money = {"mkt": {}, "our": {}, "form": {}} | |
| for q in context["rows"].get(listing["asin"], []): | |
| value = model.v55(q, "all", context) | |
| if value is None: | |
| continue | |
| for key in model.qWords(q["q"]): | |
| for field in ("mkt", "our"): | |
| money[field][key] = money[field].get(key, 0) + value[field] | |
| raw = next((w for w in q["q"].lower().split() if model.stemW(w) == key), key) | |
| money["form"].setdefault(key, re.sub("[^a-z0-9]+", "", raw)) | |
| return money | |
| def _word_context(listing, picks, context): | |
| ps = _picks(picks, context) | |
| skip = brandW84(listing, ps, context) | |
| return ps, _word_set(listing, listing["asin"], skip, context), [ | |
| _word_set(listing, a, skip, context) for a in ps], wordMoney84(listing, context) | |
| def theirs84(listing, picks, context): | |
| ps, you, theirs, money = _word_context(listing, picks, context) | |
| seen = {} | |
| for words in theirs: | |
| for key in words: | |
| seen[key] = seen.get(key, 0) + 1 | |
| rows = [{"k": k, "word": money["form"].get(k, k), "n": n, "N": len(ps), "mkt": money["mkt"].get(k, 0), | |
| "fits": wordFits(listing, k, context)} for k, n in seen.items() | |
| if k not in you and n >= max(2, math.ceil(len(ps) / 2))] | |
| return sorted(rows, key=lambda r: (-r["mkt"], -r["n"])) | |
| def yours84(listing, picks, context): | |
| ps, you, theirs, money = _word_context(listing, picks, context) | |
| rows = [{"k": k, "word": money["form"].get(k, k), "n": n, "N": len(ps), | |
| **{field: money[field].get(k, 0) for field in ("mkt", "our")}} | |
| for k in you if (n := sum(k in words for words in theirs)) <= (1 if len(ps) >= 4 else 0)] | |
| return sorted(rows, key=lambda r: -r["mkt"]) | |
| def _col_text(col): | |
| return " ".join(col["bullets"]) if col.get("bullets") is not None else col.get("text", "") | |
| def _growth(values, per, months): | |
| if per == "all": | |
| return values[-1] / values[0] - 1 if values and values[0] else None | |
| index = months.index(per) if per in months else -1 | |
| return values[index] / values[index - 1] - 1 if index > 0 and values[index - 1] else None | |
| def _object_keys(mapping): | |
| # JavaScript enumerates array-index keys before other object keys. | |
| indexes = [k for k in mapping if re.fullmatch(r"0|[1-9][0-9]*", k) and int(k) < 2**32 - 1] | |
| return sorted(indexes, key=int) + [k for k in mapping if k not in indexes] | |
| def _word_items(queries, mode, per, context): | |
| items = {} | |
| for q in queries: | |
| for key in model.qWords(q["q"]) if mode == "word" else [q["q"]]: | |
| item = items.setdefault(key, {"k": key, "forms": {}, "list": [], **dict.fromkeys(F9, 0)}) | |
| raw = next((w for w in q["q"].lower().split() if model.stemW(w) == key), key) | |
| item["forms"][raw] = item["forms"].get(raw, 0) + q["vol"] | |
| item["list"].append(q) | |
| for field in F9: | |
| item[field] += q.get(field, 0) or 0 | |
| out = [] | |
| for key in _object_keys(items) if mode == "word" else items: | |
| item = items[key] | |
| queries = item["list"] | |
| trend = lambda i: [sum((q["m"].get(m) or [0] * 13)[i] or 0 for q in queries) for m in context["months"]] | |
| common = {"trend": trend(5), "gr": _growth(trend(0), per, context["months"])} | |
| if mode == "word": | |
| out.append({**item, "word": max(_object_keys(item["forms"]), key=item["forms"].get), "ks": [item["k"]], | |
| "qs": [q["q"] for q in queries], **common}) | |
| else: | |
| q = queries[0] | |
| out.append({**q, "k": q["q"], "word": q["q"], "ks": model.qWords(q["q"]), "qs": [q["q"]], **common}) | |
| return out | |
| def _label_word(row, you, competitors, n, share, listing, context): | |
| in_you = all(k in you for k in row["ks"]) | |
| users = [a for a, words in competitors if all(k in words for k in row["ks"])] | |
| ratio = lambda a, b: row[a] / row[b] if row[b] else 0 | |
| cr = (row["mc"] / row["mi"]) / (row["tc"] / row["ti"]) if row["mi"] and row["ti"] and row["tc"] else None | |
| br = ((row["mp"] / row["mc"]) / (row["tp"] / row["tc"]) if row["tp"] and row["tc"] else | |
| 9.99 if row["mp"] else 1) if row["mc"] else None | |
| if not in_you: | |
| label = "Gap" if users else "Open" | |
| elif not row["mi"]: | |
| label = "NotSeen" | |
| elif row["mi"] < 125 * n or row["mc"] < 5 * n: | |
| label = "Thin" | |
| else: | |
| label = ("WinBoth" if br is not None and br >= 1 else "LoseSale") if cr is not None and cr >= 1 else ( | |
| "LoseClick" if br is not None and br >= 1 else "LoseBoth") | |
| return {**row, "inY": in_you, "users": users, "cs": ratio("mc", "tc"), "is": ratio("mi", "ti"), | |
| "yconv": ratio("mp", "mc"), "mconv": ratio("tp", "tc"), "cr": cr, "br": br, | |
| "lab": label, "why": ACTIONS.get(label), "fits": all(wordFits(listing, k, context) for k in row["ks"]), | |
| "gain": max(0, row["mkt"] * share - row["our"])} | |
| def kwData(listing, cols, per, mode, context): | |
| queries = [] | |
| for q in context["rows"].get(listing["asin"], []): | |
| selected = model.v55(q, per, context) if per != "all" else None | |
| value = q if per == "all" else {k: selected[k] for k in F9} if selected is not None else None | |
| if value is not None: | |
| queries.append({"q": q["q"], "m": q.get("m", {}), **value}) | |
| you = model.wordsOf(_col_text(cols[0])) | |
| competitors = [(c["id"], model.wordsOf(_col_text(c))) for c in cols[1:]] | |
| carried = [q for q in queries if any(k in you for k in model.qWords(q["q"]))] | |
| total = lambda field: sum(q.get(field, 0) or 0 for q in carried) | |
| share, clicks = total("our") / total("mkt") if total("mkt") else 0, total("mc") / total("tc") if total("tc") else 0 | |
| n = max(1, len(context["months"])) if per == "all" else 1 | |
| rows = [_label_word(r, you, competitors, n, share, listing, context) | |
| for r in _word_items(queries, mode, per, context) if r["ks"]] | |
| return {"rows": rows, "S": share, "C": clicks, "n": n} | |
| def markedWords(text, rows, side, only): | |
| if not text: | |
| return text | |
| marks = {r["k"]: r["lab"] == only and (r["inY"] if side == "you" else side in r["users"]) for r in rows} | |
| parts = re.split(r"(\s+|[^A-Za-z0-9\s]+)", text) | |
| return [{"mark": p} if len(p) > 3 and re.search("[A-Za-z]", p) and marks.get(model.stemW(p)) else p for p in parts] | |
| def TextSide28(listing, part, cols, context): | |
| if part == "TERMS": | |
| return {"note": "Backend search terms are hidden on every listing, so there is no text to compare. The keywords below still work."} | |
| data = kwData(listing, cols, "all", "word", context) | |
| marked = [] | |
| for col in cols: | |
| texts = col["bullets"][:6] if col.get("bullets") is not None else [col.get("text", "")] | |
| marked.append({**col, "marks": [markedWords(text, data["rows"], col["id"], "Gap") for text in texts]}) | |
| return {"kwData": data, "cols": marked, "note": "Competitors' item highlights are not in Amazon's API. Their titles are shown." if part == "HIGHLIGHTS" else None} | |
| def _columns(listing, picks, part, context): | |
| live = context.get("live", {}).get(listing["asin"], {}) | |
| sources = [("you", live), *((a, context["meta"][a]) for a in _picks(picks, context))] | |
| cols = [] | |
| for asin, page in sources: | |
| own = asin == "you" | |
| text = page.get("title", "") if part in ("TITLE", "HIGHLIGHTS") else "\n".join(page.get("bullets", [])) if part == "BULLETS" else ( | |
| context.get("desc", {}).get(listing["asin"], "") if own and part == "DESC" else "") | |
| cols.append({"id": asin, "name": "You" if own else page.get("brand") or asin, | |
| "m": context["meta"].get(listing["asin"] if own else asin, {}), | |
| "text": "" if own and part == "HIGHLIGHTS" else text, | |
| "bullets": page.get("bullets", []) if part == "BULLETS" else None}) | |
| return cols | |
| def prepare(cur, listing, context, *, rt, snapshot_reader, picks_reader, per="all", source_scope=None): | |
| """Enrich one loaded model with permitted own listings, Setup picks and stored competitor pages.""" | |
| picks = list(dict.fromkeys(picks_reader(rt, listing["asin"]))) | |
| meta = snapshot_reader(rt, [listing["asin"], *picks]) | |
| start, end = model.period_span(per, context) | |
| rows = model.kwModel55(listing, per, context) | |
| with _scoped_reader(cur, source_scope) as scoped: | |
| own = _own_asins(scoped, context["rows"]) | |
| ba = top_clicked(scoped, [r["q"] for r in rows], start, end) if start else {} | |
| prepared = {**context, "meta": {**meta, **context.get("meta", {})}, "BA57": ba, "picks": picks, | |
| "rows": {a: rs for a, rs in context["rows"].items() if a in own}} | |
| prepared.pop("_word_money84", None) | |
| return {**prepared, "_word_money84": {listing["asin"]: wordMoney84(listing, prepared)}} | |
| def payload(listing, context, *, per="all", part="TITLE"): | |
| """Build the five prototype sections from an already enriched model.""" | |
| part = part.upper() | |
| rows = model.kwModel55(listing, per, context) | |
| selected = _picks(context.get("picks", []), context) | |
| return {"Versus61": Versus61(listing, rows, context), "Targets84": Targets84(listing, rows, selected, context), | |
| "Cannibal84": Cannibal84(listing, per, context), | |
| "WordGap84": {"theirs84": theirs84(listing, selected, context), "yours84": yours84(listing, selected, context), | |
| "wordMoney84": wordMoney84(listing, context)} if selected else {}, | |
| "TextSide28": TextSide28(listing, part, _columns(listing, selected, part, context), context) if selected else {}, | |
| "constraints": [DESCRIPTION_LIMIT] if selected and part == "DESC" else []} | |
| def build(cur, listing, context, *, rt, snapshot_reader, picks_reader, per="all", part="TITLE", source_scope=None): | |
| """Read Setup ASIN picks through picks_reader(rt, asin) and C6 through snapshot_reader(rt, asins).""" | |
| context = prepare(cur, listing, context, rt=rt, snapshot_reader=snapshot_reader, | |
| picks_reader=picks_reader, per=per, source_scope=source_scope) | |
| return payload(listing, context, per=per, part=part) | |