Spaces:
Sleeping
Sleeping
| """ | |
| import gradio as gr | |
| from ultralytics import YOLO | |
| import torch | |
| from render import custom_render_result | |
| # poids | |
| model = YOLO('./yolov8_aug_200_100.pt') | |
| def yoloV8_func(image: gr.Image = None, | |
| image_size: int = 608, | |
| conf_threshold: float = 0.6, | |
| iou_threshold: float = 0.6): | |
| results = model.predict(image, | |
| conf=conf_threshold, | |
| iou=iou_threshold, | |
| imgsz=image_size, | |
| show_conf = False, | |
| save_conf = False) | |
| detections = results[0] | |
| # je tris les boîtes par la coordonnée x de début | |
| sorted_detections = sorted(zip(detections.boxes.xyxy, detections.boxes.cls), key=lambda x: x[0][0]) | |
| # seulement les chiffres | |
| index_lu = ''.join([str(int(cls)) for _, cls in sorted_detections if cls >= 0 and cls <= 9])+str(" m3") | |
| # je retourne les images avec les b.e et les classes et les proba | |
| render = custom_render_result(model=model, image=image, result=detections) | |
| return render, index_lu | |
| inputs = [ | |
| gr.Image(type="filepath", label="Input Image"), | |
| #gr.Slider(minimum=320, maximum=1280, step=32, label="Image Size", value=640), | |
| #gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="Confidence Threshold"), | |
| #gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label="IOU Threshold"), | |
| ] | |
| output_1 = gr.Image(type="filepath", label="Output Image") | |
| output_2 = gr.Textbox(label="Index du compteur") | |
| title = "MVP - Vers un Releveur Virtuel Intelligent entre les Mains des Clients 7/24" | |
| yolo_app = gr.Interface( | |
| fn=yoloV8_func, | |
| inputs=inputs, | |
| outputs=[output_1, output_2], | |
| title=title | |
| ) | |
| yolo_app.launch(debug=True, share=True, ssr_mode=False)#.queue() | |
| """ | |
| import os | |
| import cv2 | |
| import numpy as np | |
| from PIL import Image | |
| import gradio as gr | |
| from ultralytics import YOLO | |
| from render import custom_render_result | |
| # ✅ Fix config Ultralytics (évite la recréation à chaque démarrage) | |
| os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics" | |
| # ✅ Chargement du modèle une seule fois au démarrage (global) | |
| model = YOLO('./yolov8_aug_200_100.pt') | |
| # ✅ Fonction nommée au lieu de lambda (évite la transpilation JS de Gradio) | |
| def sort_by_x(item): | |
| return item[0][0] | |
| # ✅ Conversion universelle de l'image en numpy array RGB (format natif YOLO) | |
| def to_numpy_rgb(image): | |
| if image is None: | |
| return None | |
| if isinstance(image, str): | |
| # filepath → numpy BGR → RGB | |
| img = cv2.imread(image) | |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| return img | |
| elif isinstance(image, Image.Image): | |
| # PIL → numpy RGB | |
| return np.array(image.convert("RGB")) | |
| elif isinstance(image, np.ndarray): | |
| # déjà numpy, s'assurer que c'est RGB | |
| if len(image.shape) == 2: | |
| # image en niveaux de gris → RGB | |
| image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) | |
| return image | |
| else: | |
| raise TypeError(f"Type d'image non supporté : {type(image)}") | |
| def yoloV8_func( | |
| image=None, | |
| image_size: int = 608, | |
| conf_threshold: float = 0.6, | |
| iou_threshold: float = 0.6 | |
| ): | |
| if image is None: | |
| return None, "⚠️ Aucune image fournie" | |
| # ✅ Conversion de l'image en numpy array fiable pour YOLO | |
| try: | |
| img_array = to_numpy_rgb(image) | |
| except Exception as e: | |
| return None, f"❌ Erreur de conversion image : {str(e)}" | |
| # ✅ Inférence YOLO | |
| results = model.predict( | |
| img_array, | |
| conf=conf_threshold, | |
| iou=iou_threshold, | |
| imgsz=image_size, | |
| show_conf=False, | |
| save_conf=False | |
| ) | |
| detections = results[0] | |
| # ✅ Tri des boîtes par coordonnée X (ordre de lecture) | |
| sorted_detections = sorted( | |
| zip(detections.boxes.xyxy, detections.boxes.cls), | |
| key=sort_by_x | |
| ) | |
| # ✅ Extraction des chiffres détectés (classes 0-9) | |
| index_lu = ''.join([ | |
| str(int(cls)) | |
| for _, cls in sorted_detections | |
| if 0 <= int(cls) <= 9 | |
| ]) + " m3" | |
| # ✅ Rendu de l'image annotée | |
| render = custom_render_result(model=model, image=img_array, result=detections) | |
| return render, index_lu | |
| # ✅ Inputs / Outputs | |
| inputs = [ | |
| gr.Image(type="numpy", label="📷 Image du compteur"), | |
| ] | |
| output_1 = gr.Image(type="numpy", label="🖼️ Image annotée") | |
| output_2 = gr.Textbox(label="🔢 Index du compteur") | |
| title = "MVP - Vers un Agent Releveur Virtuel en faveur des Releveurs Terrain et entre les mains des Clients 7/24" | |
| # ✅ Interface Gradio | |
| yolo_app = gr.Interface( | |
| fn=yoloV8_func, | |
| inputs=inputs, | |
| outputs=[output_1, output_2], | |
| title=title, | |
| flagging_mode="never", | |
| ) | |
| # ✅ Launch propre pour HuggingFace Spaces | |
| yolo_app.launch( | |
| debug=False, # False en production | |
| share=False, # Toujours False sur HuggingFace Spaces | |
| ssr_mode=False # Désactive le SSR expérimental (lent) | |
| ) |