# AUTOGENERATED! DO NOT EDIT! File to edit: ../weed_classifier.ipynb. import json # %% auto 0 __all__ = ['learn', 'labels', 'article', 'title', 'description', 'examples', 'interpretation', 'enable_queue', 'predict'] CROPS = ["Maíz", "Ciruelo", "Cítricos", "Frutos y Hortalizas", "Nectarinas", "Pera y Manzano", "Vid", "Soja", "Girasol", "Pasturas", "Algodón", "Maní", "Cebada", "Trigo", "Papa", "Poroto", "Caña de azúcar", "Tomate", "Otro"] STATE = ["pre", "post", "Otro"] # %% ../weed_classifier.ipynb 1 from fastai.vision.all import * import gradio as gr import skimage # %% ../weed_classifier.ipynb 2 learn = load_learner('export.pkl') # JSON de recomendaciones with open("WEEDS_JSON.json", "r") as f: recommendations = json.load(f) # JSON de recomendaciones with open("PROVIDERS.json", "r") as f: providers = json.load(f) # %% ../weed_classifier.ipynb 3 labels = learn.dls.vocab print(learn.dls.vocab) def predict(img, crop, area, state): img = PILImage.create(img) pred, pred_idx, probs = learn.predict(img) label = labels[pred_idx] # Clasificación con porcentajes classification_output = {labels[i]: float(probs[i]) for i in range(len(labels))} # Información de recomendaciones recommendations_output = recommendations.get(label, {}) # Generación de la salida en formato HTML para las recomendaciones html_output = display_output(label, recommendations_output, crop, area, state) return classification_output, html_output def display_output(weed_name, recommendations, crop, area, state): products = recommendations.get("products", []) weed_url = recommendations.get("weed_url", "#") control = recommendations.get("text", "") # Crear una lista para almacenar la información de salida output_list = [f"Weed Identified: {weed_name}"] # Añadir recomendaciones de productos # Añadir recomendaciones de productos output_html = f"

Herbicidas recomendados

" output_list = [] for product in products: if state in product["crop_stage"] and crop in product["crop_type"]: product_name = product["name"] product_img = product["img"] product_url = product["url"] product_amount = float(product["amount_per_sq_m"]) * float(area) for product_info in providers["product_suppliers"]: if product_info["product_name"] == product_name: for supplier in product_info["suppliers"]: supplier_name = supplier["name"] supplier_price = supplier["price"] supplier_delivery_time = supplier["delivery_time"] card = f"""

{product_name}

{supplier_name}

{product_name}

{supplier_price}

{supplier_delivery_time}

Cantidad recomendada: {product_amount} ml

Más info

""" output_list.append(card) output_html += "".join(output_list) return output_html # %% ../weed_classifier.ipynb 5 article = """
Este modelo se entrenó con un conjunto de datos que contiene 5.539 imágenes de plántulas de cultivos y malas hierbas. Las imágenes se agrupan en 12 clases. Estas clases representan especies de plantas comunes en la agricultura danesa en distintas fases de crecimiento. Se ajustó un modelo ResNet34 preentrenado utilizando la biblioteca de visión fastai. La tasa de error alcanzada en el conjunto de datos de validación es del 2,5% tras 4 épocas.

""" # %% ../weed_classifier.ipynb 6 description = '''

RECOMENDADOR DE HERBICIDAS

Descubre nuestra plataforma diseñada para facilitar la selección de herbicidas de Bayer de manera eficiente. Captura imágenes con tu dispositivo móvil y recibe recomendaciones precisas basadas en las necesidades específicas de tu terreno.

La intuitiva interfaz presenta información detallada sobre los herbicidas, destacando sus características, beneficios y aplicaciones recomendadas. Mantenemos actualizada nuestra base de datos con los últimos avances en la protección de cultivos para ofrecerte la información más actualizada.

Esta herramienta no solo simplifica la toma de decisiones, sino que también fomenta una gestión más sostenible de los cultivos, alineándose con las mejores prácticas agrícolas y el cuidado responsable del medio ambiente.

''' examples = [ 'FatHen.png', 'Loose Silky-bent.png', 'CommonChickweed.png', 'cleavers.png', 'ShepherdsPurse.png', 'Black-grass.png', 'blackgrass-mature.jpg','Shepered_purse.jpeg' ] interpretation='default' enable_queue=True theme = gr.themes.Monochrome(primary_hue="blue").set( button_primary_background_fill="*primary_800", button_primary_background_fill_hover="*primary_950", checkbox_label_text_color="*primary_800", checkbox_label_background_fill="white", checkbox_label_background_fill_hover="white", checkbox_label_background_fill_selected="white", checkbox_background_color_selected="*primary_800", checkbox_background_color="*primary_200", checkbox_background_color_focus="*primary_600", ) with gr.Blocks(title="BAYER", css=".gradio-container {margin-top:10px !important; margin-bottom: 20px !important, min-width: 100% !important} footer {visibility:hidden}", theme=theme) as demo: with gr.Row(): gr.Markdown(description) with gr.Row(): with gr.Column(scale=1): image = gr.Image(source="upload", type="filepath", optional=False, label="Imagen") example = gr.Examples(examples=examples, inputs=image) with gr.Column(scale=2): with gr.Row(): with gr.Column(scale=1): crop = gr.Dropdown(CROPS, label="Cultivo", info="¿Qué cultivo hay plantado?") area = gr.Number(value=1, label="Superficie", info="¿Cuántos metros cuadrados ocupa la maleza?") state = gr.Dropdown(STATE, label="Estado", info="¿En qué estado de crecimiento está el cultivo?") btn = gr.Button(value="Recomendar") with gr.Row(): output = gr.components.Label(num_top_classes=1) with gr.Row(): output2 =gr.components.HTML() with gr.Row(): gr.Markdown(article) btn.click(predict, inputs=[image, crop, area, state], outputs=[output, output2], api_name="BAYER") demo.launch(favicon_path="favicon.ico", enable_queue=enable_queue)