import gradio as gr import tensorflow as tf import numpy as np from PIL import Image model = tf.keras.models.load_model("model.keras") IMG_SIZE = (224, 224) class_labels = ['Black Headed caterpillar', 'Eriophyid Mite Damage', 'Red Palm Weevil', 'Rhinoceros Beetle', 'White Grub', 'Whitefly'] # dictionary info_data = { "Black Headed caterpillar": { "info": """ **Pest Identity**: The leaf-eating caterpillar, also known as the black-headed caterpillar, has become a major pest in India since 1920. It's found in coastal and backwater areas, feeding on coconut palms and other related plants. **Symptoms**: The caterpillars feed on the chlorophyll, causing severe defoliation. In severe outbreaks, older leaves turn brown and appear scorched, and crop yield can be reduced by half. The larvae hide in silken webs on the underside of leaflets. **Life Cycle**: The life cycle takes about two months. Eggs are creamy white and hatch in five days. The larval period lasts 42 days, and pupation takes 12 days. Adults are medium-sized moths with light grayish-ochreaceous forewings. """, "management": """ **Chemical Management**: Insecticides can be applied directly to the affected palms or injected into the trunk. **Biological Management**: Releasing natural parasites of the caterpillar, such as the braconid wasp Goniozus nephantidis, can be an effective long-term solution. Maintaining a healthy ecosystem with diverse plants can also encourage natural predators. **Physical Management**: In small-scale infestations, manually removing and destroying the infested leaves can help reduce the population. """ }, "Eriophyid Mite Damage": { "info": """ **Pest Identity**: The coconut eriophyid mite (Aceria guerreronis) is a microscopic pest that attacks the developing coconut fruit, often causing significant damage and yield loss. **Symptoms**: Mite feeding causes triangular, yellowish patches at the base of the coconut nut. As the fruit matures, these patches turn brown, corky, and cracked, often leading to nut deformation and reduced size. """, "management": """ **Chemical Management**: Acaricides can be applied to the base of the bunches to control mite populations. **Biological Management**: Natural predators, such as predatory mites, can be used to help control the pest. **Cultural Management**: Regularly applying a nutrient-rich fertilizer can improve the palms' resilience. Maintaining proper moisture can also help. """ }, "Red Palm Weevil": { "info": """ **Pest Identity**: The Red Palm Weevil (Rhynchophorus ferrugineus) is one of the most destructive pests of palm trees worldwide. The larvae bore into the trunk, feeding on the soft, inner tissue of the palm. **Symptoms**: Signs of infestation include oozing sap from the trunk, presence of tunnels, and a "chewing" sound from the larvae. In advanced stages, the palm's crown may wither and collapse. """, "management": """ **Chemical Management**: Trunk injections with systemic insecticides are a common control method. **Trapping**: Pheromone traps can be used to monitor and mass-trap adult weevils, reducing the population. **Physical Management**: Heavily infested palms should be removed and destroyed to prevent the spread of the pest. """ }, "Rhinoceros Beetle": { "info": """ **Pest Identity**: The Rhinoceros Beetle (Oryctes rhinoceros) is a large beetle that causes characteristic V-shaped cuts on the fronds of young coconut palms. **Symptoms**: The beetles bore into the unopened fronds and spathes, creating tunnels. When the leaves open, they show a tell-tale, triangular cut. This reduces the palm's photosynthetic area and can cause significant damage to young plants. """, "management": """ **Biological Management**: Using pathogens like the Oryctes virus is an effective biological control method to reduce beetle populations. **Cultural Management**: Keeping the plantation clean by removing decaying organic matter (like dead logs or stumps) reduces breeding sites for the beetles. **Physical Management**: Manually extracting the beetles from the crowns of the palms using a hooked iron rod is an effective but labor-intensive method. """ }, "White Grub": { "info": """ **Pest Identity**: White grubs are the larvae of various beetles (e.g., Scarab beetles) that feed on the roots of plants, including coconut palms. **Symptoms**: Infested palms show stunted growth, yellowing leaves, and wilting. In severe cases, the palms can be easily pulled out of the soil due to root damage. """, "management": """ **Chemical Management**: Soil drenching with insecticides can kill the grubs. **Cultural Management**: Deep plowing and proper irrigation can expose the grubs to predators and reduce their survival. **Biological Management**: Applying entomopathogenic nematodes or fungi that are natural parasites of the grubs can be a very effective long-term solution. """ }, "Whitefly": { "info": """ **Pest Identity**: Coconut whitefly (e.g., *Aleurodicus rugioperculatus* and related species) are tiny, sap-sucking insects that colonize the undersides of fronds. Nymphs and adults excrete honeydew, fostering sooty mold that interferes with photosynthesis. **Symptoms**: Silvery stippling/yellowing on leaflets, sticky honeydew deposits, black sooty mold coating fronds and nut husks, leaf desiccation and premature frond drop. Heavy infestations can reduce vigor, yield, and attract ants. """, "management": """ **Chemical Management**: Target early instars with systemic or translaminar insecticides (e.g., neonicotinoids or diamides where permitted) via trunk/soil application; rotate modes of action (IRAC groups) to delay resistance. Use horticultural oils or insecticidal soaps to suppress nymphs and remove honeydew/sooty mold. Always follow local regulations and label directions. **Cultural Management**: Prune and destroy heavily infested fronds to lower population pressure; improve spacing and canopy airflow to reduce whitefly buildup; wash fronds with water to remove honeydew/sooty mold; avoid excessive nitrogen fertilization which favors outbreaks; manage ant populations that protect whiteflies. **Biological Management**: Conserve and, where available, augment natural enemies (Encarsia/Eretmocerus parasitoid wasps, lacewings, lady beetles). Encourage parasitoids by minimizing broad-spectrum sprays and using selective products. Entomopathogenic fungi (e.g., *Beauveria bassiana*, *Isaria* spp.) can help suppress nymphs under suitable humidity. """ } } def predict(image): # Pre-processing steps image = tf.image.resize(image, IMG_SIZE) image = tf.cast(image, tf.float32) image = image / 255.0 image = np.expand_dims(image, axis=0) # Model prediction predictions = model.predict(image) predicted_class_index = np.argmax(predictions[0]) predicted_label = class_labels[predicted_class_index] pest_info = info_data.get(predicted_label, {"info": "Info not found.", "management": "Management info not found."}) info = pest_info["info"] management = pest_info["management"] return predicted_label, info, management def about_text(): return "Machine Learning based coconut pest classifier" def how_to(): return "How to use this app" about_tab = gr.Interface( fn=about_text, inputs=[], outputs=gr.Textbox(), title="About" ) how_to_tab = gr.Interface( fn=how_to, inputs=[], outputs=gr.Textbox(), title="How to Use the Interface" ) with gr.Blocks() as image_tab: gr.Markdown("## Coconut Pest Classifier") with gr.Row(): image_input = gr.Image(type="numpy", label="Upload an Image") with gr.Column(): gr.Markdown("### Prediction Results") prediction_output = gr.Label(label="Prediction") with gr.Row(): with gr.Column(): classify_btn = gr.Button("Classify") with gr.Row(): with gr.Column(): gr.Markdown("### Info") info_output = gr.Markdown(label="info") management_output = gr.Markdown(label="management") classify_btn.click( fn=predict, inputs=image_input, outputs=[prediction_output, info_output, management_output] ) with gr.Blocks(title="CocoML") as demo: gr.Markdown("# CocoML #") gr.Markdown("This is a Machine learning based coconut pest classifier") gr.TabbedInterface( [image_tab, how_to_tab, about_tab], ["Image Classifier", "How To", "About"] ) demo.launch(debug=True)