Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import CLIPProcessor, CLIPModel
|
| 6 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 7 |
+
from datasets import load_dataset
|
| 8 |
+
|
| 9 |
+
# Load model
|
| 10 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
model_name = "openai/clip-vit-base-patch32"
|
| 12 |
+
model = CLIPModel.from_pretrained(model_name).to(device)
|
| 13 |
+
processor = CLIPProcessor.from_pretrained(model_name)
|
| 14 |
+
|
| 15 |
+
# Load embeddings
|
| 16 |
+
df = pd.read_parquet("nature_embeddings.parquet")
|
| 17 |
+
EMBEDDINGS_MATRIX = np.array(df['embedding'].tolist())
|
| 18 |
+
CAPTIONS = df['caption'].tolist()
|
| 19 |
+
|
| 20 |
+
# Load dataset
|
| 21 |
+
dataset = load_dataset("mertcobanov/nature-dataset")
|
| 22 |
+
sample_indices = list(range(5000))
|
| 23 |
+
sample_data = dataset['train'].select(sample_indices)
|
| 24 |
+
|
| 25 |
+
def get_image_embedding(image):
|
| 26 |
+
inputs = processor(images=image, return_tensors="pt", padding=True).to(device)
|
| 27 |
+
with torch.no_grad():
|
| 28 |
+
outputs = model.vision_model(**inputs)
|
| 29 |
+
features = outputs.pooler_output
|
| 30 |
+
features = torch.nn.functional.normalize(features, p=2, dim=-1)
|
| 31 |
+
return features.cpu().numpy()
|
| 32 |
+
|
| 33 |
+
def recommend(image):
|
| 34 |
+
query_embedding = get_image_embedding(image)
|
| 35 |
+
similarities = cosine_similarity(query_embedding, EMBEDDINGS_MATRIX)[0]
|
| 36 |
+
top_indices = np.argsort(similarities)[::-1]
|
| 37 |
+
top_indices = [idx for idx in top_indices if similarities[idx] < 0.9999][:3]
|
| 38 |
+
|
| 39 |
+
results = []
|
| 40 |
+
for idx in top_indices:
|
| 41 |
+
img = sample_data[int(idx)]['image']
|
| 42 |
+
cap = CAPTIONS[idx]
|
| 43 |
+
sim = float(similarities[idx])
|
| 44 |
+
results.append((img, f"{cap} (similarity: {sim:.4f})"))
|
| 45 |
+
|
| 46 |
+
return results[0][0], results[0][1], results[1][0], results[1][1], results[2][0], results[2][1]
|
| 47 |
+
|
| 48 |
+
# Gradio interface
|
| 49 |
+
with gr.Blocks(title="Nature Scene Recommender") as demo:
|
| 50 |
+
gr.Markdown("# 🌿 Nature Scene Recommender")
|
| 51 |
+
gr.Markdown("Upload a nature image and get the 3 most similar scenes!")
|
| 52 |
+
|
| 53 |
+
with gr.Row():
|
| 54 |
+
input_image = gr.Image(type="pil", label="Upload Nature Image")
|
| 55 |
+
btn = gr.Button("Find Similar Scenes 🔍", variant="primary")
|
| 56 |
+
|
| 57 |
+
gr.Markdown("### Top 3 Similar Scenes")
|
| 58 |
+
with gr.Row():
|
| 59 |
+
img1 = gr.Image(label="Match #1")
|
| 60 |
+
img2 = gr.Image(label="Match #2")
|
| 61 |
+
img3 = gr.Image(label="Match #3")
|
| 62 |
+
with gr.Row():
|
| 63 |
+
cap1 = gr.Textbox(label="Caption #1")
|
| 64 |
+
cap2 = gr.Textbox(label="Caption #2")
|
| 65 |
+
cap3 = gr.Textbox(label="Caption #3")
|
| 66 |
+
|
| 67 |
+
btn.click(fn=recommend, inputs=input_image,
|
| 68 |
+
outputs=[img1, cap1, img2, cap2, img3, cap3])
|
| 69 |
+
|
| 70 |
+
demo.launch()
|