launch-calcium commited on
Commit
ee77b90
·
verified ·
1 Parent(s): 006a441

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +244 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import zipfile
3
+ import tempfile
4
+ from typing import List, Dict, Any
5
+ import gradio as gr
6
+ from PIL import Image, ImageDraw, ImageFont
7
+ import torch
8
+ from transformers import pipeline
9
+
10
+ # Initialize Hugging Face pipeline for zero-shot object detection (OWLv2)
11
+ # Optimized for CPU execution on Hugging Face Spaces Basic CPU tier
12
+ print("Loading OWLv2 model on CPU...")
13
+ device = "cuda" if torch.cuda.is_available() else "cpu"
14
+ detector = pipeline(
15
+ task="zero-shot-object-detection",
16
+ model="google/owlv2-base-patch16-ensemble",
17
+ device=device
18
+ )
19
+ print(f"Model loaded successfully on {device}!")
20
+
21
+ def run_preview(files, query_text: str, threshold: float):
22
+ """
23
+ Phase 1: Make Preview
24
+ Spots targets (character, held objects, hands), overlays red bounding boxes,
25
+ and returns annotated previews with coordinate metadata.
26
+ """
27
+ if not files:
28
+ return None, [], "Please upload at least one image."
29
+
30
+ # Parse user-defined queries
31
+ labels = [q.strip() for q in query_text.split(",") if q.strip()]
32
+ if not labels:
33
+ labels = ["person", "character", "hand", "held object"]
34
+
35
+ annotated_gallery = []
36
+ coordinates_records = []
37
+ session_data = []
38
+
39
+ for file_idx, file_obj in enumerate(files):
40
+ img_path = file_obj.name if hasattr(file_obj, "name") else file_obj
41
+ original_name = os.path.basename(img_path)
42
+
43
+ try:
44
+ img = Image.open(img_path).convert("RGB")
45
+ except Exception as e:
46
+ continue
47
+
48
+ w, h = img.size
49
+ # Run inference
50
+ results = detector(img, candidate_labels=labels, threshold=threshold)
51
+
52
+ draw_img = img.copy()
53
+ draw = ImageDraw.Draw(draw_img)
54
+ img_boxes = []
55
+
56
+ for b_idx, res in enumerate(results):
57
+ box = res["box"]
58
+ xmin, ymin, xmax, ymax = box["xmin"], box["ymin"], box["xmax"], box["ymax"]
59
+ label = res["label"]
60
+ score = round(res["score"], 2)
61
+
62
+ # Draw prominent red bounding box
63
+ draw.rectangle([xmin, ymin, xmax, ymax], outline="#E01E1E", width=4)
64
+
65
+ # Draw tag badge
66
+ caption = f"{label} ({int(score * 100)}%) [{xmin},{ymin},{xmax-xmin},{ymax-ymin}]"
67
+ # Draw label background
68
+ text_bbox = draw.textbbox((xmin + 4, max(0, ymin - 20)), caption)
69
+ draw.rectangle(text_bbox, fill="#E01E1E")
70
+ draw.text((xmin + 4, max(0, ymin - 20)), caption, fill="white")
71
+
72
+ box_record = {
73
+ "image_index": file_idx,
74
+ "filename": original_name,
75
+ "box_id": f"IMG{file_idx+1}_BOX{b_idx+1}",
76
+ "label": label,
77
+ "score": score,
78
+ "xmin": xmin,
79
+ "ymin": ymin,
80
+ "xmax": xmax,
81
+ "ymax": ymax,
82
+ "width": xmax - xmin,
83
+ "height": ymax - ymin,
84
+ }
85
+ img_boxes.append(box_record)
86
+ coordinates_records.append([
87
+ box_record["filename"],
88
+ box_record["box_id"],
89
+ box_record["label"],
90
+ f"{int(score * 100)}%",
91
+ f"x: {xmin}, y: {ymin}",
92
+ f"{box_record['width']} x {box_record['height']} px"
93
+ ])
94
+
95
+ annotated_gallery.append(draw_img)
96
+ session_data.append({
97
+ "image_path": img_path,
98
+ "filename": original_name,
99
+ "boxes": img_boxes
100
+ })
101
+
102
+ summary_msg = f"✓ Preview complete: Detected {len(coordinates_records)} targets across {len(files)} images."
103
+ return annotated_gallery, coordinates_records, session_data, summary_msg
104
+
105
+ def run_finalize(session_data, padding: int):
106
+ """
107
+ Phase 2: Finalize & Cut
108
+ Takes the bounding boxes identified in Phase 1, crops each element
109
+ (character, held objects, hands), and packages them into a downloadable ZIP.
110
+ """
111
+ if not session_data:
112
+ return None, [], "No preview data found. Please run 'Make Preview' first."
113
+
114
+ temp_dir = tempfile.mkdtemp(prefix="batch_cuts_")
115
+ cropped_gallery = []
116
+ total_cuts = 0
117
+
118
+ for item in session_data:
119
+ img_path = item["image_path"]
120
+ orig_name, _ = os.path.splitext(item["filename"])
121
+ try:
122
+ img = Image.open(img_path).convert("RGB")
123
+ except Exception:
124
+ continue
125
+
126
+ w, h = img.size
127
+
128
+ for b in item["boxes"]:
129
+ # Apply padding while keeping within image boundary
130
+ xmin = max(0, b["xmin"] - padding)
131
+ ymin = max(0, b["ymin"] - padding)
132
+ xmax = min(w, b["xmax"] + padding)
133
+ ymax = min(h, b["ymax"] + padding)
134
+
135
+ if xmax <= xmin or ymax <= ymin:
136
+ continue
137
+
138
+ crop = img.crop((xmin, ymin, xmax, ymax))
139
+ clean_label = b["label"].replace(" ", "_")
140
+ out_filename = f"{orig_name}_{b['box_id']}_{clean_label}.png"
141
+ out_path = os.path.join(temp_dir, out_filename)
142
+
143
+ crop.save(out_path, format="PNG")
144
+ cropped_gallery.append((crop, f"{out_filename} ({crop.width}x{crop.height})"))
145
+ total_cuts += 1
146
+
147
+ if total_cuts == 0:
148
+ return None, [], "No valid bounding boxes to crop."
149
+
150
+ # Package all into a zip file
151
+ zip_path = os.path.join(temp_dir, "batch_cut_images.zip")
152
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
153
+ for root, _, files in os.walk(temp_dir):
154
+ for f in files:
155
+ if f.endswith(".png"):
156
+ full_p = os.path.join(root, f)
157
+ zipf.write(full_p, arcname=f)
158
+
159
+ status_msg = f"✓ Finalized! Sliced {total_cuts} standalone images. Ready to download ZIP."
160
+ return zip_path, cropped_gallery, status_msg
161
+
162
+ # Gradio Interface Layout
163
+ with gr.Blocks(title="Batch Image Cutter (Preview & Finalize)", theme=gr.themes.Base()) as demo:
164
+ gr.Markdown("# ✂️ Two-Phase Batch Image Cutter\nIsolate characters, held items, and hands from screenshots, selfies, and AI images.")
165
+
166
+ with gr.Row():
167
+ with gr.Column(scale=1):
168
+ file_input = gr.File(
169
+ label="Step 1: Upload Images (Batch)",
170
+ file_count="multiple",
171
+ file_types=["image"]
172
+ )
173
+ query_input = gr.Textbox(
174
+ value="character, person, hand, held object, weapon, phone",
175
+ label="Target Items to Spot (comma-separated)",
176
+ info="Prompts for zero-shot detection. Hand & held objects are detected separately."
177
+ )
178
+ with gr.Row():
179
+ threshold_slider = gr.Slider(
180
+ minimum=0.05,
181
+ maximum=0.50,
182
+ value=0.15,
183
+ step=0.01,
184
+ label="Detection Sensitivity",
185
+ info="Lower spots subtle items (like hands/small objects)."
186
+ )
187
+ padding_slider = gr.Slider(
188
+ minimum=0,
189
+ maximum=40,
190
+ value=8,
191
+ step=2,
192
+ label="Crop Padding (px)",
193
+ info="Extra margin around cropped items."
194
+ )
195
+
196
+ with gr.Row():
197
+ preview_btn = gr.Button("🔍 1. Make Preview", variant="secondary", size="lg")
198
+ finalize_btn = gr.Button("✂️ 2. Finalize & Cut", variant="primary", size="lg")
199
+
200
+ status_output = gr.Markdown("Ready for batch upload.")
201
+
202
+ with gr.Column(scale=2):
203
+ preview_gallery = gr.Gallery(
204
+ label="Phase 1: Detection Preview (Red Bounding Boxes)",
205
+ columns=2,
206
+ height=420,
207
+ object_fit="contain"
208
+ )
209
+ coords_table = gr.Dataframe(
210
+ headers=["File", "Box ID", "Target", "Confidence", "Coordinates (X, Y)", "Dimensions (W x H)"],
211
+ label="Coordinates Metadata [x, y, w, h]",
212
+ interactive=False
213
+ )
214
+
215
+ gr.Markdown("---")
216
+ gr.Markdown("### Phase 2: Extracted Slices & Download")
217
+ with gr.Row():
218
+ zip_output = gr.File(label="📦 Download All Slices as ZIP")
219
+ cuts_gallery = gr.Gallery(
220
+ label="Cropped Image Assets",
221
+ columns=4,
222
+ height=340,
223
+ object_fit="contain"
224
+ )
225
+
226
+ # State storage for bounding boxes between Phase 1 and Phase 2
227
+ session_state = gr.State([])
228
+
229
+ # Wiring Phase 1
230
+ preview_btn.click(
231
+ fn=run_preview,
232
+ inputs=[file_input, query_input, threshold_slider],
233
+ outputs=[preview_gallery, coords_table, session_state, status_output]
234
+ )
235
+
236
+ # Wiring Phase 2
237
+ finalize_btn.click(
238
+ fn=run_finalize,
239
+ inputs=[session_state, padding_slider],
240
+ outputs=[zip_output, cuts_gallery, status_output]
241
+ )
242
+
243
+ if __name__ == "__main__":
244
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ transformers>=4.40.0
3
+ torch>=2.2.0
4
+ torchvision
5
+ Pillow>=10.0.0
6
+ numpy