A powerful Python API for creating Ghost CMS blog posts with AI-powered features
Project description
Ghost Blog Smart API
๐ A powerful Python API for creating and managing Ghost CMS blog posts with AI-powered features including automatic image generation, content formatting, and comprehensive blog management.
โจ Features
๐ค Smart Gateway (NEW!)
- Intelligent Routing - Automatically determines if content needs rewriting or can be published directly
- Structured Output - Uses Gemini's structured output for consistent blog formatting
- Function Calling - Leverages Gemini function calling for smart decision making
- Auto Enhancement - Transforms scattered ideas into complete, well-structured blog posts
- Missing Component Detection - Automatically generates titles, excerpts, and tags when missing
Content Creation
- ๐จ AI Image Generation - Automatically generate feature images using Google Imagen-4
- ๐ Smart Content Formatting - Auto-format plain text to beautiful Markdown with Gemini AI
- ๐ YouTube-Style Slugs - Generate 11-character slugs like YouTube video IDs
- ๐ฌ YouTube Video Embedding - Seamlessly embed YouTube videos in posts
- ๐ Multi-language Support - Chinese to Pinyin conversion for slugs
- ๐ Language Translation - Auto-translate content to any target language
- ๐ผ๏ธ Flexible Image Handling - Support for URLs, local files, base64 data
Blog Management
- ๐ Advanced Listing - Get posts with powerful filtering options
- ๐ Search & Query - Full-text search across all posts
- ๐ Date Range Filtering - Find posts by publication/creation date
- ๐ Detailed Post Info - Get complete post details including content
- โ๏ธ Update Posts - Modify any post property (title, content, dates, etc.)
- โญ Featured Control - Set posts as featured or unfeatured
- ๐๏ธ Visibility Management - Control post visibility (public/members/paid)
- ๐ Status Toggle - Publish/unpublish posts instantly
- ๐ผ๏ธ Image Updates - Replace, generate, or remove feature images
- ๐ฏ Image Regeneration - Fix abstract images with concrete noun focus
- ๐ Date Management - Update published dates for content organization
- ๐๏ธ Post Deletion - Remove posts from Ghost CMS
- โก Batch Operations - Process multiple posts efficiently
๐ Prerequisites
- Python 3.8+
- Ghost CMS instance with Admin API access
- Google Gemini API key (for AI features)
๐ Quick Start
1. Installation
# Clone the repository
git clone https://github.com/yourusername/ghost_blog_smart_api.git
cd ghost_blog_smart_api
# Install dependencies
pip install -r requirements.txt
2. Configuration
Create a .env file in the project root:
# Ghost CMS Configuration (optional - can also pass as parameters)
GHOST_ADMIN_API_KEY=your_ghost_admin_api_key_here
GHOST_API_URL=https://your-ghost-site.com
# Google AI Configuration (optional - can also pass as parameters)
GEMINI_API_KEY=your_gemini_api_key_here
Note: All API keys can be provided either through environment variables OR as function parameters. Parameters take precedence over environment variables.
3. Basic Usage
Traditional Method
from main_functions import create_ghost_blog_post
# Create a simple blog post
result = create_ghost_blog_post(
title="My First Post",
content="This is the content of my blog post.",
excerpt="A brief summary",
tags=["Tutorial", "Getting Started"],
status="published" # or "draft"
)
if result['success']:
print(f"Post created: {result['url']}")
Smart Gateway Method (NEW!)
from smart_gateway import smart_blog_gateway
# Let AI handle everything - just provide your ideas
result = smart_blog_gateway(
"Write about AI transforming healthcare. Better diagnosis, personalized treatment.",
status="published"
)
# Gateway automatically:
# - Detects if content needs rewriting
# - Generates title, excerpt, tags if missing
# - Structures content professionally
# - Publishes to Ghost CMS
๐ฏ Examples
Smart Gateway Examples (AI-Powered)
Transform Scattered Ideas
from smart_gateway import smart_blog_gateway
# Just provide your thoughts - AI handles the rest
ideas = """
Remote work benefits:
- No commute
- Flexible schedule
- Better work-life balance
- Cost savings for companies
Challenges: isolation, communication
"""
result = smart_blog_gateway(ideas, status="published")
# AI will create a complete, structured blog post with title and sections
Enhance Existing Content
# Good content but missing title and structure
content = """
The tech industry is rapidly adopting sustainable practices.
Major companies are committing to carbon neutrality.
Data centers are switching to renewable energy.
This shift is driven by both environmental concerns and economic benefits.
"""
result = smart_blog_gateway(content, preferred_language="English")
# AI adds title, structure, excerpt, and enhances formatting
Minimal Input Creation
# Just tell it what you want
result = smart_blog_gateway(
"Create a beginner's guide to machine learning",
status="draft"
)
# AI generates complete tutorial from scratch
Content Creation Examples
Using Different Blog Sites
# Post to different Ghost blogs by providing API credentials
create_ghost_blog_post(
title="Post for Blog A",
content="Content for blog A",
ghost_admin_api_key="blog_a_admin_key",
ghost_api_url="https://blog-a.com",
status="published"
)
create_ghost_blog_post(
title="Post for Blog B",
content="Content for blog B",
ghost_admin_api_key="blog_b_admin_key",
ghost_api_url="https://blog-b.com",
status="published"
)
Basic Post
create_ghost_blog_post(
title="Welcome to My Blog",
content="This is my first post using Ghost Blog Smart API.",
excerpt="Introduction to my blog",
tags=["Welcome"],
status="draft"
)
Post with AI-Generated Image
create_ghost_blog_post(
title="The Future of AI",
content="Artificial Intelligence is transforming...",
excerpt="Exploring AI's impact",
use_generated_feature_image=True, # Enable AI image generation
image_aspect_ratio="16:9",
tags=["AI", "Technology"],
status="published"
)
Post with YouTube Video
create_ghost_blog_post(
title="Amazing Tutorial",
content="Check out this video tutorial...",
youtube_video_id="dQw4w9WgXcQ", # Becomes the post slug
use_generated_feature_image=True, # Still generate preview image
tags=["Video", "Tutorial"],
status="draft"
)
Post with Custom Image
# URL image
create_ghost_blog_post(
title="Beautiful Landscape",
content="Nature photography showcase...",
feature_image="https://example.com/image.jpg",
status="published"
)
# Local file
create_ghost_blog_post(
title="My Photo",
content="Photography collection...",
feature_image="./path/to/image.jpg",
status="published"
)
# Base64 data
create_ghost_blog_post(
title="Embedded Image",
content="Post with embedded image...",
feature_image="data:image/jpeg;base64,/9j/4AAQ...",
status="published"
)
Post with Language Translation
# Translate Chinese to English
create_ghost_blog_post(
title="AI Revolution",
content="ไบบๅทฅๆบ่ฝๆญฃๅจๆนๅไธ็ใๅป็่ฏๆญๆดๅ็กฎใ",
target_language="English", # Auto-translates to English
status="published"
)
# Translate English to Chinese
create_ghost_blog_post(
title="็งๆๆชๆฅ",
content="Technology is advancing rapidly.",
target_language="Chinese", # Auto-translates to Chinese
status="published"
)
# Preserve original language (default)
create_ghost_blog_post(
title="Multi-language",
content="This stays in original language.",
# No target_language - preserves original
status="published"
)
Blog Management Examples
Advanced Post Listing & Filtering
from post_management import (
get_ghost_posts_advanced,
get_ghost_post_details,
get_posts_summary
)
from datetime import datetime, timedelta
# Get posts from last 30 days
last_month = datetime.now() - timedelta(days=30)
result = get_ghost_posts_advanced(
published_after=last_month,
published_before=datetime.now(),
status='published',
order='published_at DESC'
)
# Search posts
result = get_ghost_posts_advanced(
search='AI', # Search term
status='all',
featured=True # Only featured posts
)
# Get complete post details
post_details = get_ghost_post_details('post_id_here')
if post_details['success']:
post = post_details['post']
print(f"Title: {post['title']}")
print(f"Content: {post['html']}")
print(f"Published: {post['published_at']}")
# Get summary of all posts
summary = get_posts_summary(status='all')
print(f"Total posts: {summary['total_posts']}")
Update Post Properties
from main_functions import update_ghost_post
# Publish/Unpublish a post
result = update_ghost_post(
post_id="your_post_id",
status='published' # or 'draft' to unpublish
)
# Toggle featured status
result = update_ghost_post(
post_id="your_post_id",
featured=True # or False to unfeature
)
# Update multiple properties at once
result = update_ghost_post(
post_id="your_post_id",
title="Updated Title",
excerpt="New excerpt",
status='published',
featured=True,
tags=["New", "Tags"],
visibility='public' # 'public', 'members', 'paid', 'tiers'
)
# Update published date
from datetime import datetime, timedelta
# Backdate to last week
last_week = datetime.now() - timedelta(days=7)
result = update_ghost_post(
post_id="your_post_id",
published_at=last_week.isoformat() + 'Z'
)
# Set specific date
result = update_ghost_post(
post_id="your_post_id",
published_at="2024-06-15T09:00:00.000Z"
)
Update Feature Image
from main_functions import update_ghost_post_image
# Generate new AI image with custom prompt
result = update_ghost_post_image(
post_id="your_post_id",
use_generated_image=True,
image_prompt="A serene mountain landscape at sunrise",
image_aspect_ratio="16:9"
)
# Auto-generate image from post content
result = update_ghost_post_image(
post_id="your_post_id",
use_generated_image=True,
auto_generate_prompt=True # Analyzes post content
)
# Use specific image URL
result = update_ghost_post_image(
post_id="your_post_id",
feature_image="https://example.com/new-image.jpg"
)
# Remove feature image
result = update_ghost_post_image(
post_id="your_post_id",
feature_image=None
)
Regenerate Feature Images (Fix Abstract Images)
from regenerate_feature_image import (
regenerate_feature_image,
batch_regenerate_images,
find_and_fix_abstract_images
)
# Regenerate single post with concrete noun focus
result = regenerate_feature_image('post_id_here')
# Dry run to preview without updating
result = regenerate_feature_image('post_id_here', dry_run=True)
# Batch regenerate multiple posts
post_ids = ['id1', 'id2', 'id3']
result = batch_regenerate_images(post_ids)
# Find and fix all abstract images from last 30 days
result = find_and_fix_abstract_images()
# Custom date range
from datetime import datetime, timedelta
result = find_and_fix_abstract_images(
date_from=datetime.now() - timedelta(days=60),
date_to=datetime.now()
)
Delete Post
from main_functions import delete_ghost_post
result = delete_ghost_post(post_id="your_post_id")
if result['success']:
print("Post deleted successfully")
๐ API Reference
Smart Gateway (AI-Powered)
smart_blog_gateway(user_input, **kwargs)
Intelligent gateway that automatically routes blog creation through the optimal path.
Parameters:
user_input(str): Your blog content, ideas, or requeststatus(str): 'published' or 'draft' (default: 'published')preferred_language(str): Target language for output (optional)
Returns:
{
'success': bool,
'response': str, # Human-readable status message
'url': str, # Ghost post URL (if successful)
'post_id': str, # Ghost post ID (if successful)
'rewritten_data': dict # Rewritten content details (if rewrite path was used)
}
How It Works:
- Analyzes Input - Determines completeness of content
- Smart Routing:
- Direct Path: Complete blogs โ format โ publish
- Rewrite Path: Incomplete/scattered โ AI rewrite โ structure โ publish
- Auto-Enhancement - Generates missing title, excerpt, tags as needed
Content Creation
create_ghost_blog_post(**kwargs)
Main function to create Ghost blog posts.
Required Parameters:
title(str): Blog post titlecontent(str): Blog post content (Markdown or plain text)
Optional Parameters:
excerpt(str): Post excerpt/summary (max 299 chars)feature_image(str): Image path, URL, or base64 datatags(list): List of tags (default: ['Blog'])post_type(str): 'post' or 'page' (default: 'post')status(str): 'published' or 'draft' (default: 'published')visibility(str): 'public' or 'private' (default: 'public')content_type(str): 'markdown' or 'html' (default: 'markdown')auto_format(bool): Auto-format plain text (default: True)target_language(str): Target language for content translation (e.g., 'English', 'Chinese')use_generated_feature_image(bool): Generate AI image (default: False)image_generation_prompt(str): Custom prompt for image generationimage_aspect_ratio(str): '16:9', '1:1', '9:16', etc. (default: '16:9')youtube_video_id(str): YouTube video ID (also becomes slug)is_test(bool): Test mode without posting (default: False)ghost_admin_api_key(str): Override env Ghost API keyghost_api_url(str): Override env Ghost API URLgemini_api_key(str): Override env Gemini API key
Returns:
{
'success': bool,
'url': str, # Post URL
'post_id': str, # Ghost post ID
'message': str # Success/error message
}
Blog Management
get_ghost_posts(**kwargs)
Get list of posts from Ghost CMS.
Parameters:
limit(int): Number of posts to retrieve (default: 15)page(int): Page number for pagination (default: 1)status(str): Filter by status ('published', 'draft', 'all')ghost_admin_api_key(str): Override env Ghost API keyghost_api_url(str): Override env Ghost API URL
Returns:
{
'success': bool,
'posts': list, # List of post objects
'meta': dict # Pagination metadata
}
update_ghost_post(post_id, **kwargs)
Update various properties of a Ghost blog post.
Parameters:
post_id(str): The ID of the post to updatestatus(str): Update status to 'published' or 'draft'featured(bool): Set featured status (True/False)title(str): Update post titlecontent(str): Update post contentexcerpt(str): Update post excerpttags(list): Update tagsvisibility(str): Update visibility ('public', 'members', 'paid', 'tiers')published_at(str/datetime): Update published date (ISO format or datetime object)ghost_admin_api_key(str): Override env Ghost API keyghost_api_url(str): Override env Ghost API URL
Returns:
{
'success': bool,
'message': str,
'post_id': str,
'status': str,
'featured': bool,
'url': str,
'updates': list # List of changes made
}
update_ghost_post_image(post_id, **kwargs)
Update the feature image of a Ghost blog post.
Parameters:
post_id(str): The ID of the post to updatefeature_image(str): Path/URL/base64 to new image, or None to removeuse_generated_image(bool): Generate new AI image (default: False)image_prompt(str): Custom prompt for AI image generationauto_generate_prompt(bool): Auto-generate prompt from post content (default: True)image_aspect_ratio(str): Aspect ratio for generated image (default: '16:9')ghost_admin_api_key(str): Override env Ghost API keyghost_api_url(str): Override env Ghost API URLgemini_api_key(str): Override env Gemini API key
Returns:
{
'success': bool,
'message': str,
'post_id': str,
'feature_image': str,
'url': str
}
delete_ghost_post(post_id, **kwargs)
Delete a Ghost blog post.
Parameters:
post_id(str): The ID of the post to deleteghost_admin_api_key(str): Override env Ghost API keyghost_api_url(str): Override env Ghost API URL
Returns:
{
'success': bool,
'message': str,
'post_id': str
}
๐ง Advanced Features
Slug Generation
The API automatically generates YouTube-style 11-character slugs:
- With YouTube ID:
https://blog.site/dQw4w9WgXcQ - Auto-generated:
https://blog.site/a2NvxBWput4
AI Image Generation
When use_generated_feature_image=True, the API:
- Analyzes your blog title, excerpt, and first paragraph
- Creates a structured image description
- Generates a professional feature image with Google Imagen-4
- Automatically uploads it to Ghost CMS
Content Formatting
With auto_format=True, plain text is automatically:
- Structured with proper paragraphs
- Enhanced with Markdown formatting
- Optimized for readability
๐ Project Structure
ghost_blog_smart_api/
โโโ main_functions.py # Core API functions
โโโ post_management.py # Advanced post management functions
โโโ regenerate_feature_image.py # Fix abstract images with concrete focus
โโโ smart_gateway.py # AI-powered intelligent routing
โโโ example_usage.py # Complete usage examples for ALL features
โโโ blog_to_image_prompt.py # AI prompt for image generation
โโโ blog_post_refine_prompt.py # Blog refinement system prompt
โโโ requirements.txt # Python dependencies
โโโ .env # Configuration (create this)
โโโ src/
โ โโโ clean_imagen_generator.py # Image generation module
โโโ generated_images/ # AI-generated images (auto-created)
๐ ๏ธ Development
Running Examples
python example_usage.py
Testing
Set is_test=True to test without actually posting:
result = create_ghost_blog_post(
title="Test Post",
content="Test content",
is_test=True # Won't actually post
)
๐ Token Optimization
The API optimizes token usage by:
- Using only title, excerpt, and first paragraph for image generation
- Caching generated images locally
- Batch processing when possible
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
๐ License
MIT License - see LICENSE file for details
๐ Acknowledgments
- Ghost CMS for the excellent blogging platform
- Google Gemini & Imagen for AI capabilities
- The open-source community
๐ Support
For issues or questions, please open an issue on GitHub.
Made with โค๏ธ for the Ghost CMS community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file ghost_blog_smart-1.0.7.tar.gz.
File metadata
- Download URL: ghost_blog_smart-1.0.7.tar.gz
- Upload date:
- Size: 45.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4821e2c8bd8e39848efb4fccd512efdfc23904b7d7682b06128f211a3c5d4a50
|
|
| MD5 |
9f022d1ebbe86f1c032b6e8a04ea2074
|
|
| BLAKE2b-256 |
e19a62b186be3dfcd2e4f06b22d61298b996c49cd198ad038168dfe5f4240ab0
|
File details
Details for the file ghost_blog_smart-1.0.7-py3-none-any.whl.
File metadata
- Download URL: ghost_blog_smart-1.0.7-py3-none-any.whl
- Upload date:
- Size: 42.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dcb407fe62b593cbf1aaed5820199fc17218f951897adaf83225a7682df45129
|
|
| MD5 |
9ac27d0dc136fa40738e7bf67f8d7b20
|
|
| BLAKE2b-256 |
0e0621e2f8566153054da123510621707fb17c60859316d8b013c032601d58a8
|