File size: 4,533 Bytes
72885c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""Gradio Blocks UI: image / video / webcam tabs plus a JSON API endpoint."""
import gradio as gr

from src.configs import settings
from src.inference.predictor import Predictor
from src.inference.video import annotate_video


def _predict_image(predictor: Predictor, image):
    if image is None:
        return None, "No image provided", "N/A"
    result = predictor.classify(image)
    return result.annotated_frame, result.label, result.confidence_str


def _predict_api(predictor: Predictor, image):
    if image is None:
        return {"success": False, "error": "No image provided"}
    try:
        result = predictor.classify(image)
        return {
            "success": True,
            "class": result.label,
            "confidence": result.confidence_str,
            "confidence_value": result.confidence,
            "threshold_exceeded": result.threshold_exceeded,
        }
    except Exception as exc:
        return {"success": False, "error": str(exc)}


def _predict_video(predictor: Predictor, video_path):
    if video_path is None:
        return None
    return annotate_video(video_path, predictor)


def build_interface(predictor: Predictor) -> gr.Blocks:
    with gr.Blocks(title="SerraSafe - Détection de Pestes") as demo:
        gr.Markdown(
            f"""
            # 🌱 SerraSafe Guardian - Système de Détection de Pestes

            Ce système utilise l'intelligence artificielle pour détecter et classifier les pestes dans votre serre.

            **Classes détectées:** {", ".join(settings.CLASS_LABELS)}
            """
        )

        with gr.Tab("📷 Analyse Image"):
            with gr.Row():
                with gr.Column():
                    image_input = gr.Image(type="numpy", label="Télécharger une image")
                    image_button = gr.Button("Analyser l'image", variant="primary")
                with gr.Column():
                    image_output = gr.Image(label="Résultat")
                    image_label = gr.Textbox(label="Classe détectée")
                    image_confidence = gr.Textbox(label="Confiance")

            image_button.click(
                fn=lambda img: _predict_image(predictor, img),
                inputs=image_input,
                outputs=[image_output, image_label, image_confidence],
            )

        with gr.Tab("📹 Analyse Vidéo"):
            with gr.Row():
                with gr.Column():
                    video_input = gr.Video(label="Télécharger une vidéo")
                    video_button = gr.Button("Analyser la vidéo", variant="primary")
                with gr.Column():
                    video_output = gr.Video(label="Vidéo annotée")

            video_button.click(
                fn=lambda path: _predict_video(predictor, path),
                inputs=video_input,
                outputs=video_output,
            )

        with gr.Tab("🎥 Webcam"):
            gr.Markdown("### Capturez une image avec votre webcam pour l'analyser")
            with gr.Row():
                with gr.Column():
                    webcam_input = gr.Image(sources=["webcam"], type="numpy", label="Webcam", streaming=False)
                    webcam_button = gr.Button("Analyser", variant="primary")
                with gr.Column():
                    webcam_output = gr.Image(label="Résultat")
                    webcam_label = gr.Textbox(label="Classe détectée")
                    webcam_confidence = gr.Textbox(label="Confiance")

            webcam_button.click(
                fn=lambda img: _predict_image(predictor, img),
                inputs=webcam_input,
                outputs=[webcam_output, webcam_label, webcam_confidence],
            )

        with gr.Tab("🔌 API (JSON)"):
            gr.Markdown(
                """
                ### API pour clients externes

                Utilisez cet endpoint pour obtenir des prédictions en JSON.

                **Endpoint:** `/api/predict` (POST, retourne `class`, `confidence`, `threshold_exceeded`)
                """
            )
            with gr.Column():
                api_image_input = gr.Image(type="numpy", label="Image")
                api_button = gr.Button("Tester l'API", variant="primary")
                api_output = gr.JSON(label="Réponse JSON")

            api_button.click(
                fn=lambda img: _predict_api(predictor, img),
                inputs=api_image_input,
                outputs=api_output,
                api_name="predict",
            )

    return demo