Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,81 +5,96 @@ from sentence_transformers import SentenceTransformer, util
|
|
| 5 |
from deep_translator import GoogleTranslator
|
| 6 |
from datasets import load_dataset
|
| 7 |
|
| 8 |
-
print("Downloading dataset and initializing model
|
| 9 |
-
# Load the dataset directly from Hugging Face
|
| 10 |
dataset = load_dataset('JotDe/birds')
|
| 11 |
|
| 12 |
-
# Load our saved embeddings and indices
|
| 13 |
print("Loading embeddings...")
|
| 14 |
df = pd.read_parquet("bird_embeddings.parquet")
|
| 15 |
subset_indices = df['dataset_index'].tolist()
|
| 16 |
subset_labels = df['label'].tolist()
|
| 17 |
|
| 18 |
-
# Extract just the vectors (ignoring the index and label columns)
|
| 19 |
feature_cols = [c for c in df.columns if c not in ['dataset_index', 'label']]
|
| 20 |
embeddings = df[feature_cols].values
|
| 21 |
dataset_embeddings = torch.tensor(embeddings, device='cpu')
|
| 22 |
|
| 23 |
-
# Load the AI Models
|
| 24 |
model = SentenceTransformer('sentence-transformers/clip-ViT-B-32', device='cpu')
|
| 25 |
translator = GoogleTranslator(source='auto', target='en')
|
| 26 |
|
| 27 |
def get_recommendations(text_input, top_k=3):
|
|
|
|
|
|
|
|
|
|
| 28 |
query_embedding = model.encode(text_input, convert_to_tensor=True, device='cpu')
|
| 29 |
similarities = util.cos_sim(query_embedding, dataset_embeddings)[0]
|
| 30 |
top_indices = similarities.argsort(descending=True)[:top_k]
|
| 31 |
|
| 32 |
recommendations = []
|
| 33 |
for idx in top_indices:
|
| 34 |
-
i = idx.item()
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
img = dataset['train'][original_idx]['image']
|
| 38 |
-
label_id = subset_labels[i]
|
| 39 |
species_name = dataset['train'].features['label'].int2str(label_id)
|
| 40 |
-
score = similarities[i].item()
|
| 41 |
|
| 42 |
recommendations.append({
|
| 43 |
"image": img,
|
| 44 |
-
"label": species_name
|
| 45 |
-
"score": score
|
| 46 |
})
|
| 47 |
return recommendations
|
| 48 |
|
| 49 |
def gradio_interface(text_input):
|
| 50 |
if not text_input or text_input.strip() == "":
|
| 51 |
-
return None, "Please enter a description."
|
|
|
|
| 52 |
if any(char.isdigit() for char in text_input):
|
| 53 |
-
return None, "
|
| 54 |
|
| 55 |
try:
|
| 56 |
english_query = translator.translate(text_input)
|
| 57 |
-
status_message = f"Translated your search to English: '{english_query}'"
|
| 58 |
except:
|
| 59 |
english_query = text_input
|
| 60 |
-
status_message = "Searching in English..."
|
| 61 |
|
| 62 |
-
results = get_recommendations(text_input=english_query, top_k=
|
| 63 |
|
| 64 |
-
if not results:
|
| 65 |
-
return None, "No matches found."
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
with gr.Blocks(title="🐦 Smart Bird Tracker") as demo:
|
| 71 |
gr.Markdown("# 🐦 Smart Bird Tracker")
|
| 72 |
-
gr.Markdown("Describe the bird you are looking for in **English** or **
|
|
|
|
|
|
|
| 73 |
gr.Video(value="video assigment 3.mp4", label="Project Presentation Video")
|
|
|
|
| 74 |
with gr.Row():
|
| 75 |
with gr.Column(scale=1):
|
| 76 |
text_in = gr.Textbox(label="Describe the bird", placeholder="Type your description here...")
|
| 77 |
submit_btn = gr.Button("Find Birds", variant="primary")
|
| 78 |
-
output_msg = gr.Textbox(label="Status Message")
|
| 79 |
|
| 80 |
with gr.Column(scale=2):
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
submit_btn.click(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
demo.launch()
|
|
|
|
| 5 |
from deep_translator import GoogleTranslator
|
| 6 |
from datasets import load_dataset
|
| 7 |
|
| 8 |
+
print("Downloading dataset and initializing model...")
|
|
|
|
| 9 |
dataset = load_dataset('JotDe/birds')
|
| 10 |
|
|
|
|
| 11 |
print("Loading embeddings...")
|
| 12 |
df = pd.read_parquet("bird_embeddings.parquet")
|
| 13 |
subset_indices = df['dataset_index'].tolist()
|
| 14 |
subset_labels = df['label'].tolist()
|
| 15 |
|
|
|
|
| 16 |
feature_cols = [c for c in df.columns if c not in ['dataset_index', 'label']]
|
| 17 |
embeddings = df[feature_cols].values
|
| 18 |
dataset_embeddings = torch.tensor(embeddings, device='cpu')
|
| 19 |
|
|
|
|
| 20 |
model = SentenceTransformer('sentence-transformers/clip-ViT-B-32', device='cpu')
|
| 21 |
translator = GoogleTranslator(source='auto', target='en')
|
| 22 |
|
| 23 |
def get_recommendations(text_input, top_k=3):
|
| 24 |
+
if not text_input or text_input.strip() == "":
|
| 25 |
+
return []
|
| 26 |
+
|
| 27 |
query_embedding = model.encode(text_input, convert_to_tensor=True, device='cpu')
|
| 28 |
similarities = util.cos_sim(query_embedding, dataset_embeddings)[0]
|
| 29 |
top_indices = similarities.argsort(descending=True)[:top_k]
|
| 30 |
|
| 31 |
recommendations = []
|
| 32 |
for idx in top_indices:
|
| 33 |
+
i = idx.item()
|
| 34 |
+
# Crucial fix for numpy types!
|
| 35 |
+
original_idx = int(subset_indices[i])
|
| 36 |
|
| 37 |
img = dataset['train'][original_idx]['image']
|
| 38 |
+
label_id = int(subset_labels[i])
|
| 39 |
species_name = dataset['train'].features['label'].int2str(label_id)
|
|
|
|
| 40 |
|
| 41 |
recommendations.append({
|
| 42 |
"image": img,
|
| 43 |
+
"label": species_name
|
|
|
|
| 44 |
})
|
| 45 |
return recommendations
|
| 46 |
|
| 47 |
def gradio_interface(text_input):
|
| 48 |
if not text_input or text_input.strip() == "":
|
| 49 |
+
return None, "### Please enter a description.", None, "", None, ""
|
| 50 |
+
|
| 51 |
if any(char.isdigit() for char in text_input):
|
| 52 |
+
return None, "### Please put a bird type (example: blue bird)", None, "", None, ""
|
| 53 |
|
| 54 |
try:
|
| 55 |
english_query = translator.translate(text_input)
|
|
|
|
| 56 |
except:
|
| 57 |
english_query = text_input
|
|
|
|
| 58 |
|
| 59 |
+
results = get_recommendations(text_input=english_query, top_k=3)
|
| 60 |
|
| 61 |
+
if not results or len(results) < 3:
|
| 62 |
+
return None, "### No matches found.", None, "", None, ""
|
| 63 |
|
| 64 |
+
name1 = f"### {results[0]['label']}"
|
| 65 |
+
name2 = f"### {results[1]['label']}"
|
| 66 |
+
name3 = f"### {results[2]['label']}"
|
| 67 |
+
|
| 68 |
+
return results[0]['image'], name1, results[1]['image'], name2, results[2]['image'], name3
|
| 69 |
|
| 70 |
with gr.Blocks(title="🐦 Smart Bird Tracker") as demo:
|
| 71 |
gr.Markdown("# 🐦 Smart Bird Tracker")
|
| 72 |
+
gr.Markdown("Describe the bird you are looking for in **English**, **Spanish**, or **Hebrew**, and the AI will find the closest matches!")
|
| 73 |
+
|
| 74 |
+
# The Video Player
|
| 75 |
gr.Video(value="video assigment 3.mp4", label="Project Presentation Video")
|
| 76 |
+
|
| 77 |
with gr.Row():
|
| 78 |
with gr.Column(scale=1):
|
| 79 |
text_in = gr.Textbox(label="Describe the bird", placeholder="Type your description here...")
|
| 80 |
submit_btn = gr.Button("Find Birds", variant="primary")
|
|
|
|
| 81 |
|
| 82 |
with gr.Column(scale=2):
|
| 83 |
+
with gr.Row():
|
| 84 |
+
with gr.Column():
|
| 85 |
+
out_img1 = gr.Image(label="Top Match 1")
|
| 86 |
+
out_name1 = gr.Markdown()
|
| 87 |
+
with gr.Column():
|
| 88 |
+
out_img2 = gr.Image(label="Top Match 2")
|
| 89 |
+
out_name2 = gr.Markdown()
|
| 90 |
+
with gr.Column():
|
| 91 |
+
out_img3 = gr.Image(label="Top Match 3")
|
| 92 |
+
out_name3 = gr.Markdown()
|
| 93 |
|
| 94 |
+
submit_btn.click(
|
| 95 |
+
fn=gradio_interface,
|
| 96 |
+
inputs=[text_in],
|
| 97 |
+
outputs=[out_img1, out_name1, out_img2, out_name2, out_img3, out_name3]
|
| 98 |
+
)
|
| 99 |
|
| 100 |
demo.launch()
|