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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from transformers import LlavaForConditionalGeneration, AutoProcessor
|
| 5 |
+
import logging
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
import uuid
|
| 10 |
+
import spacy
|
| 11 |
+
from spacy.cli import download
|
| 12 |
+
import zipfile
|
| 13 |
+
import shutil
|
| 14 |
+
|
| 15 |
+
# Set up logging
|
| 16 |
+
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Define paths
|
| 20 |
+
OUTPUT_JSON_PATH = "captions.json"
|
| 21 |
+
UPLOAD_DIR = "uploads"
|
| 22 |
+
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 23 |
+
|
| 24 |
+
# Load SpaCy model for keyword extraction
|
| 25 |
+
try:
|
| 26 |
+
try:
|
| 27 |
+
nlp = spacy.load("en_core_web_sm")
|
| 28 |
+
except OSError:
|
| 29 |
+
logger.info("Downloading en_core_web_sm model...")
|
| 30 |
+
download("en_core_web_sm")
|
| 31 |
+
nlp = spacy.load("en_core_web_sm")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
logger.error(f"Error loading SpaCy model: {str(e)}")
|
| 34 |
+
raise
|
| 35 |
+
|
| 36 |
+
# Load LLAVA model and processor
|
| 37 |
+
MODEL_PATH = "fancyfeast/llama-joycaption-beta-one-hf-llava"
|
| 38 |
+
try:
|
| 39 |
+
processor = AutoProcessor.from_pretrained(MODEL_PATH)
|
| 40 |
+
model = LlavaForConditionalGeneration.from_pretrained(
|
| 41 |
+
MODEL_PATH,
|
| 42 |
+
torch_dtype=torch.float16,
|
| 43 |
+
low_cpu_mem_usage=True,
|
| 44 |
+
device_map="auto"
|
| 45 |
+
)
|
| 46 |
+
model.eval()
|
| 47 |
+
logger.info("Model and processor loaded successfully.")
|
| 48 |
+
except Exception as e:
|
| 49 |
+
logger.error(f"Error loading model: {str(e)}")
|
| 50 |
+
raise
|
| 51 |
+
|
| 52 |
+
# Function to extract keywords
|
| 53 |
+
def extract_keywords(text):
|
| 54 |
+
try:
|
| 55 |
+
doc = nlp(text)
|
| 56 |
+
keywords = [token.text.lower() for token in doc if token.pos_ in ["NOUN", "ADJ"] and not token.is_stop]
|
| 57 |
+
return list(set(keywords))[:5]
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"Error extracting keywords: {str(e)}")
|
| 60 |
+
return []
|
| 61 |
+
|
| 62 |
+
# Function to save metadata to JSON
|
| 63 |
+
def save_to_json(image_name, caption, caption_type, custom_prompt, keywords, error=None):
|
| 64 |
+
result = {
|
| 65 |
+
"image_name": image_name,
|
| 66 |
+
"caption": caption,
|
| 67 |
+
"caption_type": caption_type,
|
| 68 |
+
"custom_prompt": custom_prompt,
|
| 69 |
+
"keywords": keywords,
|
| 70 |
+
"timestamp": datetime.now().isoformat(),
|
| 71 |
+
"error": error
|
| 72 |
+
}
|
| 73 |
+
try:
|
| 74 |
+
if os.path.exists(OUTPUT_JSON_PATH):
|
| 75 |
+
with open(OUTPUT_JSON_PATH, "r") as f:
|
| 76 |
+
data = json.load(f)
|
| 77 |
+
else:
|
| 78 |
+
data = []
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.error(f"Error reading JSON file: {str(e)}")
|
| 81 |
+
data = []
|
| 82 |
+
|
| 83 |
+
data.append(result)
|
| 84 |
+
try:
|
| 85 |
+
with open(OUTPUT_JSON_PATH, "w") as f:
|
| 86 |
+
json.dump(data, f, indent=4)
|
| 87 |
+
logger.info(f"Saved result to {OUTPUT_JSON_PATH}")
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logger.error(f"Error writing to JSON file: {str(e)}")
|
| 90 |
+
|
| 91 |
+
# Function to process single image
|
| 92 |
+
def process_single_image(image, caption_type, custom_prompt):
|
| 93 |
+
if image is None:
|
| 94 |
+
error_msg = "Please upload an image."
|
| 95 |
+
save_to_json("unknown", error_msg, caption_type, custom_prompt, [], error=error_msg)
|
| 96 |
+
return error_msg
|
| 97 |
+
|
| 98 |
+
image_name = os.path.join(UPLOAD_DIR, f"image_{uuid.uuid4().hex}.jpg")
|
| 99 |
+
image.save(image_name)
|
| 100 |
+
|
| 101 |
+
try:
|
| 102 |
+
image = image.resize((256, 256))
|
| 103 |
+
prompt = custom_prompt.strip() if custom_prompt.strip() else f"Write a {caption_type} caption for this image."
|
| 104 |
+
convo = [
|
| 105 |
+
{"role": "system", "content": "You are a helpful assistant that generates accurate and relevant image captions."},
|
| 106 |
+
{"role": "user", "content": prompt.strip()}
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
inputs = processor(images=image, text=convo[1]["content"], return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 110 |
+
|
| 111 |
+
with torch.no_grad():
|
| 112 |
+
output = model.generate(**inputs, max_new_tokens=50, temperature=0.7, top_p=0.9)
|
| 113 |
+
|
| 114 |
+
caption = processor.decode(output[0], skip_special_tokens=True).strip()
|
| 115 |
+
keywords = extract_keywords(caption)
|
| 116 |
+
|
| 117 |
+
save_to_json(image_name, caption, caption_type, custom_prompt, keywords, error=None)
|
| 118 |
+
return f"Caption: {caption}\nKeywords: {', '.join(keywords)}"
|
| 119 |
+
except Exception as e:
|
| 120 |
+
error_msg = f"Error generating caption: {str(e)}"
|
| 121 |
+
logger.error(error_msg)
|
| 122 |
+
save_to_json(image_name, "", caption_type, custom_prompt, [], error=error_msg)
|
| 123 |
+
return error_msg
|
| 124 |
+
|
| 125 |
+
# Function to process batch images
|
| 126 |
+
def process_batch_images(zip_file, caption_type, custom_prompt):
|
| 127 |
+
if zip_file is None:
|
| 128 |
+
return "Please upload a zip file."
|
| 129 |
+
|
| 130 |
+
temp_dir = "temp_upload"
|
| 131 |
+
os.makedirs(temp_dir, exist_ok=True)
|
| 132 |
+
results = []
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
with zipfile.ZipFile(zip_file.name, "r") as zip_ref:
|
| 136 |
+
zip_ref.extractall(temp_dir)
|
| 137 |
+
|
| 138 |
+
for root, _, files in os.walk(temp_dir):
|
| 139 |
+
for file in files:
|
| 140 |
+
if file.lower().endswith((".jpg", ".jpeg", ".png")):
|
| 141 |
+
image_path = os.path.join(root, file)
|
| 142 |
+
image_name = os.path.join(UPLOAD_DIR, f"image_{uuid.uuid4().hex}.jpg")
|
| 143 |
+
shutil.copy(image_path, image_name)
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
image = Image.open(image_path).convert("RGB").resize((256, 256))
|
| 147 |
+
prompt = custom_prompt.strip() if custom_prompt.strip() else f"Write a {caption_type} caption for this image."
|
| 148 |
+
convo = [
|
| 149 |
+
{"role": "system", "content": "You are a helpful assistant that generates accurate and relevant image captions."},
|
| 150 |
+
{"role": "user", "content": prompt.strip()}
|
| 151 |
+
]
|
| 152 |
+
|
| 153 |
+
inputs = processor(images=image, text=convo[1]["content"], return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 154 |
+
|
| 155 |
+
with torch.no_grad():
|
| 156 |
+
output = model.generate(**inputs, max_new_tokens=50, temperature=0.7, top_p=0.9)
|
| 157 |
+
|
| 158 |
+
caption = processor.decode(output[0], skip_special_tokens=True).strip()
|
| 159 |
+
keywords = extract_keywords(caption)
|
| 160 |
+
|
| 161 |
+
save_to_json(image_name, caption, caption_type, custom_prompt, keywords, error=None)
|
| 162 |
+
results.append(f"Image: {image_name}\nCaption: {caption}\nKeywords: {', '.join(keywords)}")
|
| 163 |
+
except Exception as e:
|
| 164 |
+
error_msg = f"Error processing {image_path}: {str(e)}"
|
| 165 |
+
logger.error(error_msg)
|
| 166 |
+
save_to_json(image_name, "", caption_type, custom_prompt, [], error=error_msg)
|
| 167 |
+
results.append(error_msg)
|
| 168 |
+
|
| 169 |
+
shutil.rmtree(temp_dir)
|
| 170 |
+
return "\n\n".join(results)
|
| 171 |
+
except Exception as e:
|
| 172 |
+
error_msg = f"Error processing batch: {str(e)}"
|
| 173 |
+
logger.error(error_msg)
|
| 174 |
+
return error_msg
|
| 175 |
+
|
| 176 |
+
# Function to search images
|
| 177 |
+
def search_images(query):
|
| 178 |
+
try:
|
| 179 |
+
if not os.path.exists(OUTPUT_JSON_PATH):
|
| 180 |
+
return "No captions available."
|
| 181 |
+
|
| 182 |
+
with open(OUTPUT_JSON_PATH, "r") as f:
|
| 183 |
+
data = json.load(f)
|
| 184 |
+
|
| 185 |
+
results = []
|
| 186 |
+
for entry in data:
|
| 187 |
+
if query.lower() in entry["caption"].lower() or any(query.lower() in kw.lower() for kw in entry["keywords"]):
|
| 188 |
+
results.append((entry["image_name"], f"Caption: {entry['caption']}\nKeywords: {', '.join(entry['keywords'])}"))
|
| 189 |
+
|
| 190 |
+
return results if results else "No matches found."
|
| 191 |
+
except Exception as e:
|
| 192 |
+
logger.error(f"Error searching images: {str(e)}")
|
| 193 |
+
return f"Error searching images: {str(e)}"
|
| 194 |
+
|
| 195 |
+
# Gradio interface
|
| 196 |
+
interface = gr.Interface(
|
| 197 |
+
fn=[process_single_image, process_batch_images, search_images],
|
| 198 |
+
inputs=[
|
| 199 |
+
[gr.Image(label="Upload Single Image", type="pil"), gr.Dropdown(choices=["descriptive", "poetic", "humorous"], label="Caption Style", value="descriptive"), gr.Textbox(label="Custom Prompt (optional)", placeholder="e.g., 'Write a poetic caption'")],
|
| 200 |
+
[gr.File(label="Upload Zip File for Batch Processing", file_types=[".zip"]), gr.Dropdown(choices=["descriptive", "poetic", "humorous"], label="Caption Style", value="descriptive"), gr.Textbox(label="Custom Prompt (optional)", placeholder="e.g., 'Write a poetic caption'")],
|
| 201 |
+
[gr.Textbox(label="Search Query", placeholder="e.g., 'beach'")]
|
| 202 |
+
],
|
| 203 |
+
outputs=[
|
| 204 |
+
gr.Textbox(label="Single Image Result"),
|
| 205 |
+
gr.Textbox(label="Batch Processing Results"),
|
| 206 |
+
gr.Gallery(label="Search Results")
|
| 207 |
+
],
|
| 208 |
+
title="Image Captioning with LLAVA",
|
| 209 |
+
description="Upload single or batch images, generate captions with custom styles, and search by captions or keywords. Results are saved to captions.json."
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
if __name__ == "__main__":
|
| 213 |
+
interface.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.0
|
| 2 |
+
transformers==4.46.0
|
| 3 |
+
torch==2.4.1
|
| 4 |
+
Pillow==10.4.0
|
| 5 |
+
accelerate==0.34.2
|
| 6 |
+
spacy==3.7.6
|
| 7 |
+
en-core-web-sm==3.7.0
|