Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Instagram Caption Generator

An AI-powered application that generates creative Instagram captions for images using fine-tuned BLIP (Bootstrapped Language-Image Pretraining) model.

🎯 Features

  • Caption Generation: Generate multiple caption variations with customizable length
  • Hashtag Generation: Automatic relevant hashtag suggestions
  • Model Training: Fine-tune BLIP on Instagram dataset (5 epochs completed)
  • Model Evaluation: Comprehensive metrics (BLEU, CIDEr, METEOR, ROUGE-L)
  • Web Interfaces: Streamlit frontend and Vue.js dashboard
  • REST API: FastAPI backend with full documentation
  • Data Analysis: Jupyter notebooks for exploration and evaluation

πŸ› οΈ Technology Stack

  • Model: BLIP (Salesforce)
  • Backend: FastAPI, PyTorch, HuggingFace Transformers
  • Frontend: Streamlit, Vue.js with Chart.js
  • Deployment: Docker, Docker Compose
  • Hardware: NVIDIA RTX 3060 (12GB VRAM)
  • Analysis: Jupyter Notebooks, Pandas, Matplotlib, Seaborn

πŸ“ Project Structure

instagram-caption-generator/
β”œβ”€β”€ backend/
β”‚   β”œβ”€β”€ main.py              # FastAPI application
β”‚   β”œβ”€β”€ model.py             # BLIP model wrapper
β”‚   β”œβ”€β”€ train.py             # Training script
β”‚   β”œβ”€β”€ evaluate.py          # Evaluation script
β”‚   β”œβ”€β”€ config.py            # Configuration
β”‚   β”œβ”€β”€ utils.py             # Utility functions
β”‚   β”œβ”€β”€ data_loader.py       # Data loading utilities
β”‚   β”œβ”€β”€ preprocessing.py     # Data preprocessing
β”‚   β”œβ”€β”€ caption_enhancer.py  # Caption enhancement
β”‚   β”œβ”€β”€ Dockerfile
β”‚   β”œβ”€β”€ requirements.txt
β”‚   └── tests/               # Unit tests
β”œβ”€β”€ frontend/
β”‚   β”œβ”€β”€ streamlit/
β”‚   β”‚   β”œβ”€β”€ app.py           # Streamlit application
β”‚   β”‚   └── requirements.txt
β”‚   └── vue-app/             # Vue.js dashboard
β”‚       β”œβ”€β”€ index.html
β”‚       β”œβ”€β”€ package.json
β”‚       β”œβ”€β”€ vite.config.js
β”‚       └── src/
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ raw/
β”‚   β”‚   β”œβ”€β”€ instagram_data/
β”‚   β”‚   β”‚   β”œβ”€β”€ img/         # Images folder 1
β”‚   β”‚   β”‚   └── captions.csv # Captions file 1
β”‚   β”‚   └── instagram_data2/
β”‚   β”‚       β”œβ”€β”€ img2/        # Images folder 2
β”‚   β”‚       └── captions2.csv # Captions file 2
β”‚   └── processed/           # Train/val/test splits
β”‚       β”œβ”€β”€ train.csv
β”‚       β”œβ”€β”€ val.csv
β”‚       β”œβ”€β”€ test.csv
β”‚       └── metadata.json
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ checkpoints/         # Trained model checkpoints
β”‚   β”‚   β”œβ”€β”€ best_model/      # Best performing checkpoint
β”‚   β”‚   β”œβ”€β”€ final_model/     # Final epoch checkpoint
β”‚   β”‚   └── epoch_*/         # Individual epoch checkpoints
β”‚   β”œβ”€β”€ evaluation/          # Evaluation results
β”‚   β”‚   β”œβ”€β”€ baseline_metrics.json
β”‚   β”‚   β”œβ”€β”€ baseline_predictions.json
β”‚   β”‚   └── baseline_results.csv
β”‚   └── models--Salesforce--blip-image-captioning-base/
β”œβ”€β”€ configs/                 # Configuration files
β”‚   β”œβ”€β”€ model_config.yaml    # Model hyperparameters
β”‚   β”œβ”€β”€ data_config.yaml     # Data processing config
β”‚   └── training_config.yaml # Training parameters
β”œβ”€β”€ notebooks/               # Jupyter notebooks
β”‚   β”œβ”€β”€ 01_data_exploration.ipynb    # Dataset analysis
β”‚   β”œβ”€β”€ 02_baseline_evaluation.ipynb # Baseline model eval
β”‚   β”œβ”€β”€ 03_results_analysis.ipynb    # Results analysis
β”‚   └── 04_error_analysis.ipynb      # Error analysis
β”œβ”€β”€ scripts/                 # Utility scripts
β”‚   β”œβ”€β”€ preprocess_data.py   # Data preprocessing
β”‚   β”œβ”€β”€ download_dataset.py  # Dataset download
β”‚   β”œβ”€β”€ evaluate_test_set.py # Test set evaluation
β”‚   β”œβ”€β”€ error_analysis.py    # Error analysis
β”‚   β”œβ”€β”€ fix_csv_headers.py   # CSV fixing utilities
β”‚   β”œβ”€β”€ image_base64.py      # Image encoding
β”‚   β”œβ”€β”€ split_dataset.py     # Dataset splitting
β”‚   └── test_improvements.py # Testing improvements
β”œβ”€β”€ logs/                    # Training and evaluation logs
β”‚   β”œβ”€β”€ training/            # Training logs
β”‚   β”œβ”€β”€ evaluation/          # Evaluation logs
β”‚   β”œβ”€β”€ api/                 # API logs
β”‚   └── csv/                 # CSV metrics logs
β”œβ”€β”€ docs/                    # Documentation
β”‚   β”œβ”€β”€ API.md              # API documentation
β”‚   β”œβ”€β”€ DEPLOYMENT.md       # Deployment guide
β”‚   └── USER_GUIDE.md       # User guide
β”œβ”€β”€ tests/                   # Performance tests
β”‚   └── performance/
β”œβ”€β”€ template/                # HTML templates
└── docker-compose.yml

πŸš€ Quick Start

Prerequisites

  • Docker and Docker Compose
  • NVIDIA GPU with CUDA support
  • NVIDIA Container Toolkit

1. Setup Data

Place your dataset in the following structure:

data/raw/
β”œβ”€β”€ instagram_data/
β”‚   β”œβ”€β”€ img/              # Images folder 1
β”‚   └── captions.csv      # Captions file 1
└── instagram_data2/
    β”œβ”€β”€ img2/             # Images folder 2
    └── captions2.csv     # Captions file 2

2. Deploy with Script

The easiest way to deploy the entire application:

# Make scripts executable (Linux/Mac)
chmod +x scripts/deploy.sh scripts/build_docker.sh

# Deploy the complete application
./scripts/deploy.sh

This will:

  • Check prerequisites (Docker, Docker Compose)
  • Build Docker images
  • Start all services
  • Wait for services to be healthy
  • Show access URLs and management commands

3. Manual Docker Deployment

If you prefer manual control:

# Build Docker images
docker-compose build

# Or use the build script
./scripts/build_docker.sh

# Start services
docker-compose up -d

# Check service status
docker-compose ps

# View logs
docker-compose logs -f

4. Explore Data (Optional)

# Enter the backend container
docker exec -it caption_backend bash

# Inside container: Preprocess data (if not done)
python scripts/preprocess_data.py

# Start Jupyter for data exploration
jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root

# Open notebooks/01_data_exploration.ipynb in your browser

5. Evaluate Baseline Model

# Run baseline evaluation
docker exec -it caption_backend bash
python backend/evaluate.py

6. Access the Application

After deployment, access the application at:

Streamlit App

# In a new terminal (outside container)
cd frontend/streamlit

# Install dependencies
pip install -r requirements.txt

# Run Streamlit
streamlit run app.py

# Or use the script
bash scripts/run_streamlit.sh

Access the app at: http://localhost:8501

Vue.js Dashboard

# In a new terminal
cd frontend/vue-app

# Install dependencies
npm install

# Run development server
npm run dev

Access the dashboard at: http://localhost:5173

πŸ“Š Dataset Information

  • Total images: ~29,899 photos
  • Captions: ~29,899 captions (processed)
  • Caption length: 3-2176 characters (mean: 50, median: 33)
  • Word count: 1-402 words (mean: 8.6, median: 6)
  • Emoji usage: 31.4% of captions contain emojis (avg 0.39 per caption)
  • Hashtag usage: 21.9% of captions contain hashtags (avg 0.43 per caption)
  • Style: Short, casual, emoji-inclusive Instagram captions
  • Split: 70% train, 15% validation, 15% test

πŸŽ“ Training Status

The model has been trained for 5 epochs with the following results:

Training Metrics (Epoch 5)

  • Validation Loss: 1.09
  • BLEU-4: 0.018
  • CIDEr: 0.149

Baseline Performance (Pretrained BLIP)

  • BLEU-1: 0.032
  • BLEU-2: 0.006
  • BLEU-3: 0.000
  • BLEU-4: 0.000
  • CIDEr: 0.030
  • METEOR: 0.012
  • ROUGE-L: 0.027

Target Performance (Fine-tuned)

  • BLEU-4: >0.030
  • CIDEr: >1.000

πŸ““ Jupyter Notebooks

The project includes comprehensive analysis notebooks:

01_data_exploration.ipynb

  • Dataset loading and structure analysis
  • Caption length and word count distributions
  • Emoji and hashtag usage analysis
  • Data quality assessment

02_baseline_evaluation.ipynb

  • Baseline model evaluation setup
  • Performance metrics calculation (BLEU, CIDEr, METEOR, ROUGE-L)
  • Sample predictions analysis
  • Model loading and inference testing

03_results_analysis.ipynb

  • Training results visualization
  • Performance metrics over epochs
  • Model comparison and analysis

04_error_analysis.ipynb

  • Error analysis framework
  • Common failure patterns identification
  • Model improvement suggestions

Logs and Metrics

The project maintains comprehensive logs for monitoring and analysis:

Training Logs (logs/training/)

  • TensorBoard event files for visualization
  • Training progress and loss curves
  • GPU memory usage and performance metrics

CSV Metrics (logs/csv/)

  • val-val_loss.csv - Validation loss over epochs
  • val-bleu_4.csv - BLEU-4 scores over epochs
  • val-cider.csv - CIDEr scores over epochs
  • train-loss.csv - Training loss
  • train-lr.csv - Learning rate schedule

Evaluation Logs (logs/evaluation/)

  • Model evaluation results
  • Performance comparisons
  • Baseline vs trained model metrics

πŸ”§ API Endpoints

  • POST /generate - Generate captions from uploaded image
  • POST /generate/base64 - Generate captions from base64 image

Training

  • POST /train/start - Start model training
  • GET /train/status - Get training status
  • GET /train/logs - Get training logs
  • GET /train/checkpoints - List available checkpoints

Evaluation

  • POST /evaluate - Evaluate model on test set
  • GET /evaluate/metrics - Get latest evaluation metrics

Model Management

  • GET /models - List available models
  • POST /models/load - Load specific checkpoint

Health

  • GET / - API information
  • GET /health - Health check

Full API documentation: http://localhost:8000/docs

πŸŽ“ Usage Examples

Generate Captions via API

import requests

# Upload image
with open('image.jpg', 'rb') as f:
    files = {'file': f}
    data = {
        'num_captions': 3,
        'length': 'medium',
        'generate_hashtags': True,
        'num_hashtags': 5
    }
    
    response = requests.post(
        'http://localhost:8000/generate',
        files=files,
        data=data
    )
    
    result = response.json()
    print("Captions:", result['captions'])
    print("Hashtags:", result['hashtags'])

Start Training via API

import requests

data = {
    'batch_size': 8,
    'epochs': 10,
    'learning_rate': 5e-5,
    'model_name': 'my-instagram-model'
}

response = requests.post(
    'http://localhost:8000/train/start',
    json=data
)

print(response.json())

Generate Captions Programmatically

from model import CaptionModel

# Load model
model = CaptionModel()

# Generate captions
captions = model.generate_with_length(
    'path/to/image.jpg',
    length='medium',
    num_captions=3
)

# Generate with hashtags
result = model.generate_with_hashtags(
    'path/to/image.jpg',
    num_captions=3,
    num_hashtags=5
)

print("Captions:", result['captions'])
print("Hashtags:", result['hashtags'])

πŸ“ˆ Evaluation Metrics

  • BLEU-1 to BLEU-4: Measures n-gram overlap with reference captions
  • CIDEr: Consensus-based metric specifically for image captioning
  • METEOR: Measures semantic similarity and synonymy
  • ROUGE-L: Measures longest common subsequence
  • Higher scores indicate better caption quality

Current Performance (5 epochs trained):

  • BLEU-4: 0.018
  • CIDEr: 0.149

Baseline Performance (Pretrained BLIP):

  • BLEU-1: 0.032, BLEU-2: 0.006, BLEU-3: 0.000, BLEU-4: 0.000
  • CIDEr: 0.030, METEOR: 0.012, ROUGE-L: 0.027

Target Performance (Fine-tuned):

  • BLEU-4: >0.030
  • CIDEr: >1.000

βš™οΈ Configuration

Configuration is managed through YAML files in the configs/ directory:

  • configs/model_config.yaml - Model architecture and generation parameters
  • configs/data_config.yaml - Data processing and loading settings
  • configs/training_config.yaml - Training hyperparameters and settings

You can also edit backend/config.py for additional customization:

  • Model parameters
  • Training hyperparameters
  • Data paths
  • Generation settings

🐳 Docker Commands

Using Deployment Script

# Deploy complete application
./scripts/deploy.sh

# Stop services
./scripts/deploy.sh stop

# Restart services
./scripts/deploy.sh restart

# View logs
./scripts/deploy.sh logs

# Check status
./scripts/deploy.sh status

# Clean up (removes containers, images, volumes)
./scripts/deploy.sh clean

# Show help
./scripts/deploy.sh help

Manual Docker Commands

# Build images
docker-compose build
# or
./scripts/build_docker.sh

# Start services
docker-compose up -d

# View logs
docker-compose logs -f

# Stop services
docker-compose down

# Rebuild after code changes
docker-compose up -d --build

# Access backend shell
docker exec -it caption_backend bash

# Access frontend shell
docker exec -it caption_frontend sh

πŸ” Troubleshooting

Issue: CUDA Out of Memory

Solution:

  • Reduce batch size in config.py
  • Enable gradient accumulation
  • Use smaller image size (224x224 instead of 384x384)

Issue: API Connection Refused

Solution:

  • Check if backend is running: docker ps
  • Verify port mapping: docker-compose ps
  • Check API health: curl http://localhost:8000/health

Issue: Training Not Starting

Solution:

  • Verify preprocessed data exists: ls data/processed/
  • Run preprocessing: python scripts/preprocess_data.py
  • Check training logs: GET /train/logs

Issue: Images Not Found

Solution:

  • Verify dataset structure matches expected paths
  • Check config.py paths are correct
  • Ensure Docker volume mounts are correct in docker-compose.yml

πŸ“ Development Workflow

  1. Data Preparation

    python scripts/preprocess_data.py
    jupyter notebook notebooks/01_data_exploration.ipynb
  2. Baseline Evaluation

    jupyter notebook notebooks/02_baseline_evaluation.ipynb
  3. Training (Completed - 5 epochs)

    # Training completed with checkpoints in models/checkpoints/
    # View training logs in logs/training/ and logs/csv/
    # Best model: models/checkpoints/best_model/
    # Monitor metrics via notebooks/03_results_analysis.ipynb
  4. Evaluation

    python backend/evaluate.py --checkpoint models/checkpoints/*/best_model.pt
  5. Deployment

    # Deploy complete application
    ./scripts/deploy.sh
    
    # Or manually:
    # docker-compose up -d
    # cd frontend/streamlit && streamlit run app.py

πŸš€ Future Enhancements

Short-term

  • Style-conditioned caption generation
  • Enhanced hashtag generation with trending tags
  • Caption editing interface
  • Batch processing for multiple images

Medium-term

  • Multi-language support
  • User authentication and accounts
  • Caption history and favorites
  • Advanced model fine-tuning options
  • A/B testing framework for caption variants

Long-term

  • Mobile application
  • Instagram API integration
  • Video caption generation
  • Community features and ratings

πŸ“„ License

This is a college project for educational purposes.

πŸ™ Acknowledgments

  • BLIP model by Salesforce Research
  • HuggingFace Transformers
  • FastAPI and Streamlit communities
  • Instagram dataset contributors

πŸ“§ Contact

For questions or issues, please open an issue on GitHub.


Made using BLIP, FastAPI, and Streamlit

About

A image captioning tool for Instagram using language model

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages