Tài liệu hướng dẫn tích hợp mô hình Vision Transformer (DeiT/ViT-Tiny) chẩn đoán Bệnh Võng mạc Tiểu đường 5 phân lớp dành cho Backend, Frontend, và Software Engineers.
1from preprocessing import DRPredictor
2
3# Khởi tạo predictor (chỉ cần chạy 1 lần khi startup hệ thống để nạp model vào RAM/GPU)
4# Chỉ định vit_path trỏ tới file .pt vừa tải
5predictor = DRPredictor(vit_path="vit_inference.pt")
6
7# Dự đoán từ đường dẫn ảnh hoặc dữ liệu bytes nhận được từ client upload
8result = predictor.predict("test_retina.jpg", use_ben_graham=True)
9
10print("Kết quả chẩn đoán:", result)
1{
2 "class_id": 0,
3 "class_name": "No DR",
4 "confidence": 0.8190,
5 "probabilities": {
6 "No DR": 0.8190,
7 "Mild": 0.0512,
8 "Moderate": 0.1118,
9 "Severe": 0.0120,
10 "Proliferative DR": 0.0060
11 }
12}
ONNX Runtime hỗ trợ chạy suy luận trực tiếp trên CPU/GPU mà không cần cài đặt PyTorch.
1const ort = require('onnxruntime-node');
2const sharp = require('sharp'); // Thư viện xử lý ảnh cho Node.js
3
4async function predict(imagePath) {
5 const session = await ort.InferenceSession.create('./vit_inference.onnx');
6
7 // 1. Thực hiện Resize & Normalize ảnh (tương đương preprocessing.py)
8 // - Resize letterbox về 224x224
9 // - Chuyển sang Float32 và chuẩn hóa ImageNet: (pixel / 255.0 - mean) / std
10 // - Sắp xếp lại chiều thành NCHW [1, 3, 224, 224]
11 const inputTensor = new ort.Tensor('float32', float32Data, [1, 3, 224, 224]);
12
13 // 2. Chạy suy luận
14 const outputs = await session.run({ input_image: inputTensor });
15 const probabilities = outputs.probabilities.data;
16
17 console.log("Xác suất dự đoán:", probabilities);
18}
Mô hình ONNX có thể chạy trực tiếp trên trình duyệt Client (React/Vue) hoặc ứng dụng Di động (Flutter/React Native) để bảo mật tuyệt đối dữ liệu y tế của bệnh nhân và giảm tải tối đa cho Server.
1import * as ort from 'onnxruntime-web';
2
3async function runOnClient(imageElement) {
4 // Tải mô hình trực tiếp từ thư mục public hoặc CDN
5 const session = await ort.InferenceSession.create('/models/vit_inference.onnx');
6
7 // Thực hiện trích xuất dữ liệu pixel của ảnh từ thẻ <canvas> hoặc <img>
8 // Chuẩn hóa và đóng gói thành Float32Array [1, 3, 224, 224]
9 const tensor = new ort.Tensor('float32', Float32ArrayPixels, [1, 3, 224, 224]);
10
11 const results = await session.run({ input_image: tensor });
12 console.log("Kết quả chẩn đoán client-side:", results.probabilities.data);
13}