vimalprasad37 commited on
Commit
c38dea0
·
1 Parent(s): 86b4e2c

Paypal Key added

Browse files
Files changed (1) hide show
  1. app.py +55 -72
app.py CHANGED
@@ -891,117 +891,100 @@ EMAIL_LINK = (
891
 
892
  # Where a key is bought. Overridable so the page can move without a code change.
893
  BUY_URL = os.environ.get(
894
- "BUY_URL", "https://vimalprasad37.github.io/wan-studio-pro/")
895
  BUY_LINK = (
896
  f"<a href='{BUY_URL}' target='_blank' rel='noopener noreferrer' "
897
  f"class='buy-link'>Get an access key</a>"
898
  )
899
 
900
 
901
- # Where keys come from now that they are sold rather than handed out by hand.
902
- # KEY_BACKEND is the payments service; it owns the database of issued keys, so a
903
- # key bought two minutes ago works without restarting this Space. ACCESS_KEYS
904
- # stays as the fallback - see _valid_keys.
905
  KEY_BACKEND = (os.environ.get("KEY_BACKEND", "") or "").rstrip("/")
906
  KEY_BACKEND_TOKEN = os.environ.get("KEY_BACKEND_TOKEN", "") or ""
 
 
907
 
908
- # The backend answer is cached briefly so a burst of clicks is one request, not
909
- # twenty. Short enough that a revoked key stops working within the minute.
910
- _KEY_CACHE = {"keys": None, "at": 0.0}
911
  _KEY_CACHE_TTL = 60.0
912
 
913
 
914
  def _env_keys():
915
- """The ACCESS_KEYS list, parsed. This is the fallback path and also what a
916
- local run with no backend uses."""
917
- import re # `re` is imported further down the file; this makes the gate independent of that
918
 
919
  raw = os.environ.get("ACCESS_KEYS", "") or ""
920
  keys = set()
921
  for part in re.split(r"[,\n;]+", raw):
922
- # Quotes are not needed in the HF secrets box, but they are an easy slip
923
- # and would otherwise become part of the key itself.
924
  part = part.strip().strip('"').strip("'").strip()
925
  if part:
926
  keys.add(part)
927
  return keys
928
 
929
 
930
- def _backend_keys():
931
- """Fetch the active key list from the payments backend.
932
-
933
- Returns None - not an empty set - on any failure, so the caller can tell
934
- "the backend says there are no keys" apart from "the backend did not
935
- answer". Conflating those would lock out every paying customer the moment
936
- the service blinked.
937
- """
938
- if not KEY_BACKEND:
939
  return None
940
-
941
  now = time.time()
942
- if _KEY_CACHE["keys"] is not None and (now - _KEY_CACHE["at"]) < _KEY_CACHE_TTL:
943
- return _KEY_CACHE["keys"]
944
-
945
  try:
946
  import json as _json
947
  import urllib.parse
948
  import urllib.request
949
 
950
- url = KEY_BACKEND + "/keys"
951
- if KEY_BACKEND_TOKEN:
952
- url += "?" + urllib.parse.urlencode({"token": KEY_BACKEND_TOKEN})
953
- # Short timeout on purpose: this runs while somebody is waiting for a
954
- # button to unlock, and the fallback below is always available.
955
- with urllib.request.urlopen(url, timeout=4) as resp:
 
 
 
956
  data = _json.loads(resp.read().decode("utf-8"))
957
  keys = {str(k).strip().upper() for k in data.get("keys", []) if str(k).strip()}
958
- _KEY_CACHE["keys"] = keys
959
- _KEY_CACHE["at"] = now
960
  return keys
961
- except Exception as exc: # noqa: BLE001 - never let this break the gate
962
- print(f"[access] key backend unreachable ({type(exc).__name__}: {exc}); "
963
- f"falling back to ACCESS_KEYS")
964
- # A stale cache is still better than nothing if we ever had one.
965
- if _KEY_CACHE["keys"] is not None:
966
- return _KEY_CACHE["keys"]
967
- return None
968
 
969
 
970
- def _valid_keys():
971
- """Every key that should unlock the app right now.
 
972
 
973
- The backend is the source of truth; ACCESS_KEYS is merged in so keys issued
974
- before the payment flow existed keep working, and so an outage degrades to
975
- the old behaviour instead of locking everyone out.
976
- """
 
 
 
 
977
  keys = set(_env_keys())
978
- from_backend = _backend_keys()
979
- if from_backend:
980
- keys |= from_backend
981
  return keys
982
 
983
 
984
  def _report_access_config():
985
- """Say at start-up whether the gate is armed. Counts only - never the keys
986
- themselves, which would put them in logs anyone with repo access can read."""
987
  env_count = len(_env_keys())
988
- backend = _backend_keys()
989
-
990
- if KEY_BACKEND:
991
- if backend is None:
992
- print(f"[access] key backend {KEY_BACKEND} did not answer at start-up; "
993
- f"falling back to ACCESS_KEYS ({env_count} key(s))")
994
- else:
995
- print(f"[access] key backend {KEY_BACKEND} reachable: "
996
- f"{len(backend)} key(s); ACCESS_KEYS fallback: {env_count}")
997
- else:
998
- print(f"[access] KEY_BACKEND is not set - using ACCESS_KEYS only "
999
- f"({env_count} key(s))")
1000
-
1001
  if not _valid_keys():
1002
- print("[access] no keys from either source - generation is locked for "
1003
- "everyone. Set KEY_BACKEND (and KEY_BACKEND_TOKEN), or ACCESS_KEYS, "
1004
- "then restart the Space.")
1005
 
1006
 
1007
  def check_access_key(key):
@@ -1021,7 +1004,7 @@ def check_access_key(key):
1021
  # sending the owner back to a Settings page where the secret already is.
1022
  return (False,
1023
  "<div class='status-idle'><b>The key list has not reached the app.</b> "
1024
- "The payments backend did not answer and no <code>ACCESS_KEYS</code> "
1025
  "fallback is set. If you have already bought a key, message Telegram "
1026
  f"{TELEGRAM_LINK} or email {EMAIL_LINK} and it will be sorted out. "
1027
  f"Otherwise {BUY_LINK}.</div>",
@@ -1072,7 +1055,7 @@ def require_access(unlocked):
1072
  if not unlocked:
1073
  raise gr.Error(
1074
  "This action needs a valid access key. Enter one at the top of the page - "
1075
- f"get one at {BUY_URL} (emailed right after payment), "
1076
  f"or contact Telegram {TELEGRAM_CONTACT} / {SUPPORT_EMAIL}."
1077
  )
1078
 
@@ -3585,7 +3568,7 @@ HERO = """
3585
  video for you.</p>
3586
  <p class="policy"><b>&#128273; Pro is key-access.</b> Browsing, joining and looping are always
3587
  free &mdash; generating video and every studio feature needs a paid key.
3588
- """ + BUY_LINK + """ &mdash; delivered by email the moment payment clears.
3589
  Questions or problems? Email """ + EMAIL_LINK + """ or message """ + TELEGRAM_LINK + """.<br>
3590
  <b>Please note:</b> a key unlocks features, not GPU time. Generation draws on the standard
3591
  Hugging Face ZeroGPU allowance, counted against your own account.</p>
@@ -3613,7 +3596,7 @@ with gr.Blocks(delete_cache=(3600, 86400)) as demo:
3613
  "Look around as much as you like &mdash; upload an image, build a prompt, browse "
3614
  "the lora library. Generating video, scene chaining, sound and the AI prompt "
3615
  "writer are the parts that need a key. "
3616
- f"{BUY_LINK} &mdash; it arrives by email the moment payment clears. Paste it "
3617
  f"below and press <b>Unlock</b>.</div>"
3618
  )
3619
  # `min_width` rather than `scale` alone. Gradio resolves `scale` in
 
891
 
892
  # Where a key is bought. Overridable so the page can move without a code change.
893
  BUY_URL = os.environ.get(
894
+ "BUY_URL", "https://vimalprasad37.github.io/wan-studio-pro/?checkout=wan-studio-pro")
895
  BUY_LINK = (
896
  f"<a href='{BUY_URL}' target='_blank' rel='noopener noreferrer' "
897
  f"class='buy-link'>Get an access key</a>"
898
  )
899
 
900
 
901
+ # Wise and PayPal keep separate key stores during the PayPal rollout. This
902
+ # preserves existing Wise keys and scopes the Odoo integration to this Space.
 
 
903
  KEY_BACKEND = (os.environ.get("KEY_BACKEND", "") or "").rstrip("/")
904
  KEY_BACKEND_TOKEN = os.environ.get("KEY_BACKEND_TOKEN", "") or ""
905
+ ODOO_KEY_BACKEND = (os.environ.get("ODOO_KEY_BACKEND", "") or "").rstrip("/")
906
+ ODOO_KEY_BACKEND_TOKEN = os.environ.get("ODOO_KEY_BACKEND_TOKEN", "") or ""
907
 
908
+ _KEY_CACHE = {"wise": {"keys": None, "at": 0.0},
909
+ "odoo": {"keys": None, "at": 0.0}}
 
910
  _KEY_CACHE_TTL = 60.0
911
 
912
 
913
  def _env_keys():
914
+ """Keys that predate the payment services, and the outage fallback."""
915
+ import re
 
916
 
917
  raw = os.environ.get("ACCESS_KEYS", "") or ""
918
  keys = set()
919
  for part in re.split(r"[,\n;]+", raw):
 
 
920
  part = part.strip().strip('"').strip("'").strip()
921
  if part:
922
  keys.add(part)
923
  return keys
924
 
925
 
926
+ def _fetch_key_source(name, base_url, token, bearer=False):
927
+ """Fetch one source, retaining its last answer during a brief outage."""
928
+ if not base_url:
 
 
 
 
 
 
929
  return None
930
+ cache = _KEY_CACHE[name]
931
  now = time.time()
932
+ if cache["keys"] is not None and (now - cache["at"]) < _KEY_CACHE_TTL:
933
+ return cache["keys"]
 
934
  try:
935
  import json as _json
936
  import urllib.parse
937
  import urllib.request
938
 
939
+ url = base_url + "/keys"
940
+ headers = {}
941
+ if token:
942
+ if bearer:
943
+ headers["Authorization"] = "Bearer " + token
944
+ else:
945
+ url += "?" + urllib.parse.urlencode({"token": token})
946
+ req = urllib.request.Request(url, headers=headers)
947
+ with urllib.request.urlopen(req, timeout=8) as resp:
948
  data = _json.loads(resp.read().decode("utf-8"))
949
  keys = {str(k).strip().upper() for k in data.get("keys", []) if str(k).strip()}
950
+ cache["keys"] = keys
951
+ cache["at"] = now
952
  return keys
953
+ except Exception as exc: # noqa: BLE001 - an outage must not reject existing buyers
954
+ print(f"[access] {name} key source unavailable ({type(exc).__name__}: {exc})")
955
+ return None if bearer else cache["keys"]
 
 
 
 
956
 
957
 
958
+ def _backend_keys():
959
+ """Read existing Wise keys."""
960
+ return _fetch_key_source("wise", KEY_BACKEND, KEY_BACKEND_TOKEN)
961
 
962
+
963
+ def _odoo_keys():
964
+ """Read PayPal keys from the protected Odoo Space."""
965
+ return _fetch_key_source("odoo", ODOO_KEY_BACKEND,
966
+ ODOO_KEY_BACKEND_TOKEN, bearer=True)
967
+
968
+
969
+ def _valid_keys():
970
  keys = set(_env_keys())
971
+ for source in (_backend_keys(), _odoo_keys()):
972
+ if source:
973
+ keys.update(source)
974
  return keys
975
 
976
 
977
  def _report_access_config():
 
 
978
  env_count = len(_env_keys())
979
+ for name, base_url, source in (("Wise", KEY_BACKEND, _backend_keys()),
980
+ ("Odoo", ODOO_KEY_BACKEND, _odoo_keys())):
981
+ if base_url:
982
+ status = "unavailable" if source is None else f"{len(source)} key(s)"
983
+ print(f"[access] {name} key source {status}")
984
+ print(f"[access] ACCESS_KEYS fallback: {env_count} key(s)")
 
 
 
 
 
 
 
985
  if not _valid_keys():
986
+ print("[access] no keys from any source; check KEY_BACKEND, "
987
+ "ODOO_KEY_BACKEND, and ACCESS_KEYS")
 
988
 
989
 
990
  def check_access_key(key):
 
1004
  # sending the owner back to a Settings page where the secret already is.
1005
  return (False,
1006
  "<div class='status-idle'><b>The key list has not reached the app.</b> "
1007
+ "The key services did not answer and no <code>ACCESS_KEYS</code> "
1008
  "fallback is set. If you have already bought a key, message Telegram "
1009
  f"{TELEGRAM_LINK} or email {EMAIL_LINK} and it will be sorted out. "
1010
  f"Otherwise {BUY_LINK}.</div>",
 
1055
  if not unlocked:
1056
  raise gr.Error(
1057
  "This action needs a valid access key. Enter one at the top of the page - "
1058
+ f"get one at {BUY_URL}, "
1059
  f"or contact Telegram {TELEGRAM_CONTACT} / {SUPPORT_EMAIL}."
1060
  )
1061
 
 
3568
  video for you.</p>
3569
  <p class="policy"><b>&#128273; Pro is key-access.</b> Browsing, joining and looping are always
3570
  free &mdash; generating video and every studio feature needs a paid key.
3571
+ """ + BUY_LINK + """ &mdash; emailed after payment verification.
3572
  Questions or problems? Email """ + EMAIL_LINK + """ or message """ + TELEGRAM_LINK + """.<br>
3573
  <b>Please note:</b> a key unlocks features, not GPU time. Generation draws on the standard
3574
  Hugging Face ZeroGPU allowance, counted against your own account.</p>
 
3596
  "Look around as much as you like &mdash; upload an image, build a prompt, browse "
3597
  "the lora library. Generating video, scene chaining, sound and the AI prompt "
3598
  "writer are the parts that need a key. "
3599
+ f"{BUY_LINK} &mdash; it arrives by email after payment verification. Paste it "
3600
  f"below and press <b>Unlock</b>.</div>"
3601
  )
3602
  # `min_width` rather than `scale` alone. Gradio resolves `scale` in