File size: 8,860 Bytes
ee77b90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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()