Spaces:
Sleeping
Sleeping
File size: 13,054 Bytes
768e711 a4f944b 768e711 a4f944b 768e711 a4f944b 768e711 0513722 a4f944b 0513722 768e711 a4f944b 768e711 a4f944b 768e711 a4f944b 768e711 a4f944b 768e711 412d9ff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
import os
import json
import re
import time
import logging
from datetime import datetime
from flask import Flask, render_template, request, jsonify, session, make_response
from google import genai
from dotenv import load_dotenv
from cachelib import SimpleCache
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
# Configure the Gemini API - get key from env or Hugging Face Spaces secrets
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
logger.warning("GEMINI_API_KEY not found in environment variables. Make sure to set it in Hugging Face Spaces secrets.")
client = genai.Client(api_key=api_key)
# Initialize cache (7 days timeout)
cache = SimpleCache(threshold=50, default_timeout=60*60*24*7)
app = Flask(__name__)
# Use secret key from environment or a default for development
app.secret_key = os.getenv("SECRET_KEY", "dev_secret_key")
# Set session cookie settings to be more persistent
app.config['SESSION_COOKIE_SECURE'] = False # Set to True in HTTPS environments
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['PERMANENT_SESSION_LIFETIME'] = 60*60*24*7 # 7 days
# Supported languages
LANGUAGES = {
"en": "English",
"hi": "हिंदी (Hindi)",
"bn": "বাংলা (Bengali)",
"te": "తెలుగు (Telugu)",
"mr": "मराठी (Marathi)",
"ta": "தமிழ் (Tamil)",
"gu": "ગુજરાતી (Gujarati)",
"ur": "اردو (Urdu)",
"kn": "ಕನ್ನಡ (Kannada)",
"or": "ଓଡ଼ିଆ (Odia)",
"ml": "മലയാളം (Malayalam)"
}
# List of pests and diseases
PESTS_DISEASES = [
{
"id": 1,
"name": "Fall Armyworm",
"type": "pest",
"crop": "Maize, Sorghum",
"image_url": "static/images/fall_armyworm.jpg"
},
{
"id": 2,
"name": "Rice Blast",
"type": "disease",
"crop": "Rice",
"image_url": "static/images/rice_blast.jpg"
},
{
"id": 3,
"name": "Aphids",
"type": "pest",
"crop": "Various crops",
"image_url": "static/images/aphids.jpg"
},
{
"id": 4,
"name": "Powdery Mildew",
"type": "disease",
"crop": "Wheat, Vegetables",
"image_url": "static/images/powdery_mildew.jpg"
},
{
"id": 5,
"name": "Stem Borer",
"type": "pest",
"crop": "Rice, Sugarcane",
"image_url": "static/images/stem_borer.jpg"
},
{
"id": 6,
"name": "Yellow Mosaic Virus",
"type": "disease",
"crop": "Pulses",
"image_url": "static/images/yellow_mosaic.jpg"
},
{
"id": 7,
"name": "Brown Planthopper",
"type": "pest",
"crop": "Rice",
"image_url": "static/images/brown_planthopper.jpg"
},
{
"id": 8,
"name": "Bacterial Leaf Blight",
"type": "disease",
"crop": "Rice",
"image_url": "static/images/bacterial_leaf_blight.jpg"
},
{
"id": 9,
"name": "Jassids",
"type": "pest",
"crop": "Cotton, Maize",
"image_url": "static/images/jassids.jpg"
},
{
"id": 10,
"name": "Downy Mildew",
"type": "disease",
"crop": "Grapes, Onion",
"image_url": "static/images/downy_mildew.jpg"
},
{
"id": 11,
"name": "Whitefly",
"type": "pest",
"crop": "Tomato, Cotton",
"image_url": "static/images/whitefly.jpg"
},
{
"id": 12,
"name": "Fusarium Wilt",
"type": "disease",
"crop": "Banana, Tomato",
"image_url": "static/images/fusarium_wilt.jpg"
}
]
@app.route('/')
def index():
# Set default language if not set
if 'language' not in session:
session['language'] = 'en'
# Make session persistent
session.permanent = True
return render_template('index.html',
pests_diseases=PESTS_DISEASES,
languages=LANGUAGES,
current_language=session['language'])
@app.route('/set_language', methods=['POST'])
def set_language():
language = request.form.get('language')
if language in LANGUAGES:
session.permanent = True
session['language'] = language
# Log the language change
logger.info(f"Language changed to {language}")
# Create a response with success message
response = make_response(jsonify({"success": True}))
# Set a cookie to ensure the language persists even if session fails
response.set_cookie('user_language', language, max_age=60*60*24*30) # 30 days
return response
return jsonify({"success": False}), 400
def extract_json_from_response(content):
"""Extract and parse JSON from API response."""
try:
# Try direct JSON parsing first
return json.loads(content)
except json.JSONDecodeError:
# If direct parsing fails, try to extract JSON from markdown code blocks
json_match = re.search(r'```json(.*?)```', content, re.DOTALL)
if json_match:
json_str = json_match.group(1).strip()
else:
json_str = content
# Clean up any potential markdown or text
json_str = json_str.replace('```json', '').replace('```', '')
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
logger.error(f"JSON parsing error: {str(e)}")
raise ValueError(f"Failed to parse response")
@app.route('/get_details/<int:pest_id>')
def get_details(pest_id):
# Get current language from session or cookie fallback
language = session.get('language', request.cookies.get('user_language', 'en'))
# Find the pest/disease by ID
pest_disease = next((item for item in PESTS_DISEASES if item["id"] == pest_id), None)
if not pest_disease:
return jsonify({"error": "Not found"}), 404
# Check cache first - cache key includes language
cache_key = f"pest_disease_{pest_id}_{language}"
cached_result = cache.get(cache_key)
if cached_result:
logger.info(f"Cache hit for pest_id {pest_id} in {language}")
return jsonify(cached_result)
logger.info(f"Cache miss for pest_id {pest_id} in {language}, fetching from API")
# If no API key is set, return a fake response for testing
if not api_key:
logger.warning("No API key set, returning placeholder content")
return jsonify({
**pest_disease,
"details": {
"description": {"title": "Description", "text": "API key not configured. Please set GEMINI_API_KEY in Hugging Face Spaces secrets."},
"lifecycle": {"title": "Lifecycle", "text": "Information not available without API key."},
"symptoms": {"title": "Symptoms", "text": "Information not available without API key."},
"impact": {"title": "Impact", "text": "Information not available without API key."},
"management": {"title": "Management", "text": "Information not available without API key."},
"prevention": {"title": "Prevention", "text": "Information not available without API key."}
},
"language": language,
"cached_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
# Generate prompt with language instruction
lang_instructions = {
"en": "Respond in English",
"hi": "हिंदी में जवाब दें (Respond in Hindi)",
"bn": "বাংলায় উত্তর দিন (Respond in Bengali)",
"te": "తెలుగులో సమాధానం ఇవ్వండి (Respond in Telugu)",
"mr": "मराठीत उत्तर द्या (Respond in Marathi)",
"ta": "தமிழில் பதிலளிக்கவும் (Respond in Tamil)",
"gu": "ગુજરાતીમાં જવાબ આપો (Respond in Gujarati)",
"ur": "اردو میں جواب دیں (Respond in Urdu)",
"kn": "ಕನ್ನಡದಲ್ಲಿ ಉತ್ತರಿಸಿ (Respond in Kannada)",
"or": "ଓଡ଼ିଆରେ ଉତ୍ତର ଦିଅନ୍ତୁ (Respond in Odia)",
"ml": "മലയാളത്തിൽ മറുപടി നൽകുക (Respond in Malayalam)"
}
prompt = f"""
{lang_instructions.get(language, "Respond in English")}
Provide detailed information about the agricultural {pest_disease['type']} known as {pest_disease['name']}
in the context of Indian agriculture, especially affecting {pest_disease['crop']}.
Include the following sections:
1. Description and identification
2. Lifecycle and spread
3. Damage symptoms
4. Economic impact
5. Management and control measures (both organic and chemical)
6. Preventive measures
Format the response as JSON with these keys: "description", "lifecycle", "symptoms",
"impact", "management", "prevention".
Each key should contain an object with "title" and "text" fields.
For example:
{{
"description": {{"title": "Description", "text": "Detailed description..."}},
"lifecycle": {{"title": "Lifecycle", "text": "Information about lifecycle..."}},
...
}}
Ensure the response is strictly valid JSON.
"""
try:
# Call AI API with retry logic
model = 'gemini-1.5-flash'
max_retries = 3
retry_delay = 2
for attempt in range(max_retries):
try:
response = client.models.generate_content(model=model, contents=prompt)
break
except Exception as e:
if attempt < max_retries - 1:
logger.warning(f"API call attempt {attempt+1} failed. Retrying...")
time.sleep(retry_delay)
retry_delay *= 2
else:
logger.error(f"All API call attempts failed for pest_id {pest_id}")
raise e
# Parse the response
detailed_info = extract_json_from_response(response.text)
# Validate the response structure
required_keys = ["description", "lifecycle", "symptoms", "impact", "management", "prevention"]
for key in required_keys:
if key not in detailed_info:
detailed_info[key] = {"title": f"{key.capitalize()}", "text": "Information not available."}
elif not isinstance(detailed_info[key], dict):
detailed_info[key] = {"title": f"{key.capitalize()}", "text": str(detailed_info[key])}
elif "text" not in detailed_info[key]:
detailed_info[key]["text"] = "Information not available."
# Add timestamp and language info
result = {
**pest_disease,
"details": detailed_info,
"language": language,
"cached_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
# Cache the result
cache.set(cache_key, result)
logger.info(f"Successfully cached data for pest_id {pest_id} in {language}")
return jsonify(result)
except Exception as e:
logger.error(f"Error: {str(e)}")
return jsonify({
"error": "Failed to fetch information",
"message": "Please try again later."
}), 500
@app.route('/api/pests')
def get_pests_list():
return jsonify(PESTS_DISEASES)
@app.route('/api/clear-cache/<int:pest_id>', methods=['POST'])
def clear_specific_cache(pest_id):
for lang in LANGUAGES.keys():
cache_key = f"pest_disease_{pest_id}_{lang}"
cache.delete(cache_key)
return jsonify({"success": True, "message": f"Cache cleared for pest ID {pest_id}"})
# Add a diagnostics endpoint to help debug session issues
@app.route('/debug/session')
def debug_session():
# Only enable in development
if os.getenv("FLASK_ENV") == "production":
return jsonify({"error": "Not available in production"}), 403
return jsonify({
"session_data": dict(session),
"cookies": dict(request.cookies),
"session_cookie_name": app.session_cookie_name,
"session_cookie_secure": app.config.get('SESSION_COOKIE_SECURE'),
"session_cookie_httponly": app.config.get('SESSION_COOKIE_HTTPONLY'),
"session_cookie_samesite": app.config.get('SESSION_COOKIE_SAMESITE'),
"permanent_session_lifetime": str(app.config.get('PERMANENT_SESSION_LIFETIME'))
})
if __name__ == '__main__':
# Use PORT environment variable if available (for Hugging Face Spaces)
port = int(os.environ.get("PORT", 7860))
app.run(host="0.0.0.0", port=port) |