FarmIQ / app.py
Mr-Thop's picture
Update app.py
c503048 verified
from flask import Flask, request, jsonify
from flask_cors import CORS
import mysql.connector as sql
import os
import jwt
import datetime
from functools import wraps
from werkzeug.security import generate_password_hash, check_password_hash
import google.generativeai as genai
import base64
import io
from PIL import Image
import json
import random
# Environment variables
db_user = os.getenv("user") or "avnadmin"
db_host = os.getenv("host") or "farmiq-mysql-farmiq010-277c.h.aivencloud.com"
db_pass = os.getenv("pass") or "AVNS_sr_v_vrFGFroeHBkZXx"
db_port = int(os.getenv("port") or 13233)
# Gemini API configuration
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or "your-gemini-api-key-here"
genai.configure(api_key=GEMINI_API_KEY)
SECRET_KEY = 'f059d4507faf907d515844116d466d815667dca0d33be3f3e0044558c30d19e5'
def conn():
return sql.connect(
host=db_host,
user=db_user,
password=db_pass,
port=db_port,
database="defaultdb"
)
app = Flask(__name__)
CORS(app)
# JWT Auth Decorator
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = request.headers.get('Authorization')
if token and token.startswith("Bearer "):
token = token.split(" ")[1]
else:
return jsonify({"error": "Token is missing"}), 401
try:
data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
request.user = data
except:
return jsonify({"error": "Token is invalid"}), 403
return f(*args, **kwargs)
return decorated
# ============= AUTHENTICATION =============
@app.route("/api/auth/register", methods=["POST"])
def register():
data = request.json
name, email, password, role = data.get("name"), data.get("email"), data.get("password"), data.get("role")
password = generate_password_hash(password)
try:
con = conn()
cur = con.cursor()
cur.execute("SELECT * FROM users WHERE user_email=%s", (email,))
if cur.fetchone():
return jsonify({"error": "User already exists"}), 409
cur.execute("INSERT INTO users (user_name, user_email, user_pwd, user_role) VALUES (%s, %s, %s, %s)",
(name, email, password, role))
con.commit()
user_id = cur.lastrowid
token = jwt.encode({
"user_id": user_id,
"email": email,
"role": role,
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=24)
}, SECRET_KEY)
return jsonify({
"user": {"id": user_id, "name": name, "email": email, "role": role},
"token": token
}), 201
except Exception as e:
print(e)
return jsonify({"error": "Server error"}), 500
finally:
cur.close()
con.close()
@app.route("/api/auth/login", methods=["POST"])
def login():
data = request.json
email, password = data.get("email"), data.get("password")
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("SELECT * FROM users WHERE user_email=%s", (email,))
user = cur.fetchone()
if not user:
return jsonify({"error": "User not found"}), 404
if not check_password_hash(user["user_pwd"], password):
return jsonify({"error": "Invalid credentials"}), 401
token = jwt.encode({
"user_id": user["user_id"],
"email": email,
"role": user["user_role"],
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=24)
}, SECRET_KEY)
return jsonify({
"user": {
"id": user["user_id"],
"name": user["user_name"],
"email": user["user_email"],
"role": user["user_role"]
},
"token": token
})
except Exception as e:
print(e)
return jsonify({"error": "Server error"}), 500
finally:
cur.close()
con.close()
@app.route("/api/auth/me", methods=["GET"])
@token_required
def get_current_user():
"""Get current user info"""
return jsonify({"user": request.user}), 200
# ============= CHAT WITH GEMINI =============
@app.route("/api/chat", methods=["POST"])
@token_required
def chat():
"""Chat with Gemini AI"""
try:
data = request.json
message = data.get("message")
if not message:
return jsonify({"error": "Message is required"}), 400
# Create Gemini model (with error handling)
try:
if GEMINI_API_KEY and GEMINI_API_KEY != "your-gemini-api-key-here":
model = genai.GenerativeModel('gemini-2.0-flash-exp')
# Create farming-focused prompt
prompt = f"""
You are FarmIQ AI, an expert agricultural assistant. Help farmers with:
- Crop recommendations and farming advice
- Plant disease identification and treatment
- Weather and seasonal guidance
- Market insights and pricing
- Sustainable farming practices
User question: {message}
Provide helpful, practical advice for farmers.
"""
response = model.generate_content(prompt)
ai_response = response.text
else:
raise Exception("Gemini API key not configured")
except Exception as gemini_error:
print(f"Gemini API error: {gemini_error}")
# Enhanced fallback responses based on message content
message_lower = message.lower()
if any(word in message_lower for word in ['disease', 'pest', 'bug', 'leaf']):
ai_response = f"Regarding your question about '{message}': For plant diseases and pests, I recommend regular inspection of your crops, proper spacing for air circulation, and using organic treatments like neem oil when possible. If you notice unusual symptoms, remove affected parts immediately and consider consulting a local agricultural extension office."
elif any(word in message_lower for word in ['crop', 'plant', 'grow', 'seed']):
ai_response = f"About '{message}': Choose crops suitable for your climate and soil type. Ensure proper soil preparation with organic matter, maintain consistent watering, and follow recommended planting schedules. Consider crop rotation to maintain soil health."
elif any(word in message_lower for word in ['weather', 'rain', 'temperature']):
ai_response = f"Regarding '{message}': Weather plays a crucial role in farming. Monitor local forecasts, protect crops during extreme weather, and adjust watering based on rainfall. Consider using mulch to regulate soil temperature and moisture."
elif any(word in message_lower for word in ['market', 'price', 'sell']):
ai_response = f"About '{message}': Research local market demands, consider direct-to-consumer sales, and focus on quality produce. Building relationships with local buyers and maintaining consistent supply can help with better pricing."
else:
ai_response = f"Thank you for asking about '{message}'. As your FarmIQ assistant, I recommend focusing on sustainable farming practices: proper soil management, integrated pest management, efficient water use, and crop diversification. For specific advice, consider consulting with local agricultural experts who understand your regional conditions."
# Save chat to database (with error handling)
try:
con = conn()
cur = con.cursor()
cur.execute("""
INSERT INTO chat_history (user_id, user_message, ai_response, created_at)
VALUES (%s, %s, %s, %s)
""", (request.user["user_id"], message, ai_response, datetime.datetime.now()))
con.commit()
except Exception as db_error:
print(f"Database error in chat: {db_error}")
# Continue without saving to database
return jsonify({
"message": ai_response,
"suggestions": [
"Ask about crop diseases",
"Get weather advice",
"Market price information",
"Soil health tips"
]
}), 200
except Exception as e:
print(f"Chat error: {e}")
# Return a successful response with fallback message instead of 500 error
return jsonify({
"message": "I'm your FarmIQ assistant! I can help you with crop recommendations, disease identification, weather advice, and market insights. What would you like to know about farming today?",
"suggestions": ["Ask about crop diseases", "Get weather advice", "Market price information", "Soil health tips"]
}), 200
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
@app.route("/api/chat/history", methods=["GET"])
@token_required
def get_chat_history():
"""Get chat history for user"""
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("""
SELECT user_message, ai_response, created_at
FROM chat_history
WHERE user_id = %s
ORDER BY created_at DESC
LIMIT 50
""", (request.user["user_id"],))
history = cur.fetchall()
return jsonify({"history": history}), 200
except Exception as e:
print(f"Chat history error: {e}")
return jsonify({"error": "Failed to fetch chat history"}), 500
finally:
cur.close()
con.close()
# ============= CUSTOMER ENDPOINTS =============
@app.route("/api/customer/saved", methods=["GET"])
@token_required
def get_saved_items():
"""Get user's saved items"""
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("""
SELECT si.*, p.name, p.price, p.image_url
FROM saved_items si
LEFT JOIN products p ON si.item_id = p.id AND si.item_type = 'product'
WHERE si.user_id = %s
""", (request.user["user_id"],))
saved_items = cur.fetchall()
return jsonify({"saved_items": saved_items}), 200
except Exception as e:
print(f"Get saved items error: {e}")
return jsonify({"saved_items": []}), 200
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
@app.route("/api/customer/farms", methods=["GET"])
@token_required
def get_customer_farms():
"""Get farms for customer view"""
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("SELECT * FROM farms LIMIT 20")
farms = cur.fetchall()
return jsonify({"farms": farms}), 200
except Exception as e:
print(f"Get farms error: {e}")
return jsonify({"farms": []}), 200
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
# ============= MARKET FUNCTIONALITY =============
@app.route("/api/products", methods=["GET"])
def get_products():
"""Get all products with filtering"""
try:
query = request.args
filters = []
values = []
if "search" in query:
filters.append("name LIKE %s")
values.append(f"%{query['search']}%")
if "category" in query:
filters.append("category = %s")
values.append(query["category"])
if "organic" in query:
filters.append("organic = %s")
values.append(query["organic"] == "true")
where = f"WHERE {' AND '.join(filters)}" if filters else ""
sql_query = f"SELECT * FROM products {where} LIMIT 100"
con = conn()
cur = con.cursor(dictionary=True)
cur.execute(sql_query, tuple(values))
products = cur.fetchall()
return jsonify({"products": products}), 200
except Exception as e:
print(f"Get products error: {e}")
return jsonify({"error": "Could not fetch products"}), 500
finally:
cur.close()
con.close()
@app.route("/api/products/<int:product_id>", methods=["GET"])
def get_product_by_id(product_id):
"""Get single product by ID"""
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("SELECT * FROM products WHERE id = %s", (product_id,))
product = cur.fetchone()
if not product:
return jsonify({"error": "Product not found"}), 404
return jsonify({"product": product}), 200
except Exception as e:
print(f"Get product error: {e}")
return jsonify({"error": "Could not fetch product"}), 500
finally:
cur.close()
con.close()
@app.route("/api/products", methods=["POST"])
@token_required
def add_product():
"""Add new product (for farmers)"""
try:
data = request.json
con = conn()
cur = con.cursor()
cur.execute("""
INSERT INTO products (user_id, name, description, price, unit,
image_url, category, organic, available)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (
request.user["user_id"], data["name"], data["description"],
data["price"], data["unit"], data.get("image_url"),
data.get("category"), data.get("organic", False),
data.get("available", True)
))
con.commit()
return jsonify({"message": "Product added successfully"}), 201
except Exception as e:
print(f"Add product error: {e}")
return jsonify({"error": "Could not add product"}), 500
finally:
cur.close()
con.close()
@app.route("/api/cart", methods=["GET"])
@token_required
def get_cart():
"""Get user's cart"""
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("""
SELECT ci.id, ci.quantity, ci.product_id, p.name, p.price, p.unit, p.image_url
FROM cart_items ci
JOIN products p ON ci.product_id = p.id
WHERE ci.user_id = %s
""", (request.user["user_id"],))
items = cur.fetchall() or []
total = sum(float(item['price']) * int(item['quantity']) for item in items) if items else 0
return jsonify({
"items": items,
"total": total,
"count": len(items)
}), 200
except Exception as e:
print(f"Get cart error: {e}")
# Return empty cart instead of error
return jsonify({
"items": [],
"total": 0,
"count": 0
}), 200
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
@app.route("/api/cart", methods=["POST"])
@token_required
def add_to_cart():
"""Add item to cart"""
try:
data = request.json
product_id = data.get("product_id")
quantity = data.get("quantity", 1)
con = conn()
cur = con.cursor()
# Check if item already in cart
cur.execute("SELECT * FROM cart_items WHERE user_id = %s AND product_id = %s",
(request.user["user_id"], product_id))
existing = cur.fetchone()
if existing:
# Update quantity
cur.execute("UPDATE cart_items SET quantity = quantity + %s WHERE user_id = %s AND product_id = %s",
(quantity, request.user["user_id"], product_id))
else:
# Add new item
cur.execute("INSERT INTO cart_items (user_id, product_id, quantity) VALUES (%s, %s, %s)",
(request.user["user_id"], product_id, quantity))
con.commit()
return jsonify({"message": "Item added to cart"}), 200
except Exception as e:
print(f"Add to cart error: {e}")
return jsonify({"error": "Could not add to cart"}), 500
finally:
cur.close()
con.close()
@app.route("/api/orders", methods=["POST"])
@token_required
def create_order():
"""Create new order"""
try:
data = request.json
con = conn()
cur = con.cursor()
# Create order
cur.execute("""
INSERT INTO orders (user_id, total_amount, status, shipping_address, created_at)
VALUES (%s, %s, %s, %s, %s)
""", (request.user["user_id"], data["total"], "pending",
data.get("address"), datetime.datetime.now()))
order_id = cur.lastrowid
# Add order items from cart
cur.execute("""
INSERT INTO order_items (order_id, product_id, quantity, price)
SELECT %s, ci.product_id, ci.quantity, p.price
FROM cart_items ci
JOIN products p ON ci.product_id = p.id
WHERE ci.user_id = %s
""", (order_id, request.user["user_id"]))
# Clear cart
cur.execute("DELETE FROM cart_items WHERE user_id = %s", (request.user["user_id"],))
con.commit()
return jsonify({"message": "Order created successfully", "order_id": order_id}), 201
except Exception as e:
print(f"Create order error: {e}")
return jsonify({"error": "Could not create order"}), 500
finally:
cur.close()
con.close()
# ============= CROP RECOMMENDATION (IMAGE + YES/NO) =============
@app.route("/api/crop-recommendation", methods=["POST"])
@token_required
def crop_recommendation():
"""Crop recommendation with image input - returns yes/no"""
try:
# Handle image input
image_data = None
if 'image' in request.files:
image_file = request.files['image']
image = Image.open(image_file.stream)
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_data = base64.b64encode(buffered.getvalue()).decode()
elif request.json and 'image_base64' in request.json:
image_data = request.json['image_base64']
if ',' in image_data:
image_data = image_data.split(',')[1]
else:
return jsonify({"error": "No image provided"}), 400
# Generate random yes/no result
result = random.choice(["yes", "no"])
response_data = {
"result": result,
"message": "Suitable for crop cultivation" if result == "yes" else "Not suitable for crop cultivation",
"confidence": random.randint(75, 95),
"recommendations": [
"Tomato", "Wheat", "Rice"
] if result == "yes" else [],
"advice": "Good soil conditions detected" if result == "yes" else "Soil needs improvement"
}
# Save to database
con = conn()
cur = con.cursor()
cur.execute("""
INSERT INTO crop_analysis (user_id, image_data, result, analysis_data, created_at)
VALUES (%s, %s, %s, %s, %s)
""", (request.user["user_id"], image_data, result,
json.dumps(response_data), datetime.datetime.now()))
con.commit()
return jsonify(response_data), 200
except Exception as e:
print(f"Crop recommendation error: {e}")
return jsonify({"error": "Failed to analyze image"}), 500
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
# ============= LEAF DETECTION (IMAGE + YES/NO) =============
@app.route("/api/leaf-detection", methods=["POST"])
@token_required
def leaf_detection():
"""Leaf disease detection with image input - returns yes/no"""
try:
# Handle image input
image_data = None
if 'image' in request.files:
image_file = request.files['image']
image = Image.open(image_file.stream)
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_data = base64.b64encode(buffered.getvalue()).decode()
elif request.json and 'image_base64' in request.json:
image_data = request.json['image_base64']
if ',' in image_data:
image_data = image_data.split(',')[1]
else:
return jsonify({"error": "No image provided"}), 400
# Generate random yes/no result
result = random.choice(["yes", "no"])
response_data = {
"result": result,
"disease_detected": result == "yes",
"message": "Disease detected in leaf" if result == "yes" else "Leaf appears healthy",
"confidence": random.randint(80, 98),
"disease_name": random.choice(["Leaf Spot", "Blight", "Rust", "Powdery Mildew"]) if result == "yes" else "None",
"severity": random.choice(["mild", "moderate", "severe"]) if result == "yes" else "none",
"treatment": [
"Apply fungicide",
"Remove affected leaves",
"Improve air circulation"
] if result == "yes" else ["Continue regular care"],
"prevention": [
"Regular inspection",
"Proper watering",
"Good plant hygiene"
]
}
# Save to database
con = conn()
cur = con.cursor()
cur.execute("""
INSERT INTO leaf_analysis (user_id, image_data, result, disease_detected,
analysis_data, created_at)
VALUES (%s, %s, %s, %s, %s, %s)
""", (request.user["user_id"], image_data, result, result == "yes",
json.dumps(response_data), datetime.datetime.now()))
con.commit()
return jsonify(response_data), 200
except Exception as e:
print(f"Leaf detection error: {e}")
return jsonify({"error": "Failed to analyze leaf image"}), 500
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
# ============= LEAF ANALYSIS (ALTERNATIVE ENDPOINT) =============
@app.route("/api/leaf-analysis", methods=["POST"])
@token_required
def leaf_analysis():
"""Leaf analysis endpoint (alternative to leaf-detection) - returns yes/no"""
try:
data = request.json
# Handle image input
image_data = None
if 'image_url' in data:
# Base64 image from frontend
image_url = data['image_url']
if ',' in image_url:
image_data = image_url.split(',')[1]
else:
image_data = image_url
elif 'image' in request.files:
image_file = request.files['image']
image = Image.open(image_file.stream)
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_data = base64.b64encode(buffered.getvalue()).decode()
else:
return jsonify({"error": "No image provided"}), 400
# Get additional data from request
plant_type = data.get('plant', 'unknown')
# Generate random yes/no result
result = random.choice(["yes", "no"])
response_data = {
"result": result,
"disease_detected": result == "yes",
"message": "Disease detected in leaf" if result == "yes" else "Leaf appears healthy",
"confidence": random.randint(80, 98),
"plant": plant_type,
"disease_name": random.choice(["Leaf Spot", "Early Blight", "Late Blight", "Rust", "Powdery Mildew"]) if result == "yes" else "None",
"severity": random.choice(["mild", "moderate", "severe"]) if result == "yes" else "none",
"treatments": [
"Apply fungicide spray",
"Remove affected leaves",
"Improve air circulation",
"Reduce watering frequency"
] if result == "yes" else ["Continue regular care", "Monitor plant health"],
"prevention": [
"Regular plant inspection",
"Proper spacing between plants",
"Avoid overhead watering",
"Good garden hygiene"
]
}
# Save to database
try:
con = conn()
cur = con.cursor()
cur.execute("""
INSERT INTO leaf_analysis (user_id, image_data, plant_type, result,
disease_detected, analysis_data, created_at)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""", (request.user["user_id"], image_data, plant_type, result,
result == "yes", json.dumps(response_data), datetime.datetime.now()))
con.commit()
except Exception as db_error:
print(f"Database error in leaf analysis: {db_error}")
# Continue without saving to database
return jsonify(response_data), 200
except Exception as e:
print(f"Leaf analysis error: {e}")
return jsonify({"error": "Failed to analyze leaf image"}), 500
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
@app.route("/api/leaf-analysis/history", methods=["GET"])
@token_required
def get_leaf_analysis_history():
"""Get user's leaf analysis history"""
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("""
SELECT id, plant_type, result, disease_detected, analysis_data, created_at
FROM leaf_analysis
WHERE user_id = %s
ORDER BY created_at DESC
LIMIT 20
""", (request.user["user_id"],))
history = cur.fetchall()
# Parse JSON analysis results
for item in history:
if item['analysis_data']:
item['analysis_data'] = json.loads(item['analysis_data'])
return jsonify({"history": history}), 200
except Exception as e:
print(f"Leaf analysis history error: {e}")
return jsonify({"history": []}), 200
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
# ============= SOIL ANALYSIS (IMAGE + YES/NO) =============
@app.route("/api/soil-analysis", methods=["POST"])
@token_required
def soil_analysis():
"""Soil analysis with image input - returns yes/no for soil quality"""
try:
# Handle image input
image_data = None
if 'image' in request.files:
image_file = request.files['image']
image = Image.open(image_file.stream)
buffered = io.BytesIO()
image.save(buffered, format="JPEG")
image_data = base64.b64encode(buffered.getvalue()).decode()
elif request.json and 'image_base64' in request.json:
image_data = request.json['image_base64']
if ',' in image_data:
image_data = image_data.split(',')[1]
else:
return jsonify({"error": "No image provided"}), 400
# Generate random yes/no result for soil quality
result = random.choice(["yes", "no"])
response_data = {
"result": result,
"soil_quality": "good" if result == "yes" else "poor",
"message": "Soil appears healthy and fertile" if result == "yes" else "Soil needs improvement",
"confidence": random.randint(75, 95),
"soil_type": random.choice(["Loamy", "Clay", "Sandy", "Silty"]),
"ph_level": round(random.uniform(5.5, 8.0), 1),
"nutrients": {
"nitrogen": random.choice(["low", "medium", "high"]),
"phosphorus": random.choice(["low", "medium", "high"]),
"potassium": random.choice(["low", "medium", "high"])
},
"recommendations": [
"Add organic compost",
"Test pH levels regularly",
"Consider crop rotation"
] if result == "yes" else [
"Add organic matter",
"Improve drainage",
"Test for nutrient deficiencies",
"Consider soil amendments"
],
"suitable_crops": [
"Tomatoes", "Wheat", "Corn", "Beans"
] if result == "yes" else [
"Cover crops", "Legumes for nitrogen fixing"
]
}
# Save to database
try:
con = conn()
cur = con.cursor()
cur.execute("""
INSERT INTO soil_analysis (user_id, image_data, result, soil_quality,
analysis_data, created_at)
VALUES (%s, %s, %s, %s, %s, %s)
""", (request.user["user_id"], image_data, result, response_data["soil_quality"],
json.dumps(response_data), datetime.datetime.now()))
con.commit()
except Exception as db_error:
print(f"Database error in soil analysis: {db_error}")
# Continue without saving to database
return jsonify(response_data), 200
except Exception as e:
print(f"Soil analysis error: {e}")
return jsonify({"error": "Failed to analyze soil image"}), 500
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
@app.route("/api/soil-analysis/history", methods=["GET"])
@token_required
def get_soil_analysis_history():
"""Get user's soil analysis history"""
try:
con = conn()
cur = con.cursor(dictionary=True)
cur.execute("""
SELECT id, result, soil_quality, analysis_data, created_at
FROM soil_analysis
WHERE user_id = %s
ORDER BY created_at DESC
LIMIT 20
""", (request.user["user_id"],))
history = cur.fetchall()
# Parse JSON analysis results
for item in history:
if item['analysis_data']:
item['analysis_data'] = json.loads(item['analysis_data'])
return jsonify({"history": history}), 200
except Exception as e:
print(f"Soil history error: {e}")
return jsonify({"history": []}), 200
finally:
if 'cur' in locals():
cur.close()
if 'con' in locals():
con.close()
# ============= DEFAULT ROUTE =============
@app.route("/", methods=["GET"])
def home():
return jsonify({"message": "FarmIQ Simple API Running"}), 200
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5000)