launch-calcium's picture
Upload 2 files
ee77b90 verified
Raw History Blame Contribute Delete
8.86 kB
import os
import zipfile
import tempfile
from typing import List, Dict, Any
import gradio as gr
from PIL import Image, ImageDraw, ImageFont
import torch
from transformers import pipeline
# Initialize Hugging Face pipeline for zero-shot object detection (OWLv2)
# Optimized for CPU execution on Hugging Face Spaces Basic CPU tier
print("Loading OWLv2 model on CPU...")
device = "cuda" if torch.cuda.is_available() else "cpu"
detector = pipeline(
task="zero-shot-object-detection",
model="google/owlv2-base-patch16-ensemble",
device=device
)
print(f"Model loaded successfully on {device}!")
def run_preview(files, query_text: str, threshold: float):
"""
Phase 1: Make Preview
Spots targets (character, held objects, hands), overlays red bounding boxes,
and returns annotated previews with coordinate metadata.
"""
if not files:
return None, [], "Please upload at least one image."
# Parse user-defined queries
labels = [q.strip() for q in query_text.split(",") if q.strip()]
if not labels:
labels = ["person", "character", "hand", "held object"]
annotated_gallery = []
coordinates_records = []
session_data = []
for file_idx, file_obj in enumerate(files):
img_path = file_obj.name if hasattr(file_obj, "name") else file_obj
original_name = os.path.basename(img_path)
try:
img = Image.open(img_path).convert("RGB")
except Exception as e:
continue
w, h = img.size
# Run inference
results = detector(img, candidate_labels=labels, threshold=threshold)
draw_img = img.copy()
draw = ImageDraw.Draw(draw_img)
img_boxes = []
for b_idx, res in enumerate(results):
box = res["box"]
xmin, ymin, xmax, ymax = box["xmin"], box["ymin"], box["xmax"], box["ymax"]
label = res["label"]
score = round(res["score"], 2)
# Draw prominent red bounding box
draw.rectangle([xmin, ymin, xmax, ymax], outline="#E01E1E", width=4)
# Draw tag badge
caption = f"{label} ({int(score * 100)}%) [{xmin},{ymin},{xmax-xmin},{ymax-ymin}]"
# Draw label background
text_bbox = draw.textbbox((xmin + 4, max(0, ymin - 20)), caption)
draw.rectangle(text_bbox, fill="#E01E1E")
draw.text((xmin + 4, max(0, ymin - 20)), caption, fill="white")
box_record = {
"image_index": file_idx,
"filename": original_name,
"box_id": f"IMG{file_idx+1}_BOX{b_idx+1}",
"label": label,
"score": score,
"xmin": xmin,
"ymin": ymin,
"xmax": xmax,
"ymax": ymax,
"width": xmax - xmin,
"height": ymax - ymin,
}
img_boxes.append(box_record)
coordinates_records.append([
box_record["filename"],
box_record["box_id"],
box_record["label"],
f"{int(score * 100)}%",
f"x: {xmin}, y: {ymin}",
f"{box_record['width']} x {box_record['height']} px"
])
annotated_gallery.append(draw_img)
session_data.append({
"image_path": img_path,
"filename": original_name,
"boxes": img_boxes
})
summary_msg = f"✓ Preview complete: Detected {len(coordinates_records)} targets across {len(files)} images."
return annotated_gallery, coordinates_records, session_data, summary_msg
def run_finalize(session_data, padding: int):
"""
Phase 2: Finalize & Cut
Takes the bounding boxes identified in Phase 1, crops each element
(character, held objects, hands), and packages them into a downloadable ZIP.
"""
if not session_data:
return None, [], "No preview data found. Please run 'Make Preview' first."
temp_dir = tempfile.mkdtemp(prefix="batch_cuts_")
cropped_gallery = []
total_cuts = 0
for item in session_data:
img_path = item["image_path"]
orig_name, _ = os.path.splitext(item["filename"])
try:
img = Image.open(img_path).convert("RGB")
except Exception:
continue
w, h = img.size
for b in item["boxes"]:
# Apply padding while keeping within image boundary
xmin = max(0, b["xmin"] - padding)
ymin = max(0, b["ymin"] - padding)
xmax = min(w, b["xmax"] + padding)
ymax = min(h, b["ymax"] + padding)
if xmax <= xmin or ymax <= ymin:
continue
crop = img.crop((xmin, ymin, xmax, ymax))
clean_label = b["label"].replace(" ", "_")
out_filename = f"{orig_name}_{b['box_id']}_{clean_label}.png"
out_path = os.path.join(temp_dir, out_filename)
crop.save(out_path, format="PNG")
cropped_gallery.append((crop, f"{out_filename} ({crop.width}x{crop.height})"))
total_cuts += 1
if total_cuts == 0:
return None, [], "No valid bounding boxes to crop."
# Package all into a zip file
zip_path = os.path.join(temp_dir, "batch_cut_images.zip")
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(temp_dir):
for f in files:
if f.endswith(".png"):
full_p = os.path.join(root, f)
zipf.write(full_p, arcname=f)
status_msg = f"✓ Finalized! Sliced {total_cuts} standalone images. Ready to download ZIP."
return zip_path, cropped_gallery, status_msg
# Gradio Interface Layout
with gr.Blocks(title="Batch Image Cutter (Preview & Finalize)", theme=gr.themes.Base()) as demo:
gr.Markdown("# ✂️ Two-Phase Batch Image Cutter\nIsolate characters, held items, and hands from screenshots, selfies, and AI images.")
with gr.Row():
with gr.Column(scale=1):
file_input = gr.File(
label="Step 1: Upload Images (Batch)",
file_count="multiple",
file_types=["image"]
)
query_input = gr.Textbox(
value="character, person, hand, held object, weapon, phone",
label="Target Items to Spot (comma-separated)",
info="Prompts for zero-shot detection. Hand & held objects are detected separately."
)
with gr.Row():
threshold_slider = gr.Slider(
minimum=0.05,
maximum=0.50,
value=0.15,
step=0.01,
label="Detection Sensitivity",
info="Lower spots subtle items (like hands/small objects)."
)
padding_slider = gr.Slider(
minimum=0,
maximum=40,
value=8,
step=2,
label="Crop Padding (px)",
info="Extra margin around cropped items."
)
with gr.Row():
preview_btn = gr.Button("🔍 1. Make Preview", variant="secondary", size="lg")
finalize_btn = gr.Button("✂️ 2. Finalize & Cut", variant="primary", size="lg")
status_output = gr.Markdown("Ready for batch upload.")
with gr.Column(scale=2):
preview_gallery = gr.Gallery(
label="Phase 1: Detection Preview (Red Bounding Boxes)",
columns=2,
height=420,
object_fit="contain"
)
coords_table = gr.Dataframe(
headers=["File", "Box ID", "Target", "Confidence", "Coordinates (X, Y)", "Dimensions (W x H)"],
label="Coordinates Metadata [x, y, w, h]",
interactive=False
)
gr.Markdown("---")
gr.Markdown("### Phase 2: Extracted Slices & Download")
with gr.Row():
zip_output = gr.File(label="📦 Download All Slices as ZIP")
cuts_gallery = gr.Gallery(
label="Cropped Image Assets",
columns=4,
height=340,
object_fit="contain"
)
# State storage for bounding boxes between Phase 1 and Phase 2
session_state = gr.State([])
# Wiring Phase 1
preview_btn.click(
fn=run_preview,
inputs=[file_input, query_input, threshold_slider],
outputs=[preview_gallery, coords_table, session_state, status_output]
)
# Wiring Phase 2
finalize_btn.click(
fn=run_finalize,
inputs=[session_state, padding_slider],
outputs=[zip_output, cuts_gallery, status_output]
)
if __name__ == "__main__":
demo.launch()