Spaces:
Runtime error
Runtime error
Add AgriSagot BERT API application with demo and API endpoints
Browse files- README.md +49 -5
- app.py +208 -0
- requirements.txt +6 -0
README.md
CHANGED
|
@@ -1,13 +1,57 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.49.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: AgriSagot BERT API
|
| 3 |
+
emoji: 🌾
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.49.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
| 11 |
+
tags:
|
| 12 |
+
- agriculture
|
| 13 |
+
- bert
|
| 14 |
+
- recommendations
|
| 15 |
+
- philippines
|
| 16 |
+
- farming
|
| 17 |
+
- crops
|
| 18 |
+
- diseases
|
| 19 |
---
|
| 20 |
|
| 21 |
+
# 🌾 AgriSagot BERT Model API
|
| 22 |
+
|
| 23 |
+
**Philippine Agricultural Recommendation System**
|
| 24 |
+
|
| 25 |
+
This Hugging Face Space hosts the AgriSagot BERT model for generating agricultural product recommendations based on crop and disease detection.
|
| 26 |
+
|
| 27 |
+
## Features
|
| 28 |
+
|
| 29 |
+
- 🎯 **Crop-Disease Recommendations**: Get relevant product suggestions
|
| 30 |
+
- 🔧 **API Endpoints**: Integrate with your applications
|
| 31 |
+
- 📊 **Similarity Calculations**: Compare agricultural text semantically
|
| 32 |
+
- 🌾 **Philippine Context**: Trained on local agricultural data
|
| 33 |
+
|
| 34 |
+
## Usage
|
| 35 |
+
|
| 36 |
+
### Demo Interface
|
| 37 |
+
Use the web interface to test recommendations:
|
| 38 |
+
1. Enter crop name (e.g., "rice", "corn", "tomato")
|
| 39 |
+
2. Enter disease/pest (e.g., "blast", "borer", "aphids")
|
| 40 |
+
3. Get ranked product recommendations
|
| 41 |
+
|
| 42 |
+
### API Integration
|
| 43 |
+
|
| 44 |
+
**Get Text Embedding:**
|
| 45 |
+
```bash
|
| 46 |
+
curl -X POST https://hayme-agrisagot-bert.hf.space/api/embedding \
|
| 47 |
+
-H "Content-Type: application/json" \
|
| 48 |
+
-d '{"text": "rice blast treatment"}'
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Model Details
|
| 52 |
+
|
| 53 |
+
- **Base Model**: BERT-base-uncased
|
| 54 |
+
- **Training Data**: Philippine registered agricultural products
|
| 55 |
+
- **Use Case**: Agricultural product recommendations
|
| 56 |
+
- **Languages**: English
|
| 57 |
+
- **License**: MIT
|
app.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.metrics.pairwise import cosine_similarity
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
class AgriSagotBERT:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
"""Load AgriSagot BERT model"""
|
| 11 |
+
print("🔄 Loading AgriSagot BERT model...")
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
self.tokenizer = AutoTokenizer.from_pretrained('Hayme/agrisago-bert')
|
| 15 |
+
self.model = AutoModel.from_pretrained('Hayme/agrisago-bert')
|
| 16 |
+
self.model.eval()
|
| 17 |
+
print("✅ AgriSagot BERT loaded successfully!")
|
| 18 |
+
except Exception as e:
|
| 19 |
+
print(f"⚠️ Custom model failed: {e}")
|
| 20 |
+
print("🔄 Using fallback model...")
|
| 21 |
+
self.tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
| 22 |
+
self.model = AutoModel.from_pretrained('sentence-transformers/all-MiniLM-L6-v2')
|
| 23 |
+
self.model.eval()
|
| 24 |
+
|
| 25 |
+
def get_embedding(self, text):
|
| 26 |
+
"""Get embedding for text"""
|
| 27 |
+
inputs = self.tokenizer(
|
| 28 |
+
text,
|
| 29 |
+
return_tensors='pt',
|
| 30 |
+
padding=True,
|
| 31 |
+
truncation=True,
|
| 32 |
+
max_length=512
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
with torch.no_grad():
|
| 36 |
+
outputs = self.model(**inputs)
|
| 37 |
+
embedding = outputs.last_hidden_state.mean(dim=1)
|
| 38 |
+
|
| 39 |
+
return embedding.numpy().tolist()[0]
|
| 40 |
+
|
| 41 |
+
def calculate_similarity(self, text1, text2):
|
| 42 |
+
"""Calculate similarity between two texts"""
|
| 43 |
+
emb1 = np.array(self.get_embedding(text1)).reshape(1, -1)
|
| 44 |
+
emb2 = np.array(self.get_embedding(text2)).reshape(1, -1)
|
| 45 |
+
similarity = cosine_similarity(emb1, emb2)[0][0]
|
| 46 |
+
return float(similarity)
|
| 47 |
+
|
| 48 |
+
# Initialize model
|
| 49 |
+
bert_model = AgriSagotBERT()
|
| 50 |
+
|
| 51 |
+
def get_embedding_api(text):
|
| 52 |
+
"""API endpoint for getting embeddings"""
|
| 53 |
+
try:
|
| 54 |
+
embedding = bert_model.get_embedding(text)
|
| 55 |
+
return {
|
| 56 |
+
"embedding": embedding,
|
| 57 |
+
"dimension": len(embedding),
|
| 58 |
+
"success": True
|
| 59 |
+
}
|
| 60 |
+
except Exception as e:
|
| 61 |
+
return {
|
| 62 |
+
"error": str(e),
|
| 63 |
+
"success": False
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
def calculate_similarity_api(text1, text2):
|
| 67 |
+
"""API endpoint for calculating similarity"""
|
| 68 |
+
try:
|
| 69 |
+
similarity = bert_model.calculate_similarity(text1, text2)
|
| 70 |
+
return {
|
| 71 |
+
"similarity": similarity,
|
| 72 |
+
"text1": text1,
|
| 73 |
+
"text2": text2,
|
| 74 |
+
"success": True
|
| 75 |
+
}
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return {
|
| 78 |
+
"error": str(e),
|
| 79 |
+
"success": False
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
def demo_recommendations(crop, disease):
|
| 83 |
+
"""Demo function showing recommendations"""
|
| 84 |
+
query = f"{crop} {disease} treatment"
|
| 85 |
+
|
| 86 |
+
# Sample products (in real app, this comes from Firebase)
|
| 87 |
+
products = [
|
| 88 |
+
"WARDOG 2.5 EC Insecticide for rice pest control",
|
| 89 |
+
"WARDEN 2.5 EC Cypermethrin insecticide for crops",
|
| 90 |
+
"XPressmethrin 5EC Cypermethrin fungicide treatment",
|
| 91 |
+
"Chix Insecticide 1Liter for farm pest control",
|
| 92 |
+
"Honda Tractor equipment for rice farming",
|
| 93 |
+
"Spray equipment for pesticide application"
|
| 94 |
+
]
|
| 95 |
+
|
| 96 |
+
results = []
|
| 97 |
+
query_emb = np.array(bert_model.get_embedding(query)).reshape(1, -1)
|
| 98 |
+
|
| 99 |
+
for product in products:
|
| 100 |
+
product_emb = np.array(bert_model.get_embedding(product)).reshape(1, -1)
|
| 101 |
+
similarity = cosine_similarity(query_emb, product_emb)[0][0]
|
| 102 |
+
results.append((product, float(similarity)))
|
| 103 |
+
|
| 104 |
+
# Sort by similarity
|
| 105 |
+
results.sort(key=lambda x: x[1], reverse=True)
|
| 106 |
+
|
| 107 |
+
# Format output
|
| 108 |
+
output = f"🌾 Query: {query}\n\n"
|
| 109 |
+
output += "🎯 Recommendations (sorted by relevance):\n"
|
| 110 |
+
output += "="*50 + "\n"
|
| 111 |
+
|
| 112 |
+
for i, (product, score) in enumerate(results, 1):
|
| 113 |
+
output += f"{i}. {product}\n"
|
| 114 |
+
output += f" Similarity: {score:.4f}\n\n"
|
| 115 |
+
|
| 116 |
+
return output
|
| 117 |
+
|
| 118 |
+
# Create Gradio interface
|
| 119 |
+
with gr.Blocks(title="AgriSagot BERT API", theme=gr.themes.Soft()) as app:
|
| 120 |
+
gr.Markdown("""
|
| 121 |
+
# 🌾 AgriSagot BERT Model API
|
| 122 |
+
**Philippine Agricultural Recommendation System**
|
| 123 |
+
|
| 124 |
+
This Space hosts the AgriSagot BERT model for generating agricultural product recommendations.
|
| 125 |
+
""")
|
| 126 |
+
|
| 127 |
+
with gr.Tabs():
|
| 128 |
+
# Demo Tab
|
| 129 |
+
with gr.TabItem("🎯 Recommendation Demo"):
|
| 130 |
+
gr.Markdown("### Test the recommendation system")
|
| 131 |
+
|
| 132 |
+
with gr.Row():
|
| 133 |
+
crop_input = gr.Textbox(
|
| 134 |
+
label="Crop",
|
| 135 |
+
placeholder="e.g., rice, corn, tomato",
|
| 136 |
+
value="rice"
|
| 137 |
+
)
|
| 138 |
+
disease_input = gr.Textbox(
|
| 139 |
+
label="Disease/Pest",
|
| 140 |
+
placeholder="e.g., blast, borer, aphids",
|
| 141 |
+
value="blast"
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
demo_btn = gr.Button("Get Recommendations", variant="primary")
|
| 145 |
+
demo_output = gr.Textbox(
|
| 146 |
+
label="Recommendations",
|
| 147 |
+
lines=15,
|
| 148 |
+
max_lines=20
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
demo_btn.click(
|
| 152 |
+
demo_recommendations,
|
| 153 |
+
inputs=[crop_input, disease_input],
|
| 154 |
+
outputs=demo_output
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# API Tab
|
| 158 |
+
with gr.TabItem("🔧 API Endpoints"):
|
| 159 |
+
gr.Markdown("""
|
| 160 |
+
### API Usage for Your Application
|
| 161 |
+
|
| 162 |
+
**Get Embedding:**
|
| 163 |
+
```bash
|
| 164 |
+
curl -X POST https://your-space-name.hf.space/api/embedding \\
|
| 165 |
+
-H "Content-Type: application/json" \\
|
| 166 |
+
-d '{"text": "rice blast treatment"}'
|
| 167 |
+
```
|
| 168 |
+
|
| 169 |
+
**Calculate Similarity:**
|
| 170 |
+
```bash
|
| 171 |
+
curl -X POST https://your-space-name.hf.space/api/similarity \\
|
| 172 |
+
-H "Content-Type: application/json" \\
|
| 173 |
+
-d '{"text1": "rice blast", "text2": "fungicide treatment"}'
|
| 174 |
+
```
|
| 175 |
+
""")
|
| 176 |
+
|
| 177 |
+
with gr.Row():
|
| 178 |
+
api_text = gr.Textbox(
|
| 179 |
+
label="Text for Embedding",
|
| 180 |
+
placeholder="Enter text to get embedding"
|
| 181 |
+
)
|
| 182 |
+
api_btn = gr.Button("Get Embedding")
|
| 183 |
+
api_output = gr.JSON(label="API Response")
|
| 184 |
+
|
| 185 |
+
api_btn.click(
|
| 186 |
+
get_embedding_api,
|
| 187 |
+
inputs=api_text,
|
| 188 |
+
outputs=api_output
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
with gr.Row():
|
| 192 |
+
sim_text1 = gr.Textbox(label="Text 1", placeholder="First text")
|
| 193 |
+
sim_text2 = gr.Textbox(label="Text 2", placeholder="Second text")
|
| 194 |
+
|
| 195 |
+
sim_btn = gr.Button("Calculate Similarity")
|
| 196 |
+
sim_output = gr.JSON(label="Similarity Result")
|
| 197 |
+
|
| 198 |
+
sim_btn.click(
|
| 199 |
+
calculate_similarity_api,
|
| 200 |
+
inputs=[sim_text1, sim_text2],
|
| 201 |
+
outputs=sim_output
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Add API routes
|
| 205 |
+
app.queue()
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
app.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
gradio
|
| 4 |
+
numpy
|
| 5 |
+
scikit-learn
|
| 6 |
+
requests
|