Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234564 unmodified lines11121314151617181920212223242526272829303132333435363738393 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# app.py — makeitmatta/matta-system-app# Version: v0.5# Description: Robust CLIP scoring app supporting Gradio UI and remote /run/predict API# Last updated: 2025-05-26import gradio as gr4 unmodified linesimport base64import logging# ---- Setup ----logging.basicConfig(level=logging.INFO)logger = logging.getLogger("hf-app")device = "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.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 stringReturns:- dict of label: similarity score or error"""logger.info("Received inputs: image=%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 lineselse: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 labelstry: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 modeltry:image_input = preprocess(image).unsqueeze(0).to(device)text_tokens = tokenizer(labels).to(device)with torch.no_grad():image_features = model.encode_image(image_input)text_features = model.encode_text(text_tokens)similarities = (image_features @ text_features.T).squeeze(0)scores = dict(zip(labels, similarities.tolist()))logger.info("Returning scores: %s", scores)return scoresexcept Exception as e:logger.exception("CLIP 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.")demo.launch()1234564 unmodified lines111213141516171819202122232425262728293031323334353 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374# app.py — makeitmatta/matta-system-app# Version: v0.6# Description: HF Space-compatible CLIP scoring app with base64 + label input# Last updated: 2025-05-26import gradio as gr4 unmodified linesimport base64import logginglogging.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.to(device).eval()def score_image(image_data, label_csv):"""Accepts:- image_data: base64 string or PIL.Image- label_csv: comma-separated stringReturns:- dict of label: similarity score"""logger.info("Received input — image type: %s | labels: %s", type(image_data), label_csv)try:if isinstance(image_data, str):image_bytes = base64.b64decode(image_data.split(",")[-1])3 unmodified lineselse:return {"error": "Invalid image input type"}except Exception as e:return {"error": f"Invalid image format: {e}"}labels = [label.strip() for label in label_csv.split(",") if label.strip()]if not labels:return {"error": "No valid labels provided."}try:image_input = preprocess(image).unsqueeze(0).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_inputs)similarities = (image_features @ text_features.T).squeeze(0)return dict(zip(labels, similarities.tolist()))except Exception as e:logger.exception("Scoring failed")return {"error": f"Model inference error: {e}"}# 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