Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
CHANGED
|
@@ -1,91 +1,108 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
-
import hashlib, zipfile, os, shutil
|
| 4 |
from PIL import Image
|
| 5 |
from transformers import pipeline
|
| 6 |
|
| 7 |
-
# 1.
|
| 8 |
-
print("
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# 2.
|
| 12 |
RULES = {
|
| 13 |
-
"
|
|
|
|
|
|
|
| 14 |
"shirt": "apparel-merch",
|
| 15 |
-
"
|
| 16 |
-
"
|
| 17 |
-
"
|
| 18 |
}
|
| 19 |
|
| 20 |
def process_images(input_file):
|
| 21 |
-
if not input_file: return pd.DataFrame({"Status": ["No file
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
os.makedirs(p)
|
| 27 |
|
|
|
|
|
|
|
| 28 |
try:
|
| 29 |
-
#
|
| 30 |
if input_file.name.lower().endswith('.zip'):
|
| 31 |
with zipfile.ZipFile(input_file.name, 'r') as z:
|
| 32 |
-
z.extractall(
|
| 33 |
else:
|
| 34 |
-
shutil.copy(input_file.name, os.path.join(
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
# SEARCH: Look through every folder inside 'temp_in'
|
| 39 |
-
for root, dirs, files in os.walk("temp_in"):
|
| 40 |
for filename in files:
|
| 41 |
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
|
| 42 |
img_path = os.path.join(root, filename)
|
| 43 |
|
| 44 |
-
#
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
-
#
|
| 57 |
short_hash = hashlib.md5(filename.encode()).hexdigest()[:6]
|
| 58 |
-
|
| 59 |
-
new_name = f"{label}-{short_hash}{ext}"
|
| 60 |
|
| 61 |
-
shutil.copy(img_path, os.path.join(
|
| 62 |
-
data_log.append({
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
#
|
| 68 |
df = pd.DataFrame(data_log)
|
| 69 |
-
|
|
|
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
|
| 76 |
-
return df,
|
| 77 |
|
| 78 |
except Exception as e:
|
| 79 |
return pd.DataFrame({"Error": [str(e)]}), None
|
| 80 |
|
| 81 |
-
# UI
|
| 82 |
-
with gr.Blocks(theme=gr.themes.
|
| 83 |
-
gr.Markdown("#
|
| 84 |
-
f_in = gr.File(label="Upload
|
| 85 |
-
btn = gr.Button("
|
| 86 |
-
with gr.
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
| 89 |
btn.click(process_images, inputs=f_in, outputs=[t_out, f_out])
|
| 90 |
|
| 91 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
+
import hashlib, zipfile, os, shutil, time, re
|
| 4 |
from PIL import Image
|
| 5 |
from transformers import pipeline
|
| 6 |
|
| 7 |
+
# 1. LOAD THE ENGINES (Captioning + Object Detection)
|
| 8 |
+
print("Initializing Ultra-Pro AI Engines...")
|
| 9 |
+
captioner = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
|
| 10 |
+
# Adding a dedicated Object Detector for better taxonomy matching
|
| 11 |
+
detector = pipeline("object-detection", model="facebook/detr-resnet-50")
|
| 12 |
|
| 13 |
+
# 2. MASTER TAXONOMY (Easily Expandable)
|
| 14 |
RULES = {
|
| 15 |
+
"graffiti": "street-art-character",
|
| 16 |
+
"mural": "street-art-mural",
|
| 17 |
+
"snail": "cartoon-asset-snail",
|
| 18 |
"shirt": "apparel-merch",
|
| 19 |
+
"train": "transit-model-sheet",
|
| 20 |
+
"leaf": "cannabis-asset-plant",
|
| 21 |
+
"text": "typography-design"
|
| 22 |
}
|
| 23 |
|
| 24 |
def process_images(input_file):
|
| 25 |
+
if not input_file: return pd.DataFrame({"Status": ["No file"]}), None
|
| 26 |
|
| 27 |
+
session_id = f"pro_{int(time.time())}"
|
| 28 |
+
temp_in, temp_out = f"in_{session_id}", f"out_{session_id}"
|
| 29 |
+
os.makedirs(temp_in); os.makedirs(temp_out)
|
|
|
|
| 30 |
|
| 31 |
+
data_log = []
|
| 32 |
+
|
| 33 |
try:
|
| 34 |
+
# Extract Logic (Robust)
|
| 35 |
if input_file.name.lower().endswith('.zip'):
|
| 36 |
with zipfile.ZipFile(input_file.name, 'r') as z:
|
| 37 |
+
z.extractall(temp_in)
|
| 38 |
else:
|
| 39 |
+
shutil.copy(input_file.name, os.path.join(temp_in, os.path.basename(input_file.name)))
|
| 40 |
|
| 41 |
+
for root, _, files in os.walk(temp_in):
|
|
|
|
|
|
|
|
|
|
| 42 |
for filename in files:
|
| 43 |
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
|
| 44 |
img_path = os.path.join(root, filename)
|
| 45 |
|
| 46 |
+
# --- STEP 1: OBJECT DETECTION (More Accurate than Captioning) ---
|
| 47 |
+
detections = detector(img_path)
|
| 48 |
+
found_objects = [d['label'] for d in detections if d['score'] > 0.8]
|
| 49 |
+
|
| 50 |
+
# --- STEP 2: CAPTIONING (The Context) ---
|
| 51 |
+
cap_res = captioner(img_path)
|
| 52 |
+
description = cap_res[0]['generated_text'].lower()
|
| 53 |
|
| 54 |
+
# --- STEP 3: LOGIC ENGINE ---
|
| 55 |
+
tag = "uncategorized"
|
| 56 |
+
# Try to match detected objects first
|
| 57 |
+
for obj in found_objects:
|
| 58 |
+
if obj in RULES: tag = RULES[obj]; break
|
| 59 |
+
|
| 60 |
+
# If no object match, try caption keywords
|
| 61 |
+
if tag == "uncategorized":
|
| 62 |
+
for key, val in RULES.items():
|
| 63 |
+
if key in description: tag = val; break
|
| 64 |
+
|
| 65 |
+
# Fallback to AI's primary noun
|
| 66 |
+
if tag == "uncategorized":
|
| 67 |
+
tag = description.split()[0]
|
| 68 |
|
| 69 |
+
# Final Cleanup & Rename
|
| 70 |
short_hash = hashlib.md5(filename.encode()).hexdigest()[:6]
|
| 71 |
+
new_name = f"{tag}-{short_hash}{os.path.splitext(filename)[1].lower()}"
|
|
|
|
| 72 |
|
| 73 |
+
shutil.copy(img_path, os.path.join(temp_out, new_name))
|
| 74 |
+
data_log.append({
|
| 75 |
+
"Original": filename,
|
| 76 |
+
"Detected": ", ".join(found_objects),
|
| 77 |
+
"AI Description": description,
|
| 78 |
+
"Final Name": new_name
|
| 79 |
+
})
|
| 80 |
|
| 81 |
+
# Wrap it up
|
| 82 |
df = pd.DataFrame(data_log)
|
| 83 |
+
csv_path = f"audit_{session_id}.csv"
|
| 84 |
+
df.to_csv(csv_path, index=False)
|
| 85 |
|
| 86 |
+
zip_path = f"ScaleBreakers_Output_{int(time.time())}.zip"
|
| 87 |
+
with zipfile.ZipFile(zip_path, 'w') as zf:
|
| 88 |
+
for f in os.listdir(temp_out): zf.write(os.path.join(temp_out, f), f)
|
| 89 |
+
zf.write(csv_path, "audit_trail.csv")
|
| 90 |
|
| 91 |
+
return df, zip_path
|
| 92 |
|
| 93 |
except Exception as e:
|
| 94 |
return pd.DataFrame({"Error": [str(e)]}), None
|
| 95 |
|
| 96 |
+
# Professional UI
|
| 97 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
|
| 98 |
+
gr.Markdown("# π **ScaleBreakers: Ultra-Pro Renamer**\n### Dual-Engine (Object Detection + Image Captioning)")
|
| 99 |
+
f_in = gr.File(label="Upload Batch")
|
| 100 |
+
btn = gr.Button("π₯ PROCESS BATCH", variant="primary")
|
| 101 |
+
with gr.Tabs():
|
| 102 |
+
with gr.TabItem("Data Insights"):
|
| 103 |
+
t_out = gr.Dataframe()
|
| 104 |
+
with gr.TabItem("Download"):
|
| 105 |
+
f_out = gr.File()
|
| 106 |
btn.click(process_images, inputs=f_in, outputs=[t_out, f_out])
|
| 107 |
|
| 108 |
demo.launch()
|