{"id":23288542,"url":"https://github.com/kernferm/yolo-script","last_synced_at":"2025-08-21T19:31:44.508Z","repository":{"id":244653957,"uuid":"795087406","full_name":"KernFerm/yolo-script","owner":"KernFerm","description":"This repository contains a script to load and export YOLO models using the Ultralytics library. The script can detect and utilize NVIDIA and AMD GPUs to accelerate the process. The supported export formats include ONNX, TorchScript, CoreML, TFLite, and TFJS.","archived":false,"fork":false,"pushed_at":"2024-11-16T01:58:46.000Z","size":168,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-11-16T02:32:37.378Z","etag":null,"topics":["ai","amd-gpu","batch-script","machine-learning","nvidia-gpu","onnx","pip","pt","python","ultralytics","virtual-environment","windows","yolov5","yolov8"],"latest_commit_sha":null,"homepage":"","language":"Batchfile","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/KernFerm.png","metadata":{"files":{"readme":"README.MD","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-05-02T15:00:29.000Z","updated_at":"2024-11-16T01:58:49.000Z","dependencies_parsed_at":"2024-06-16T13:25:08.334Z","dependency_job_id":"7a2a6759-eb60-4cf8-84ca-330d225dfea7","html_url":"https://github.com/KernFerm/yolo-script","commit_stats":null,"previous_names":["kernferm/ptonnx","kernferm/pt_onnx_converter","kernferm/yolo-export-script","kernferm/yolo-script"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KernFerm%2Fyolo-script","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KernFerm%2Fyolo-script/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KernFerm%2Fyolo-script/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/KernFerm%2Fyolo-script/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/KernFerm","download_url":"https://codeload.github.com/KernFerm/yolo-script/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230528060,"owners_count":18240093,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","amd-gpu","batch-script","machine-learning","nvidia-gpu","onnx","pip","pt","python","ultralytics","virtual-environment","windows","yolov5","yolov8"],"created_at":"2024-12-20T03:20:34.808Z","updated_at":"2024-12-20T03:20:35.383Z","avatar_url":"https://github.com/KernFerm.png","language":"Batchfile","readme":"# This one works 100% https://github.com/KernFerm/exporting-YOLO\r\n---\r\n---\r\n## Support the Project ⭐\r\n\r\nIf you find this project useful, please give it a star! Your support is appreciated and helps keep the project growing. 🌟\r\n\r\n\r\n# YOLO Model Export Script\r\n\r\nThis repository contains a script to load and export YOLO models using the Ultralytics library. The script can detect and utilize NVIDIA and AMD GPUs to accelerate the process. The supported export formats include `ONNX`, `TorchScript`, `CoreML`, `TFLite`, and `TFJS`.\r\n\r\n## Features\r\n\r\n- **GPU Detection**: Automatically detects and uses NVIDIA and AMD GPUs if available.\r\n- **Multiple Export Formats**: Supports exporting the YOLO model to various formats.\r\n- **Robust Error Handling**: Includes comprehensive error handling and logging.\r\n- **`YOLO V5 \u0026 YOLO V8 Only`**\r\n\r\n## how to download the repo first time users\r\n\r\n  - click link to read [**Instructions**](https://www.gitprojects.fnbubbles420.org/how-to-download-repos)\r\n\r\n## Prerequisites\r\n\r\n- Python 3.7 or later\r\n- PyTorch\r\n- Ultralytics YOLO\r\n\r\n ### If you dont have a pet python here is a couple below:\r\n- **YOU ONLY NEED ONLY VERSION OF PYTHON TO RUN THIS !!**\r\n- [Python 3.11.6](https://github.com/KernFerm/Py3.11.6installer)\r\n- [Python 3.11.9](https://github.com/KernFerm/Py3.11.9installer)\r\n- [Python 3.12.1](https://github.com/KernFerm/Py3.12.1-installer-batch)\r\n\r\n\r\n# Logging for YOLO Model Export Script\r\n\r\nThis script is configured to use logging to provide detailed information about its execution process.\r\n\r\n## Logging Configuration\r\n\r\nThe script uses the `logging` module to log messages with the following configuration:\r\n\r\n```\r\nimport logging\r\n\r\n# Configure logging\r\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\r\nlogger = logging.getLogger(__name__)\r\n```\r\n\r\n- Log Level: The logging level is set to `INFO`. This means that the script will log messages with a severity level of `INFO` or higher (e.g., `ERROR`).\r\n- Log Format: The log messages will include the timestamp, log level, and message content.\r\n\r\n## Logged Events\r\n- The script logs various events throughout its execution, including:\r\n\r\n1. **Loading the Model:**\r\n- Logs the start of the model loading process.\r\n- Logs the successful loading of the model.\r\n\r\n```\r\n2024-07-17 12:00:00 - INFO - Loading model from best.pt\r\n2024-07-17 12:00:01 - INFO - Model loaded successfully\r\n```\r\n\r\n2. **Exporting the Model:**\r\n- Logs the start of the model export process.\r\n- Logs the successful export of the model.\r\n\r\n```\r\n2024-07-17 12:00:02 - INFO - Exporting model to onnx format\r\n2024-07-17 12:00:03 - INFO - Model exported successfully\r\n```\r\n\r\n## Detecting GPU:\r\n- Logs the detection of NVIDIA or AMD GPUs, or the use of CPU if no compatible GPU is detected.\r\n\r\n```\r\n2024-07-17 12:00:04 - INFO - NVIDIA GPU detected.\r\n```\r\n\r\n## Error Logging\r\n- The script includes error handling to log exceptions for various error scenarios:\r\n\r\n1. **File Not Found:**\r\n- Logs an error if the specified model file does not exist.\r\n\r\n```\r\n2024-07-17 12:00:00 - ERROR - The model file best.pt does not exist.\r\n```\r\n\r\n2. **Unsupported Export Format:**\r\n- Logs an error if the specified export format is not supported.\r\n\r\n```\r\n2024-07-17 12:00:01 - ERROR - Unsupported export format: invalid_format. Supported formats are: onnx, torchscript, coreml, tflite, tfjs\r\n```\r\n\r\n3. **Model Loading Error:**\r\n- Logs any exceptions that occur during model loading.\r\n\r\n```\r\n2024-07-17 12:00:02 - ERROR - Error loading model: [Exception details]\r\n```\r\n\r\n4. **Model Exporting Error:**\r\n- Logs any exceptions that occur during model export.\r\n\r\n```\r\n2024-07-17 12:00:03 - ERROR - Error exporting model: [Exception details]\r\n```\r\n\r\n5. **General Errors:**\r\n- Logs any other exceptions that occur during script execution.\r\n\r\n```\r\n2024-07-17 12:00:04 - ERROR - Failed to complete the operation: [Exception details]\r\n```\r\n\r\n## Viewing Logs\r\n- To view the logs, simply run the script, and the log messages will be printed to the console. This helps in debugging and understanding the script's execution flow.\r\n\r\n\r\n## Installation\r\n\r\n1. Clone this repository:\r\n   ```\r\n   git clone https://github.com/kernferm/yolo-export-script.git\r\n   cd yolo-export-script\r\n   ```\r\n2. Install the required Python packages:\r\n   ```\r\n   pip install torch torchvision torchaudio ultralytics\r\n   ```\r\n- If you have an AMD GPU and want to use ROCm:\r\n\r\n   ```\r\n   pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/rocm5.0\r\n   ```\r\n## Usage \r\n\r\n- Run the convert.py script with the following arguments:\r\n\r\n`--model-path:` Path to the YOLO model file (e.g., `best.pt`).\r\n`--export-format:` Export format (default: `onnx`). Supported formats: `onnx`, `torchscript`, `corem`l, `tflite`, `tfjs`.\r\n\r\n## Example\r\n\r\n```\r\npython convert.py --model-path best.pt --export-format onnx\r\n```\r\n\r\n## Script Description\r\n\r\n```\r\nimport argparse\r\nimport logging\r\nfrom ultralytics import YOLO\r\nimport os\r\nimport torch\r\n\r\n# Configure logging\r\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\r\nlogger = logging.getLogger(__name__)\r\n\r\nSUPPORTED_FORMATS = ['onnx', 'torchscript', 'coreml', 'tflite', 'tfjs']\r\n\r\ndef validate_export_format(export_format):\r\n    if export_format not in SUPPORTED_FORMATS:\r\n        raise ValueError(f\"Unsupported export format: {export_format}. Supported formats are: {', '.join(SUPPORTED_FORMATS)}\")\r\n\r\ndef load_model(model_path):\r\n    if not os.path.exists(model_path):\r\n        raise FileNotFoundError(f\"The model file {model_path} does not exist.\")\r\n    try:\r\n        logger.info(f\"Loading model from {model_path}\")\r\n        model = YOLO(model_path)\r\n        logger.info(\"Model loaded successfully\")\r\n        return model\r\n    except Exception as e:\r\n        logger.error(f\"Error loading model: {e}\")\r\n        raise\r\n\r\ndef export_model(model, export_format):\r\n    try:\r\n        logger.info(f\"Exporting model to {export_format} format\")\r\n        model.export(format=export_format)\r\n        logger.info(\"Model exported successfully\")\r\n    except Exception as e:\r\n        logger.error(f\"Error exporting model: {e}\")\r\n        raise\r\n\r\ndef detect_gpu():\r\n    if torch.cuda.is_available():\r\n        logger.info(\"NVIDIA GPU detected.\")\r\n        return torch.device('cuda')\r\n    elif torch.backends.mps.is_available():\r\n        logger.info(\"AMD GPU detected (via MPS).\")\r\n        return torch.device('mps')\r\n    elif torch.has_mps:\r\n        logger.info(\"AMD GPU detected (via ROCm).\")\r\n        return torch.device('mps')\r\n    else:\r\n        logger.info(\"No compatible GPU detected. Using CPU.\")\r\n        return torch.device('cpu')\r\n\r\ndef main():\r\n    parser = argparse.ArgumentParser(description=\"Load and export YOLO model\")\r\n    parser.add_argument('--model-path', type=str, required=True, help=\"Path to the YOLO model file (e.g., 'best.pt')\")\r\n    parser.add_argument('--export-format', type=str, default='onnx', help=f\"Export format (default: 'onnx'). Supported formats: {', '.join(SUPPORTED_FORMATS)}\")\r\n\r\n    args = parser.parse_args()\r\n\r\n    try:\r\n        validate_export_format(args.export_format)\r\n        device = detect_gpu()\r\n        model = load_model(args.model_path)\r\n        model.to(device)\r\n        export_model(model, args.export_format)\r\n    except FileNotFoundError as fnf_error:\r\n        logger.error(fnf_error)\r\n    except ValueError as val_error:\r\n        logger.error(val_error)\r\n    except Exception as e:\r\n        logger.error(f\"Failed to complete the operation: {e}\")\r\n\r\nif __name__ == \"__main__\":\r\n```\r\n\r\n\r\n## Special Thanks\r\n- [@hamsterdog6](https://github.com/hamsterdog6), thank you for the tiny snippet you provided to make this project come alive.\r\n\r\n```\r\nfrom ultralytics import YOLO\r\n\r\nLoad a model\r\nmodel = YOLO('best.pt')\r\n\r\nExport the model\r\nmodel.export(format='onnx')\r\n```\r\n\r\n## LICENSE\r\n\r\n- `MIT` [License Agreement](https://github.com/KernFerm/yolo-export-script/blob/main/LICENSE)\r\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkernferm%2Fyolo-script","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkernferm%2Fyolo-script","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkernferm%2Fyolo-script/lists"}