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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Gradio interface for multi-image processing with Qwen2-VL model
|
| 4 |
+
"""
|
| 5 |
import gradio as gr
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import logging
|
| 10 |
+
from typing import List, Dict, Any
|
| 11 |
+
import asyncio
|
| 12 |
+
from PIL import Image
|
| 13 |
+
import io
|
| 14 |
+
import base64
|
| 15 |
|
| 16 |
+
# Add the backend directory to Python path
|
| 17 |
+
backend_dir = Path(__file__).parent
|
| 18 |
+
sys.path.append(str(backend_dir))
|
| 19 |
+
|
| 20 |
+
# Import the image processor
|
| 21 |
+
try:
|
| 22 |
+
from app.services.ai.images.image_processor import ImageProcessor
|
| 23 |
+
except ImportError as e:
|
| 24 |
+
print(f"Import error: {e}")
|
| 25 |
+
# Fallback for direct execution
|
| 26 |
+
ImageProcessor = None
|
| 27 |
+
|
| 28 |
+
# Configure logging
|
| 29 |
+
logging.basicConfig(level=logging.INFO)
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
class GradioImageProcessor:
|
| 33 |
+
def __init__(self, use_api: bool = True, api_key: str = None):
|
| 34 |
+
"""
|
| 35 |
+
Initialize the Gradio image processor
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
use_api: Whether to use API mode (True) or local model (False)
|
| 39 |
+
api_key: Hugging Face API key for API mode
|
| 40 |
+
"""
|
| 41 |
+
self.use_api = use_api
|
| 42 |
+
self.api_key = api_key or os.getenv("HF_API_KEY")
|
| 43 |
+
|
| 44 |
+
if use_api and not self.api_key:
|
| 45 |
+
logger.warning("No API key provided. Please set HF_API_KEY environment variable.")
|
| 46 |
+
|
| 47 |
+
# Initialize the image processor
|
| 48 |
+
if ImageProcessor:
|
| 49 |
+
try:
|
| 50 |
+
self.processor = ImageProcessor()
|
| 51 |
+
logger.info("Image processor initialized successfully")
|
| 52 |
+
except Exception as e:
|
| 53 |
+
logger.error(f"Failed to initialize image processor: {e}")
|
| 54 |
+
self.processor = None
|
| 55 |
+
else:
|
| 56 |
+
self.processor = None
|
| 57 |
+
logger.warning("ImageProcessor not available")
|
| 58 |
+
|
| 59 |
+
def process_single_image(self, image: Image.Image, prompt: str = "Describe this image in detail.") -> str:
|
| 60 |
+
"""
|
| 61 |
+
Process a single image with the given prompt
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
image: PIL Image object
|
| 65 |
+
prompt: Text prompt for the model
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
Generated description
|
| 69 |
+
"""
|
| 70 |
+
if not self.processor:
|
| 71 |
+
return "β Image processor not available"
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
# Convert PIL image to bytes for processing
|
| 75 |
+
img_byte_arr = io.BytesIO()
|
| 76 |
+
image.save(img_byte_arr, format='JPEG')
|
| 77 |
+
img_byte_arr = img_byte_arr.getvalue()
|
| 78 |
+
|
| 79 |
+
# Create a temporary file-like object
|
| 80 |
+
img_io = io.BytesIO(img_byte_arr)
|
| 81 |
+
img_io.seek(0)
|
| 82 |
+
|
| 83 |
+
# Process the image
|
| 84 |
+
result = self.processor._process_single_image(
|
| 85 |
+
image_data=img_io,
|
| 86 |
+
prompt_text=prompt
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
logger.error(f"Error processing image: {e}")
|
| 93 |
+
return f"β Error processing image: {str(e)}"
|
| 94 |
+
|
| 95 |
+
def process_multiple_images(self, images: List[Image.Image], prompt: str = "Describe each image in detail.") -> List[str]:
|
| 96 |
+
"""
|
| 97 |
+
Process multiple images with the same prompt
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
images: List of PIL Image objects
|
| 101 |
+
prompt: Text prompt for the model
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
List of generated descriptions
|
| 105 |
+
"""
|
| 106 |
+
if not self.processor:
|
| 107 |
+
return ["β Image processor not available"] * len(images)
|
| 108 |
+
|
| 109 |
+
results = []
|
| 110 |
+
for i, image in enumerate(images):
|
| 111 |
+
try:
|
| 112 |
+
result = self.process_single_image(image, prompt)
|
| 113 |
+
results.append(f"Image {i+1}: {result}")
|
| 114 |
+
except Exception as e:
|
| 115 |
+
logger.error(f"Error processing image {i+1}: {e}")
|
| 116 |
+
results.append(f"Image {i+1}: β Error - {str(e)}")
|
| 117 |
+
|
| 118 |
+
return results
|
| 119 |
+
|
| 120 |
+
def create_gradio_interface():
|
| 121 |
+
"""
|
| 122 |
+
Create the Gradio interface
|
| 123 |
+
"""
|
| 124 |
+
# Initialize the processor
|
| 125 |
+
processor = GradioImageProcessor(use_api=True)
|
| 126 |
|
| 127 |
+
def process_images(images, prompt, api_key):
|
| 128 |
+
"""
|
| 129 |
+
Process uploaded images
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
images: List of uploaded images
|
| 133 |
+
prompt: User-provided prompt
|
| 134 |
+
api_key: Optional API key override
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
List of descriptions
|
| 138 |
+
"""
|
| 139 |
+
if not images:
|
| 140 |
+
return "Please upload at least one image."
|
| 141 |
+
|
| 142 |
+
# Update API key if provided
|
| 143 |
+
if api_key:
|
| 144 |
+
processor.api_key = api_key
|
| 145 |
+
|
| 146 |
+
# Convert Gradio images to PIL Images
|
| 147 |
+
pil_images = []
|
| 148 |
+
for img in images:
|
| 149 |
+
if img is not None:
|
| 150 |
+
pil_images.append(Image.fromarray(img))
|
| 151 |
+
|
| 152 |
+
if not pil_images:
|
| 153 |
+
return "No valid images found."
|
| 154 |
+
|
| 155 |
+
# Process images
|
| 156 |
+
results = processor.process_multiple_images(pil_images, prompt)
|
| 157 |
+
|
| 158 |
+
# Format results
|
| 159 |
+
if len(results) == 1:
|
| 160 |
+
return results[0]
|
| 161 |
+
else:
|
| 162 |
+
return "\n\n".join(results)
|
| 163 |
+
|
| 164 |
+
# Create the interface
|
| 165 |
+
with gr.Blocks(
|
| 166 |
+
title="Multi-Image AI Processor",
|
| 167 |
+
theme=gr.themes.Soft(),
|
| 168 |
+
fill_height=True
|
| 169 |
+
) as demo:
|
| 170 |
+
|
| 171 |
+
gr.Markdown("# πΌοΈ Multi-Image AI Processor")
|
| 172 |
+
gr.Markdown("Upload multiple images and get AI-generated descriptions using the Qwen2-VL model.")
|
| 173 |
+
|
| 174 |
+
with gr.Row():
|
| 175 |
+
with gr.Column(scale=2):
|
| 176 |
+
# Image upload area
|
| 177 |
+
images_input = gr.File(
|
| 178 |
+
file_count="multiple",
|
| 179 |
+
file_types=["image"],
|
| 180 |
+
label="Upload Images",
|
| 181 |
+
height=300
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# Prompt input
|
| 185 |
+
prompt_input = gr.Textbox(
|
| 186 |
+
label="Prompt",
|
| 187 |
+
placeholder="Describe this image in detail...",
|
| 188 |
+
value="Describe this image in detail.",
|
| 189 |
+
lines=3
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# API key input (optional)
|
| 193 |
+
api_key_input = gr.Textbox(
|
| 194 |
+
label="Hugging Face API Key (optional)",
|
| 195 |
+
placeholder="hf_...",
|
| 196 |
+
type="password",
|
| 197 |
+
info="Leave empty to use environment variable"
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# Process button
|
| 201 |
+
process_btn = gr.Button(
|
| 202 |
+
"π Process Images",
|
| 203 |
+
variant="primary",
|
| 204 |
+
size="lg"
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
with gr.Column(scale=2):
|
| 208 |
+
# Results area
|
| 209 |
+
results_output = gr.Textbox(
|
| 210 |
+
label="Results",
|
| 211 |
+
lines=10,
|
| 212 |
+
max_lines=20,
|
| 213 |
+
interactive=False
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
# Examples
|
| 217 |
+
with gr.Accordion("Examples", open=False):
|
| 218 |
+
gr.Examples(
|
| 219 |
+
examples=[
|
| 220 |
+
[
|
| 221 |
+
["Describe the architectural style and features of this building."],
|
| 222 |
+
"Upload images of buildings to analyze their architectural style."
|
| 223 |
+
],
|
| 224 |
+
[
|
| 225 |
+
["What are the key features and amenities shown in this property?"],
|
| 226 |
+
"Upload property images to get detailed descriptions of features and amenities."
|
| 227 |
+
],
|
| 228 |
+
[
|
| 229 |
+
["Describe the interior design and layout of this space."],
|
| 230 |
+
"Upload interior photos to get detailed descriptions of design and layout."
|
| 231 |
+
]
|
| 232 |
+
],
|
| 233 |
+
inputs=[prompt_input],
|
| 234 |
+
outputs=[results_output],
|
| 235 |
+
label="Example Prompts"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# Footer
|
| 239 |
+
gr.Markdown("---")
|
| 240 |
+
gr.Markdown("""
|
| 241 |
+
**How to use:**
|
| 242 |
+
1. Upload one or more images
|
| 243 |
+
2. Enter a prompt describing what you want to know about the images
|
| 244 |
+
3. Optionally provide your Hugging Face API key
|
| 245 |
+
4. Click "Process Images" to get AI-generated descriptions
|
| 246 |
+
|
| 247 |
+
**Tips:**
|
| 248 |
+
- Use specific prompts for better results
|
| 249 |
+
- The model works best with clear, high-quality images
|
| 250 |
+
- You can process multiple images at once
|
| 251 |
+
""")
|
| 252 |
+
|
| 253 |
+
# Connect the process button
|
| 254 |
+
process_btn.click(
|
| 255 |
+
fn=process_images,
|
| 256 |
+
inputs=[images_input, prompt_input, api_key_input],
|
| 257 |
+
outputs=[results_output]
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
return demo
|
| 261 |
+
|
| 262 |
+
def main():
|
| 263 |
+
"""
|
| 264 |
+
Main function to launch the Gradio app
|
| 265 |
+
"""
|
| 266 |
+
print("π Starting Multi-Image AI Processor...")
|
| 267 |
+
|
| 268 |
+
# Create the interface
|
| 269 |
+
demo = create_gradio_interface()
|
| 270 |
+
|
| 271 |
+
# Launch the app
|
| 272 |
+
demo.launch(
|
| 273 |
+
server_name="0.0.0.0",
|
| 274 |
+
server_port=7860,
|
| 275 |
+
share=False,
|
| 276 |
+
show_error=True,
|
| 277 |
+
show_tips=True
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if __name__ == "__main__":
|
| 281 |
+
main()
|