Spaces:
Sleeping
Sleeping
File size: 4,406 Bytes
6961349 284ad86 6961349 284ad86 6961349 284ad86 6961349 284ad86 6961349 284ad86 6961349 284ad86 6961349 284ad86 6961349 284ad86 c85f9e2 284ad86 c85f9e2 6f6c67a 284ad86 c85f9e2 284ad86 6961349 284ad86 6f6c67a 284ad86 6f6c67a 284ad86 6961349 284ad86 6f6c67a 284ad86 6f6c67a 284ad86 6f6c67a 284ad86 c85f9e2 284ad86 6f6c67a 284ad86 6f6c67a 284ad86 6f6c67a c85f9e2 6961349 284ad86 6f6c67a 6961349 | 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 | import gradio as gr
import pandas as pd
import hashlib, zipfile, os, shutil, time, re
from PIL import Image
from transformers import pipeline
# 1. LOAD THE ENGINES (Captioning + Object Detection)
print("Initializing Ultra-Pro AI Engines...")
captioner = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
# Adding a dedicated Object Detector for better taxonomy matching
detector = pipeline("object-detection", model="facebook/detr-resnet-50")
# 2. MASTER TAXONOMY (Easily Expandable)
RULES = {
"graffiti": "street-art-character",
"mural": "street-art-mural",
"snail": "cartoon-asset-snail",
"shirt": "apparel-merch",
"train": "transit-model-sheet",
"leaf": "cannabis-asset-plant",
"text": "typography-design"
}
def process_images(input_file):
if not input_file: return pd.DataFrame({"Status": ["No file"]}), None
session_id = f"pro_{int(time.time())}"
temp_in, temp_out = f"in_{session_id}", f"out_{session_id}"
os.makedirs(temp_in); os.makedirs(temp_out)
data_log = []
try:
# Extract Logic (Robust)
if input_file.name.lower().endswith('.zip'):
with zipfile.ZipFile(input_file.name, 'r') as z:
z.extractall(temp_in)
else:
shutil.copy(input_file.name, os.path.join(temp_in, os.path.basename(input_file.name)))
for root, _, files in os.walk(temp_in):
for filename in files:
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
img_path = os.path.join(root, filename)
# --- STEP 1: OBJECT DETECTION (More Accurate than Captioning) ---
detections = detector(img_path)
found_objects = [d['label'] for d in detections if d['score'] > 0.8]
# --- STEP 2: CAPTIONING (The Context) ---
cap_res = captioner(img_path)
description = cap_res[0]['generated_text'].lower()
# --- STEP 3: LOGIC ENGINE ---
tag = "uncategorized"
# Try to match detected objects first
for obj in found_objects:
if obj in RULES: tag = RULES[obj]; break
# If no object match, try caption keywords
if tag == "uncategorized":
for key, val in RULES.items():
if key in description: tag = val; break
# Fallback to AI's primary noun
if tag == "uncategorized":
tag = description.split()[0]
# Final Cleanup & Rename
short_hash = hashlib.md5(filename.encode()).hexdigest()[:6]
new_name = f"{tag}-{short_hash}{os.path.splitext(filename)[1].lower()}"
shutil.copy(img_path, os.path.join(temp_out, new_name))
data_log.append({
"Original": filename,
"Detected": ", ".join(found_objects),
"AI Description": description,
"Final Name": new_name
})
# Wrap it up
df = pd.DataFrame(data_log)
csv_path = f"audit_{session_id}.csv"
df.to_csv(csv_path, index=False)
zip_path = f"ScaleBreakers_Output_{int(time.time())}.zip"
with zipfile.ZipFile(zip_path, 'w') as zf:
for f in os.listdir(temp_out): zf.write(os.path.join(temp_out, f), f)
zf.write(csv_path, "audit_trail.csv")
return df, zip_path
except Exception as e:
return pd.DataFrame({"Error": [str(e)]}), None
# Professional UI
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
gr.Markdown("# 🚀 **ScaleBreakers: Ultra-Pro Renamer**\n### Dual-Engine (Object Detection + Image Captioning)")
f_in = gr.File(label="Upload Batch")
btn = gr.Button("🔥 PROCESS BATCH", variant="primary")
with gr.Tabs():
with gr.TabItem("Data Insights"):
t_out = gr.Dataframe()
with gr.TabItem("Download"):
f_out = gr.File()
btn.click(process_images, inputs=f_in, outputs=[t_out, f_out])
demo.launch() |