scalebreakers's picture
Create app.py
284ad86 verified
Raw History Blame Contribute Delete
4.41 kB
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()