haxerwddle commited on
Commit
9dc7c2c
·
1 Parent(s): f9d1a87

Change model

Browse files
Files changed (1) hide show
  1. app.py +24 -29
app.py CHANGED
@@ -1,45 +1,40 @@
1
  import gradio as gr
2
- import numpy as np
3
- from PIL import Image
4
 
5
- from datasets import load_dataset
6
- from huggingface_hub import hf_hub_download
7
- import tensorflow as tf
8
- from tensorflow.keras.applications.resnet50 import preprocess_input
9
 
10
- # --- LOAD LABELS ---
11
- ds = load_dataset("dvk65/TrashTypes")
12
- class_names = ds["train"].features["label"].names
13
 
14
- # --- LOAD MODEL ---
15
- REPO_ID = "dvk65/trash-classifier-resnet50"
16
- FILENAME = "trashclassify_13.keras"
17
 
18
- model_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
 
 
19
 
20
- model = tf.keras.models.load_model(
21
- model_path,
22
- custom_objects={"preprocess_input": preprocess_input}
23
- )
 
 
 
 
 
 
 
24
 
25
- # --- PREPROCESS---
26
- def preprocess(image):
27
- image = image.resize((224, 224))
28
- image = np.array(image).astype("float32")
29
- image = np.expand_dims(image, axis=0)
30
- return image
31
 
32
- def predict(img):
33
- img = preprocess(img)
34
- preds = model.predict(img)[0]
35
-
36
- return {class_names[i]: float(preds[i]) for i in range(len(preds))}
37
 
38
  demo = gr.Interface(
39
  fn=predict,
40
  inputs=gr.Image(type="pil"),
41
  outputs=gr.Label(num_top_classes=3),
42
- title="AI Waste Classifier",
43
  )
44
 
45
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoFeatureExtractor, AutoModelForImageClassification
3
+ import torch
4
 
5
+ # Load model + extractor
6
+ model_name = "Aalaa/Fine_tuned_Vit_trash_classification"
 
 
7
 
8
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
9
+ model = AutoModelForImageClassification.from_pretrained(model_name)
 
10
 
11
+ # Label mapping
12
+ id2label = model.config.id2label
 
13
 
14
+ def predict(image):
15
+ # Convert Gradio PIL to model input
16
+ inputs = feature_extractor(images=image, return_tensors="pt")
17
 
18
+ with torch.no_grad():
19
+ outputs = model(**inputs)
20
+
21
+ logits = outputs.logits
22
+ probs = torch.nn.functional.softmax(logits, dim=-1)[0]
23
+
24
+ # Return top 3
25
+ result = {
26
+ id2label[i]: float(probs[i])
27
+ for i in probs.topk(3).indices.tolist()
28
+ }
29
 
30
+ return result
 
 
 
 
 
31
 
 
 
 
 
 
32
 
33
  demo = gr.Interface(
34
  fn=predict,
35
  inputs=gr.Image(type="pil"),
36
  outputs=gr.Label(num_top_classes=3),
37
+ title="AI Waste Classifier (ViT)"
38
  )
39
 
40
  demo.launch()