string-schema 0.1.2__py3-none-any.whl → 0.1.4__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,345 @@
1
+ """
2
+ Built-in schema presets for Simple Schema
3
+
4
+ Contains commonly used schema definitions for typical data structures.
5
+ """
6
+
7
+ from typing import Any, Dict, List, Optional, Union
8
+ import logging
9
+
10
+ from ..core.fields import SimpleField
11
+ from ..core.builders import simple_schema, list_of_objects_schema
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def user_schema(include_email: bool = True, include_phone: bool = False,
17
+ include_profile: bool = False, include_preferences: bool = False) -> Dict[str, Any]:
18
+ """Generate enhanced user schema with special types"""
19
+ fields = {
20
+ 'name': SimpleField('string', 'Full name', min_length=1, max_length=100),
21
+ 'age': SimpleField('integer', 'Age in years', min_val=13, max_val=120, required=False)
22
+ }
23
+
24
+ if include_email:
25
+ fields['email'] = SimpleField('string', 'Email address', format_hint='email')
26
+
27
+ if include_phone:
28
+ fields['phone'] = SimpleField('string', 'Phone number', format_hint='phone', required=False)
29
+
30
+ if include_profile:
31
+ fields['bio'] = SimpleField('string', 'Biography', max_length=500, required=False)
32
+ fields['avatar'] = SimpleField('string', 'Avatar URL', format_hint='url', required=False)
33
+
34
+ if include_preferences:
35
+ fields['theme'] = SimpleField('string', 'UI theme', choices=['light', 'dark'], required=False)
36
+ fields['notifications'] = SimpleField('boolean', 'Email notifications enabled', required=False)
37
+
38
+ return simple_schema(fields)
39
+
40
+
41
+ def product_schema(include_price: bool = True, include_description: bool = True,
42
+ include_images: bool = False, include_reviews: bool = False) -> Dict[str, Any]:
43
+ """Generate enhanced product schema"""
44
+ fields = {
45
+ 'name': SimpleField('string', 'Product name', min_length=1, max_length=200),
46
+ 'category': SimpleField('string', 'Product category',
47
+ choices=['electronics', 'clothing', 'books', 'home', 'sports'])
48
+ }
49
+
50
+ if include_price:
51
+ fields['price'] = SimpleField('number', 'Price', min_val=0)
52
+
53
+ if include_description:
54
+ fields['description'] = SimpleField('string', 'Product description',
55
+ max_length=1000, required=False)
56
+
57
+ if include_images:
58
+ # This would need to be handled as a nested array, which is complex
59
+ # For now, we'll represent it as a simple field
60
+ fields['image_urls'] = SimpleField('string', 'Comma-separated image URLs', required=False)
61
+
62
+ if include_reviews:
63
+ # Similarly, this would be a complex nested structure
64
+ fields['avg_rating'] = SimpleField('number', 'Average rating', min_val=1.0, max_val=5.0, required=False)
65
+ fields['review_count'] = SimpleField('integer', 'Number of reviews', min_val=0, required=False)
66
+
67
+ return simple_schema(fields)
68
+
69
+
70
+ def contact_schema(include_company: bool = False, include_address: bool = False,
71
+ include_social: bool = False) -> Dict[str, Any]:
72
+ """Generate enhanced contact schema"""
73
+ fields = {
74
+ 'name': SimpleField('string', 'Contact name', min_length=1, max_length=100),
75
+ 'email': SimpleField('string', 'Email address', format_hint='email'),
76
+ 'phone': SimpleField('string', 'Phone number', format_hint='phone', required=False)
77
+ }
78
+
79
+ if include_company:
80
+ fields['company'] = SimpleField('string', 'Company name', max_length=200, required=False)
81
+ fields['job_title'] = SimpleField('string', 'Job title', max_length=100, required=False)
82
+
83
+ if include_address:
84
+ fields['address'] = SimpleField('string', 'Full address', max_length=500, required=False)
85
+ fields['city'] = SimpleField('string', 'City', max_length=100, required=False)
86
+ fields['country'] = SimpleField('string', 'Country', max_length=100, required=False)
87
+
88
+ if include_social:
89
+ fields['linkedin'] = SimpleField('string', 'LinkedIn URL', format_hint='url', required=False)
90
+ fields['twitter'] = SimpleField('string', 'Twitter URL', format_hint='url', required=False)
91
+ fields['website'] = SimpleField('string', 'Personal website', format_hint='url', required=False)
92
+
93
+ return simple_schema(fields)
94
+
95
+
96
+ def article_schema(include_summary: bool = True, include_tags: bool = False,
97
+ include_metadata: bool = False) -> Dict[str, Any]:
98
+ """Generate enhanced article schema"""
99
+ fields = {
100
+ 'title': SimpleField('string', 'Article title', min_length=1, max_length=200),
101
+ 'content': SimpleField('string', 'Article content', min_length=10)
102
+ }
103
+
104
+ if include_summary:
105
+ fields['summary'] = SimpleField('string', 'Brief summary', max_length=500, required=False)
106
+
107
+ if include_tags:
108
+ # Represented as comma-separated for simplicity
109
+ fields['tags'] = SimpleField('string', 'Comma-separated tags', max_length=200, required=False)
110
+
111
+ if include_metadata:
112
+ fields['author'] = SimpleField('string', 'Author name', max_length=100, required=False)
113
+ fields['published_date'] = SimpleField('string', 'Publication date', format_hint='date', required=False)
114
+ fields['word_count'] = SimpleField('integer', 'Word count', min_val=0, required=False)
115
+
116
+ return simple_schema(fields)
117
+
118
+
119
+ def event_schema(include_location: bool = True, include_attendees: bool = False) -> Dict[str, Any]:
120
+ """Generate enhanced event schema"""
121
+ fields = {
122
+ 'title': SimpleField('string', 'Event title', min_length=1, max_length=200),
123
+ 'date': SimpleField('string', 'Event date', format_hint='datetime'),
124
+ 'status': SimpleField('string', 'Event status',
125
+ choices=['planned', 'active', 'completed', 'cancelled'])
126
+ }
127
+
128
+ if include_location:
129
+ fields['venue'] = SimpleField('string', 'Venue name', max_length=200, required=False)
130
+ fields['address'] = SimpleField('string', 'Event address', max_length=500, required=False)
131
+ fields['is_online'] = SimpleField('boolean', 'Is online event', required=False)
132
+ fields['meeting_url'] = SimpleField('string', 'Meeting URL', format_hint='url', required=False)
133
+
134
+ if include_attendees:
135
+ fields['max_attendees'] = SimpleField('integer', 'Maximum attendees', min_val=1, required=False)
136
+ fields['current_attendees'] = SimpleField('integer', 'Current attendee count', min_val=0, required=False)
137
+
138
+ return simple_schema(fields)
139
+
140
+
141
+ # List versions of schemas
142
+ def user_list_schema(**kwargs) -> Dict[str, Any]:
143
+ """Generate schema for array of users"""
144
+ user_fields = {}
145
+ user_base = user_schema(**kwargs)
146
+
147
+ # Convert properties to SimpleField definitions
148
+ for field_name, field_schema in user_base['properties'].items():
149
+ field_type = field_schema['type']
150
+ required = field_name in user_base.get('required', [])
151
+
152
+ simple_field = SimpleField(field_type, required=required)
153
+
154
+ # Copy constraints
155
+ if 'minimum' in field_schema:
156
+ simple_field.min_val = field_schema['minimum']
157
+ if 'maximum' in field_schema:
158
+ simple_field.max_val = field_schema['maximum']
159
+ if 'minLength' in field_schema:
160
+ simple_field.min_length = field_schema['minLength']
161
+ if 'maxLength' in field_schema:
162
+ simple_field.max_length = field_schema['maxLength']
163
+ if 'enum' in field_schema:
164
+ simple_field.choices = field_schema['enum']
165
+ if 'format' in field_schema:
166
+ simple_field.format_hint = field_schema['format']
167
+
168
+ user_fields[field_name] = simple_field
169
+
170
+ return list_of_objects_schema(user_fields, "List of users")
171
+
172
+
173
+ def product_list_schema(**kwargs) -> Dict[str, Any]:
174
+ """Generate schema for array of products"""
175
+ return _convert_object_to_list_schema(product_schema(**kwargs), "List of products")
176
+
177
+
178
+ def contact_list_schema(**kwargs) -> Dict[str, Any]:
179
+ """Generate schema for array of contacts"""
180
+ return _convert_object_to_list_schema(contact_schema(**kwargs), "List of contacts")
181
+
182
+
183
+ def article_list_schema(**kwargs) -> Dict[str, Any]:
184
+ """Generate schema for array of articles"""
185
+ return _convert_object_to_list_schema(article_schema(**kwargs), "List of articles")
186
+
187
+
188
+ def event_list_schema(**kwargs) -> Dict[str, Any]:
189
+ """Generate schema for array of events"""
190
+ return _convert_object_to_list_schema(event_schema(**kwargs), "List of events")
191
+
192
+
193
+ def _convert_object_to_list_schema(object_schema: Dict[str, Any], description: str) -> Dict[str, Any]:
194
+ """Helper function to convert object schema to list schema"""
195
+ fields = {}
196
+
197
+ # Convert properties to SimpleField definitions
198
+ for field_name, field_schema in object_schema['properties'].items():
199
+ field_type = field_schema['type']
200
+ required = field_name in object_schema.get('required', [])
201
+
202
+ simple_field = SimpleField(field_type, required=required)
203
+
204
+ # Copy constraints
205
+ if 'minimum' in field_schema:
206
+ simple_field.min_val = field_schema['minimum']
207
+ if 'maximum' in field_schema:
208
+ simple_field.max_val = field_schema['maximum']
209
+ if 'minLength' in field_schema:
210
+ simple_field.min_length = field_schema['minLength']
211
+ if 'maxLength' in field_schema:
212
+ simple_field.max_length = field_schema['maxLength']
213
+ if 'enum' in field_schema:
214
+ simple_field.choices = field_schema['enum']
215
+ if 'format' in field_schema:
216
+ simple_field.format_hint = field_schema['format']
217
+ if 'description' in field_schema:
218
+ simple_field.description = field_schema['description']
219
+
220
+ fields[field_name] = simple_field
221
+
222
+ return list_of_objects_schema(fields, description)
223
+
224
+
225
+ # Enhanced utility schemas
226
+ def simple_list_schema(item_type: str = 'string', description: str = 'List of items',
227
+ min_items: Optional[int] = None, max_items: Optional[int] = None) -> Dict[str, Any]:
228
+ """Generate schema for simple arrays with enhanced constraints"""
229
+ from ..core.builders import simple_array_schema
230
+ return simple_array_schema(item_type, description, min_items, max_items)
231
+
232
+
233
+ def key_value_schema(description: str = 'Key-value pairs') -> Dict[str, Any]:
234
+ """Generate schema for flexible key-value objects"""
235
+ return {
236
+ "type": "object",
237
+ "description": description,
238
+ "additionalProperties": {"type": "string"}
239
+ }
240
+
241
+
242
+ def enum_schema(field_name: str, values: List[str], description: str = "") -> Dict[str, Any]:
243
+ """Generate schema for a single enum field"""
244
+ fields = {
245
+ field_name: SimpleField('string', description, choices=values)
246
+ }
247
+ return simple_schema(fields)
248
+
249
+
250
+ def union_schema(field_name: str, types: List[str], description: str = "") -> Dict[str, Any]:
251
+ """Generate schema for a single union field"""
252
+ fields = {
253
+ field_name: SimpleField('string', description, union_types=types)
254
+ }
255
+ return simple_schema(fields)
256
+
257
+
258
+ # Enhanced examples with all new features
259
+ ENHANCED_EXAMPLES = {
260
+ "simple_user": {
261
+ "description": "Basic user information with special types",
262
+ "schema": user_schema(include_email=True, include_phone=True),
263
+ "prompt_example": "Extract user: John Doe, 25 years old, john@example.com, phone +1-555-0123"
264
+ },
265
+
266
+ "product_with_enum": {
267
+ "description": "Product with category enum",
268
+ "schema": product_schema(include_price=True, include_description=True),
269
+ "prompt_example": "Product: iPhone 14, $999, Electronics category, Latest smartphone with advanced features"
270
+ },
271
+
272
+ "contact_with_social": {
273
+ "description": "Contact with social media links",
274
+ "schema": contact_schema(include_company=True, include_social=True),
275
+ "prompt_example": "Contact: Jane Smith, jane@company.org, works at TechCorp as Developer, LinkedIn: linkedin.com/in/janesmith"
276
+ },
277
+
278
+ "simple_string_array": {
279
+ "description": "Simple array of strings (FIXED!)",
280
+ "schema": simple_list_schema('string', 'List of tags', max_items=5),
281
+ "prompt_example": "Tags: python, javascript, react, machine-learning, AI"
282
+ },
283
+
284
+ "email_array": {
285
+ "description": "Array of email addresses",
286
+ "schema": simple_list_schema('string', 'List of emails', min_items=1, max_items=3),
287
+ "prompt_example": "Emails: john@example.com, jane@company.org, admin@website.com"
288
+ },
289
+
290
+ "user_list": {
291
+ "description": "List of user objects",
292
+ "schema": user_list_schema(include_email=True),
293
+ "prompt_example": "Users: John Doe (25, john@example.com), Jane Smith (30, jane@company.org)"
294
+ },
295
+
296
+ "enum_status": {
297
+ "description": "Simple enum field",
298
+ "schema": enum_schema('status', ['active', 'inactive', 'pending'], 'User status'),
299
+ "prompt_example": "Status: active"
300
+ },
301
+
302
+ "union_id": {
303
+ "description": "Union type field",
304
+ "schema": union_schema('id', ['string', 'integer'], 'Flexible ID field'),
305
+ "prompt_example": "ID: abc123 or ID: 12345"
306
+ }
307
+ }
308
+
309
+
310
+ def get_examples() -> Dict[str, Dict[str, Any]]:
311
+ """Get all enhanced simple schema examples"""
312
+ return ENHANCED_EXAMPLES.copy()
313
+
314
+
315
+ def print_examples():
316
+ """Print all enhanced simple schema examples"""
317
+ print("🔧 Enhanced Simple Schema Examples:")
318
+ print("=" * 60)
319
+
320
+ for name, example in ENHANCED_EXAMPLES.items():
321
+ print(f"\n📋 {name.upper().replace('_', ' ')}")
322
+ print(f"Description: {example['description']}")
323
+ print(f"Prompt: {example['prompt_example']}")
324
+ print(f"Schema Preview: {_schema_preview(example['schema'])}")
325
+ print("-" * 40)
326
+
327
+
328
+ def _schema_preview(schema: Dict[str, Any]) -> str:
329
+ """Generate a preview of the schema structure"""
330
+ if schema.get('type') == 'object':
331
+ properties = schema.get('properties', {})
332
+ field_names = list(properties.keys())
333
+ if len(field_names) <= 3:
334
+ return f"Object with fields: {', '.join(field_names)}"
335
+ else:
336
+ return f"Object with {len(field_names)} fields: {', '.join(field_names[:3])}..."
337
+ elif schema.get('type') == 'array':
338
+ items = schema.get('items', {})
339
+ if items.get('type') == 'object':
340
+ item_fields = list(items.get('properties', {}).keys())
341
+ return f"Array of objects with fields: {', '.join(item_fields[:3])}"
342
+ else:
343
+ return f"Array of {items.get('type', 'items')}"
344
+ else:
345
+ return f"{schema.get('type', 'unknown')} type"