Commit
·
f03a25b
1
Parent(s):
02a4024
fix
Browse files- __pycache__/app.cpython-310.pyc +0 -0
- app.py +110 -180
__pycache__/app.cpython-310.pyc
ADDED
|
Binary file (7.11 kB). View file
|
|
|
app.py
CHANGED
|
@@ -1,167 +1,102 @@
|
|
| 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
|
| 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 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 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 |
-
|
| 33 |
-
|
| 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 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
Returns:
|
| 68 |
-
Generated description
|
| 69 |
-
"""
|
| 70 |
-
if not self.processor:
|
| 71 |
-
return "❌ Image processor not available"
|
| 72 |
-
|
| 73 |
try:
|
| 74 |
-
# Convert
|
| 75 |
-
|
| 76 |
-
image.save(img_byte_arr, format='JPEG')
|
| 77 |
-
img_byte_arr = img_byte_arr.getvalue()
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
|
| 81 |
-
img_io.seek(0)
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
|
|
|
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
except Exception as e:
|
| 92 |
-
|
| 93 |
-
return f"❌ Error processing image: {str(e)}"
|
| 94 |
|
| 95 |
-
|
| 96 |
-
""
|
| 97 |
-
|
| 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(),
|
|
@@ -169,7 +104,7 @@ def create_gradio_interface():
|
|
| 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):
|
|
@@ -189,12 +124,12 @@ def create_gradio_interface():
|
|
| 189 |
lines=3
|
| 190 |
)
|
| 191 |
|
| 192 |
-
# API key input (
|
| 193 |
api_key_input = gr.Textbox(
|
| 194 |
-
label="Hugging Face API Key
|
| 195 |
placeholder="hf_...",
|
| 196 |
type="password",
|
| 197 |
-
info="
|
| 198 |
)
|
| 199 |
|
| 200 |
# Process button
|
|
@@ -208,26 +143,34 @@ def create_gradio_interface():
|
|
| 208 |
# Results area
|
| 209 |
results_output = gr.Textbox(
|
| 210 |
label="Results",
|
| 211 |
-
lines=
|
| 212 |
-
max_lines=
|
| 213 |
interactive=False
|
| 214 |
)
|
| 215 |
|
| 216 |
# Examples
|
| 217 |
-
with gr.Accordion("
|
| 218 |
gr.Examples(
|
| 219 |
examples=[
|
| 220 |
[
|
| 221 |
-
|
| 222 |
"Upload images of buildings to analyze their architectural style."
|
| 223 |
],
|
| 224 |
[
|
| 225 |
-
|
| 226 |
"Upload property images to get detailed descriptions of features and amenities."
|
| 227 |
],
|
| 228 |
[
|
| 229 |
-
|
| 230 |
"Upload interior photos to get detailed descriptions of design and layout."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
]
|
| 232 |
],
|
| 233 |
inputs=[prompt_input],
|
|
@@ -239,43 +182,30 @@ def create_gradio_interface():
|
|
| 239 |
gr.Markdown("---")
|
| 240 |
gr.Markdown("""
|
| 241 |
**How to use:**
|
| 242 |
-
1.
|
| 243 |
-
2.
|
| 244 |
-
3.
|
| 245 |
-
4.
|
|
|
|
| 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=
|
| 256 |
inputs=[images_input, prompt_input, api_key_input],
|
| 257 |
outputs=[results_output]
|
| 258 |
)
|
| 259 |
|
| 260 |
return demo
|
| 261 |
|
| 262 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import base64
|
| 4 |
+
import io
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import os
|
| 7 |
|
| 8 |
+
def encode_image_to_base64(image):
|
| 9 |
+
"""Convert PIL image to base64 string"""
|
| 10 |
+
buffered = io.BytesIO()
|
| 11 |
+
image.save(buffered, format="JPEG")
|
| 12 |
+
img_str = base64.b64encode(buffered.getvalue()).decode()
|
| 13 |
+
return f"data:image/jpeg;base64,{img_str}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
def process_images_with_api(images, prompt, api_key):
|
| 16 |
+
"""
|
| 17 |
+
Process multiple images using Hugging Face Inference API
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
Args:
|
| 20 |
+
images: List of uploaded images
|
| 21 |
+
prompt: User-provided prompt
|
| 22 |
+
api_key: Hugging Face API key
|
| 23 |
|
| 24 |
+
Returns:
|
| 25 |
+
Generated descriptions
|
| 26 |
+
"""
|
| 27 |
+
if not images:
|
| 28 |
+
return "Please upload at least one image."
|
| 29 |
+
|
| 30 |
+
if not api_key:
|
| 31 |
+
return "Please provide your Hugging Face API key."
|
| 32 |
+
|
| 33 |
+
# API endpoint for Qwen2-VL model
|
| 34 |
+
api_url = "https://api-inference.huggingface.co/models/Qwen/Qwen2-VL-7B-Instruct"
|
| 35 |
+
|
| 36 |
+
headers = {
|
| 37 |
+
"Authorization": f"Bearer {api_key}",
|
| 38 |
+
"Content-Type": "application/json"
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
results = []
|
| 42 |
+
|
| 43 |
+
for i, image in enumerate(images):
|
| 44 |
+
if image is None:
|
| 45 |
+
continue
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
+
# Convert numpy array to PIL Image
|
| 49 |
+
pil_image = Image.fromarray(image)
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
# Encode image to base64
|
| 52 |
+
base64_image = encode_image_to_base64(pil_image)
|
|
|
|
| 53 |
|
| 54 |
+
# Prepare the request payload
|
| 55 |
+
payload = {
|
| 56 |
+
"inputs": [
|
| 57 |
+
{
|
| 58 |
+
"role": "user",
|
| 59 |
+
"content": [
|
| 60 |
+
{
|
| 61 |
+
"type": "text",
|
| 62 |
+
"text": prompt
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"type": "image_url",
|
| 66 |
+
"image_url": {
|
| 67 |
+
"url": base64_image
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
]
|
| 71 |
+
}
|
| 72 |
+
]
|
| 73 |
+
}
|
| 74 |
|
| 75 |
+
# Make API request
|
| 76 |
+
response = requests.post(api_url, headers=headers, json=payload, timeout=60)
|
| 77 |
|
| 78 |
+
if response.status_code == 200:
|
| 79 |
+
result = response.json()
|
| 80 |
+
if "choices" in result and len(result["choices"]) > 0:
|
| 81 |
+
description = result["choices"][0]["message"]["content"]
|
| 82 |
+
results.append(f"Image {i+1}: {description}")
|
| 83 |
+
else:
|
| 84 |
+
results.append(f"Image {i+1}: ❌ No response from API")
|
| 85 |
+
else:
|
| 86 |
+
error_msg = f"API Error (Status {response.status_code}): {response.text}"
|
| 87 |
+
results.append(f"Image {i+1}: ❌ {error_msg}")
|
| 88 |
+
|
| 89 |
except Exception as e:
|
| 90 |
+
results.append(f"Image {i+1}: ❌ Error - {str(e)}")
|
|
|
|
| 91 |
|
| 92 |
+
if not results:
|
| 93 |
+
return "No valid images processed."
|
| 94 |
+
|
| 95 |
+
return "\n\n".join(results)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
def create_gradio_interface():
|
| 98 |
+
"""Create the Gradio interface for Hugging Face Spaces"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
|
|
|
| 100 |
with gr.Blocks(
|
| 101 |
title="Multi-Image AI Processor",
|
| 102 |
theme=gr.themes.Soft(),
|
|
|
|
| 104 |
) as demo:
|
| 105 |
|
| 106 |
gr.Markdown("# 🖼️ Multi-Image AI Processor")
|
| 107 |
+
gr.Markdown("Upload multiple images and get AI-generated descriptions using the Qwen2-VL model via Hugging Face Inference API.")
|
| 108 |
|
| 109 |
with gr.Row():
|
| 110 |
with gr.Column(scale=2):
|
|
|
|
| 124 |
lines=3
|
| 125 |
)
|
| 126 |
|
| 127 |
+
# API key input (required)
|
| 128 |
api_key_input = gr.Textbox(
|
| 129 |
+
label="Hugging Face API Key",
|
| 130 |
placeholder="hf_...",
|
| 131 |
type="password",
|
| 132 |
+
info="Required: Get your API key from https://huggingface.co/settings/tokens"
|
| 133 |
)
|
| 134 |
|
| 135 |
# Process button
|
|
|
|
| 143 |
# Results area
|
| 144 |
results_output = gr.Textbox(
|
| 145 |
label="Results",
|
| 146 |
+
lines=15,
|
| 147 |
+
max_lines=25,
|
| 148 |
interactive=False
|
| 149 |
)
|
| 150 |
|
| 151 |
# Examples
|
| 152 |
+
with gr.Accordion("Example Prompts", open=False):
|
| 153 |
gr.Examples(
|
| 154 |
examples=[
|
| 155 |
[
|
| 156 |
+
"Describe the architectural style and features of this building.",
|
| 157 |
"Upload images of buildings to analyze their architectural style."
|
| 158 |
],
|
| 159 |
[
|
| 160 |
+
"What are the key features and amenities shown in this property?",
|
| 161 |
"Upload property images to get detailed descriptions of features and amenities."
|
| 162 |
],
|
| 163 |
[
|
| 164 |
+
"Describe the interior design and layout of this space.",
|
| 165 |
"Upload interior photos to get detailed descriptions of design and layout."
|
| 166 |
+
],
|
| 167 |
+
[
|
| 168 |
+
"What type of property is this and what are its main characteristics?",
|
| 169 |
+
"Upload property images to identify type and characteristics."
|
| 170 |
+
],
|
| 171 |
+
[
|
| 172 |
+
"Describe the condition and quality of this property.",
|
| 173 |
+
"Upload property images to assess condition and quality."
|
| 174 |
]
|
| 175 |
],
|
| 176 |
inputs=[prompt_input],
|
|
|
|
| 182 |
gr.Markdown("---")
|
| 183 |
gr.Markdown("""
|
| 184 |
**How to use:**
|
| 185 |
+
1. Get your Hugging Face API key from https://huggingface.co/settings/tokens
|
| 186 |
+
2. Upload one or more images
|
| 187 |
+
3. Enter a prompt describing what you want to know about the images
|
| 188 |
+
4. Paste your API key
|
| 189 |
+
5. Click "Process Images" to get AI-generated descriptions
|
| 190 |
|
| 191 |
**Tips:**
|
| 192 |
- Use specific prompts for better results
|
| 193 |
- The model works best with clear, high-quality images
|
| 194 |
- You can process multiple images at once
|
| 195 |
+
- Each image is processed individually with the same prompt
|
| 196 |
""")
|
| 197 |
|
| 198 |
# Connect the process button
|
| 199 |
process_btn.click(
|
| 200 |
+
fn=process_images_with_api,
|
| 201 |
inputs=[images_input, prompt_input, api_key_input],
|
| 202 |
outputs=[results_output]
|
| 203 |
)
|
| 204 |
|
| 205 |
return demo
|
| 206 |
|
| 207 |
+
# Create and launch the interface
|
| 208 |
+
demo = create_gradio_interface()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
if __name__ == "__main__":
|
| 211 |
+
demo.launch()
|