Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- Dockerfile +26 -0
- README.md +180 -5
- app.py +296 -0
- generate_server.py +119 -0
- requirements.txt +6 -0
- run.py +42 -0
Dockerfile
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9
|
| 2 |
+
|
| 3 |
+
# Set up a new user named "user" with user ID 1000
|
| 4 |
+
RUN useradd -m -u 1000 user
|
| 5 |
+
|
| 6 |
+
# Switch to the "user" user
|
| 7 |
+
USER user
|
| 8 |
+
|
| 9 |
+
# Set home to the user's home directory
|
| 10 |
+
ENV HOME=/home/user \
|
| 11 |
+
PATH=/home/user/.local/bin:$PATH
|
| 12 |
+
|
| 13 |
+
# Set the working directory to the user's home directory
|
| 14 |
+
WORKDIR $HOME/app
|
| 15 |
+
|
| 16 |
+
# Copy the current directory contents into the container at $HOME/app setting the owner to the user
|
| 17 |
+
COPY --chown=user . $HOME/app
|
| 18 |
+
|
| 19 |
+
# Install any needed packages specified in requirements.txt
|
| 20 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
| 21 |
+
|
| 22 |
+
# Make port 7860 available to the world outside this container
|
| 23 |
+
EXPOSE 7860
|
| 24 |
+
|
| 25 |
+
# Run app.py when the container launches
|
| 26 |
+
CMD ["gunicorn", "-b", "0.0.0.0:7860", "app:app", "--timeout", "120"]
|
README.md
CHANGED
|
@@ -1,11 +1,186 @@
|
|
| 1 |
---
|
| 2 |
title: Imagify
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
-
|
| 9 |
---
|
| 10 |
|
| 11 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Imagify
|
| 3 |
+
emoji: 🎨
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: purple
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
app_port: 7860
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# 🎨 Imagify – AI Image to Story & Caption Generator
|
| 12 |
+
|
| 13 |
+
<p align="center">
|
| 14 |
+
<img src="assets/images/01.Home.png" width="900" alt="Imagify Home"/>
|
| 15 |
+
</p>
|
| 16 |
+
|
| 17 |
+
<p align="center">
|
| 18 |
+
<b>Transform images into immersive stories, poetic descriptions, and social‑ready captions using Vision‑Language AI.</b>
|
| 19 |
+
</p>
|
| 20 |
+
|
| 21 |
+
<p align="center">
|
| 22 |
+
<img src="https://img.shields.io/badge/Version-1.0.0-blue"/>
|
| 23 |
+
<img src="https://img.shields.io/badge/Python-3.8%2B-green"/>
|
| 24 |
+
<img src="https://img.shields.io/badge/Framework-Flask-lightblue"/>
|
| 25 |
+
<img src="https://img.shields.io/badge/License-MIT-yellow"/>
|
| 26 |
+
</p>
|
| 27 |
+
|
| 28 |
+
---
|
| 29 |
+
|
| 30 |
+
## 🎥 Demo Video
|
| 31 |
+
|
| 32 |
+
> A complete walkthrough of Imagify’s AI‑powered image understanding and story generation workflow.
|
| 33 |
+
|
| 34 |
+
**▶ Click to play the demo video:**
|
| 35 |
+
|
| 36 |
+
[https://github.com/bhavyadoshi12/Imagify/raw/main/assets/video/Imagify.mp4](https://github.com/bhavyadoshi12/Imagify/raw/main/assets/video/Imagify.mp4)
|
| 37 |
+
|
| 38 |
+
---
|
| 39 |
+
|
| 40 |
+
## ✨ Key Features
|
| 41 |
+
|
| 42 |
+
### 🎯 Core Capabilities
|
| 43 |
+
|
| 44 |
+
* 🧠 **Vision‑Language Intelligence** using Salesforce **BLIP** for deep image understanding
|
| 45 |
+
* ✍️ **Multi‑Style Generation**
|
| 46 |
+
|
| 47 |
+
* 📖 Creative Stories
|
| 48 |
+
* 🎼 Poetic Descriptions
|
| 49 |
+
* 💬 Smart Social Captions
|
| 50 |
+
* ⚡ **Real‑Time Inference Pipeline** with optimized model loading
|
| 51 |
+
* 🖥️ **Clean & Intuitive UI** for seamless user experience
|
| 52 |
+
|
| 53 |
+
### 🧩 AI Design Highlights
|
| 54 |
+
|
| 55 |
+
* Context‑aware caption extraction
|
| 56 |
+
* Dynamic prompt construction based on user style selection
|
| 57 |
+
* Narrative enhancement layer for human‑like storytelling
|
| 58 |
+
* Extensible architecture for future LLM integration
|
| 59 |
+
|
| 60 |
+
---
|
| 61 |
+
|
| 62 |
+
## 🖥️ Application Screenshots
|
| 63 |
+
|
| 64 |
+
<details>
|
| 65 |
+
<summary><b>📸 Click to view application UI</b></summary>
|
| 66 |
+
|
| 67 |
+
### 🏠 Home Interface
|
| 68 |
+
|
| 69 |
+

|
| 70 |
+
|
| 71 |
+

|
| 72 |
+
|
| 73 |
+
### ℹ️ About Section
|
| 74 |
+
|
| 75 |
+

|
| 76 |
+
|
| 77 |
+

|
| 78 |
+
|
| 79 |
+
### ⚙️ How It Works – Flow
|
| 80 |
+
|
| 81 |
+

|
| 82 |
+
|
| 83 |
+

|
| 84 |
+
|
| 85 |
+

|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
### 📤 Image Upload
|
| 89 |
+
|
| 90 |
+

|
| 91 |
+
|
| 92 |
+
### 🎭 Output Type Selection
|
| 93 |
+
|
| 94 |
+

|
| 95 |
+
|
| 96 |
+
### 💬 Generated Caption
|
| 97 |
+
|
| 98 |
+

|
| 99 |
+
|
| 100 |
+
### 📖 Generated Story
|
| 101 |
+
|
| 102 |
+

|
| 103 |
+
|
| 104 |
+
### 📖 Generated Poetic
|
| 105 |
+
|
| 106 |
+

|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
</details>
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
## 🚀 Quick Start
|
| 114 |
+
|
| 115 |
+
### ✅ Prerequisites
|
| 116 |
+
|
| 117 |
+
* Python 3.8+
|
| 118 |
+
* 4GB+ RAM (8GB recommended)
|
| 119 |
+
* Internet access (for first‑time model download)
|
| 120 |
+
|
| 121 |
+
### ⚙️ Installation & Run
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
git clone https://github.com/bhavyadoshi12/Imagify.git
|
| 125 |
+
cd Imagify
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
```bash
|
| 129 |
+
python -m venv .venv
|
| 130 |
+
source .venv/bin/activate # Windows: .venv\\Scripts\\activate
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
```bash
|
| 134 |
+
pip install -r requirements.txt
|
| 135 |
+
python app.py
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
🌐 Open **[http://localhost:5000](http://localhost:5000)** in your browser
|
| 139 |
+
|
| 140 |
+
---
|
| 141 |
+
|
| 142 |
+
## 🧠 How It Works (AI Pipeline)
|
| 143 |
+
|
| 144 |
+
```text
|
| 145 |
+
User uploads an image
|
| 146 |
+
↓
|
| 147 |
+
BLIP Vision‑Language Model
|
| 148 |
+
↓
|
| 149 |
+
Semantic context extraction (objects, mood, scene)
|
| 150 |
+
↓
|
| 151 |
+
Dynamic prompt generation (Story / Poem / Caption)
|
| 152 |
+
↓
|
| 153 |
+
AI‑enhanced narrative synthesis
|
| 154 |
+
↓
|
| 155 |
+
Final output rendered in UI
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
---
|
| 159 |
+
|
| 160 |
+
## 🛠️ Tech Stack
|
| 161 |
+
|
| 162 |
+
| Layer | Tools |
|
| 163 |
+
| --------- | ----------------------------------------- |
|
| 164 |
+
| Backend | Python, Flask |
|
| 165 |
+
| AI / ML | PyTorch, Hugging Face Transformers (BLIP) |
|
| 166 |
+
| Frontend | HTML, CSS, JavaScript |
|
| 167 |
+
| Utilities | Pillow, NumPy |
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## 🔮 Future Enhancements
|
| 172 |
+
|
| 173 |
+
* 🤖 LLM‑powered creative expansion (OpenAI / GPT)
|
| 174 |
+
* 🎚️ Creativity & tone controls
|
| 175 |
+
* ☁️ Dockerized cloud deployment
|
| 176 |
+
|
| 177 |
+
---
|
| 178 |
+
|
| 179 |
+
## 👨💻 Author
|
| 180 |
+
|
| 181 |
+
**Bhavya Doshi**
|
| 182 |
+
🔗 GitHub: [https://github.com/bhavyadoshi12](https://github.com/bhavyadoshi12)
|
| 183 |
+
|
| 184 |
+
---
|
| 185 |
+
|
| 186 |
+
⭐ If you found this project helpful, consider giving it a **star**!
|
app.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, jsonify
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import torch
|
| 4 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 5 |
+
import io
|
| 6 |
+
import base64
|
| 7 |
+
import os
|
| 8 |
+
import numpy as np
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import random
|
| 11 |
+
import re
|
| 12 |
+
|
| 13 |
+
app = Flask(__name__)
|
| 14 |
+
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10MB max file size
|
| 15 |
+
|
| 16 |
+
# Load models
|
| 17 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
print(f"🚀 Using device: {device}")
|
| 19 |
+
|
| 20 |
+
processor = None
|
| 21 |
+
blip_model = None
|
| 22 |
+
try:
|
| 23 |
+
print("📥 Loading BLIP model...")
|
| 24 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 25 |
+
blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 26 |
+
blip_model.to(device)
|
| 27 |
+
blip_model.eval()
|
| 28 |
+
print("✅ BLIP loaded successfully!")
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"❌ Error loading BLIP model: {e}")
|
| 31 |
+
processor = None
|
| 32 |
+
blip_model = None
|
| 33 |
+
|
| 34 |
+
# --- Templates for different styles (kept short so direct descriptions are copy/paste ready) ---
|
| 35 |
+
DIRECT_TEMPLATES = [
|
| 36 |
+
"{caption_sentence}",
|
| 37 |
+
"{subject} stands by the water.",
|
| 38 |
+
"A {subject} stands near the water's edge.",
|
| 39 |
+
"{subject} is standing in front of a body of water."
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
POETIC_TEMPLATES = [
|
| 43 |
+
"Where light and shadow dance in harmony, {caption_phrase}. Nature's poetry unfolds in silent verses that only the heart can hear.",
|
| 44 |
+
"In the gentle embrace of this serene moment, {caption_phrase}. Time stands still as beauty reveals its timeless secrets.",
|
| 45 |
+
"A poetic vision unfolds where {caption_phrase}. Each element whispers its own lyrical story to the soul."
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
CREATIVE_TEMPLATES = [
|
| 49 |
+
"In this captivating scene, {caption_phrase}. The atmosphere is filled with a sense of wonder that sparks the imagination.",
|
| 50 |
+
"As you gaze upon this view, {caption_phrase}. It feels like the beginning of a small, gentle story.",
|
| 51 |
+
"This moment captures {caption_phrase}. The world seems to pause and listen."
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
CAPTION_TEMPLATES = [
|
| 55 |
+
"✨ {caption_short} | A moment worth remembering",
|
| 56 |
+
"📸 {caption_short} - Capturing life's beautiful moments",
|
| 57 |
+
"🌟 {caption_short} | Where every detail tells a story"
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
ADJECTIVES = ["gentle", "calm", "majestic", "quiet", "serene", "stoic"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Utility: sanitize and shorten caption for short usage
|
| 64 |
+
def shorten_caption(caption, max_words=7):
|
| 65 |
+
if not caption:
|
| 66 |
+
return ""
|
| 67 |
+
# remove parentheses and extra whitespace
|
| 68 |
+
s = re.sub(r"[\(\)\[\]]", "", caption).strip()
|
| 69 |
+
words = s.split()
|
| 70 |
+
if len(words) <= max_words:
|
| 71 |
+
return s
|
| 72 |
+
return " ".join(words[:max_words]) + "..."
|
| 73 |
+
|
| 74 |
+
# Utility: convert BLIP caption to a present-tense single sentence
|
| 75 |
+
def caption_to_present_sentence(caption):
|
| 76 |
+
if not caption:
|
| 77 |
+
return ""
|
| 78 |
+
text = caption.strip()
|
| 79 |
+
# remove trailing punctuation
|
| 80 |
+
text = re.sub(r"[\.!?]+$", "", text).strip()
|
| 81 |
+
# Try to simplify the caption:
|
| 82 |
+
# If caption contains "standing", "sitting", "running" -> change to "stands", "sits", "runs"
|
| 83 |
+
# naive substitution for common gerunds -> present tense
|
| 84 |
+
subs = {
|
| 85 |
+
r'\bstanding\b': 'stands',
|
| 86 |
+
r'\bsitting\b': 'sits',
|
| 87 |
+
r'\brunning\b': 'runs',
|
| 88 |
+
r'\bwalking\b': 'walks',
|
| 89 |
+
r'\bflying\b': 'flies',
|
| 90 |
+
r'\blying\b': 'lies',
|
| 91 |
+
r'\bplaying\b': 'plays'
|
| 92 |
+
}
|
| 93 |
+
s = text.lower()
|
| 94 |
+
for patt, rep in subs.items():
|
| 95 |
+
s = re.sub(patt, rep, s)
|
| 96 |
+
# Capitalize first letter
|
| 97 |
+
s = s.strip()
|
| 98 |
+
if not s:
|
| 99 |
+
return ""
|
| 100 |
+
s = s[0].upper() + s[1:]
|
| 101 |
+
# add period if missing
|
| 102 |
+
if not re.search(r'[\.!?]$', s):
|
| 103 |
+
s = s + '.'
|
| 104 |
+
# Basic fix: if starts with 'an ' or 'a ' keep it
|
| 105 |
+
return s
|
| 106 |
+
|
| 107 |
+
# Helper: extract a short subject noun phrase (very naive fallback; replace with real detector if available)
|
| 108 |
+
def extract_subject_from_caption(caption):
|
| 109 |
+
if not caption:
|
| 110 |
+
return "subject"
|
| 111 |
+
# look for pattern like "a/an <noun>" or first noun-like word
|
| 112 |
+
caption = caption.lower()
|
| 113 |
+
m = re.search(r'\b(an|a)\s+([a-z\-]+)', caption)
|
| 114 |
+
if m:
|
| 115 |
+
return m.group(2)
|
| 116 |
+
# else take first word
|
| 117 |
+
first_word = caption.split()[0]
|
| 118 |
+
# strip adjectives if common
|
| 119 |
+
first_word = re.sub(r'^(the|this|that|these|those)\s+', '', first_word)
|
| 120 |
+
return first_word
|
| 121 |
+
|
| 122 |
+
# Core generator: given an image and style plus seeds/temperature, return caption & story
|
| 123 |
+
def generate_story_from_image(image_pil, style="creative", variation_seed=None, request_id=None, temperature=0.7):
|
| 124 |
+
# Seed RNG deterministically so repeated calls with same seed yield same output
|
| 125 |
+
if variation_seed is not None:
|
| 126 |
+
try:
|
| 127 |
+
seed = int(variation_seed) & 0x7fffffff
|
| 128 |
+
except:
|
| 129 |
+
seed = int(datetime.utcnow().timestamp() * 1000) ^ (hash(request_id) & 0xffffffff)
|
| 130 |
+
else:
|
| 131 |
+
seed = int(datetime.utcnow().timestamp() * 1000) ^ (hash(request_id) & 0xffffffff)
|
| 132 |
+
rnd = random.Random(seed)
|
| 133 |
+
|
| 134 |
+
# 1) Generate caption using BLIP (if available); otherwise fallback to a placeholder
|
| 135 |
+
caption = ""
|
| 136 |
+
try:
|
| 137 |
+
if processor is not None and blip_model is not None:
|
| 138 |
+
inputs = processor(image_pil, return_tensors="pt").to(device)
|
| 139 |
+
with torch.no_grad():
|
| 140 |
+
out_ids = blip_model.generate(**inputs, max_length=50, num_beams=5, early_stopping=True)
|
| 141 |
+
caption = processor.decode(out_ids[0], skip_special_tokens=True)
|
| 142 |
+
else:
|
| 143 |
+
caption = "an object near water"
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print("❌ BLIP captioning failed:", e)
|
| 146 |
+
caption = "an object near water"
|
| 147 |
+
|
| 148 |
+
# Prepare variants for template filling
|
| 149 |
+
caption_short = shorten_caption(caption, max_words=6)
|
| 150 |
+
caption_phrase = caption_short
|
| 151 |
+
caption_sentence = caption_to_present_sentence(caption) # single present-tense sentence
|
| 152 |
+
|
| 153 |
+
# subject extraction for direct templates
|
| 154 |
+
subject = extract_subject_from_caption(caption)
|
| 155 |
+
if not subject:
|
| 156 |
+
subject = "subject"
|
| 157 |
+
|
| 158 |
+
# Choose template list based on style
|
| 159 |
+
style_key = (style or "creative").lower()
|
| 160 |
+
if style_key in ("direct", "direct_description", "description"):
|
| 161 |
+
templates = DIRECT_TEMPLATES
|
| 162 |
+
# For direct we prefer the caption_sentence as highest priority
|
| 163 |
+
# But still vary templates using seed
|
| 164 |
+
elif style_key == "poetic":
|
| 165 |
+
templates = POETIC_TEMPLATES
|
| 166 |
+
elif style_key == "caption":
|
| 167 |
+
templates = CAPTION_TEMPLATES
|
| 168 |
+
elif style_key == "creative":
|
| 169 |
+
templates = CREATIVE_TEMPLATES
|
| 170 |
+
else:
|
| 171 |
+
templates = CREATIVE_TEMPLATES
|
| 172 |
+
|
| 173 |
+
# Use rnd to pick template (ensures variations)
|
| 174 |
+
chosen_template = rnd.choice(templates)
|
| 175 |
+
|
| 176 |
+
# For direct: ensure we prefer the short present sentence if template contains {caption_sentence}
|
| 177 |
+
try:
|
| 178 |
+
story = chosen_template.format(
|
| 179 |
+
caption=caption,
|
| 180 |
+
caption_short=caption_short,
|
| 181 |
+
caption_phrase=caption_phrase,
|
| 182 |
+
caption_sentence=caption_sentence,
|
| 183 |
+
subject=subject
|
| 184 |
+
)
|
| 185 |
+
except Exception as e:
|
| 186 |
+
# fallback simple composition
|
| 187 |
+
story = caption_sentence if style_key.startswith("direct") else caption
|
| 188 |
+
|
| 189 |
+
# Slight random adjective insertion for non-caption styles (keeps direct minimal)
|
| 190 |
+
if style_key not in ("caption", "direct"):
|
| 191 |
+
if rnd.random() < 0.35:
|
| 192 |
+
adj = rnd.choice(ADJECTIVES)
|
| 193 |
+
# insert adjective before first noun/subject if possible
|
| 194 |
+
if "{subject}" in chosen_template:
|
| 195 |
+
story = story.replace(subject, f"{adj} {subject}", 1)
|
| 196 |
+
|
| 197 |
+
# Final cleanup
|
| 198 |
+
story = story.strip()
|
| 199 |
+
# Ensure story ends with punctuation
|
| 200 |
+
if not re.search(r'[\.!?]$', story):
|
| 201 |
+
story = story + '.'
|
| 202 |
+
|
| 203 |
+
return caption, story, seed
|
| 204 |
+
|
| 205 |
+
# Routes
|
| 206 |
+
@app.route('/')
|
| 207 |
+
def home():
|
| 208 |
+
print("🏠 Home page accessed")
|
| 209 |
+
return render_template('index.html')
|
| 210 |
+
|
| 211 |
+
@app.route('/about')
|
| 212 |
+
def about():
|
| 213 |
+
return render_template('about.html')
|
| 214 |
+
|
| 215 |
+
@app.route('/working')
|
| 216 |
+
def working():
|
| 217 |
+
return render_template('working.html')
|
| 218 |
+
|
| 219 |
+
@app.route('/generate', methods=['POST'])
|
| 220 |
+
def generate():
|
| 221 |
+
try:
|
| 222 |
+
print("🔄 /generate called")
|
| 223 |
+
if 'image' not in request.files:
|
| 224 |
+
print("❌ No image in request")
|
| 225 |
+
return jsonify({'success': False, 'error': 'No image uploaded'})
|
| 226 |
+
|
| 227 |
+
image_file = request.files['image']
|
| 228 |
+
style = request.form.get('style', 'creative')
|
| 229 |
+
variation_seed = request.form.get('variation_seed') or request.form.get('seed') or None
|
| 230 |
+
request_id = request.form.get('request_id') or ''
|
| 231 |
+
temperature = request.form.get('temperature')
|
| 232 |
+
try:
|
| 233 |
+
temperature = float(temperature) if temperature is not None else 0.7
|
| 234 |
+
except:
|
| 235 |
+
temperature = 0.7
|
| 236 |
+
|
| 237 |
+
print(f"📁 Received file: {image_file.filename}")
|
| 238 |
+
print(f"🎨 Style requested: {style}")
|
| 239 |
+
print(f"🔑 variation_seed: {variation_seed} request_id: {request_id} temp:{temperature}")
|
| 240 |
+
|
| 241 |
+
if image_file.filename == '':
|
| 242 |
+
print("❌ Empty filename")
|
| 243 |
+
return jsonify({'success': False, 'error': 'No image selected'})
|
| 244 |
+
|
| 245 |
+
# load image
|
| 246 |
+
image = Image.open(image_file.stream).convert('RGB')
|
| 247 |
+
print("✅ Image loaded into PIL.Image")
|
| 248 |
+
|
| 249 |
+
# Generate caption/story with deterministic variation
|
| 250 |
+
caption, story, seed_used = generate_story_from_image(
|
| 251 |
+
image_pil=image,
|
| 252 |
+
style=style,
|
| 253 |
+
variation_seed=variation_seed,
|
| 254 |
+
request_id=request_id,
|
| 255 |
+
temperature=temperature
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# Convert image to base64 for display
|
| 259 |
+
buffered = io.BytesIO()
|
| 260 |
+
image.save(buffered, format="JPEG", quality=85)
|
| 261 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 262 |
+
|
| 263 |
+
response_data = {
|
| 264 |
+
'success': True,
|
| 265 |
+
'caption': caption,
|
| 266 |
+
'story': story,
|
| 267 |
+
'style': style,
|
| 268 |
+
'image_data': f"data:image/jpeg;base64,{img_str}",
|
| 269 |
+
'timestamp': datetime.now().isoformat(),
|
| 270 |
+
'seed_used': seed_used
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
print("✅ /generate response prepared:", response_data.get('story')[:120], "...")
|
| 274 |
+
return jsonify(response_data)
|
| 275 |
+
|
| 276 |
+
except Exception as e:
|
| 277 |
+
print("❌ Error in /generate:", e)
|
| 278 |
+
return jsonify({'success': False, 'error': str(e)})
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@app.route('/health')
|
| 282 |
+
def health():
|
| 283 |
+
models_loaded = (processor is not None and blip_model is not None)
|
| 284 |
+
return jsonify({
|
| 285 |
+
'status': 'healthy' if models_loaded else 'models_missing',
|
| 286 |
+
'models_loaded': models_loaded,
|
| 287 |
+
'device': str(device)
|
| 288 |
+
})
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == '__main__':
|
| 292 |
+
print("🚀 Starting ImagifyAI Server...")
|
| 293 |
+
print("📍 Home: http://localhost:5000")
|
| 294 |
+
print("📍 Health: http://localhost:5000/health")
|
| 295 |
+
print("🔥 Debug mode: ON")
|
| 296 |
+
app.run(debug=True, host='0.0.0.0', port=5000)
|
generate_server.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# generate_server.py
|
| 2 |
+
from flask import Flask, request, jsonify
|
| 3 |
+
import random, base64
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# Simple variation helpers
|
| 10 |
+
DIRECT_TEMPLATES = [
|
| 11 |
+
"{subject} stands in front of a body of water.",
|
| 12 |
+
"{subject} is standing by the water, facing the camera.",
|
| 13 |
+
"An {subject} stands near the water's edge, looking calm.",
|
| 14 |
+
"{subject} stands at the bank of a water body under the sky.",
|
| 15 |
+
"A lone {subject} stands before a reflective body of water."
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
POETIC_TEMPLATES = [
|
| 19 |
+
"Where light and shadow meet, {subject} stands before the mirrored water.",
|
| 20 |
+
"Sunset breathes over the water while {subject} stands, a quiet poem in motion.",
|
| 21 |
+
"By the water's hush, {subject} waits as nature hums its soft verses.",
|
| 22 |
+
"Beneath the dwindling sun, {subject} becomes a silhouette of patient grace before the water."
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
CREATIVE_TEMPLATES = [
|
| 26 |
+
"In a quiet moment, {subject} pauses by the water — as if listening to old stories.",
|
| 27 |
+
"{subject} and the water share a secret under the wide sky.",
|
| 28 |
+
"An ordinary day turns gentle as {subject} meets the horizon of the water.",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
CAPTION_TEMPLATES = [
|
| 32 |
+
"{subject} at the water — nature's calm moment.",
|
| 33 |
+
"{subject} by the water. #serene #nature",
|
| 34 |
+
"{subject} — a peaceful scene."
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
# small function to pick a subject phrase by simple heuristics (could be replaced by image captioner)
|
| 38 |
+
def quick_detect_subject_from_image(file_bytes):
|
| 39 |
+
# QUICK fallback: don't try heavy vision here. For demo, return 'elephant' if filename hints or default 'subject'
|
| 40 |
+
# If the request includes a filename you can inspect request.files['image'].filename
|
| 41 |
+
return "elephant" # change if you have image caption code; keep simple for demo
|
| 42 |
+
|
| 43 |
+
@app.route('/generate', methods=['POST'])
|
| 44 |
+
def generate():
|
| 45 |
+
# read fields
|
| 46 |
+
style = request.form.get('style', 'direct').lower()
|
| 47 |
+
variation = request.form.get('variation', 'false').lower() == 'true'
|
| 48 |
+
request_id = request.form.get('request_id', '') # optional
|
| 49 |
+
variation_seed = request.form.get('variation_seed')
|
| 50 |
+
temperature = request.form.get('temperature') # optional hint
|
| 51 |
+
|
| 52 |
+
# read uploaded image (optional: return it back as data-uri)
|
| 53 |
+
image_data_uri = ""
|
| 54 |
+
if 'image' in request.files:
|
| 55 |
+
f = request.files['image']
|
| 56 |
+
raw = f.read()
|
| 57 |
+
# return the uploaded image back as base64 so client can display it (not required)
|
| 58 |
+
try:
|
| 59 |
+
image_data_uri = "data:image/jpeg;base64," + base64.b64encode(raw).decode('utf-8')
|
| 60 |
+
except Exception:
|
| 61 |
+
image_data_uri = ""
|
| 62 |
+
|
| 63 |
+
# choose seed
|
| 64 |
+
if variation_seed:
|
| 65 |
+
try:
|
| 66 |
+
seed = int(variation_seed) % (2**31 - 1)
|
| 67 |
+
except:
|
| 68 |
+
seed = int(datetime.utcnow().timestamp() * 1000) ^ (hash(request_id) & 0xffffffff)
|
| 69 |
+
else:
|
| 70 |
+
seed = int(datetime.utcnow().timestamp() * 1000) ^ (hash(request_id) & 0xffffffff)
|
| 71 |
+
|
| 72 |
+
rnd = random.Random(seed)
|
| 73 |
+
|
| 74 |
+
# Quick subject detection (replace with your model if available)
|
| 75 |
+
subject = quick_detect_subject_from_image(raw if 'raw' in locals() else None)
|
| 76 |
+
|
| 77 |
+
# Pick template set
|
| 78 |
+
templates = DIRECT_TEMPLATES
|
| 79 |
+
if style == 'poetic':
|
| 80 |
+
templates = POETIC_TEMPLATES
|
| 81 |
+
elif style == 'creative':
|
| 82 |
+
templates = CREATIVE_TEMPLATES
|
| 83 |
+
elif style == 'caption':
|
| 84 |
+
templates = CAPTION_TEMPLATES
|
| 85 |
+
else:
|
| 86 |
+
templates = DIRECT_TEMPLATES
|
| 87 |
+
|
| 88 |
+
# Variation: if variation requested, change selection logic to ensure different template often
|
| 89 |
+
# Use rnd.choice to vary; because rnd seeded differently on each request, choice will differ
|
| 90 |
+
chosen = rnd.choice(templates)
|
| 91 |
+
|
| 92 |
+
# Small extra variation: maybe add an adjective randomly (for direct style keep minimal)
|
| 93 |
+
adjectives = ["majestic", "gentle", "calm", "quiet", "stoic", "grand"]
|
| 94 |
+
adj = ""
|
| 95 |
+
if style != 'caption' and rnd.random() < 0.3:
|
| 96 |
+
adj = rnd.choice(adjectives)
|
| 97 |
+
# insert adjective if template supports
|
| 98 |
+
if "{subject}" in chosen:
|
| 99 |
+
chosen = chosen.replace("{subject}", f"{adj} {subject}")
|
| 100 |
+
else:
|
| 101 |
+
chosen = chosen.format(subject=subject)
|
| 102 |
+
|
| 103 |
+
# ensure if any leftover placeholder exists
|
| 104 |
+
try:
|
| 105 |
+
story = chosen.format(subject=subject)
|
| 106 |
+
except:
|
| 107 |
+
story = chosen
|
| 108 |
+
|
| 109 |
+
# Return JSON
|
| 110 |
+
return jsonify({
|
| 111 |
+
"success": True,
|
| 112 |
+
"story": story,
|
| 113 |
+
"image_data": image_data_uri,
|
| 114 |
+
"request_id": request_id,
|
| 115 |
+
"seed_used": seed
|
| 116 |
+
})
|
| 117 |
+
|
| 118 |
+
if __name__ == '__main__':
|
| 119 |
+
app.run(debug=True, port=8000)
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
torch
|
| 3 |
+
transformers
|
| 4 |
+
Pillow
|
| 5 |
+
numpy
|
| 6 |
+
gunicorn
|
run.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
ImagifyAI - Image to Story Generator
|
| 4 |
+
Startup script for the application
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
from app import app
|
| 10 |
+
|
| 11 |
+
def main():
|
| 12 |
+
print("🎨 ImagifyAI - Image to Story Generator")
|
| 13 |
+
print("=" * 50)
|
| 14 |
+
|
| 15 |
+
# Check if models directory exists
|
| 16 |
+
if not os.path.exists('models'):
|
| 17 |
+
print("⚠️ Models directory not found.")
|
| 18 |
+
print("📥 Please make sure you have the trained models in the 'models' folder")
|
| 19 |
+
print("💡 You can download pre-trained models or train your own")
|
| 20 |
+
|
| 21 |
+
# Check requirements
|
| 22 |
+
try:
|
| 23 |
+
import torch
|
| 24 |
+
import transformers
|
| 25 |
+
import flask
|
| 26 |
+
print("✅ All dependencies are available")
|
| 27 |
+
except ImportError as e:
|
| 28 |
+
print(f"❌ Missing dependency: {e}")
|
| 29 |
+
print("💡 Run: pip install -r requirements.txt")
|
| 30 |
+
sys.exit(1)
|
| 31 |
+
|
| 32 |
+
print("\n🚀 Starting server...")
|
| 33 |
+
print("📍 Local: http://localhost:5000")
|
| 34 |
+
print("📍 Network: http://0.0.0.0:5000")
|
| 35 |
+
print("⏹️ Press Ctrl+C to stop the server\n")
|
| 36 |
+
|
| 37 |
+
# Start Flask app
|
| 38 |
+
port = int(os.environ.get('PORT', 5000))
|
| 39 |
+
app.run(debug=True, host='0.0.0.0', port=port)
|
| 40 |
+
|
| 41 |
+
if __name__ == '__main__':
|
| 42 |
+
main()
|