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

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -35
app.py CHANGED
@@ -4,10 +4,11 @@ import hashlib, zipfile, os, shutil
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",
@@ -17,56 +18,74 @@ RULES = {
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()
 
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",
 
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()