A production-ready, beginner-friendly text-to-image generation system powered by Stable Diffusion, Hugging Face Diffusers, and FastAPI.
- Introduction
- Features
- Architecture
- Folder Structure
- Installation
- Running the Application
- API Endpoints
- Frontend Usage
- Deployment
- Troubleshooting
This project implements a Text-to-Image Generative AI system using Stable Diffusion and the Hugging Face Diffusers library. Users can enter a natural language prompt (e.g., "a futuristic city at night, neon lights, cyberpunk style") and the system generates a high-quality image using the diffusion model pipeline.
The system is built with:
- Backend: Python + FastAPI
- Frontend: HTML5 + CSS3 + JavaScript (Vanilla)
- AI Model: Stable Diffusion v2.1 via Hugging Face
- Deployment: Docker, AWS EC2 / Google Cloud / Hugging Face Spaces
- πΌοΈ Text-to-Image Generation using Stable Diffusion 2.1
- β‘ FastAPI Backend with async support and Swagger UI
- π¨ Beautiful Responsive Frontend with loading animations
- π‘οΈ Error Handling at API and UI level
- π³ Docker Support for easy containerization
- βοΈ Cloud Deployment guides for AWS, GCP, and Hugging Face Spaces
- π Well-Documented Code with inline comments
- π Environment Variable Management via
.env - π Model Architecture Explanation (CLIP + U-Net + VAE)
User Prompt (Text)
β
βΌ
βββββββββββββββββββββββββββββββββββββββ
β CLIP Text Encoder β β Converts text to embeddings
β (openai/clip-vit-large-patch14) β
βββββββββββββββββββββββββββββββββββββββ
β Text Embeddings
βΌ
βββββββββββββββββββββββββββββββββββββββ
β U-Net Diffusion Model β β Iterative denoising (50 steps)
β (Noise β Denoised Latent Space) β
βββββββββββββββββββββββββββββββββββββββ
β Denoised Latents
βΌ
βββββββββββββββββββββββββββββββββββββββ
β VAE Decoder β β Latents β Pixel Space (Image)
β (Variational Autoencoder) β
βββββββββββββββββββββββββββββββββββββββ
β
βΌ
Generated Image (PNG)
| Component | Role |
|---|---|
| CLIP Text Encoder | Converts your text prompt into numerical embeddings |
| U-Net | Iteratively denoises a random noise tensor guided by the text embeddings |
| VAE Decoder | Decodes the denoised latent representation into a full-resolution image |
| Scheduler | Controls the denoising steps (PNDM, DDIM, etc.) |
Image/
βββ backend/ # FastAPI backend
β βββ main.py # App entry point
β βββ config.py # Configuration & settings
β βββ routes/
β β βββ generate.py # /generate API route
β βββ services/
β β βββ diffusion_service.py # Stable Diffusion logic
β βββ utils/
β βββ image_utils.py # Image processing helpers
βββ frontend/ # Web UI
β βββ index.html # Main HTML page
β βββ styles.css # Responsive CSS with animations
β βββ script.js # API calls and UI logic
βββ outputs/ # Generated images (auto-created)
βββ docs/
β βββ ARCHITECTURE.md # Deep technical architecture
βββ .env.example # Environment variable template
βββ .gitignore
βββ Dockerfile
βββ docker-compose.yml
βββ requirements.txt # Python dependencies
βββ README.md # This file
- Python 3.10+
- CUDA-enabled GPU (recommended) OR CPU (slower)
- 8GB+ RAM / 4GB+ VRAM (GPU)
- pip or conda
git clone https://github.com/yourusername/image-gen-ai.git
cd image-gen-aipython -m venv venv
# On Windows:
venv\Scripts\activate
# On Linux/Mac:
source venv/bin/activatepip install -r requirements.txtcp .env.example .env
# Edit .env with your settings (HuggingFace token, etc.)uvicorn backend.main:app --reload --host 0.0.0.0 --port 8000Open frontend/index.html in your browser, or serve it:
python -m http.server 3000 --directory frontendThen visit: http://localhost:3000
Visit: http://localhost:8000/docs
Generate an image from a text prompt.
Request Body:
{
"prompt": "a beautiful sunset over the ocean, photorealistic",
"negative_prompt": "blurry, low quality",
"num_inference_steps": 50,
"guidance_scale": 7.5,
"width": 512,
"height": 512,
"seed": -1
}Response:
{
"success": true,
"image_base64": "data:image/png;base64,iVBORw0KGgo...",
"image_path": "outputs/generated_1234567890.png",
"prompt": "a beautiful sunset over the ocean, photorealistic",
"generation_time": 12.45,
"parameters": { ... }
}Check server and model status.
List available models.
docker-compose up --build- Launch a
g4dn.xlargeinstance (NVIDIA T4 GPU) - Install CUDA drivers and Docker
- Clone the repo and run
docker-compose up - Configure Security Group to allow port 8000
- Create a Compute Engine instance with NVIDIA GPU
- Use Cloud Run for serverless deployment
- Push Docker image to Artifact Registry
- Create a new Space with Gradio SDK
- Upload your code
- Set
HF_TOKENin Space secrets - The Space will auto-build and deploy
| Issue | Solution |
|---|---|
| Out of memory (GPU) | Reduce width/height to 512x512, enable enable_attention_slicing |
| Slow generation (CPU) | Use torch_dtype=torch.float32, expect 5-10 minutes per image |
| Model download fails | Set HF_TOKEN in .env for gated models |
| Port already in use | Change port: --port 8001 |
| CUDA not found | Install CUDA 11.8+, reinstall torch with CUDA support |
MIT License β free to use, modify, and distribute.