Spaces:
Runtime error
Runtime error
File size: 14,016 Bytes
d238832 fd2ff1b d238832 fd2ff1b 3b99a22 fd2ff1b d238832 fd2ff1b d238832 fd2ff1b d238832 22ee3b6 d238832 22ee3b6 d238832 21b672e 20dda03 fc1e6fb 21b672e fc1e6fb 21b672e fc1e6fb 21b672e fc1e6fb 21b672e d238832 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
# from __future__ import annotations
import gradio as gr
from huggingface_hub import from_pretrained_fastai
import os
from typing import Iterable
# from gradio.themes.base import Base
# from gradio.themes.utils import colors, fonts, sizes
os.environ["HF_ENDPOINT"] = "https://huggingface.co"
materials_model = from_pretrained_fastai("pyesonekyaw/recycletree_materials")
paper_model = from_pretrained_fastai("pyesonekyaw/recycletree_paper")
plastic_model = from_pretrained_fastai("pyesonekyaw/recycletree_plastic")
metal_model = from_pretrained_fastai("pyesonekyaw/recycletree_metal")
others_model = from_pretrained_fastai("pyesonekyaw/recycletree_others")
glass_model = from_pretrained_fastai("pyesonekyaw/recycletree_glass")
examples = ["Examples/1.jpg", "Examples/2.jpg",
"Examples/3.jpg", "Examples/4.jpg", "Examples/5.jpg"]
material_names = ['Glass', 'Metal', 'Others', 'Paper', 'Plastic']
plastic_names = ['CD Disk', 'Straw', 'Plastic Bag', 'Clothes Hanger', 'Plastic Container or Bottle',
'Disposable Cutlery', 'Plastic Packaging', 'Plastic Packaging With Foil', 'Styrofoam']
paper_names = ['Beverage Carton', 'Cardboard', 'Chopsticks', 'Disposables', 'Paper Bag', 'Paper Packaging',
'Paper Product', 'Receipt', 'Paper Roll', 'Paper Sheet', 'Tissue Box', 'Tissue Paper']
glass_names = ['Ceramic', 'Glassware', 'Lightbulb']
other_names = ['Battery', 'Electronic Waste', 'Stationery']
metal_names = ['Aerosol Can', 'Aluminium Foil or Tray', 'Metal Can or Container']
material_num_name_dict = {
"metal": "Metal",
"glass": "Glass",
"paper": "Paper",
"plastic": "Plastic",
"others": "Others",
}
# No plastic bags, wrap, or film (please take back to a local retailer)
# No Styrofoam
# No single-use paper (no paper towels, napkins, tissues, or paper plates)
# No clothing, shoes, or textiles (take gently used items to a donation center)
# No chain, wire, hoses, or hangers of any kind
# No lumber, scrap wood, or yard waste
# No food or liquids
# No soiled food boxes
# No electronics
# No furniture
# Cardboard and boxboard (flatten boxes)
# Paper: junk mail, magazines, newspaper (no napkins, tissues, paper towels, or paper plates)
# Aluminum and steel cans (no scrap metal)
# Plastic bottles, tubs, and jugs (no plastic bags, wrap, film, or Styrofoam)
# Glass bottles and jars (remove all lids)
# Poly-coated cartons
plastic_item_num_dict = {
"CD Disk": ["CD Disk", "No, find a local e-waste collection near you (refer to the info page!!!)"],
"Straw": ["Straw", "No, dispose as general waste"],
"Plastic Bag": ["Plastic Bag", "Yes, plastic bags can be recycled at most big grocery stores (refer to info page!!) unless it's contaminated with food waste/liquid waste/other forms of waste."],
"Clothes Hanger": ["Clothes Hanger", "Yes, but if it's made up of more than one plastic just dispose as normal waste "],
"Plastic Container or Bottle": ["Plastic Container or Bottle", "Yes. Empty it, rinse it if needed, and keep the cap on."],
"Disposable Cutlery": ["Disposable Cutlery", "No, dispose as general waste", "Nil"],
"Plastic Packaging": ["Plastic Packaging", "Yes, some packaging can be recycled at collection centers (refer to info page!!!) but no if directly enclosing food like cling wrap or contaminated with food contents "],
"Plastic Packaging With Foil": ["Plastic Packaging With Foil", "No, dispose as general waste"],
"Styrofoam": ["Styrofoam", "No, dispose as general waste or drop it at a collection center (refer to info page)"]
}
glass_item_num_dict = {
"Ceramic": ["Ceramic", "No, donate if can be reused"],
"Glassware": ["Glassware", "Yes. Unless there is liquid/solid residue inside the glassware. Clean and recycle if possible."],
"Lightbulb": ["Lightbulb", "No, find a local e-waste collection near you (refer to the info page!!!)"]
}
metal_item_num_dict = {
"Aerosol Can": ["Aerosol Can", "Yes, only if there is nothing left in the can"],
"Aluminium Foil or Tray": ["Aluminium Foil or Tray", "Yes. Unless there is any residue. Clean and recycle if possible."],
"Metal Can or Container": ["Metal Can or Container", "Yes. Unless there is any residue. Clean and recycle if possible."]
}
others_item_num_dict = {
"Battery": ["Battery", "No, find a local e-waste collection near you (refer to the info page!!!)"],
"Electronic Waste": ["Electronic Waste", "No, find a local e-waste collection near you (refer to the info page!!!)"],
"Stationery": ["Stationery", "No, donate if can be reused"]
}
paper_item_num_dict = {
"Beverage Carton": ["Beverage Carton", "Yes, rinsed and flattened"],
"Cardboard": ["Cardboard", "Yes, remove other materials such as tape and flatten!! Don't recycle if contaminated with other waste like food"],
"Chopsticks": ["Chopsticks", "No, dispose as general waste"],
"Disposables": ["Disposables", "No, dispose as general waste"],
"Paper Bag": ["Paper Bag", "Yes. Unless contaminated with food waste or other waste"],
"Paper Packaging": ["Paper Packaging", "Yes, remove other materials such as tape and flatten!! Don't recycle if contaminated with other waste like food"],
"Paper Product": ["Paper Product", "Yes, remove other materials such as tape and flatten!! Don't recycle if contaminated with other waste like food"],
"Receipt": ["Receipt", "No, dispose as general waste"],
"Paper Roll": ["Paper Roll", "Yes. Unless contaminated with food waste or other waste"],
"Paper Sheet": ["Paper Sheet", "Yes. Unless contaminated with food waste or other waste"],
"Tissue Box": ["Tissue Box", "Yes, remove plastic liners. Don't recycle if contaminated with other waste "],
"Tissue Paper": ["Tissue Paper", "No, dispose as general waste"]
}
# class Seafoam(Base):
# def __init__(
# self,
# *,
# primary_hue: colors.Color | str = colors.emerald,
# secondary_hue: colors.Color | str = colors.teal,
# neutral_hue: colors.Color | str = colors.teal,
# spacing_size: sizes.Size | str = sizes.spacing_md,
# radius_size: sizes.Size | str = sizes.radius_md,
# text_size: sizes.Size | str = sizes.text_lg,
# font: fonts.Font
# | str
# | Iterable[fonts.Font | str] = (
# fonts.GoogleFont("Quicksand"),
# "ui-sans-serif",
# "sans-serif",
# ),
# font_mono: fonts.Font
# | str
# | Iterable[fonts.Font | str] = (
# fonts.GoogleFont("IBM Plex Mono"),
# "ui-monospace",
# "monospace",
# ),
# ):
# super().__init__(
# primary_hue=primary_hue,
# secondary_hue=secondary_hue,
# neutral_hue=neutral_hue,
# spacing_size=spacing_size,
# radius_size=radius_size,
# text_size=text_size,
# font=font,
# font_mono=font_mono,
# )
# super().set(
# body_background_fill="linear-gradient(45deg, *primary_200, *primary_200 10px, *primary_50 10px, *primary_50 20px)",
# body_background_fill_dark="linear-gradient(45deg, *primary_200, *primary_200 10px, *primary_50 10px, *primary_50 20px)",
# stat_background_fill_dark="linear-gradient(to right, *primary_400, *primary_200)",
# error_background_fill_dark=f"linear-gradient(to right, {colors.red.c100}, *background_fill_secondary)",
# button_primary_background_fill="linear-gradient(90deg, *primary_300, *secondary_400)",
# button_primary_background_fill_hover="linear-gradient(90deg, *primary_200, *secondary_300)",
# button_primary_background_fill_hover_dark="linear-gradient(90deg, *primary_200, *secondary_300)",
# button_primary_text_color="white",
# button_primary_background_fill_dark="linear-gradient(90deg, *primary_300, *secondary_400)",
# slider_color="*secondary_300",
# slider_color_dark="*secondary_300",
# block_title_text_weight="600",
# block_border_width="3px",
# block_shadow="*shadow_drop_lg",
# button_shadow="*shadow_drop_lg",
# button_large_padding="32px",
# )
# for k in list(self.__dict__.keys()):
# if '_dark' in k:
# setattr(self,k,None)
# seafoam = Seafoam()
def predict_image(inp):
"""
Performs inference for a given input image and returns the prediction and CAM image.
"""
try:
material_label, material_label_idx, material_probs = materials_model.predict(inp)
material_preds = {name: prob for name, prob in zip(material_names, material_probs.tolist())}
if material_label == 'paper':
specific_label, specific_label_idx, specific_probs = paper_model.predict(inp)
specific_preds = {name: prob for name, prob in zip(paper_names, specific_probs.tolist())}
specific_label = paper_names[int(specific_label_idx)]
recyclable_qn = paper_item_num_dict[specific_label][0]
recyclable_advice = paper_item_num_dict[specific_label][1]
elif material_label == 'plastic':
specific_label, specific_label_idx, specific_probs = plastic_model.predict(inp)
specific_preds = {name: prob for name, prob in zip(plastic_names, specific_probs.tolist())}
specific_label = plastic_names[int(specific_label_idx)]
recyclable_qn = plastic_item_num_dict[specific_label][0]
recyclable_advice = plastic_item_num_dict[specific_label][1]
elif material_label == 'glass':
specific_label, specific_label_idx, specific_probs = glass_model.predict(inp)
specific_preds = {name: prob for name, prob in zip(glass_names, specific_probs.tolist())}
specific_label = glass_names[int(specific_label_idx)]
recyclable_qn = glass_item_num_dict[specific_label][0]
recyclable_advice = glass_item_num_dict[specific_label][1]
elif material_label == 'metal':
specific_label, specific_label_idx, specific_probs = metal_model.predict(inp)
specific_preds = {name: prob for name, prob in zip(metal_names, specific_probs.tolist())}
specific_label = metal_names[int(specific_label_idx)]
recyclable_qn = metal_item_num_dict[specific_label][0]
recyclable_advice = metal_item_num_dict[specific_label][1]
elif material_label == 'others':
specific_label, specific_label_idx, specific_probs = others_model.predict(inp)
specific_preds = {name: prob for name, prob in zip(other_names, specific_probs.tolist())}
specific_label = other_names[int(specific_label_idx)]
recyclable_qn = others_item_num_dict[specific_label][0]
recyclable_advice = others_item_num_dict[specific_label][1]
return material_preds, specific_preds, recyclable_qn, recyclable_advice
except:
raise Exception("Invalid file format! Please only upload .jpg or .png files!")
with gr.Blocks(title="Trash Classification", css="#custom_header {min-height: 3rem} #custom_title {min-height: 3rem; text-align: center}") as demo:#, theme=seafoam) as demo:
gr.Markdown("# Check whether your trash is recyclable or not!", elem_id="custom_title")
gr.Markdown("Gradio Inference interface for classification of trash and recyclables. To use it, simply upload your image, or click one of the examples to load them. Images uploaded are never saved or indexed. No data or images uploaded are saved or logged.", elem_id="custom_title")
with gr.Column():
with gr.Column():
with gr.Box():
gr.Markdown("## Inputs", elem_id="custom_header")
input_image = gr.Image(label="Input Image")
input_image.style(height=240)
btn = gr.Button(value="Submit")
btn.style(full_width=True)
with gr.Column():
with gr.Box():
gr.Markdown("## Outputs", elem_id="custom_header")
recycling_qn = gr.outputs.Textbox(label="Is this recyclable?")
recycling_advice = gr.outputs.Textbox(label="It is not recyclable when:")
with gr.Row():
material_probs = gr.outputs.Label(label="Material Prediction")
item_probs = gr.outputs.Label(label="Item Prediction")
gr.Examples(
examples=examples,
inputs=input_image,
fn=predict_image,
cache_examples=False,
)
btn.click(predict_image, inputs=[input_image],
outputs=[material_probs, item_probs, recycling_qn, recycling_advice])
# css = """
# #warning {background-color: #FFCCCB}
# #custom_header {min-height: 3rem} #custom_title {min-height: 3rem; text-align: center}
# .feedback textarea {font-size: 24px !important}
# """
# with gr.Blocks(title="Green Genius", css=css, theme=gr.themes.Monochrome()
# ) as demo:
# with gr.Column():
# with gr.Column():
# input_image = gr.Image(label="Input Image")
# input_image.style(height=240)
# btn = gr.Button(value="Submit")
# btn.style(full_width=True)
# with gr.Column():
# gr.Markdown("# We think this is?",elem_id="custom_header")
# with gr.Row():
# item_probs = gr.outputs.Label(label=" ",num_top_classes=1)
# material_probs = gr.outputs.Label(label=" ",num_top_classes=1)
# gr.Markdown("# Can it Recycle?", elem_id="custom_header")
# recycling_qn = gr.outputs.Label(label=" ",)
# gr.Markdown("# This Cant be Recycled when: ",elem_id="custom_header")
# recycling_advice = gr.outputs.Label(label=" ",)
# btn.click(predict_image, inputs=[input_image],
# outputs=[material_probs, item_probs, recycling_qn, recycling_advice])
if __name__ == "__main__":
demo.launch(show_error=True)
|