piclets-server / API_DOCUMENTATION.md
Fraser's picture
basics
682910a
# Piclets Server API Documentation
## Overview
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.
## Quick Start
### Running Locally
```bash
pip install -r requirements.txt
python app.py
```
### Accessing the API
- **Web Interface**: http://localhost:7860
- **Programmatic Access**: Use Gradio Client to connect to the space
## API Endpoints
### 1. Save Piclet
**Endpoint**: `/save_piclet_api`
**Method**: Gradio function call
**Purpose**: Save a new Piclet with optional image
**Input Parameters**:
- `piclet_json` (string): JSON-formatted Piclet data
- `image_file` (file, optional): Image file for the Piclet
**Response Format**:
```json
{
"success": true,
"piclet_id": "uuid-string",
"message": "Piclet saved successfully"
}
```
**Error Response**:
```json
{
"success": false,
"error": "Error description"
}
```
### 2. Get Piclet
**Endpoint**: `/get_piclet_api`
**Method**: Gradio function call
**Purpose**: Retrieve a Piclet by ID
**Input Parameters**:
- `piclet_id` (string): Unique Piclet identifier
**Response Format**:
```json
{
"success": true,
"piclet": {
"id": "uuid-string",
"name": "Piclet Name",
"description": "Description",
"tier": "medium",
"primaryType": "space",
"baseStats": { ... },
"movepool": [ ... ],
"created_at": "2024-07-26T10:30:00"
}
}
```
### 3. List Piclets
**Endpoint**: `/list_piclets_api`
**Method**: Gradio function call
**Purpose**: Get a list of all saved Piclets
**Input Parameters**:
- `limit` (integer): Maximum number of results (1-100, default: 50)
**Response Format**:
```json
{
"success": true,
"piclets": [
{
"id": "uuid-string",
"name": "Piclet Name",
"primaryType": "space",
"tier": "medium",
"created_at": "2024-07-26T10:30:00",
"has_image": true
}
],
"count": 1
}
```
### 4. Get Piclet Image
**Endpoint**: `/get_piclet_image_api`
**Method**: Gradio function call
**Purpose**: Retrieve the image associated with a Piclet
**Input Parameters**:
- `piclet_id` (string): Unique Piclet identifier
**Response**: Image file or None if not found
## Required JSON Format for Piclets
When saving a Piclet, the JSON must include these required fields:
```json
{
"name": "Stellar Wolf",
"description": "A majestic wolf creature infused with cosmic energy",
"tier": "medium",
"primaryType": "space",
"secondaryType": "beast",
"baseStats": {
"hp": 85,
"attack": 90,
"defense": 70,
"speed": 80
},
"nature": "Bold",
"specialAbility": {
"name": "Cosmic Howl",
"description": "Increases attack when health is low"
},
"movepool": [
{
"name": "Star Strike",
"type": "space",
"power": 75,
"accuracy": 90,
"pp": 15,
"priority": 0,
"flags": [],
"effects": [
{
"type": "damage",
"target": "opponent",
"amount": "normal"
}
]
}
]
}
```
### Field Specifications
#### Required Fields
- **name**: String - Piclet's name
- **primaryType**: String - One of: beast, bug, aquatic, flora, mineral, space, machina, structure, culture, cuisine
- **baseStats**: Object with hp, attack, defense, speed (integers)
- **movepool**: Array of move objects (minimum 1 move)
#### Optional Fields
- **description**: String - Flavor text
- **tier**: String - low, medium, high, legendary
- **secondaryType**: String - Same options as primaryType or null
- **nature**: String - Personality trait
- **specialAbility**: Object with name and description
#### Move Object Format
```json
{
"name": "Move Name",
"type": "attack_type",
"power": 75,
"accuracy": 90,
"pp": 15,
"priority": 0,
"flags": ["contact", "bite"],
"effects": [
{
"type": "damage",
"target": "opponent",
"amount": "normal"
}
]
}
```
## Frontend Integration
### Using Gradio Client (JavaScript)
```javascript
// Connect to the Piclets server
const client = await window.gradioClient.Client.connect("your-hf-space-name");
// Save a Piclet
async function savePiclet(picletData, imageFile = null) {
const result = await client.predict("/save_piclet_api", [
JSON.stringify(picletData),
imageFile
]);
return JSON.parse(result.data[0]);
}
// Get a Piclet
async function getPiclet(picletId) {
const result = await client.predict("/get_piclet_api", [picletId]);
return JSON.parse(result.data[0]);
}
// List Piclets
async function listPiclets(limit = 20) {
const result = await client.predict("/list_piclets_api", [limit]);
return JSON.parse(result.data[0]);
}
// Get Piclet Image
async function getPicletImage(picletId) {
const result = await client.predict("/get_piclet_image_api", [picletId]);
return result.data[0]; // Returns image path or null
}
```
### Example Usage
```javascript
// Example Piclet data
const picletData = {
name: "Thunder Drake",
primaryType: "space",
baseStats: { hp: 90, attack: 85, defense: 75, speed: 95 },
movepool: [
{
name: "Lightning Bolt",
type: "space",
power: 80,
accuracy: 95,
pp: 15,
priority: 0,
flags: [],
effects: [{ type: "damage", target: "opponent", amount: "normal" }]
}
]
};
// Save the Piclet
const saveResult = await savePiclet(picletData);
if (saveResult.success) {
console.log(`Piclet saved with ID: ${saveResult.piclet_id}`);
// Retrieve it back
const retrievedPiclet = await getPiclet(saveResult.piclet_id);
console.log(retrievedPiclet);
}
```
## Storage Structure
The server uses a file-based storage system:
```
data/
β”œβ”€β”€ piclets/ # Individual Piclet JSON files
β”‚ β”œβ”€β”€ uuid1.json
β”‚ β”œβ”€β”€ uuid2.json
β”‚ └── ...
β”œβ”€β”€ images/ # Piclet images
β”‚ β”œβ”€β”€ uuid1.png
β”‚ β”œβ”€β”€ uuid2.jpg
β”‚ └── ...
└── collections/ # Future: Shared collections
└── ...
```
## Error Handling
All API endpoints return consistent error formats:
```json
{
"success": false,
"error": "Descriptive error message"
}
```
### Common Errors
- **Missing required field**: When JSON is missing name, primaryType, baseStats, or movepool
- **Invalid JSON format**: When the input string is not valid JSON
- **Piclet not found**: When requesting a non-existent Piclet ID
- **File system errors**: Issues with saving/reading files
## Deployment to Hugging Face Spaces
1. **Push to Repository**: The space automatically deploys when you push to the connected git repository
2. **Environment**: Python 3.9+ with Gradio 5.38.2
3. **Persistent Storage**: Data persists between space restarts
4. **Public Access**: The API is accessible to anyone with the space URL
### Space Configuration (in README.md)
```yaml
---
title: Piclets Server
emoji: πŸ¦€
colorFrom: yellow
colorTo: pink
sdk: gradio
sdk_version: 5.38.2
app_file: app.py
pinned: false
---
```
## Future Enhancements
### Planned Features
- **Collections**: Save and share groups of Piclets
- **User Authentication**: Personal Piclet collections
- **Battle Statistics**: Track battle performance
- **Online Multiplayer**: Real-time battle coordination
- **Search and Filtering**: Find Piclets by type, tier, name
- **Import/Export**: Bulk operations
### API Extensions
- `create_collection_api(name, piclet_ids)`
- `get_collection_api(collection_id)`
- `search_piclets_api(query, filters)`
- `get_battle_stats_api(piclet_id)`
## Security Considerations
- **Input Validation**: All JSON inputs are validated
- **File Size Limits**: Images are limited by Gradio defaults
- **Rate Limiting**: Handled by Hugging Face Spaces infrastructure
- **Content Filtering**: Future enhancement for inappropriate content
## Support
For issues or questions:
1. Check the error messages in API responses
2. Verify JSON format matches the specification
3. Ensure all required fields are present
4. Test with the example data provided