Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import numpy as np | |
| import pandas as pd | |
| from sentence_transformers import SentenceTransformer | |
| from sklearn.metrics.pairwise import cosine_similarity | |
| from PIL import Image | |
| import requests | |
| from io import BytesIO | |
| # 1. 讟注讬谞转 讛诪讜讚诇 讜讛谞转讜谞讬诐 | |
| print("Loading model and data...") | |
| model = SentenceTransformer('sentence-transformers/clip-ViT-B-32') | |
| # 讟注讬谞转 讛讜拽讟讜专讬诐 讜讛诪讬讚注 砖砖诪专谞讜 诪专讗砖 | |
| embeddings = np.load('flower_embeddings.npy') | |
| df = pd.read_csv('flower_metadata.csv') | |
| # 讟注讬谞转 讛讚讗讟讛-住讟 讛诪拽讜专讬 讻讚讬 诇砖诇讜祝 讗转 讛转诪讜谞讜转 讛讗诪讬转讬讜转 | |
| from datasets import load_dataset, concatenate_datasets | |
| print("Loading dataset images...") | |
| ds = load_dataset("nelorth/oxford-flowers") | |
| full_dataset = concatenate_datasets([ds[split] for split in ds.keys()]) | |
| # 2. 驻讜谞拽爪讬讬转 讛讞讬驻讜砖 | |
| def search_flower(text_query, input_image=None): | |
| # 讗诐 讛诪砖转诪砖 讛注诇讛 转诪讜谞讛, 谞砖转诪砖 讘讛. 讗讞专转, 谞砖转诪砖 讘讟拽住讟 | |
| if input_image is not None: | |
| query_emb = model.encode(input_image, convert_to_tensor=True).cpu().numpy() | |
| else: | |
| query_emb = model.encode([text_query], convert_to_tensor=True).cpu().numpy() | |
| # 讞讬砖讜讘 讚诪讬讜谉 | |
| similarities = cosine_similarity(query_emb.reshape(1, -1), embeddings) | |
| # 砖诇讬驻转 3 讛转讜爪讗讜转 讛讻讬 讟讜讘讜转 | |
| top_k = 3 | |
| top_indices = similarities[0].argsort()[-top_k:][::-1] | |
| top_scores = similarities[0][top_indices] | |
| results = [] | |
| for idx, score in zip(top_indices, top_scores): | |
| # 砖诇讬驻转 讛转诪讜谞讛 讛诪拽讜专讬转 诪讛讚讗讟讛-住讟 | |
| img = full_dataset[int(df.iloc[idx]['original_index'])]['image'] | |
| lbl = df.iloc[idx]['label'] | |
| results.append((img, f"Label: {lbl} (Score: {score:.2f})")) | |
| return results | |
| # 3. 讘谞讬讬转 讛诪诪砖拽 讛讙专驻讬 | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 馃尭 Smart Flower Search Engine") | |
| gr.Markdown("Search for flowers using text description OR by uploading an image!") | |
| with gr.Row(): | |
| with gr.Column(): | |
| txt_input = gr.Textbox(label="Describe a flower (e.g., 'red rose')", placeholder="A yellow sunflower...") | |
| img_input = gr.Image(label="Or upload an image", type="pil") | |
| btn = gr.Button("Find Similar Flowers") | |
| with gr.Column(): | |
| gallery = gr.Gallery(label="Recommended Flowers") | |
| btn.click(fn=search_flower, inputs=[txt_input, img_input], outputs=gallery) | |
| # 讛驻注诇转 讛讗驻诇讬拽爪讬讛 | |
| demo.launch() |