1- from flask import Flask , jsonify , request
2- from flask_cors import CORS
3- import numpy as np
1+ from flask import Flask , render_template , jsonify
2+ import random
43
54app = Flask (__name__ )
6- CORS (app )
75
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"""
6+ # Agriculture Knowledge Base
7+ AGRICULTURE_KNOWLEDGE_BASE = {
8+ "recommendations" : [
9+ "Implement precision irrigation scheduling" ,
10+ "Adopt integrated pest management" ,
11+ "Use soil moisture sensors" ,
12+ "Apply crop rotation strategies" ,
13+ "Monitor weather patterns for planting" ,
14+ "Utilize organic fertilizers" ,
15+ "Practice conservation tillage" ,
16+ "Install windbreaks for soil protection"
17+ ],
18+ "details" : [
19+ """Precision Irrigation Best Practices:
20+ - Use soil moisture sensors for data-driven watering
21+ - Implement drip irrigation systems
22+ - Schedule irrigation during cooler hours
23+ - Monitor evapotranspiration rates
24+ - Adjust for crop growth stages""" ,
25+
26+ """Integrated Pest Management:
27+ - Regular field scouting
28+ - Use biological control agents
29+ - Implement trap cropping
30+ - Apply targeted pesticides
31+ - Maintain pest monitoring records"""
32+ ]
4833}
4934
50- # Convert recommendations into numerical vectors for search
51- def text_to_vector (text ):
52- return np .array ([ord (char ) for char in text ])
35+ def generate_recommendation_cards (num_cards = 3 ):
36+ """
37+ Generates recommendation dashboard cards for farmers.
38+ """
39+ recommendations = AGRICULTURE_KNOWLEDGE_BASE ["recommendations" ]
40+ details = AGRICULTURE_KNOWLEDGE_BASE ["details" ]
5341
54- recommendation_vectors = { rec : text_to_vector ( rec ) for rec in recommendations }
42+ selected_recommendations = random . sample ( recommendations , min ( num_cards , len ( recommendations )))
5543
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 )
44+ recommendation_cards = []
45+ for rec in selected_recommendations :
46+ detail_index = recommendations .index (rec ) if recommendations .index (rec ) < len (details ) else None
47+ recommendation_cards .append ({
48+ "title" : rec ,
49+ "details" : details [detail_index ] if detail_index is not None else "Additional information not available."
50+ })
6451
65- @app .route ('/' )
66- def home ():
67- return jsonify ({"message" : "Welcome to the Agricultural Expert System API!" })
68-
69- @app .route ('/recommendations' , methods = ['GET' ])
70- def get_recommendations ():
71- return jsonify ({"recommendations" : recommendations })
52+ return recommendation_cards
7253
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." )
54+ @app .route ("/" )
55+ def home ():
56+ return render_template ("index.html" , recommendations = generate_recommendation_cards ())
8157
82- return jsonify ({
83- "query" : query ,
84- "matched_recommendation" : best_match ,
85- "details" : detail
86- })
58+ @app .route ("/api/recommendations" )
59+ def api_recommendations ():
60+ return jsonify (generate_recommendation_cards ())
8761
88- if __name__ == ' __main__' :
89- app .run (host = ' 0.0.0.0' , port = 5000 )
62+ if __name__ == " __main__" :
63+ app .run (host = " 0.0.0.0" , port = 8000 )
0 commit comments