Spaces:
Runtime error
Runtime error
Download api/app.py from Pavankumardns/flora: direct link, hf CLI and curl.
- Browser
- Download file 38 kB
-
https://huggingface.co/spaces/Pavankumardns/flora/resolve/main/api/app.py
- Command line
-
hf download hf://spaces/Pavankumardns/flora/api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Pavankumardns/flora/resolve/main/api/app.py
38 kB
from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_cors import CORS
import os
import numpy as np
from PIL import Image
import io
import base64
import torch
import torch.nn as nn
import torch.nn.functional as F
import tensorflow as tf
import tensorflow_hub as hub
from werkzeug.utils import secure_filename
from pymongo import MongoClient
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__, static_folder='dist')
CORS(app) # Enable CORS for all routes
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.config['UPLOAD_FOLDER'] = 'uploads'
# MongoDB setup
MONGO_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017/')
client = MongoClient(MONGO_URI)
db = client['flora_ai']
plants_collection = db['plants']
watering_collection = db['watering_tasks']
# Create uploads folder if it doesn't exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Plant Disease Classes
PLANT_DISEASE_CLASSES = [
'Apple___Apple_scab', 'Apple___Black_rot', 'Apple___Cedar_apple_rust', 'Apple___healthy',
'Blueberry___healthy', 'Cherry_(including_sour)___Powdery_mildew',
'Cherry_(including_sour)___healthy', 'Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot',
'Corn_(maize)___Common_rust_', 'Corn_(maize)___Northern_Leaf_Blight', 'Corn_(maize)___healthy',
'Grape___Black_rot', 'Grape___Esca_(Black_Measles)', 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)',
'Grape___healthy', 'Orange___Haunglongbing_(Citrus_greening)', 'Peach___Bacterial_spot',
'Peach___healthy', 'Pepper,_bell___Bacterial_spot', 'Pepper,_bell___healthy',
'Potato___Early_blight', 'Potato___Late_blight', 'Potato___healthy',
'Raspberry___healthy', 'Soybean___healthy', 'Squash___Powdery_mildew',
'Strawberry___Leaf_scorch', 'Strawberry___healthy', 'Tomato___Bacterial_spot',
'Tomato___Early_blight', 'Tomato___Late_blight', 'Tomato___Leaf_Mold',
'Tomato___Septoria_leaf_spot', 'Tomato___Spider_mites Two-spotted_spider_mite',
'Tomato___Target_Spot', 'Tomato___Tomato_Yellow_Leaf_Curl_Virus', 'Tomato___Tomato_mosaic_virus',
'Tomato___healthy'
]
# Soil Classes
SOIL_CLASSES = ('Alluvial soil', 'Black Soil', 'Clay soil', 'Red soil')
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Plant Disease Model Architecture
class ImageClassificationBase(nn.Module):
def training_step(self, batch):
images, labels = batch
out = self(images)
loss = F.cross_entropy(out, labels)
return loss
def validation_step(self, batch):
images, labels = batch
out = self(images)
loss = F.cross_entropy(out, labels)
acc = accuracy(out, labels)
return {'val_loss': loss.detach(), 'val_acc': acc}
def validation_epoch_end(self, outputs):
batch_losses = [x['val_loss'] for x in outputs]
epoch_loss = torch.stack(batch_losses).mean()
batch_accs = [x['val_acc'] for x in outputs]
epoch_acc = torch.stack(batch_accs).mean()
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
def epoch_end(self, epoch, result):
print("Epoch [{}], train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}".format(
epoch, result['train_loss'], result['val_loss'], result['val_acc']))
def ConvBlock(in_channels, out_channels, pool=False):
layers = [nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)]
if pool:
layers.append(nn.MaxPool2d(4))
return nn.Sequential(*layers)
class ResNet9(ImageClassificationBase):
def __init__(self, in_channels, num_diseases):
super().__init__()
self.conv1 = ConvBlock(in_channels, 64)
self.conv2 = ConvBlock(64, 128, pool=True)
self.res1 = nn.Sequential(ConvBlock(128, 128), ConvBlock(128, 128))
self.conv3 = ConvBlock(128, 256, pool=True)
self.conv4 = ConvBlock(256, 512, pool=True)
self.res2 = nn.Sequential(ConvBlock(512, 512), ConvBlock(512, 512))
self.classifier = nn.Sequential(nn.MaxPool2d(4),
nn.Flatten(),
nn.Linear(512, num_diseases))
def forward(self, xb):
out = self.conv1(xb)
out = self.conv2(out)
out = self.res1(out) + out
out = self.conv3(out)
out = self.conv4(out)
out = self.res2(out) + out
out = self.classifier(out)
return out
# Load models
print("Loading models...")
try:
# Load Plant Disease Model
checkpoint = torch.load('plant-disease-model-complete.pth', map_location=device)
# Check if it's a state_dict or full model
if isinstance(checkpoint, dict):
plant_disease_model = ResNet9(3, len(PLANT_DISEASE_CLASSES))
plant_disease_model.load_state_dict(checkpoint)
else:
# It's the full model
plant_disease_model = checkpoint
plant_disease_model.to(device)
plant_disease_model.eval()
print("Plant disease model loaded successfully!")
except Exception as e:
print(f"Error loading plant disease model: {e}")
plant_disease_model = None
try:
# Load Soil Analysis Model
soil_model = tf.keras.models.load_model('soil.h5', custom_objects={'KerasLayer': hub.KerasLayer})
print("Soil analysis model loaded successfully!")
except Exception as e:
print(f"Error loading soil model: {e}")
soil_model = None
def preprocess_image_plant(image):
"""Preprocess image for plant disease model"""
image = image.convert('RGB')
image = image.resize((256, 256))
image_array = np.array(image) / 255.0
image_tensor = torch.FloatTensor(image_array).permute(2, 0, 1)
return image_tensor.unsqueeze(0).to(device)
def preprocess_image_soil(image):
"""Preprocess image for soil analysis model"""
image = image.convert('RGB')
image = image.resize((224, 224))
image_array = np.array(image) / 255.0
return np.expand_dims(image_array, axis=0)
def predict_plant_disease(image):
"""Predict plant disease"""
if plant_disease_model is None:
return {"error": "Plant disease model not loaded"}
try:
image_tensor = preprocess_image_plant(image)
with torch.no_grad():
outputs = plant_disease_model(image_tensor)
_, predicted = torch.max(outputs, 1)
probabilities = F.softmax(outputs, dim=1)
confidence = probabilities[0][predicted].item() * 100
predicted_class = PLANT_DISEASE_CLASSES[predicted.item()]
# Format the result
plant, disease = predicted_class.split('___')
plant = plant.replace('_', ' ')
disease = disease.replace('_', ' ')
return {
"plant": plant,
"disease": disease,
"confidence": f"{confidence:.2f}%",
"raw_prediction": predicted_class
}
except Exception as e:
return {"error": str(e)}
def predict_soil_type(image):
"""Predict soil type"""
if soil_model is None:
return {"error": "Soil model not loaded"}
try:
image_array = preprocess_image_soil(image)
print(f"Soil image preprocessed, shape: {image_array.shape}")
predictions = soil_model.predict(image_array, verbose=0)
print(f"Predictions: {predictions}")
predicted_index = np.argmax(predictions)
confidence = predictions[0][predicted_index] * 100
return {
"soil_type": SOIL_CLASSES[predicted_index],
"confidence": f"{confidence:.2f}%",
"all_probabilities": {
SOIL_CLASSES[i]: f"{predictions[0][i]*100:.2f}%"
for i in range(len(SOIL_CLASSES))
}
}
except Exception as e:
import traceback
print(f"Error in predict_soil_type: {str(e)}")
print(traceback.format_exc())
return {"error": str(e)}
@app.route('/predict', methods=['POST'])
def predict():
print("\n=== NEW PREDICTION REQUEST ===")
print(f"Files in request: {list(request.files.keys())}")
print(f"Form data: {list(request.form.keys())}")
if 'file' not in request.files and 'image_data' not in request.form:
print("ERROR: No image provided")
return jsonify({"error": "No image provided"}), 400
model_type = request.form.get('model_type', 'plant')
print(f"Model type: {model_type}")
try:
# Handle file upload or base64 image
print("Step 1: Reading image...")
if 'file' in request.files and request.files['file'].filename != '':
file = request.files['file']
print(f" - File upload: {file.filename}")
image = Image.open(file.stream)
print(f" - Image opened: {image.size}, {image.mode}")
elif 'image_data' in request.form:
print(" - Base64 image data")
image_data = request.form['image_data']
if ',' in image_data:
image_data = image_data.split(',')[1]
image_bytes = base64.b64decode(image_data)
image = Image.open(io.BytesIO(image_bytes))
print(f" - Image opened: {image.size}, {image.mode}")
else:
print("ERROR: No valid image")
return jsonify({"error": "No valid image provided"}), 400
print("Step 2: Making prediction...")
# Make prediction based on model type
if model_type == 'plant':
print(" - Using plant disease model")
if plant_disease_model is None:
print("ERROR: Plant model not loaded")
return jsonify({"error": "Plant disease model not loaded"}), 500
result = predict_plant_disease(image)
else:
print(" - Using soil analysis model")
if soil_model is None:
print("ERROR: Soil model not loaded")
return jsonify({"error": "Soil model not loaded"}), 500
result = predict_soil_type(image)
print("Step 3: Processing result...")
if "error" in result:
print(f"Prediction error: {result['error']}")
return jsonify(result), 500
print(f"SUCCESS: {result}")
return jsonify(result)
except Exception as e:
import traceback
error_msg = str(e)
print(f"\n!!! EXCEPTION in predict route !!!")
print(f"Error: {error_msg}")
print("Traceback:")
print(traceback.format_exc())
return jsonify({"error": error_msg}), 500
@app.route('/plant-analysis', methods=['POST'])
def plant_analysis():
"""Get AI-powered plant health analysis using Groq"""
try:
from groq import Groq
import matplotlib
matplotlib.use('Agg') # Use non-interactive backend
import matplotlib.pyplot as plt
import seaborn as sns
data = request.json
plant = data.get('plant', 'Unknown')
disease = data.get('disease', 'Unknown')
confidence = data.get('confidence', '0%')
# Initialize Groq client
groq_api_key = os.getenv('GROQ_API_KEY')
if not groq_api_key:
return jsonify({"error": "GROQ_API_KEY not configured"}), 500
client = Groq(api_key=groq_api_key)
# Check if plant is healthy
is_healthy = 'healthy' in disease.lower()
if is_healthy:
prompt = f"""You are a plant health expert. The plant '{plant}' appears to be healthy with {confidence} confidence.
Provide a brief, encouraging response (2-3 sentences) about:
1. Confirmation that the plant is healthy
2. General care tips to maintain health
3. What to watch for
Keep it concise and positive."""
else:
prompt = f"""You are a plant disease expert. A '{plant}' plant has been diagnosed with '{disease}' with {confidence} confidence.
Provide a structured response with:
1. Disease Overview (1-2 sentences)
2. Recommended Medication/Treatment (specific products or methods)
3. Expected Recovery Time (in days/weeks)
4. Prevention Tips (2-3 points)
Be specific, practical, and concise."""
# Get AI response
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are an expert agricultural scientist specializing in plant diseases and treatments. Provide practical, actionable advice."
},
{
"role": "user",
"content": prompt
}
],
model="llama-3.1-70b-versatile",
temperature=0.7,
max_tokens=500
)
ai_response = chat_completion.choices[0].message.content
# Create visualization if disease detected
chart_url = None
if not is_healthy:
try:
# Create a simple severity chart
fig, ax = plt.subplots(figsize=(8, 4))
# Sample data for disease progression
stages = ['Initial', 'Early', 'Moderate', 'Severe']
severity = [20, 40, 60, 80]
colors = ['#68B030', '#FFB800', '#FF8C00', '#DC2626']
sns.barplot(x=stages, y=severity, palette=colors, ax=ax)
ax.set_ylabel('Severity Level (%)', fontsize=12)
ax.set_xlabel('Disease Stage', fontsize=12)
ax.set_title(f'{disease} - Severity Progression', fontsize=14, fontweight='bold')
ax.set_ylim(0, 100)
# Add confidence line
confidence_val = float(confidence.replace('%', ''))
ax.axhline(y=confidence_val, color='red', linestyle='--', label=f'Current: {confidence}')
ax.legend()
# Save chart
chart_path = os.path.join(app.config['UPLOAD_FOLDER'], 'disease_chart.png')
plt.tight_layout()
plt.savefig(chart_path, dpi=100, bbox_inches='tight')
plt.close()
# Convert to base64
with open(chart_path, 'rb') as f:
import base64
chart_data = base64.b64encode(f.read()).decode()
chart_url = f"data:image/png;base64,{chart_data}"
except Exception as e:
print(f"Chart generation error: {e}")
return jsonify({
"analysis": ai_response,
"isHealthy": is_healthy,
"chartUrl": chart_url
})
except Exception as e:
print(f"Plant analysis error: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({"error": str(e)}), 500
@app.route('/soil-analysis-ai', methods=['POST'])
def soil_analysis_ai():
"""Get AI-powered soil analysis with crop recommendations"""
try:
from groq import Groq
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
data = request.json
soil_type = data.get('soil_type', 'Unknown')
confidence = data.get('confidence', '0%')
# Get current weather for location
weather_response = get_weather()
weather_data = weather_response.get_json() if hasattr(weather_response, 'get_json') else {}
temperature = weather_data.get('temperature', 24)
humidity = weather_data.get('humidity', 60)
location = weather_data.get('location', 'your area')
# Initialize Groq client
groq_api_key = os.getenv('GROQ_API_KEY')
if not groq_api_key:
return jsonify({"error": "GROQ_API_KEY not configured"}), 500
client = Groq(api_key=groq_api_key)
prompt = f"""You are an agricultural expert. Analyze this soil and provide crop recommendations.
Soil Type: {soil_type}
Confidence: {confidence}
Current Weather: {temperature}°C, {humidity}% humidity
Location: {location}
Provide a structured response with:
1. Soil Characteristics (2-3 key properties)
2. Top 5 Recommended Crops (with brief reason for each)
3. Crops to Avoid (2-3 examples with reasons)
4. Soil Improvement Tips (3-4 actionable suggestions)
5. Best Planting Season (considering current weather)
Be specific, practical, and consider both soil type and weather conditions."""
# Get AI response
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are an expert agricultural scientist specializing in soil science and crop selection. Provide practical, region-specific advice."
},
{
"role": "user",
"content": prompt
}
],
model="llama-3.1-70b-versatile",
temperature=0.7,
max_tokens=800
)
ai_response = chat_completion.choices[0].message.content
# Create visualizations
charts = {}
try:
# Chart 1: Soil Properties Radar Chart
fig1, ax1 = plt.subplots(figsize=(8, 6), subplot_kw=dict(projection='polar'))
# Soil properties based on type
properties = {
'Alluvial soil': {'Fertility': 90, 'Drainage': 80, 'Water Retention': 85, 'Nutrient Content': 88, 'pH Balance': 75},
'Black Soil': {'Fertility': 95, 'Drainage': 60, 'Water Retention': 95, 'Nutrient Content': 90, 'pH Balance': 70},
'Clay soil': {'Fertility': 70, 'Drainage': 40, 'Water Retention': 95, 'Nutrient Content': 75, 'pH Balance': 65},
'Red soil': {'Fertility': 65, 'Drainage': 85, 'Water Retention': 50, 'Nutrient Content': 60, 'pH Balance': 60}
}
soil_props = properties.get(soil_type, properties['Alluvial soil'])
categories = list(soil_props.keys())
values = list(soil_props.values())
values += values[:1] # Complete the circle
angles = [n / float(len(categories)) * 2 * 3.14159 for n in range(len(categories))]
angles += angles[:1]
ax1.plot(angles, values, 'o-', linewidth=2, color='#68B030', label=soil_type)
ax1.fill(angles, values, alpha=0.25, color='#68B030')
ax1.set_xticks(angles[:-1])
ax1.set_xticklabels(categories, size=10)
ax1.set_ylim(0, 100)
ax1.set_title(f'{soil_type} - Properties Analysis', size=14, fontweight='bold', pad=20)
ax1.legend(loc='upper right', bbox_to_anchor=(1.3, 1.1))
ax1.grid(True)
chart1_path = os.path.join(app.config['UPLOAD_FOLDER'], 'soil_properties.png')
plt.tight_layout()
plt.savefig(chart1_path, dpi=100, bbox_inches='tight')
plt.close()
with open(chart1_path, 'rb') as f:
import base64
chart_data = base64.b64encode(f.read()).decode()
charts['properties'] = f"data:image/png;base64,{chart_data}"
# Chart 2: Crop Suitability Bar Chart
fig2, ax2 = plt.subplots(figsize=(10, 6))
# Crop suitability based on soil type
crop_suitability = {
'Alluvial soil': {'Rice': 95, 'Wheat': 90, 'Sugarcane': 88, 'Cotton': 75, 'Vegetables': 92, 'Fruits': 85},
'Black Soil': {'Cotton': 98, 'Wheat': 85, 'Sorghum': 90, 'Pulses': 88, 'Sunflower': 82, 'Tobacco': 80},
'Clay soil': {'Rice': 95, 'Wheat': 80, 'Barley': 75, 'Vegetables': 70, 'Sugarcane': 85, 'Pulses': 78},
'Red soil': {'Groundnut': 92, 'Pulses': 88, 'Millets': 90, 'Cotton': 75, 'Tobacco': 85, 'Oilseeds': 87}
}
crops_data = crop_suitability.get(soil_type, crop_suitability['Alluvial soil'])
crops = list(crops_data.keys())
suitability = list(crops_data.values())
colors = ['#68B030' if s >= 85 else '#FFB800' if s >= 75 else '#FF8C00' for s in suitability]
bars = ax2.barh(crops, suitability, color=colors)
ax2.set_xlabel('Suitability Score (%)', fontsize=12)
ax2.set_title(f'Crop Suitability for {soil_type}', fontsize=14, fontweight='bold')
ax2.set_xlim(0, 100)
# Add value labels
for i, (bar, val) in enumerate(zip(bars, suitability)):
ax2.text(val + 2, i, f'{val}%', va='center', fontsize=10)
chart2_path = os.path.join(app.config['UPLOAD_FOLDER'], 'crop_suitability.png')
plt.tight_layout()
plt.savefig(chart2_path, dpi=100, bbox_inches='tight')
plt.close()
with open(chart2_path, 'rb') as f:
chart_data = base64.b64encode(f.read()).decode()
charts['suitability'] = f"data:image/png;base64,{chart_data}"
# Chart 3: Weather Impact Heatmap
fig3, ax3 = plt.subplots(figsize=(8, 6))
# Weather suitability matrix
seasons = ['Winter', 'Spring', 'Summer', 'Monsoon', 'Autumn']
crop_types = ['Cereals', 'Pulses', 'Vegetables', 'Fruits', 'Cash Crops']
# Generate suitability matrix (0-100)
import numpy as np
np.random.seed(42)
suitability_matrix = np.random.randint(60, 100, size=(len(crop_types), len(seasons)))
sns.heatmap(suitability_matrix, annot=True, fmt='d', cmap='YlGn',
xticklabels=seasons, yticklabels=crop_types,
cbar_kws={'label': 'Suitability %'}, ax=ax3)
ax3.set_title(f'Seasonal Crop Suitability - {location}', fontsize=14, fontweight='bold')
chart3_path = os.path.join(app.config['UPLOAD_FOLDER'], 'seasonal_suitability.png')
plt.tight_layout()
plt.savefig(chart3_path, dpi=100, bbox_inches='tight')
plt.close()
with open(chart3_path, 'rb') as f:
chart_data = base64.b64encode(f.read()).decode()
charts['seasonal'] = f"data:image/png;base64,{chart_data}"
except Exception as e:
print(f"Chart generation error: {e}")
import traceback
traceback.print_exc()
return jsonify({
"analysis": ai_response,
"charts": charts,
"weather": {
"temperature": temperature,
"humidity": humidity,
"location": location
}
})
except Exception as e:
print(f"Soil analysis AI error: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({"error": str(e)}), 500
@app.route('/weather', methods=['GET'])
def get_weather():
"""Get weather data using IP-based location (free, no API key needed)"""
try:
import requests
# Get location from query params or use Hyderabad as default
city = request.args.get('city', 'Hyderabad')
# Use wttr.in - completely free weather API, no key needed
# Empty city string makes it auto-detect location from IP
url = f'https://wttr.in/{city}?format=j1'
print(f"Fetching weather from: {url}")
response = requests.get(url, timeout=10)
if response.status_code == 200:
data = response.json()
current = data['current_condition'][0]
location_info = data['nearest_area'][0]
# Extract weather data
temp = int(current['temp_C'])
humidity = int(current['humidity'])
# Calculate light level based on cloud coverage
cloud_cover = int(current['cloudcover'])
light_level = 100 - cloud_cover
# Estimate soil moisture based on humidity
soil_moisture = min(100, int(humidity * 0.7))
# Determine status
temp_status = "Optimal range" if 18 <= temp <= 28 else ("Too warm" if temp > 28 else "Too cool")
humidity_status = "Good level" if 50 <= humidity <= 70 else ("High" if humidity > 70 else "Low")
detected_location = location_info['areaName'][0]['value']
result = {
"temperature": temp,
"humidity": humidity,
"lightLevel": light_level,
"soilMoisture": soil_moisture,
"tempStatus": temp_status,
"humidityStatus": humidity_status,
"condition": current['weatherDesc'][0]['value'],
"location": detected_location
}
print(f"Weather data: {result}")
return jsonify(result)
else:
print(f"Weather API error: {response.status_code}")
return jsonify({"error": "Failed to fetch weather data"}), 500
except Exception as e:
print(f"Weather endpoint error: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({"error": str(e)}), 500
@app.route('/plants', methods=['GET'])
def get_plants():
"""Get all plants for a user"""
try:
user_id = request.args.get('userId')
if not user_id:
return jsonify({"error": "userId required"}), 400
plants = list(plants_collection.find({"userId": user_id}))
# Convert ObjectId to string
for plant in plants:
plant['_id'] = str(plant['_id'])
return jsonify(plants)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/plants', methods=['POST'])
def add_plant():
"""Add a new plant (manual or from scan)"""
try:
data = request.json
user_id = data.get('userId')
if not user_id:
return jsonify({"error": "userId required"}), 400
plant = {
"userId": user_id,
"name": data.get('name'),
"type": data.get('type'),
"health": data.get('health', 'healthy'),
"disease": data.get('disease'),
"confidence": data.get('confidence'),
"location": data.get('location', 'Garden'),
"addedDate": datetime.utcnow().isoformat(),
"lastWatered": data.get('lastWatered'),
"nextWatering": data.get('nextWatering'),
"imageUrl": data.get('imageUrl')
}
result = plants_collection.insert_one(plant)
plant['_id'] = str(result.inserted_id)
return jsonify(plant), 201
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/plants/<plant_id>', methods=['DELETE'])
def delete_plant(plant_id):
"""Delete a plant"""
try:
from bson.objectid import ObjectId
result = plants_collection.delete_one({"_id": ObjectId(plant_id)})
if result.deleted_count == 0:
return jsonify({"error": "Plant not found"}), 404
return jsonify({"message": "Plant deleted"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/plants/<plant_id>', methods=['PUT'])
def update_plant(plant_id):
"""Update plant information"""
try:
from bson.objectid import ObjectId
data = request.json
update_data = {}
if 'health' in data:
update_data['health'] = data['health']
if 'disease' in data:
update_data['disease'] = data['disease']
if 'lastWatered' in data:
update_data['lastWatered'] = data['lastWatered']
if 'nextWatering' in data:
update_data['nextWatering'] = data['nextWatering']
result = plants_collection.update_one(
{"_id": ObjectId(plant_id)},
{"$set": update_data}
)
if result.matched_count == 0:
return jsonify({"error": "Plant not found"}), 404
return jsonify({"message": "Plant updated"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/dashboard-stats', methods=['GET'])
def get_dashboard_stats():
"""Get dashboard statistics for a user"""
try:
user_id = request.args.get('userId')
if not user_id:
return jsonify({"error": "userId required"}), 400
plants = list(plants_collection.find({"userId": user_id}))
total_plants = len(plants)
healthy_plants = len([p for p in plants if p.get('health') == 'healthy'])
diseased = len([p for p in plants if p.get('health') == 'diseased'])
needs_attention = len([p for p in plants if p.get('health') == 'needs_attention'])
# Count watering tasks for today
today = datetime.utcnow().date().isoformat()
watering_today = len([p for p in plants if p.get('nextWatering', '').startswith(today)])
return jsonify({
"totalPlants": total_plants,
"healthyPlants": healthy_plants,
"needsAttention": needs_attention,
"diseased": diseased,
"wateringToday": watering_today
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/watering-tasks', methods=['GET'])
def get_watering_tasks():
"""Get watering schedule for a user"""
try:
user_id = request.args.get('userId')
if not user_id:
return jsonify({"error": "userId required"}), 400
plants = list(plants_collection.find({"userId": user_id, "nextWatering": {"$exists": True}}))
tasks = []
for plant in plants:
tasks.append({
"plantId": str(plant['_id']),
"plant": plant.get('name', plant.get('type')),
"time": plant.get('nextWatering'),
"priority": "high" if plant.get('health') == 'needs_attention' else "medium",
"status": "pending"
})
# Sort by time
tasks.sort(key=lambda x: x['time'])
return jsonify(tasks[:5]) # Return top 5
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/tasks', methods=['GET'])
def get_tasks():
"""Get all tasks for a user"""
try:
user_id = request.args.get('userId')
if not user_id:
return jsonify({"error": "userId required"}), 400
tasks = list(db['tasks'].find({"userId": user_id}).sort("dueDate", 1))
for task in tasks:
task['_id'] = str(task['_id'])
return jsonify(tasks)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/tasks', methods=['POST'])
def add_task():
"""Add a new task"""
try:
data = request.json
user_id = data.get('userId')
if not user_id:
return jsonify({"error": "userId required"}), 400
task = {
"userId": user_id,
"title": data.get('title'),
"description": data.get('description'),
"type": data.get('type'),
"priority": data.get('priority', 'medium'),
"dueDate": data.get('dueDate'),
"status": data.get('status', 'pending'),
"createdAt": datetime.utcnow().isoformat()
}
result = db['tasks'].insert_one(task)
task['_id'] = str(result.inserted_id)
return jsonify(task), 201
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/tasks/<task_id>', methods=['PUT'])
def update_task(task_id):
"""Update task status"""
try:
from bson.objectid import ObjectId
data = request.json
result = db['tasks'].update_one(
{"_id": ObjectId(task_id)},
{"$set": {"status": data.get('status', 'completed')}}
)
if result.matched_count == 0:
return jsonify({"error": "Task not found"}), 404
return jsonify({"message": "Task updated"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/generate-report', methods=['GET'])
def generate_report():
"""Generate AI-powered garden report"""
try:
from groq import Groq
user_id = request.args.get('userId')
if not user_id:
return jsonify({"error": "userId required"}), 400
# Get user's plants
plants = list(plants_collection.find({"userId": user_id}))
if not plants:
return jsonify({"error": "No plants found"}), 404
# Calculate stats
total_plants = len(plants)
healthy_plants = len([p for p in plants if p.get('health') == 'healthy'])
diseased = len([p for p in plants if p.get('health') == 'diseased'])
needs_attention = len([p for p in plants if p.get('health') == 'needs_attention'])
# Get disease details
diseased_details = [
f"{p.get('name', p.get('type'))}: {p.get('disease', 'Unknown')}"
for p in plants if p.get('health') == 'diseased'
]
# Initialize Groq
groq_api_key = os.getenv('GROQ_API_KEY')
if not groq_api_key:
return jsonify({"error": "GROQ_API_KEY not configured"}), 500
client = Groq(api_key=groq_api_key)
prompt = f"""You are an expert agricultural consultant. Generate a comprehensive garden health report.
Garden Statistics:
- Total Plants: {total_plants}
- Healthy Plants: {healthy_plants}
- Diseased Plants: {diseased}
- Needs Attention: {needs_attention}
Diseased Plants Details:
{chr(10).join(diseased_details) if diseased_details else "None"}
Provide TWO sections:
1. GARDEN HEALTH SUMMARY (3-4 paragraphs):
- Overall health assessment
- Key observations and trends
- Areas of concern
- Positive highlights
2. TREATMENT RECOMMENDATIONS:
- Specific pesticides/fungicides for detected diseases
- Application methods and frequency
- Preventive measures
- Organic alternatives
- Expected recovery timeline
Be specific, practical, and professional."""
chat_completion = client.chat.completions.create(
messages=[
{
"role": "system",
"content": "You are an expert agricultural consultant specializing in plant health management and disease treatment."
},
{
"role": "user",
"content": prompt
}
],
model="llama-3.1-70b-versatile",
temperature=0.7,
max_tokens=1500
)
full_response = chat_completion.choices[0].message.content
# Split into summary and recommendations
parts = full_response.split("2. TREATMENT RECOMMENDATIONS")
summary = parts[0].replace("1. GARDEN HEALTH SUMMARY", "").strip()
recommendations = parts[1].strip() if len(parts) > 1 else "No specific recommendations at this time."
return jsonify({
"summary": summary,
"recommendations": recommendations,
"stats": {
"totalPlants": total_plants,
"healthyPlants": healthy_plants,
"diseasedPlants": diseased,
"needsAttention": needs_attention
}
})
except Exception as e:
print(f"Report generation error: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({"error": str(e)}), 500
# Serve static files
@app.route('/assets/<path:filename>')
def serve_assets(filename):
return send_from_directory(os.path.join(app.static_folder, 'assets'), filename)
@app.route('/logo.png')
def serve_logo():
return send_from_directory(app.static_folder, 'logo.png')
@app.route('/bell.png')
def serve_bell():
return send_from_directory(app.static_folder, 'bell.png')
@app.route('/favicon.ico')
def serve_favicon():
return send_from_directory(app.static_folder, 'favicon.ico')
# Serve root
@app.route('/')
def index():
return send_from_directory(app.static_folder, 'index.html')
# Catch all other routes and serve React app
@app.route('/<path:path>')
def catch_all(path):
"""Catch-all route for React Router"""
print(f"\n=== CATCH_ALL CALLED: {path} ===")
# Check if it's a static file
if '.' in path:
file_path = os.path.join(app.static_folder, path)
if os.path.exists(file_path):
return send_from_directory(app.static_folder, path)
# Serve index.html for all React Router paths
return send_from_directory(app.static_folder, 'index.html')
if __name__ == '__main__':
port = int(os.environ.get('PORT', 10000))
print(f"Starting full app on port {port}")
app.run(debug=True, host='0.0.0.0', port=port, use_reloader=False)
from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_cors import CORS
import os
import numpy as np
from PIL import Image
import io
import base64
import torch
import torch.nn as nn
import torch.nn.functional as F
import tensorflow as tf
import tensorflow_hub as hub
from werkzeug.utils import secure_filename
from pymongo import MongoClient
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__, static_folder='dist')
CORS(app) # Enable CORS for all routes
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.config['UPLOAD_FOLDER'] = 'uploads'
# MongoDB setup
MONGO_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017/')
client = MongoClient(MONGO_URI)
db = client['flora_ai']
plants_collection = db['plants']
watering_collection = db['watering_tasks']
# Create uploads folder if it doesn't exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Plant Disease Classes
PLANT_DISEASE_CLASSES = [
'Apple___Apple_scab', 'Apple___Black_rot', 'Apple___Cedar_apple_rust', 'Apple___healthy',
'Blueberry___healthy', 'Cherry_(including_sour)___Powdery_mildew',
'Cherry_(including_sour)___healthy', 'Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot',
'Corn_(maize)___Common_rust_', 'Corn_(maize)___Northern_Leaf_Blight', 'Corn_(maize)___healthy',
'Grape___Black_rot', 'Grape___Esca_(Black_Measles)', 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)',
'Grape___healthy', 'Orange___Haunglongbing_(Citrus_greening)', 'Peach___Bacterial_spot',
'Peach___healthy', 'Pepper,_bell___Bacterial_spot', 'Pepper,_bell___healthy',
'Potato___Early_blight', 'Potato___Late_blight', 'Potato___healthy',
'Raspberry___healthy', 'Soybean___healthy', 'Squash___Powdery_mildew',
'Strawberry___Leaf_scorch', 'Strawberry___healthy', 'Tomato___Bacterial_spot',
'Tomato___Early_blight', 'Tomato___Late_blight', 'Tomato___Leaf_Mold',
'Tomato___Septoria_leaf_spot', 'Tomato___Spider_mites Two-spotted_spider_mite',
'Tomato___Target_Spot', 'Tomato___Tomato_Yellow_Leaf_Curl_Virus', 'Tomato___Tomato_mosaic_virus',
'Tomato___healthy'
]
# Soil Classes
SOIL_CLASSES = ('Alluvial soil', 'Black Soil', 'Clay soil', 'Red soil')
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Plant Disease Model Architecture
class ImageClassificationBase(nn.Module):
def training_step(self, batch):
images, labels = batch
out = self(images)
loss = F.cross_entropy(out, labels)
return loss
def validation_step(self, batch):
images, labels = batch
out = self(images)
loss = F.cross_entropy(out, labels)
acc = accuracy(out, labels)
return {'val_loss': loss.detach(), 'val_acc': acc}
def validation_epoch_end(self, outputs):
batch_losses = [x['val_loss'] for x in outputs]
epoch_loss = torch.stack(batch_losses).mean()
batch_accs = [x['val_acc'] for x in outputs]
epoch_acc = torch.stack(batch_accs).mean()
return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}
def epoch_end(self, epoch, result):
print("Epoch [{}], train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}".format(
epoch, result['train_loss'], result['val_loss'], result['val_acc']))
def ConvBlock(in_channels, out_channels, pool=False):
layers = [nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)]
if pool:
layers.append(nn.MaxPool2d(4))
return nn.Sequential(*layers)
class ResNet9(ImageClassificationBase):
def __init__(self, in_channels, num_diseases):
super().__init__()
self.conv1 = ConvBlock(in_channels, 64)
self.conv2 = ConvBlock(64, 128, pool=True)
self.res1 = nn.Sequential(ConvBlock(128, 128), ConvBlock(128, 128))