Files
ds-smart-farm-project/API_DOCUMENTATION.md
T

316 lines
7.7 KiB
Markdown
Raw Normal View History

# 🚜 Smart Farm Photo Keyword Tagging AI - API Documentation
## 🌐 Web UI & API Overview
The Smart Farm AI system provides both a **web interface** and **REST API** for agricultural photo keyword generation.
### 🚀 Quick Start
```bash
# Start the web UI and API server
python3 start_ui.py
# Or manually start with uvicorn
uvicorn src.api.main:app --host 0.0.0.0 --port 8000
```
**Access Points:**
- **Web UI**: http://localhost:8000
- **API Docs**: http://localhost:8000/docs (Swagger)
- **Alternative Docs**: http://localhost:8000/redoc
- **System Status**: http://localhost:8000/status
## 📋 API Endpoints
### 1. System Status
**GET** `/status`
Get current system status and capabilities.
**Response:**
```json
{
"status": "Operational",
"model_loaded": true,
"version": "1.0.0",
"capabilities": [
"Agricultural keyword generation",
"Image title creation",
"Quality validation",
"Batch processing",
"Agricultural distinctions (farmer vs rancher)",
"Location extraction",
"Performance metrics"
]
}
```
### 2. Single Image Analysis
**POST** `/analyze/single`
Analyze a single agricultural image for keywords and title.
**Request:**
- **Content-Type**: `multipart/form-data`
- **Body**: Image file (JPG, PNG, etc.)
**Response:**
```json
{
"filename": "farm_photo.jpg",
"keywords": ["farmer", "corn", "field", "agriculture", "tractor"],
"title": "Agricultural scene: Farmer working in corn field",
"quality_score": 73.3,
"processing_time": 2.5,
"caption": "a farmer working in a corn field with a tractor"
}
```
**cURL Example:**
```bash
curl -X POST "http://localhost:8000/analyze/single" \
-H "accept: application/json" \
-H "Content-Type: multipart/form-data" \
-F "file=@farm_photo.jpg"
```
### 3. Batch Image Analysis
**POST** `/analyze/batch`
Analyze multiple agricultural images in a single request.
**Request:**
- **Content-Type**: `multipart/form-data`
- **Body**: Multiple image files
**Response:**
```json
{
"total_images": 5,
"successful": 5,
"failed": 0,
"results": [
{
"filename": "corn_field.jpg",
"keywords": ["corn", "field", "agriculture", "farming"],
"title": "Agricultural scene: Corn field at sunset",
"quality_score": 80.0,
"processing_time": 2.1,
"caption": "a corn field at sunset"
}
],
"average_quality": 75.2,
"total_processing_time": 12.5
}
```
**cURL Example:**
```bash
curl -X POST "http://localhost:8000/analyze/batch" \
-H "accept: application/json" \
-H "Content-Type: multipart/form-data" \
-F "files=@photo1.jpg" \
-F "files=@photo2.jpg" \
-F "files=@photo3.jpg"
```
### 4. Demo with Sample Images
**GET** `/demo`
Run demonstration using existing sample agricultural images.
**Response:**
```json
{
"total_images": 7,
"successful": 7,
"failed": 0,
"results": [
{
"filename": "agric-field8.png",
"keywords": ["corn", "field", "agriculture", "farming", "rural"],
"title": "Agricultural scene: A corn field with the sun setting",
"quality_score": 73.3,
"processing_time": 3.2,
"caption": "a corn field with the sun setting in the background"
}
],
"average_quality": 65.2,
"total_processing_time": 18.7
}
```
## 🎯 Quality Scoring
The system provides quality scores for generated keywords:
| Score Range | Quality Level | Description |
|-------------|---------------|-------------|
| 80-100 | **Excellent** | High agricultural relevance, specific terms |
| 60-79 | **Good** | Relevant agricultural content, some generic terms |
| 40-59 | **Fair** | Basic agricultural recognition, needs improvement |
| 0-39 | **Poor** | Limited agricultural context, mostly generic |
## 🔧 Agricultural Distinctions
The AI system automatically applies agricultural distinctions:
### Farmer vs Rancher Logic
- **Farmer**: Detected when crops, grains, or cultivation mentioned
- **Rancher**: Detected when cattle, livestock, or grazing mentioned
- **Dairy Farmer**: Detected when milk, dairy, or Holstein mentioned
- **Chicken Farmer**: Detected when poultry, chickens, or eggs mentioned
### Gender Identification
- Combines gender detection with agricultural roles
- Examples: "male farmer", "female rancher"
## 📊 Performance Metrics
**Current System Performance:**
- **Processing Speed**: ~3 seconds per image
- **Batch Capability**: 500+ images efficiently
- **Quality Score**: 65.2/100 average
- **Scalability**: 1000 images in ~50 minutes
## 🌐 Web UI Features
### Interactive Interface
- **Drag & Drop**: Upload multiple images easily
- **Real-time Processing**: See results as they're generated
- **Quality Visualization**: Color-coded quality scores
- **Demo Mode**: Test with sample agricultural images
### Visual Elements
- **Green Theme**: Agricultural color scheme
- **Responsive Design**: Works on desktop and mobile
- **Progress Indicators**: Loading states and progress bars
- **Error Handling**: Clear error messages and recovery
## 🔒 Error Handling
### Common Error Responses
**400 Bad Request**
```json
{
"detail": "Invalid image format. Please upload JPG, PNG, or similar."
}
```
**500 Internal Server Error**
```json
{
"detail": "AI system not initialized"
}
```
**404 Not Found**
```json
{
"detail": "Sample images not found"
}
```
## 🧪 Testing the API
### Python Example
```python
import requests
# Test system status
response = requests.get("http://localhost:8000/status")
print(response.json())
# Analyze single image
with open("farm_photo.jpg", "rb") as f:
files = {"file": f}
response = requests.post("http://localhost:8000/analyze/single", files=files)
print(response.json())
# Run demo
response = requests.get("http://localhost:8000/demo")
print(response.json())
```
### JavaScript Example
```javascript
// Analyze image with fetch API
const formData = new FormData();
formData.append('file', imageFile);
fetch('http://localhost:8000/analyze/single', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data));
```
## 🚀 Production Deployment
### Docker Deployment
```dockerfile
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "src.api.main:app", "--host", "0.0.0.0", "--port", "8000"]
```
### Environment Variables
```bash
# Optional configuration
export MODEL_PATH="/path/to/custom/model" # Use custom trained model
export MAX_UPLOAD_SIZE="10MB" # Limit upload size
export BATCH_SIZE_LIMIT="50" # Limit batch processing
```
## 📈 Integration Examples
### Stock Photo Platform Integration
```python
# Example integration for stock photo workflow
import requests
def process_new_photos(photo_directory):
files = []
for photo in os.listdir(photo_directory):
files.append(('files', open(os.path.join(photo_directory, photo), 'rb')))
response = requests.post("http://localhost:8000/analyze/batch", files=files)
results = response.json()
# Update database with AI-generated keywords
for result in results['results']:
update_photo_keywords(result['filename'], result['keywords'])
```
### Quality Control Workflow
```python
# Filter high-quality results
def filter_high_quality_results(api_response):
high_quality = []
for result in api_response['results']:
if result['quality_score'] >= 70:
high_quality.append(result)
return high_quality
```
## 🎯 Next Steps
1. **Start the UI**: `python3 start_ui.py`
2. **Test with Demo**: Click "Run Demo" button
3. **Upload Your Photos**: Drag and drop agricultural images
4. **Integrate API**: Use endpoints in your applications
5. **Scale Up**: Process your 30,000 photo dataset
---
**Ready to demonstrate the system to your team!** 🚜✨