ozon-sdk-pro 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.
- ozon_parser/__init__.py +137 -0
- ozon_parser/_model.py +370 -0
- ozon_parser/ai.py +1024 -0
- ozon_parser/browser.py +154 -0
- ozon_parser/cli.py +480 -0
- ozon_parser/client.py +640 -0
- ozon_parser/config.py +111 -0
- ozon_parser/endpoints.py +279 -0
- ozon_parser/exceptions.py +46 -0
- ozon_parser/export.py +330 -0
- ozon_parser/gui/__init__.py +25 -0
- ozon_parser/gui/app.py +1171 -0
- ozon_parser/http.py +469 -0
- ozon_parser/mcp_server.py +444 -0
- ozon_parser/models.py +207 -0
- ozon_parser/py.typed +0 -0
- ozon_parser/rank.py +209 -0
- ozon_parser/reviews.py +267 -0
- ozon_parser/telegram.py +144 -0
- ozon_parser/tracker.py +200 -0
- ozon_parser/widgets.py +526 -0
- ozon_sdk_pro-1.0.0.dist-info/METADATA +345 -0
- ozon_sdk_pro-1.0.0.dist-info/RECORD +26 -0
- ozon_sdk_pro-1.0.0.dist-info/WHEEL +4 -0
- ozon_sdk_pro-1.0.0.dist-info/entry_points.txt +5 -0
- ozon_sdk_pro-1.0.0.dist-info/licenses/LICENSE +21 -0
ozon_parser/__init__.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Ozon SDK Pro (`ozon_parser` / `ozon-sdk-pro`).
|
|
3
|
+
|
|
4
|
+
Modular Python Sync/Async SDK, CLI (`ozon-parser` / `ozon-sdk`), Native MCP Server (`ozon-mcp`),
|
|
5
|
+
and optional 7-Tab CustomTkinter Desktop GUI (`ozon-gui`) for:
|
|
6
|
+
- Direct Composer API v2 product, seller (company + INN + orders + rating), search & category scraping
|
|
7
|
+
- Ozon Card discount math & SQLite price-drop history (`OzonPriceTracker`)
|
|
8
|
+
- Multi-page Search Rank Tracking with SQLite history deltas (`OzonRankTracker`)
|
|
9
|
+
- Smart Review Extractor & Hybrid AI Engine (`SmartOzonReviewAnalyzer` + `ozon_parser.ai`):
|
|
10
|
+
Offline NLP, Free zero-key AI (`g4f` / local `Ollama`), Hybrid (`OpenRouter` `:free` / `Groq` / `Gemini`),
|
|
11
|
+
and Paid APIs (`OpenAI` / `DeepSeek` / `ProxyAPI`) with built-in health diagnostics
|
|
12
|
+
- Resilient HTTP transport (`curl_cffi` -> `httpx` -> `requests`, IPv4, proxy rotation) + optional `[browser]` Chrome fallback
|
|
13
|
+
- Telegram alerts & styled Excel / CSV / JSON / JSONL / Pandas exports
|
|
14
|
+
|
|
15
|
+
Supports CPython 3.8-3.16, PyPy 3.8-3.12, and Free-Threaded No-GIL (3.13t-3.16t).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
__version__ = "1.0.0"
|
|
21
|
+
|
|
22
|
+
from ozon_parser.ai import (
|
|
23
|
+
AI_PROVIDER_PRESETS,
|
|
24
|
+
AIChatResult,
|
|
25
|
+
AIClient,
|
|
26
|
+
AIProviderInfo,
|
|
27
|
+
AIProviderResult,
|
|
28
|
+
FREE_G4F_CANDIDATES,
|
|
29
|
+
find_ai_provider,
|
|
30
|
+
generate_completion,
|
|
31
|
+
is_g4f_available,
|
|
32
|
+
list_ai_providers,
|
|
33
|
+
quick_scan_ai_providers,
|
|
34
|
+
test_ai_provider,
|
|
35
|
+
)
|
|
36
|
+
from ozon_parser.client import AsyncOzonClient, OzonClient, ParseOzon, filter_products
|
|
37
|
+
from ozon_parser.config import OzonConfig, REVIEW_SORT_OPTIONS, SORT_OPTIONS
|
|
38
|
+
from ozon_parser.endpoints import (
|
|
39
|
+
category_api_url,
|
|
40
|
+
classify_target,
|
|
41
|
+
extract_inn,
|
|
42
|
+
extract_seller_id,
|
|
43
|
+
extract_sku,
|
|
44
|
+
parse_price_number,
|
|
45
|
+
product_api_url,
|
|
46
|
+
product_page_url,
|
|
47
|
+
reviews_api_url,
|
|
48
|
+
search_api_url,
|
|
49
|
+
seller_catalog_api_url,
|
|
50
|
+
seller_modal_api_url,
|
|
51
|
+
)
|
|
52
|
+
from ozon_parser.exceptions import (
|
|
53
|
+
OzonAntiBotError,
|
|
54
|
+
OzonError,
|
|
55
|
+
OzonNetworkError,
|
|
56
|
+
OzonNotFoundError,
|
|
57
|
+
OzonRateLimitError,
|
|
58
|
+
OzonValidationError,
|
|
59
|
+
)
|
|
60
|
+
from ozon_parser.export import (
|
|
61
|
+
rank_results_to_excel,
|
|
62
|
+
reviews_to_excel,
|
|
63
|
+
to_csv,
|
|
64
|
+
to_dataframe,
|
|
65
|
+
to_excel,
|
|
66
|
+
to_json,
|
|
67
|
+
to_jsonl,
|
|
68
|
+
)
|
|
69
|
+
from ozon_parser.models import (
|
|
70
|
+
OzonProduct,
|
|
71
|
+
OzonReviewItem,
|
|
72
|
+
OzonReviewSummary,
|
|
73
|
+
PriceRecord,
|
|
74
|
+
SellerInfo,
|
|
75
|
+
)
|
|
76
|
+
from ozon_parser.rank import OzonRankTracker, RankResult
|
|
77
|
+
from ozon_parser.reviews import SmartOzonReviewAnalyzer
|
|
78
|
+
from ozon_parser.telegram import TelegramNotifier
|
|
79
|
+
from ozon_parser.tracker import OzonPriceTracker
|
|
80
|
+
|
|
81
|
+
__all__ = [
|
|
82
|
+
"__version__",
|
|
83
|
+
"AI_PROVIDER_PRESETS",
|
|
84
|
+
"AIChatResult",
|
|
85
|
+
"AIClient",
|
|
86
|
+
"AIProviderInfo",
|
|
87
|
+
"AIProviderResult",
|
|
88
|
+
"AsyncOzonClient",
|
|
89
|
+
"FREE_G4F_CANDIDATES",
|
|
90
|
+
"OzonAntiBotError",
|
|
91
|
+
"OzonClient",
|
|
92
|
+
"OzonConfig",
|
|
93
|
+
"OzonError",
|
|
94
|
+
"OzonNetworkError",
|
|
95
|
+
"OzonNotFoundError",
|
|
96
|
+
"OzonPriceTracker",
|
|
97
|
+
"OzonProduct",
|
|
98
|
+
"OzonRankTracker",
|
|
99
|
+
"OzonRateLimitError",
|
|
100
|
+
"OzonReviewItem",
|
|
101
|
+
"OzonReviewSummary",
|
|
102
|
+
"OzonValidationError",
|
|
103
|
+
"ParseOzon",
|
|
104
|
+
"PriceRecord",
|
|
105
|
+
"REVIEW_SORT_OPTIONS",
|
|
106
|
+
"RankResult",
|
|
107
|
+
"SORT_OPTIONS",
|
|
108
|
+
"SellerInfo",
|
|
109
|
+
"SmartOzonReviewAnalyzer",
|
|
110
|
+
"TelegramNotifier",
|
|
111
|
+
"category_api_url",
|
|
112
|
+
"classify_target",
|
|
113
|
+
"extract_inn",
|
|
114
|
+
"extract_seller_id",
|
|
115
|
+
"extract_sku",
|
|
116
|
+
"filter_products",
|
|
117
|
+
"find_ai_provider",
|
|
118
|
+
"generate_completion",
|
|
119
|
+
"is_g4f_available",
|
|
120
|
+
"list_ai_providers",
|
|
121
|
+
"parse_price_number",
|
|
122
|
+
"product_api_url",
|
|
123
|
+
"product_page_url",
|
|
124
|
+
"quick_scan_ai_providers",
|
|
125
|
+
"rank_results_to_excel",
|
|
126
|
+
"reviews_api_url",
|
|
127
|
+
"reviews_to_excel",
|
|
128
|
+
"search_api_url",
|
|
129
|
+
"seller_catalog_api_url",
|
|
130
|
+
"seller_modal_api_url",
|
|
131
|
+
"test_ai_provider",
|
|
132
|
+
"to_csv",
|
|
133
|
+
"to_dataframe",
|
|
134
|
+
"to_excel",
|
|
135
|
+
"to_json",
|
|
136
|
+
"to_jsonl",
|
|
137
|
+
]
|
ozon_parser/_model.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lightweight, zero-dependency, Free-Threaded (No-GIL) safe model layer for `ozon_parser`.
|
|
3
|
+
|
|
4
|
+
Implements a clean Pydantic-v2-compatible subset (`BaseModel`, `Field`, `ConfigDict`,
|
|
5
|
+
`model_validator`, `model_validate`, `model_dump`, `model_dump_json`) in 100% pure Python
|
|
6
|
+
so the core SDK runs natively on CPython 3.8-3.16, PyPy 3.8-3.12, No-GIL 3.13t-3.16t, and Debian APT.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import functools
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
import threading
|
|
15
|
+
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
from typing import get_args, get_origin, get_type_hints
|
|
19
|
+
except ImportError: # pragma: no cover
|
|
20
|
+
from typing_extensions import get_args, get_origin, get_type_hints # type: ignore
|
|
21
|
+
|
|
22
|
+
T = TypeVar("T", bound="BaseModel")
|
|
23
|
+
|
|
24
|
+
_NONE_TYPE = type(None)
|
|
25
|
+
_SPEC_LOCK = threading.RLock()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _UnsetType:
|
|
29
|
+
"""Sentinel distinguishing omitted default values from explicit `None`."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_UNSET = _UnsetType()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _FieldInfo:
|
|
36
|
+
__slots__ = ("default", "default_factory", "alias")
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
*,
|
|
41
|
+
default: Any = _UNSET,
|
|
42
|
+
default_factory: Optional[Callable[[], Any]] = None,
|
|
43
|
+
alias: Optional[str] = None,
|
|
44
|
+
) -> None:
|
|
45
|
+
self.default = default
|
|
46
|
+
self.default_factory = default_factory
|
|
47
|
+
self.alias = alias
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def Field(
|
|
51
|
+
default: Any = _UNSET,
|
|
52
|
+
*,
|
|
53
|
+
default_factory: Optional[Callable[[], Any]] = None,
|
|
54
|
+
alias: Optional[str] = None,
|
|
55
|
+
**_extra: Any,
|
|
56
|
+
) -> Any:
|
|
57
|
+
"""Declare field defaults, factories, or input aliases on a `BaseModel`."""
|
|
58
|
+
return _FieldInfo(default=default, default_factory=default_factory, alias=alias)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def ConfigDict(**kwargs: Any) -> Dict[str, Any]:
|
|
62
|
+
"""Build model configuration dictionary (`extra`, `populate_by_name`, etc.)."""
|
|
63
|
+
return dict(kwargs)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class _BeforeValidator:
|
|
67
|
+
"""Descriptor wrapping a `@model_validator(mode='before')` method."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, fn: Any) -> None:
|
|
70
|
+
self._is_cm = isinstance(fn, classmethod)
|
|
71
|
+
self.fn = fn.__func__ if self._is_cm else fn
|
|
72
|
+
self._ozon_before_validator = True
|
|
73
|
+
|
|
74
|
+
def __get__(self, instance: Any, owner: Any = None) -> Any:
|
|
75
|
+
cls = owner if owner is not None else type(instance)
|
|
76
|
+
return functools.partial(self.fn, cls) if self._is_cm else self.fn
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def model_validator(*, mode: str = "before") -> Callable[[Any], Any]:
|
|
80
|
+
"""Register a pre-validation normalization hook (`mode='before'`)."""
|
|
81
|
+
|
|
82
|
+
def _decorator(fn: Any) -> Any:
|
|
83
|
+
if mode == "before":
|
|
84
|
+
return _BeforeValidator(fn)
|
|
85
|
+
return fn
|
|
86
|
+
|
|
87
|
+
return _decorator
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _FieldSpec:
|
|
91
|
+
__slots__ = ("name", "annotation", "default", "default_factory", "alias")
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
*,
|
|
96
|
+
name: str,
|
|
97
|
+
annotation: Any,
|
|
98
|
+
default: Any,
|
|
99
|
+
default_factory: Optional[Callable[[], Any]],
|
|
100
|
+
alias: Optional[str],
|
|
101
|
+
) -> None:
|
|
102
|
+
self.name = name
|
|
103
|
+
self.annotation = annotation
|
|
104
|
+
self.default = default
|
|
105
|
+
self.default_factory = default_factory
|
|
106
|
+
self.alias = alias
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class _ModelSpec:
|
|
110
|
+
__slots__ = ("fields", "before_validators", "populate_by_name", "extra")
|
|
111
|
+
|
|
112
|
+
def __init__(
|
|
113
|
+
self,
|
|
114
|
+
*,
|
|
115
|
+
fields: List[_FieldSpec],
|
|
116
|
+
before_validators: List[Callable[..., Any]],
|
|
117
|
+
populate_by_name: bool,
|
|
118
|
+
extra: str,
|
|
119
|
+
) -> None:
|
|
120
|
+
self.fields = fields
|
|
121
|
+
self.before_validators = before_validators
|
|
122
|
+
self.populate_by_name = populate_by_name
|
|
123
|
+
self.extra = extra
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _copy_default(value: Any) -> Any:
|
|
127
|
+
if isinstance(value, (list, dict, set)):
|
|
128
|
+
return value.copy()
|
|
129
|
+
return value
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _dump_value(value: Any) -> Any:
|
|
133
|
+
if isinstance(value, BaseModel):
|
|
134
|
+
return value.model_dump()
|
|
135
|
+
if isinstance(value, list):
|
|
136
|
+
return [_dump_value(item) for item in value]
|
|
137
|
+
if isinstance(value, tuple):
|
|
138
|
+
return [_dump_value(item) for item in value]
|
|
139
|
+
if isinstance(value, dict):
|
|
140
|
+
return {k: _dump_value(v) for k, v in value.items()}
|
|
141
|
+
return value
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _coerce_value(value: Any, annotation: Any) -> Any:
|
|
145
|
+
if annotation is Any or annotation is object:
|
|
146
|
+
return value
|
|
147
|
+
|
|
148
|
+
origin = get_origin(annotation)
|
|
149
|
+
args = get_args(annotation)
|
|
150
|
+
|
|
151
|
+
if origin is Union:
|
|
152
|
+
if value is None and _NONE_TYPE in args:
|
|
153
|
+
return None
|
|
154
|
+
non_none = [arg for arg in args if arg is not _NONE_TYPE]
|
|
155
|
+
if len(non_none) == 1:
|
|
156
|
+
return _coerce_value(value, non_none[0])
|
|
157
|
+
for candidate in non_none:
|
|
158
|
+
try:
|
|
159
|
+
return _coerce_value(value, candidate)
|
|
160
|
+
except Exception:
|
|
161
|
+
continue
|
|
162
|
+
return value
|
|
163
|
+
|
|
164
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
165
|
+
if isinstance(value, annotation):
|
|
166
|
+
return value
|
|
167
|
+
if isinstance(value, dict):
|
|
168
|
+
return annotation.model_validate(value)
|
|
169
|
+
return value
|
|
170
|
+
|
|
171
|
+
if origin in (list, List):
|
|
172
|
+
if value is None:
|
|
173
|
+
return []
|
|
174
|
+
seq = list(value)
|
|
175
|
+
if args and args[0] is not Any:
|
|
176
|
+
elem_type = args[0]
|
|
177
|
+
return [_coerce_value(item, elem_type) for item in seq]
|
|
178
|
+
return seq
|
|
179
|
+
|
|
180
|
+
if origin in (dict, Dict):
|
|
181
|
+
if value is None:
|
|
182
|
+
return {}
|
|
183
|
+
if not isinstance(value, dict):
|
|
184
|
+
return dict(value)
|
|
185
|
+
key_type = args[0] if len(args) >= 1 else Any
|
|
186
|
+
val_type = args[1] if len(args) >= 2 else Any
|
|
187
|
+
return {
|
|
188
|
+
_coerce_value(k, key_type): _coerce_value(v, val_type)
|
|
189
|
+
for k, v in value.items()
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if annotation is bool:
|
|
193
|
+
return bool(value)
|
|
194
|
+
|
|
195
|
+
if annotation is int:
|
|
196
|
+
if isinstance(value, bool):
|
|
197
|
+
return int(value)
|
|
198
|
+
if isinstance(value, int):
|
|
199
|
+
return value
|
|
200
|
+
try:
|
|
201
|
+
return int(value)
|
|
202
|
+
except (TypeError, ValueError):
|
|
203
|
+
return int(float(value))
|
|
204
|
+
|
|
205
|
+
if annotation is float:
|
|
206
|
+
return float(value)
|
|
207
|
+
|
|
208
|
+
if annotation is str:
|
|
209
|
+
return "" if value is None else str(value)
|
|
210
|
+
|
|
211
|
+
return value
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _compile_model_spec(cls: Type["BaseModel"]) -> _ModelSpec:
|
|
215
|
+
fields: List[_FieldSpec] = []
|
|
216
|
+
before_validators: List[Callable[..., Any]] = []
|
|
217
|
+
seen_fields: Set[str] = set()
|
|
218
|
+
field_order: List[str] = []
|
|
219
|
+
hints: Dict[str, Any] = {}
|
|
220
|
+
defaults: Dict[str, Any] = {}
|
|
221
|
+
|
|
222
|
+
for base in reversed(cls.__mro__):
|
|
223
|
+
if base in (BaseModel, object):
|
|
224
|
+
continue
|
|
225
|
+
|
|
226
|
+
raw_ann = base.__dict__.get("__annotations__", {})
|
|
227
|
+
mod = sys.modules.get(base.__module__)
|
|
228
|
+
base_globals = getattr(mod, "__dict__", {}) if mod is not None else {}
|
|
229
|
+
try:
|
|
230
|
+
resolved_hints = get_type_hints(base, globalns=base_globals)
|
|
231
|
+
except Exception:
|
|
232
|
+
resolved_hints = {}
|
|
233
|
+
|
|
234
|
+
for fname in raw_ann:
|
|
235
|
+
if fname == "model_config":
|
|
236
|
+
continue
|
|
237
|
+
if fname not in seen_fields:
|
|
238
|
+
seen_fields.add(fname)
|
|
239
|
+
field_order.append(fname)
|
|
240
|
+
hints[fname] = resolved_hints.get(fname, Any)
|
|
241
|
+
|
|
242
|
+
for attr_name, attr_val in base.__dict__.items():
|
|
243
|
+
if attr_name in raw_ann and attr_name != "model_config":
|
|
244
|
+
defaults[attr_name] = attr_val
|
|
245
|
+
if isinstance(attr_val, _BeforeValidator):
|
|
246
|
+
before_validators.append(attr_val.fn)
|
|
247
|
+
|
|
248
|
+
for fname in field_order:
|
|
249
|
+
raw_def = defaults.get(fname, _UNSET)
|
|
250
|
+
if isinstance(raw_def, _FieldInfo):
|
|
251
|
+
f_default = raw_def.default
|
|
252
|
+
f_factory = raw_def.default_factory
|
|
253
|
+
f_alias = raw_def.alias
|
|
254
|
+
else:
|
|
255
|
+
f_default = raw_def
|
|
256
|
+
f_factory = None
|
|
257
|
+
f_alias = None
|
|
258
|
+
fields.append(
|
|
259
|
+
_FieldSpec(
|
|
260
|
+
name=fname,
|
|
261
|
+
annotation=hints.get(fname, Any),
|
|
262
|
+
default=f_default,
|
|
263
|
+
default_factory=f_factory,
|
|
264
|
+
alias=f_alias,
|
|
265
|
+
)
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
cfg = getattr(cls, "model_config", None)
|
|
269
|
+
if not isinstance(cfg, dict):
|
|
270
|
+
cfg = {}
|
|
271
|
+
|
|
272
|
+
return _ModelSpec(
|
|
273
|
+
fields=fields,
|
|
274
|
+
before_validators=before_validators,
|
|
275
|
+
populate_by_name=bool(cfg.get("populate_by_name", False)),
|
|
276
|
+
extra=str(cfg.get("extra", "ignore")),
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _get_model_spec(cls: Type["BaseModel"]) -> _ModelSpec:
|
|
281
|
+
existing = cls.__dict__.get("__ozon_compiled_spec__")
|
|
282
|
+
if isinstance(existing, _ModelSpec):
|
|
283
|
+
return existing
|
|
284
|
+
with _SPEC_LOCK:
|
|
285
|
+
existing = cls.__dict__.get("__ozon_compiled_spec__")
|
|
286
|
+
if isinstance(existing, _ModelSpec):
|
|
287
|
+
return existing
|
|
288
|
+
spec = _compile_model_spec(cls)
|
|
289
|
+
setattr(cls, "__ozon_compiled_spec__", spec)
|
|
290
|
+
return spec
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
class BaseModel:
|
|
294
|
+
"""Thread-safe pure-Python base model compatible with Pydantic v2 SDK calls."""
|
|
295
|
+
|
|
296
|
+
model_config: Dict[str, Any] = ConfigDict(extra="ignore", populate_by_name=True)
|
|
297
|
+
|
|
298
|
+
def __init__(self, **data: Any) -> None:
|
|
299
|
+
self._populate_from_mapping(data)
|
|
300
|
+
|
|
301
|
+
def _populate_from_mapping(self, raw: Any) -> None:
|
|
302
|
+
cls = type(self)
|
|
303
|
+
spec = _get_model_spec(cls)
|
|
304
|
+
|
|
305
|
+
payload: Any = dict(raw) if isinstance(raw, dict) else raw
|
|
306
|
+
for fn in spec.before_validators:
|
|
307
|
+
payload = fn(cls, payload)
|
|
308
|
+
|
|
309
|
+
if not isinstance(payload, dict):
|
|
310
|
+
raise TypeError(f"{cls.__name__} expected dict input, got {type(payload).__name__}")
|
|
311
|
+
|
|
312
|
+
for field in spec.fields:
|
|
313
|
+
if spec.populate_by_name:
|
|
314
|
+
if field.name in payload:
|
|
315
|
+
val = payload[field.name]
|
|
316
|
+
elif field.alias and field.alias in payload:
|
|
317
|
+
val = payload[field.alias]
|
|
318
|
+
elif field.default_factory is not None:
|
|
319
|
+
val = field.default_factory()
|
|
320
|
+
elif field.default is not _UNSET:
|
|
321
|
+
val = _copy_default(field.default)
|
|
322
|
+
else:
|
|
323
|
+
raise ValueError(f"Missing required field {field.name!r} for {cls.__name__}")
|
|
324
|
+
else:
|
|
325
|
+
if field.alias and field.alias in payload:
|
|
326
|
+
val = payload[field.alias]
|
|
327
|
+
elif field.name in payload:
|
|
328
|
+
val = payload[field.name]
|
|
329
|
+
elif field.default_factory is not None:
|
|
330
|
+
val = field.default_factory()
|
|
331
|
+
elif field.default is not _UNSET:
|
|
332
|
+
val = _copy_default(field.default)
|
|
333
|
+
else:
|
|
334
|
+
raise ValueError(f"Missing required field {field.name!r} for {cls.__name__}")
|
|
335
|
+
|
|
336
|
+
setattr(self, field.name, _coerce_value(val, field.annotation))
|
|
337
|
+
|
|
338
|
+
@classmethod
|
|
339
|
+
def model_validate(cls: Type[T], obj: Any) -> T:
|
|
340
|
+
"""Create and validate a model instance from a dict or existing instance."""
|
|
341
|
+
if isinstance(obj, cls):
|
|
342
|
+
return obj
|
|
343
|
+
if isinstance(obj, BaseModel):
|
|
344
|
+
obj = obj.model_dump()
|
|
345
|
+
instance = cls.__new__(cls)
|
|
346
|
+
instance._populate_from_mapping(obj)
|
|
347
|
+
return instance
|
|
348
|
+
|
|
349
|
+
def model_dump(self) -> Dict[str, Any]:
|
|
350
|
+
"""Serialize model fields recursively to a plain dictionary."""
|
|
351
|
+
spec = _get_model_spec(type(self))
|
|
352
|
+
return {
|
|
353
|
+
field.name: _dump_value(getattr(self, field.name))
|
|
354
|
+
for field in spec.fields
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
def model_dump_json(self, indent: Optional[int] = None) -> str:
|
|
358
|
+
"""Serialize model fields recursively to UTF-8 JSON string."""
|
|
359
|
+
return json.dumps(self.model_dump(), ensure_ascii=False, indent=indent)
|
|
360
|
+
|
|
361
|
+
def __repr__(self) -> str:
|
|
362
|
+
spec = _get_model_spec(type(self))
|
|
363
|
+
parts = ", ".join(f"{f.name}={getattr(self, f.name)!r}" for f in spec.fields[:5])
|
|
364
|
+
suffix = ", ..." if len(spec.fields) > 5 else ""
|
|
365
|
+
return f"{type(self).__name__}({parts}{suffix})"
|
|
366
|
+
|
|
367
|
+
def __eq__(self, other: Any) -> bool:
|
|
368
|
+
if type(self) is not type(other):
|
|
369
|
+
return False
|
|
370
|
+
return self.model_dump() == other.model_dump()
|