scalebreakers commited on
Commit
c85f9e2
ยท
verified ยท
1 Parent(s): 6961349

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -63
app.py CHANGED
@@ -4,91 +4,69 @@ import hashlib, zipfile, os, shutil
4
  from PIL import Image
5
  from transformers import pipeline
6
 
7
- # Load the AI Captioner
8
  print("Loading AI...")
9
  captioner = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
10
 
11
- # --- CUSTOM TAXONOMY RULES ---
12
- # You can edit the words below to match your specific project!
13
  RULES = {
14
  "snail": "cartoon-snail",
15
  "shirt": "apparel-merch",
16
  "graffiti": "street-art",
17
  "train": "transit-model",
18
- "font": "typography",
19
- "leaf": "cannabis-asset"
20
  }
21
 
22
  def process_images(input_file):
23
- if not input_file: return None, None
 
 
24
 
25
- extract_path = "temp_images"
26
- output_path = "renamed_images"
27
- if os.path.exists(extract_path): shutil.rmtree(extract_path)
28
- if os.path.exists(output_path): shutil.rmtree(output_path)
29
- os.makedirs(output_path)
30
- os.makedirs(extract_path)
31
 
32
- # Unpack Zip or Single File
33
- if input_file.name.lower().endswith('.zip'):
34
- with zipfile.ZipFile(input_file.name, 'r') as zip_ref:
35
- zip_ref.extractall(extract_path)
36
- else:
37
- shutil.copy(input_file.name, os.path.join(extract_path, os.path.basename(input_file.name)))
38
 
39
- data_log = []
40
-
41
- for filename in os.listdir(extract_path):
42
- if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
43
  img_path = os.path.join(extract_path, filename)
 
 
44
 
45
- # 1. AI Captioning
46
- result = captioner(img_path)
47
- caption = result[0]['generated_text'].lower()
48
-
49
- # 2. Apply Taxonomy Rules
50
  label = "uncategorized"
51
- for keyword, category in RULES.items():
52
- if keyword in caption:
53
- label = category
54
  break
55
-
56
- # If no rule matched, use the first word the AI said
57
- if label == "uncategorized":
58
- label = caption.split()[0]
59
 
60
- # 3. Create Name: label + short_hash
61
- short_hash = hashlib.md5(filename.encode()).hexdigest()[:6]
62
- ext = os.path.splitext(filename)[1]
63
- new_name = f"{label}-{short_hash}{ext}"
64
-
65
- # 4. Save
66
  shutil.copy(img_path, os.path.join(output_path, new_name))
67
- data_log.append({"Original": filename, "Renamed": new_name, "AI_Caption": caption, "Final_Label": label})
68
 
69
- # Create CSV and Final Zip
70
- df = pd.DataFrame(data_log)
71
- df.to_csv("audit_trail.csv", index=False)
72
-
73
- final_zip = "renamed_assets.zip"
74
- with zipfile.ZipFile(final_zip, 'w') as zipf:
75
- for file in os.listdir(output_path):
76
- zipf.write(os.path.join(output_path, file), file)
77
- zipf.write("audit_trail.csv")
78
 
79
- return df, final_zip
80
-
81
- # UI Setup (Chrome & Orange Theme)
82
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange", neutral_hue="slate")) as demo:
83
- gr.Markdown("# ๐Ÿ“ธ ScaleBreakers: IMG_Name_Breaker\n### Semantic AI Renamer & Taxonomy Tool")
84
-
85
- with gr.Row():
86
- file_input = gr.File(label="Upload Zip or Image")
87
-
88
- run_btn = gr.Button("๐Ÿš€ EXECUTE PIPELINE", variant="primary")
89
-
90
  with gr.Row():
91
- table_out = gr.Dataframe(label="Audit Trail / Preview")
92
- file_out = gr.File(label="Download Renamed Package")
 
93
 
94
  demo.launch()
 
4
  from PIL import Image
5
  from transformers import pipeline
6
 
7
+ # Load the AI
8
  print("Loading AI...")
9
  captioner = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")
10
 
 
 
11
  RULES = {
12
  "snail": "cartoon-snail",
13
  "shirt": "apparel-merch",
14
  "graffiti": "street-art",
15
  "train": "transit-model",
16
+ "font": "typography"
 
17
  }
18
 
19
  def process_images(input_file):
20
+ # Safety: always return 2 things
21
+ if input_file is None:
22
+ return pd.DataFrame({"Status": ["No file uploaded"]}), None
23
 
24
+ extract_path, output_path = "temp_images", "renamed_images"
25
+ for p in [extract_path, output_path]:
26
+ if os.path.exists(p): shutil.rmtree(p)
27
+ os.makedirs(p)
 
 
28
 
29
+ try:
30
+ if input_file.name.lower().endswith('.zip'):
31
+ with zipfile.ZipFile(input_file.name, 'r') as z: z.extractall(extract_path)
32
+ else:
33
+ shutil.copy(input_file.name, os.path.join(extract_path, os.path.basename(input_file.name)))
 
34
 
35
+ data_log = []
36
+ files = [f for f in os.listdir(extract_path) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]
37
+
38
+ for filename in files:
39
  img_path = os.path.join(extract_path, filename)
40
+ res = captioner(img_path)
41
+ cap = res[0]['generated_text'].lower()
42
 
 
 
 
 
 
43
  label = "uncategorized"
44
+ for k, v in RULES.items():
45
+ if k in cap:
46
+ label = v
47
  break
48
+ if label == "uncategorized": label = cap.split()[0]
 
 
 
49
 
50
+ new_name = f"{label}-{hashlib.md5(filename.encode()).hexdigest()[:6]}{os.path.splitext(filename)[1]}"
 
 
 
 
 
51
  shutil.copy(img_path, os.path.join(output_path, new_name))
52
+ data_log.append({"Original": filename, "Renamed": new_name, "Description": cap})
53
 
54
+ df = pd.DataFrame(data_log)
55
+ df.to_csv("audit.csv", index=False)
56
+ with zipfile.ZipFile("results.zip", 'w') as z:
57
+ for f in os.listdir(output_path): z.write(os.path.join(output_path, f), f)
58
+ z.write("audit.csv")
59
+ return df, "results.zip"
60
+ except Exception as e:
61
+ return pd.DataFrame({"Error": [str(e)]}), None
 
62
 
63
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="orange")) as demo:
64
+ gr.Markdown("# ๐Ÿ“ธ IMG_Name_Breaker")
65
+ file_input = gr.File(label="Upload Zip or Image")
66
+ run_btn = gr.Button("๐Ÿš€ EXECUTE", variant="primary")
 
 
 
 
 
 
 
67
  with gr.Row():
68
+ table_out = gr.Dataframe(label="Log")
69
+ file_out = gr.File(label="Download Zip")
70
+ run_btn.click(process_images, inputs=file_input, outputs=[table_out, file_out])
71
 
72
  demo.launch()