Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import spaces
|
| 3 |
+
from cumo.model.builder import load_pretrained_model
|
| 4 |
+
from cumo.mm_utils import process_images, tokenizer_image_token
|
| 5 |
+
from cumo.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
model_path = "BenkHel/CumoThesis" # <-- Das ist dein Modell!
|
| 10 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
|
| 12 |
+
tokenizer, model, image_processor, context_len = load_pretrained_model(
|
| 13 |
+
model_path, None, None, False, False, device, use_flash_attn=False
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
PROMPT = "What material is this item and how is it disposed of?"
|
| 17 |
+
PROMPT_WITH_IMAGE = f"{DEFAULT_IMAGE_TOKEN} {PROMPT}"
|
| 18 |
+
|
| 19 |
+
@spaces.GPU
|
| 20 |
+
def classify_image(image):
|
| 21 |
+
if image is None:
|
| 22 |
+
return "Please upload an image."
|
| 23 |
+
if not isinstance(image, Image.Image):
|
| 24 |
+
image = Image.fromarray(image)
|
| 25 |
+
images = process_images([image], image_processor, model.config)
|
| 26 |
+
images = [img.to(device, dtype=torch.float16) for img in images]
|
| 27 |
+
image_args = {"images": images}
|
| 28 |
+
input_ids = tokenizer_image_token(PROMPT_WITH_IMAGE, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(device)
|
| 29 |
+
with torch.no_grad():
|
| 30 |
+
outputs = model.generate(
|
| 31 |
+
inputs=input_ids,
|
| 32 |
+
max_new_tokens=128,
|
| 33 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 34 |
+
**image_args
|
| 35 |
+
)
|
| 36 |
+
output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 37 |
+
answer = output_text[len(PROMPT):].strip() if output_text.startswith(PROMPT) else output_text
|
| 38 |
+
return answer
|
| 39 |
+
|
| 40 |
+
iface = gr.Interface(
|
| 41 |
+
fn=classify_image,
|
| 42 |
+
inputs=gr.Image(type="pil", label="Upload an image of a waste item"),
|
| 43 |
+
outputs=gr.Textbox(label="Classification & Disposal Recommendation"),
|
| 44 |
+
title="CuMo Waste Classifier",
|
| 45 |
+
description="Upload a photo of a household waste item. The model will classify the material and recommend how to dispose of it."
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
iface.launch()
|