TangYiJay commited on
Commit
2aa80dd
·
verified ·
1 Parent(s): 0f57f37

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -0
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageChops
3
+ from transformers import BlipProcessor, BlipForQuestionAnswering
4
+ import torch
5
+
6
+ # Load BLIP model
7
+ model_name = "Salesforce/blip-vqa-base"
8
+ processor = BlipProcessor.from_pretrained(model_name)
9
+ model = BlipForQuestionAnswering.from_pretrained(model_name)
10
+
11
+ # Ensure device
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+ model.to(device)
14
+
15
+ def crop_difference(base_img: Image.Image, trash_img: Image.Image) -> Image.Image:
16
+ # Convert to same mode
17
+ base_img = base_img.convert("RGB")
18
+ trash_img = trash_img.convert("RGB")
19
+
20
+ # Compute difference
21
+ diff = ImageChops.difference(trash_img, base_img)
22
+ # Crop to non-zero bbox
23
+ bbox = diff.getbbox()
24
+ if bbox:
25
+ cropped = trash_img.crop(bbox)
26
+ return cropped
27
+ else:
28
+ return trash_img # fallback if no difference
29
+
30
+ def identify_material(base_img: Image.Image, trash_img: Image.Image) -> str:
31
+ if base_img is None or trash_img is None:
32
+ return "Please upload both base and trash images."
33
+
34
+ cropped = crop_difference(base_img, trash_img)
35
+
36
+ question = "What material is this? Choose from: plastic, metal, paper, cardboard, glass, trash."
37
+ inputs = processor(cropped, question, return_tensors="pt").to(device)
38
+ out = model.generate(**inputs)
39
+ answer = processor.decode(out[0], skip_special_tokens=True)
40
+
41
+ valid_classes = ["plastic", "metal", "paper", "cardboard", "glass", "trash"]
42
+ result = next((c for c in valid_classes if c in answer.lower()), "trash")
43
+ return result.capitalize()
44
+
45
+ title = "Smart Waste Material Detector"
46
+ description = """
47
+ Upload two images:
48
+ 1. Base image (empty background)
49
+ 2. Trash image (object placed on background)
50
+
51
+ The AI will detect the difference and classify the material:
52
+ plastic, metal, paper, cardboard, glass, or trash.
53
+ """
54
+
55
+ demo = gr.Interface(
56
+ fn=identify_material,
57
+ inputs=[
58
+ gr.Image(type="pil", label="Upload Base Image (Empty)"),
59
+ gr.Image(type="pil", label="Upload Trash Image")
60
+ ],
61
+ outputs=gr.Textbox(label="Detected Material"),
62
+ title=title,
63
+ description=description,
64
+ allow_flagging="never"
65
+ )
66
+
67
+ if __name__ == "__main__":
68
+ demo.launch()