Spaces:
Sleeping
Sleeping
Create app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import gradio as grimport numpy as npimport tensorflow as tfimport pandas as pdimport osimport zipfileimport shutil
# 1. Load the model directly from the folder of your Spacemodel_path = 'sugarcane_20_epoch_model.keras'model = tf.keras.models.load_model(model_path)
class_names = ['Healthy', 'Mosaic', 'RedRot', 'Rust', 'Yellow']
# Single Image Logicdef predict_single_leaf(input_image): if input_image is None: return None img = tf.image.resize(input_image, (224, 224)) img_array = tf.expand_dims(img, 0) predictions = model.predict(img_array, verbose=0) scores = predictions[0] return {class_names[i]: float(scores[i]) for i in range(5)}
# Mass Zip Logicdef predict_bulk_zip(zip_file): if zip_file is None: return None extract_dir = "./temp_mass_images" if os.path.exists(extract_dir): shutil.rmtree(extract_dir) os.makedirs(extract_dir) with zipfile.ZipFile(zip_file.name, 'r') as zip_ref: zip_ref.extractall(extract_dir) results = [] for root, dirs, files in os.walk(extract_dir): for filename in files: if filename.lower().endswith(('.png', '.jpg', '.jpeg')): img_path = os.path.join(root, filename) try: img = tf.keras.utils.load_img(img_path, target_size=(224, 224)) img_array = tf.keras.utils.img_to_array(img) img_array = tf.expand_dims(img_array, 0) predictions = model.predict(img_array, verbose=0) scores = predictions[0] highest_idx = np.argmax(scores) results.append({ "File Name": filename, "Predicted Diagnosis": class_names[highest_idx], "Confidence Level": f"{(scores[highest_idx] * 100):.2f}%" }) except Exception: continue shutil.rmtree(extract_dir) if results: df = pd.DataFrame(results) report_path = "./mass_detection_report.csv" df.to_csv(report_path, index=False) return report_path return None
# Build UI layoutwith gr.Blocks(title="Sugarcane AI") as app: gr.Markdown("# 🌾 Sugarcane Leaf AI Detection Hub") gr.Markdown("An enterprise diagnostic tool to analyze sugarcane crops instantly.") with gr.Tab("Single Leaf Diagnostics"): image_input = gr.Image() label_output = gr.Label(num_top_classes=3) image_button = gr.Button("Analyze Leaf") image_button.click(fn=predict_single_leaf, inputs=image_input, outputs=label_output) with gr.Tab("Mass Bulk Detection (Zip Folder)"): file_input = gr.File(file_types=[".zip"], label="Upload Unlabeled Leaf Folder (.zip)") file_output = gr.File(label="Download Generated Diagnostics Report (.csv)") file_button = gr.Button("Run Mass Detection Process") file_button.click(fn=predict_bulk_zip, inputs=file_input, outputs=file_output)
app.launch()app.pyAdded+86