scalebreakers commited on
Commit
284ad86
Β·
verified Β·
1 Parent(s): 6f6c67a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -54
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. Load the AI
8
- print("Loading AI...")
9
- pipe = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
 
 
10
 
11
- # 2. Your Rules
12
  RULES = {
13
- "snail": "cartoon-snail",
 
 
14
  "shirt": "apparel-merch",
15
- "graffiti": "street-art",
16
- "train": "transit-model",
17
- "font": "typography"
18
  }
19
 
20
  def process_images(input_file):
21
- if not input_file: return pd.DataFrame({"Status": ["No file uploaded"]}), None
22
 
23
- # Clean workspace
24
- for p in ["temp_in", "temp_out"]:
25
- if os.path.exists(p): shutil.rmtree(p)
26
- os.makedirs(p)
27
 
 
 
28
  try:
29
- # UNZIP: Handles subfolders automatically
30
  if input_file.name.lower().endswith('.zip'):
31
  with zipfile.ZipFile(input_file.name, 'r') as z:
32
- z.extractall("temp_in")
33
  else:
34
- shutil.copy(input_file.name, os.path.join("temp_in", os.path.basename(input_file.name)))
35
 
36
- data_log = []
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
- # AI VISION
45
- res = pipe(img_path)
46
- cap = res[0]['generated_text'].lower()
 
 
 
 
47
 
48
- # APPLY RULES
49
- label = "uncategorized"
50
- for k, v in RULES.items():
51
- if k in cap:
52
- label = v
53
- break
54
- if label == "uncategorized": label = cap.split()[0]
 
 
 
 
 
 
 
55
 
56
- # RENAME
57
  short_hash = hashlib.md5(filename.encode()).hexdigest()[:6]
58
- ext = os.path.splitext(filename)[1]
59
- new_name = f"{label}-{short_hash}{ext}"
60
 
61
- shutil.copy(img_path, os.path.join("temp_out", new_name))
62
- data_log.append({"Original": filename, "Renamed": new_name, "AI_Sees": cap})
63
-
64
- if not data_log:
65
- return pd.DataFrame({"Warning": ["No images found. Check if they are valid JPG/PNGs."]}), None
 
 
66
 
67
- # CREATE OUTPUT
68
  df = pd.DataFrame(data_log)
69
- df.to_csv("audit_trail.csv", index=False)
 
70
 
71
- with zipfile.ZipFile("renamed_package.zip", 'w') as z:
72
- for f in os.listdir("temp_out"):
73
- z.write(os.path.join("temp_out", f), f)
74
- z.write("audit_trail.csv")
75
 
76
- return df, "renamed_package.zip"
77
 
78
  except Exception as e:
79
  return pd.DataFrame({"Error": [str(e)]}), None
80
 
81
- # UI
82
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange")) as demo:
83
- gr.Markdown("# πŸ“Έ ScaleBreakers: Final Stable Renamer")
84
- f_in = gr.File(label="Upload Zip")
85
- btn = gr.Button("πŸš€ RUN PIPELINE", variant="primary")
86
- with gr.Row():
87
- t_out = gr.Dataframe(label="Audit Trail")
88
- f_out = gr.File(label="Download Renamed Zip")
 
 
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()