Update app.py
Browse files
app.py
CHANGED
|
@@ -109,15 +109,15 @@ RECOMMENDATIONS = {
|
|
| 109 |
# BACTERIAL DISEASES (2)
|
| 110 |
# =========================================================================
|
| 111 |
'bacterial_leaf_blight': {
|
| 112 |
-
'recommendation': 'Use resistant varieties like PSB Rc18 (ALA), NSIC Rc354, or NSIC Rc302. Apply balanced nutrients, especially nitrogen (avoid excess). Maintain good drainage and field sanitation: weed removal, plow under stubbles and straw. Destroy ratoons and volunteer seedlings. Allow fallow fields to dry to suppress pathogens. Consult your local DA technician for specific advice.',
|
| 113 |
-
'details': 'Bacterial Leaf Blight (BLB) is caused by Xanthomonas oryzae pv. oryzae.
|
| 114 |
'category': 'Bacterial',
|
| 115 |
'severity': 'High'
|
| 116 |
},
|
| 117 |
|
| 118 |
'bacterial_leaf_streak': {
|
| 119 |
-
'recommendation': 'Use resistant rice varieties. Apply balanced fertilization and avoid excessive nitrogen. Maintain proper field drainage and sanitation. Remove and destroy infected plant debris. Practice crop rotation where possible. Use copper-based bactericides only if infection is severe, following BPI guidelines. Consult local DA for variety recommendations.',
|
| 120 |
-
'details': 'Bacterial Leaf Streak (BLS) is caused by Xanthomonas oryzae pv. oryzicola. Symptoms
|
| 121 |
'category': 'Bacterial',
|
| 122 |
'severity': 'Medium'
|
| 123 |
},
|
|
@@ -134,7 +134,7 @@ RECOMMENDATIONS = {
|
|
| 134 |
|
| 135 |
'brown_spot': {
|
| 136 |
'recommendation': 'Plant resistant varieties and ensure balanced fertilization, especially sufficient potassium (use complete or potash fertilizers). Conduct soil test and correct deficiencies. Improve soil health and maintain proper field drainage. Use clean, healthy seeds and practice field sanitation (remove stubbles, weeds). Split nitrogen fertilizer application. Apply calcium silicate & potassium fertilizers. If severe, apply fungicides (triazoles, strobilurins) following BPI registration and safety rules. Consult local DA.',
|
| 137 |
-
'details': 'Brown Spot is caused by Cochliobolus miyabeanus.
|
| 138 |
'category': 'Fungal',
|
| 139 |
'severity': 'Medium to High'
|
| 140 |
},
|
|
@@ -148,35 +148,35 @@ RECOMMENDATIONS = {
|
|
| 148 |
|
| 149 |
'rice_blast': {
|
| 150 |
'recommendation': 'Use resistant varieties such as PSB Rc18 or IRRI-derived lines. Avoid high nitrogen application and split nitrogen fertilizer application. Maintain proper irrigation (avoid water stress) and field sanitation (remove stubbles, debris). Adjust planting calendar to avoid peak infection period. Apply calcium silicate to strengthen cell walls. Apply fungicides: triazoles and strobilurins at first signs, especially during tillering/booting. Burn or plow under infected straw. Consult local DA.',
|
| 151 |
-
'details': 'Rice Blast is caused by Magnaporthe oryzae
|
| 152 |
'category': 'Fungal',
|
| 153 |
'severity': 'Very High'
|
| 154 |
},
|
| 155 |
|
| 156 |
'rice_false_smut': {
|
| 157 |
'recommendation': 'Use disease-free seeds and resistant varieties. Apply balanced fertilization, avoid excessive nitrogen at heading stage. Ensure proper field drainage and spacing for air circulation. Apply preventive fungicides (triazoles, strobilurins) at booting to early heading stage. Remove and destroy infected panicles (burn, do not compost). Adjust planting date to avoid high humidity during flowering. Consult DA for timing and fungicide recommendations.',
|
| 158 |
-
'details': 'Rice False Smut is caused by Ustilaginoidea virens fungus. Individual grains are transformed into large (1-2 cm), velvety, yellow-green to dark green balls of fungal spores. Infected grains are replaced by smut balls that reduce yield and grain quality.
|
| 159 |
'category': 'Fungal',
|
| 160 |
'severity': 'Medium'
|
| 161 |
},
|
| 162 |
|
| 163 |
'sheath_blight': {
|
| 164 |
'recommendation': 'Use moderately resistant varieties. Apply balanced fertilization, avoid excessive nitrogen. Maintain proper plant spacing for air circulation. Ensure good water management and drainage. Remove lower infected leaves when feasible. Apply fungicides (validamycin, azoxystrobin) at early infection stages. Use silicon fertilizers to strengthen plant tissue. Practice crop rotation with non-host crops. Consult local DA for fungicide timing.',
|
| 165 |
-
'details': 'Sheath Blight is caused by Rhizoctonia solani fungus.
|
| 166 |
'category': 'Fungal',
|
| 167 |
'severity': 'High'
|
| 168 |
},
|
| 169 |
|
| 170 |
'sheath_rot': {
|
| 171 |
'recommendation': 'Use resistant or tolerant varieties. Apply balanced fertilization (avoid excess nitrogen at late growth stages). Maintain proper water management, especially during heading. Ensure adequate spacing for air circulation. Remove and destroy infected panicles. Apply fungicides at boot leaf stage if disease history exists. Practice field sanitation. Consult DA for variety and fungicide recommendations.',
|
| 172 |
-
'details': 'Sheath Rot is caused primarily by Sarocladium oryzae (formerly Acrocylindrium oryzae). Symptoms include grayish-brown discoloration of flag leaf sheath, which may have pink to orange spore masses. Panicles emerge with difficulty, are partially exserted, may be discolored or rotted. Grains may be empty, discolored, or show poor filling. Disease is favored by high humidity, injuries
|
| 173 |
'category': 'Fungal',
|
| 174 |
'severity': 'Medium to High'
|
| 175 |
},
|
| 176 |
|
| 177 |
'stem_rot': {
|
| 178 |
'recommendation': 'Use resistant varieties and disease-free seeds. Maintain proper water management (avoid prolonged flooding). Apply balanced fertilization. Practice good field sanitation (remove stubbles, infected debris). Avoid mechanical injuries to stems. Ensure adequate drainage. Apply silicon fertilizers. Rotate with non-host crops. Remove and destroy infected plants. Consult DA for variety recommendations.',
|
| 179 |
-
'details': 'Stem Rot is caused by several fungi including
|
| 180 |
'category': 'Fungal',
|
| 181 |
'severity': 'High to Very High'
|
| 182 |
},
|
|
@@ -185,22 +185,22 @@ RECOMMENDATIONS = {
|
|
| 185 |
# VIRAL DISEASES (3)
|
| 186 |
# =========================================================================
|
| 187 |
'grassy_stunt_virus': {
|
| 188 |
-
'recommendation': 'Use resistant varieties if available. Control brown planthopper (vector) through integrated pest management: encourage natural enemies, avoid excessive nitrogen, maintain proper water depth. Practice
|
| 189 |
-
'details': 'Grassy Stunt Virus is transmitted by brown planthopper (Nilaparvata lugens). Symptoms include severe stunting, excessive tillering with thin tillers, narrow and short yellowish leaves, and no panicle formation. Infected plants resemble grass. Disease is most damaging when infection occurs at early growth stages. Can cause 100% yield loss if infected early. Virus cannot be cured once plant is infected. Common in tropical Asia.',
|
| 190 |
'category': 'Viral',
|
| 191 |
'severity': 'Very High'
|
| 192 |
},
|
| 193 |
|
| 194 |
'ragged_stunt_virus': {
|
| 195 |
-
'recommendation': 'Use resistant or tolerant varieties. Control brown planthopper (vector) populations through IPM: biological control, proper water management, balanced fertilization (avoid excess nitrogen). Practice synchronous planting and maintain fallow periods between crops. Remove and destroy infected plants. Monitor planthopper populations regularly. Use light traps for monitoring. No chemical cure for virus. Consult DA for variety recommendations.',
|
| 196 |
-
'details': 'Ragged Stunt Virus is transmitted by brown planthopper (Nilaparvata lugens). Symptoms include stunted growth, twisted and ragged leaves with irregular margins, short and twisted panicles, dark green leaves with yellow or orange discoloration, and reduced grain filling. Infected plants produce small, distorted panicles with high sterility. Can cause 20-100% yield loss depending on infection stage. Most damaging when infection occurs before maximum tillering.',
|
| 197 |
'category': 'Viral',
|
| 198 |
'severity': 'Very High'
|
| 199 |
},
|
| 200 |
|
| 201 |
'tungro_virus': {
|
| 202 |
-
'recommendation': '
|
| 203 |
-
'details': 'Rice Tungro Disease is caused by a combination of two viruses
|
| 204 |
'category': 'Viral',
|
| 205 |
'severity': 'Very High'
|
| 206 |
},
|
|
@@ -419,3 +419,424 @@ if __name__ == "__main__":
|
|
| 419 |
import uvicorn
|
| 420 |
# Production settings: no hot reload, proper host binding
|
| 421 |
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
# BACTERIAL DISEASES (2)
|
| 110 |
# =========================================================================
|
| 111 |
'bacterial_leaf_blight': {
|
| 112 |
+
'recommendation': 'Use resistant varieties like PSB Rc18 (ALA), NSIC Rc354, or NSIC Rc302. Apply balanced nutrients, especially nitrogen (avoid excess). Maintain good drainage and field sanitation: weed removal, plow under stubbles and straw. Destroy ratoons and volunteer seedlings. Allow fallow fields to dry to suppress pathogens. Use clean fields, moderate nitrogen use, proper drainage, and destruction of infected plant debris. Consult your local DA technician for specific advice.',
|
| 113 |
+
'details': 'Bacterial Leaf Blight (BLB) is one of the most serious bacterial diseases of rice caused by Xanthomonas oryzae pv. oryzae. Early symptoms start as tiny water-soaked spots that spread into large grayish-white lesions with wavy light brown margins, causing leaves to wilt and die (known as "Kresek" symptom). In susceptible varieties, yield loss can reach 70%. At booting stage, causes poor quality grains and high broken grain percentage. The disease spreads through rain, wind, contaminated water, tools, ooze droplets, strong winds, heavy rains, contaminated stubbles, and infected weeds. It thrives in high humidity and warm temperatures (25-34°C, >70% relative humidity) in tropical and temperate lowlands.',
|
| 114 |
'category': 'Bacterial',
|
| 115 |
'severity': 'High'
|
| 116 |
},
|
| 117 |
|
| 118 |
'bacterial_leaf_streak': {
|
| 119 |
+
'recommendation': 'Use resistant rice varieties. Apply balanced fertilization and avoid excessive nitrogen. Maintain proper field drainage and sanitation. Remove and destroy infected plant debris. Practice crop rotation where possible. Use clean planting materials and balanced fertilization. Use copper-based bactericides only if infection is severe, following BPI guidelines. Consult local DA for variety recommendations.',
|
| 120 |
+
'details': 'Bacterial Leaf Streak (BLS) is caused by Xanthomonas oryzae pv. oryzicola. Symptoms appear as small water-soaked streaks between leaf veins that turn narrow, dark brown to yellow-orange. In severe cases, leaves become yellow, dry up, and reduce grain weight. Disease is favored by high humidity, warm temperatures (25-34°C), and heavy rainfall. Can cause 10-30% yield loss in susceptible varieties. The disease spreads through infected seeds, stubbles, rain splash, wind-driven rain, and contaminated tools.',
|
| 121 |
'category': 'Bacterial',
|
| 122 |
'severity': 'Medium'
|
| 123 |
},
|
|
|
|
| 134 |
|
| 135 |
'brown_spot': {
|
| 136 |
'recommendation': 'Plant resistant varieties and ensure balanced fertilization, especially sufficient potassium (use complete or potash fertilizers). Conduct soil test and correct deficiencies. Improve soil health and maintain proper field drainage. Use clean, healthy seeds and practice field sanitation (remove stubbles, weeds). Split nitrogen fertilizer application. Apply calcium silicate & potassium fertilizers. If severe, apply fungicides (triazoles, strobilurins) following BPI registration and safety rules. Consult local DA.',
|
| 137 |
+
'details': 'Brown Spot is caused by Cochliobolus miyabeanus fungus. Historically responsible for the Great Bengal Famine in 1943 due to massive crop loss. It affects leaves, coleoptiles, roots, and grains, forming brown circular to oval spots with gray centers that can merge and wither the leaf. Symptoms also include black spots on glumes with dark brown velvety fungal spores and discolored, shriveled grains. The fungus can survive in infected seeds, stubbles, and soil for 2-4 years. It thrives in high humidity (86-100%), temperatures of 16-36°C, and particularly in nutrient-deficient or toxic soils. Yield loss ranges 5-45% and causes seedling blight mortality of 10-58%.',
|
| 138 |
'category': 'Fungal',
|
| 139 |
'severity': 'Medium to High'
|
| 140 |
},
|
|
|
|
| 148 |
|
| 149 |
'rice_blast': {
|
| 150 |
'recommendation': 'Use resistant varieties such as PSB Rc18 or IRRI-derived lines. Avoid high nitrogen application and split nitrogen fertilizer application. Maintain proper irrigation (avoid water stress) and field sanitation (remove stubbles, debris). Adjust planting calendar to avoid peak infection period. Apply calcium silicate to strengthen cell walls. Apply fungicides: triazoles and strobilurins at first signs, especially during tillering/booting. Burn or plow under infected straw. Consult local DA.',
|
| 151 |
+
'details': 'Rice Blast is one of the most destructive fungal diseases caused by Magnaporthe oryzae. It can infect the plant at almost any stage from seedling to maturity. Symptoms include grayish spindle-shaped spots on leaves with brown borders and gray centers, blackened nodes that break easily, and unfilled panicles with blackened bases. The disease develops under cool and humid conditions with frequent rain or dew, particularly when there are large day-night temperature differences. Can reduce yield significantly by reducing leaf area for grain filling and causing panicle sterility.',
|
| 152 |
'category': 'Fungal',
|
| 153 |
'severity': 'Very High'
|
| 154 |
},
|
| 155 |
|
| 156 |
'rice_false_smut': {
|
| 157 |
'recommendation': 'Use disease-free seeds and resistant varieties. Apply balanced fertilization, avoid excessive nitrogen at heading stage. Ensure proper field drainage and spacing for air circulation. Apply preventive fungicides (triazoles, strobilurins) at booting to early heading stage. Remove and destroy infected panicles (burn, do not compost). Adjust planting date to avoid high humidity during flowering. Consult DA for timing and fungicide recommendations.',
|
| 158 |
+
'details': 'Rice False Smut is caused by Ustilaginoidea virens fungus. This disease appears during the flowering to milking stage. Individual grains are transformed into large (1-2 cm), velvety, yellow-green to dark green balls of fungal spores, causing chalky and lighter grains. Infected grains are completely replaced by smut balls that reduce yield and grain quality. The fungus favors low temperatures (around 20°C), high humidity (>90%), and high nitrogen levels during flowering. Can produce mycotoxins harmful to humans and animals. Yield loss typically 5-10% but quality loss is significant.',
|
| 159 |
'category': 'Fungal',
|
| 160 |
'severity': 'Medium'
|
| 161 |
},
|
| 162 |
|
| 163 |
'sheath_blight': {
|
| 164 |
'recommendation': 'Use moderately resistant varieties. Apply balanced fertilization, avoid excessive nitrogen. Maintain proper plant spacing for air circulation. Ensure good water management and drainage. Remove lower infected leaves when feasible. Apply fungicides (validamycin, azoxystrobin) at early infection stages. Use silicon fertilizers to strengthen plant tissue. Practice crop rotation with non-host crops. Consult local DA for fungicide timing.',
|
| 165 |
+
'details': 'Sheath Blight is caused by Rhizoctonia solani fungus and is second only to rice blast in importance. It infects the leaf sheath and lower leaves, producing oval to irregular greenish-gray lesions near the water line that later become white to gray with brown borders. Lesions spread quickly upward to leaves and panicles. The disease develops in warm (28-32°C), humid conditions, especially in fields with dense planting and excessive nitrogen use. It spreads through sclerotia and mycelium floating on water. Can cause lodging and reduced grain filling. Yield loss can reach 25-50% in susceptible varieties under favorable conditions.',
|
| 166 |
'category': 'Fungal',
|
| 167 |
'severity': 'High'
|
| 168 |
},
|
| 169 |
|
| 170 |
'sheath_rot': {
|
| 171 |
'recommendation': 'Use resistant or tolerant varieties. Apply balanced fertilization (avoid excess nitrogen at late growth stages). Maintain proper water management, especially during heading. Ensure adequate spacing for air circulation. Remove and destroy infected panicles. Apply fungicides at boot leaf stage if disease history exists. Practice field sanitation. Consult DA for variety and fungicide recommendations.',
|
| 172 |
+
'details': 'Sheath Rot is caused primarily by Sarocladium oryzae (formerly Acrocylindrium oryzae). This disease affects the uppermost leaf sheath enclosing young panicles, leading to rotting and poor panicle emergence. Symptoms include grayish-brown discoloration of flag leaf sheath, which may have pink to orange spore masses. Panicles emerge with difficulty, are partially exserted, may be discolored or rotted. Grains may be empty, discolored, or show poor filling. The disease is common during the wet season with high nitrogen and humidity. Disease is favored by high humidity, injuries from insects or mechanical damage, and imbalanced nutrition. Yield loss ranges 20-85% in severe cases.',
|
| 173 |
'category': 'Fungal',
|
| 174 |
'severity': 'Medium to High'
|
| 175 |
},
|
| 176 |
|
| 177 |
'stem_rot': {
|
| 178 |
'recommendation': 'Use resistant varieties and disease-free seeds. Maintain proper water management (avoid prolonged flooding). Apply balanced fertilization. Practice good field sanitation (remove stubbles, infected debris). Avoid mechanical injuries to stems. Ensure adequate drainage. Apply silicon fertilizers. Rotate with non-host crops. Remove and destroy infected plants. Consult DA for variety recommendations.',
|
| 179 |
+
'details': 'Stem Rot is caused by several fungi including Sclerotium oryzae (Magnaporthe salvinii). It infects the stem base near the waterline, forming small black lesions on outer leaf sheaths that expand into irregular black patches. Stems become hollow, weak, and lodge easily. Interior of stems shows black or white sclerotia and fungal growth. The disease is common in irrigated lowlands and spreads through floating sclerotia in water. Disease is most severe in deep-water and flood-prone areas. Can cause complete lodging and severe yield loss (up to 100% in heavily infected fields). Favored by deep water, high temperatures, and prolonged flooding.',
|
| 180 |
'category': 'Fungal',
|
| 181 |
'severity': 'High to Very High'
|
| 182 |
},
|
|
|
|
| 185 |
# VIRAL DISEASES (3)
|
| 186 |
# =========================================================================
|
| 187 |
'grassy_stunt_virus': {
|
| 188 |
+
'recommendation': 'Use BPH-resistant varieties if available. Control brown planthopper (BPH - the vector) through integrated pest management: encourage natural enemies, avoid excessive nitrogen, maintain proper water depth. Practice synchronized planting with neighbors to break pest cycle and maintain fallow periods. Remove and destroy infected plants immediately. Plow infected stubbles. Avoid continuous rice cropping (maintain fallow period). Monitor for planthopper populations regularly. Note: No chemical cure for virus once infected. Consult DA for resistant varieties.',
|
| 189 |
+
'details': 'Rice Grassy Stunt Virus (RGSV) is transmitted by the brown planthopper (BPH - Nilaparvata lugens). Symptoms include severe stunting, excessive tillering with thin tillers resembling grass (grassy and rosette-like plants), narrow and short yellowish leaves, and failure to produce panicles or no panicle formation. Infected plants resemble grass. The disease is favored by continuous rice planting and high humidity. Disease is most damaging when infection occurs at early growth stages. Can cause 100% yield loss if infected early. Virus cannot be cured once plant is infected. Common in tropical Asia.',
|
| 190 |
'category': 'Viral',
|
| 191 |
'severity': 'Very High'
|
| 192 |
},
|
| 193 |
|
| 194 |
'ragged_stunt_virus': {
|
| 195 |
+
'recommendation': 'Use resistant or tolerant varieties. Control brown planthopper (BPH - vector) populations through IPM: biological control, proper water management, balanced fertilization (avoid excess nitrogen). Practice synchronous planting and maintain fallow periods between crops. Remove and destroy infected plants. Monitor planthopper populations regularly. Use light traps for monitoring. Ensure proper crop timing and field sanitation. No chemical cure for virus once infected. Consult DA for variety recommendations.',
|
| 196 |
+
'details': 'Rice Ragged Stunt Virus (RRSV) is also transmitted by brown planthopper (BPH - Nilaparvata lugens). Symptoms include stunted growth, twisted and ragged leaves with irregular margins, short and twisted panicles, spiral twisted leaves, dark green leaves with yellow or orange discoloration, delayed flowering, unfilled grains, and reduced grain filling. Infected plants produce small, distorted panicles with high sterility. Can cause 20-100% (up to 80%) yield loss depending on infection stage in tropical areas. Most damaging when infection occurs before maximum tillering.',
|
| 197 |
'category': 'Viral',
|
| 198 |
'severity': 'Very High'
|
| 199 |
},
|
| 200 |
|
| 201 |
'tungro_virus': {
|
| 202 |
+
'recommendation': 'Grow tungro-resistant or GLH-resistant varieties like IR64 if available. Practice synchronous planting (sabay-sabay) with neighbors and maintain a fallow period (at least 1 month) between crops to break vector cycles. Remove (rogue) and destroy infected plants and stubbles immediately. Plow infected stubbles after harvest to destroy inoculum and GLH breeding sites. Maintain balanced nutrient management. Note: Chemical control of GLH is not effective as they move quickly and spread tungro even with short feeding. Consult local DA.',
|
| 203 |
+
'details': 'Rice Tungro Disease is caused by a combination of two viruses: Rice Tungro Bacilliform Virus (RTBV) and Rice Tungro Spherical Virus (RTSV), transmitted by the green leafhopper (GLH). Infected plants show symptoms including yellow-orange leaves, young leaves becoming mottled, older leaves turning yellow to orange, stunted growth, fewer tillers, reduced tillers, delayed flowering, small panicles, sterile panicles, and high sterility. Yield loss can reach up to 100% if infection occurs early in the growth stage. Highly destructive in South & Southeast Asia. Most damaging during vegetative and tillering stage.',
|
| 204 |
'category': 'Viral',
|
| 205 |
'severity': 'Very High'
|
| 206 |
},
|
|
|
|
| 419 |
import uvicorn
|
| 420 |
# Production settings: no hot reload, proper host binding
|
| 421 |
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=False)
|
| 422 |
+
|
| 423 |
+
# import io
|
| 424 |
+
# import sys
|
| 425 |
+
# import time
|
| 426 |
+
# import logging
|
| 427 |
+
# import tempfile
|
| 428 |
+
# import torch
|
| 429 |
+
# import torch.nn.functional as F
|
| 430 |
+
# from pydantic import BaseModel
|
| 431 |
+
# from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 432 |
+
# from fastapi.middleware.cors import CORSMiddleware
|
| 433 |
+
# from contextlib import asynccontextmanager # Add this import
|
| 434 |
+
# from models.rice_model import RiceDiseaseCNN # Legacy 4-class model
|
| 435 |
+
# from models.resnet_rice_model import create_model # New 14-class ResNet18 model
|
| 436 |
+
# from rice_leaf_validator import RiceLeafValidator # New ResNet18 validator (99.84% accuracy)
|
| 437 |
+
# from utils.image_processing import process_image
|
| 438 |
+
# import requests
|
| 439 |
+
# import json
|
| 440 |
+
# import os
|
| 441 |
+
# from typing import Dict, Any
|
| 442 |
+
|
| 443 |
+
# # Configure logging
|
| 444 |
+
# logging.basicConfig(
|
| 445 |
+
# level=logging.INFO,
|
| 446 |
+
# format="%(asctime)s [%(levelname)s] %(message)s",
|
| 447 |
+
# handlers=[
|
| 448 |
+
# logging.StreamHandler(sys.stdout)
|
| 449 |
+
# ]
|
| 450 |
+
# )
|
| 451 |
+
|
| 452 |
+
# # Initialize model variables
|
| 453 |
+
# model = None
|
| 454 |
+
# rice_validator = None # New ResNet18 validator instance
|
| 455 |
+
# model_path = "rice_disease_model_final.pth" # 14-class disease detection model
|
| 456 |
+
# rice_validator_model_path = "rice_leaf_validator_resnet18.pth" # New ResNet18 validator (99.84% accuracy)
|
| 457 |
+
# model_loaded = False
|
| 458 |
+
# validator_loaded = False
|
| 459 |
+
# model_loading = False
|
| 460 |
+
# last_error = None
|
| 461 |
+
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 462 |
+
|
| 463 |
+
# # Define lifespan context manager for model loading
|
| 464 |
+
# @asynccontextmanager
|
| 465 |
+
# async def lifespan(app):
|
| 466 |
+
# # Load models on startup
|
| 467 |
+
# load_model()
|
| 468 |
+
# yield
|
| 469 |
+
# # Cleanup operations can be added here for shutdown
|
| 470 |
+
|
| 471 |
+
# # Create FastAPI app with lifespan
|
| 472 |
+
# app = FastAPI(lifespan=lifespan)
|
| 473 |
+
|
| 474 |
+
# # Add CORS middleware
|
| 475 |
+
# app.add_middleware(
|
| 476 |
+
# CORSMiddleware,
|
| 477 |
+
# allow_origins=["*"], # Allows all origins
|
| 478 |
+
# allow_credentials=True,
|
| 479 |
+
# allow_methods=["*"], # Allows all methods
|
| 480 |
+
# allow_headers=["*"], # Allows all headers
|
| 481 |
+
# )
|
| 482 |
+
|
| 483 |
+
# # Class names matching your training data (14 classes)
|
| 484 |
+
# # Order MUST match the training script's class order
|
| 485 |
+
# CLASS_NAMES = [
|
| 486 |
+
# 'bacterial_leaf_blight',
|
| 487 |
+
# 'bacterial_leaf_streak',
|
| 488 |
+
# 'bakanae',
|
| 489 |
+
# 'brown_spot',
|
| 490 |
+
# 'grassy_stunt_virus',
|
| 491 |
+
# 'healthy_rice_plant',
|
| 492 |
+
# 'narrow_brown_spot',
|
| 493 |
+
# 'ragged_stunt_virus',
|
| 494 |
+
# 'rice_blast',
|
| 495 |
+
# 'rice_false_smut',
|
| 496 |
+
# 'sheath_blight',
|
| 497 |
+
# 'sheath_rot',
|
| 498 |
+
# 'stem_rot',
|
| 499 |
+
# 'tungro_virus'
|
| 500 |
+
# ]
|
| 501 |
+
|
| 502 |
+
# # Disease display names for more specific prompts
|
| 503 |
+
# disease_display_names = {
|
| 504 |
+
# # Bacterial Diseases
|
| 505 |
+
# 'bacterial_leaf_blight': 'Bacterial Leaf Blight (BLB)',
|
| 506 |
+
# 'bacterial_leaf_streak': 'Bacterial Leaf Streak (BLS)',
|
| 507 |
+
|
| 508 |
+
# # Fungal Diseases
|
| 509 |
+
# 'bakanae': 'Bakanae (Foolish Seedling Disease)',
|
| 510 |
+
# 'brown_spot': 'Brown Spot Disease',
|
| 511 |
+
# 'narrow_brown_spot': 'Narrow Brown Spot',
|
| 512 |
+
# 'rice_blast': 'Rice Blast Disease',
|
| 513 |
+
# 'rice_false_smut': 'Rice False Smut',
|
| 514 |
+
# 'sheath_blight': 'Sheath Blight',
|
| 515 |
+
# 'sheath_rot': 'Sheath Rot',
|
| 516 |
+
# 'stem_rot': 'Stem Rot',
|
| 517 |
+
|
| 518 |
+
# # Viral Diseases
|
| 519 |
+
# 'grassy_stunt_virus': 'Grassy Stunt Virus',
|
| 520 |
+
# 'ragged_stunt_virus': 'Ragged Stunt Virus',
|
| 521 |
+
# 'tungro_virus': 'Rice Tungro Virus',
|
| 522 |
+
|
| 523 |
+
# # Healthy
|
| 524 |
+
# 'healthy_rice_plant': 'Healthy Rice Plant'
|
| 525 |
+
# }
|
| 526 |
+
|
| 527 |
+
# # Disease recommendations for all 14 classes
|
| 528 |
+
# RECOMMENDATIONS = {
|
| 529 |
+
# # =========================================================================
|
| 530 |
+
# # BACTERIAL DISEASES (2)
|
| 531 |
+
# # =========================================================================
|
| 532 |
+
# 'bacterial_leaf_blight': {
|
| 533 |
+
# 'recommendation': 'Use resistant varieties like PSB Rc18 (ALA), NSIC Rc354, or NSIC Rc302. Apply balanced nutrients, especially nitrogen (avoid excess). Maintain good drainage and field sanitation: weed removal, plow under stubbles and straw. Destroy ratoons and volunteer seedlings. Allow fallow fields to dry to suppress pathogens. Consult your local DA technician for specific advice.',
|
| 534 |
+
# 'details': 'Bacterial Leaf Blight (BLB) is caused by Xanthomonas oryzae pv. oryzae. Symptoms include water-soaked stripes that expand to large grayish-white lesions with wavy light brown margins. In susceptible varieties, yield loss can reach 70%. At booting stage, causes poor quality grains and high broken grain percentage. Spread by ooze droplets, strong winds, heavy rains, contaminated stubbles, and infected weeds in tropical and temperate lowlands (25-34°C, >70% relative humidity).',
|
| 535 |
+
# 'category': 'Bacterial',
|
| 536 |
+
# 'severity': 'High'
|
| 537 |
+
# },
|
| 538 |
+
|
| 539 |
+
# 'bacterial_leaf_streak': {
|
| 540 |
+
# 'recommendation': 'Use resistant rice varieties. Apply balanced fertilization and avoid excessive nitrogen. Maintain proper field drainage and sanitation. Remove and destroy infected plant debris. Practice crop rotation where possible. Use copper-based bactericides only if infection is severe, following BPI guidelines. Consult local DA for variety recommendations.',
|
| 541 |
+
# 'details': 'Bacterial Leaf Streak (BLS) is caused by Xanthomonas oryzae pv. oryzicola. Symptoms include narrow, dark brown to yellow-orange streaks between leaf veins. Leaves may become yellow and dry. Disease is favored by high humidity, warm temperatures (25-34°C), and heavy rainfall. Can cause 10-30% yield loss in susceptible varieties. Spread through wind-driven rain, contaminated tools, and infected seeds.',
|
| 542 |
+
# 'category': 'Bacterial',
|
| 543 |
+
# 'severity': 'Medium'
|
| 544 |
+
# },
|
| 545 |
+
|
| 546 |
+
# # =========================================================================
|
| 547 |
+
# # FUNGAL DISEASES (8)
|
| 548 |
+
# # =========================================================================
|
| 549 |
+
# 'bakanae': {
|
| 550 |
+
# 'recommendation': 'Use certified disease-free seeds. Treat seeds with fungicides (e.g., prochloraz, tricyclazole) before planting. Remove and destroy infected seedlings immediately. Avoid deep sowing and excessive nitrogen fertilization. Maintain proper water management. Practice crop rotation. Do not use infected plants as seedbed. Consult DA for registered fungicides.',
|
| 551 |
+
# 'details': 'Bakanae (Foolish Seedling Disease) is caused by Fusarium fujikuroi fungus. Infected seedlings grow abnormally tall, pale yellow-green, with thin stems and few tillers. Some seedlings may die, others produce empty or partially filled grains. Fungus produces gibberellin (growth hormone) causing abnormal elongation. Seedborne disease that can cause 10-50% stand loss. Favored by contaminated seeds and infected soil.',
|
| 552 |
+
# 'category': 'Fungal',
|
| 553 |
+
# 'severity': 'Medium'
|
| 554 |
+
# },
|
| 555 |
+
|
| 556 |
+
# 'brown_spot': {
|
| 557 |
+
# 'recommendation': 'Plant resistant varieties and ensure balanced fertilization, especially sufficient potassium (use complete or potash fertilizers). Conduct soil test and correct deficiencies. Improve soil health and maintain proper field drainage. Use clean, healthy seeds and practice field sanitation (remove stubbles, weeds). Split nitrogen fertilizer application. Apply calcium silicate & potassium fertilizers. If severe, apply fungicides (triazoles, strobilurins) following BPI registration and safety rules. Consult local DA.',
|
| 558 |
+
# 'details': 'Brown Spot is caused by Cochliobolus miyabeanus. Symptoms include small, circular to oval spots with gray centers on leaves, black spots on glumes with dark brown velvety fungal spores, and discolored, shriveled grains. Historically caused the 1943 Great Bengal Famine. Yield loss ranges 5-45% and causes seedling blight mortality of 10-58%. Fungus survives 2-4 years in infected tissues under high humidity (86-100%), 16-36°C, in nutrient-deficient or toxic soils.',
|
| 559 |
+
# 'category': 'Fungal',
|
| 560 |
+
# 'severity': 'Medium to High'
|
| 561 |
+
# },
|
| 562 |
+
|
| 563 |
+
# 'narrow_brown_spot': {
|
| 564 |
+
# 'recommendation': 'Use resistant or tolerant varieties. Apply balanced fertilization with adequate potassium and micronutrients. Maintain proper water management and field sanitation. Remove infected plant debris after harvest. Use clean, certified seeds. Apply foliar fungicides if infection is severe. Practice proper crop rotation. Consult DA for variety selection.',
|
| 565 |
+
# 'details': 'Narrow Brown Spot is caused by Cercospora janseana (Sphaerulina oryzina). Symptoms include narrow, elongated brown lesions on leaves, typically 1-5 mm long, running parallel to leaf veins. Lesions may have light centers with dark borders. Disease is favored by nutrient deficiency, especially potassium, and high humidity. Can reduce photosynthetic area and grain filling. Common in nutrient-poor soils.',
|
| 566 |
+
# 'category': 'Fungal',
|
| 567 |
+
# 'severity': 'Low to Medium'
|
| 568 |
+
# },
|
| 569 |
+
|
| 570 |
+
# 'rice_blast': {
|
| 571 |
+
# 'recommendation': 'Use resistant varieties such as PSB Rc18 or IRRI-derived lines. Avoid high nitrogen application and split nitrogen fertilizer application. Maintain proper irrigation (avoid water stress) and field sanitation (remove stubbles, debris). Adjust planting calendar to avoid peak infection period. Apply calcium silicate to strengthen cell walls. Apply fungicides: triazoles and strobilurins at first signs, especially during tillering/booting. Burn or plow under infected straw. Consult local DA.',
|
| 572 |
+
# 'details': 'Rice Blast is caused by Magnaporthe oryzae fungus. Symptoms include leaf blast (small, spindle-shaped spots with brown border and gray center), node blast (nodes become black and break easily), and panicle blast (base becomes black, grains remain unfilled). Occurs from seedling to reproductive stage under cool temperature, high relative humidity, continuous rain, and large day-night temperature differences. Can reduce yield significantly by reducing leaf area for grain filling.',
|
| 573 |
+
# 'category': 'Fungal',
|
| 574 |
+
# 'severity': 'Very High'
|
| 575 |
+
# },
|
| 576 |
+
|
| 577 |
+
# 'rice_false_smut': {
|
| 578 |
+
# 'recommendation': 'Use disease-free seeds and resistant varieties. Apply balanced fertilization, avoid excessive nitrogen at heading stage. Ensure proper field drainage and spacing for air circulation. Apply preventive fungicides (triazoles, strobilurins) at booting to early heading stage. Remove and destroy infected panicles (burn, do not compost). Adjust planting date to avoid high humidity during flowering. Consult DA for timing and fungicide recommendations.',
|
| 579 |
+
# 'details': 'Rice False Smut is caused by Ustilaginoidea virens fungus. Individual grains are transformed into large (1-2 cm), velvety, yellow-green to dark green balls of fungal spores. Infected grains are replaced by smut balls that reduce yield and grain quality. Disease is favored by high nitrogen, high humidity (>90%), and temperatures of 25-30°C during flowering. Can produce mycotoxins harmful to humans and animals. Yield loss typically 5-10% but quality loss is significant.',
|
| 580 |
+
# 'category': 'Fungal',
|
| 581 |
+
# 'severity': 'Medium'
|
| 582 |
+
# },
|
| 583 |
+
|
| 584 |
+
# 'sheath_blight': {
|
| 585 |
+
# 'recommendation': 'Use moderately resistant varieties. Apply balanced fertilization, avoid excessive nitrogen. Maintain proper plant spacing for air circulation. Ensure good water management and drainage. Remove lower infected leaves when feasible. Apply fungicides (validamycin, azoxystrobin) at early infection stages. Use silicon fertilizers to strengthen plant tissue. Practice crop rotation with non-host crops. Consult local DA for fungicide timing.',
|
| 586 |
+
# 'details': 'Sheath Blight is caused by Rhizoctonia solani fungus. Symptoms include oval to irregular greenish-gray lesions on leaf sheaths near water line, later becoming white to gray with brown borders. Lesions expand upward to leaves and panicles. Can cause lodging and reduced grain filling. Disease is favored by high humidity, dense planting, high nitrogen, and warm temperatures (28-32°C). Yield loss can reach 25-50% in susceptible varieties under favorable conditions.',
|
| 587 |
+
# 'category': 'Fungal',
|
| 588 |
+
# 'severity': 'High'
|
| 589 |
+
# },
|
| 590 |
+
|
| 591 |
+
# 'sheath_rot': {
|
| 592 |
+
# 'recommendation': 'Use resistant or tolerant varieties. Apply balanced fertilization (avoid excess nitrogen at late growth stages). Maintain proper water management, especially during heading. Ensure adequate spacing for air circulation. Remove and destroy infected panicles. Apply fungicides at boot leaf stage if disease history exists. Practice field sanitation. Consult DA for variety and fungicide recommendations.',
|
| 593 |
+
# 'details': 'Sheath Rot is caused primarily by Sarocladium oryzae (formerly Acrocylindrium oryzae). Symptoms include grayish-brown discoloration of flag leaf sheath, which may have pink to orange spore masses. Panicles emerge with difficulty, are partially exserted, may be discolored or rotted. Grains may be empty, discolored, or show poor filling. Disease is favored by high humidity, injuries (insect or mechanical), and imbalanced nutrition. Yield loss ranges 20-85% in severe cases.',
|
| 594 |
+
# 'category': 'Fungal',
|
| 595 |
+
# 'severity': 'Medium to High'
|
| 596 |
+
# },
|
| 597 |
+
|
| 598 |
+
# 'stem_rot': {
|
| 599 |
+
# 'recommendation': 'Use resistant varieties and disease-free seeds. Maintain proper water management (avoid prolonged flooding). Apply balanced fertilization. Practice good field sanitation (remove stubbles, infected debris). Avoid mechanical injuries to stems. Ensure adequate drainage. Apply silicon fertilizers. Rotate with non-host crops. Remove and destroy infected plants. Consult DA for variety recommendations.',
|
| 600 |
+
# 'details': 'Stem Rot is caused by several fungi including Magnaporthe salvinii (formerly Sclerotium oryzae). Small black lesions appear on outer leaf sheaths near water line, expanding to form irregular black patches. Stems become hollow, weak, and lodge easily. Interior of stems shows black fungal growth. Disease is most severe in deep-water and flood-prone areas. Can cause complete lodging and severe yield loss (up to 100% in heavily infected fields). Favored by deep water, high temperatures, and prolonged flooding.',
|
| 601 |
+
# 'category': 'Fungal',
|
| 602 |
+
# 'severity': 'High to Very High'
|
| 603 |
+
# },
|
| 604 |
+
|
| 605 |
+
# # =========================================================================
|
| 606 |
+
# # VIRAL DISEASES (3)
|
| 607 |
+
# # =========================================================================
|
| 608 |
+
# 'grassy_stunt_virus': {
|
| 609 |
+
# 'recommendation': 'Use resistant varieties if available. Control brown planthopper (vector) through integrated pest management: encourage natural enemies, avoid excessive nitrogen, maintain proper water depth. Practice synchronous planting with neighbors to break pest cycle. Remove and destroy infected plants immediately. Avoid continuous rice cropping (maintain fallow period). Monitor for planthopper populations. Note: No chemical cure for virus. Consult DA for resistant varieties.',
|
| 610 |
+
# 'details': 'Grassy Stunt Virus is transmitted by brown planthopper (Nilaparvata lugens). Symptoms include severe stunting, excessive tillering with thin tillers, narrow and short yellowish leaves, and no panicle formation. Infected plants resemble grass. Disease is most damaging when infection occurs at early growth stages. Can cause 100% yield loss if infected early. Virus cannot be cured once plant is infected. Common in tropical Asia.',
|
| 611 |
+
# 'category': 'Viral',
|
| 612 |
+
# 'severity': 'Very High'
|
| 613 |
+
# },
|
| 614 |
+
|
| 615 |
+
# 'ragged_stunt_virus': {
|
| 616 |
+
# 'recommendation': 'Use resistant or tolerant varieties. Control brown planthopper (vector) populations through IPM: biological control, proper water management, balanced fertilization (avoid excess nitrogen). Practice synchronous planting and maintain fallow periods between crops. Remove and destroy infected plants. Monitor planthopper populations regularly. Use light traps for monitoring. No chemical cure for virus. Consult DA for variety recommendations.',
|
| 617 |
+
# 'details': 'Ragged Stunt Virus is transmitted by brown planthopper (Nilaparvata lugens). Symptoms include stunted growth, twisted and ragged leaves with irregular margins, short and twisted panicles, dark green leaves with yellow or orange discoloration, and reduced grain filling. Infected plants produce small, distorted panicles with high sterility. Can cause 20-100% yield loss depending on infection stage. Most damaging when infection occurs before maximum tillering.',
|
| 618 |
+
# 'category': 'Viral',
|
| 619 |
+
# 'severity': 'Very High'
|
| 620 |
+
# },
|
| 621 |
+
|
| 622 |
+
# 'tungro_virus': {
|
| 623 |
+
# 'recommendation': 'Plant tungro- or GLH-resistant varieties like IR64 if available. Practice synchronous planting (sabay-sabay) with neighbors and maintain a fallow period (at least 1 month) between crops to break vector cycles. Remove (rogue) and destroy infected plants immediately. Plow infected stubbles after harvest to destroy inoculum and GLH breeding sites. Maintain balanced nutrient management. Note: Chemical control of GLH is not effective as they move quickly and spread tungro even with short feeding. Consult local DA.',
|
| 624 |
+
# 'details': 'Rice Tungro Disease is caused by a combination of two viruses (Rice Tungro Bacilliform Virus + Rice Tungro Spherical Virus) transmitted by green leafhoppers (GLH). Symptoms include young leaves becoming mottled, older leaves turning yellow to orange, stunted growth, reduced tillers, delayed flowering, small panicles, and high sterility. Highly destructive in South & Southeast Asia with yield loss up to 100% in susceptible varieties infected early. Most damaging during vegetative/tillering stage.',
|
| 625 |
+
# 'category': 'Viral',
|
| 626 |
+
# 'severity': 'Very High'
|
| 627 |
+
# },
|
| 628 |
+
|
| 629 |
+
# # =========================================================================
|
| 630 |
+
# # HEALTHY
|
| 631 |
+
# # =========================================================================
|
| 632 |
+
# 'healthy_rice_plant': {
|
| 633 |
+
# 'recommendation': 'Your rice plant appears healthy! Continue with good agricultural practices: maintain balanced fertilization, proper irrigation and drainage, regular field monitoring, integrated pest management, and field sanitation. Keep monitoring for any early signs of diseases or pests. Follow recommended crop calendar and consult your local DA for best practices.',
|
| 634 |
+
# 'details': 'No disease detected. The plant shows normal healthy characteristics including uniform green color, normal growth, no lesions or discoloration, and no signs of stress or infection. Continue preventive measures and regular monitoring to maintain plant health.',
|
| 635 |
+
# 'category': 'Healthy',
|
| 636 |
+
# 'severity': 'None'
|
| 637 |
+
# }
|
| 638 |
+
# }
|
| 639 |
+
|
| 640 |
+
# def load_model():
|
| 641 |
+
# """Load the PyTorch models"""
|
| 642 |
+
# global model, rice_validator, model_loaded, validator_loaded, model_loading, last_error
|
| 643 |
+
# try:
|
| 644 |
+
# logging.info(f"Loading disease model from: {model_path}")
|
| 645 |
+
# model_loading = True
|
| 646 |
+
|
| 647 |
+
# # Initialize the ResNet18 disease model architecture for 14 classes
|
| 648 |
+
# model = create_model(num_classes=14).to(device)
|
| 649 |
+
|
| 650 |
+
# # Load the saved model weights
|
| 651 |
+
# model.load_state_dict(torch.load(model_path, map_location=device))
|
| 652 |
+
# model.eval() # Set to evaluation mode
|
| 653 |
+
# model_loaded = True
|
| 654 |
+
|
| 655 |
+
# # Load rice leaf validator model (new ResNet18 validator - 99.84% accuracy)
|
| 656 |
+
# logging.info(f"Loading ResNet18 rice leaf validator from: {rice_validator_model_path}")
|
| 657 |
+
# rice_validator = RiceLeafValidator(rice_validator_model_path, device)
|
| 658 |
+
# validator_loaded = True
|
| 659 |
+
|
| 660 |
+
# model_loading = False
|
| 661 |
+
# logging.info("Models loaded successfully!")
|
| 662 |
+
# logging.info(f"Disease model: ResNet18 with {len(CLASS_NAMES)} classes")
|
| 663 |
+
# logging.info(f"Rice validator: ResNet18 binary classifier (99.84% accuracy)")
|
| 664 |
+
# logging.info(f"Classes: {CLASS_NAMES}")
|
| 665 |
+
# return True
|
| 666 |
+
# except Exception as e:
|
| 667 |
+
# last_error = str(e)
|
| 668 |
+
# model_loading = False
|
| 669 |
+
# logging.error(f"Failed to load models: {e}")
|
| 670 |
+
# return False
|
| 671 |
+
|
| 672 |
+
# @app.get("/")
|
| 673 |
+
# async def root():
|
| 674 |
+
# """API root endpoint"""
|
| 675 |
+
# return {
|
| 676 |
+
# "message": "Rice Disease Detection API is running!",
|
| 677 |
+
# "model_loaded": model_loaded,
|
| 678 |
+
# "validator_loaded": validator_loaded,
|
| 679 |
+
# "model_loading": model_loading,
|
| 680 |
+
# "error": last_error
|
| 681 |
+
# }
|
| 682 |
+
|
| 683 |
+
# @app.get("/health")
|
| 684 |
+
# async def health():
|
| 685 |
+
# """Health check endpoint needed by PHP status checker"""
|
| 686 |
+
# return {
|
| 687 |
+
# "status": "running",
|
| 688 |
+
# "model_status": "loaded" if model_loaded else "loading" if model_loading else "not_loaded",
|
| 689 |
+
# "validator_status": "loaded" if validator_loaded else "not_loaded",
|
| 690 |
+
# "model_loaded": model_loaded,
|
| 691 |
+
# "model_loading": model_loading,
|
| 692 |
+
# "last_error": last_error,
|
| 693 |
+
# "device": str(device)
|
| 694 |
+
# }
|
| 695 |
+
|
| 696 |
+
# @app.get("/status")
|
| 697 |
+
# async def status():
|
| 698 |
+
# """Check model loading status"""
|
| 699 |
+
# return {
|
| 700 |
+
# "model_loaded": model_loaded,
|
| 701 |
+
# "validator_loaded": validator_loaded,
|
| 702 |
+
# "model_loading": model_loading,
|
| 703 |
+
# "error": last_error,
|
| 704 |
+
# "device": str(device)
|
| 705 |
+
# }
|
| 706 |
+
|
| 707 |
+
# @app.post("/validate-leaf/")
|
| 708 |
+
# async def validate_rice_leaf_image(file: UploadFile = File(...)):
|
| 709 |
+
# """Check if an image contains a rice leaf"""
|
| 710 |
+
# if not validator_loaded:
|
| 711 |
+
# if model_loading:
|
| 712 |
+
# raise HTTPException(status_code=503, detail="Models are still loading. Please try again later.")
|
| 713 |
+
# else:
|
| 714 |
+
# success = load_model()
|
| 715 |
+
# if not success:
|
| 716 |
+
# raise HTTPException(status_code=500, detail=f"Failed to load models: {last_error}")
|
| 717 |
+
|
| 718 |
+
# try:
|
| 719 |
+
# # Save uploaded file temporarily (cross-platform)
|
| 720 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as temp_file:
|
| 721 |
+
# temp_file_path = temp_file.name
|
| 722 |
+
# temp_file.write(await file.read())
|
| 723 |
+
|
| 724 |
+
# # Check if image contains rice leaf using ResNet18 validator
|
| 725 |
+
# result = rice_validator.validate_image(temp_file_path, threshold=0.5)
|
| 726 |
+
# is_rice = result['is_rice_leaf']
|
| 727 |
+
# confidence = result['confidence']
|
| 728 |
+
|
| 729 |
+
# # Remove temporary file
|
| 730 |
+
# os.remove(temp_file_path)
|
| 731 |
+
|
| 732 |
+
# return {
|
| 733 |
+
# "is_rice_leaf": is_rice,
|
| 734 |
+
# "confidence": f"{confidence * 100:.2f}%",
|
| 735 |
+
# "probabilities": result['probabilities']
|
| 736 |
+
# }
|
| 737 |
+
# except Exception as e:
|
| 738 |
+
# logging.error(f"Error during leaf validation: {e}")
|
| 739 |
+
# raise HTTPException(status_code=500, detail=f"Validation failed: {str(e)}")
|
| 740 |
+
|
| 741 |
+
# @app.post("/predict/")
|
| 742 |
+
# async def predict_disease(file: UploadFile = File(...), use_ai_recommendation: bool = True):
|
| 743 |
+
# """Predict rice disease from uploaded image"""
|
| 744 |
+
# # Check if models are loaded
|
| 745 |
+
# if not model_loaded or not validator_loaded:
|
| 746 |
+
# if model_loading:
|
| 747 |
+
# raise HTTPException(status_code=503, detail="Models are still loading. Please try again later.")
|
| 748 |
+
# else:
|
| 749 |
+
# # Try loading the models if they're not already loading
|
| 750 |
+
# success = load_model()
|
| 751 |
+
# if not success:
|
| 752 |
+
# raise HTTPException(status_code=500, detail=f"Failed to load models: {last_error}")
|
| 753 |
+
|
| 754 |
+
# try:
|
| 755 |
+
# # Read image file
|
| 756 |
+
# start_time = time.time()
|
| 757 |
+
|
| 758 |
+
# # Save uploaded file temporarily for validation (cross-platform)
|
| 759 |
+
# contents = await file.read()
|
| 760 |
+
# with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as temp_file:
|
| 761 |
+
# temp_file_path = temp_file.name
|
| 762 |
+
# temp_file.write(contents)
|
| 763 |
+
|
| 764 |
+
# logging.info(f"Image size: {len(contents)} bytes")
|
| 765 |
+
|
| 766 |
+
# # First validate if it's a rice leaf using ResNet18 validator
|
| 767 |
+
# validation_result = rice_validator.validate_image(temp_file_path, threshold=0.5)
|
| 768 |
+
# is_rice = validation_result['is_rice_leaf']
|
| 769 |
+
# rice_confidence = validation_result['confidence']
|
| 770 |
+
|
| 771 |
+
# # Remove temporary file
|
| 772 |
+
# os.remove(temp_file_path)
|
| 773 |
+
|
| 774 |
+
# if not is_rice:
|
| 775 |
+
# logging.info(f"Image not recognized as rice leaf: {rice_confidence * 100:.2f}% confidence")
|
| 776 |
+
# return {
|
| 777 |
+
# "is_rice_leaf": False,
|
| 778 |
+
# "confidence": f"{rice_confidence * 100:.2f}%",
|
| 779 |
+
# "message": "The uploaded image does not appear to be a rice leaf. Please upload a clear image of a rice plant leaf.",
|
| 780 |
+
# "probabilities": validation_result['probabilities']
|
| 781 |
+
# }
|
| 782 |
+
|
| 783 |
+
# # Process image for disease detection
|
| 784 |
+
# input_tensor = process_image(contents).to(device)
|
| 785 |
+
|
| 786 |
+
# # Make prediction
|
| 787 |
+
# with torch.no_grad():
|
| 788 |
+
# outputs = model(input_tensor)
|
| 789 |
+
# probabilities = F.softmax(outputs, dim=1)[0]
|
| 790 |
+
|
| 791 |
+
# # Get top predictions with probabilities
|
| 792 |
+
# top_probs, top_classes = torch.topk(probabilities, len(CLASS_NAMES))
|
| 793 |
+
|
| 794 |
+
# predictions = []
|
| 795 |
+
# for i in range(len(top_classes)):
|
| 796 |
+
# class_idx = top_classes[i].item()
|
| 797 |
+
# predictions.append({
|
| 798 |
+
# "label": CLASS_NAMES[class_idx],
|
| 799 |
+
# "confidence": f"{top_probs[i].item()*100:.2f}%"
|
| 800 |
+
# })
|
| 801 |
+
|
| 802 |
+
# # Get primary prediction (highest confidence)
|
| 803 |
+
# predicted_class = top_classes[0].item()
|
| 804 |
+
# disease_name = CLASS_NAMES[predicted_class]
|
| 805 |
+
# confidence = float(top_probs[0].item()) * 100
|
| 806 |
+
|
| 807 |
+
# # Get comprehensive disease recommendation from built-in database
|
| 808 |
+
# recommendation_data = RECOMMENDATIONS.get(disease_name, {
|
| 809 |
+
# 'recommendation': 'Unknown disease. Please consult with agricultural extension services.',
|
| 810 |
+
# 'details': 'Disease information not available in database.',
|
| 811 |
+
# 'category': 'Unknown',
|
| 812 |
+
# 'severity': 'Unknown'
|
| 813 |
+
# })
|
| 814 |
+
|
| 815 |
+
# logging.info(f"Using built-in recommendation for {disease_name}")
|
| 816 |
+
|
| 817 |
+
# # Log prediction time
|
| 818 |
+
# processing_time = time.time() - start_time
|
| 819 |
+
# logging.info(f"Prediction completed in {processing_time:.3f} seconds")
|
| 820 |
+
|
| 821 |
+
# # Return in format expected by PHP code
|
| 822 |
+
# return {
|
| 823 |
+
# "is_rice_leaf": True,
|
| 824 |
+
# "leaf_confidence": f"{rice_confidence * 100:.2f}%",
|
| 825 |
+
# "predictions": predictions,
|
| 826 |
+
# "disease": disease_name,
|
| 827 |
+
# "confidence": f"{confidence:.2f}%",
|
| 828 |
+
# "recommendation": recommendation_data.get("recommendation", ""),
|
| 829 |
+
# "details": recommendation_data.get("details", ""),
|
| 830 |
+
# "category": recommendation_data.get("category", "Unknown"),
|
| 831 |
+
# "severity": recommendation_data.get("severity", "Unknown"),
|
| 832 |
+
# "inference_time_seconds": round(processing_time, 3)
|
| 833 |
+
# }
|
| 834 |
+
|
| 835 |
+
# except Exception as e:
|
| 836 |
+
# logging.error(f"Error during prediction: {e}")
|
| 837 |
+
# raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")
|
| 838 |
+
|
| 839 |
+
# if __name__ == "__main__":
|
| 840 |
+
# import uvicorn
|
| 841 |
+
# # Production settings: no hot reload, proper host binding
|
| 842 |
+
# uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=False)
|