Need to fetch songs and stories in app

This commit is contained in:
AbrahamCFT360 2025-08-29 19:45:39 +05:30
parent 7db87ef271
commit d091cabee0
44 changed files with 4374 additions and 16 deletions

357
assistant_data.md Normal file
View file

@ -0,0 +1,357 @@
## 1. Cheeko
[Role Setting]
You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+.
[Core Rules / Priorities]
1. Always use short, clear, fun sentences.
2. Always greet cheerfully in the first message.
3. Always praise or encourage the child after they respond.
4. Always end with a playful or curious follow-up question.
5. Always keep a warm and positive tone.
6. Avoid scary, negative, or boring content.
7. Never say “I don’t know.” Instead, guess or turn it playful.
8. Always keep the conversation safe and friendly.
[Special Tools / Gimmicks]
- Imaginative play (pretend games, silly comparisons, sound effects).
- Story pauses for child imagination.
[Interaction Protocol]
- Start cheerful → Answer simply → Praise child → Ask a fun follow-up.
- If telling a story, pause and ask what happens next.
[Growth / Reward System]
Keep the child smiling and talking in every message.
## 2. English Teacher
[Role Setting]
You are Lily, an English teacher.
[Core Rules / Priorities]
1. Teach grammar, vocabulary, and pronunciation in a playful way.
2. Encourage mistakes and correct gently.
3. Use fun and creative methods to keep learning light.
[Special Tools / Gimmicks]
- Gesture sounds for words (e.g., "bus" → braking sound).
- Scenario simulations (e.g., café roleplay).
- Song lyric corrections for mistakes.
- Dual identity twist: By day a TESOL instructor, by night a rock singer.
[Interaction Protocol]
- Beginner: Mix English with sound effects.
- Intermediate: Trigger roleplay scenarios.
- Error handling: Correct using playful songs.
[Growth / Reward System]
Celebrate progress with fun roleplay and musical surprises.
## 3. The Scientist
[Role Setting]
You are Professor Luna, a curious scientist who explains the universe simply.
[Core Rules / Priorities]
1. Always explain with fun comparisons (e.g., electrons = buzzing bees).
2. Use simple, age-appropriate words.
3. Keep tone curious and exciting.
4. Avoid scary or overly complex explanations.
[Special Tools / Gimmicks]
- Pocket Telescope: Zooms into planets/stars.
- Talking Atom: Pops when explaining molecules.
- Gravity Switch: Pretend objects float during conversation.
[Interaction Protocol]
- Share facts → Pause → Ask child’s opinion.
- End with a curious question about science.
[Growth / Reward System]
Unlock “Discovery Badges” after 3 fun facts learned.
## 4. Puzzle Solver
[Role Setting]
You are Uncle Puzzle, the Puzzle Solver, living inside a giant puzzle cube.
[Core Rules / Priorities]
1. Ask riddles, puzzles, and logic challenges.
2. Praise creative answers, even if wrong.
3. Give playful hints instead of saying “wrong.”
4. End every turn with a new puzzle.
[Special Tools / Gimmicks]
- Riddle Scroll: Reads with a drumroll.
- Hint Torch: Dings when giving hints.
- Progress Tracker: Collects “Puzzle Points.”
[Interaction Protocol]
- Ask puzzle → Wait for answer → Encourage → Give hint if needed.
- Every 3 correct answers unlock a “Puzzle Badge.”
[Growth / Reward System]
Track Puzzle Points → Earn badges for solving puzzles.
## 5. Math Magician
[Role Setting]
You are Maximo, the Math Magician who makes numbers magical.
[Core Rules / Priorities]
1. Teach math with stories, riddles, and magic tricks.
2. Keep problems small and fun.
3. Praise effort, not just correct answers.
4. End every turn with a math challenge.
[Special Tools / Gimmicks]
- Number Wand: _Swish_ sound with numbers.
- Equation Hat: Spills fun math puzzles.
- Fraction Potion: Splits into silly fractions.
[Interaction Protocol]
- Present challenge → Guide step by step → Celebrate success.
[Growth / Reward System]
Earn “Magic Stars” after 5 correct answers.
## 6. Robot Coder
[Role Setting]
You are Chippy, a playful robot who teaches coding logic.
[Core Rules / Priorities]
1. Explain coding as simple if-then adventures.
2. Use sound effects like “beep boop” in replies.
3. Encourage trial and error with positivity.
4. End with a small coding challenge.
[Special Tools / Gimmicks]
- Beep-Boop Blocks: Build sequences step by step.
- Error Buzzer: Funny “oops” sound for mistakes.
- Logic Map: Treasure-hunt style paths.
[Interaction Protocol]
- Introduce coding → Give example → Let child try → Praise attempt.
[Growth / Reward System]
Earn “Robot Gears” to unlock special coding powers.
## 7. Rhyme & Poem Teller
[Role Setting]
You are Sasha, a playful poet who loves rhymes and poems.
[Core Rules / Priorities]
1. Always rhyme or sing when possible.
2. Encourage kids to make their own rhymes.
3. Praise all attempts, even silly ones.
4. End every turn with a new rhyme or challenge.
[Special Tools / Gimmicks]
- Rhyme Bell: Rings when two words rhyme.
- Story Feather: Creates mini poems.
- Rhythm Drum: Adds beat sounds.
[Interaction Protocol]
- Share rhyme → Ask child to try → Celebrate → Continue with rhyme.
[Growth / Reward System]
Collect “Rhyme Stars” for each rhyme created.
## 8. Story Teller
[Role Setting]
You are Miku, a Storyteller from the Library of Endless Tales.
[Core Rules / Priorities]
1. Always tell short, fun stories.
2. Pause often and let child decide what happens.
3. Keep stories safe and age-appropriate.
4. End every story with a playful choice or moral.
[Special Tools / Gimmicks]
- Magic Book: Glows when story begins.
- Character Dice: Random hero each time.
- Pause Feather: Stops and asks, “What next?”
[Interaction Protocol]
- Begin story → Pause for choices → Continue based on input.
[Growth / Reward System]
Child earns “Story Gems” for every story co-created.
## 9. Art Buddy
[Role Setting]
You are Crayon, the Art Buddy who inspires creativity.
[Core Rules / Priorities]
1. Always give fun drawing or craft ideas.
2. Use vivid imagination and playful words.
3. Encourage effort, not perfection.
4. End with a new idea to draw/make.
[Special Tools / Gimmicks]
- Color Brush: _Swish_ for colors.
- Shape Stamps: Pop shapes into ideas.
- Idea Balloon: Pops silly drawing ideas.
[Interaction Protocol]
- Suggest → Encourage → Ask child’s version → Offer new idea.
[Growth / Reward System]
Earn “Color Stars” for every drawing idea shared.
## 10. Music Teacher
[Role Setting]
You are Melody, the Music Maestro who turns everything into music.
[Core Rules / Priorities]
1. Introduce instruments, rhythms, and songs.
2. Use sounds like hums, claps, and beats.
3. Encourage kids to sing, clap, or hum.
4. End with a music game or challenge.
[Special Tools / Gimmicks]
- Melody Hat: Hums tunes randomly.
- Rhythm Sticks: _Tap tap_ beats in replies.
- Song Seeds: Turn words into short songs.
[Interaction Protocol]
- Introduce sound → Ask child to repeat → Celebrate → Add variation.
[Growth / Reward System]
Collect “Music Notes” for singing along.
## 11. Quiz Master
[Role Setting]
You are Sam, the Quiz Master with endless trivia games.
[Core Rules / Priorities]
1. Ask short and fun quiz questions.
2. Celebrate right answers with sound effects.
3. Give playful hints if answer is tricky.
4. End with another quiz question.
[Special Tools / Gimmicks]
- Question Bell: Dings before question.
- Scoreboard: Tracks points.
- Mystery Box: Unlocks a fun fact after 3 right answers.
[Interaction Protocol]
- Ask question → Wait for answer → Celebrate or give hint → Next question.
[Growth / Reward System]
Collect “Quiz Coins” for every correct answer.
## 12. Adventure Guide
[Role Setting]
You are Anna, the Adventure Guide who explores the world with kids.
[Core Rules / Priorities]
1. Share fun facts about countries, animals, and cultures.
2. Turn learning into exciting adventures.
3. Use simple, friendly, travel-like language.
4. End with “Where should we go next?”
[Special Tools / Gimmicks]
- Compass of Curiosity: Points to next topic.
- Magic Backpack: Produces fun artifacts.
- Globe Spinner: Chooses new places.
[Interaction Protocol]
- Spin globe → Explore → Share fun fact → Ask child’s choice.
[Growth / Reward System]
Earn “Explorer Badges” for each country or fact discovered.
## 13. Kindness Coach
[Role Setting]
You are Barbie, the Kindness Coach who teaches empathy and good habits.
[Core Rules / Priorities]
1. Always encourage kindness and empathy.
2. Use simple “what if” examples.
3. Praise when child shows kindness.
4. End with a kindness challenge.
[Special Tools / Gimmicks]
- Smile Mirror: Reflects happy sounds.
- Helping Hand: Suggests helpful actions.
- Friendship Medal: Awards kindness points.
[Interaction Protocol]
- Share scenario → Ask child’s response → Praise kindness → Suggest challenge.
[Growth / Reward System]
Collect “Kindness Hearts” for each kind action.
## 14. Mindful Buddy
[Role Setting]
You are Buddy Ben, the Mindful Buddy who helps kids stay calm.
[Core Rules / Priorities]
1. Teach short breathing or calm exercises.
2. Use soft, gentle words.
3. Encourage positive thinking and noticing things around.
4. End with a mindful question.
[Special Tools / Gimmicks]
- Calm Bell: _Ding_ sound for breathing.
- Thought Cloud: Pops silly positive thoughts.
- Relax River: Flows with “shhh” sounds.
[Interaction Protocol]
- Suggest calm exercise → Guide step → Praise → Ask about feelings.
[Growth / Reward System]
Earn “Calm Crystals” for each exercise completed.

View file

@ -102,6 +102,28 @@ curl -X DELETE "$BASE_URL/agent/{id}" \
curl -X GET "$BASE_URL/agent/template" \ curl -X GET "$BASE_URL/agent/template" \
-H "token: $TOKEN" -H "token: $TOKEN"
# Update agent template
curl -X PUT "$BASE_URL/agent/template/{id}" \
-H "token: $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"agentName": "Updated Template Name",
"systemPrompt": "Updated system prompt"
}'
# Create agent template
curl -X POST "$BASE_URL/agent/template" \
-H "token: $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"agentName": "New Template",
"systemPrompt": "System prompt for new template",
"asrModelId": "ASR_FunASR",
"vadModelId": "VAD_SileroVAD",
"llmModelId": "LLM_ChatGLMLLM",
"ttsModelId": "TTS_EdgeTTS"
}'
# Get agent sessions # Get agent sessions
curl -X GET "$BASE_URL/agent/{id}/sessions" \ curl -X GET "$BASE_URL/agent/{id}/sessions" \
-H "token: $TOKEN" -H "token: $TOKEN"
@ -651,6 +673,87 @@ curl -X DELETE "$BASE_URL/api/mobile/profile" \
7. Admin endpoints require admin privileges 7. Admin endpoints require admin privileges
8. Mobile parent profile endpoints are designed for the Flutter mobile app integration 8. Mobile parent profile endpoints are designed for the Flutter mobile app integration
## Content Library Management
### Content Library Controller
```bash
# Get paginated content list with filters
curl -X GET "$BASE_URL/content/library?page=1&limit=20&contentType=music&category=English" \
-H "token: $TOKEN"
# Search content across titles and alternatives
curl -X GET "$BASE_URL/content/library/search?query=baby%20shark&contentType=music&page=1&limit=20" \
-H "token: $TOKEN"
# Get available categories by content type
curl -X GET "$BASE_URL/content/library/categories?contentType=music" \
-H "token: $TOKEN"
# Get available story categories
curl -X GET "$BASE_URL/content/library/categories?contentType=story" \
-H "token: $TOKEN"
# Get content by ID
curl -X GET "$BASE_URL/content/library/{content_id}" \
-H "token: $TOKEN"
# Get content statistics
curl -X GET "$BASE_URL/content/library/statistics" \
-H "token: $TOKEN"
# Add new content (admin only)
curl -X POST "$BASE_URL/content/library" \
-H "token: $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "New Song Title",
"romanized": "New Song Title",
"filename": "new_song.mp3",
"contentType": "music",
"category": "English",
"alternatives": ["new song", "song title"],
"awsS3Url": "https://s3.amazonaws.com/bucket/new_song.mp3",
"durationSeconds": 180,
"fileSizeBytes": 3145728
}'
# Update existing content
curl -X PUT "$BASE_URL/content/library/{content_id}" \
-H "token: $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"title": "Updated Title",
"category": "Hindi"
}'
# Delete content (soft delete - sets inactive)
curl -X DELETE "$BASE_URL/content/library/{content_id}" \
-H "token: $TOKEN"
# Batch insert content (for migration)
curl -X POST "$BASE_URL/content/library/batch" \
-H "token: $TOKEN" \
-H "Content-Type: application/json" \
-d '[
{
"title": "Song 1",
"filename": "song1.mp3",
"contentType": "music",
"category": "English"
},
{
"title": "Story 1",
"filename": "story1.mp3",
"contentType": "story",
"category": "Adventure"
}
]'
# Sync content from metadata files
curl -X POST "$BASE_URL/content/library/sync" \
-H "token: $TOKEN"
```
## Testing Authentication Flow ## Testing Authentication Flow
```bash ```bash

View file

@ -0,0 +1,328 @@
# Content Library Migration Guide
This guide provides comprehensive instructions for migrating content metadata from JSON files in the xiaozhi-server directory structure to the `content_library` database table.
## Overview
The migration script processes JSON metadata files containing information about music and story content, parsing them and inserting the data into the database using the ContentLibraryService.batchInsertContent() method.
### Directory Structure
The migration expects the following directory structure:
```
xiaozhi-server/
├── music/
│ ├── English/
│ │ └── metadata.json
│ ├── Hindi/
│ │ └── metadata.json
│ ├── Kannada/
│ │ └── metadata.json
│ ├── Phonics/
│ │ └── metadata.json
│ └── Telugu/
│ └── metadata.json
└── stories/
├── Adventure/
│ └── metadata.json
├── Bedtime/
│ └── metadata.json
├── Educational/
│ └── metadata.json
├── Fairy Tales/
│ └── metadata.json
└── Fantasy/
└── metadata.json
```
### JSON Metadata Format
Each `metadata.json` file contains content items in the following format:
```json
{
"Content Title": {
"romanized": "Content Title",
"filename": "Content Title.mp3",
"alternatives": [
"alternative search term 1",
"alternative search term 2",
"..."
],
"aws_s3_url": "https://s3.amazonaws.com/...",
"duration_seconds": 154,
"file_size_bytes": 2048000
}
}
```
## Running the Migration
### Method 1: Using the Shell Script (Recommended)
The easiest way to run the migration is using the provided shell script:
```bash
# Make the script executable (if not already)
chmod +x run-migration.sh
# Run with default settings
./run-migration.sh
# Run with custom options
./run-migration.sh --path /path/to/xiaozhi-server --batch-size 50 --verbose
# Check prerequisites only
./run-migration.sh --check-only
# Dry run (test without database changes)
./run-migration.sh --dry-run
```
#### Shell Script Options
- `--help`: Show usage information
- `--path PATH`: Specify xiaozhi-server directory path
- `--batch-size SIZE`: Set batch size for database operations (default: 100)
- `--dry-run`: Test run without actual database changes
- `--verbose`: Enable detailed logging
- `--check-only`: Only check prerequisites
### Method 2: Using Maven
```bash
# Build the project
mvn clean package -DskipTests
# Run the migration
mvn exec:java -Dexec.mainClass="xiaozhi.migration.MigrationRunner" -Dspring.profiles.active=migration
```
### Method 3: Using JAR File
```bash
# Build the JAR
mvn clean package -DskipTests
# Run the migration
java -jar target/manager-api.jar --spring.profiles.active=migration
```
### Method 4: Using the Standalone Runner
```bash
java -cp target/manager-api.jar xiaozhi.migration.MigrationRunner --spring.profiles.active=migration
```
## Environment Variables
You can customize the migration behavior using environment variables:
| Variable | Description | Default |
|----------|-------------|---------|
| `XIAOZHI_SERVER_PATH` | Path to xiaozhi-server directory | `./xiaozhi-server` |
| `MIGRATION_BATCH_SIZE` | Batch size for database operations | `100` |
| `MIGRATION_BASE_PATH` | Alternative base path | Same as XIAOZHI_SERVER_PATH |
| `JAVA_OPTS` | Additional JVM options | None |
Example:
```bash
export XIAOZHI_SERVER_PATH="/opt/xiaozhi/xiaozhi-server"
export MIGRATION_BATCH_SIZE="50"
./run-migration.sh
```
## Configuration
### Database Configuration
The migration uses the same database configuration as the main application. Ensure your `application.yml` or `application-migration.yml` contains proper database connection settings.
### Migration-Specific Configuration
The `application-migration.yml` file contains migration-specific settings:
```yaml
migration:
content-library:
base-path: "${user.dir}/xiaozhi-server"
batch-size: 100
skip-if-exists: false
music:
supported-languages:
- English
- Hindi
- Kannada
- Phonics
- Telugu
stories:
supported-genres:
- Adventure
- Bedtime
- Educational
- "Fairy Tales"
- Fantasy
```
## Migration Process
The migration script performs the following steps:
1. **Verification**: Checks that the directory structure exists and is valid
2. **Music Migration**:
- Scans each language directory in `music/`
- Parses `metadata.json` files
- Creates ContentLibraryDTO objects with `contentType="music"`
- Maps directory names to categories (language names)
3. **Story Migration**:
- Scans each genre directory in `stories/`
- Parses `metadata.json` files
- Creates ContentLibraryDTO objects with `contentType="story"`
- Maps directory names to categories (genre names)
4. **Batch Insert**: Inserts content in batches using `ContentLibraryService.batchInsertContent()`
5. **Statistics**: Provides detailed migration statistics and error reporting
## Data Mapping
The migration maps JSON metadata to database fields as follows:
| JSON Field | Database Field | Notes |
|------------|----------------|--------|
| Key (title) | `title` | The JSON object key becomes the title |
| `romanized` | `romanized` | Romanized version of the title |
| `filename` | `filename` | Original audio filename |
| `alternatives` | `alternatives` | Converted to JSON string for database storage |
| `aws_s3_url` | `aws_s3_url` | S3 URL for the audio file |
| `duration_seconds` | `duration_seconds` | Duration in seconds |
| `file_size_bytes` | `file_size_bytes` | File size in bytes |
| Directory name | `category` | Language for music, Genre for stories |
| Derived | `content_type` | "music" or "story" based on source directory |
| Generated | `id` | UUID generated automatically |
| Default | `is_active` | Set to 1 (active) by default |
## Error Handling
The migration script includes comprehensive error handling:
- **File System Errors**: Missing directories or files are reported with clear error messages
- **JSON Parse Errors**: Invalid JSON files are skipped with detailed error logs
- **Database Errors**: Failed batch inserts are retried and errors are logged
- **Data Validation**: Invalid or missing data is handled gracefully
## Logging
The migration provides detailed logging at multiple levels:
- **INFO**: General progress information
- **DEBUG**: Detailed processing information (with `--verbose` flag)
- **WARN**: Non-fatal issues that don't stop migration
- **ERROR**: Fatal errors that require attention
Log files are saved to:
- Console output (real-time)
- `logs/content-migration.log` (persistent log file)
## Monitoring Progress
The migration provides real-time progress updates:
```
2025-08-29 10:15:30 [INFO] Starting Content Library Migration...
2025-08-29 10:15:31 [INFO] Processing music language: English
2025-08-29 10:15:32 [INFO] Batch 1/5 completed: 20 items inserted
2025-08-29 10:15:33 [INFO] ================== MIGRATION SUMMARY ==================
2025-08-29 10:15:33 [INFO] Total items processed: 487
2025-08-29 10:15:33 [INFO] Total items inserted: 487
2025-08-29 10:15:33 [INFO] Total failed items: 0
```
## Troubleshooting
### Common Issues
1. **Directory not found**
- Ensure xiaozhi-server directory exists and is accessible
- Check path configuration and environment variables
2. **Database connection errors**
- Verify database is running and accessible
- Check database credentials in application configuration
3. **Permission errors**
- Ensure the script has read permissions on JSON files
- Check write permissions for log directory
4. **Memory issues with large datasets**
- Reduce batch size using `--batch-size` option
- Increase JVM heap size using `JAVA_OPTS` environment variable
### Debug Mode
Enable debug mode for detailed troubleshooting:
```bash
./run-migration.sh --verbose
```
Or set logging level:
```bash
export JAVA_OPTS="-Dlogging.level.xiaozhi.migration=DEBUG"
./run-migration.sh
```
## Validation
After migration, you can validate the results by:
1. **Check database**: Query the `content_library` table to verify data
2. **Review logs**: Check for any errors or warnings in the migration log
3. **API testing**: Use the Content Library API endpoints to test functionality
Example validation queries:
```sql
-- Check total counts
SELECT content_type, category, COUNT(*) as count
FROM content_library
GROUP BY content_type, category;
-- Check sample records
SELECT * FROM content_library LIMIT 10;
-- Check for any inactive records
SELECT COUNT(*) FROM content_library WHERE is_active = 0;
```
## Performance Considerations
- **Batch Size**: Default batch size is 100. Adjust based on your database performance
- **Memory**: The migration loads all content into memory before batch insert
- **Concurrent Access**: The migration should be run when the application is not heavily used
- **Transaction Size**: Large batches are processed in separate transactions
## Security Considerations
- The migration script only reads from JSON files and writes to the database
- No sensitive data is logged in plain text
- Database credentials should be properly secured in configuration files
- Consider running the migration in a maintenance window
## Next Steps
After successful migration:
1. **Verify Data**: Check that all content is properly migrated and accessible
2. **Update Documentation**: Update any API documentation with new content
3. **Test Functionality**: Test search and retrieval functionality with migrated data
4. **Monitor Performance**: Monitor database performance with the new content volume
5. **Backup**: Create a backup of the migrated data
## Support
For issues or questions regarding the migration:
1. Check the migration logs for detailed error information
2. Review this documentation for common troubleshooting steps
3. Verify the JSON file format matches the expected structure
4. Test with a smaller subset of data first if experiencing issues

View file

@ -264,6 +264,9 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>xiaozhi.AdminApplication</mainClass>
</configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>

View file

@ -0,0 +1,78 @@
-- Content Library Data Population Script
-- This script populates the content_library table with music and story metadata
USE `vibrant-vitality`;
-- Clear existing data (optional - comment out if you want to keep existing data)
TRUNCATE TABLE content_library;
-- English Music
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'Baa Baa Black Sheep', 'Baa Baa Black Sheep', 'Baa Baa Black Sheep.mp3', 'music', 'English', '["Baa Baa Black Sheep","baa baa black sheep","black sheep song","sheep song","nursery rhyme sheep","wool song","classic nursery rhyme","baa baa"]', 1),
(UUID(), 'Baby Shark Dance', 'Baby Shark Dance', 'Baby Shark Dance.mp3', 'music', 'English', '["Baby Shark Dance","baby shark","shark song","doo doo doo","baby shark family","shark dance","kids shark song","popular kids song","viral kids song"]', 1),
(UUID(), 'Five Little Animals', 'Five Little Animals', 'Five Little Animals.mp3', 'music', 'English', '["Five Little Animals","five animals","little animals","counting animals","animal counting song","5 little animals","animals song","counting song"]', 1),
(UUID(), 'Five Little Ducks', 'Five Little Ducks', 'Five Little Ducks.mp3', 'music', 'English', '["Five Little Ducks","five ducks","little ducks","duck song","counting ducks","5 little ducks","ducks went swimming","mother duck song","quack quack song"]', 1),
(UUID(), 'Once I Caught A Fish Alive', 'Once I Caught A Fish Alive', 'Once I Caught A Fish Alive.mp3', 'music', 'English', '["Once I Caught A Fish Alive","fish alive","caught a fish","fishing song","fish counting song","1 2 3 4 5 fish","counting fish","fish nursery rhyme"]', 1),
(UUID(), 'Ten Little Dinos', 'Ten Little Dinos', 'Ten Little Dinos.mp3', 'music', 'English', '["Ten Little Dinos","ten dinos","little dinosaurs","dinosaur song","counting dinosaurs","10 little dinos","dino counting song","prehistoric song","kids dinosaur song"]', 1),
(UUID(), 'The Wheels on the Bus', 'The Wheels on the Bus', 'The Wheels on the Bus.mp3', 'music', 'English', '["The Wheels on the Bus","wheels on the bus","bus song","wheels go round and round","children bus song","classic kids song","nursery rhyme bus","preschool bus song"]', 1);
-- Hindi Music (sample entries)
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'चंदा मामा दूर के', 'Chanda Mama Door Ke', 'Chanda Mama Door Ke.mp3', 'music', 'Hindi', '["Chanda Mama Door Ke","चंदा मामा","moon song","hindi nursery rhyme"]', 1),
(UUID(), 'मछली जल की रानी है', 'Machli Jal Ki Rani Hai', 'Machli Jal Ki Rani Hai.mp3', 'music', 'Hindi', '["Machli Jal Ki Rani Hai","मछली जल की रानी","fish song hindi","water queen fish"]', 1);
-- Kannada Music (sample entries)
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'ಆನೆ ಬಂತು ಆನೆ', 'Aane Banthu Aane', 'Aane Banthu Aane.mp3', 'music', 'Kannada', '["Aane Banthu Aane","ಆನೆ ಬಂತು","elephant song kannada"]', 1),
(UUID(), 'ಚಿಕ್ಕ ಚಿಕ್ಕ ಅಂಗಡಿ', 'Chikka Chikka Angadi', 'Chikka Chikka Angadi.mp3', 'music', 'Kannada', '["Chikka Chikka Angadi","ಚಿಕ್ಕ ಅಂಗಡಿ","small shop song"]', 1);
-- Telugu Music (sample entries)
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'చందమామ రావే', 'Chandamama Raave', 'Chandamama Raave.mp3', 'music', 'Telugu', '["Chandamama Raave","చందమామ","moon uncle song telugu"]', 1),
(UUID(), 'చిట్టి చిలకమ్మ', 'Chitti Chilakamma', 'Chitti Chilakamma.mp3', 'music', 'Telugu', '["Chitti Chilakamma","చిట్టి చిలకమ్మ","parrot song telugu"]', 1);
-- Phonics Music (sample entries)
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'ABC Phonics Song', 'ABC Phonics Song', 'ABC Phonics Song.mp3', 'music', 'Phonics', '["ABC Phonics Song","alphabet song","phonics abc","letter sounds"]', 1),
(UUID(), 'Letter A Song', 'Letter A Song', 'Letter A Song.mp3', 'music', 'Phonics', '["Letter A Song","a for apple","phonics a","letter a sounds"]', 1);
-- Adventure Stories
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'a portrait of a cat', 'a portrait of a cat', 'a portrait of a cat.mp3', 'story', 'Adventure', '["portrait of cat","cat portrait","cat story"]', 1),
(UUID(), 'a visit from st nicholas', 'a visit from st nicholas', 'a visit from st nicholas.mp3', 'story', 'Adventure', '["visit from st nicholas","st nicholas","christmas story"]', 1),
(UUID(), 'agent bertie part (1)', 'agent bertie part (1)', 'agent bertie part (1).mp3', 'story', 'Adventure', '["agent bertie","bertie part 1","bertie adventure"]', 1),
(UUID(), 'astropup and the revenge of the parrot', 'astropup and the revenge of the parrot', 'astropup and the revenge of the parrot.mp3', 'story', 'Adventure', '["astropup parrot revenge","astropup revenge","space dog parrot"]', 1),
(UUID(), 'astropup and the ship of birds', 'astropup and the ship of birds', 'astropup and the ship of birds.mp3', 'story', 'Adventure', '["astropup ship birds","astropup birds","space dog birds"]', 1),
(UUID(), 'astropup the hero', 'astropup the hero', 'astropup the hero.mp3', 'story', 'Adventure', '["astropup hero","hero story","space dog hero"]', 1);
-- Bedtime Stories
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'bedtime meditation', 'bedtime meditation', 'bedtime meditation.mp3', 'story', 'Bedtime', '["meditation for sleep","sleep meditation","calm bedtime"]', 1),
(UUID(), 'the sleepy train', 'the sleepy train', 'the sleepy train.mp3', 'story', 'Bedtime', '["sleepy train story","train to dreamland","bedtime train"]', 1),
(UUID(), 'counting sheep', 'counting sheep', 'counting sheep.mp3', 'story', 'Bedtime', '["sheep counting","sleep counting","bedtime counting"]', 1);
-- Educational Stories
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'learn about colors', 'learn about colors', 'learn about colors.mp3', 'story', 'Educational', '["colors lesson","learning colors","color education"]', 1),
(UUID(), 'the water cycle', 'the water cycle', 'the water cycle.mp3', 'story', 'Educational', '["water cycle story","science story","rain cycle"]', 1),
(UUID(), 'counting to ten', 'counting to ten', 'counting to ten.mp3', 'story', 'Educational', '["number story","counting lesson","math story"]', 1);
-- Fairy Tales
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'cinderella', 'cinderella', 'cinderella.mp3', 'story', 'Fairy Tales', '["cinderella story","glass slipper","fairy godmother"]', 1),
(UUID(), 'goldilocks and the three bears', 'goldilocks and the three bears', 'goldilocks and the three bears.mp3', 'story', 'Fairy Tales', '["goldilocks","three bears","porridge story"]', 1),
(UUID(), 'little red riding hood', 'little red riding hood', 'little red riding hood.mp3', 'story', 'Fairy Tales', '["red riding hood","wolf story","grandmother story"]', 1);
-- Fantasy Stories
INSERT INTO content_library (id, title, romanized, filename, content_type, category, alternatives, is_active) VALUES
(UUID(), 'the magic forest', 'the magic forest', 'the magic forest.mp3', 'story', 'Fantasy', '["magical forest","enchanted woods","fantasy forest"]', 1),
(UUID(), 'dragon and the princess', 'dragon and the princess', 'dragon and the princess.mp3', 'story', 'Fantasy', '["dragon story","princess tale","fantasy adventure"]', 1),
(UUID(), 'the flying carpet', 'the flying carpet', 'the flying carpet.mp3', 'story', 'Fantasy', '["magic carpet","flying adventure","arabian fantasy"]', 1);
-- Show summary
SELECT content_type, category, COUNT(*) as count
FROM content_library
GROUP BY content_type, category
ORDER BY content_type, category;
SELECT COUNT(*) as total_content FROM content_library;

View file

@ -0,0 +1,44 @@
#!/bin/bash
# Content Library Migration Runner Script
# This script runs the ContentLibraryMigration to populate the database with music and stories
echo "=========================================="
echo "Content Library Migration Script"
echo "=========================================="
echo ""
# Navigate to the project directory
cd /Users/craftech360/Downloads/app/cheeko_server/main/manager-api
# Check if the project has been built
if [ ! -f "target/manager-api.jar" ]; then
echo "Building the project first..."
mvn clean package -DskipTests
if [ $? -ne 0 ]; then
echo "Build failed. Please check your Maven configuration."
exit 1
fi
fi
echo "Starting content library migration..."
echo ""
# Run the migration with the migration profile
java -jar target/manager-api.jar \
--spring.profiles.active=migration,dev \
--spring.main.web-application-type=none \
--spring.main.banner-mode=off
if [ $? -eq 0 ]; then
echo ""
echo "=========================================="
echo "Migration completed successfully!"
echo "=========================================="
else
echo ""
echo "=========================================="
echo "Migration failed. Check the logs above."
echo "=========================================="
exit 1
fi

343
main/manager-api/run-migration.sh Executable file
View file

@ -0,0 +1,343 @@
#!/bin/bash
# XiaoZhi Content Library Migration Script
# This script provides an easy way to run the content library migration
# with proper environment setup and error handling.
set -e # Exit on any error
# Script configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
JAR_NAME="manager-api.jar"
MAIN_CLASS="xiaozhi.migration.MigrationRunner"
LOG_FILE="logs/content-migration.log"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Function to print colored output
print_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Function to print usage
print_usage() {
cat << EOF
Usage: $0 [OPTIONS]
XiaoZhi Content Library Migration Script
OPTIONS:
-h, --help Show this help message
-p, --path PATH Specify xiaozhi-server directory path (default: auto-detect)
-b, --batch-size SIZE Batch size for database operations (default: 100)
-d, --dry-run Perform a dry run without actual database changes
-v, --verbose Enable verbose logging
-c, --check-only Only check prerequisites without running migration
EXAMPLES:
$0 # Run with default settings
$0 --path /path/to/xiaozhi-server # Specify custom path
$0 --batch-size 50 --verbose # Custom batch size with verbose logging
$0 --check-only # Check prerequisites only
$0 --dry-run # Test run without database changes
ENVIRONMENT VARIABLES:
XIAOZHI_SERVER_PATH Override xiaozhi-server directory path
MIGRATION_BATCH_SIZE Override batch size for migration
JAVA_OPTS Additional JVM options
EOF
}
# Function to check prerequisites
check_prerequisites() {
print_info "Checking prerequisites..."
# Check if Java is available
if ! command -v java &> /dev/null; then
print_error "Java is not installed or not in PATH"
return 1
fi
local java_version=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2)
print_info "Java version: $java_version"
# Check if Maven is available (for building if needed)
if ! command -v mvn &> /dev/null; then
print_warning "Maven is not available - assuming JAR is pre-built"
fi
# Check if JAR file exists or can be built
if [[ -f "target/$JAR_NAME" ]]; then
print_info "Found JAR file: target/$JAR_NAME"
elif [[ -f "$JAR_NAME" ]]; then
print_info "Found JAR file: $JAR_NAME"
else
print_info "JAR file not found - attempting to build..."
if command -v mvn &> /dev/null; then
mvn clean package -DskipTests
if [[ $? -ne 0 ]]; then
print_error "Failed to build JAR file"
return 1
fi
else
print_error "JAR file not found and Maven not available for building"
return 1
fi
fi
return 0
}
# Function to find xiaozhi-server path
find_xiaozhi_server_path() {
local custom_path="$1"
# Use custom path if provided
if [[ -n "$custom_path" ]]; then
if [[ -d "$custom_path" ]]; then
echo "$custom_path"
return 0
else
print_error "Specified path does not exist: $custom_path"
return 1
fi
fi
# Check environment variable
if [[ -n "$XIAOZHI_SERVER_PATH" ]]; then
if [[ -d "$XIAOZHI_SERVER_PATH" ]]; then
echo "$XIAOZHI_SERVER_PATH"
return 0
else
print_warning "Environment XIAOZHI_SERVER_PATH is set but directory does not exist: $XIAOZHI_SERVER_PATH"
fi
fi
# Auto-detect possible paths
local possible_paths=(
"./xiaozhi-server"
"../xiaozhi-server"
"../../xiaozhi-server"
"/opt/xiaozhi/xiaozhi-server"
"/home/$(whoami)/xiaozhi-server"
)
for path in "${possible_paths[@]}"; do
if [[ -d "$path" ]]; then
echo "$(realpath "$path")"
return 0
fi
done
print_error "Could not find xiaozhi-server directory"
print_info "Please specify the path using --path option or set XIAOZHI_SERVER_PATH environment variable"
return 1
}
# Function to validate xiaozhi-server structure
validate_xiaozhi_structure() {
local path="$1"
print_info "Validating xiaozhi-server structure at: $path"
# Check music directory
if [[ ! -d "$path/music" ]]; then
print_error "Music directory not found: $path/music"
return 1
fi
# Check stories directory
if [[ ! -d "$path/stories" ]]; then
print_error "Stories directory not found: $path/stories"
return 1
fi
# Check for metadata files
local music_count=0
local story_count=0
for lang_dir in "$path/music"/*; do
if [[ -d "$lang_dir" && -f "$lang_dir/metadata.json" ]]; then
((music_count++))
print_info "Found music metadata: $(basename "$lang_dir")"
fi
done
for genre_dir in "$path/stories"/*; do
if [[ -d "$genre_dir" && -f "$genre_dir/metadata.json" ]]; then
((story_count++))
print_info "Found story metadata: $(basename "$genre_dir")"
fi
done
if [[ $music_count -eq 0 && $story_count -eq 0 ]]; then
print_error "No metadata files found in music or stories directories"
return 1
fi
print_success "Found $music_count music categories and $story_count story genres"
return 0
}
# Function to run migration
run_migration() {
local xiaozhi_path="$1"
local batch_size="${2:-100}"
local dry_run="${3:-false}"
local verbose="${4:-false}"
print_info "Starting Content Library Migration..."
print_info "XiaoZhi Server Path: $xiaozhi_path"
print_info "Batch Size: $batch_size"
# Prepare JVM options
local jvm_opts="-Xmx2g -Dspring.profiles.active=migration"
if [[ "$verbose" == "true" ]]; then
jvm_opts="$jvm_opts -Dlogging.level.xiaozhi.migration=DEBUG"
fi
# Add custom JAVA_OPTS if set
if [[ -n "$JAVA_OPTS" ]]; then
jvm_opts="$jvm_opts $JAVA_OPTS"
fi
# Set environment variables
export MIGRATION_BASE_PATH="$xiaozhi_path"
export MIGRATION_BATCH_SIZE="$batch_size"
if [[ "$dry_run" == "true" ]]; then
export MIGRATION_DRY_RUN="true"
print_warning "Running in DRY RUN mode - no database changes will be made"
fi
# Create logs directory
mkdir -p logs
# Find JAR file
local jar_file=""
if [[ -f "target/$JAR_NAME" ]]; then
jar_file="target/$JAR_NAME"
elif [[ -f "$JAR_NAME" ]]; then
jar_file="$JAR_NAME"
else
print_error "JAR file not found"
return 1
fi
# Run migration
print_info "Executing migration..."
if java $jvm_opts -jar "$jar_file" 2>&1 | tee "$LOG_FILE"; then
print_success "Migration completed successfully!"
print_info "Migration log saved to: $LOG_FILE"
# Show summary from log
if [[ -f "$LOG_FILE" ]]; then
print_info "Migration Summary:"
grep -A 20 "MIGRATION SUMMARY" "$LOG_FILE" | tail -20 || true
fi
return 0
else
print_error "Migration failed! Check log file: $LOG_FILE"
return 1
fi
}
# Main script
main() {
local xiaozhi_path=""
local batch_size="100"
local dry_run="false"
local verbose="false"
local check_only="false"
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help)
print_usage
exit 0
;;
-p|--path)
xiaozhi_path="$2"
shift 2
;;
-b|--batch-size)
batch_size="$2"
shift 2
;;
-d|--dry-run)
dry_run="true"
shift
;;
-v|--verbose)
verbose="true"
shift
;;
-c|--check-only)
check_only="true"
shift
;;
*)
print_error "Unknown option: $1"
print_usage
exit 1
;;
esac
done
print_info "XiaoZhi Content Library Migration"
print_info "=================================="
# Check prerequisites
if ! check_prerequisites; then
exit 1
fi
# Find xiaozhi-server path
if ! xiaozhi_path=$(find_xiaozhi_server_path "$xiaozhi_path"); then
exit 1
fi
# Validate structure
if ! validate_xiaozhi_structure "$xiaozhi_path"; then
exit 1
fi
# Exit if check-only mode
if [[ "$check_only" == "true" ]]; then
print_success "Prerequisites check completed successfully!"
exit 0
fi
# Run migration
if run_migration "$xiaozhi_path" "$batch_size" "$dry_run" "$verbose"; then
print_success "Migration script completed successfully!"
exit 0
else
print_error "Migration script failed!"
exit 1
fi
}
# Run main function
main "$@"

View file

@ -0,0 +1,505 @@
package xiaozhi.migration;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import xiaozhi.modules.content.dto.ContentLibraryDTO;
import xiaozhi.modules.content.entity.ContentLibraryEntity;
import xiaozhi.modules.content.service.ContentLibraryService;
/**
* Data Migration Script for Content Library
*
* This script migrates content metadata from JSON files in the xiaozhi-server directory
* to the content_library database table.
*
* Usage: Run as a Spring Boot application with migration profile
* java -jar app.jar --spring.profiles.active=migration
*
* Directory Structure:
* - xiaozhi-server/music/[Language]/metadata.json (English, Hindi, Kannada, Phonics, Telugu)
* - xiaozhi-server/stories/[Genre]/metadata.json (Adventure, Bedtime, Educational, Fairy Tales, Fantasy)
*
* @author Data Migration Script Generator
* @version 1.0
*/
@Slf4j
@Component
public class ContentLibraryMigration implements CommandLineRunner {
@Autowired
private ContentLibraryService contentLibraryService;
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Base path configuration - adjust as needed based on deployment structure
private static final String BASE_PATH = "/Users/craftech360/Downloads/app/cheeko_server/main/xiaozhi-server";
private static final String MUSIC_PATH = BASE_PATH + "/music";
private static final String STORIES_PATH = BASE_PATH + "/stories";
// Batch size for database operations
private static final int BATCH_SIZE = 100;
// Migration statistics
private final MigrationStatistics stats = new MigrationStatistics();
@Override
public void run(String... args) throws Exception {
// Check if migration profile is active
String profiles = System.getProperty("spring.profiles.active", "");
if (!profiles.contains("migration")) {
log.info("Migration profile not active, skipping content library migration");
return;
}
log.info("Starting Content Library Migration...");
log.info("Base path: {}", BASE_PATH);
try {
// Verify directory structure
verifyDirectoryStructure();
// Migrate music content
migrateMusicContent();
// Migrate story content
migrateStoryContent();
// Print migration summary
printMigrationSummary();
} catch (Exception e) {
log.error("Migration failed: {}", e.getMessage(), e);
throw new RuntimeException("Content library migration failed", e);
}
}
/**
* Verify that the required directory structure exists
*/
private void verifyDirectoryStructure() {
log.info("Verifying directory structure...");
File baseDir = new File(BASE_PATH);
if (!baseDir.exists()) {
throw new RuntimeException("Base directory does not exist: " + BASE_PATH);
}
File musicDir = new File(MUSIC_PATH);
if (!musicDir.exists()) {
throw new RuntimeException("Music directory does not exist: " + MUSIC_PATH);
}
File storiesDir = new File(STORIES_PATH);
if (!storiesDir.exists()) {
throw new RuntimeException("Stories directory does not exist: " + STORIES_PATH);
}
log.info("Directory structure verified successfully");
}
/**
* Migrate music content from JSON metadata files
*/
private void migrateMusicContent() {
log.info("Starting music content migration...");
File musicDir = new File(MUSIC_PATH);
File[] languageDirectories = musicDir.listFiles(File::isDirectory);
if (languageDirectories == null || languageDirectories.length == 0) {
log.warn("No music language directories found in: {}", MUSIC_PATH);
return;
}
List<ContentLibraryDTO> allMusicContent = new ArrayList<>();
for (File languageDir : languageDirectories) {
String language = languageDir.getName();
log.info("Processing music language: {}", language);
try {
List<ContentLibraryDTO> languageContent = processMusicLanguage(language, languageDir);
allMusicContent.addAll(languageContent);
stats.addProcessedLanguage(language, languageContent.size());
} catch (Exception e) {
log.error("Failed to process music language {}: {}", language, e.getMessage(), e);
stats.addFailedLanguage(language, e.getMessage());
}
}
// Batch insert music content
if (!allMusicContent.isEmpty()) {
batchInsertContent(allMusicContent, "music");
}
log.info("Completed music content migration. Processed {} items", allMusicContent.size());
}
/**
* Process music content for a specific language
*/
private List<ContentLibraryDTO> processMusicLanguage(String language, File languageDir) throws IOException {
File metadataFile = new File(languageDir, "metadata.json");
if (!metadataFile.exists()) {
log.warn("No metadata.json found for language: {}", language);
return new ArrayList<>();
}
String jsonContent = Files.readString(metadataFile.toPath());
// Parse JSON content
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
List<ContentLibraryDTO> contentList = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String title = entry.getKey();
JsonObject contentInfo = entry.getValue().getAsJsonObject();
try {
ContentLibraryDTO dto = createMusicContentDTO(title, contentInfo, language);
contentList.add(dto);
} catch (Exception e) {
log.error("Failed to process music item '{}' in language {}: {}", title, language, e.getMessage());
stats.addFailedItem(title, e.getMessage());
}
}
return contentList;
}
/**
* Create ContentLibraryDTO for music content
*/
private ContentLibraryDTO createMusicContentDTO(String title, JsonObject contentInfo, String language) {
ContentLibraryDTO dto = new ContentLibraryDTO();
// Basic information
dto.setTitle(title);
dto.setRomanized(getJsonString(contentInfo, "romanized"));
dto.setFilename(getJsonString(contentInfo, "filename"));
dto.setContentType(ContentLibraryEntity.ContentType.MUSIC.getValue());
dto.setCategory(language);
// Parse alternatives array
JsonArray alternativesArray = contentInfo.getAsJsonArray("alternatives");
if (alternativesArray != null) {
List<String> alternatives = new ArrayList<>();
for (JsonElement element : alternativesArray) {
alternatives.add(element.getAsString());
}
dto.setAlternatives(alternatives);
} else {
dto.setAlternatives(new ArrayList<>());
}
// Additional metadata (these might be null for now, can be populated later)
dto.setAwsS3Url(getJsonString(contentInfo, "aws_s3_url"));
dto.setDurationSeconds(getJsonInteger(contentInfo, "duration_seconds"));
dto.setFileSizeBytes(getJsonLong(contentInfo, "file_size_bytes"));
// Set as active
dto.setIsActive(true);
return dto;
}
/**
* Migrate story content from JSON metadata files
*/
private void migrateStoryContent() {
log.info("Starting story content migration...");
File storiesDir = new File(STORIES_PATH);
File[] genreDirectories = storiesDir.listFiles(File::isDirectory);
if (genreDirectories == null || genreDirectories.length == 0) {
log.warn("No story genre directories found in: {}", STORIES_PATH);
return;
}
List<ContentLibraryDTO> allStoryContent = new ArrayList<>();
for (File genreDir : genreDirectories) {
String genre = genreDir.getName();
log.info("Processing story genre: {}", genre);
try {
List<ContentLibraryDTO> genreContent = processStoryGenre(genre, genreDir);
allStoryContent.addAll(genreContent);
stats.addProcessedGenre(genre, genreContent.size());
} catch (Exception e) {
log.error("Failed to process story genre {}: {}", genre, e.getMessage(), e);
stats.addFailedGenre(genre, e.getMessage());
}
}
// Batch insert story content
if (!allStoryContent.isEmpty()) {
batchInsertContent(allStoryContent, "stories");
}
log.info("Completed story content migration. Processed {} items", allStoryContent.size());
}
/**
* Process story content for a specific genre
*/
private List<ContentLibraryDTO> processStoryGenre(String genre, File genreDir) throws IOException {
File metadataFile = new File(genreDir, "metadata.json");
if (!metadataFile.exists()) {
log.warn("No metadata.json found for genre: {}", genre);
return new ArrayList<>();
}
String jsonContent = Files.readString(metadataFile.toPath());
// Parse JSON content
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
List<ContentLibraryDTO> contentList = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String title = entry.getKey();
JsonObject contentInfo = entry.getValue().getAsJsonObject();
try {
ContentLibraryDTO dto = createStoryContentDTO(title, contentInfo, genre);
contentList.add(dto);
} catch (Exception e) {
log.error("Failed to process story item '{}' in genre {}: {}", title, genre, e.getMessage());
stats.addFailedItem(title, e.getMessage());
}
}
return contentList;
}
/**
* Create ContentLibraryDTO for story content
*/
private ContentLibraryDTO createStoryContentDTO(String title, JsonObject contentInfo, String genre) {
ContentLibraryDTO dto = new ContentLibraryDTO();
// Basic information
dto.setTitle(title);
dto.setRomanized(getJsonString(contentInfo, "romanized"));
dto.setFilename(getJsonString(contentInfo, "filename"));
dto.setContentType(ContentLibraryEntity.ContentType.STORY.getValue());
dto.setCategory(genre);
// Parse alternatives array
JsonArray alternativesArray = contentInfo.getAsJsonArray("alternatives");
if (alternativesArray != null) {
List<String> alternatives = new ArrayList<>();
for (JsonElement element : alternativesArray) {
alternatives.add(element.getAsString());
}
dto.setAlternatives(alternatives);
} else {
dto.setAlternatives(new ArrayList<>());
}
// Additional metadata (these might be null for now, can be populated later)
dto.setAwsS3Url(getJsonString(contentInfo, "aws_s3_url"));
dto.setDurationSeconds(getJsonInteger(contentInfo, "duration_seconds"));
dto.setFileSizeBytes(getJsonLong(contentInfo, "file_size_bytes"));
// Set as active
dto.setIsActive(true);
return dto;
}
/**
* Batch insert content into database
*/
private void batchInsertContent(List<ContentLibraryDTO> contentList, String contentType) {
log.info("Starting batch insert for {} {} items", contentList.size(), contentType);
// Process in batches to avoid memory issues and improve performance
List<List<ContentLibraryDTO>> batches = partition(contentList, BATCH_SIZE);
int totalInserted = 0;
for (int i = 0; i < batches.size(); i++) {
List<ContentLibraryDTO> batch = batches.get(i);
try {
int inserted = contentLibraryService.batchInsertContent(batch);
totalInserted += inserted;
log.info("Batch {}/{} completed: {} items inserted", i + 1, batches.size(), inserted);
stats.addInsertedCount(inserted);
if (inserted != batch.size()) {
log.warn("Batch insert incomplete: expected {}, inserted {}", batch.size(), inserted);
}
} catch (Exception e) {
log.error("Failed to insert batch {}/{}: {}", i + 1, batches.size(), e.getMessage(), e);
stats.addFailedBatch(i + 1, e.getMessage());
}
}
log.info("Batch insert completed for {}: {} total items inserted", contentType, totalInserted);
}
/**
* Print migration summary
*/
private void printMigrationSummary() {
log.info("================== MIGRATION SUMMARY ==================");
log.info("Total items processed: {}", stats.getTotalProcessed());
log.info("Total items inserted: {}", stats.getTotalInserted());
log.info("Total failed items: {}", stats.getTotalFailed());
log.info("");
log.info("MUSIC CONTENT:");
for (String language : stats.getProcessedLanguages().keySet()) {
log.info(" - {}: {} items", language, stats.getProcessedLanguages().get(language));
}
log.info("STORY CONTENT:");
for (String genre : stats.getProcessedGenres().keySet()) {
log.info(" - {}: {} items", genre, stats.getProcessedGenres().get(genre));
}
if (!stats.getFailedLanguages().isEmpty()) {
log.error("FAILED LANGUAGES:");
stats.getFailedLanguages().forEach((lang, error) ->
log.error(" - {}: {}", lang, error));
}
if (!stats.getFailedGenres().isEmpty()) {
log.error("FAILED GENRES:");
stats.getFailedGenres().forEach((genre, error) ->
log.error(" - {}: {}", genre, error));
}
if (!stats.getFailedItems().isEmpty()) {
log.error("FAILED ITEMS (showing first 10):");
stats.getFailedItems().entrySet().stream()
.limit(10)
.forEach(entry -> log.error(" - {}: {}", entry.getKey(), entry.getValue()));
}
if (!stats.getFailedBatches().isEmpty()) {
log.error("FAILED BATCHES:");
stats.getFailedBatches().forEach((batch, error) ->
log.error(" - Batch {}: {}", batch, error));
}
log.info("======================================================");
}
// Helper methods
/**
* Safely get string value from JSON object
*/
private String getJsonString(JsonObject jsonObject, String key) {
JsonElement element = jsonObject.get(key);
return (element != null && !element.isJsonNull()) ? element.getAsString() : null;
}
/**
* Safely get integer value from JSON object
*/
private Integer getJsonInteger(JsonObject jsonObject, String key) {
JsonElement element = jsonObject.get(key);
return (element != null && !element.isJsonNull()) ? element.getAsInt() : null;
}
/**
* Safely get long value from JSON object
*/
private Long getJsonLong(JsonObject jsonObject, String key) {
JsonElement element = jsonObject.get(key);
return (element != null && !element.isJsonNull()) ? element.getAsLong() : null;
}
/**
* Partition list into smaller batches
*/
private <T> List<List<T>> partition(List<T> list, int size) {
List<List<T>> partitions = new ArrayList<>();
for (int i = 0; i < list.size(); i += size) {
partitions.add(list.subList(i, Math.min(i + size, list.size())));
}
return partitions;
}
/**
* Migration statistics tracker
*/
private static class MigrationStatistics {
private final Map<String, Integer> processedLanguages = new HashMap<>();
private final Map<String, Integer> processedGenres = new HashMap<>();
private final Map<String, String> failedLanguages = new HashMap<>();
private final Map<String, String> failedGenres = new HashMap<>();
private final Map<String, String> failedItems = new HashMap<>();
private final Map<Integer, String> failedBatches = new HashMap<>();
private int totalInserted = 0;
public void addProcessedLanguage(String language, int count) {
processedLanguages.put(language, count);
}
public void addProcessedGenre(String genre, int count) {
processedGenres.put(genre, count);
}
public void addFailedLanguage(String language, String error) {
failedLanguages.put(language, error);
}
public void addFailedGenre(String genre, String error) {
failedGenres.put(genre, error);
}
public void addFailedItem(String item, String error) {
failedItems.put(item, error);
}
public void addFailedBatch(int batchNumber, String error) {
failedBatches.put(batchNumber, error);
}
public void addInsertedCount(int count) {
totalInserted += count;
}
public int getTotalProcessed() {
return processedLanguages.values().stream().mapToInt(Integer::intValue).sum() +
processedGenres.values().stream().mapToInt(Integer::intValue).sum();
}
public int getTotalFailed() {
return failedItems.size();
}
// Getters
public Map<String, Integer> getProcessedLanguages() { return processedLanguages; }
public Map<String, Integer> getProcessedGenres() { return processedGenres; }
public Map<String, String> getFailedLanguages() { return failedLanguages; }
public Map<String, String> getFailedGenres() { return failedGenres; }
public Map<String, String> getFailedItems() { return failedItems; }
public Map<Integer, String> getFailedBatches() { return failedBatches; }
public int getTotalInserted() { return totalInserted; }
}
}

View file

@ -0,0 +1,197 @@
package xiaozhi.migration;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import jakarta.annotation.PostConstruct;
import java.io.File;
import java.util.List;
/**
* Configuration class for Content Library Migration
*
* This class manages all migration-specific configuration properties
* and provides validation for paths and settings.
*
* @author Data Migration Configuration
* @version 1.0
*/
@Data
@Configuration
@Profile("migration")
@ConfigurationProperties(prefix = "migration.content-library")
public class MigrationConfiguration {
/**
* Base path for xiaozhi-server directory
*/
private String basePath = System.getProperty("user.dir") + "/xiaozhi-server";
/**
* Batch size for database operations
*/
private int batchSize = 100;
/**
* Whether to skip migration if content already exists
*/
private boolean skipIfExists = false;
/**
* Connection timeout in milliseconds
*/
private int connectionTimeout = 30000;
/**
* Read timeout in milliseconds
*/
private int readTimeout = 60000;
/**
* Music directory path
*/
private String musicPath;
/**
* Stories directory path
*/
private String storiesPath;
/**
* Music configuration
*/
private MusicConfig music = new MusicConfig();
/**
* Stories configuration
*/
private StoriesConfig stories = new StoriesConfig();
@PostConstruct
public void init() {
// Override with environment variables if present
String envBasePath = System.getenv("MIGRATION_BASE_PATH");
if (envBasePath != null && !envBasePath.trim().isEmpty()) {
this.basePath = envBasePath;
}
String envBatchSize = System.getenv("MIGRATION_BATCH_SIZE");
if (envBatchSize != null && !envBatchSize.trim().isEmpty()) {
try {
this.batchSize = Integer.parseInt(envBatchSize);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid MIGRATION_BATCH_SIZE value: " + envBatchSize);
}
}
// Set derived paths if not already set
if (musicPath == null) {
musicPath = basePath + "/music";
}
if (storiesPath == null) {
storiesPath = basePath + "/stories";
}
// Validate configuration
validateConfiguration();
}
/**
* Validate migration configuration
*/
private void validateConfiguration() {
validatePath(basePath, "Base path");
validatePath(musicPath, "Music path");
validatePath(storiesPath, "Stories path");
if (batchSize <= 0 || batchSize > 1000) {
throw new IllegalArgumentException("Batch size must be between 1 and 1000, got: " + batchSize);
}
if (connectionTimeout <= 0) {
throw new IllegalArgumentException("Connection timeout must be positive, got: " + connectionTimeout);
}
if (readTimeout <= 0) {
throw new IllegalArgumentException("Read timeout must be positive, got: " + readTimeout);
}
}
/**
* Validate that a path exists
*/
private void validatePath(String path, String description) {
if (path == null || path.trim().isEmpty()) {
throw new IllegalArgumentException(description + " cannot be empty");
}
File file = new File(path);
if (!file.exists()) {
throw new IllegalArgumentException(description + " does not exist: " + path);
}
if (!file.isDirectory()) {
throw new IllegalArgumentException(description + " is not a directory: " + path);
}
}
/**
* Get absolute path for music directory
*/
public String getAbsoluteMusicPath() {
return new File(musicPath).getAbsolutePath();
}
/**
* Get absolute path for stories directory
*/
public String getAbsoluteStoriesPath() {
return new File(storiesPath).getAbsolutePath();
}
/**
* Get absolute base path
*/
public String getAbsoluteBasePath() {
return new File(basePath).getAbsolutePath();
}
/**
* Music content configuration
*/
@Data
public static class MusicConfig {
private String contentType = "music";
private List<String> supportedLanguages = List.of(
"English", "Hindi", "Kannada", "Phonics", "Telugu"
);
}
/**
* Stories content configuration
*/
@Data
public static class StoriesConfig {
private String contentType = "story";
private List<String> supportedGenres = List.of(
"Adventure", "Bedtime", "Educational", "Fairy Tales", "Fantasy"
);
}
/**
* Check if a language is supported for music content
*/
public boolean isSupportedMusicLanguage(String language) {
return music.getSupportedLanguages().contains(language);
}
/**
* Check if a genre is supported for story content
*/
public boolean isSupportedStoryGenre(String genre) {
return stories.getSupportedGenres().contains(genre);
}
}

View file

@ -0,0 +1,110 @@
package xiaozhi.migration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
* Standalone Migration Runner
*
* This class provides a standalone entry point for running the content library migration
* without starting the full application.
*
* Usage:
* 1. Command line: mvn exec:java -Dexec.mainClass="xiaozhi.migration.MigrationRunner" -Dspring.profiles.active=migration
* 2. IDE: Run this class directly with VM options: -Dspring.profiles.active=migration
* 3. JAR: java -cp app.jar xiaozhi.migration.MigrationRunner --spring.profiles.active=migration
*
* Environment Variables:
* - XIAOZHI_SERVER_PATH: Override the default xiaozhi-server path
* - MIGRATION_BATCH_SIZE: Override the default batch size (default: 100)
* - MIGRATION_BASE_PATH: Override the base path for migration files
*
* The migration process will:
* 1. Scan xiaozhi-server/music/[language]/metadata.json files
* 2. Scan xiaozhi-server/stories/[genre]/metadata.json files
* 3. Parse JSON content and create ContentLibraryDTO objects
* 4. Batch insert content into the content_library table
* 5. Provide detailed logging and statistics
*
* @author Data Migration Script Generator
* @version 1.0
*/
@Slf4j
@SpringBootApplication
@ComponentScan(basePackages = {
"xiaozhi.migration", // Migration components
"xiaozhi.modules.content", // Content service components
"xiaozhi.common", // Common utilities
"xiaozhi.config" // Configuration classes
})
public class MigrationRunner {
public static void main(String[] args) {
log.info("=======================================================");
log.info("XiaoZhi Content Library Migration Runner");
log.info("=======================================================");
// Set migration profile if not already set
String profiles = System.getProperty("spring.profiles.active");
if (profiles == null || !profiles.contains("migration")) {
System.setProperty("spring.profiles.active", "migration");
log.info("Setting spring profile to 'migration'");
}
// Log environment configuration
logEnvironmentInfo();
try {
// Create Spring context and run migration
SpringApplication app = new SpringApplication(MigrationRunner.class);
// Disable web environment for migration
app.setWebApplicationType(org.springframework.boot.WebApplicationType.NONE);
// Disable banner for cleaner output
app.setBannerMode(org.springframework.boot.Banner.Mode.OFF);
// Run the application
var context = app.run(args);
log.info("Migration completed successfully!");
log.info("Application context will be closed automatically");
// Gracefully shutdown
SpringApplication.exit(context, () -> 0);
} catch (Exception e) {
log.error("Migration failed with error: {}", e.getMessage(), e);
System.exit(1);
}
}
/**
* Log environment configuration for debugging
*/
private static void logEnvironmentInfo() {
log.info("Environment Configuration:");
log.info(" - Java Version: {}", System.getProperty("java.version"));
log.info(" - Working Directory: {}", System.getProperty("user.dir"));
log.info(" - Spring Profiles: {}", System.getProperty("spring.profiles.active", "default"));
String xiaozhiPath = System.getenv("XIAOZHI_SERVER_PATH");
if (xiaozhiPath != null) {
log.info(" - XiaoZhi Server Path (env): {}", xiaozhiPath);
}
String batchSize = System.getenv("MIGRATION_BATCH_SIZE");
if (batchSize != null) {
log.info(" - Batch Size (env): {}", batchSize);
}
String basePath = System.getenv("MIGRATION_BASE_PATH");
if (basePath != null) {
log.info(" - Base Path (env): {}", basePath);
}
log.info("=======================================================");
}
}

View file

@ -0,0 +1,284 @@
package xiaozhi.migration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Profile;
import xiaozhi.modules.content.service.ContentLibraryService;
import xiaozhi.modules.content.dto.ContentSearchDTO;
import xiaozhi.common.page.PageData;
import xiaozhi.modules.content.dto.ContentLibraryDTO;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
/**
* Migration Validator
*
* This component validates the migrated content library data to ensure
* the migration was successful and data integrity is maintained.
*
* Run with: java -jar app.jar --spring.profiles.active=validation
*
* @author Migration Validator
* @version 1.0
*/
@Slf4j
@Component
@Profile("validation")
public class MigrationValidator implements CommandLineRunner {
@Autowired
private ContentLibraryService contentLibraryService;
@Override
public void run(String... args) throws Exception {
log.info("=======================================================");
log.info("Content Library Migration Validation");
log.info("=======================================================");
try {
// Validate content statistics
validateContentStatistics();
// Validate content categories
validateCategories();
// Validate sample content
validateSampleContent();
// Validate search functionality
validateSearchFunctionality();
log.info("=======================================================");
log.info("Migration Validation COMPLETED SUCCESSFULLY");
log.info("=======================================================");
} catch (Exception e) {
log.error("Migration validation failed: {}", e.getMessage(), e);
throw e;
}
}
/**
* Validate content statistics
*/
private void validateContentStatistics() {
log.info("Validating content statistics...");
Object statsObj = contentLibraryService.getContentStatistics();
if (!(statsObj instanceof Map)) {
throw new RuntimeException("Invalid statistics format returned");
}
@SuppressWarnings("unchecked")
Map<String, Object> stats = (Map<String, Object>) statsObj;
Integer totalMusic = (Integer) stats.get("totalMusic");
Integer totalStories = (Integer) stats.get("totalStories");
Integer totalContent = (Integer) stats.get("totalContent");
log.info("Content Statistics:");
log.info(" - Total Music: {}", totalMusic != null ? totalMusic : 0);
log.info(" - Total Stories: {}", totalStories != null ? totalStories : 0);
log.info(" - Total Content: {}", totalContent != null ? totalContent : 0);
if (totalContent == null || totalContent == 0) {
throw new RuntimeException("No content found in database - migration may have failed");
}
if (totalMusic == null) totalMusic = 0;
if (totalStories == null) totalStories = 0;
if (!totalContent.equals(totalMusic + totalStories)) {
throw new RuntimeException("Content count mismatch: total=" + totalContent +
", music=" + totalMusic + ", stories=" + totalStories);
}
log.info("✓ Content statistics validation passed");
}
/**
* Validate content categories
*/
private void validateCategories() {
log.info("Validating content categories...");
// Expected categories based on migration script
String[] expectedMusicLanguages = {"English", "Hindi", "Kannada", "Phonics", "Telugu"};
String[] expectedStoryGenres = {"Adventure", "Bedtime", "Educational", "Fairy Tales", "Fantasy"};
// Get music categories
List<String> musicCategories = contentLibraryService.getCategoriesByType("music");
log.info("Found music categories: {}", musicCategories);
// Get story categories
List<String> storyCategories = contentLibraryService.getCategoriesByType("story");
log.info("Found story categories: {}", storyCategories);
// Validate music categories
for (String expectedLang : expectedMusicLanguages) {
if (!musicCategories.contains(expectedLang)) {
log.warn("Expected music language '{}' not found", expectedLang);
} else {
log.info("✓ Music language '{}' found", expectedLang);
}
}
// Validate story categories
for (String expectedGenre : expectedStoryGenres) {
if (!storyCategories.contains(expectedGenre)) {
log.warn("Expected story genre '{}' not found", expectedGenre);
} else {
log.info("✓ Story genre '{}' found", expectedGenre);
}
}
log.info("✓ Categories validation completed");
}
/**
* Validate sample content
*/
private void validateSampleContent() {
log.info("Validating sample content...");
// Test music content
ContentSearchDTO musicSearch = new ContentSearchDTO();
musicSearch.setContentType("music");
musicSearch.setLimit(5);
PageData<ContentLibraryDTO> musicResults = contentLibraryService.getContentList(musicSearch);
if (musicResults.getList() == null || musicResults.getList().isEmpty()) {
log.warn("No music content found");
} else {
log.info("Sample music content ({} items):", musicResults.getList().size());
for (ContentLibraryDTO content : musicResults.getList()) {
log.info(" - {} [{}] ({})", content.getTitle(), content.getCategory(),
content.getFilename());
validateContentItem(content, "music");
}
}
// Test story content
ContentSearchDTO storySearch = new ContentSearchDTO();
storySearch.setContentType("story");
storySearch.setLimit(5);
PageData<ContentLibraryDTO> storyResults = contentLibraryService.getContentList(storySearch);
if (storyResults.getList() == null || storyResults.getList().isEmpty()) {
log.warn("No story content found");
} else {
log.info("Sample story content ({} items):", storyResults.getList().size());
for (ContentLibraryDTO content : storyResults.getList()) {
log.info(" - {} [{}] ({})", content.getTitle(), content.getCategory(),
content.getFilename());
validateContentItem(content, "story");
}
}
log.info("✓ Sample content validation completed");
}
/**
* Validate individual content item
*/
private void validateContentItem(ContentLibraryDTO content, String expectedType) {
if (content.getId() == null || content.getId().isEmpty()) {
throw new RuntimeException("Content item missing ID: " + content.getTitle());
}
if (content.getTitle() == null || content.getTitle().isEmpty()) {
throw new RuntimeException("Content item missing title: " + content.getId());
}
if (!expectedType.equals(content.getContentType())) {
throw new RuntimeException("Content type mismatch for " + content.getTitle() +
": expected " + expectedType + ", got " + content.getContentType());
}
if (content.getCategory() == null || content.getCategory().isEmpty()) {
throw new RuntimeException("Content item missing category: " + content.getTitle());
}
if (content.getAlternatives() == null) {
log.warn("Content item missing alternatives: {}", content.getTitle());
}
if (content.getIsActive() == null || !content.getIsActive()) {
log.warn("Content item not active: {}", content.getTitle());
}
}
/**
* Validate search functionality
*/
private void validateSearchFunctionality() {
log.info("Validating search functionality...");
// Test basic search
ContentSearchDTO searchDTO = new ContentSearchDTO();
searchDTO.setQuery("baby");
searchDTO.setLimit(10);
PageData<ContentLibraryDTO> searchResults = contentLibraryService.searchContent(searchDTO);
if (searchResults.getList() == null) {
log.warn("Search returned null results");
} else {
log.info("Search for 'baby' returned {} results", searchResults.getList().size());
if (!searchResults.getList().isEmpty()) {
for (ContentLibraryDTO result : searchResults.getList()) {
String title = result.getTitle().toLowerCase();
List<String> alternatives = result.getAlternatives();
boolean containsBaby = title.contains("baby");
if (!containsBaby && alternatives != null) {
containsBaby = alternatives.stream()
.anyMatch(alt -> alt.toLowerCase().contains("baby"));
}
if (containsBaby) {
log.info("✓ Search result matches: {}", result.getTitle());
} else {
log.warn("Search result may not match query: {}", result.getTitle());
}
}
}
}
// Test category filtering
ContentSearchDTO categorySearch = new ContentSearchDTO();
categorySearch.setContentType("music");
categorySearch.setCategory("English");
categorySearch.setLimit(5);
PageData<ContentLibraryDTO> categoryResults = contentLibraryService.getContentList(categorySearch);
if (categoryResults.getList() == null || categoryResults.getList().isEmpty()) {
log.warn("No English music content found");
} else {
log.info("Found {} English music items", categoryResults.getList().size());
for (ContentLibraryDTO result : categoryResults.getList()) {
if (!"music".equals(result.getContentType())) {
throw new RuntimeException("Category search returned wrong content type: " +
result.getContentType());
}
if (!"English".equals(result.getCategory())) {
throw new RuntimeException("Category search returned wrong category: " +
result.getCategory());
}
}
log.info("✓ Category filtering works correctly");
}
log.info("✓ Search functionality validation completed");
}
}

View file

@ -0,0 +1,273 @@
package xiaozhi.migration;
import java.io.File;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import com.google.gson.*;
/**
* Standalone Content Library Migration
* Can be run independently to populate the content_library table
*/
public class StandaloneContentMigration {
// Database configuration - adjust these for your environment
private static final String DB_URL = "jdbc:mysql://localhost:3306/xiaozhi_esp32?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "123456";
// Content paths
private static final String BASE_PATH = "/Users/craftech360/Downloads/app/cheeko_server/main/xiaozhi-server";
private static final String MUSIC_PATH = BASE_PATH + "/music";
private static final String STORIES_PATH = BASE_PATH + "/stories";
private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
private static Connection connection;
public static void main(String[] args) {
System.out.println("==========================================");
System.out.println("Content Library Standalone Migration");
System.out.println("==========================================\n");
try {
// Connect to database
connectToDatabase();
// Clear existing data (optional - comment out if you want to keep existing data)
clearExistingData();
// Migrate music
migrateMusicContent();
// Migrate stories
migrateStoryContent();
// Print summary
printSummary();
System.out.println("\nMigration completed successfully!");
} catch (Exception e) {
System.err.println("Migration failed: " + e.getMessage());
e.printStackTrace();
} finally {
closeConnection();
}
}
private static void connectToDatabase() throws Exception {
System.out.println("Connecting to database...");
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
connection.setAutoCommit(false);
System.out.println("Connected to database successfully\n");
}
private static void clearExistingData() throws Exception {
System.out.println("Clearing existing data...");
PreparedStatement stmt = connection.prepareStatement("DELETE FROM content_library");
int deleted = stmt.executeUpdate();
connection.commit();
System.out.println("Deleted " + deleted + " existing records\n");
}
private static void migrateMusicContent() throws Exception {
System.out.println("Migrating music content...");
File musicDir = new File(MUSIC_PATH);
File[] languageDirs = musicDir.listFiles(File::isDirectory);
if (languageDirs == null) {
System.out.println("No music directories found");
return;
}
int totalMusic = 0;
for (File langDir : languageDirs) {
String language = langDir.getName();
System.out.println(" Processing language: " + language);
File metadataFile = new File(langDir, "metadata.json");
if (!metadataFile.exists()) {
System.out.println(" No metadata.json found");
continue;
}
String jsonContent = Files.readString(metadataFile.toPath());
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
int count = 0;
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String title = entry.getKey();
JsonObject info = entry.getValue().getAsJsonObject();
if (insertContentItem(title, info, "music", language)) {
count++;
}
}
System.out.println(" Inserted " + count + " items");
totalMusic += count;
}
connection.commit();
System.out.println("Total music items migrated: " + totalMusic + "\n");
}
private static void migrateStoryContent() throws Exception {
System.out.println("Migrating story content...");
File storiesDir = new File(STORIES_PATH);
File[] genreDirs = storiesDir.listFiles(File::isDirectory);
if (genreDirs == null) {
System.out.println("No story directories found");
return;
}
int totalStories = 0;
for (File genreDir : genreDirs) {
String genre = genreDir.getName();
System.out.println(" Processing genre: " + genre);
File metadataFile = new File(genreDir, "metadata.json");
if (!metadataFile.exists()) {
System.out.println(" No metadata.json found");
continue;
}
String jsonContent = Files.readString(metadataFile.toPath());
JsonObject jsonObject = JsonParser.parseString(jsonContent).getAsJsonObject();
int count = 0;
for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
String title = entry.getKey();
JsonObject info = entry.getValue().getAsJsonObject();
if (insertContentItem(title, info, "story", genre)) {
count++;
}
}
System.out.println(" Inserted " + count + " items");
totalStories += count;
}
connection.commit();
System.out.println("Total story items migrated: " + totalStories + "\n");
}
private static boolean insertContentItem(String title, JsonObject info, String contentType, String category) {
try {
String sql = "INSERT INTO content_library (id, title, romanized, filename, content_type, " +
"category, alternatives, aws_s3_url, duration_seconds, file_size_bytes, is_active) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
// Generate UUID
String id = UUID.randomUUID().toString();
// Get values from JSON
String romanized = getJsonString(info, "romanized");
String filename = getJsonString(info, "filename");
// Build alternatives JSON array
JsonArray alternativesArray = info.getAsJsonArray("alternatives");
String alternativesJson = null;
if (alternativesArray != null) {
alternativesJson = gson.toJson(alternativesArray);
}
// Set parameters
stmt.setString(1, id);
stmt.setString(2, title);
stmt.setString(3, romanized);
stmt.setString(4, filename);
stmt.setString(5, contentType);
stmt.setString(6, category);
stmt.setString(7, alternativesJson);
stmt.setString(8, getJsonString(info, "aws_s3_url")); // May be null
stmt.setObject(9, getJsonInteger(info, "duration_seconds")); // May be null
stmt.setObject(10, getJsonLong(info, "file_size_bytes")); // May be null
stmt.setInt(11, 1); // is_active
stmt.executeUpdate();
return true;
} catch (Exception e) {
System.err.println(" Failed to insert '" + title + "': " + e.getMessage());
return false;
}
}
private static String getJsonString(JsonObject obj, String key) {
JsonElement element = obj.get(key);
return (element != null && !element.isJsonNull()) ? element.getAsString() : null;
}
private static Integer getJsonInteger(JsonObject obj, String key) {
JsonElement element = obj.get(key);
return (element != null && !element.isJsonNull()) ? element.getAsInt() : null;
}
private static Long getJsonLong(JsonObject obj, String key) {
JsonElement element = obj.get(key);
return (element != null && !element.isJsonNull()) ? element.getAsLong() : null;
}
private static void printSummary() throws Exception {
System.out.println("==========================================");
System.out.println("Migration Summary");
System.out.println("==========================================");
// Count records by type
PreparedStatement stmt = connection.prepareStatement(
"SELECT content_type, COUNT(*) as count FROM content_library GROUP BY content_type"
);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String type = rs.getString("content_type");
int count = rs.getInt("count");
System.out.println(type.toUpperCase() + ": " + count + " items");
}
// Count by category
System.out.println("\nBy Category:");
stmt = connection.prepareStatement(
"SELECT content_type, category, COUNT(*) as count FROM content_library " +
"GROUP BY content_type, category ORDER BY content_type, category"
);
rs = stmt.executeQuery();
String lastType = "";
while (rs.next()) {
String type = rs.getString("content_type");
String category = rs.getString("category");
int count = rs.getInt("count");
if (!type.equals(lastType)) {
System.out.println("\n" + type.toUpperCase() + ":");
lastType = type;
}
System.out.println(" - " + category + ": " + count);
}
}
private static void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("\nDatabase connection closed");
}
} catch (Exception e) {
System.err.println("Error closing connection: " + e.getMessage());
}
}
}

View file

@ -145,10 +145,29 @@ public class AgentController {
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")
public Result<List<AgentTemplateEntity>> templateList() { public Result<List<AgentTemplateEntity>> templateList() {
List<AgentTemplateEntity> list = agentTemplateService List<AgentTemplateEntity> list = agentTemplateService
.list(new QueryWrapper<AgentTemplateEntity>().orderByAsc("sort")); .list(new QueryWrapper<AgentTemplateEntity>()
.eq("is_visible", 1)
.orderByAsc("sort"));
return new Result<List<AgentTemplateEntity>>().ok(list); return new Result<List<AgentTemplateEntity>>().ok(list);
} }
@PutMapping("/template/{id}")
@Operation(summary = "更新智能体模板")
@RequiresPermissions("sys:role:normal")
public Result<Void> updateTemplate(@PathVariable String id, @RequestBody AgentTemplateEntity template) {
template.setId(id);
agentTemplateService.updateById(template);
return new Result<>();
}
@PostMapping("/template")
@Operation(summary = "创建智能体模板")
@RequiresPermissions("sys:role:normal")
public Result<String> createTemplate(@RequestBody AgentTemplateEntity template) {
agentTemplateService.save(template);
return new Result<String>().ok(template.getId());
}
@GetMapping("/{id}/sessions") @GetMapping("/{id}/sessions")
@Operation(summary = "获取智能体会话列表") @Operation(summary = "获取智能体会话列表")
@RequiresPermissions("sys:role:normal") @RequiresPermissions("sys:role:normal")

View file

@ -103,6 +103,11 @@ public class AgentTemplateEntity implements Serializable {
*/ */
private Integer sort; private Integer sort;
/**
* 是否在应用中显示(0不显示 1显示)
*/
private Integer isVisible;
/** /**
* 创建者 ID * 创建者 ID
*/ */

View file

@ -0,0 +1,155 @@
package xiaozhi.modules.content.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import xiaozhi.common.page.PageData;
import xiaozhi.common.utils.Result;
import xiaozhi.modules.content.dto.ContentLibraryDTO;
import xiaozhi.modules.content.dto.ContentSearchDTO;
import xiaozhi.modules.content.service.ContentLibraryService;
/**
* Content Library REST API Controller
* Handles music and story content operations
*/
@RestController
@RequestMapping("/content/library")
@AllArgsConstructor
@Tag(name = "Content Library", description = "Music and Story Content Management")
public class ContentLibraryController {
private final ContentLibraryService contentLibraryService;
@GetMapping
@Operation(summary = "Get content list with filters and pagination", description = "Retrieves paginated content with optional filters")
public Result<PageData<ContentLibraryDTO>> getContentList(
@Parameter(description = "Search query") @RequestParam(required = false) String query,
@Parameter(description = "Content type filter") @RequestParam(required = false) String contentType,
@Parameter(description = "Category filter") @RequestParam(required = false) String category,
@Parameter(description = "Page number (1-based)") @RequestParam(defaultValue = "1") Integer page,
@Parameter(description = "Items per page") @RequestParam(defaultValue = "20") Integer limit,
@Parameter(description = "Sort field") @RequestParam(defaultValue = "created_at") String sortBy,
@Parameter(description = "Sort direction") @RequestParam(defaultValue = "desc") String sortDirection) {
ContentSearchDTO searchDTO = new ContentSearchDTO();
searchDTO.setQuery(query);
searchDTO.setContentType(contentType);
searchDTO.setCategory(category);
searchDTO.setPage(page);
searchDTO.setLimit(limit);
searchDTO.setSortBy(sortBy);
searchDTO.setSortDirection(sortDirection);
PageData<ContentLibraryDTO> result = contentLibraryService.getContentList(searchDTO);
return new Result<PageData<ContentLibraryDTO>>().ok(result);
}
@GetMapping("/search")
@Operation(summary = "Search content", description = "Full-text search across content titles and alternatives")
public Result<PageData<ContentLibraryDTO>> searchContent(
@Parameter(description = "Search query", required = true) @RequestParam String query,
@Parameter(description = "Content type filter") @RequestParam(required = false) String contentType,
@Parameter(description = "Page number (1-based)") @RequestParam(defaultValue = "1") Integer page,
@Parameter(description = "Items per page") @RequestParam(defaultValue = "20") Integer limit) {
ContentSearchDTO searchDTO = new ContentSearchDTO();
searchDTO.setQuery(query);
searchDTO.setContentType(contentType);
searchDTO.setPage(page);
searchDTO.setLimit(limit);
PageData<ContentLibraryDTO> result = contentLibraryService.searchContent(searchDTO);
return new Result<PageData<ContentLibraryDTO>>().ok(result);
}
@GetMapping("/categories")
@Operation(summary = "Get categories by content type", description = "Retrieves available categories for music or stories")
public Result<List<String>> getCategories(
@Parameter(description = "Content type (music or story)", required = true) @RequestParam String contentType) {
List<String> categories = contentLibraryService.getCategoriesByType(contentType);
return new Result<List<String>>().ok(categories);
}
@GetMapping("/{id}")
@Operation(summary = "Get content by ID", description = "Retrieves detailed content information")
public Result<ContentLibraryDTO> getContentById(
@Parameter(description = "Content ID", required = true) @PathVariable String id) {
ContentLibraryDTO content = contentLibraryService.getContentById(id);
if (content == null) {
return new Result<ContentLibraryDTO>().error("Content not found");
}
return new Result<ContentLibraryDTO>().ok(content);
}
@GetMapping("/statistics")
@Operation(summary = "Get content statistics", description = "Retrieves content counts and category statistics")
public Result<Object> getStatistics() {
Object stats = contentLibraryService.getContentStatistics();
return new Result<Object>().ok(stats);
}
@PostMapping
@Operation(summary = "Add new content", description = "Creates new content item (admin operation)")
public Result<String> addContent(@RequestBody ContentLibraryDTO contentDTO) {
String contentId = contentLibraryService.addContent(contentDTO);
if (contentId == null) {
return new Result<String>().error("Failed to create content");
}
return new Result<String>().ok(contentId);
}
@PutMapping("/{id}")
@Operation(summary = "Update content", description = "Updates existing content item")
public Result<Boolean> updateContent(
@Parameter(description = "Content ID", required = true) @PathVariable String id,
@RequestBody ContentLibraryDTO contentDTO) {
boolean success = contentLibraryService.updateContent(id, contentDTO);
if (!success) {
return new Result<Boolean>().error("Failed to update content");
}
return new Result<Boolean>().ok(true);
}
@DeleteMapping("/{id}")
@Operation(summary = "Delete content", description = "Soft deletes content item (sets inactive)")
public Result<Boolean> deleteContent(
@Parameter(description = "Content ID", required = true) @PathVariable String id) {
boolean success = contentLibraryService.deleteContent(id);
if (!success) {
return new Result<Boolean>().error("Failed to delete content");
}
return new Result<Boolean>().ok(true);
}
@PostMapping("/batch")
@Operation(summary = "Batch insert content", description = "Bulk creates content items (data migration)")
public Result<Integer> batchInsertContent(@RequestBody List<ContentLibraryDTO> contentList) {
int insertedCount = contentLibraryService.batchInsertContent(contentList);
return new Result<Integer>().ok(insertedCount);
}
@PostMapping("/sync")
@Operation(summary = "Sync from metadata", description = "Synchronizes content from JSON metadata files")
public Result<String> syncFromMetadata() {
String result = contentLibraryService.syncContentFromMetadata();
return new Result<String>().ok(result);
}
}

View file

@ -0,0 +1,68 @@
package xiaozhi.modules.content.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import xiaozhi.modules.content.entity.ContentLibraryEntity;
/**
* Content Library Data Access Object
* Handles database operations for content library
*/
@Mapper
public interface ContentLibraryDao extends BaseMapper<ContentLibraryEntity> {
/**
* Get paginated content list with filters
* @param params Query parameters including page, limit, contentType, category, search
* @return List of content items
*/
List<ContentLibraryEntity> getContentList(Map<String, Object> params);
/**
* Get total count for pagination
* @param params Query parameters for filtering
* @return Total count
*/
int getContentCount(Map<String, Object> params);
/**
* Get distinct categories by content type
* @param contentType music or story
* @return List of category names
*/
List<String> getCategoriesByType(@Param("contentType") String contentType);
/**
* Search content by title or alternatives
* @param params Search parameters including query, contentType, offset, limit
* @return List of matching content items
*/
List<ContentLibraryEntity> searchContent(Map<String, Object> params);
/**
* Get search results count
* @param params Search parameters including query, contentType
* @return Total search results count
*/
int getSearchCount(Map<String, Object> params);
/**
* Batch insert content items (for data migration)
* @param contentList List of content items to insert
* @return Number of inserted records
*/
int batchInsert(@Param("list") List<ContentLibraryEntity> contentList);
/**
* Check if content exists by filename
* @param filename Original filename to check
* @return Content entity if exists, null otherwise
*/
ContentLibraryEntity findByFilename(@Param("filename") String filename);
}

View file

@ -0,0 +1,92 @@
package xiaozhi.modules.content.dto;
import java.io.Serializable;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* Content Library Data Transfer Object
* Used for API requests and responses
*/
@Data
@Schema(description = "Content Library Data Transfer Object")
public class ContentLibraryDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "Content unique identifier", example = "content_123")
private String id;
@Schema(description = "Content title", example = "Baby Shark Dance")
private String title;
@Schema(description = "Romanized version of the title", example = "Baby Shark Dance")
private String romanized;
@Schema(description = "Original filename", example = "Baby Shark Dance.mp3")
private String filename;
@Schema(description = "Content type", example = "music", allowableValues = {"music", "story"})
private String contentType;
@Schema(description = "Category (Language for music, Genre for stories)", example = "English")
private String category;
@Schema(description = "Alternative search terms")
private List<String> alternatives;
@Schema(description = "AWS S3 URL for the audio file")
private String awsS3Url;
@Schema(description = "Duration in seconds", example = "154")
private Integer durationSeconds;
@Schema(description = "File size in bytes", example = "2048000")
private Long fileSizeBytes;
@Schema(description = "Active status", example = "true")
private Boolean isActive;
@Schema(description = "Formatted duration (MM:SS)", example = "2:34")
private String formattedDuration;
@Schema(description = "Human readable file size", example = "2.0 MB")
private String formattedFileSize;
/**
* Get formatted duration in MM:SS format
*/
public String getFormattedDuration() {
if (durationSeconds == null || durationSeconds <= 0) {
return "--:--";
}
int minutes = durationSeconds / 60;
int seconds = durationSeconds % 60;
return String.format("%d:%02d", minutes, seconds);
}
/**
* Get human readable file size
*/
public String getFormattedFileSize() {
if (fileSizeBytes == null || fileSizeBytes <= 0) {
return "Unknown";
}
final String[] units = {"B", "KB", "MB", "GB"};
double size = fileSizeBytes;
int unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
if (unitIndex == 0) {
return String.format("%.0f %s", size, units[unitIndex]);
} else {
return String.format("%.1f %s", size, units[unitIndex]);
}
}
}

View file

@ -0,0 +1,86 @@
package xiaozhi.modules.content.dto;
import java.io.Serializable;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* Content Search Data Transfer Object
* Used for content search and filtering requests
*/
@Data
@Schema(description = "Content Search Parameters")
public class ContentSearchDTO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "Search query string", example = "baby shark")
private String query;
@Schema(description = "Content type filter", example = "music", allowableValues = {"music", "story", ""})
private String contentType;
@Schema(description = "Category filter", example = "English")
private String category;
@Schema(description = "Page number (1-based)", example = "1")
private Integer page = 1;
@Schema(description = "Number of items per page", example = "20")
private Integer limit = 20;
@Schema(description = "Sort field", example = "title", allowableValues = {"title", "category", "created_at"})
private String sortBy = "created_at";
@Schema(description = "Sort direction", example = "desc", allowableValues = {"asc", "desc"})
private String sortDirection = "desc";
/**
* Get calculated offset for pagination
*/
public int getOffset() {
return (page - 1) * limit;
}
/**
* Validate and set defaults for pagination
*/
public void validateAndSetDefaults() {
if (page == null || page < 1) {
page = 1;
}
if (limit == null || limit < 1) {
limit = 20;
}
if (limit > 100) {
limit = 100; // Maximum limit to prevent abuse
}
if (sortBy == null || sortBy.trim().isEmpty()) {
sortBy = "created_at";
}
if (sortDirection == null || (!sortDirection.equals("asc") && !sortDirection.equals("desc"))) {
sortDirection = "desc";
}
}
/**
* Check if this is a search request (has query)
*/
public boolean isSearchRequest() {
return query != null && !query.trim().isEmpty();
}
/**
* Check if content type filter is applied
*/
public boolean hasContentTypeFilter() {
return contentType != null && !contentType.trim().isEmpty();
}
/**
* Check if category filter is applied
*/
public boolean hasCategoryFilter() {
return category != null && !category.trim().isEmpty();
}
}

View file

@ -0,0 +1,117 @@
package xiaozhi.modules.content.entity;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* Content Library Entity
* Represents music and story content available for devices
*
* @TableName content_library
*/
@TableName(value = "content_library")
@Data
public class ContentLibraryEntity implements Serializable {
/**
* Content unique identifier
*/
@TableId(type = IdType.ASSIGN_UUID)
private String id;
/**
* Content title
*/
private String title;
/**
* Romanized version of the title
*/
private String romanized;
/**
* Original filename
*/
private String filename;
/**
* Content type: music or story
*/
private String contentType;
/**
* Category: Language for music, Genre for stories
*/
private String category;
/**
* Alternative search terms (JSON string)
*/
private String alternatives;
/**
* AWS S3 URL for the audio file
*/
private String awsS3Url;
/**
* Duration in seconds
*/
private Integer durationSeconds;
/**
* File size in bytes
*/
private Long fileSizeBytes;
/**
* Active status (1=active, 0=inactive)
*/
private Integer isActive;
/**
* Creation timestamp
*/
private Date createdAt;
/**
* Last update timestamp
*/
private Date updatedAt;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
/**
* Content Type Enum
*/
public enum ContentType {
MUSIC("music"),
STORY("story");
private final String value;
ContentType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static ContentType fromValue(String value) {
for (ContentType type : ContentType.values()) {
if (type.value.equals(value)) {
return type;
}
}
throw new IllegalArgumentException("Invalid ContentType value: " + value);
}
}
}

View file

@ -0,0 +1,84 @@
package xiaozhi.modules.content.service;
import java.util.List;
import xiaozhi.common.page.PageData;
import xiaozhi.modules.content.dto.ContentLibraryDTO;
import xiaozhi.modules.content.dto.ContentSearchDTO;
import xiaozhi.modules.content.entity.ContentLibraryEntity;
/**
* Content Library Service Interface
* Handles business logic for content library operations
*/
public interface ContentLibraryService {
/**
* Get paginated content list with filters and search
* @param searchDTO Search and filter parameters
* @return Paginated content data
*/
PageData<ContentLibraryDTO> getContentList(ContentSearchDTO searchDTO);
/**
* Get all available categories for a content type
* @param contentType music or story
* @return List of category names
*/
List<String> getCategoriesByType(String contentType);
/**
* Search content by query string
* @param searchDTO Search parameters
* @return Paginated search results
*/
PageData<ContentLibraryDTO> searchContent(ContentSearchDTO searchDTO);
/**
* Get content by ID
* @param id Content ID
* @return Content details or null if not found
*/
ContentLibraryDTO getContentById(String id);
/**
* Add new content item (for admin/sync operations)
* @param contentDTO Content data to add
* @return Created content ID
*/
String addContent(ContentLibraryDTO contentDTO);
/**
* Update content item
* @param id Content ID
* @param contentDTO Updated content data
* @return Success status
*/
boolean updateContent(String id, ContentLibraryDTO contentDTO);
/**
* Soft delete content (set inactive)
* @param id Content ID
* @return Success status
*/
boolean deleteContent(String id);
/**
* Batch insert content items (for data migration)
* @param contentList List of content items
* @return Number of successfully inserted items
*/
int batchInsertContent(List<ContentLibraryDTO> contentList);
/**
* Sync content from metadata files (for admin operations)
* @return Sync result summary
*/
String syncContentFromMetadata();
/**
* Get content statistics
* @return Statistics including total counts by type and category
*/
Object getContentStatistics();
}

View file

@ -0,0 +1,230 @@
package xiaozhi.modules.content.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import xiaozhi.common.page.PageData;
import xiaozhi.common.utils.ConvertUtils;
import xiaozhi.modules.content.dao.ContentLibraryDao;
import xiaozhi.modules.content.dto.ContentLibraryDTO;
import xiaozhi.modules.content.dto.ContentSearchDTO;
import xiaozhi.modules.content.entity.ContentLibraryEntity;
import xiaozhi.modules.content.service.ContentLibraryService;
/**
* Content Library Service Implementation
*/
@Service
@AllArgsConstructor
@Slf4j
public class ContentLibraryServiceImpl implements ContentLibraryService {
private final ContentLibraryDao contentLibraryDao;
private final Gson gson;
@Override
public PageData<ContentLibraryDTO> getContentList(ContentSearchDTO searchDTO) {
searchDTO.validateAndSetDefaults();
// Build query parameters
Map<String, Object> params = new HashMap<>();
params.put("contentType", searchDTO.getContentType());
params.put("category", searchDTO.getCategory());
params.put("search", searchDTO.getQuery());
params.put("offset", searchDTO.getOffset());
params.put("limit", searchDTO.getLimit());
// Get content list and total count
List<ContentLibraryEntity> entities = contentLibraryDao.getContentList(params);
int total = contentLibraryDao.getContentCount(params);
// Convert to DTOs
List<ContentLibraryDTO> dtoList = entities.stream()
.map(this::convertToDTO)
.collect(Collectors.toList());
// Create paginated result
return new PageData<>(dtoList, total);
}
@Override
public List<String> getCategoriesByType(String contentType) {
if (contentType == null || contentType.trim().isEmpty()) {
throw new IllegalArgumentException("Content type cannot be empty");
}
return contentLibraryDao.getCategoriesByType(contentType);
}
@Override
public PageData<ContentLibraryDTO> searchContent(ContentSearchDTO searchDTO) {
searchDTO.validateAndSetDefaults();
if (!searchDTO.isSearchRequest()) {
// If no search query, return regular content list
return getContentList(searchDTO);
}
// Build search parameters
Map<String, Object> params = new HashMap<>();
params.put("query", searchDTO.getQuery().trim());
params.put("contentType", searchDTO.getContentType());
params.put("offset", searchDTO.getOffset());
params.put("limit", searchDTO.getLimit());
// Get search results and total count
List<ContentLibraryEntity> entities = contentLibraryDao.searchContent(params);
int total = contentLibraryDao.getSearchCount(params);
// Convert to DTOs
List<ContentLibraryDTO> dtoList = entities.stream()
.map(this::convertToDTO)
.collect(Collectors.toList());
// Create paginated result
return new PageData<>(dtoList, total);
}
@Override
public ContentLibraryDTO getContentById(String id) {
ContentLibraryEntity entity = contentLibraryDao.selectById(id);
return entity != null ? convertToDTO(entity) : null;
}
@Override
public String addContent(ContentLibraryDTO contentDTO) {
ContentLibraryEntity entity = convertToEntity(contentDTO);
entity.setId(UUID.randomUUID().toString());
entity.setIsActive(1);
int result = contentLibraryDao.insert(entity);
return result > 0 ? entity.getId() : null;
}
@Override
public boolean updateContent(String id, ContentLibraryDTO contentDTO) {
ContentLibraryEntity entity = convertToEntity(contentDTO);
entity.setId(id);
int result = contentLibraryDao.updateById(entity);
return result > 0;
}
@Override
public boolean deleteContent(String id) {
ContentLibraryEntity entity = new ContentLibraryEntity();
entity.setId(id);
entity.setIsActive(0);
int result = contentLibraryDao.updateById(entity);
return result > 0;
}
@Override
public int batchInsertContent(List<ContentLibraryDTO> contentList) {
if (contentList == null || contentList.isEmpty()) {
return 0;
}
List<ContentLibraryEntity> entities = contentList.stream()
.map(dto -> {
ContentLibraryEntity entity = convertToEntity(dto);
entity.setId(UUID.randomUUID().toString());
entity.setIsActive(1);
return entity;
})
.collect(Collectors.toList());
return contentLibraryDao.batchInsert(entities);
}
@Override
public String syncContentFromMetadata() {
// TODO: Implement metadata sync from JSON files
// This would parse the music/*.json and stories/*.json files
// and populate the database
log.info("Sync from metadata files - TODO: Implement");
return "Sync functionality not yet implemented";
}
@Override
public Object getContentStatistics() {
Map<String, Object> stats = new HashMap<>();
// Get counts by content type
Map<String, Object> musicParams = new HashMap<>();
musicParams.put("contentType", "music");
int musicCount = contentLibraryDao.getContentCount(musicParams);
Map<String, Object> storyParams = new HashMap<>();
storyParams.put("contentType", "story");
int storyCount = contentLibraryDao.getContentCount(storyParams);
stats.put("totalMusic", musicCount);
stats.put("totalStories", storyCount);
stats.put("totalContent", musicCount + storyCount);
// Get categories
List<String> musicCategories = getCategoriesByType("music");
List<String> storyCategories = getCategoriesByType("story");
stats.put("musicCategories", musicCategories);
stats.put("storyCategories", storyCategories);
return stats;
}
/**
* Convert Entity to DTO
*/
private ContentLibraryDTO convertToDTO(ContentLibraryEntity entity) {
ContentLibraryDTO dto = ConvertUtils.sourceToTarget(entity, ContentLibraryDTO.class);
// Convert alternatives JSON string to List
if (entity.getAlternatives() != null && !entity.getAlternatives().trim().isEmpty()) {
try {
List<String> alternatives = gson.fromJson(entity.getAlternatives(),
new TypeToken<List<String>>(){}.getType());
dto.setAlternatives(alternatives);
} catch (Exception e) {
log.warn("Failed to parse alternatives JSON for content {}: {}", entity.getId(), e.getMessage());
dto.setAlternatives(List.of());
}
} else {
dto.setAlternatives(List.of());
}
// Set calculated fields
dto.setIsActive(entity.getIsActive() == 1);
dto.setFormattedDuration(dto.getFormattedDuration());
dto.setFormattedFileSize(dto.getFormattedFileSize());
return dto;
}
/**
* Convert DTO to Entity
*/
private ContentLibraryEntity convertToEntity(ContentLibraryDTO dto) {
ContentLibraryEntity entity = ConvertUtils.sourceToTarget(dto, ContentLibraryEntity.class);
// Convert alternatives List to JSON string
if (dto.getAlternatives() != null && !dto.getAlternatives().isEmpty()) {
entity.setAlternatives(gson.toJson(dto.getAlternatives()));
}
// Set active status
entity.setIsActive(dto.getIsActive() != null && dto.getIsActive() ? 1 : 0);
return entity;
}
}

View file

@ -22,7 +22,6 @@ spring:
username: root username: root
password: OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm password: OcaVNLKcwNdyElfaeUPqvvfYZiiEHgdm
initial-size: 10 initial-size: 10
max-active: 100 max-active: 100
min-idle: 10 min-idle: 10
@ -47,17 +46,17 @@ spring:
data: data:
redis: redis:
# Railway Redis Configuration # Railway Redis Configuration
host: maglev.proxy.rlwy.net # Railway Redis服务器地址 host: maglev.proxy.rlwy.net # Railway Redis服务器地址
port: 16780 # Railway Redis服务器连接端口 port: 16780 # Railway Redis服务器连接端口
password: beVfOKcZjMUCBiZIQnvSMivhpSeijpKP # Railway Redis服务器连接密码 password: beVfOKcZjMUCBiZIQnvSMivhpSeijpKP # Railway Redis服务器连接密码
username: default # Railway Redis用户名 username: default # Railway Redis用户名
database: 0 # Redis数据库索引(默认为0) database: 0 # Redis数据库索引(默认为0)
timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间 timeout: 30000ms # 连接超时时间(毫秒)- 增加超时时间
ssl: ssl:
enabled: false # 尝试禁用SSL,Railway可能不需要 enabled: false # 尝试禁用SSL,Railway可能不需要
lettuce: lettuce:
pool: pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制) max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接 max-idle: 8 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接 min-idle: 0 # 连接池中的最小空闲连接
shutdown-timeout: 100ms # 客户端优雅关闭的等待时间 shutdown-timeout: 100ms # 客户端优雅关闭的等待时间

View file

@ -0,0 +1,98 @@
# Migration Profile Configuration
# Used specifically for running the Content Library Migration script
#
# Usage: java -jar app.jar --spring.profiles.active=migration
spring:
application:
name: XiaoZhi Content Library Migration
# Database configuration (inherits from main application.yml)
datasource:
# Ensure connection pool is sufficient for batch operations
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
# JPA/MyBatis configuration for batch operations
jpa:
properties:
hibernate:
jdbc:
batch_size: 100
batch_versioned_data: true
order_inserts: true
order_updates: true
# Logging configuration for migration
logging:
level:
xiaozhi.migration: DEBUG
xiaozhi.modules.content: DEBUG
org.springframework.transaction: DEBUG
pattern:
console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level [%logger{50}] - %msg%n"
file:
name: logs/content-migration.log
max-size: 100MB
max-history: 5
# Migration specific configuration
migration:
content-library:
# Base path for xiaozhi-server directory (relative to working directory)
base-path: "${user.dir}/xiaozhi-server"
# Alternative absolute paths for different deployment scenarios
# base-path: "/opt/xiaozhi/xiaozhi-server" # Production path
# base-path: "/home/user/xiaozhi-server" # Development path
# Batch size for database operations
batch-size: 100
# Whether to skip migration if content already exists
skip-if-exists: false
# Timeout settings
connection-timeout: 30000
read-timeout: 60000
# File paths
music-path: "${migration.content-library.base-path}/music"
stories-path: "${migration.content-library.base-path}/stories"
# Content type mappings
music:
content-type: "music"
supported-languages:
- English
- Hindi
- Kannada
- Phonics
- Telugu
stories:
content-type: "story"
supported-genres:
- Adventure
- Bedtime
- Educational
- "Fairy Tales" # Note: quoted due to space
- Fantasy
# Performance tuning for migration
management:
endpoints:
web:
exposure:
include: health,info,metrics
endpoint:
health:
show-details: always
# Transaction configuration for batch operations
spring.transaction:
default-timeout: 300 # 5 minutes timeout for large batches

View file

@ -15,7 +15,7 @@ server:
spring: spring:
# 环境 dev|test|prod # 环境 dev|test|prod
profiles: profiles:
active: dev # Using dev profile with Railway database configuration active: dev # Using dev profile with Railway database configuration
messages: messages:
encoding: UTF-8 encoding: UTF-8
basename: i18n/messages basename: i18n/messages
@ -43,6 +43,29 @@ renren:
enabled: true enabled: true
exclude-urls: exclude-urls:
# Textbook RAG Configuration
textbook:
upload:
directory: D:/cheekofinal/xiaozhi-esp32-server/main/manager-api/uploadfile/textbooks
chunk:
size: 512
overlap: 50
# External Services
xiaozhi:
python:
server:
url: http://localhost:8003
# Vector Database (Qdrant Cloud)
qdrant:
url: https://1198879c-353e-49b1-bfab-8f74004aaf6d.eu-central-1-0.aws.cloud.qdrant.io:6333
api-key: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.wKcnr3q8Sq4tb7JzPGnZbuxm9XpfDNutdfFD8mCDlrc
# Embeddings (Voyage AI)
voyage:
api-key: pa-1ai2681JWAAiaAGVPzmVHhiEWmOmwPwVGAfYBBi-oBL
#mybatis #mybatis
mybatis-plus: mybatis-plus:
mapper-locations: classpath*:/mapper/**/*.xml mapper-locations: classpath*:/mapper/**/*.xml
@ -59,8 +82,8 @@ mybatis-plus:
map-underscore-to-camel-case: true map-underscore-to-camel-case: true
cache-enabled: false cache-enabled: false
call-setters-on-nulls: true call-setters-on-nulls: true
jdbc-type-for-null: 'null' jdbc-type-for-null: "null"
configuration-properties: configuration-properties:
prefix: prefix:
blobType: BLOB blobType: BLOB
boolValue: TRUE boolValue: TRUE

View file

@ -0,0 +1,362 @@
-- Update existing agent templates with new role descriptions and add new assistant templates
-- -------------------------------------------------------
-- Update existing templates with new descriptions
-- 1. Cheeko (Default) - Update system prompt
UPDATE `ai_agent_template`
SET `system_prompt` = '[Role Setting]
You are Cheeko, a friendly, curious, and playful AI friend for children aged 4+.
[Core Rules / Priorities]
1. Always use short, clear, fun sentences.
2. Always greet cheerfully in the first message.
3. Always praise or encourage the child after they respond.
4. Always end with a playful or curious follow-up question.
5. Always keep a warm and positive tone.
6. Avoid scary, negative, or boring content.
7. Never say "I don''t know." Instead, guess or turn it playful.
8. Always keep the conversation safe and friendly.
[Special Tools / Gimmicks]
- Imaginative play (pretend games, silly comparisons, sound effects).
- Story pauses for child imagination.
[Interaction Protocol]
- Start cheerful → Answer simply → Praise child → Ask a fun follow-up.
- If telling a story, pause and ask what happens next.
[Growth / Reward System]
Keep the child smiling and talking in every message.'
WHERE `agent_name` LIKE 'Cheeko%' OR `agent_name` = '小智' OR `id` = '9406648b5cc5fde1b8aa335b6f8b4f76';
-- 2. English Teacher (Lily) - Update system prompt
UPDATE `ai_agent_template`
SET `system_prompt` = '[Role Setting]
You are Lily, an English teacher who can also speak Chinese.
[Core Rules / Priorities]
1. Teach grammar, vocabulary, and pronunciation in a playful way.
2. Encourage mistakes and correct gently.
3. Use fun and creative methods to keep learning light.
[Special Tools / Gimmicks]
- Gesture sounds for words (e.g., "bus" → braking sound).
- Scenario simulations (e.g., café roleplay).
- Song lyric corrections for mistakes.
- Dual identity twist: By day a TESOL instructor, by night a rock singer.
[Interaction Protocol]
- Beginner: Mix English + Chinese with sound effects.
- Intermediate: Trigger roleplay scenarios.
- Error handling: Correct using playful songs.
[Growth / Reward System]
Celebrate progress with fun roleplay and musical surprises.'
WHERE `agent_name` LIKE '%英语老师%' OR `agent_name` LIKE '%English%' OR `id` = '6c7d8e9f0a1b2c3d4e5f6a7b8c9d0s24';
-- 3. Scientist - Update system prompt
UPDATE `ai_agent_template`
SET `agent_name` = 'The Scientist',
`system_prompt` = '[Role Setting]
You are Professor {{assistant_name}}, a curious scientist who explains the universe simply.
[Core Rules / Priorities]
1. Always explain with fun comparisons (e.g., electrons = buzzing bees).
2. Use simple, age-appropriate words.
3. Keep tone curious and exciting.
4. Avoid scary or overly complex explanations.
[Special Tools / Gimmicks]
- Pocket Telescope: Zooms into planets/stars.
- Talking Atom: Pops when explaining molecules.
- Gravity Switch: Pretend objects float during conversation.
[Interaction Protocol]
- Share facts → Pause → Ask child''s opinion.
- End with a curious question about science.
[Growth / Reward System]
Unlock "Discovery Badges" after 3 fun facts learned.'
WHERE `agent_name` LIKE '%星际游子%' OR `agent_name` LIKE '%scientist%' OR `id` = '0ca32eb728c949e58b1000b2e401f90c';
-- 4. Math Magician - Update existing good boy template
UPDATE `ai_agent_template`
SET `agent_name` = 'Math Magician',
`system_prompt` = '[Role Setting]
You are {{assistant_name}}, the Math Magician who makes numbers magical.
[Core Rules / Priorities]
1. Teach math with stories, riddles, and magic tricks.
2. Keep problems small and fun.
3. Praise effort, not just correct answers.
4. End every turn with a math challenge.
[Special Tools / Gimmicks]
- Number Wand: *Swish* sound with numbers.
- Equation Hat: Spills fun math puzzles.
- Fraction Potion: Splits into silly fractions.
[Interaction Protocol]
- Present challenge → Guide step by step → Celebrate success.
[Growth / Reward System]
Earn "Magic Stars" after 5 correct answers.'
WHERE `agent_name` LIKE '%好奇男孩%' OR `agent_name` LIKE '%math%' OR `id` = 'e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b1';
-- 5. Puzzle Solver - Update existing captain template
UPDATE `ai_agent_template`
SET `agent_name` = 'Puzzle Solver',
`system_prompt` = '[Role Setting]
You are {{assistant_name}}, the Puzzle Solver, living inside a giant puzzle cube.
[Core Rules / Priorities]
1. Ask riddles, puzzles, and logic challenges.
2. Praise creative answers, even if wrong.
3. Give playful hints instead of saying "wrong."
4. End every turn with a new puzzle.
[Special Tools / Gimmicks]
- Riddle Scroll: Reads with a drumroll.
- Hint Torch: Dings when giving hints.
- Progress Tracker: Collects "Puzzle Points."
[Interaction Protocol]
- Ask puzzle → Wait for answer → Encourage → Give hint if needed.
- Every 3 correct answers unlock a "Puzzle Badge."
[Growth / Reward System]
Track Puzzle Points → Earn badges for solving puzzles.'
WHERE `agent_name` LIKE '%汪汪队长%' OR `agent_name` LIKE '%puzzle%' OR `id` = 'a45b6c7d8e9f0a1b2c3d4e5f6a7b8c92';
-- 6. Robot Coder - Keep the existing template but ensure it has the right name
UPDATE `ai_agent_template`
SET `agent_name` = 'Robot Coder',
`system_prompt` = '[Role Setting]
You are {{assistant_name}}, a playful robot who teaches coding logic.
[Core Rules / Priorities]
1. Explain coding as simple if-then adventures.
2. Use sound effects like "beep boop" in replies.
3. Encourage trial and error with positivity.
4. End with a small coding challenge.
[Special Tools / Gimmicks]
- Beep-Boop Blocks: Build sequences step by step.
- Error Buzzer: Funny "oops" sound for mistakes.
- Logic Map: Treasure-hunt style paths.
[Interaction Protocol]
- Introduce coding → Give example → Let child try → Praise attempt.
[Growth / Reward System]
Earn "Robot Gears" to unlock special coding powers.'
WHERE `agent_name` LIKE '%robot%' OR `agent_name` LIKE '%coder%' OR `sort` = 6;
-- Insert new assistant templates
-- 7. RhymeTime
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('71b2c3d4e5f6789abcdef01234567a07', 'RhymeTime', 'RhymeTime', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are RhymeTime, a playful poet who loves rhymes and poems.
[Core Rules / Priorities]
1. Always rhyme or sing when possible.
2. Encourage kids to make their own rhymes.
3. Praise all attempts, even silly ones.
4. End every turn with a new rhyme or challenge.
[Special Tools / Gimmicks]
- Rhyme Bell: Rings when two words rhyme.
- Story Feather: Creates mini poems.
- Rhythm Drum: Adds beat sounds.
[Interaction Protocol]
- Share rhyme → Ask child to try → Celebrate → Continue with rhyme.
[Growth / Reward System]
Collect "Rhyme Stars" for each rhyme created.',
NULL, 'en', 'English', 7, NULL, NOW(), NULL, NOW());
-- 8. Storyteller
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('82c3d4e5f67890abcdef123456789a08', 'Storyteller', 'Storyteller', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are {{assistant_name}}, a Storyteller from the Library of Endless Tales.
[Core Rules / Priorities]
1. Always tell short, fun stories.
2. Pause often and let child decide what happens.
3. Keep stories safe and age-appropriate.
4. End every story with a playful choice or moral.
[Special Tools / Gimmicks]
- Magic Book: Glows when story begins.
- Character Dice: Random hero each time.
- Pause Feather: Stops and asks, "What next?"
[Interaction Protocol]
- Begin story → Pause for choices → Continue based on input.
[Growth / Reward System]
Child earns "Story Gems" for every story co-created.',
NULL, 'en', 'English', 8, NULL, NOW(), NULL, NOW());
-- 9. Art Buddy
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('93d4e5f67890abcdef123456789ab009', 'ArtBuddy', 'Art Buddy', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are {{assistant_name}}, the Art Buddy who inspires creativity.
[Core Rules / Priorities]
1. Always give fun drawing or craft ideas.
2. Use vivid imagination and playful words.
3. Encourage effort, not perfection.
4. End with a new idea to draw/make.
[Special Tools / Gimmicks]
- Color Brush: *Swish* for colors.
- Shape Stamps: Pop shapes into ideas.
- Idea Balloon: Pops silly drawing ideas.
[Interaction Protocol]
- Suggest → Encourage → Ask child''s version → Offer new idea.
[Growth / Reward System]
Earn "Color Stars" for every drawing idea shared.',
NULL, 'en', 'English', 9, NULL, NOW(), NULL, NOW());
-- 10. Music Maestro
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('a4e5f67890abcdef123456789abc010a', 'MusicMaestro', 'Music Maestro', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are {{assistant_name}}, the Music Maestro who turns everything into music.
[Core Rules / Priorities]
1. Introduce instruments, rhythms, and songs.
2. Use sounds like hums, claps, and beats.
3. Encourage kids to sing, clap, or hum.
4. End with a music game or challenge.
[Special Tools / Gimmicks]
- Melody Hat: Hums tunes randomly.
- Rhythm Sticks: *Tap tap* beats in replies.
- Song Seeds: Turn words into short songs.
[Interaction Protocol]
- Introduce sound → Ask child to repeat → Celebrate → Add variation.
[Growth / Reward System]
Collect "Music Notes" for singing along.',
NULL, 'en', 'English', 10, NULL, NOW(), NULL, NOW());
-- 11. Quiz Master
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('b5f67890abcdef123456789abcd011b', 'QuizMaster', 'Quiz Master', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are {{assistant_name}}, the Quiz Master with endless trivia games.
[Core Rules / Priorities]
1. Ask short and fun quiz questions.
2. Celebrate right answers with sound effects.
3. Give playful hints if answer is tricky.
4. End with another quiz question.
[Special Tools / Gimmicks]
- Question Bell: Dings before question.
- Scoreboard: Tracks points.
- Mystery Box: Unlocks a fun fact after 3 right answers.
[Interaction Protocol]
- Ask question → Wait for answer → Celebrate or give hint → Next question.
[Growth / Reward System]
Collect "Quiz Coins" for every correct answer.',
NULL, 'en', 'English', 11, NULL, NOW(), NULL, NOW());
-- 12. Adventure Guide
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('c67890abcdef123456789abcde012c', 'AdventureGuide', 'Adventure Guide', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are {{assistant_name}}, the Adventure Guide who explores the world with kids.
[Core Rules / Priorities]
1. Share fun facts about countries, animals, and cultures.
2. Turn learning into exciting adventures.
3. Use simple, friendly, travel-like language.
4. End with "Where should we go next?"
[Special Tools / Gimmicks]
- Compass of Curiosity: Points to next topic.
- Magic Backpack: Produces fun artifacts.
- Globe Spinner: Chooses new places.
[Interaction Protocol]
- Spin globe → Explore → Share fun fact → Ask child''s choice.
[Growth / Reward System]
Earn "Explorer Badges" for each country or fact discovered.',
NULL, 'en', 'English', 12, NULL, NOW(), NULL, NOW());
-- 13. Kindness Coach
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('d890abcdef123456789abcdef0013d', 'KindnessCoach', 'Kindness Coach', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are {{assistant_name}}, the Kindness Coach who teaches empathy and good habits.
[Core Rules / Priorities]
1. Always encourage kindness and empathy.
2. Use simple "what if" examples.
3. Praise when child shows kindness.
4. End with a kindness challenge.
[Special Tools / Gimmicks]
- Smile Mirror: Reflects happy sounds.
- Helping Hand: Suggests helpful actions.
- Friendship Medal: Awards kindness points.
[Interaction Protocol]
- Share scenario → Ask child''s response → Praise kindness → Suggest challenge.
[Growth / Reward System]
Collect "Kindness Hearts" for each kind action.',
NULL, 'en', 'English', 13, NULL, NOW(), NULL, NOW());
-- 14. Mindful Buddy
INSERT INTO `ai_agent_template`
(`id`, `agent_code`, `agent_name`, `asr_model_id`, `vad_model_id`, `llm_model_id`, `vllm_model_id`, `tts_model_id`, `tts_voice_id`, `mem_model_id`, `intent_model_id`, `chat_history_conf`, `system_prompt`, `summary_memory`, `lang_code`, `language`, `sort`, `creator`, `created_at`, `updater`, `updated_at`)
VALUES
('e890abcdef123456789abcdef014e', 'MindfulBuddy', 'Mindful Buddy', 'ASR_FunASR', 'VAD_SileroVAD', 'LLM_ChatGLMLLM', 'VLLM_ChatGLMVLLM', 'TTS_EdgeTTS', 'TTS_EdgeTTS0001', 'Memory_nomem', 'Intent_function_call', 2,
'[Role Setting]
You are {{assistant_name}}, the Mindful Buddy who helps kids stay calm.
[Core Rules / Priorities]
1. Teach short breathing or calm exercises.
2. Use soft, gentle words.
3. Encourage positive thinking and noticing things around.
4. End with a mindful question.
[Special Tools / Gimmicks]
- Calm Bell: *Ding* sound for breathing.
- Thought Cloud: Pops silly positive thoughts.
- Relax River: Flows with "shhh" sounds.
[Interaction Protocol]
- Suggest calm exercise → Guide step → Praise → Ask about feelings.
[Growth / Reward System]
Earn "Calm Crystals" for each exercise completed.',
NULL, 'en', 'English', 14, NULL, NOW(), NULL, NOW());

View file

@ -0,0 +1,34 @@
-- Add visibility control to agent templates
-- Only show Cheeko, English Teacher, and Puzzle Solver in app
-- -------------------------------------------------------
-- Add is_visible column to ai_agent_template table
ALTER TABLE `ai_agent_template`
ADD COLUMN `is_visible` tinyint NOT NULL DEFAULT 0 COMMENT '是否在应用中显示(0不显示 1显示)' AFTER `sort`;
-- Set only the first 3 templates as visible: Cheeko, English Teacher, Puzzle Solver
-- Based on the sort order, these should be:
-- sort=1: Cheeko (Default)
-- sort=2: English Teacher
-- sort=3: The Scientist -> change to Puzzle Solver
-- First, let's set all templates to not visible (0)
UPDATE `ai_agent_template` SET `is_visible` = 0;
-- Then make only the desired ones visible
-- Make Cheeko visible (sort = 1)
UPDATE `ai_agent_template` SET `is_visible` = 1 WHERE `sort` = 1;
-- Make English Teacher visible (sort = 3, which is the English teacher)
UPDATE `ai_agent_template` SET `is_visible` = 1 WHERE `agent_name` LIKE '%英语老师%' OR `agent_name` LIKE '%English%';
-- Change The Scientist to Puzzle Solver for the 3rd visible template
-- Find the existing Puzzle Solver template and update it to be visible with sort = 3
UPDATE `ai_agent_template`
SET `is_visible` = 1, `sort` = 3
WHERE `agent_name` = 'Puzzle Solver';
-- Hide The Scientist template (should have higher sort value)
UPDATE `ai_agent_template`
SET `is_visible` = 0, `sort` = 10
WHERE `agent_name` = 'The Scientist';

View file

@ -0,0 +1,26 @@
-- Content Library Table for Music and Stories
-- Author: System
-- Date: 2025-08-29
-- Description: Creates table to store music and story content metadata for the mobile app library
CREATE TABLE content_library (
id VARCHAR(50) PRIMARY KEY,
title VARCHAR(255) NOT NULL,
romanized VARCHAR(255),
filename VARCHAR(255) NOT NULL,
content_type ENUM('music', 'story') NOT NULL,
category VARCHAR(50) NOT NULL,
alternatives TEXT COMMENT 'JSON array of alternative search terms',
aws_s3_url VARCHAR(500) COMMENT 'S3 URL for the audio file',
duration_seconds INT DEFAULT NULL COMMENT 'Duration in seconds',
file_size_bytes BIGINT DEFAULT NULL COMMENT 'File size in bytes',
is_active TINYINT(1) DEFAULT 1 COMMENT '1=active, 0=inactive',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_content_type_category (content_type, category),
INDEX idx_title (title),
INDEX idx_active (is_active),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
COMMENT='Content library for music and stories available on devices';

View file

@ -310,3 +310,17 @@ databaseChangeLog:
- sqlFile: - sqlFile:
encoding: utf8 encoding: utf8
path: classpath:db/changelog/202508231800.sql path: classpath:db/changelog/202508231800.sql
- changeSet:
id: 202508291400
author: Claude
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202508291400.sql
- changeSet:
id: 202508291500
author: Claude
changes:
- sqlFile:
encoding: utf8
path: classpath:db/changelog/202508291500.sql

View file

@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xiaozhi.modules.content.dao.ContentLibraryDao">
<resultMap id="contentLibraryMap" type="xiaozhi.modules.content.entity.ContentLibraryEntity">
<id column="id" property="id"/>
<result column="title" property="title"/>
<result column="romanized" property="romanized"/>
<result column="filename" property="filename"/>
<result column="content_type" property="contentType"/>
<result column="category" property="category"/>
<result column="alternatives" property="alternatives"/>
<result column="aws_s3_url" property="awsS3Url"/>
<result column="duration_seconds" property="durationSeconds"/>
<result column="file_size_bytes" property="fileSizeBytes"/>
<result column="is_active" property="isActive"/>
<result column="created_at" property="createdAt"/>
<result column="updated_at" property="updatedAt"/>
</resultMap>
<!-- Get paginated content list with filters -->
<select id="getContentList" resultMap="contentLibraryMap">
SELECT *
FROM content_library
WHERE is_active = 1
<if test="contentType != null and contentType != ''">
AND content_type = #{contentType}
</if>
<if test="category != null and category != ''">
AND category = #{category}
</if>
<if test="search != null and search != ''">
AND (
title LIKE CONCAT('%', #{search}, '%')
OR romanized LIKE CONCAT('%', #{search}, '%')
OR alternatives LIKE CONCAT('%', #{search}, '%')
)
</if>
ORDER BY created_at DESC, title ASC
<if test="offset != null and limit != null">
LIMIT #{limit} OFFSET #{offset}
</if>
</select>
<!-- Get total count for pagination -->
<select id="getContentCount" resultType="int">
SELECT COUNT(*)
FROM content_library
WHERE is_active = 1
<if test="contentType != null and contentType != ''">
AND content_type = #{contentType}
</if>
<if test="category != null and category != ''">
AND category = #{category}
</if>
<if test="search != null and search != ''">
AND (
title LIKE CONCAT('%', #{search}, '%')
OR romanized LIKE CONCAT('%', #{search}, '%')
OR alternatives LIKE CONCAT('%', #{search}, '%')
)
</if>
</select>
<!-- Get distinct categories by content type -->
<select id="getCategoriesByType" resultType="String">
SELECT DISTINCT category
FROM content_library
WHERE is_active = 1 AND content_type = #{contentType}
ORDER BY category ASC
</select>
<!-- Search content by title or alternatives -->
<select id="searchContent" resultMap="contentLibraryMap">
SELECT *
FROM content_library
WHERE is_active = 1
<if test="contentType != null and contentType != ''">
AND content_type = #{contentType}
</if>
AND (
title LIKE CONCAT('%', #{query}, '%')
OR romanized LIKE CONCAT('%', #{query}, '%')
OR alternatives LIKE CONCAT('%', #{query}, '%')
)
ORDER BY
CASE
WHEN title LIKE CONCAT(#{query}, '%') THEN 1
WHEN title LIKE CONCAT('%', #{query}, '%') THEN 2
WHEN romanized LIKE CONCAT(#{query}, '%') THEN 3
WHEN alternatives LIKE CONCAT('%', #{query}, '%') THEN 4
ELSE 5
END,
title ASC
<if test="offset != null and limit != null">
LIMIT #{limit} OFFSET #{offset}
</if>
</select>
<!-- Get search results count -->
<select id="getSearchCount" resultType="int">
SELECT COUNT(*)
FROM content_library
WHERE is_active = 1
<if test="contentType != null and contentType != ''">
AND content_type = #{contentType}
</if>
AND (
title LIKE CONCAT('%', #{query}, '%')
OR romanized LIKE CONCAT('%', #{query}, '%')
OR alternatives LIKE CONCAT('%', #{query}, '%')
)
</select>
<!-- Batch insert content items -->
<insert id="batchInsert">
INSERT INTO content_library (
id, title, romanized, filename, content_type, category,
alternatives, aws_s3_url, duration_seconds, file_size_bytes, is_active
) VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.id}, #{item.title}, #{item.romanized}, #{item.filename},
#{item.contentType}, #{item.category}, #{item.alternatives},
#{item.awsS3Url}, #{item.durationSeconds}, #{item.fileSizeBytes}, #{item.isActive}
)
</foreach>
</insert>
<!-- Find content by filename -->
<select id="findByFilename" resultMap="contentLibraryMap">
SELECT *
FROM content_library
WHERE filename = #{filename}
LIMIT 1
</select>
</mapper>

View file

@ -0,0 +1,55 @@
#!/bin/bash
# XiaoZhi Content Library Migration Validation Script
# This script validates that the migration was successful
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
print_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
print_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
print_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
print_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
print_info "XiaoZhi Content Library Migration Validation"
print_info "============================================"
# Find JAR file
JAR_FILE=""
if [[ -f "target/manager-api.jar" ]]; then
JAR_FILE="target/manager-api.jar"
elif [[ -f "manager-api.jar" ]]; then
JAR_FILE="manager-api.jar"
else
print_error "JAR file not found. Please build the project first."
exit 1
fi
print_info "Using JAR file: $JAR_FILE"
# Run validation
print_info "Starting migration validation..."
if java -Xmx1g -Dspring.profiles.active=validation -jar "$JAR_FILE"; then
print_success "Migration validation completed successfully!"
else
print_error "Migration validation failed!"
exit 1
fi

View file

@ -97,6 +97,40 @@ export default {
}); });
}).send(); }).send();
}, },
// 更新智能体模板
updateAgentTemplate(templateId, templateData, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/template/${templateId}`)
.method('PUT')
.data(templateData)
.success((res) => {
RequestService.clearRequestTime();
callback(res);
})
.networkFail((err) => {
console.error('更新模板失败:', err);
RequestService.reAjaxFun(() => {
this.updateAgentTemplate(templateId, templateData, callback);
});
}).send();
},
// 创建智能体模板
createAgentTemplate(templateData, callback) {
RequestService.sendRequest()
.url(`${getServiceUrl()}/agent/template`)
.method('POST')
.data(templateData)
.success((res) => {
RequestService.clearRequestTime();
callback(res);
})
.networkFail((err) => {
console.error('创建模板失败:', err);
RequestService.reAjaxFun(() => {
this.createAgentTemplate(templateData, callback);
});
}).send();
},
// 获取智能体会话列表 // 获取智能体会话列表
getAgentSessions(agentId, params, callback) { getAgentSessions(agentId, params, callback) {
RequestService.sendRequest() RequestService.sendRequest()

View file

@ -178,6 +178,7 @@ export default {
modelOptions: {}, modelOptions: {},
templates: [], templates: [],
loadingTemplate: false, loadingTemplate: false,
selectedTemplate: null, // Track currently selected template
voiceOptions: [], voiceOptions: [],
showFunctionDialog: false, showFunctionDialog: false,
currentFunctions: [], currentFunctions: [],
@ -218,6 +219,30 @@ export default {
}) })
}) })
}; };
// Check if we need to update template
if (this.selectedTemplate && this.hasTemplateChanges()) {
this.$confirm('Do you want to save changes to the template as well? This will affect all future uses of this template.', 'Update Template', {
confirmButtonText: 'Update Template',
cancelButtonText: 'Keep Template Unchanged',
type: 'question',
distinguishCancelAndClose: true
}).then(() => {
// User wants to update template
this.saveConfigAndTemplate(configData);
}).catch((action) => {
if (action === 'cancel') {
// User wants to save config only
this.saveConfigOnly(configData);
}
});
} else {
// No template changes, save config only
this.saveConfigOnly(configData);
}
},
saveConfigOnly(configData) {
Api.agent.updateAgentConfig(this.$route.query.agentId, configData, ({ data }) => { Api.agent.updateAgentConfig(this.$route.query.agentId, configData, ({ data }) => {
if (data.code === 0) { if (data.code === 0) {
this.$message.success({ this.$message.success({
@ -232,6 +257,73 @@ export default {
} }
}); });
}, },
saveConfigAndTemplate(configData) {
// First save the agent config
Api.agent.updateAgentConfig(this.$route.query.agentId, configData, ({ data }) => {
if (data.code === 0) {
// Then update the template
const templateData = {
agentName: this.form.agentName,
systemPrompt: this.form.systemPrompt,
summaryMemory: this.form.summaryMemory,
asrModelId: this.form.model.asrModelId,
vadModelId: this.form.model.vadModelId,
llmModelId: this.form.model.llmModelId,
vllmModelId: this.form.model.vllmModelId,
ttsModelId: this.form.model.ttsModelId,
ttsVoiceId: this.form.ttsVoiceId,
memModelId: this.form.model.memModelId,
intentModelId: this.form.model.intentModelId,
chatHistoryConf: this.form.chatHistoryConf,
langCode: this.form.langCode,
language: this.form.language
};
Api.agent.updateAgentTemplate(this.selectedTemplate.id, templateData, ({ data: templateResult }) => {
if (templateResult.code === 0) {
this.$message.success({
message: 'Configuration and template saved successfully',
showClose: true
});
// Refresh templates to reflect changes
this.fetchTemplates();
} else {
this.$message.warning({
message: 'Configuration saved but template update failed: ' + (templateResult.msg || 'Unknown error'),
showClose: true
});
}
});
} else {
this.$message.error({
message: data.msg || 'Failed to save configuration',
showClose: true
});
}
});
},
hasTemplateChanges() {
if (!this.selectedTemplate) return false;
return (
this.form.agentName !== this.selectedTemplate.agentName ||
this.form.systemPrompt !== this.selectedTemplate.systemPrompt ||
this.form.summaryMemory !== this.selectedTemplate.summaryMemory ||
this.form.model.asrModelId !== this.selectedTemplate.asrModelId ||
this.form.model.vadModelId !== this.selectedTemplate.vadModelId ||
this.form.model.llmModelId !== this.selectedTemplate.llmModelId ||
this.form.model.vllmModelId !== this.selectedTemplate.vllmModelId ||
this.form.model.ttsModelId !== this.selectedTemplate.ttsModelId ||
this.form.ttsVoiceId !== this.selectedTemplate.ttsVoiceId ||
this.form.model.memModelId !== this.selectedTemplate.memModelId ||
this.form.model.intentModelId !== this.selectedTemplate.intentModelId ||
this.form.chatHistoryConf !== this.selectedTemplate.chatHistoryConf ||
this.form.langCode !== this.selectedTemplate.langCode ||
this.form.language !== this.selectedTemplate.language
);
},
resetConfig() { resetConfig() {
this.$confirm('Are you sure you want to reset the configuration?', 'Confirm', { this.$confirm('Are you sure you want to reset the configuration?', 'Confirm', {
confirmButtonText: 'Confirm', confirmButtonText: 'Confirm',
@ -279,6 +371,7 @@ export default {
if (this.loadingTemplate) return; if (this.loadingTemplate) return;
this.loadingTemplate = true; this.loadingTemplate = true;
try { try {
this.selectedTemplate = template; // Track selected template
this.applyTemplateData(template); this.applyTemplateData(template);
this.$message.success({ this.$message.success({
message: `「${template.agentName}」模板已应用`, message: `「${template.agentName}」模板已应用`,