Yoel125 commited on
Commit
e0a0485
·
verified ·
1 Parent(s): c4f9e2a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -0
app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import pandas as pd
4
+ 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 (this takes a minute on startup)...")
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=10):
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() # Index inside our subset
35
+ original_idx = subset_indices[i] # Index inside the real Hugging Face dataset
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, "Can't put a number! Please write a bird type."
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=10)
63
+
64
+ if not results:
65
+ return None, "No matches found."
66
+
67
+ gallery_items = [(r['image'], f"{r['label']} (Score: {r['score']:.2f})") for r in results]
68
+ return gallery_items, status_message
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 **Spanish**, and the AI will find the closest matches!")
73
+
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
+ gallery = gr.Gallery(label="Top 10 Matches", columns=2, height="auto")
82
+
83
+ submit_btn.click(fn=gradio_interface, inputs=[text_in], outputs=[gallery, output_msg])
84
+
85
+ demo.launch()