1- # Azure Web app.py
21from flask import Flask , jsonify , request
32from flask_cors import CORS
43import numpy as np
5- import faiss
6- import os
74
85app = Flask (__name__ )
9- CORS (app ) # Enable CORS for cross-origin requests
6+ CORS (app )
107
11- # Agricultural best practices database
12- AGRICULTURE_KNOWLEDGE_BASE = {
13- "recommendations" : [
14- "Implement precision irrigation scheduling" ,
15- "Adopt integrated pest management" ,
16- "Use soil moisture sensors" ,
17- "Apply crop rotation strategies" ,
18- "Monitor weather patterns for planting" ,
19- "Utilize organic fertilizers" ,
20- "Practice conservation tillage" ,
21- "Install windbreaks for soil protection"
22- ],
23- "details" : [
24- """Precision Irrigation Best Practices:
25- - Use soil moisture sensors for data-driven watering
26- - Implement drip irrigation systems
27- - Schedule irrigation during cooler hours
28- - Monitor evapotranspiration rates
29- - Adjust for crop growth stages""" ,
30-
31- """Integrated Pest Management:
32- - Regular field scouting
33- - Use biological control agents
34- - Implement trap cropping
35- - Apply targeted pesticides
36- - Maintain pest monitoring records""" ,
37-
38- # Add other details entries...
39- ]
8+ # Expert recommendations
9+ recommendations = [
10+ "Optimize irrigation scheduling" ,
11+ "Implement field health monitoring" ,
12+ "Set up pest & disease alerts" ,
13+ "Conduct soil analysis & fertilization advice" ,
14+ "Follow weather-based farming recommendations"
15+ ]
16+
17+ # Detailed knowledge base for each recommendation
18+ detailed_knowledge = {
19+ "Optimize irrigation scheduling" : """Irrigation Scheduling Details:
20+ - Use soil moisture sensors for precision watering
21+ - Adjust schedules based on crop growth stages
22+ - Consider evapotranspiration rates
23+ - Implement drip irrigation for efficiency""" ,
24+
25+ "Implement field health monitoring" : """Field Health Monitoring Details:
26+ - Regular satellite imagery analysis
27+ - Drone-based NDVI scans weekly
28+ - Soil nutrient level tracking
29+ - Early stress detection algorithms""" ,
30+
31+ "Set up pest & disease alerts" : """Pest & Disease Alerts Details:
32+ - Automated pheromone trap monitoring
33+ - Weather-based outbreak prediction
34+ - Image recognition for disease identification
35+ - Integrated pest management strategies""" ,
36+
37+ "Conduct soil analysis & fertilization advice" : """Soil Analysis Details:
38+ - Seasonal nutrient profiling
39+ - pH balance optimization
40+ - Organic matter content analysis
41+ - Custom fertilizer blending recommendations""" ,
42+
43+ "Follow weather-based farming recommendations" : """Weather-based Farming Details:
44+ - Microclimate prediction models
45+ - Frost/heatwave early warning systems
46+ - Rainfall pattern adaptation
47+ - Crop variety selection advisor"""
4048}
4149
42- # Create embeddings and FAISS index
43- embeddings = np .random .randn (len (AGRICULTURE_KNOWLEDGE_BASE ["recommendations" ]), 128 ).astype ('float32' )
44- index = faiss .IndexFlatL2 (128 )
45- index .add (embeddings )
50+ # Convert recommendations into numerical vectors for search
51+ def text_to_vector (text ):
52+ return np .array ([ord (char ) for char in text ])
53+
54+ recommendation_vectors = {rec : text_to_vector (rec ) for rec in recommendations }
55+
56+ def find_best_match (query ):
57+ """Find the most relevant recommendation using cosine similarity"""
58+ query_vector = text_to_vector (query )
59+ similarities = {
60+ rec : np .dot (query_vector , rec_vector ) / (np .linalg .norm (query_vector ) * np .linalg .norm (rec_vector ))
61+ for rec , rec_vector in recommendation_vectors .items ()
62+ }
63+ return max (similarities , key = similarities .get )
64+
65+ @app .route ('/' )
66+ def home ():
67+ return jsonify ({"message" : "Welcome to the Agricultural Expert System API!" })
4668
4769@app .route ('/recommendations' , methods = ['GET' ])
4870def get_recommendations ():
49- """Return list of agricultural best practices recommendations"""
50- return jsonify ({
51- "source" : "FAO Agricultural Best Practices Database" ,
52- "recommendations" : AGRICULTURE_KNOWLEDGE_BASE ["recommendations" ],
53- "last_updated" : "2024-03-15"
54- })
71+ return jsonify ({"recommendations" : recommendations })
5572
56- @app .route ('/details' , methods = ['POST' ])
57- def get_details ():
58- """Get detailed information for a specific recommendation"""
59- data = request .json
60- try :
61- index = int (data .get ('index' ))
62- if index < 0 or index >= len (AGRICULTURE_KNOWLEDGE_BASE ["recommendations" ]):
63- raise ValueError
64- except (ValueError , TypeError ):
65- return jsonify ({"error" : "Invalid recommendation index" }), 400
73+ @app .route ('/recommendation/detail' , methods = ['GET' ])
74+ def get_recommendation_detail ():
75+ query = request .args .get ('query' , '' ).strip ()
76+ if not query :
77+ return jsonify ({"error" : "Query parameter is required" }), 400
78+
79+ best_match = find_best_match (query )
80+ detail = detailed_knowledge .get (best_match , "No details available." )
6681
6782 return jsonify ({
68- "recommendation" : AGRICULTURE_KNOWLEDGE_BASE ["recommendations" ][index ],
69- "details" : AGRICULTURE_KNOWLEDGE_BASE ["details" ][index ],
70- "related_resources" : [
71- "FAO Guidelines" ,
72- "Local Extension Services" ,
73- "Climate Smart Agriculture Handbook"
74- ]
75- })
76-
77- @app .route ('/' )
78- def health_check ():
79- return jsonify ({
80- "status" : "active" ,
81- "service" : "Agricultural Best Practices API" ,
82- "version" : "1.2.0"
83+ "query" : query ,
84+ "matched_recommendation" : best_match ,
85+ "details" : detail
8386 })
8487
8588if __name__ == '__main__' :
86- app .run (host = '0.0.0.0' , port = int ( os . environ . get ( 'PORT' , 5000 )) )
89+ app .run (host = '0.0.0.0' , port = 5000 )
0 commit comments