Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| import torch | |
| from PIL import Image | |
| from torchvision import transforms | |
| import warnings | |
| import sys | |
| import google.generativeai as genai | |
| import os | |
| import contextlib | |
| from transformers import ViTForImageClassification, pipeline | |
| # Suppress warnings related to the model weights initialization | |
| warnings.filterwarnings("ignore", category=UserWarning, message=".*weights.*") | |
| warnings.filterwarnings("ignore", category=FutureWarning, module="torch") | |
| # Suppress output for copying files and verbose model initialization messages | |
| def suppress_stdout(): | |
| with open(os.devnull, 'w') as devnull: | |
| old_stdout = sys.stdout | |
| sys.stdout = devnull | |
| try: | |
| yield | |
| finally: | |
| sys.stdout = old_stdout | |
| # Load the saved model and suppress the warnings | |
| with suppress_stdout(): | |
| model = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224-in21k', num_labels=6) | |
| model.load_state_dict(torch.load('vit_sugarcane_disease_detection.pth', map_location=torch.device('cpu'))) | |
| model.eval() | |
| # Define the same transformation used during training | |
| transform = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | |
| ]) | |
| # Load the class names (disease types) | |
| class_names = ['BacterialBlights', 'Healthy', 'Mosaic', 'RedRot', 'Rust', 'Yellow'] | |
| #Gemini Response | |
| def get_response_llm(predicted_label,knowledge_base): | |
| 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 breif answer of advise for managing this condition." | |
| genai.configure(api_key=os.getenv("GEMINI_API_KEY")) | |
| model = genai.GenerativeModel("gemini-1.5-flash") | |
| response = model.generate_content([prompt]) | |
| return response.text | |
| # Comprehensive knowledge base for sugarcane diseases and practices | |
| knowledge_base = """ | |
| 'BacterialBlights': Bacterial blights are caused by *Xanthomonas albilineans*. | |
| **Symptoms:** | |
| - Water-soaked lesions on leaves. | |
| - Gradual yellowing and withering of leaves. | |
| - Reduction in photosynthesis and stunted growth. | |
| **Management:** | |
| - Apply copper-based fungicides. | |
| - Improve field drainage to avoid waterlogging. | |
| - Use disease-free planting material., | |
| 'Mosaic': Mosaic disease is caused by the Sugarcane mosaic virus (SCMV) and often transmitted by aphids. | |
| **Symptoms:** | |
| - Mottled appearance on leaves with streaks of yellow and green. | |
| - Reduced photosynthetic efficiency. | |
| - Decreased cane weight and sugar content. | |
| **Management:** | |
| - Use resistant sugarcane varieties. | |
| - Control aphid populations with insecticides. | |
| - Remove and destroy infected plants to prevent spread., | |
| 'RedRot': Red rot is caused by the fungus *Colletotrichum falcatum*. | |
| **Symptoms:** | |
| - Red streaks inside the cane with white patches. | |
| - Rotting of the stalk, emitting a sour smell. | |
| - Drying of leaves and eventual plant death. | |
| **Management:** | |
| - Plant resistant varieties. | |
| - Remove and burn infected plants. | |
| - Treat soil with fungicides and practice crop rotation., | |
| 'Rust': Rust is caused by the fungus *Puccinia melanocephala*. | |
| **Symptoms:** | |
| - Formation of orange to reddish pustules on leaves. | |
| - Premature drying of leaves. | |
| - Reduced plant vigor and yield. | |
| **Management:** | |
| - Apply systemic fungicides (e.g., triazoles). | |
| - Ensure proper field hygiene. | |
| - Avoid water stress and maintain balanced nutrition., | |
| 'Yellow': Yellowing can be caused by nutrient deficiencies or disease onset. | |
| **Symptoms:** | |
| - Yellowing of leaf tips or entire leaves. | |
| - Reduced photosynthesis and growth. | |
| **Management:** | |
| - Conduct soil testing to identify deficiencies. | |
| - Apply balanced fertilizers as per soil nutrient status. | |
| - Maintain proper irrigation schedules., | |
| 'Smut': Smut is caused by the fungus *Sporisorium scitamineum*. | |
| **Symptoms:** | |
| - Formation of whip-like structures at the growing points. | |
| - Stunted growth and tiller proliferation. | |
| - Reduced sugar content. | |
| **Management:** | |
| - Plant smut-resistant varieties. | |
| - Remove smut-infected plants. | |
| - Treat seed sets with fungicides before planting., | |
| 'Healthy': The sugarcane crop is healthy. | |
| Continue regular monitoring and follow good agronomic practices: | |
| - Ensure balanced fertilization. | |
| - Maintain proper irrigation schedules. | |
| - Monitor for pests and diseases regularly., | |
| 'GeneralPractices': **General Practices for Disease Prevention** | |
| - **Field Sanitation:** Remove and destroy crop residues and infected plants to reduce inoculum levels. | |
| - **Resistant Varieties:** Cultivate sugarcane varieties that are resistant to specific diseases. | |
| - **Seed Treatment:** Use disease-free, certified seed material. Treat seed sets with fungicides before planting. | |
| - **Crop Rotation:** Rotate sugarcane with non-host crops to break the disease cycle. | |
| - **Optimal Agronomic Practices:** Ensure proper irrigation and drainage. Maintain balanced fertilization and avoid over-application of nitrogen. | |
| - **Timely Monitoring and Control:** Inspect fields regularly for symptoms. Apply recommended fungicides or bactericides as soon as symptoms appear. | |
| - **Integrated Pest and Disease Management (IPDM):** Combine biological, chemical, and cultural methods to manage diseases sustainably., | |
| 'ImpactOfDiseases': **Impact of Sugarcane Diseases** | |
| - **Yield Reduction:** Diseases like red rot and smut can reduce cane yield by 30β60%. | |
| - **Quality Degradation:** Affected plants produce less sugar and lower-quality juice. | |
| - **Economic Losses:** Increased cost of management and reduced marketable output affect profitability., | |
| 'SugarcaneOverview': Sugarcane is a critical crop globally, providing raw materials for sugar, ethanol, and other byproducts. | |
| However, it is susceptible to various diseases caused by fungi, bacteria, viruses, and environmental factors. | |
| Effective management practices are essential to ensure high yield and quality. | |
| """ | |
| # Update the predict_disease function | |
| def predict_disease(image): | |
| # Apply transformations to the image | |
| img_tensor = transform(image).unsqueeze(0) # Add batch dimension | |
| # Make prediction | |
| with torch.no_grad(): | |
| outputs = model(img_tensor) | |
| _, predicted_class = torch.max(outputs.logits, 1) | |
| # Get the predicted label | |
| predicted_label = class_names[predicted_class.item()] | |
| # # Retrieve response from knowledge base | |
| # if predicted_label in knowledge_base: | |
| # detailed_response = knowledge_base[predicted_label] | |
| # else: | |
| # # Fallback to AI-generated response | |
| predicted_label = f'The predicted label is {predicted_label}' | |
| detailed_response = get_response_llm(predicted_label,knowledge_base) | |
| # Create a styled HTML output | |
| output_message = f""" | |
| <div style='font-size: 18px; color: #4CAF50; font-weight: bold;'> | |
| Detected Disease: <span style='color: #FF5722;'>{predicted_label}</span> | |
| </div> | |
| """ | |
| if predicted_label != "Healthy": | |
| output_message += f""" | |
| <p style='font-size: 16px; color: #757575;'> | |
| {detailed_response} | |
| </p> | |
| """ | |
| else: | |
| output_message += f""" | |
| <p style='font-size: 16px; color: #757575;'> | |
| {detailed_response} | |
| </p> | |
| """ | |
| return output_message | |
| # Create Gradio interface | |
| inputs = gr.Image(type="pil") | |
| outputs = gr.HTML() # Use HTML output for styled text | |
| EXAMPLES = ["img1.jpeg", "redrot2.jpg", "cropped_yellow.jpeg","cropped_rust.jpeg", "cropped_BacterialBlight.png","cropped_mosaic.jpeg","healthy2.jpeg"] | |
| demo_app = gr.Interface( | |
| fn=predict_disease, | |
| inputs=inputs, | |
| outputs=outputs, | |
| title="Sugarcane Disease Detection", | |
| examples=EXAMPLES, | |
| live=True, | |
| theme="huggingface" | |
| ) | |
| demo_app.launch(debug=True) | |