File size: 2,811 Bytes
8eec78f
 
 
 
cbf2876
 
 
 
6695907
 
adde932
cbf2876
8eec78f
4580c52
cbf2876
 
 
4606f2a
6695907
 
 
 
 
 
 
 
 
8eec78f
6695907
 
8eec78f
 
6695907
 
 
 
 
 
 
 
 
8eec78f
 
 
 
 
 
 
6695907
 
cbf2876
 
d25790c
6695907
8eec78f
cbf2876
 
adde932
 
 
 
 
 
 
 
cbf2876
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53d3f0d
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
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0"

import gradio as gr
import numpy as np
import tensorflow as tf
import keras
import zipfile
import json
import spaces  # <-- Make sure this is imported

# 1. Stand-in function for your model's Lambda layer structure
@keras.saving.register_keras_serializable(package="Custom")
def preprocess_input(x):
    return x

# 2. Helper function to recursively scrub out the bad parameters from the inner json dictionary
def strip_quantization_keys(config):
    if isinstance(config, dict):
        config.pop('quantization_config', None)
        for key, value in config.items():
            strip_quantization_keys(value)
    elif isinstance(config, list):
        for item in config:
            strip_quantization_keys(item)

# 3. Read, rewrite, and hot-load the sanitized structural data
def load_sanitized_model(original_path):
    sanitized_path = "sanitized_classifier.keras"
    print("Intercepting model zip archive to remove quantization flags...")
    
    with zipfile.ZipFile(original_path, 'r') as zin:
        with zipfile.ZipFile(sanitized_path, 'w') as zout:
            for item in zin.infolist():
                data = zin.read(item.filename)
                if item.filename == "config.json":
                    config_dict = json.loads(data.decode('utf-8'))
                    strip_quantization_keys(config_dict)
                    data = json.dumps(config_dict).encode('utf-8')
                zout.writestr(item, data)
                
    model = keras.models.load_model(
        sanitized_path, 
        custom_objects={'preprocess_input': preprocess_input},
        safe_mode=False
    )
    
    if os.path.exists(sanitized_path):
        os.remove(sanitized_path)
    return model

print("Loading Keras model into Hugging Face memory...")
model_loaded = load_sanitized_model('garbage_classifier.keras')

lookup = {0: "Cardboard", 1: "Glass", 2: "Metal", 3: "Paper", 4: "Plastic", 5: "Trash"}

# 4. Dummy GPU function to satisfy Hugging Face's ZeroGPU environment health check
@spaces.GPU
def initialize_gpu_hardware():
    return True

# Call it once at boot to keep the health checker happy
initialize_gpu_hardware()

def predict_image(img):
    if img is None:
        return "No image provided"
        
    img_resized = tf.image.resize(img, [224, 224])
    img_tensor = tf.expand_dims(img_resized, axis=0)
    
    predictions = model_loaded.predict({'resnet_input': img_tensor, 'vgg_input': img_tensor})
    class_idx = int(np.argmax(predictions[0]))
    
    return lookup.get(class_idx, "Unknown")

demo = gr.Interface(
    fn=predict_image, 
    inputs=gr.Image(type="numpy"), 
    outputs="text",
    api_name="predict"
)

demo.queue().launch(server_name="0.0.0.0", server_port=7860)