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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Piclets Server API Documentation
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
The Piclets Server provides a Gradio-based API for saving and sharing AI-generated creatures (Piclets) from the Piclets game. This backend supports the main game client with persistent storage and sharing capabilities.
|
| 6 |
+
|
| 7 |
+
## Quick Start
|
| 8 |
+
|
| 9 |
+
### Running Locally
|
| 10 |
+
```bash
|
| 11 |
+
pip install -r requirements.txt
|
| 12 |
+
python app.py
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
### Accessing the API
|
| 16 |
+
- **Web Interface**: http://localhost:7860
|
| 17 |
+
- **Programmatic Access**: Use Gradio Client to connect to the space
|
| 18 |
+
|
| 19 |
+
## API Endpoints
|
| 20 |
+
|
| 21 |
+
### 1. Save Piclet
|
| 22 |
+
**Endpoint**: `/save_piclet_api`
|
| 23 |
+
**Method**: Gradio function call
|
| 24 |
+
**Purpose**: Save a new Piclet with optional image
|
| 25 |
+
|
| 26 |
+
**Input Parameters**:
|
| 27 |
+
- `piclet_json` (string): JSON-formatted Piclet data
|
| 28 |
+
- `image_file` (file, optional): Image file for the Piclet
|
| 29 |
+
|
| 30 |
+
**Response Format**:
|
| 31 |
+
```json
|
| 32 |
+
{
|
| 33 |
+
"success": true,
|
| 34 |
+
"piclet_id": "uuid-string",
|
| 35 |
+
"message": "Piclet saved successfully"
|
| 36 |
+
}
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
**Error Response**:
|
| 40 |
+
```json
|
| 41 |
+
{
|
| 42 |
+
"success": false,
|
| 43 |
+
"error": "Error description"
|
| 44 |
+
}
|
| 45 |
+
```
|
| 46 |
+
|
| 47 |
+
### 2. Get Piclet
|
| 48 |
+
**Endpoint**: `/get_piclet_api`
|
| 49 |
+
**Method**: Gradio function call
|
| 50 |
+
**Purpose**: Retrieve a Piclet by ID
|
| 51 |
+
|
| 52 |
+
**Input Parameters**:
|
| 53 |
+
- `piclet_id` (string): Unique Piclet identifier
|
| 54 |
+
|
| 55 |
+
**Response Format**:
|
| 56 |
+
```json
|
| 57 |
+
{
|
| 58 |
+
"success": true,
|
| 59 |
+
"piclet": {
|
| 60 |
+
"id": "uuid-string",
|
| 61 |
+
"name": "Piclet Name",
|
| 62 |
+
"description": "Description",
|
| 63 |
+
"tier": "medium",
|
| 64 |
+
"primaryType": "space",
|
| 65 |
+
"baseStats": { ... },
|
| 66 |
+
"movepool": [ ... ],
|
| 67 |
+
"created_at": "2024-07-26T10:30:00"
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
### 3. List Piclets
|
| 73 |
+
**Endpoint**: `/list_piclets_api`
|
| 74 |
+
**Method**: Gradio function call
|
| 75 |
+
**Purpose**: Get a list of all saved Piclets
|
| 76 |
+
|
| 77 |
+
**Input Parameters**:
|
| 78 |
+
- `limit` (integer): Maximum number of results (1-100, default: 50)
|
| 79 |
+
|
| 80 |
+
**Response Format**:
|
| 81 |
+
```json
|
| 82 |
+
{
|
| 83 |
+
"success": true,
|
| 84 |
+
"piclets": [
|
| 85 |
+
{
|
| 86 |
+
"id": "uuid-string",
|
| 87 |
+
"name": "Piclet Name",
|
| 88 |
+
"primaryType": "space",
|
| 89 |
+
"tier": "medium",
|
| 90 |
+
"created_at": "2024-07-26T10:30:00",
|
| 91 |
+
"has_image": true
|
| 92 |
+
}
|
| 93 |
+
],
|
| 94 |
+
"count": 1
|
| 95 |
+
}
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
### 4. Get Piclet Image
|
| 99 |
+
**Endpoint**: `/get_piclet_image_api`
|
| 100 |
+
**Method**: Gradio function call
|
| 101 |
+
**Purpose**: Retrieve the image associated with a Piclet
|
| 102 |
+
|
| 103 |
+
**Input Parameters**:
|
| 104 |
+
- `piclet_id` (string): Unique Piclet identifier
|
| 105 |
+
|
| 106 |
+
**Response**: Image file or None if not found
|
| 107 |
+
|
| 108 |
+
## Required JSON Format for Piclets
|
| 109 |
+
|
| 110 |
+
When saving a Piclet, the JSON must include these required fields:
|
| 111 |
+
|
| 112 |
+
```json
|
| 113 |
+
{
|
| 114 |
+
"name": "Stellar Wolf",
|
| 115 |
+
"description": "A majestic wolf creature infused with cosmic energy",
|
| 116 |
+
"tier": "medium",
|
| 117 |
+
"primaryType": "space",
|
| 118 |
+
"secondaryType": "beast",
|
| 119 |
+
"baseStats": {
|
| 120 |
+
"hp": 85,
|
| 121 |
+
"attack": 90,
|
| 122 |
+
"defense": 70,
|
| 123 |
+
"speed": 80
|
| 124 |
+
},
|
| 125 |
+
"nature": "Bold",
|
| 126 |
+
"specialAbility": {
|
| 127 |
+
"name": "Cosmic Howl",
|
| 128 |
+
"description": "Increases attack when health is low"
|
| 129 |
+
},
|
| 130 |
+
"movepool": [
|
| 131 |
+
{
|
| 132 |
+
"name": "Star Strike",
|
| 133 |
+
"type": "space",
|
| 134 |
+
"power": 75,
|
| 135 |
+
"accuracy": 90,
|
| 136 |
+
"pp": 15,
|
| 137 |
+
"priority": 0,
|
| 138 |
+
"flags": [],
|
| 139 |
+
"effects": [
|
| 140 |
+
{
|
| 141 |
+
"type": "damage",
|
| 142 |
+
"target": "opponent",
|
| 143 |
+
"amount": "normal"
|
| 144 |
+
}
|
| 145 |
+
]
|
| 146 |
+
}
|
| 147 |
+
]
|
| 148 |
+
}
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
### Field Specifications
|
| 152 |
+
|
| 153 |
+
#### Required Fields
|
| 154 |
+
- **name**: String - Piclet's name
|
| 155 |
+
- **primaryType**: String - One of: beast, bug, aquatic, flora, mineral, space, machina, structure, culture, cuisine
|
| 156 |
+
- **baseStats**: Object with hp, attack, defense, speed (integers)
|
| 157 |
+
- **movepool**: Array of move objects (minimum 1 move)
|
| 158 |
+
|
| 159 |
+
#### Optional Fields
|
| 160 |
+
- **description**: String - Flavor text
|
| 161 |
+
- **tier**: String - low, medium, high, legendary
|
| 162 |
+
- **secondaryType**: String - Same options as primaryType or null
|
| 163 |
+
- **nature**: String - Personality trait
|
| 164 |
+
- **specialAbility**: Object with name and description
|
| 165 |
+
|
| 166 |
+
#### Move Object Format
|
| 167 |
+
```json
|
| 168 |
+
{
|
| 169 |
+
"name": "Move Name",
|
| 170 |
+
"type": "attack_type",
|
| 171 |
+
"power": 75,
|
| 172 |
+
"accuracy": 90,
|
| 173 |
+
"pp": 15,
|
| 174 |
+
"priority": 0,
|
| 175 |
+
"flags": ["contact", "bite"],
|
| 176 |
+
"effects": [
|
| 177 |
+
{
|
| 178 |
+
"type": "damage",
|
| 179 |
+
"target": "opponent",
|
| 180 |
+
"amount": "normal"
|
| 181 |
+
}
|
| 182 |
+
]
|
| 183 |
+
}
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
## Frontend Integration
|
| 187 |
+
|
| 188 |
+
### Using Gradio Client (JavaScript)
|
| 189 |
+
|
| 190 |
+
```javascript
|
| 191 |
+
// Connect to the Piclets server
|
| 192 |
+
const client = await window.gradioClient.Client.connect("your-hf-space-name");
|
| 193 |
+
|
| 194 |
+
// Save a Piclet
|
| 195 |
+
async function savePiclet(picletData, imageFile = null) {
|
| 196 |
+
const result = await client.predict("/save_piclet_api", [
|
| 197 |
+
JSON.stringify(picletData),
|
| 198 |
+
imageFile
|
| 199 |
+
]);
|
| 200 |
+
return JSON.parse(result.data[0]);
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
// Get a Piclet
|
| 204 |
+
async function getPiclet(picletId) {
|
| 205 |
+
const result = await client.predict("/get_piclet_api", [picletId]);
|
| 206 |
+
return JSON.parse(result.data[0]);
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
// List Piclets
|
| 210 |
+
async function listPiclets(limit = 20) {
|
| 211 |
+
const result = await client.predict("/list_piclets_api", [limit]);
|
| 212 |
+
return JSON.parse(result.data[0]);
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
// Get Piclet Image
|
| 216 |
+
async function getPicletImage(picletId) {
|
| 217 |
+
const result = await client.predict("/get_piclet_image_api", [picletId]);
|
| 218 |
+
return result.data[0]; // Returns image path or null
|
| 219 |
+
}
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
### Example Usage
|
| 223 |
+
|
| 224 |
+
```javascript
|
| 225 |
+
// Example Piclet data
|
| 226 |
+
const picletData = {
|
| 227 |
+
name: "Thunder Drake",
|
| 228 |
+
primaryType: "space",
|
| 229 |
+
baseStats: { hp: 90, attack: 85, defense: 75, speed: 95 },
|
| 230 |
+
movepool: [
|
| 231 |
+
{
|
| 232 |
+
name: "Lightning Bolt",
|
| 233 |
+
type: "space",
|
| 234 |
+
power: 80,
|
| 235 |
+
accuracy: 95,
|
| 236 |
+
pp: 15,
|
| 237 |
+
priority: 0,
|
| 238 |
+
flags: [],
|
| 239 |
+
effects: [{ type: "damage", target: "opponent", amount: "normal" }]
|
| 240 |
+
}
|
| 241 |
+
]
|
| 242 |
+
};
|
| 243 |
+
|
| 244 |
+
// Save the Piclet
|
| 245 |
+
const saveResult = await savePiclet(picletData);
|
| 246 |
+
if (saveResult.success) {
|
| 247 |
+
console.log(`Piclet saved with ID: ${saveResult.piclet_id}`);
|
| 248 |
+
|
| 249 |
+
// Retrieve it back
|
| 250 |
+
const retrievedPiclet = await getPiclet(saveResult.piclet_id);
|
| 251 |
+
console.log(retrievedPiclet);
|
| 252 |
+
}
|
| 253 |
+
```
|
| 254 |
+
|
| 255 |
+
## Storage Structure
|
| 256 |
+
|
| 257 |
+
The server uses a file-based storage system:
|
| 258 |
+
|
| 259 |
+
```
|
| 260 |
+
data/
|
| 261 |
+
βββ piclets/ # Individual Piclet JSON files
|
| 262 |
+
β βββ uuid1.json
|
| 263 |
+
β βββ uuid2.json
|
| 264 |
+
β βββ ...
|
| 265 |
+
βββ images/ # Piclet images
|
| 266 |
+
β βββ uuid1.png
|
| 267 |
+
β βββ uuid2.jpg
|
| 268 |
+
β βββ ...
|
| 269 |
+
βββ collections/ # Future: Shared collections
|
| 270 |
+
βββ ...
|
| 271 |
+
```
|
| 272 |
+
|
| 273 |
+
## Error Handling
|
| 274 |
+
|
| 275 |
+
All API endpoints return consistent error formats:
|
| 276 |
+
|
| 277 |
+
```json
|
| 278 |
+
{
|
| 279 |
+
"success": false,
|
| 280 |
+
"error": "Descriptive error message"
|
| 281 |
+
}
|
| 282 |
+
```
|
| 283 |
+
|
| 284 |
+
### Common Errors
|
| 285 |
+
- **Missing required field**: When JSON is missing name, primaryType, baseStats, or movepool
|
| 286 |
+
- **Invalid JSON format**: When the input string is not valid JSON
|
| 287 |
+
- **Piclet not found**: When requesting a non-existent Piclet ID
|
| 288 |
+
- **File system errors**: Issues with saving/reading files
|
| 289 |
+
|
| 290 |
+
## Deployment to Hugging Face Spaces
|
| 291 |
+
|
| 292 |
+
1. **Push to Repository**: The space automatically deploys when you push to the connected git repository
|
| 293 |
+
2. **Environment**: Python 3.9+ with Gradio 5.38.2
|
| 294 |
+
3. **Persistent Storage**: Data persists between space restarts
|
| 295 |
+
4. **Public Access**: The API is accessible to anyone with the space URL
|
| 296 |
+
|
| 297 |
+
### Space Configuration (in README.md)
|
| 298 |
+
```yaml
|
| 299 |
+
---
|
| 300 |
+
title: Piclets Server
|
| 301 |
+
emoji: π¦
|
| 302 |
+
colorFrom: yellow
|
| 303 |
+
colorTo: pink
|
| 304 |
+
sdk: gradio
|
| 305 |
+
sdk_version: 5.38.2
|
| 306 |
+
app_file: app.py
|
| 307 |
+
pinned: false
|
| 308 |
+
---
|
| 309 |
+
```
|
| 310 |
+
|
| 311 |
+
## Future Enhancements
|
| 312 |
+
|
| 313 |
+
### Planned Features
|
| 314 |
+
- **Collections**: Save and share groups of Piclets
|
| 315 |
+
- **User Authentication**: Personal Piclet collections
|
| 316 |
+
- **Battle Statistics**: Track battle performance
|
| 317 |
+
- **Online Multiplayer**: Real-time battle coordination
|
| 318 |
+
- **Search and Filtering**: Find Piclets by type, tier, name
|
| 319 |
+
- **Import/Export**: Bulk operations
|
| 320 |
+
|
| 321 |
+
### API Extensions
|
| 322 |
+
- `create_collection_api(name, piclet_ids)`
|
| 323 |
+
- `get_collection_api(collection_id)`
|
| 324 |
+
- `search_piclets_api(query, filters)`
|
| 325 |
+
- `get_battle_stats_api(piclet_id)`
|
| 326 |
+
|
| 327 |
+
## Security Considerations
|
| 328 |
+
|
| 329 |
+
- **Input Validation**: All JSON inputs are validated
|
| 330 |
+
- **File Size Limits**: Images are limited by Gradio defaults
|
| 331 |
+
- **Rate Limiting**: Handled by Hugging Face Spaces infrastructure
|
| 332 |
+
- **Content Filtering**: Future enhancement for inappropriate content
|
| 333 |
+
|
| 334 |
+
## Support
|
| 335 |
+
|
| 336 |
+
For issues or questions:
|
| 337 |
+
1. Check the error messages in API responses
|
| 338 |
+
2. Verify JSON format matches the specification
|
| 339 |
+
3. Ensure all required fields are present
|
| 340 |
+
4. Test with the example data provided
|
app.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import uuid
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from typing import Dict, List, Optional, Tuple
|
| 7 |
+
import hashlib
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
# Create data directories
|
| 11 |
+
DATA_DIR = Path("data")
|
| 12 |
+
PICLETS_DIR = DATA_DIR / "piclets"
|
| 13 |
+
COLLECTIONS_DIR = DATA_DIR / "collections"
|
| 14 |
+
IMAGES_DIR = DATA_DIR / "images"
|
| 15 |
+
|
| 16 |
+
for dir_path in [DATA_DIR, PICLETS_DIR, COLLECTIONS_DIR, IMAGES_DIR]:
|
| 17 |
+
dir_path.mkdir(exist_ok=True)
|
| 18 |
+
|
| 19 |
+
class PicletStorage:
|
| 20 |
+
"""Handles saving and retrieving Piclet data using file-based storage"""
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def save_piclet(piclet_data: dict, image_file=None) -> Tuple[bool, str]:
|
| 24 |
+
"""
|
| 25 |
+
Save a Piclet with optional image file
|
| 26 |
+
Returns: (success, piclet_id_or_error_message)
|
| 27 |
+
"""
|
| 28 |
+
try:
|
| 29 |
+
# Generate unique ID
|
| 30 |
+
piclet_id = str(uuid.uuid4())
|
| 31 |
+
|
| 32 |
+
# Add metadata
|
| 33 |
+
piclet_data["id"] = piclet_id
|
| 34 |
+
piclet_data["created_at"] = datetime.now().isoformat()
|
| 35 |
+
|
| 36 |
+
# Handle image file if provided
|
| 37 |
+
if image_file is not None:
|
| 38 |
+
# Generate image filename
|
| 39 |
+
image_ext = Path(image_file.name).suffix if hasattr(image_file, 'name') else '.png'
|
| 40 |
+
image_filename = f"{piclet_id}{image_ext}"
|
| 41 |
+
image_path = IMAGES_DIR / image_filename
|
| 42 |
+
|
| 43 |
+
# Save image file
|
| 44 |
+
if hasattr(image_file, 'save'):
|
| 45 |
+
image_file.save(str(image_path))
|
| 46 |
+
else:
|
| 47 |
+
# Handle different image input types
|
| 48 |
+
with open(image_path, 'wb') as f:
|
| 49 |
+
if hasattr(image_file, 'read'):
|
| 50 |
+
f.write(image_file.read())
|
| 51 |
+
else:
|
| 52 |
+
f.write(image_file)
|
| 53 |
+
|
| 54 |
+
piclet_data["image_filename"] = image_filename
|
| 55 |
+
|
| 56 |
+
# Save Piclet data
|
| 57 |
+
piclet_file = PICLETS_DIR / f"{piclet_id}.json"
|
| 58 |
+
with open(piclet_file, 'w') as f:
|
| 59 |
+
json.dump(piclet_data, f, indent=2)
|
| 60 |
+
|
| 61 |
+
return True, piclet_id
|
| 62 |
+
|
| 63 |
+
except Exception as e:
|
| 64 |
+
return False, f"Error saving Piclet: {str(e)}"
|
| 65 |
+
|
| 66 |
+
@staticmethod
|
| 67 |
+
def get_piclet(piclet_id: str) -> Tuple[bool, dict]:
|
| 68 |
+
"""
|
| 69 |
+
Retrieve a Piclet by ID
|
| 70 |
+
Returns: (success, piclet_data_or_error_message)
|
| 71 |
+
"""
|
| 72 |
+
try:
|
| 73 |
+
piclet_file = PICLETS_DIR / f"{piclet_id}.json"
|
| 74 |
+
if not piclet_file.exists():
|
| 75 |
+
return False, {"error": "Piclet not found"}
|
| 76 |
+
|
| 77 |
+
with open(piclet_file, 'r') as f:
|
| 78 |
+
piclet_data = json.load(f)
|
| 79 |
+
|
| 80 |
+
return True, piclet_data
|
| 81 |
+
|
| 82 |
+
except Exception as e:
|
| 83 |
+
return False, {"error": f"Error retrieving Piclet: {str(e)}"}
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def list_piclets(limit: int = 50) -> Tuple[bool, List[dict]]:
|
| 87 |
+
"""
|
| 88 |
+
List all saved Piclets with basic info
|
| 89 |
+
Returns: (success, list_of_piclet_summaries)
|
| 90 |
+
"""
|
| 91 |
+
try:
|
| 92 |
+
piclets = []
|
| 93 |
+
piclet_files = list(PICLETS_DIR.glob("*.json"))
|
| 94 |
+
|
| 95 |
+
# Sort by creation time (newest first)
|
| 96 |
+
piclet_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
|
| 97 |
+
|
| 98 |
+
for piclet_file in piclet_files[:limit]:
|
| 99 |
+
try:
|
| 100 |
+
with open(piclet_file, 'r') as f:
|
| 101 |
+
data = json.load(f)
|
| 102 |
+
|
| 103 |
+
# Create summary
|
| 104 |
+
summary = {
|
| 105 |
+
"id": data.get("id"),
|
| 106 |
+
"name": data.get("name", "Unnamed Piclet"),
|
| 107 |
+
"primaryType": data.get("primaryType"),
|
| 108 |
+
"tier": data.get("tier"),
|
| 109 |
+
"created_at": data.get("created_at"),
|
| 110 |
+
"has_image": "image_filename" in data
|
| 111 |
+
}
|
| 112 |
+
piclets.append(summary)
|
| 113 |
+
|
| 114 |
+
except Exception as e:
|
| 115 |
+
print(f"Error reading {piclet_file}: {e}")
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
return True, piclets
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
return False, [{"error": f"Error listing Piclets: {str(e)}"}]
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def get_piclet_image(piclet_id: str):
|
| 125 |
+
"""Get the image file for a Piclet"""
|
| 126 |
+
try:
|
| 127 |
+
# First get the Piclet data to find image filename
|
| 128 |
+
success, piclet_data = PicletStorage.get_piclet(piclet_id)
|
| 129 |
+
if not success:
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
if "image_filename" not in piclet_data:
|
| 133 |
+
return None
|
| 134 |
+
|
| 135 |
+
image_path = IMAGES_DIR / piclet_data["image_filename"]
|
| 136 |
+
if image_path.exists():
|
| 137 |
+
return str(image_path)
|
| 138 |
+
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"Error getting image for {piclet_id}: {e}")
|
| 143 |
+
return None
|
| 144 |
+
|
| 145 |
+
def save_piclet_api(piclet_json: str, image_file=None) -> str:
|
| 146 |
+
"""
|
| 147 |
+
API endpoint to save a Piclet
|
| 148 |
+
"""
|
| 149 |
+
try:
|
| 150 |
+
# Parse the JSON data
|
| 151 |
+
piclet_data = json.loads(piclet_json)
|
| 152 |
+
|
| 153 |
+
# Validate required fields
|
| 154 |
+
required_fields = ["name", "primaryType", "baseStats", "movepool"]
|
| 155 |
+
for field in required_fields:
|
| 156 |
+
if field not in piclet_data:
|
| 157 |
+
return json.dumps({
|
| 158 |
+
"success": False,
|
| 159 |
+
"error": f"Missing required field: {field}"
|
| 160 |
+
})
|
| 161 |
+
|
| 162 |
+
# Save the Piclet
|
| 163 |
+
success, result = PicletStorage.save_piclet(piclet_data, image_file)
|
| 164 |
+
|
| 165 |
+
if success:
|
| 166 |
+
return json.dumps({
|
| 167 |
+
"success": True,
|
| 168 |
+
"piclet_id": result,
|
| 169 |
+
"message": "Piclet saved successfully"
|
| 170 |
+
})
|
| 171 |
+
else:
|
| 172 |
+
return json.dumps({
|
| 173 |
+
"success": False,
|
| 174 |
+
"error": result
|
| 175 |
+
})
|
| 176 |
+
|
| 177 |
+
except json.JSONDecodeError:
|
| 178 |
+
return json.dumps({
|
| 179 |
+
"success": False,
|
| 180 |
+
"error": "Invalid JSON format"
|
| 181 |
+
})
|
| 182 |
+
except Exception as e:
|
| 183 |
+
return json.dumps({
|
| 184 |
+
"success": False,
|
| 185 |
+
"error": f"Unexpected error: {str(e)}"
|
| 186 |
+
})
|
| 187 |
+
|
| 188 |
+
def get_piclet_api(piclet_id: str) -> str:
|
| 189 |
+
"""
|
| 190 |
+
API endpoint to retrieve a Piclet by ID
|
| 191 |
+
"""
|
| 192 |
+
try:
|
| 193 |
+
if not piclet_id.strip():
|
| 194 |
+
return json.dumps({
|
| 195 |
+
"success": False,
|
| 196 |
+
"error": "Piclet ID is required"
|
| 197 |
+
})
|
| 198 |
+
|
| 199 |
+
success, result = PicletStorage.get_piclet(piclet_id.strip())
|
| 200 |
+
|
| 201 |
+
if success:
|
| 202 |
+
return json.dumps({
|
| 203 |
+
"success": True,
|
| 204 |
+
"piclet": result
|
| 205 |
+
})
|
| 206 |
+
else:
|
| 207 |
+
return json.dumps({
|
| 208 |
+
"success": False,
|
| 209 |
+
"error": result.get("error", "Unknown error")
|
| 210 |
+
})
|
| 211 |
+
|
| 212 |
+
except Exception as e:
|
| 213 |
+
return json.dumps({
|
| 214 |
+
"success": False,
|
| 215 |
+
"error": f"Unexpected error: {str(e)}"
|
| 216 |
+
})
|
| 217 |
+
|
| 218 |
+
def list_piclets_api(limit: int = 50) -> str:
|
| 219 |
+
"""
|
| 220 |
+
API endpoint to list all saved Piclets
|
| 221 |
+
"""
|
| 222 |
+
try:
|
| 223 |
+
limit = max(1, min(limit, 100)) # Limit between 1 and 100
|
| 224 |
+
|
| 225 |
+
success, result = PicletStorage.list_piclets(limit)
|
| 226 |
+
|
| 227 |
+
if success:
|
| 228 |
+
return json.dumps({
|
| 229 |
+
"success": True,
|
| 230 |
+
"piclets": result,
|
| 231 |
+
"count": len(result)
|
| 232 |
+
})
|
| 233 |
+
else:
|
| 234 |
+
return json.dumps({
|
| 235 |
+
"success": False,
|
| 236 |
+
"error": "Failed to list Piclets"
|
| 237 |
+
})
|
| 238 |
+
|
| 239 |
+
except Exception as e:
|
| 240 |
+
return json.dumps({
|
| 241 |
+
"success": False,
|
| 242 |
+
"error": f"Unexpected error: {str(e)}"
|
| 243 |
+
})
|
| 244 |
+
|
| 245 |
+
def get_piclet_image_api(piclet_id: str):
|
| 246 |
+
"""
|
| 247 |
+
API endpoint to get a Piclet's image
|
| 248 |
+
"""
|
| 249 |
+
try:
|
| 250 |
+
if not piclet_id.strip():
|
| 251 |
+
return None
|
| 252 |
+
|
| 253 |
+
image_path = PicletStorage.get_piclet_image(piclet_id.strip())
|
| 254 |
+
return image_path
|
| 255 |
+
|
| 256 |
+
except Exception as e:
|
| 257 |
+
print(f"Error in get_piclet_image_api: {e}")
|
| 258 |
+
return None
|
| 259 |
+
|
| 260 |
+
# Create example Piclet data for testing
|
| 261 |
+
def create_example_piclet() -> str:
|
| 262 |
+
"""Create an example Piclet for testing"""
|
| 263 |
+
example_piclet = {
|
| 264 |
+
"name": "Stellar Wolf",
|
| 265 |
+
"description": "A majestic wolf creature infused with cosmic energy",
|
| 266 |
+
"tier": "medium",
|
| 267 |
+
"primaryType": "space",
|
| 268 |
+
"secondaryType": "beast",
|
| 269 |
+
"baseStats": {
|
| 270 |
+
"hp": 85,
|
| 271 |
+
"attack": 90,
|
| 272 |
+
"defense": 70,
|
| 273 |
+
"speed": 80
|
| 274 |
+
},
|
| 275 |
+
"nature": "Bold",
|
| 276 |
+
"specialAbility": {
|
| 277 |
+
"name": "Cosmic Howl",
|
| 278 |
+
"description": "Increases attack when health is low"
|
| 279 |
+
},
|
| 280 |
+
"movepool": [
|
| 281 |
+
{
|
| 282 |
+
"name": "Star Strike",
|
| 283 |
+
"type": "space",
|
| 284 |
+
"power": 75,
|
| 285 |
+
"accuracy": 90,
|
| 286 |
+
"pp": 15,
|
| 287 |
+
"priority": 0,
|
| 288 |
+
"flags": [],
|
| 289 |
+
"effects": [
|
| 290 |
+
{
|
| 291 |
+
"type": "damage",
|
| 292 |
+
"target": "opponent",
|
| 293 |
+
"amount": "normal"
|
| 294 |
+
}
|
| 295 |
+
]
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"name": "Lunar Bite",
|
| 299 |
+
"type": "beast",
|
| 300 |
+
"power": 80,
|
| 301 |
+
"accuracy": 85,
|
| 302 |
+
"pp": 12,
|
| 303 |
+
"priority": 0,
|
| 304 |
+
"flags": ["contact", "bite"],
|
| 305 |
+
"effects": [
|
| 306 |
+
{
|
| 307 |
+
"type": "damage",
|
| 308 |
+
"target": "opponent",
|
| 309 |
+
"amount": "normal"
|
| 310 |
+
}
|
| 311 |
+
]
|
| 312 |
+
}
|
| 313 |
+
]
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
return json.dumps(example_piclet, indent=2)
|
| 317 |
+
|
| 318 |
+
# Create the Gradio interface
|
| 319 |
+
with gr.Blocks(title="Piclets Server API", theme=gr.themes.Soft()) as app:
|
| 320 |
+
gr.Markdown("""
|
| 321 |
+
# π¦ Piclets Server API
|
| 322 |
+
|
| 323 |
+
Backend server for saving and sharing Piclets (AI-generated creatures) from the Piclets game.
|
| 324 |
+
|
| 325 |
+
## Quick Start
|
| 326 |
+
1. **Save a Piclet**: Use the JSON format below with optional image upload
|
| 327 |
+
2. **Retrieve a Piclet**: Enter a Piclet ID to get the full data
|
| 328 |
+
3. **List Piclets**: See all saved Piclets with summaries
|
| 329 |
+
4. **Get Images**: Retrieve the original image for any Piclet
|
| 330 |
+
""")
|
| 331 |
+
|
| 332 |
+
with gr.Tabs():
|
| 333 |
+
# Save Piclet Tab
|
| 334 |
+
with gr.Tab("πΎ Save Piclet"):
|
| 335 |
+
gr.Markdown("### Save a new Piclet with optional image")
|
| 336 |
+
|
| 337 |
+
with gr.Row():
|
| 338 |
+
with gr.Column(scale=2):
|
| 339 |
+
piclet_json_input = gr.Textbox(
|
| 340 |
+
label="Piclet JSON Data",
|
| 341 |
+
placeholder="Paste your Piclet JSON here...",
|
| 342 |
+
lines=15,
|
| 343 |
+
value=create_example_piclet()
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
with gr.Column(scale=1):
|
| 347 |
+
image_input = gr.File(
|
| 348 |
+
label="Piclet Image (Optional)",
|
| 349 |
+
file_types=["image"]
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
save_btn = gr.Button("πΎ Save Piclet", variant="primary")
|
| 353 |
+
|
| 354 |
+
save_output = gr.JSON(label="Save Result")
|
| 355 |
+
|
| 356 |
+
save_btn.click(
|
| 357 |
+
fn=save_piclet_api,
|
| 358 |
+
inputs=[piclet_json_input, image_input],
|
| 359 |
+
outputs=save_output
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# Get Piclet Tab
|
| 363 |
+
with gr.Tab("π Get Piclet"):
|
| 364 |
+
gr.Markdown("### Retrieve a Piclet by ID")
|
| 365 |
+
|
| 366 |
+
with gr.Row():
|
| 367 |
+
with gr.Column(scale=2):
|
| 368 |
+
piclet_id_input = gr.Textbox(
|
| 369 |
+
label="Piclet ID",
|
| 370 |
+
placeholder="Enter Piclet ID here..."
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
get_btn = gr.Button("π Get Piclet", variant="primary")
|
| 374 |
+
|
| 375 |
+
with gr.Column(scale=2):
|
| 376 |
+
get_output = gr.JSON(label="Piclet Data")
|
| 377 |
+
|
| 378 |
+
get_btn.click(
|
| 379 |
+
fn=get_piclet_api,
|
| 380 |
+
inputs=piclet_id_input,
|
| 381 |
+
outputs=get_output
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
# List Piclets Tab
|
| 385 |
+
with gr.Tab("π List Piclets"):
|
| 386 |
+
gr.Markdown("### Browse all saved Piclets")
|
| 387 |
+
|
| 388 |
+
with gr.Row():
|
| 389 |
+
with gr.Column(scale=1):
|
| 390 |
+
limit_input = gr.Slider(
|
| 391 |
+
label="Max Results",
|
| 392 |
+
minimum=1,
|
| 393 |
+
maximum=100,
|
| 394 |
+
value=20,
|
| 395 |
+
step=1
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
list_btn = gr.Button("π List Piclets", variant="primary")
|
| 399 |
+
|
| 400 |
+
with gr.Column(scale=3):
|
| 401 |
+
list_output = gr.JSON(label="Piclets List")
|
| 402 |
+
|
| 403 |
+
list_btn.click(
|
| 404 |
+
fn=list_piclets_api,
|
| 405 |
+
inputs=limit_input,
|
| 406 |
+
outputs=list_output
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
# Get Image Tab
|
| 410 |
+
with gr.Tab("πΌοΈ Get Image"):
|
| 411 |
+
gr.Markdown("### Retrieve a Piclet's image")
|
| 412 |
+
|
| 413 |
+
with gr.Row():
|
| 414 |
+
with gr.Column(scale=1):
|
| 415 |
+
image_id_input = gr.Textbox(
|
| 416 |
+
label="Piclet ID",
|
| 417 |
+
placeholder="Enter Piclet ID here..."
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
get_image_btn = gr.Button("πΌοΈ Get Image", variant="primary")
|
| 421 |
+
|
| 422 |
+
with gr.Column(scale=2):
|
| 423 |
+
image_output = gr.Image(label="Piclet Image")
|
| 424 |
+
|
| 425 |
+
get_image_btn.click(
|
| 426 |
+
fn=get_piclet_image_api,
|
| 427 |
+
inputs=image_id_input,
|
| 428 |
+
outputs=image_output
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
# API Documentation Tab
|
| 432 |
+
with gr.Tab("π API Documentation"):
|
| 433 |
+
gr.Markdown("""
|
| 434 |
+
## API Endpoints
|
| 435 |
+
|
| 436 |
+
This Gradio interface provides the following API endpoints that can be accessed programmatically:
|
| 437 |
+
|
| 438 |
+
### 1. Save Piclet
|
| 439 |
+
- **Function**: `save_piclet_api(piclet_json, image_file=None)`
|
| 440 |
+
- **Input**: JSON string with Piclet data, optional image file
|
| 441 |
+
- **Output**: JSON response with success status and Piclet ID
|
| 442 |
+
|
| 443 |
+
### 2. Get Piclet
|
| 444 |
+
- **Function**: `get_piclet_api(piclet_id)`
|
| 445 |
+
- **Input**: Piclet ID string
|
| 446 |
+
- **Output**: JSON response with full Piclet data
|
| 447 |
+
|
| 448 |
+
### 3. List Piclets
|
| 449 |
+
- **Function**: `list_piclets_api(limit=50)`
|
| 450 |
+
- **Input**: Maximum number of results (1-100)
|
| 451 |
+
- **Output**: JSON response with Piclet summaries
|
| 452 |
+
|
| 453 |
+
### 4. Get Image
|
| 454 |
+
- **Function**: `get_piclet_image_api(piclet_id)`
|
| 455 |
+
- **Input**: Piclet ID string
|
| 456 |
+
- **Output**: Image file path or None
|
| 457 |
+
|
| 458 |
+
## Required JSON Format
|
| 459 |
+
|
| 460 |
+
```json
|
| 461 |
+
{
|
| 462 |
+
"name": "Piclet Name",
|
| 463 |
+
"description": "Description of the creature",
|
| 464 |
+
"tier": "low|medium|high|legendary",
|
| 465 |
+
"primaryType": "beast|bug|aquatic|flora|mineral|space|machina|structure|culture|cuisine",
|
| 466 |
+
"secondaryType": "same options as primaryType or null",
|
| 467 |
+
"baseStats": {
|
| 468 |
+
"hp": 85,
|
| 469 |
+
"attack": 90,
|
| 470 |
+
"defense": 70,
|
| 471 |
+
"speed": 80
|
| 472 |
+
},
|
| 473 |
+
"nature": "Personality trait",
|
| 474 |
+
"specialAbility": {
|
| 475 |
+
"name": "Ability Name",
|
| 476 |
+
"description": "What the ability does"
|
| 477 |
+
},
|
| 478 |
+
"movepool": [
|
| 479 |
+
{
|
| 480 |
+
"name": "Move Name",
|
| 481 |
+
"type": "attack type",
|
| 482 |
+
"power": 75,
|
| 483 |
+
"accuracy": 90,
|
| 484 |
+
"pp": 15,
|
| 485 |
+
"priority": 0,
|
| 486 |
+
"flags": ["contact", "bite", etc.],
|
| 487 |
+
"effects": [
|
| 488 |
+
{
|
| 489 |
+
"type": "damage|heal|modifyStats|etc.",
|
| 490 |
+
"target": "opponent|self|all",
|
| 491 |
+
"amount": "weak|normal|strong|extreme"
|
| 492 |
+
}
|
| 493 |
+
]
|
| 494 |
+
}
|
| 495 |
+
]
|
| 496 |
+
}
|
| 497 |
+
```
|
| 498 |
+
|
| 499 |
+
## Usage from Frontend
|
| 500 |
+
|
| 501 |
+
```javascript
|
| 502 |
+
// Connect to this Gradio space
|
| 503 |
+
const client = await window.gradioClient.Client.connect("your-space-name");
|
| 504 |
+
|
| 505 |
+
// Save a Piclet
|
| 506 |
+
const saveResult = await client.predict("/save_piclet_api", [
|
| 507 |
+
JSON.stringify(picletData), // Piclet JSON
|
| 508 |
+
imageFile // Optional image file
|
| 509 |
+
]);
|
| 510 |
+
|
| 511 |
+
// Get a Piclet
|
| 512 |
+
const getResult = await client.predict("/get_piclet_api", [
|
| 513 |
+
picletId // Piclet ID string
|
| 514 |
+
]);
|
| 515 |
+
|
| 516 |
+
// List Piclets
|
| 517 |
+
const listResult = await client.predict("/list_piclets_api", [
|
| 518 |
+
20 // Maximum results
|
| 519 |
+
]);
|
| 520 |
+
```
|
| 521 |
+
|
| 522 |
+
## Storage Structure
|
| 523 |
+
|
| 524 |
+
- **Data Directory**: `./data/`
|
| 525 |
+
- **Piclets**: `./data/piclets/*.json`
|
| 526 |
+
- **Images**: `./data/images/*`
|
| 527 |
+
- **Collections**: `./data/collections/*.json` (future feature)
|
| 528 |
+
|
| 529 |
+
All data is stored locally in the Hugging Face Space persistent storage.
|
| 530 |
+
""")
|
| 531 |
+
|
| 532 |
+
# Launch the app
|
| 533 |
+
if __name__ == "__main__":
|
| 534 |
+
app.launch(
|
| 535 |
+
server_name="0.0.0.0",
|
| 536 |
+
server_port=7860,
|
| 537 |
+
share=False
|
| 538 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.38.2
|
| 2 |
+
Pillow>=9.0.0
|