An AI-powered application that generates creative Instagram captions for images using fine-tuned BLIP (Bootstrapped Language-Image Pretraining) model.
- 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
- 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
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
- Docker and Docker Compose
- NVIDIA GPU with CUDA support
- NVIDIA Container Toolkit
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
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.shThis will:
- Check prerequisites (Docker, Docker Compose)
- Build Docker images
- Start all services
- Wait for services to be healthy
- Show access URLs and management commands
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# 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# Run baseline evaluation
docker exec -it caption_backend bash
python backend/evaluate.pyAfter deployment, access the application at:
- Backend API: http://localhost:8000
- API Documentation: http://localhost:8000/docs
- Vue.js Dashboard: http://localhost:3000
- Streamlit App: http://localhost:8501 (if started separately)
# 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.shAccess the app at: http://localhost:8501
# In a new terminal
cd frontend/vue-app
# Install dependencies
npm install
# Run development server
npm run devAccess the dashboard at: http://localhost:5173
- 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
The model has been trained for 5 epochs with the following results:
- Validation Loss: 1.09
- BLEU-4: 0.018
- CIDEr: 0.149
- 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
- BLEU-4: >0.030
- CIDEr: >1.000
The project includes comprehensive analysis notebooks:
- Dataset loading and structure analysis
- Caption length and word count distributions
- Emoji and hashtag usage analysis
- Data quality assessment
- Baseline model evaluation setup
- Performance metrics calculation (BLEU, CIDEr, METEOR, ROUGE-L)
- Sample predictions analysis
- Model loading and inference testing
- Training results visualization
- Performance metrics over epochs
- Model comparison and analysis
- Error analysis framework
- Common failure patterns identification
- Model improvement suggestions
The project maintains comprehensive logs for monitoring and analysis:
- TensorBoard event files for visualization
- Training progress and loss curves
- GPU memory usage and performance metrics
val-val_loss.csv- Validation loss over epochsval-bleu_4.csv- BLEU-4 scores over epochsval-cider.csv- CIDEr scores over epochstrain-loss.csv- Training losstrain-lr.csv- Learning rate schedule
- Model evaluation results
- Performance comparisons
- Baseline vs trained model metrics
POST /generate- Generate captions from uploaded imagePOST /generate/base64- Generate captions from base64 image
POST /train/start- Start model trainingGET /train/status- Get training statusGET /train/logs- Get training logsGET /train/checkpoints- List available checkpoints
POST /evaluate- Evaluate model on test setGET /evaluate/metrics- Get latest evaluation metrics
GET /models- List available modelsPOST /models/load- Load specific checkpoint
GET /- API informationGET /health- Health check
Full API documentation: http://localhost:8000/docs
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'])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())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'])- 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 is managed through YAML files in the configs/ directory:
configs/model_config.yaml- Model architecture and generation parametersconfigs/data_config.yaml- Data processing and loading settingsconfigs/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
# 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# 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 shSolution:
- Reduce batch size in
config.py - Enable gradient accumulation
- Use smaller image size (224x224 instead of 384x384)
Solution:
- Check if backend is running:
docker ps - Verify port mapping:
docker-compose ps - Check API health:
curl http://localhost:8000/health
Solution:
- Verify preprocessed data exists:
ls data/processed/ - Run preprocessing:
python scripts/preprocess_data.py - Check training logs:
GET /train/logs
Solution:
- Verify dataset structure matches expected paths
- Check
config.pypaths are correct - Ensure Docker volume mounts are correct in
docker-compose.yml
-
Data Preparation
python scripts/preprocess_data.py jupyter notebook notebooks/01_data_exploration.ipynb
-
Baseline Evaluation
jupyter notebook notebooks/02_baseline_evaluation.ipynb
-
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
-
Evaluation
python backend/evaluate.py --checkpoint models/checkpoints/*/best_model.pt -
Deployment
# Deploy complete application ./scripts/deploy.sh # Or manually: # docker-compose up -d # cd frontend/streamlit && streamlit run app.py
- Style-conditioned caption generation
- Enhanced hashtag generation with trending tags
- Caption editing interface
- Batch processing for multiple images
- Multi-language support
- User authentication and accounts
- Caption history and favorites
- Advanced model fine-tuning options
- A/B testing framework for caption variants
- Mobile application
- Instagram API integration
- Video caption generation
- Community features and ratings
This is a college project for educational purposes.
- BLIP model by Salesforce Research
- HuggingFace Transformers
- FastAPI and Streamlit communities
- Instagram dataset contributors
For questions or issues, please open an issue on GitHub.
Made using BLIP, FastAPI, and Streamlit