saritha commited on
Commit
ed83dd4
·
verified ·
1 Parent(s): d521450

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -17
app.py CHANGED
@@ -4,6 +4,7 @@ from PIL import Image
4
  from torchvision import transforms
5
  import warnings
6
  import sys
 
7
  import os
8
  import contextlib
9
  from transformers import ViTForImageClassification, pipeline
@@ -39,18 +40,106 @@ transform = transforms.Compose([
39
  # Load the class names (disease types)
40
  class_names = ['BacterialBlights', 'Healthy', 'Mosaic', 'RedRot', 'Rust', 'Yellow']
41
 
42
- # Load AI response generator (using a local GPT pipeline or OpenAI's GPT-3/4 API)
43
- ai_pipeline = pipeline("text-generation", model="gpt2", tokenizer="gpt2")
 
 
 
 
 
44
 
45
  # Knowledge base for sugarcane diseases (example data from the website)
46
- knowledge_base = {
47
- 'BacterialBlights': "Bacterial blights cause water-soaked lesions on leaves, leading to yellowing and withering. To manage, apply copper-based fungicides and ensure proper drainage.",
48
- 'Mosaic': "Mosaic disease results in streaked and mottled leaves, reducing photosynthesis. Use disease-resistant varieties and control aphids to prevent spread.",
49
- 'RedRot': "Red rot is identified by reddening and rotting of stalks. Remove infected plants and treat soil with appropriate fungicides.",
50
- 'Rust': "Rust appears as orange pustules on leaves. Apply systemic fungicides and maintain optimal field conditions to reduce spread.",
51
- 'Yellow': "Yellowing indicates nutrient deficiencies or initial disease stages. Test soil and provide balanced fertilizers.",
52
- 'Healthy': "The sugarcane crop is healthy. Continue regular monitoring and good agronomic practices."
53
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  # Update the predict_disease function
56
  def predict_disease(image):
@@ -65,13 +154,13 @@ def predict_disease(image):
65
  # Get the predicted label
66
  predicted_label = class_names[predicted_class.item()]
67
 
68
- # Retrieve response from knowledge base
69
- if predicted_label in knowledge_base:
70
- detailed_response = knowledge_base[predicted_label]
71
- else:
72
- # Fallback to AI-generated response
73
- prompt = f"The detected sugarcane disease is '{predicted_label}'. Provide detailed advice for managing this condition."
74
- detailed_response = ai_pipeline(prompt, max_length=100, num_return_sequences=1, truncation=True)[0]['generated_text']
75
 
76
  # Create a styled HTML output
77
  output_message = f"""
 
4
  from torchvision import transforms
5
  import warnings
6
  import sys
7
+ import google.generativeai as genai
8
  import os
9
  import contextlib
10
  from transformers import ViTForImageClassification, pipeline
 
40
  # Load the class names (disease types)
41
  class_names = ['BacterialBlights', 'Healthy', 'Mosaic', 'RedRot', 'Rust', 'Yellow']
42
 
43
+ #Gemini Response
44
+ def get_response_llm(predicted_label,knowledge_base)
45
+ prompt = f"Your an helpful assistant who helps farmers know about the sugarcane leaf diseases , precaution, advise etc....Predicted disease label will is given to you '{predicted_label}' and also {knowledge_base} Provide detailed advice for managing this condition."
46
+ genai.configure(api_key="YOUR_API_KEY")
47
+ model = genai.GenerativeModel("gemini-1.5-flash")
48
+ response = model.generate_content([prompt])
49
+ return response.text
50
 
51
  # Knowledge base for sugarcane diseases (example data from the website)
52
+ # Comprehensive knowledge base for sugarcane diseases and practices
53
+ knowledge_base = """
54
+ 'BacterialBlights': Bacterial blights are caused by *Xanthomonas albilineans*.
55
+ **Symptoms:**
56
+ - Water-soaked lesions on leaves.
57
+ - Gradual yellowing and withering of leaves.
58
+ - Reduction in photosynthesis and stunted growth.
59
+
60
+ **Management:**
61
+ - Apply copper-based fungicides.
62
+ - Improve field drainage to avoid waterlogging.
63
+ - Use disease-free planting material.""",
64
+
65
+ 'Mosaic': """Mosaic disease is caused by the Sugarcane mosaic virus (SCMV) and often transmitted by aphids.
66
+ **Symptoms:**
67
+ - Mottled appearance on leaves with streaks of yellow and green.
68
+ - Reduced photosynthetic efficiency.
69
+ - Decreased cane weight and sugar content.
70
+
71
+ **Management:**
72
+ - Use resistant sugarcane varieties.
73
+ - Control aphid populations with insecticides.
74
+ - Remove and destroy infected plants to prevent spread.""",
75
+
76
+ 'RedRot': """Red rot is caused by the fungus *Colletotrichum falcatum*.
77
+ **Symptoms:**
78
+ - Red streaks inside the cane with white patches.
79
+ - Rotting of the stalk, emitting a sour smell.
80
+ - Drying of leaves and eventual plant death.
81
+
82
+ **Management:**
83
+ - Plant resistant varieties.
84
+ - Remove and burn infected plants.
85
+ - Treat soil with fungicides and practice crop rotation.""",
86
+
87
+ 'Rust': """Rust is caused by the fungus *Puccinia melanocephala*.
88
+ **Symptoms:**
89
+ - Formation of orange to reddish pustules on leaves.
90
+ - Premature drying of leaves.
91
+ - Reduced plant vigor and yield.
92
+
93
+ **Management:**
94
+ - Apply systemic fungicides (e.g., triazoles).
95
+ - Ensure proper field hygiene.
96
+ - Avoid water stress and maintain balanced nutrition.""",
97
+
98
+ 'Yellow': """Yellowing can be caused by nutrient deficiencies or disease onset.
99
+ **Symptoms:**
100
+ - Yellowing of leaf tips or entire leaves.
101
+ - Reduced photosynthesis and growth.
102
+
103
+ **Management:**
104
+ - Conduct soil testing to identify deficiencies.
105
+ - Apply balanced fertilizers as per soil nutrient status.
106
+ - Maintain proper irrigation schedules.""",
107
+
108
+ 'Smut': """Smut is caused by the fungus *Sporisorium scitamineum*.
109
+ **Symptoms:**
110
+ - Formation of whip-like structures at the growing points.
111
+ - Stunted growth and tiller proliferation.
112
+ - Reduced sugar content.
113
+
114
+ **Management:**
115
+ - Plant smut-resistant varieties.
116
+ - Remove smut-infected plants.
117
+ - Treat seed sets with fungicides before planting.""",
118
+
119
+ 'Healthy': """The sugarcane crop is healthy.
120
+ Continue regular monitoring and follow good agronomic practices:
121
+ - Ensure balanced fertilization.
122
+ - Maintain proper irrigation schedules.
123
+ - Monitor for pests and diseases regularly.""",
124
+
125
+ 'GeneralPractices': """**General Practices for Disease Prevention**
126
+ - **Field Sanitation:** Remove and destroy crop residues and infected plants to reduce inoculum levels.
127
+ - **Resistant Varieties:** Cultivate sugarcane varieties that are resistant to specific diseases.
128
+ - **Seed Treatment:** Use disease-free, certified seed material. Treat seed sets with fungicides before planting.
129
+ - **Crop Rotation:** Rotate sugarcane with non-host crops to break the disease cycle.
130
+ - **Optimal Agronomic Practices:** Ensure proper irrigation and drainage. Maintain balanced fertilization and avoid over-application of nitrogen.
131
+ - **Timely Monitoring and Control:** Inspect fields regularly for symptoms. Apply recommended fungicides or bactericides as soon as symptoms appear.
132
+ - **Integrated Pest and Disease Management (IPDM):** Combine biological, chemical, and cultural methods to manage diseases sustainably.""",
133
+
134
+ 'ImpactOfDiseases': """**Impact of Sugarcane Diseases**
135
+ - **Yield Reduction:** Diseases like red rot and smut can reduce cane yield by 30–60%.
136
+ - **Quality Degradation:** Affected plants produce less sugar and lower-quality juice.
137
+ - **Economic Losses:** Increased cost of management and reduced marketable output affect profitability.""",
138
+
139
+ 'SugarcaneOverview': """Sugarcane is a critical crop globally, providing raw materials for sugar, ethanol, and other byproducts.
140
+ However, it is susceptible to various diseases caused by fungi, bacteria, viruses, and environmental factors.
141
+ Effective management practices are essential to ensure high yield and quality."""
142
+
143
 
144
  # Update the predict_disease function
145
  def predict_disease(image):
 
154
  # Get the predicted label
155
  predicted_label = class_names[predicted_class.item()]
156
 
157
+ # # Retrieve response from knowledge base
158
+ # if predicted_label in knowledge_base:
159
+ # detailed_response = knowledge_base[predicted_label]
160
+ # else:
161
+ # # Fallback to AI-generated response
162
+
163
+ detailed_response = get_response_llm(predicted_label,knowledge_base)
164
 
165
  # Create a styled HTML output
166
  output_message = f"""