ddex-workbench 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.
@@ -0,0 +1,35 @@
1
+ # packages/python-sdk/ddex_workbench/__init__.py
2
+ """
3
+ DDEX Workbench SDK for Python
4
+
5
+ Official Python SDK for DDEX validation and processing tools.
6
+ """
7
+
8
+ from .client import DDEXClient
9
+ from .validator import DDEXValidator
10
+ from .errors import (
11
+ DDEXError,
12
+ RateLimitError,
13
+ ValidationError,
14
+ AuthenticationError
15
+ )
16
+ from .types import (
17
+ ValidationResult,
18
+ ValidationError as ValidationErrorDetail,
19
+ ERNVersion,
20
+ ERNProfile
21
+ )
22
+
23
+ __version__ = "1.0.0"
24
+ __all__ = [
25
+ "DDEXClient",
26
+ "DDEXValidator",
27
+ "DDEXError",
28
+ "RateLimitError",
29
+ "ValidationError",
30
+ "AuthenticationError",
31
+ "ValidationResult",
32
+ "ValidationErrorDetail",
33
+ "ERNVersion",
34
+ "ERNProfile"
35
+ ]
@@ -0,0 +1,401 @@
1
+ # packages/python-sdk/ddex_workbench/client.py
2
+ """DDEX Workbench API Client"""
3
+
4
+ import time
5
+ from typing import Optional, Dict, Any, BinaryIO, Union, List
6
+ from pathlib import Path
7
+ import requests
8
+ from requests.adapters import HTTPAdapter
9
+ from urllib3.util.retry import Retry
10
+
11
+ from .errors import (
12
+ DDEXError,
13
+ RateLimitError,
14
+ AuthenticationError,
15
+ NotFoundError,
16
+ ValidationError as ValidationErrorException,
17
+ create_error_from_response
18
+ )
19
+ from .types import (
20
+ ValidationResult,
21
+ ValidationOptions,
22
+ SupportedFormats,
23
+ HealthStatus,
24
+ ApiKey
25
+ )
26
+ from .validator import DDEXValidator
27
+
28
+
29
+ class DDEXClient:
30
+ """
31
+ DDEX Workbench API Client
32
+
33
+ Example:
34
+ >>> from ddex_workbench import DDEXClient
35
+ >>> client = DDEXClient(api_key="ddex_your-api-key")
36
+ >>> result = client.validate(xml_content, version="4.3", profile="AudioAlbum")
37
+ >>> print(f"Valid: {result.valid}")
38
+ """
39
+
40
+ DEFAULT_BASE_URL = "https://api.ddex-workbench.org/v1"
41
+ DEFAULT_TIMEOUT = 30
42
+ DEFAULT_MAX_RETRIES = 3
43
+ DEFAULT_RETRY_DELAY = 1.0
44
+
45
+ def __init__(
46
+ self,
47
+ api_key: Optional[str] = None,
48
+ base_url: str = DEFAULT_BASE_URL,
49
+ timeout: int = DEFAULT_TIMEOUT,
50
+ max_retries: int = DEFAULT_MAX_RETRIES,
51
+ retry_delay: float = DEFAULT_RETRY_DELAY,
52
+ verify_ssl: bool = True
53
+ ):
54
+ """
55
+ Initialize DDEX Client
56
+
57
+ Args:
58
+ api_key: Optional API key for higher rate limits
59
+ base_url: API base URL
60
+ timeout: Request timeout in seconds
61
+ max_retries: Maximum number of retry attempts
62
+ retry_delay: Initial delay between retries (exponential backoff)
63
+ verify_ssl: Verify SSL certificates
64
+ """
65
+ self.api_key = api_key
66
+ self.base_url = base_url.rstrip('/')
67
+ self.timeout = timeout
68
+ self.max_retries = max_retries
69
+ self.retry_delay = retry_delay
70
+ self.verify_ssl = verify_ssl
71
+
72
+ # Create session with retry strategy
73
+ self.session = self._create_session()
74
+
75
+ # Create validator instance
76
+ self.validator = DDEXValidator(self)
77
+
78
+ def _create_session(self) -> requests.Session:
79
+ """Create and configure requests session with retry strategy"""
80
+ session = requests.Session()
81
+
82
+ # Configure retries
83
+ retry_strategy = Retry(
84
+ total=self.max_retries,
85
+ backoff_factor=self.retry_delay,
86
+ status_forcelist=[500, 502, 503, 504],
87
+ allowed_methods=["GET", "POST", "DELETE"]
88
+ )
89
+ adapter = HTTPAdapter(max_retries=retry_strategy)
90
+ session.mount("http://", adapter)
91
+ session.mount("https://", adapter)
92
+
93
+ # Set default headers
94
+ session.headers.update({
95
+ "Content-Type": "application/json",
96
+ "User-Agent": f"ddex-workbench-python-sdk/{self._get_version()}"
97
+ })
98
+
99
+ if self.api_key:
100
+ session.headers["X-API-Key"] = self.api_key
101
+
102
+ session.verify = self.verify_ssl
103
+
104
+ return session
105
+
106
+ def validate(
107
+ self,
108
+ content: str,
109
+ version: str,
110
+ profile: Optional[str] = None,
111
+ mode: Optional[str] = None,
112
+ strict: bool = False
113
+ ) -> ValidationResult:
114
+ """
115
+ Validate DDEX XML content
116
+
117
+ Args:
118
+ content: XML content as string
119
+ version: ERN version (e.g., "4.3", "4.2", "3.8.2")
120
+ profile: Optional profile (e.g., "AudioAlbum", "AudioSingle")
121
+ mode: Validation mode ("full", "quick", "xsd", "business")
122
+ strict: Treat warnings as errors
123
+
124
+ Returns:
125
+ ValidationResult object with errors and metadata
126
+
127
+ Example:
128
+ >>> result = client.validate(xml_content, version="4.3")
129
+ >>> if not result.valid:
130
+ ... for error in result.errors:
131
+ ... print(f"Line {error.line}: {error.message}")
132
+ """
133
+ payload = {
134
+ "content": content,
135
+ "type": "ERN",
136
+ "version": version
137
+ }
138
+
139
+ if profile:
140
+ payload["profile"] = profile
141
+ if mode:
142
+ payload["mode"] = mode
143
+ if strict:
144
+ payload["strict"] = strict
145
+
146
+ response = self._post("/api/validate", json=payload)
147
+ return ValidationResult.from_dict(response)
148
+
149
+ def validate_file(
150
+ self,
151
+ file_path: Union[str, Path, BinaryIO],
152
+ version: str,
153
+ profile: Optional[str] = None,
154
+ mode: Optional[str] = None
155
+ ) -> ValidationResult:
156
+ """
157
+ Validate DDEX XML file
158
+
159
+ Args:
160
+ file_path: Path to XML file or file-like object
161
+ version: ERN version
162
+ profile: Optional profile
163
+ mode: Optional validation mode
164
+
165
+ Returns:
166
+ ValidationResult object
167
+
168
+ Example:
169
+ >>> result = client.validate_file("release.xml", version="4.3")
170
+ >>> print(f"Valid: {result.valid}")
171
+ """
172
+ if isinstance(file_path, str):
173
+ file_path = Path(file_path)
174
+
175
+ if isinstance(file_path, Path):
176
+ if not file_path.exists():
177
+ raise FileNotFoundError(f"File not found: {file_path}")
178
+
179
+ with open(file_path, 'rb') as f:
180
+ files = {'file': (file_path.name, f, 'text/xml')}
181
+ data = {
182
+ 'type': 'ERN',
183
+ 'version': version
184
+ }
185
+ if profile:
186
+ data['profile'] = profile
187
+ if mode:
188
+ data['mode'] = mode
189
+
190
+ # Note: Don't use json parameter with files
191
+ response = self._post("/api/validate/file", files=files, data=data)
192
+ else:
193
+ # File-like object
194
+ files = {'file': ('document.xml', file_path, 'text/xml')}
195
+ data = {
196
+ 'type': 'ERN',
197
+ 'version': version
198
+ }
199
+ if profile:
200
+ data['profile'] = profile
201
+ if mode:
202
+ data['mode'] = mode
203
+
204
+ response = self._post("/api/validate/file", files=files, data=data)
205
+
206
+ return ValidationResult.from_dict(response)
207
+
208
+ def validate_url(
209
+ self,
210
+ url: str,
211
+ version: str,
212
+ profile: Optional[str] = None
213
+ ) -> ValidationResult:
214
+ """
215
+ Validate XML from URL
216
+
217
+ Args:
218
+ url: URL to XML file
219
+ version: ERN version
220
+ profile: Optional profile
221
+
222
+ Returns:
223
+ ValidationResult object
224
+
225
+ Example:
226
+ >>> result = client.validate_url("https://example.com/release.xml", version="4.3")
227
+ """
228
+ # Fetch XML content
229
+ try:
230
+ response = requests.get(url, timeout=self.timeout)
231
+ response.raise_for_status()
232
+ except requests.RequestException as e:
233
+ raise DDEXError(f"Failed to fetch XML from URL: {str(e)}")
234
+
235
+ return self.validate(response.text, version, profile)
236
+
237
+ def get_supported_formats(self) -> SupportedFormats:
238
+ """
239
+ Get supported DDEX formats and versions
240
+
241
+ Returns:
242
+ SupportedFormats object with version information
243
+ """
244
+ response = self._get("/api/formats")
245
+ return SupportedFormats.from_dict(response)
246
+
247
+ def check_health(self) -> HealthStatus:
248
+ """
249
+ Check API health status
250
+
251
+ Returns:
252
+ HealthStatus object
253
+ """
254
+ response = self._get("/api/health")
255
+ return HealthStatus.from_dict(response)
256
+
257
+ def list_api_keys(self, auth_token: str) -> List[ApiKey]:
258
+ """
259
+ List API keys for authenticated user
260
+
261
+ Args:
262
+ auth_token: Firebase auth token
263
+
264
+ Returns:
265
+ List of ApiKey objects
266
+ """
267
+ headers = {"Authorization": f"Bearer {auth_token}"}
268
+ response = self._get("/api/keys", headers=headers)
269
+ return [ApiKey.from_dict(key) for key in response]
270
+
271
+ def create_api_key(self, name: str, auth_token: str) -> ApiKey:
272
+ """
273
+ Create new API key
274
+
275
+ Args:
276
+ name: Friendly name for the key
277
+ auth_token: Firebase auth token
278
+
279
+ Returns:
280
+ ApiKey object (includes the key value only on creation)
281
+ """
282
+ headers = {"Authorization": f"Bearer {auth_token}"}
283
+ response = self._post("/api/keys", json={"name": name}, headers=headers)
284
+ return ApiKey.from_dict(response)
285
+
286
+ def revoke_api_key(self, key_id: str, auth_token: str) -> None:
287
+ """
288
+ Revoke API key
289
+
290
+ Args:
291
+ key_id: API key ID to revoke
292
+ auth_token: Firebase auth token
293
+ """
294
+ headers = {"Authorization": f"Bearer {auth_token}"}
295
+ self._delete(f"/api/keys/{key_id}", headers=headers)
296
+
297
+ def set_api_key(self, api_key: str) -> None:
298
+ """Update API key for this client instance"""
299
+ self.api_key = api_key
300
+ self.session.headers["X-API-Key"] = api_key
301
+
302
+ def clear_api_key(self) -> None:
303
+ """Remove API key from this client instance"""
304
+ self.api_key = None
305
+ self.session.headers.pop("X-API-Key", None)
306
+
307
+ # Private methods
308
+ def _get(self, path: str, headers: Optional[Dict] = None, **kwargs) -> Any:
309
+ """Internal GET request"""
310
+ return self._request("GET", path, headers=headers, **kwargs)
311
+
312
+ def _post(self, path: str, headers: Optional[Dict] = None, **kwargs) -> Any:
313
+ """Internal POST request"""
314
+ return self._request("POST", path, headers=headers, **kwargs)
315
+
316
+ def _delete(self, path: str, headers: Optional[Dict] = None, **kwargs) -> None:
317
+ """Internal DELETE request"""
318
+ self._request("DELETE", path, headers=headers, **kwargs)
319
+
320
+ def _request(
321
+ self,
322
+ method: str,
323
+ path: str,
324
+ headers: Optional[Dict] = None,
325
+ **kwargs
326
+ ) -> Optional[Any]:
327
+ """
328
+ Make HTTP request with error handling
329
+
330
+ Args:
331
+ method: HTTP method
332
+ path: API path
333
+ headers: Optional additional headers
334
+ **kwargs: Additional request parameters
335
+
336
+ Returns:
337
+ Response data or None
338
+
339
+ Raises:
340
+ DDEXError: On API errors
341
+ RateLimitError: On rate limiting
342
+ """
343
+ url = f"{self.base_url}{path}"
344
+
345
+ # Merge headers
346
+ if headers:
347
+ request_headers = dict(self.session.headers)
348
+ request_headers.update(headers)
349
+ kwargs["headers"] = request_headers
350
+
351
+ # Set timeout
352
+ kwargs.setdefault("timeout", self.timeout)
353
+
354
+ try:
355
+ response = self.session.request(method, url, **kwargs)
356
+
357
+ # Handle rate limiting
358
+ if response.status_code == 429:
359
+ retry_after = response.headers.get("Retry-After", "60")
360
+ raise RateLimitError(
361
+ f"Rate limit exceeded. Retry after {retry_after} seconds",
362
+ retry_after=int(retry_after) if retry_after.isdigit() else 60
363
+ )
364
+
365
+ # Handle authentication errors
366
+ if response.status_code == 401:
367
+ raise AuthenticationError("Authentication required or invalid API key")
368
+
369
+ # Handle not found
370
+ if response.status_code == 404:
371
+ raise NotFoundError(f"Resource not found: {path}")
372
+
373
+ # Raise for other HTTP errors
374
+ response.raise_for_status()
375
+
376
+ # Return JSON response if available
377
+ if response.text and response.status_code != 204:
378
+ return response.json()
379
+ return None
380
+
381
+ except requests.exceptions.RequestException as e:
382
+ # Convert requests exceptions to our custom exceptions
383
+ if not isinstance(e, (DDEXError, RateLimitError, AuthenticationError, NotFoundError)):
384
+ raise create_error_from_response(e)
385
+ raise
386
+
387
+ def _get_version(self) -> str:
388
+ """Get SDK version"""
389
+ try:
390
+ from . import __version__
391
+ return __version__
392
+ except ImportError:
393
+ return "1.0.0"
394
+
395
+ def __enter__(self):
396
+ """Context manager support"""
397
+ return self
398
+
399
+ def __exit__(self, exc_type, exc_val, exc_tb):
400
+ """Clean up session on exit"""
401
+ self.session.close()