unitbytes 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
unitbytes/ali1688.py ADDED
@@ -0,0 +1,538 @@
1
+ """1688.com factory & cross-border sourcing domain namespace (`ub.ali1688`) with MOQ tier pricing, FBA freight, and SKU inventory helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass
6
+ from decimal import Decimal
7
+ import re
8
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
9
+ from urllib.parse import urlparse
10
+
11
+ from ._transports import unwrap_items_payload
12
+
13
+ if TYPE_CHECKING:
14
+ from .client import UnitBytes
15
+
16
+ ACTOR_1688_MAINLAND = "unitbytes/1688-scraper"
17
+ ACTOR_1688_IMAGE_SEARCH = "unitbytes/1688-image-search-scraper"
18
+ ACTOR_1688_GLOBAL = "unitbytes/1688-global-scraper"
19
+
20
+ DetailLevel = Literal["full", "summary"]
21
+ SortMode = Literal["normal", "booked", "repurchase", "priceAsc", "priceDesc", "newest"]
22
+ GlobalCurrency = Literal[
23
+ "USD", "CNY", "EUR", "GBP", "JPY", "AUD", "CAD",
24
+ "SGD", "MYR", "THB", "VND", "IDR", "PHP", "KRW", "HKD",
25
+ ]
26
+
27
+ _ALLOWED_1688_HOSTS = {
28
+ "1688.com", "www.1688.com", "detail.1688.com", "m.1688.com",
29
+ "s.1688.com", "show.1688.com", "shop.1688.com", "global.1688.com",
30
+ }
31
+ _OFFER_ID_PATH_RE = re.compile(r"/offer/(\d{8,16})\.html", re.IGNORECASE)
32
+ _OFFER_ID_DIGITS_RE = re.compile(r"^(\d{8,16})$")
33
+ _OFFER_ID_QUERY_RE = re.compile(r"(?:offerId|id)=(\d{8,16})", re.IGNORECASE)
34
+
35
+ PROVINCE_ALIASES: dict[str, str] = {
36
+ "guangdong": "广东", "shenzhen": "广东", "guangzhou": "广东", "dongguan": "广东",
37
+ "foshan": "广东", "shantou": "广东", "zhongshan": "广东",
38
+ "zhejiang": "浙江", "yiwu": "浙江", "hangzhou": "浙江", "ningbo": "浙江",
39
+ "wenzhou": "浙江", "taizhou": "浙江", "jinhua": "浙江", "shaoxing": "浙江",
40
+ "jiangsu": "江苏", "suzhou": "江苏", "nanjing": "江苏", "wuxi": "江苏",
41
+ "changzhou": "江苏", "nantong": "江苏",
42
+ "shandong": "山东", "qingdao": "山东", "jinan": "山东", "linyi": "山东",
43
+ "fujian": "福建", "xiamen": "福建", "quanzhou": "福建", "fuzhou": "福建", "putian": "福建",
44
+ "hebei": "河北", "baoding": "河北", "shijiazhuang": "河北",
45
+ "henan": "河南", "zhengzhou": "河南",
46
+ "anhui": "安徽", "hefei": "安徽",
47
+ "hubei": "湖北", "wuhan": "湖北",
48
+ "hunan": "湖南", "changsha": "湖南",
49
+ "sichuan": "四川", "chengdu": "四川",
50
+ "jiangxi": "江西", "nanchang": "江西",
51
+ "shanghai": "上海", "beijing": "北京", "tianjin": "天津", "chongqing": "重庆",
52
+ }
53
+
54
+
55
+ def _to_float(value: Any) -> float | None:
56
+ if value is None or isinstance(value, bool):
57
+ return None
58
+ if isinstance(value, (int, float)):
59
+ return float(value)
60
+ text = str(value).strip()
61
+ if not text:
62
+ return None
63
+ cleaned = re.sub(r"[^\d.\-]", "", text.split("-")[0] if "-" in text and not text.startswith("-") else text)
64
+ if not cleaned:
65
+ return None
66
+ try:
67
+ return float(cleaned)
68
+ except ValueError:
69
+ return None
70
+
71
+
72
+ def _to_int(value: Any) -> int | None:
73
+ num = _to_float(value)
74
+ return int(round(num)) if num is not None else None
75
+
76
+
77
+ def normalize_offer_id(offer_id_or_url: str | int) -> str:
78
+ """Extract and validate an 8-to-16 digit 1688 offer ID from an ID or `1688.com` URL."""
79
+ raw = str(offer_id_or_url).strip()
80
+ if not raw:
81
+ raise ValueError("offer_id_or_url cannot be empty.")
82
+ digits_match = _OFFER_ID_DIGITS_RE.match(raw)
83
+ if digits_match:
84
+ return digits_match.group(1)
85
+ if raw.startswith(("http://", "https://")):
86
+ parsed = urlparse(raw)
87
+ if parsed.username or parsed.password:
88
+ raise ValueError("1688 URL must not include embedded credentials.")
89
+ host = (parsed.hostname or "").lower().strip(".")
90
+ if not (host in _ALLOWED_1688_HOSTS or host.endswith(".1688.com")):
91
+ raise ValueError(f"Expected a 1688.com URL, got host {host!r}.")
92
+ path_match = _OFFER_ID_PATH_RE.search(parsed.path or "")
93
+ if path_match:
94
+ return path_match.group(1)
95
+ query_match = _OFFER_ID_QUERY_RE.search(parsed.query or "")
96
+ if query_match:
97
+ return query_match.group(1)
98
+ raise ValueError(f"Could not extract a valid 8-16 digit offer ID from URL: {raw!r}")
99
+ raise ValueError(f"Invalid 1688 offer identifier {raw!r}.")
100
+
101
+
102
+ def normalize_province(province: str | None) -> str:
103
+ """Normalize English manufacturing hub or Chinese province names to canonical 1688 filter strings."""
104
+ if not province:
105
+ return ""
106
+ cleaned = province.strip()
107
+ if not cleaned:
108
+ return ""
109
+ alias_key = re.sub(r"[\s_-]+", "", cleaned.lower())
110
+ for suffix in ("province", "sheng"):
111
+ if alias_key.endswith(suffix):
112
+ alias_key = alias_key[: -len(suffix)]
113
+ break
114
+ if alias_key in PROVINCE_ALIASES:
115
+ return PROVINCE_ALIASES[alias_key]
116
+ if cleaned.endswith("省") and len(cleaned) > 2:
117
+ return cleaned[:-1]
118
+ if cleaned.endswith("市") and cleaned[:-1] in {"上海", "北京", "天津", "重庆"}:
119
+ return cleaned[:-1]
120
+ return cleaned
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class TierQuote:
125
+ quantity: int
126
+ min_order_quantity: int
127
+ meets_moq: bool
128
+ matched_tier_min_qty: int
129
+ matched_tier_max_qty: int | None
130
+ unit_price_cny: float
131
+ total_price_cny: float
132
+ unit_price_usd: float
133
+ total_price_usd: float
134
+ discount_vs_base_pct: float
135
+ cny_to_usd_rate: float
136
+
137
+ def to_dict(self) -> dict[str, Any]:
138
+ return asdict(self)
139
+
140
+
141
+ def resolve_unit_price_for_qty(
142
+ offer_or_tiers: Mapping[str, Any] | Sequence[Mapping[str, Any]],
143
+ quantity: int,
144
+ *,
145
+ cny_to_usd: float = 0.138,
146
+ strict_moq: bool = False,
147
+ ) -> TierQuote:
148
+ """Resolve the active 1688 wholesale tier unit price and total cost for a target order quantity."""
149
+ if quantity < 1:
150
+ raise ValueError(f"quantity must be >= 1, got {quantity}")
151
+ if cny_to_usd <= 0:
152
+ raise ValueError(f"cny_to_usd must be > 0, got {cny_to_usd}")
153
+
154
+ raw_tiers: Sequence[Mapping[str, Any]] = []
155
+ fallback_price: float | None = None
156
+ explicit_moq: int | None = None
157
+
158
+ if isinstance(offer_or_tiers, Mapping):
159
+ raw_tiers = offer_or_tiers.get("tieredPrices") or offer_or_tiers.get("priceTiers") or []
160
+ fallback_price = _to_float(
161
+ offer_or_tiers.get("price") if offer_or_tiers.get("price") is not None else offer_or_tiers.get("priceCny")
162
+ )
163
+ explicit_moq = _to_int(
164
+ offer_or_tiers.get("minOrderQuantity")
165
+ if offer_or_tiers.get("minOrderQuantity") is not None
166
+ else offer_or_tiers.get("moq")
167
+ )
168
+ else:
169
+ raw_tiers = offer_or_tiers
170
+
171
+ parsed_tiers: list[tuple[int, int | None, float]] = []
172
+ for entry in raw_tiers:
173
+ if not isinstance(entry, Mapping):
174
+ continue
175
+ min_q = _to_int(entry.get("minQuantity") if entry.get("minQuantity") is not None else entry.get("beginAmount"))
176
+ max_q = _to_int(entry.get("maxQuantity"))
177
+ price_val = _to_float(entry.get("price") if entry.get("price") is not None else entry.get("priceCny"))
178
+ if min_q is not None and price_val is not None and price_val > 0:
179
+ parsed_tiers.append((max(1, min_q), max_q, price_val))
180
+
181
+ parsed_tiers.sort(key=lambda item: item[0])
182
+ if not parsed_tiers:
183
+ if fallback_price is None or fallback_price <= 0:
184
+ raise ValueError("Cannot resolve unit price: offer has neither valid tieredPrices nor a base price.")
185
+ moq = max(1, explicit_moq or 1)
186
+ parsed_tiers = [(moq, None, fallback_price)]
187
+
188
+ lowest_tier_min, lowest_tier_max, base_unit_price = parsed_tiers[0]
189
+ moq = max(1, explicit_moq if explicit_moq is not None else lowest_tier_min)
190
+ meets_moq = quantity >= moq
191
+ if strict_moq and not meets_moq:
192
+ raise ValueError(f"Requested quantity ({quantity}) is below supplier MOQ ({moq}).")
193
+
194
+ selected_min, selected_max, selected_price = lowest_tier_min, lowest_tier_max, base_unit_price
195
+ for min_q, max_q, tier_price in parsed_tiers:
196
+ if quantity >= min_q:
197
+ selected_min, selected_max, selected_price = min_q, max_q, tier_price
198
+ else:
199
+ break
200
+
201
+ total_cny = round(selected_price * quantity, 2)
202
+ unit_usd = round(selected_price * cny_to_usd, 4)
203
+ total_usd = round(total_cny * cny_to_usd, 2)
204
+ discount_pct = round(max(0.0, (base_unit_price - selected_price) / base_unit_price * 100.0), 2) if base_unit_price > 0 else 0.0
205
+ return TierQuote(
206
+ quantity=quantity,
207
+ min_order_quantity=moq,
208
+ meets_moq=meets_moq,
209
+ matched_tier_min_qty=selected_min,
210
+ matched_tier_max_qty=selected_max,
211
+ unit_price_cny=round(selected_price, 4),
212
+ total_price_cny=total_cny,
213
+ unit_price_usd=unit_usd,
214
+ total_price_usd=total_usd,
215
+ discount_vs_base_pct=discount_pct,
216
+ cny_to_usd_rate=cny_to_usd,
217
+ )
218
+
219
+
220
+ @dataclass(frozen=True)
221
+ class SkuInventorySummary:
222
+ total_skus: int
223
+ in_stock_skus: int
224
+ out_of_stock_skus: int
225
+ total_stock: int
226
+ min_sku_price_cny: float | None
227
+ max_sku_price_cny: float | None
228
+
229
+ def to_dict(self) -> dict[str, Any]:
230
+ return asdict(self)
231
+
232
+
233
+ def summarize_sku_stock(offer: Mapping[str, Any]) -> SkuInventorySummary:
234
+ """Summarize variant inventory and price spread across `skuMatrix` or `skus`."""
235
+ raw_skus = offer.get("skuMatrix") or offer.get("skus") or []
236
+ if not isinstance(raw_skus, Sequence) or isinstance(raw_skus, (str, bytes)):
237
+ raw_skus = []
238
+ in_stock = 0
239
+ out_of_stock = 0
240
+ total_stock = 0
241
+ prices: list[float] = []
242
+ for sku in raw_skus:
243
+ if not isinstance(sku, Mapping):
244
+ continue
245
+ stock = _to_int(sku.get("stock")) or 0
246
+ if stock > 0:
247
+ in_stock += 1
248
+ total_stock += stock
249
+ else:
250
+ out_of_stock += 1
251
+ sku_price = _to_float(sku.get("price") if sku.get("price") is not None else sku.get("priceCny"))
252
+ if sku_price is not None and sku_price > 0:
253
+ prices.append(sku_price)
254
+
255
+ if total_stock == 0:
256
+ fallback_stock = _to_int(offer.get("totalStock"))
257
+ if fallback_stock and fallback_stock > 0:
258
+ total_stock = fallback_stock
259
+
260
+ return SkuInventorySummary(
261
+ total_skus=in_stock + out_of_stock,
262
+ in_stock_skus=in_stock,
263
+ out_of_stock_skus=out_of_stock,
264
+ total_stock=total_stock,
265
+ min_sku_price_cny=round(min(prices), 4) if prices else None,
266
+ max_sku_price_cny=round(max(prices), 4) if prices else None,
267
+ )
268
+
269
+
270
+ class Ali1688Namespace:
271
+ """Mainland & Cross-Border 1688.com factory sourcing (`ub.ali1688`)."""
272
+
273
+ def __init__(self, client: UnitBytes) -> None:
274
+ self._client = client
275
+
276
+ def search(
277
+ self,
278
+ keyword: str | Sequence[str],
279
+ *,
280
+ max_items: int = 20,
281
+ page: int = 1,
282
+ detail_level: DetailLevel = "full",
283
+ sort_by: SortMode = "normal",
284
+ price_min: float | None = None,
285
+ price_max: float | None = None,
286
+ province: str | None = None,
287
+ channel: str = "",
288
+ super_factory: bool = False,
289
+ factory_inspection: bool = False,
290
+ no_cache: bool = False,
291
+ max_total_charge_usd: float | Decimal | None = None,
292
+ ) -> list[dict[str, Any]]:
293
+ """Search mainland 1688.com factory & supplier offers by keyword with MOQ/price/province filters."""
294
+ queries = [keyword.strip()] if isinstance(keyword, str) else [str(q).strip() for q in keyword if q and str(q).strip()]
295
+ if not queries:
296
+ raise ValueError("keyword must contain at least one non-empty query.")
297
+ if int(max_items) < 1:
298
+ raise ValueError("max_items must be >= 1.")
299
+
300
+ norm_province = normalize_province(province)
301
+ vertical_flag = (
302
+ channel
303
+ if channel in {"factory", "superFactory", "kuajing", "spot"}
304
+ else ("superFactory" if super_factory else "")
305
+ )
306
+ actor_sort = "booked" if sort_by in {"booked", "repurchase"} else "normal"
307
+ actor_input: dict[str, Any] = {
308
+ "queries": queries,
309
+ "maxItems": max(1, min(10000, int(max_items))),
310
+ "detailLevel": detail_level,
311
+ "sortBy": actor_sort,
312
+ }
313
+ if price_min is not None:
314
+ actor_input["priceMin"] = int(price_min)
315
+ if price_max is not None:
316
+ actor_input["priceMax"] = int(price_max)
317
+ if norm_province:
318
+ actor_input["province"] = norm_province
319
+ if vertical_flag:
320
+ actor_input["verticalProductFlag"] = vertical_flag
321
+
322
+ is_channel_op = channel in {"onePiece", "superFactory", "crossBorder", "taohuo"}
323
+ rest_op = "channel" if is_channel_op else "search"
324
+ rest_params: dict[str, Any] = (
325
+ {
326
+ "channel": channel,
327
+ "keyword": queries[0],
328
+ "page": int(page),
329
+ "page_size": max(1, min(60, int(max_items))),
330
+ "no_cache": no_cache or None,
331
+ }
332
+ if is_channel_op
333
+ else {
334
+ "keyword": queries[0],
335
+ "page": int(page),
336
+ "page_size": max(1, min(60, int(max_items))),
337
+ "sort_by": sort_by,
338
+ "price_min": price_min,
339
+ "price_max": price_max,
340
+ "province": norm_province or None,
341
+ "super_factory": super_factory or (channel == "superFactory") or None,
342
+ "factory_inspection": factory_inspection or None,
343
+ "no_cache": no_cache or None,
344
+ }
345
+ )
346
+
347
+ raw = self._client._transport.execute_operation(
348
+ service="1688",
349
+ operation=rest_op,
350
+ actor_slug=ACTOR_1688_MAINLAND,
351
+ actor_input=actor_input,
352
+ http_method="GET",
353
+ params=rest_params,
354
+ max_total_charge_usd=max_total_charge_usd,
355
+ )
356
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")][: int(max_items) * len(queries)]
357
+
358
+ def image_search(
359
+ self,
360
+ *,
361
+ image_url: str | None = None,
362
+ image_base64: str | None = None,
363
+ image_urls: Sequence[str] | None = None,
364
+ max_items: int = 20,
365
+ page: int = 1,
366
+ detail_level: DetailLevel = "summary",
367
+ sort_by: Literal["normal", "booked", "priceAsc", "priceDesc"] = "normal",
368
+ price_min: float | None = None,
369
+ price_max: float | None = None,
370
+ province: str | None = None,
371
+ super_factory: bool = False,
372
+ factory_inspection: bool = False,
373
+ no_cache: bool = False,
374
+ max_total_charge_usd: float | Decimal | None = None,
375
+ ) -> list[dict[str, Any]]:
376
+ """Find source factories on 1688.com from a product image URL or base64 image."""
377
+ urls = [u.strip() for u in (image_urls or []) if u and u.strip()]
378
+ if image_url and image_url.strip():
379
+ urls.insert(0, image_url.strip())
380
+ b64 = (image_base64 or "").strip()
381
+ if not urls and not b64:
382
+ raise ValueError("Provide image_url, image_urls, or image_base64 for 1688 visual search.")
383
+
384
+ norm_province = normalize_province(province)
385
+ actor_input: dict[str, Any] = {
386
+ "maxItems": max(1, min(10000, int(max_items))),
387
+ "detailLevel": detail_level,
388
+ "sortBy": sort_by,
389
+ "superFactory": bool(super_factory),
390
+ "factoryInspection": bool(factory_inspection),
391
+ }
392
+ if urls:
393
+ actor_input["imageUrls"] = urls
394
+ if b64:
395
+ actor_input["imagesBase64"] = [b64]
396
+ if price_min is not None:
397
+ actor_input["priceMin"] = int(price_min)
398
+ if price_max is not None:
399
+ actor_input["priceMax"] = int(price_max)
400
+ if norm_province:
401
+ actor_input["province"] = norm_province
402
+
403
+ if b64:
404
+ rest_method: Literal["GET", "POST"] = "POST"
405
+ rest_params = {"no_cache": no_cache or None}
406
+ rest_body: dict[str, Any] | None = {
407
+ "image_base64": b64,
408
+ "page": int(page),
409
+ "page_size": min(40, int(max_items)),
410
+ "sort_by": sort_by,
411
+ "price_min": price_min,
412
+ "price_max": price_max,
413
+ "province": norm_province or None,
414
+ "super_factory": bool(super_factory),
415
+ "factory_inspection": bool(factory_inspection),
416
+ "no_cache": bool(no_cache),
417
+ }
418
+ else:
419
+ rest_method = "GET"
420
+ rest_body = None
421
+ rest_params = {
422
+ "image_url": urls[0],
423
+ "page": int(page),
424
+ "page_size": min(40, int(max_items)),
425
+ "sort_by": sort_by,
426
+ "price_min": price_min,
427
+ "price_max": price_max,
428
+ "province": norm_province or None,
429
+ "super_factory": super_factory or None,
430
+ "factory_inspection": factory_inspection or None,
431
+ "no_cache": no_cache or None,
432
+ }
433
+
434
+ raw = self._client._transport.execute_operation(
435
+ service="1688",
436
+ operation="image-search",
437
+ actor_slug=ACTOR_1688_IMAGE_SEARCH,
438
+ actor_input=actor_input,
439
+ http_method=rest_method,
440
+ params=rest_params,
441
+ json_body=rest_body,
442
+ max_total_charge_usd=max_total_charge_usd,
443
+ )
444
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
445
+
446
+ def global_search(
447
+ self,
448
+ keyword: str | Sequence[str],
449
+ *,
450
+ currency: GlobalCurrency = "USD",
451
+ max_items: int = 20,
452
+ page: int = 1,
453
+ detail_level: DetailLevel = "full",
454
+ sort_by: Literal["normal", "va_sales360", "price_asc", "price_desc"] = "normal",
455
+ min_moq: int | None = None,
456
+ max_moq: int | None = None,
457
+ price_min: float | None = None,
458
+ price_max: float | None = None,
459
+ hot_select: str = "",
460
+ shipping_filter: str = "",
461
+ seller_tenure: str = "",
462
+ localisation_service: str = "",
463
+ certifications: Sequence[str] | None = None,
464
+ no_cache: bool = False,
465
+ max_total_charge_usd: float | Decimal | None = None,
466
+ ) -> list[dict[str, Any]]:
467
+ """Search 1688 Global cross-border catalog with 15 localized currencies, MOQ filters, and CE/FCC/RoHS compliance."""
468
+ queries = [keyword.strip()] if isinstance(keyword, str) else [str(q).strip() for q in keyword if q and str(q).strip()]
469
+ if not queries:
470
+ raise ValueError("keyword must contain at least one non-empty query.")
471
+
472
+ certs = [c.strip() for c in (certifications or []) if c and c.strip()]
473
+ actor_input: dict[str, Any] = {
474
+ "mode": "search",
475
+ "queries": queries,
476
+ "maxItems": max(1, min(5000, int(max_items))),
477
+ "detailLevel": detail_level,
478
+ "currency": currency,
479
+ "sortBy": sort_by,
480
+ }
481
+ if min_moq is not None:
482
+ actor_input["minMoq"] = int(min_moq)
483
+ if max_moq is not None:
484
+ actor_input["maxMoq"] = int(max_moq)
485
+ if price_min is not None:
486
+ actor_input["priceMin"] = str(price_min)
487
+ if price_max is not None:
488
+ actor_input["priceMax"] = str(price_max)
489
+ if hot_select:
490
+ actor_input["hotSelect"] = hot_select
491
+ if shipping_filter:
492
+ actor_input["shippingFilter"] = shipping_filter
493
+ if seller_tenure:
494
+ actor_input["sellerTenure"] = seller_tenure
495
+ if localisation_service:
496
+ actor_input["localisationService"] = localisation_service
497
+ if certs:
498
+ actor_input["certifications"] = certs
499
+
500
+ rest_params: dict[str, Any] = {
501
+ "keyword": queries[0],
502
+ "currency": currency,
503
+ "page": int(page),
504
+ "page_size": min(40, int(max_items)),
505
+ "sort_by": sort_by,
506
+ "min_moq": min_moq,
507
+ "max_moq": max_moq,
508
+ "price_min": price_min,
509
+ "price_max": price_max,
510
+ "hot_select": hot_select or None,
511
+ "shipping_filter": shipping_filter or None,
512
+ "seller_tenure": seller_tenure or None,
513
+ "localisation_service": localisation_service or None,
514
+ "certifications": ",".join(certs) if certs else None,
515
+ "no_cache": no_cache or None,
516
+ }
517
+
518
+ raw = self._client._transport.execute_operation(
519
+ service="1688",
520
+ operation="global/search",
521
+ actor_slug=ACTOR_1688_GLOBAL,
522
+ actor_input=actor_input,
523
+ http_method="GET",
524
+ params=rest_params,
525
+ max_total_charge_usd=max_total_charge_usd,
526
+ )
527
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
528
+
529
+
530
+ __all__ = [
531
+ "Ali1688Namespace",
532
+ "TierQuote",
533
+ "SkuInventorySummary",
534
+ "normalize_offer_id",
535
+ "normalize_province",
536
+ "resolve_unit_price_for_qty",
537
+ "summarize_sku_stock",
538
+ ]