Theflame47 commited on
Commit
e159005
·
verified ·
1 Parent(s): c21e453

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -79
app.py CHANGED
@@ -2,7 +2,7 @@ import os
2
  import time
3
  import json
4
  import tempfile
5
- from typing import Dict, Any, List
6
 
7
  import requests
8
  import gradio as gr
@@ -15,6 +15,10 @@ def _now() -> str:
15
  return time.strftime("%H:%M:%S")
16
 
17
 
 
 
 
 
18
  def _auth_headers() -> Dict[str, str]:
19
  token = os.environ.get("PRINTIFY_API_TOKEN")
20
  if not token:
@@ -38,44 +42,10 @@ def _log(logs: List[str], msg: str):
38
  logs.append(f"[{_now()}] {msg}")
39
 
40
 
41
- def _pick_shop_id(logs: List[str], shop_id_text: str) -> int:
42
- if isinstance(shop_id_text, str) and shop_id_text.strip().isdigit():
43
- sid = int(shop_id_text.strip())
44
- _log(logs, f"USING_SHOP_ID (manual) {sid}")
45
- return sid
46
-
47
- _log(logs, "Listing shops")
48
- shops = _req("GET", "/v1/shops.json")
49
- if not isinstance(shops, list):
50
- raise RuntimeError("Unexpected shops response.")
51
-
52
- _log(logs, f"FOUND {len(shops)} shops")
53
-
54
- picked = None
55
- for s in shops:
56
- title = (s.get("title") or "").strip().lower()
57
- if title == "atheria":
58
- picked = s
59
- break
60
-
61
- if not picked and shops:
62
- picked = shops[0]
63
-
64
- if not picked or not picked.get("id"):
65
- raise RuntimeError("Could not resolve a shop id (no shops returned).")
66
-
67
- sid = int(picked["id"])
68
- _log(logs, f"USING_SHOP_ID (auto) {sid} title={(picked.get('title') or 'untitled')}")
69
- return sid
70
-
71
-
72
- def _collect_phase_a(shop_id: int, logs: List[str]) -> Dict[str, Any]:
73
  _log(logs, "Listing blueprints")
74
  blueprints = _req("GET", "/v1/catalog/blueprints.json")
75
 
76
- templates: List[Dict[str, Any]] = []
77
- scanned_pairs = 0
78
-
79
  for bp in blueprints:
80
  bp_id = str(bp["id"])
81
  _log(logs, f"Blueprint {bp_id}: fetching providers")
@@ -83,7 +53,6 @@ def _collect_phase_a(shop_id: int, logs: List[str]) -> Dict[str, Any]:
83
  providers = _req("GET", f"/v1/catalog/blueprints/{bp_id}/print_providers.json")
84
  for p in providers:
85
  p_id = str(p["id"])
86
- scanned_pairs += 1
87
  _log(logs, f"Blueprint {bp_id} / Provider {p_id}: fetching variants")
88
 
89
  vr = _req(
@@ -91,32 +60,22 @@ def _collect_phase_a(shop_id: int, logs: List[str]) -> Dict[str, Any]:
91
  f"/v1/catalog/blueprints/{bp_id}/print_providers/{p_id}/variants.json?show-out-of-stock=1",
92
  )
93
  variants = vr.get("variants")
94
- if not (isinstance(variants, list) and variants):
95
- continue
96
-
97
- _log(logs, f"FOUND {len(variants)} variants")
98
-
99
- blob = {
100
- "blueprint": bp,
101
- "provider": p,
102
- "variants": variants,
103
- "blueprintDetails": _req("GET", f"/v1/catalog/blueprints/{bp_id}.json"),
104
- "providerDetails": _req("GET", f"/v1/catalog/print_providers/{p_id}.json"),
105
- "shippingInfo": _req(
106
- "GET",
107
- f"/v1/catalog/blueprints/{bp_id}/print_providers/{p_id}/shipping.json",
108
- ),
109
- }
110
-
111
- templates.append({
112
- "shop_id": shop_id,
113
- "blueprint_id": int(bp_id),
114
- "print_provider_id": int(p_id),
115
- "raw": blob,
116
- })
117
-
118
- _log(logs, f"PHASE_A_DONE templates={len(templates)} scanned_pairs={scanned_pairs}")
119
- return {"shop_id": shop_id, "templates": templates}
120
 
121
 
122
  def _build_product(blob: Dict[str, Any], currency: str, logs: List[str]) -> Dict[str, Any]:
@@ -167,7 +126,7 @@ def _build_product(blob: Dict[str, Any], currency: str, logs: List[str]) -> Dict
167
  }
168
 
169
 
170
- def run(currency, shop_id_text):
171
  logs: List[str] = []
172
  result: Dict[str, Any] = {}
173
  dl_path = ""
@@ -179,23 +138,20 @@ def run(currency, shop_id_text):
179
  _log(logs, "START")
180
  yield flush()
181
 
182
- sid = _pick_shop_id(logs, shop_id_text)
 
183
  yield flush()
184
 
185
- phase_a = _collect_phase_a(sid, logs)
186
  yield flush()
187
 
188
- templates = phase_a.get("templates") or []
189
- if templates:
190
- first_raw = (templates[0].get("raw") or {})
191
- result = _build_product(first_raw, currency or "USD", logs)
192
- else:
193
- result = {"shop_id": sid, "templates": []}
194
 
195
- fd, path = tempfile.mkstemp(prefix="phase_a_", suffix=".json")
196
  os.close(fd)
197
  with open(path, "w", encoding="utf-8") as f:
198
- json.dump(phase_a, f, indent=2)
199
  dl_path = path
200
 
201
  _log(logs, "DONE")
@@ -208,16 +164,14 @@ def run(currency, shop_id_text):
208
 
209
 
210
  with gr.Blocks(title="Printify Catalog Probe") as demo:
211
- gr.Markdown("Extract and normalize Printify catalog into Phase A templates, plus a sample normalized product JSON.")
212
 
213
  currency = gr.Textbox(label="Currency", value="USD")
214
- shop_id = gr.Textbox(label="Shop ID (optional; leave blank to auto-pick Atheria)", value="")
215
-
216
  btn = gr.Button("Run")
217
  logs = gr.Textbox(label="Logs", lines=18)
218
  out = gr.Textbox(label="Output JSON", lines=18)
219
- dl = gr.File(label="Download Phase A JSON")
220
 
221
- btn.click(run, inputs=[currency, shop_id], outputs=[logs, out, dl])
222
 
223
  demo.queue().launch()
 
2
  import time
3
  import json
4
  import tempfile
5
+ from typing import Dict, Any, List, Generator, Tuple
6
 
7
  import requests
8
  import gradio as gr
 
15
  return time.strftime("%H:%M:%S")
16
 
17
 
18
+ def _sleep(ms: int):
19
+ time.sleep(ms / 1000)
20
+
21
+
22
  def _auth_headers() -> Dict[str, str]:
23
  token = os.environ.get("PRINTIFY_API_TOKEN")
24
  if not token:
 
42
  logs.append(f"[{_now()}] {msg}")
43
 
44
 
45
+ def _find_first_valid_pair(logs: List[str]) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  _log(logs, "Listing blueprints")
47
  blueprints = _req("GET", "/v1/catalog/blueprints.json")
48
 
 
 
 
49
  for bp in blueprints:
50
  bp_id = str(bp["id"])
51
  _log(logs, f"Blueprint {bp_id}: fetching providers")
 
53
  providers = _req("GET", f"/v1/catalog/blueprints/{bp_id}/print_providers.json")
54
  for p in providers:
55
  p_id = str(p["id"])
 
56
  _log(logs, f"Blueprint {bp_id} / Provider {p_id}: fetching variants")
57
 
58
  vr = _req(
 
60
  f"/v1/catalog/blueprints/{bp_id}/print_providers/{p_id}/variants.json?show-out-of-stock=1",
61
  )
62
  variants = vr.get("variants")
63
+ if isinstance(variants, list) and variants:
64
+ _log(logs, f"FOUND {len(variants)} variants")
65
+
66
+ return {
67
+ "blueprint": bp,
68
+ "provider": p,
69
+ "variants": variants,
70
+ "blueprintDetails": _req("GET", f"/v1/catalog/blueprints/{bp_id}.json"),
71
+ "providerDetails": _req("GET", f"/v1/catalog/print_providers/{p_id}.json"),
72
+ "shippingInfo": _req(
73
+ "GET",
74
+ f"/v1/catalog/blueprints/{bp_id}/print_providers/{p_id}/shipping.json",
75
+ ),
76
+ }
77
+
78
+ raise RuntimeError("No blueprint/provider pair with variants found.")
 
 
 
 
 
 
 
 
 
 
79
 
80
 
81
  def _build_product(blob: Dict[str, Any], currency: str, logs: List[str]) -> Dict[str, Any]:
 
126
  }
127
 
128
 
129
+ def run(currency: str) -> Generator[Tuple[str, str, str], None, None]:
130
  logs: List[str] = []
131
  result: Dict[str, Any] = {}
132
  dl_path = ""
 
138
  _log(logs, "START")
139
  yield flush()
140
 
141
+ shops = _req("GET", "/v1/shops.json")
142
+ _log(logs, f"SHOP_LIST {json.dumps(shops)}")
143
  yield flush()
144
 
145
+ blob = _find_first_valid_pair(logs)
146
  yield flush()
147
 
148
+ result = _build_product(blob, currency or "USD", logs)
149
+ yield flush()
 
 
 
 
150
 
151
+ fd, path = tempfile.mkstemp(prefix="shops_", suffix=".json")
152
  os.close(fd)
153
  with open(path, "w", encoding="utf-8") as f:
154
+ json.dump(shops, f, indent=2)
155
  dl_path = path
156
 
157
  _log(logs, "DONE")
 
164
 
165
 
166
  with gr.Blocks(title="Printify Catalog Probe") as demo:
167
+ gr.Markdown("Extract and normalize ONE Printify blueprint/provider into a structured JSON object.")
168
 
169
  currency = gr.Textbox(label="Currency", value="USD")
 
 
170
  btn = gr.Button("Run")
171
  logs = gr.Textbox(label="Logs", lines=18)
172
  out = gr.Textbox(label="Output JSON", lines=18)
173
+ dl = gr.File(label="Download Shops JSON")
174
 
175
+ btn.click(run, inputs=[currency], outputs=[logs, out, dl])
176
 
177
  demo.queue().launch()