Spaces:
Sleeping
Sleeping
Update app.py
Browse files123234564 unmodified lines111213141514151617182021192021222425232425262728322930343132363334353 unmodified lines39404146424349505152534445465455564758484961505152645354666768555670575859737475767778798081828384606162636465666768697071727374# app.py — makeitmatta/matta-system-app# Version: v0.5# Description: Robust CLIP scoring app supporting Gradio UI and remote /run/predict API# Version: v0.6# Description: HF Space-compatible CLIP scoring app with base64 + label input# Last updated: 2025-05-26
import gradio as gr4 unmodified linesimport base64import logging
# ---- Setup ----
logging.basicConfig(level=logging.INFO)logger = logging.getLogger("hf-app")
# Load CLIP modeldevice = "cuda" if torch.cuda.is_available() else "cpu"model, _, preprocess = open_clip.create_model_and_transforms('ViT-B-32', pretrained='laion2b_s34b_b79k')tokenizer = open_clip.get_tokenizer('ViT-B-32')model, _, preprocess = open_clip.create_model_and_transforms("ViT-B-32", pretrained="laion2b_s34b_b79k")tokenizer = open_clip.get_tokenizer("ViT-B-32")model.to(device).eval()
# ---- Main Scoring Function ----
def score_image(image_data, label_csv): """ Accepts: - image_data: base64 string or PIL.Image - label_csv: comma-separated string Returns: - dict of label: similarity score or error - dict of label: similarity score """ logger.info("Received inputs: image=%s, labels='%s'", type(image_data), label_csv) logger.info("Received input — image type: %s | labels: %s", type(image_data), label_csv)
# Step 1: Handle image (PIL or base64 string) try: if isinstance(image_data, str): image_bytes = base64.b64decode(image_data.split(",")[-1])3 unmodified lines else: return {"error": "Invalid image input type"} except Exception as e: logger.warning("Failed to parse image: %s", e) return {"error": f"Invalid image format: {e}"}
# Step 2: Handle labels try: labels = [label.strip() for label in label_csv.split(",") if label.strip()] if not labels: return {"error": "No valid labels provided."} labels = [label.strip() for label in label_csv.split(",") if label.strip()] if not labels: return {"error": "No valid labels provided."} except Exception as e: logger.warning("Failed to parse labels: %s", e) return {"error": f"Invalid label input: {e}"}
# Step 3: Run CLIP model try: image_input = preprocess(image).unsqueeze(0).to(device) text_tokens = tokenizer(labels).to(device) text_inputs = tokenizer(labels).to(device) with torch.no_grad(): image_features = model.encode_image(image_input) text_features = model.encode_text(text_tokens) text_features = model.encode_text(text_inputs) similarities = (image_features @ text_features.T).squeeze(0) scores = dict(zip(labels, similarities.tolist())) logger.info("Returning scores: %s", scores) return scores return dict(zip(labels, similarities.tolist())) except Exception as e: logger.exception("CLIP scoring failed") logger.exception("Scoring failed") return {"error": f"Model inference error: {e}"}
# ---- Gradio Interface ----
demo = gr.Interface( fn=score_image, inputs=[ gr.Image(type="pil", label="Upload Image"), gr.Textbox(label="Comma-separated labels (e.g. confident, bold, expressive)") ], outputs="json", title="MATTA System: CLIP Scoring v0.5", description="Upload a brand image or call via API. Supports base64-encoded image POSTs via /run/predict.")# Wrap in a function so Spaces binds to it correctlydef build_interface(): return gr.Interface( fn=score_image, inputs=[ gr.Image(type="pil", label="Upload Image"), gr.Textbox(label="Comma-separated labels") ], outputs="json", title="MATTA System: CLIP Scoring v0.6", description="Upload a brand image or call via API. Supports base64-encoded image POSTs via /run/predict." )
demo = build_interface()demo.launch()app.py+27-39