Dish Recognition SDK (Online Edition) API Reference
Version: v1.3.0 | Build date: 2026-10-12 | Architecture: arm64-v8a (RK3576 / RKNN) | Artifact: sdk-release.aar (built-in CLIP image model + YOLO detection model + object tracking + WebSocket + HTTP communication + activation code licensing)v1.3.0 changes (activation code licensing)
- Added
com.rockchip.gpadc.demo.license.LicenseManager: unique device identifier (Android ID), online activation (/api/device_verify_code), local activation state persistence, and gateway heartbeat sync (/device_heartlock/disable state takes effect immediately). - Enforced gating:
ClipHelper.initVisionModel()andInferenceWrapper.initModel()/initModelFromAssets()refuse to initialize when not activated (return false / throwLicenseNotActivatedException); no inference is possible without activation. - The host app must guide the user to enter an activation code and activate online on first launch; see §11 Activation Code Licensing.
v1.2.1 changes (single-class model fix)
- YOLO post-processing
OBJ_CLASS_NUMchanged from 80 to 1 (PROP_BOX_SIZE=5+1=6), strictly matching the single-class modelnc:1,names:["food"]. - Java grid buffers changed from
255×N×Nto18×N×N; the prebuilt 80-classlibrknn4j.sowas removed and is now compiled from source with CMake; the label file was reduced to a single linefood.
v1.2.0 changes
- Two models bundled: both CLIP
clip_vision_finetuned.rknnand YOLObest.rknnare packed into the AAR. - YOLO gains
initModelFromAssets(Context,h,w,c), which copies the model from assets automatically.
v1.1.0 changes (history)
- The gateway address became configurable at runtime; the AAR size dropped from ~473MB to ~163MB.
1. Overview
This SDK packages the core inference and communication capabilities of the original Android project rknn_yolov5+clip+websocket+download_android_apk_demo as an AAR library for direct integration by third-party apps. Capabilities:
| Capability | Description |
|---|---|
| YOLOv5 object detection | RKNN (NPU) inference returning boxes, classes and confidence; model best.rknn is bundled |
| CLIP image recognition | On-device CLIP model extracts 512-dim features from the detection crop and classifies; model clip_vision_finetuned.rknn is bundled |
| Object tracking | Multi-object tracking (track id) to stabilize detections |
| WebSocket communication | Socket.IO long connection for device binding / heartbeat / training progress reporting |
| HTTP API | OkHttp wrapper that talks to the backend gateway (default port 5006) |
| Category / feature management | Positive / exclusion feature persistence (bin+json) and cloud download |
Package structure (com.rockchip.gpadc.demo)
com.rockchip.gpadc.demo
├── ClipHelper # High-level CLIP recognition wrapper (recommended entry)
├── ClipHelper$Result # Recognition result {clsName, score, isNegative}
├── ClipHelper$LoadCallback # Download callback
├── clip.ClipInferenceWrapper # Low-level CLIP RKNN image/text model wrapper
├── yolo.InferenceWrapper # YOLO RKNN detection wrapper (singleton)
├── yolo.PostProcess # Label loading
├── tracker.ObjectTracker # Multi-object tracking
├── InferenceResult # Inference result container (OutputBuffer / Recognition / DetectResultGroup)
├── DetectionResult # Parcelable detection result (cross-process)
├── ImageBufferQueue # NPU image buffer queue
├── rga.RGA # Color conversion (RGA hardware acceleration)
├── rga.HALDefine # Constant definitions
├── network.WebSocketManager # Socket.IO long connection
└── network.ApiClient # OkHttp HTTP wrapperNative dependencies and models (packed in the AAR)
Model assets (assets/):
| File | Type | Size | Description |
|---|---|---|---|
clip_vision_finetuned.rknn | CLIP image model | ~175MB | 512-dim image feature extraction |
best.rknn | YOLOv5 detection model | ~10MB | NPU object detection (single class: food) |
categories.json | Categories | - | Initial category mapping |
text_features.bin | CLIP features | - | Precomputed text features (used by default, no on-device text model needed) |
coco_80_labels_list.txt | Labels | - | YOLO class labels |
tokenizer/ | Vocabulary | - | CLIP text tokenizer (merges.txt + vocab.json) |
Native .so files (jni/arm64-v8a/):
librknn4j.so(JNI core of this SDK, compiled from C++ sources)librknnrt.so(RKNN Runtime)librga.so(RGA hardware acceleration)libopencv_java3.so(OpenCV)
Since v1.2.0 the AAR bundles both YOLO and CLIP models, for a total size of about 169MB. The host app no longer needs to download or store model files separately.
2. Integration
2.1 Adding the AAR
Copy sdk-release.aar into the host project's app/libs/ directory and add the following to app/build.gradle:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
// SDK transitive dependencies (already declared as api in the AAR; optional but keeps versions aligned)
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'io.socket:socket.io-client:2.1.0'
implementation 'com.google.code.gson:gson:2.10.1'
}2.2 Permissions
The AAR's AndroidManifest.xml declares the following permissions, which are merged automatically:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />The host must still request the camera permission at runtime (Android 6.0+):
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
}2.3 Hardware requirements
- RKNN-capable platforms such as RK3588 / RK3568 (arm64-v8a)
- RKNN driver installed or built in (NPU available)
3. CLIP Recognition (ClipHelper)
⚠️ Prerequisite: activation must be completed before calling (see §11 Activation Code Licensing). When not activated,initVisionModel()returnsfalsedirectly andisReady()isfalse.
CLIP recognition is an image classification capability: given a Bitmap cropped from a detection box, it returns the best-matching category.
3.1 Initialization (singleton)
import com.rockchip.gpadc.demo.ClipHelper;
ClipHelper clipHelper = ClipHelper.getInstance(context);
// Internally: copies clip_vision_finetuned.rknn to the cache and loads text_features.bin / categories.json
boolean ready = clipHelper.isReady();getInstance(Context): returns the global singleton; the first call runsinitVisionModel()and is slow (model loading).resetInstance(): resets the singleton and clears static caches (categories, exclusions).
3.2 Image feature extraction
float[] feature = clipHelper.extractImageFeature(bitmap); // Returns a 512-dim normalized feature, or null on failure3.3 Classification (core API)
// Simple classification
ClipHelper.Result r = clipHelper.clipClassify(cropBitmap);
// With position (filters targets at the frame edge; the filter logic can be customized)
ClipHelper.Result r = clipHelper.clipClassify(cropBitmap, rectF);
// With trackId (enables stabilization: output after 3 consistent results to prevent label jumps)
ClipHelper.Result r = clipHelper.clipClassify(cropBitmap, rectF, trackId);ClipHelper.Result:
| Field | Type | Description |
|---|---|---|
clsName | String | Category name; null means an exclusion matched; "ignore" means below threshold; "failed" means failure |
score | float | Similarity score (0~1, normalized cosine similarity) |
isNegative | boolean | true = the result should be ignored (exclusion / below threshold) |
3.4 Category / feature management
// Add a category (feature is 512-dim; pass null to generate a placeholder feature)
boolean ok = clipHelper.addTextCategory("Braised pork", false, feature); // positive sample
boolean ok2 = clipHelper.addTextCategory("Plate", true, null); // exclusion
// Delete / toggle exclusion state
clipHelper.removeCategory("Braised pork");
clipHelper.toggleExcludeStatus("Plate"); // positive <-> exclusion
// Query
Map<String, Boolean> all = clipHelper.getAllCategories(); // label -> isExclude
Map<String, Boolean> pos = clipHelper.getPositiveCategories();
List<String> excludes = clipHelper.getExcludeList();
boolean isExclude = clipHelper.isExclude("Plate");
float[] feat = clipHelper.getFeature("Braised pork");
int count = clipHelper.getCategoryCount();
// Persist (writes context.getFilesDir()/text_features.bin + categories.json)
clipHelper.saveFeaturesToFile();
// Load / refresh from the files directory
clipHelper.loadCategoriesFromFiles();
clipHelper.refreshCategoriesFromFiles();
clipHelper.reloadFeatures();3.5 Downloading features from the cloud
clipHelper.loadFeaturesFromUrls("http://host/text_features.bin",
"http://host/categories.json", new ClipHelper.LoadCallback() {
@Override public void onSuccess(int categoryCount) { }
@Override public void onFailure(String error) { }
});3.6 Threshold and stabilization
float threshold = clipHelper.getThreshold(); // Default 0.6
clipHelper.setThreshold(0.65f); // Range 0.3 ~ 0.9
clipHelper.clearStableCache(trackId); // Clear the stability cache for one target
clipHelper.clearAllStableCache(); // Clear all3.7 Release
clipHelper.release(); // Releases the image model and stability cache (call resetInstance to null the singleton)4. YOLOv5 Object Detection (InferenceWrapper)
⚠️ Prerequisite: activation must be completed before calling (see §11 Activation Code Licensing). When not activated,initModelFromAssets()throwsLicenseNotActivatedExceptionand the model is not loaded.
The YOLO model best.rknn is bundled in the AAR and supports two initialization approaches:
4.1 Initialization (singleton)
Option 1 (recommended): load from the AAR assets
import com.rockchip.gpadc.demo.yolo.InferenceWrapper;
InferenceWrapper yolo = InferenceWrapper.getInstance();
// Automatically copies assets/best.rknn to the cache and initializes
yolo.initModelFromAssets(context, 640, 640, 3);
boolean ready = yolo.isInitialized();Option 2: host supplies a custom model path
InferenceWrapper yolo = InferenceWrapper.getInstance();
yolo.initModel(640, 640, 3, "/data/user/0/" + context.getPackageName() + "/files/best.rknn");
// Or point to any readable path, such as external storage or raw resourcesinitModelFromAssets(Context, im_height, im_width, im_channel): automatically copiesbest.rknnfrom the AAR assets tocontext.getCacheDir()/best.rknnand reuses it when the cached file already exists and is >1MB (no repeated copy); then callsinitModel()to finish NPU initialization. Returns 0 on success and non-zero on failure.
4.2 Inference
run requires an NPU image buffer handle (from ImageBufferQueue) and returns the raw outputs of the three grid scales:
ImageBufferQueue queue = new ImageBufferQueue(3, previewW, previewH);
ImageBufferQueue.ImageBuffer buf = queue.getFreeBuffer();
// ... convert the camera frame through RGA into the npu buffer (see the RGA section)
InferenceResult.OutputBuffer out = yolo.run(buf.mImage_handle, previewW, previewH);4.3 Post-processing
ArrayList<InferenceResult.Recognition> list = yolo.postProcess(out);
// Recognition: getId() class id / getConfidence() / getLocation() RectF normalized coords / getTrackId()4.4 Release
yolo.deinit();5. Inference Result Containers (InferenceResult)
5.1 Recognition
| Method | Description |
|---|---|
int getId() | Class id |
float getConfidence() | Confidence (0~1) |
RectF getLocation() | Normalized target box (0~1) |
int getTrackId() | Track id |
void setTrackId(int) / void setLocation(RectF) | Setters |
5.2 OutputBuffer
| Field | Type | Description |
|---|---|---|
mGrid0Out/mGrid1Out/mGrid2Out | byte[] | Raw outputs of the three YOLO scales |
floatOutput | float[] | CLIP image feature output (512-dim) |
5.3 DetectionResult (Parcelable, cross-process)
| Field | Type | Description |
|---|---|---|
id | int | Class id |
confidence | float | Confidence |
left/top/right/bottom | float | Normalized coordinates |
trackId | int | Track id |
label | String | Category name |
6. Object Tracking (ObjectTracker)
import com.rockchip.gpadc.demo.tracker.ObjectTracker;
ObjectTracker tracker = new ObjectTracker(previewWidth, previewHeight, maxTrackLifetime /* e.g. 4 */);
ArrayList<InferenceResult.Recognition> tracked = tracker.tracker(recognitions);
// Each returned Recognition carries a trackId and normalized coordinates7. NPU Image Buffers (ImageBufferQueue)
Allocates/reuses NPU image buffers (targets of RGA conversion).
ImageBufferQueue queue = new ImageBufferQueue(3, width, height);
ImageBufferQueue.ImageBuffer buf = queue.getFreeBuffer(); // Take a free buffer
queue.postBuffer(buf); // Mark ready after filling
ImageBufferQueue.ImageBuffer ready = queue.getReadyBuffer(); // Take a ready buffer for inference
queue.releaseBuffer(ready); // Release after use
queue.release(); // Release everything (onDestroy)isNPUAvailable()(static): whether the NPU is initialized and available.ImageBuffer.mImage_handle: NPU buffer handle (passed toInferenceWrapper.run/RGA.colorConvertAndFlip).
8. RGA Color Conversion (RGA / HALDefine)
import com.rockchip.gpadc.demo.rga.RGA;
import static com.rockchip.gpadc.demo.rga.HALDefine.*;
// Convert an NV21/RGBA camera frame into the NPU buffer, optionally flipping horizontally
int ret = RGA.colorConvertAndFlip(srcBytes, RK_FORMAT_YCrCb_420_SP,
npuBuffer.mImage_handle, RK_FORMAT_RGB_888, width, height, IM_HAL_TRANSFORM_FLIP_H);
// Returns 0 on successCommon format constants (HALDefine):
| Constant | Value | Description |
|---|---|---|
RK_FORMAT_RGBA_8888 | 0x0 | RGBA |
RK_FORMAT_RGB_888 | 0x200 | RGB |
RK_FORMAT_YCrCb_420_SP | 0xe00 | NV21 |
IM_HAL_TRANSFORM_FLIP_H | 0x08 | Horizontal flip |
9. WebSocket Communication (WebSocketManager)
Based on Socket.IO, connects to http://<YOUR_SERVER>:5006 by default (configurable at runtime, see 9.1).
9.1 Gateway address configuration
Three ways to set the server address (all take precedence over the default):
// Option 1: specify in the constructor
WebSocketManager ws = new WebSocketManager(listener, "http://<YOUR_SERVER>:5006");
// Option 2: create first, set the address, then connect (effective after disconnect)
WebSocketManager ws = new WebSocketManager(listener);
ws.setServerUrl("http://<YOUR_SERVER>:5006").connect();
// Option 3: default address (falls back to http://<YOUR_SERVER>:5006 when not set)
WebSocketManager ws = new WebSocketManager(listener);setServerUrl(String): sets the address and returnsthisfor chaining; call it beforeconnect()(the constructor connects automatically, so calldisconnect()first, then set, thenconnect()to change the address).disconnect(): disconnects and releases the socket (the socket is nulled; the nextconnect()rebuilds it with the new address).connect(): establishes the connection; if the socket was released, it is rebuilt from the currentmServerUrl.
9.2 Connecting and listening
import com.rockchip.gpadc.demo.network.WebSocketManager;
WebSocketManager ws = new WebSocketManager(new WebSocketManager.WsEventListener() {
@Override public void onTaskUpdate(JSONObject data) { } // task_update
@Override public void onConnect() { }
@Override public void onDisconnect() { }
@Override public void onError(String error) { }
@Override public void onTrainProgress(JSONObject data) { } // train_real_progress / train_progress_update
@Override public void onAuthSuccess() { } // ws_auth_success
@Override public void onAuthFailed(String msg) { } // ws_auth_failed / device_locked
});9.3 Common methods
ws.bindDevice("deviceId123"); // Device binding/auth (device_ws_auth)
ws.reportProgress("deviceId", "taskId", 50, "training"); // Report training progress (ws_report_progress)
ws.sendPing(); // Send a heartbeat ping
ws.isConnected(); // Whether connected
ws.disconnect(); // Disconnect (stops the heartbeat) Heartbeat interval is 15s, sending ping_check automatically; the connection auto-reconnects when dropped (up to 10 times).10. HTTP Communication (ApiClient)
Based on OkHttp, BASE_URL defaults to http://<YOUR_SERVER>:5006 (configurable at runtime).
10.1 Gateway address configuration
// Call once during app initialization; applies to all subsequent requests
ApiClient.setBaseUrl("http://<YOUR_SERVER>:5006");
String current = ApiClient.getBaseUrl(); // Get the current addresssetBaseUrl(String): sets the gateway BASE_URL (a trailing/is removed automatically); defaults tohttp://<YOUR_SERVER>:5006when not set.
10.2 Request APIs
import com.rockchip.gpadc.demo.network.ApiClient;
// POST (JsonObject)
ApiClient.postJson("/api/xxx", jsonObject, new ApiClient.ApiCallback() {
@Override public void onSuccess(String response) { }
@Override public void onFailure(String error) { }
});
// POST (JSON string)
ApiClient.postJson("/api/xxx", "{\"key\":\"value\"}", callback);
// GET
ApiClient.get("/api/xxx", callback);11. Activation Code Licensing (LicenseManager)
Added in v1.3.0. The SDK uses a device + activation code licensing model: each device must complete activation online with an activation code on the gateway (port 5006) before first use, otherwiseClipHelperandInferenceWrapperrefuse to load models and no inference is possible.
11.1 Licensing flow
App launch
└─► LicenseManager.getDeviceId(context) // Get the unique device identifier (Android ID)
└─► Activated locally?
├─ Yes ─► LicenseManager.syncStatus(...) // Optional: heartbeat check whether locked/disabled on the server
│ └─► Passed → initialize ClipHelper / InferenceWrapper normally
└─ No ─► Show the activation page → user enters the activation code
└─► LicenseManager.activate(context, code, cb)
├─ Success → write local SP, continue the normal flow
└─ Failure → Toast the error (invalid code / network unreachable)11.2 Core APIs
Package: com.rockchip.gpadc.demo.license.LicenseManager
| Method | Description |
|---|---|
static String getDeviceId(Context ctx) | Returns the unique device identifier (prefers Android ID, generates and persists a UUID when unavailable). Be sure to report this ID to operations/administrators so the activation code can be bound on the gateway. |
static boolean isActivated(Context ctx) | Synchronously reads the local activation state (no network). |
static void activate(Context ctx, String code, LicenseCallback cb) | Online activation. Callbacks run on the main thread. |
static void syncStatus(Context ctx, LicenseCallback cb) | Syncs with the gateway /device_heart; if the server returns locked=1 or activated=0, the local activation is invalidated immediately. Recommended once per app launch. |
static String getActivationCode(Context ctx) / getExpireTime(Context ctx) | Returns the locally saved activation code and expiry date (empty string = permanent). |
static void assertActivated(Context ctx) | Throws LicenseNotActivatedException when not activated (the SDK already calls it during model initialization). |
static void clearActivation(Context ctx) | Clears the local activation state (code replacement / sign-out). |
Callback interface:
LicenseManager.LicenseCallback cb = new LicenseManager.LicenseCallback() {
@Override public void onSuccess(String msg) { /* Activated, go to the home screen */ }
@Override public void onFailure(String errMsg) { /* Show the error, e.g. "Invalid activation code, please check and retry" */ }
};11.3 Minimal integration example
import com.rockchip.gpadc.demo.license.LicenseManager;
import com.rockchip.gpadc.demo.license.LicenseManager.LicenseCallback;
// 1) Configure the gateway address (shared with WebSocket/HTTP)
ApiClient.setBaseUrl("http://<YOUR_SERVER>:5006");
// 2) Already activated? Use it directly
if (LicenseManager.isActivated(this)) {
goToMainPage();
} else {
// 3) Show the activation page; after the user enters the code:
LicenseManager.activate(this, editTextCode.getText().toString().trim(), new LicenseCallback() {
@Override public void onSuccess(String msg) { goToMainPage(); }
@Override public void onFailure(String err) { Toast.makeText(MainActivity.this, err, Toast.LENGTH_LONG).show(); }
});
}
// 4) Initialize inference after entering the home screen (gating now passes)
ClipHelper clip = ClipHelper.getInstance(this);
InferenceWrapper.getInstance().initModelFromAssets(this, 640, 640, 3);11.4 Gateway-side API contract (port 5006)
The SDK calls only the following two gateway APIs; the operations side needs no code changes:
POST /api/device_verify_code — activation
// Request
{ "device_id": "xxxxxxxx", "activation_code": "<ACTIVATION_CODE>", "board_platform": "RK3576-Android" }
// Success
{ "code": 0, "msg": "verified", "group_id": "<ACTIVATION_CODE>" }
// Failure
{ "code": 1, "msg": "Invalid activation code, please check and retry" }POST /device_heart — heartbeat / status sync
// Request
{ "device_id": "xxxxxxxx", "device_type": "label_client" }
// Response
{ "code": 0, "locked": 0, "activated": 1, "activation_code": "<ACTIVATION_CODE>", "tip": "" }
// When locked=1 or activated=0, the local activation is invalidated immediately11.5 Error codes and FAQ
| Symptom | Cause | Resolution |
|---|---|---|
LicenseNotActivatedException | initModelFromAssets called before activation | Complete LicenseManager.activate first |
| "Invalid activation code" | The gateway has no such code, or it was deleted | Contact operations to confirm the code |
| "Cannot reach gateway" | Network unreachable / wrong ApiClient.setBaseUrl | Check that port 5006 is reachable |
| Activated but invalid after restart | The device was disabled/locked from the gateway console | Re-enable it in gateway device management |
getDeviceId differs each time | Very rare (device replacement / factory reset) | The new device must be activated again |
12. Complete Example (YOLO detection + CLIP recognition)
public class Demo {
private InferenceWrapper mYolo;
private ClipHelper mClip;
private ImageBufferQueue mQueue;
private ObjectTracker mTracker;
public void init(Context context) {
// 1. Initialize YOLO (v1.2.0: load best.rknn from the bundled assets)
mYolo = InferenceWrapper.getInstance();
mYolo.initModelFromAssets(context, 640, 640, 3);
// 2. Initialize CLIP (the singleton loads the bundled model and features)
mClip = ClipHelper.getInstance(context);
// 3. NPU buffers and tracker
mQueue = new ImageBufferQueue(3, 1024, 768);
mTracker = new ObjectTracker(1024, 768, 4);
}
public void onFrame(byte[] nv21, int w, int h) {
// 4. Color conversion into the NPU buffer
ImageBufferQueue.ImageBuffer buf = mQueue.getFreeBuffer();
RGA.colorConvertAndFlip(nv21, HALDefine.RK_FORMAT_YCrCb_420_SP,
buf.mImage_handle, HALDefine.RK_FORMAT_RGB_888, w, h, 0);
mQueue.postBuffer(buf);
// 5. YOLO inference + post-processing
InferenceResult.OutputBuffer out = mYolo.run(buf.mImage_handle, w, h);
ArrayList<InferenceResult.Recognition> dets = mYolo.postProcess(out);
// 6. Object tracking
dets = mTracker.tracker(dets);
// 7. Run CLIP recognition on each detection box
for (InferenceResult.Recognition r : dets) {
RectF loc = r.getLocation(); // Normalized coordinates
Bitmap crop = cropFromPreview(loc, w, h); // Crop from the frame (implement yourself)
ClipHelper.Result cls = mClip.clipClassify(crop, loc, r.getTrackId());
if (cls != null && !cls.isNegative) {
Log.d("DEMO", "Detected: " + cls.clsName + " score=" + cls.score);
}
}
}
}13. Test Version Download API (RestoreManager / gateway)
Used by devices to download test version models and category images in one tap and ingest them (the/api/test_version/*APIs of the gateway, backed by object storage). This feature lives in the host app layer (RestoreManager); the SDK providesApiClientfor it to call.
13.1 Test version info
- Path:
GET {BASE_URL}/api/test_version/info - Response:
{
"code": 0,
"data": {
"version": "1.0.0",
"name": "Test version (object storage)",
"categories": {...},
"category_image_count": {"Coca-Cola": 5, "C'estbon Water": 5, "Wanglaoji": 6, "Sprite": 5},
"total_categories": 4,
"total_images": 21,
"has_model": true,
"has_clip": true
}
}- Notes: counts the models, CLIP files, categories and images under the
test_version/directory in object storage.
13.2 Download a single test-version file
- Path:
GET {BASE_URL}/api/test_version/download/<filename> - Supported files:
bestv5n.rknn,clip_images_cn.rknn,text_features.bin,categories.json - Response: file binary stream (
application/octet-stream) fetched fromtest_version/<filename>in object storage - Notes: only the four whitelisted files above are allowed;
filenamecontaining..or/returns 400.
13.3 Test version categories + image list
- Path:
GET {BASE_URL}/api/test_version/categories_with_images - Response:
{
"code": 0,
"data": {
"Coca-Cola": [{"name": "xxx.jpg", "url": "https://<YOUR_CDN_DOMAIN>/test_version/category_images/Coca-Cola/xxx.jpg"}],
"C'estbon Water": [...],
"Wanglaoji": [...],
"Sprite": [...]
}
}- Notes: walks
test_version/category_images/{category}/{filename}.jpgin object storage and returns the image list per category (with public URLs).
13.4 Download a single test-version category image
- Path:
GET {BASE_URL}/api/test_version/category_images/<path> - Parameter:
path={category}/{filename}.jpg - Response: image binary stream (
image/jpeg)
13.5 Client ingestion flow (host reference)
After downloading a test version, the images must be written into the SDK category library for ClipHelper / product management to read:
- Call
13.2to download the 4 core files (rknn / bin / json) into the version directory; - Call
13.3to get the category + image list; - For each image call
13.4to download it, then ingest withLocalImageManager.downloadSingleImage(url, categoryName, "", localManager, cb); - Before ingesting, call
clearAllImages(localManager)to clear old images, and usemarkImageAsTrainedto mark them trained; - In the product management UI,
CategoryManagerActivity.refreshList()reads categories frommClipHelper.getAllCategories()(categories.json) and image counts frommLocalManager.getLabelCounts()(RKNN_Training directory).
Configure the gateway address once viaApiClient.setBaseUrl()/WebSocketManager.setServerUrl(), so the app does not need to change URLs everywhere.
14. Training-related APIs (SDK-side interaction)
The SDK interacts with the training gateway (5006) through WebSocketManager + ApiClient and participates in the whole training flow:
| Capability | Method / event | Description |
|---|---|---|
| Device binding / auth | ws.bindDevice(deviceId) | Sends device_ws_auth, receives ws_auth_success/failed |
| Report training progress | ws.reportProgress(deviceId, taskId, progress, log) | Sends ws_report_progress |
| Receive real-time progress | onTrainProgress(JSONObject) | Receives train_real_progress / train_progress_update |
| Receive task notifications | onTaskUpdate(JSONObject) | Receives task_update / new_task_notification |
| Submit a training task | ApiClient.postJson("/submit_train_task", {...}, cb) | Uploads annotated images + categories to submit training |
| Claim / complete tasks | ApiClient.get("/api/pending_task", cb) etc. | Polling on the training side (as an annotation client the SDK mainly submits / reports progress / downloads) |
| Download training artifacts | ApiClient calls /api/download_model / /api/test_version/download | Obtains model URLs or test-version files |
Typical actions of the SDK as an annotation client (Android):
// Submit a training task
JsonObject task = new JsonObject();
task.addProperty("device_id", "android_xxx");
task.addProperty("task_type", "yolo_clip");
task.addProperty("image_count", 100);
task.add("uploaded_images", imagesArray);
task.addProperty("epochs", 50);
ApiClient.postJson("/submit_train_task", task, callback);
// Report progress (over WS)
ws.reportProgress("device_id", "taskId", 50, "Epoch 25/50");
// Download the latest model
ApiClient.postJson("/api/download_model", req, callback);
// The response data contains model_pt_url / model_rknn_url / clip_bin_url / clip_json_url / categoriesFor the complete HTTP/Socket.IO API list of the training service (port 5005) and the training gateway (port 5006), see the training gateway API notes.
15. Known Limitations and Notes
- AAR size: about 169MB (CLIP model + YOLO model + OpenCV). v1.2.0 bundles both models; to slim it down, remove
clip_vision_finetuned.rknn(keeping YOLO only) or prune during deserialization. - Server address:
WebSocketManager(setServerUrl/ constructor argument) andApiClient(setBaseUrl) are all configurable at runtime, defaulting tohttp://<YOUR_SERVER>:5006; set them once at app startup. - Hardware dependency: must run on an RKNN platform (arm64-v8a); ordinary emulators have no NPU.
- CLIP text model: the SDK keeps both image and text model interfaces of
ClipInferenceWrapper, butClipHelperuses the precomputed text feature file (text_features.bin) by default and does not load the text model on-device. - Source of category features: on first use, ensure
text_features.binandcategories.jsonexist in thefiles/directory (downloadable from the cloud or generated by the SDK). - YOLO model: since v1.2.0
best.rknnis bundled in the AAR and loads with one call toinitModelFromAssets(); to replace it, pass an external path toinitModel(). The model is single-class (food) and post-processing is compiled forOBJ_CLASS_NUM=1; do not substitute a COCO 80-class model. - Test version vs. bundled models: the AAR bundles
best.rknn/clip_vision_finetuned.rknn, while the test-version API downloadsbestv5n.rknn/clip_images_cn.rknn(cloud test versions). The file names differ; ingest them as described in section 13.5. - Obfuscation: the AAR ships with
proguard.txtthat keeps JNI and data entity classes; if the host app is obfuscated, make sure these keep rules are preserved.
16. SDK Project Structure (source available for customization)
sdk/
├── build.gradle # Library module (namespace: com.rockchip.gpadc.demo)
├── CMakeLists.txt # Builds librknn4j.so (C++ sources)
├── proguard-rules.pro
└── src/main/
├── AndroidManifest.xml # Permission declarations
├── assets/ # best.rknn + clip_vision_finetuned.rknn + labels + features + tokenizer
├── cpp/ # native-lib.cc / post_process.cc / yolo_image.cc / object_tracker/ / rga/
├── jniLibs/arm64-v8a/ # librknnrt.so / librga.so / libopencv_java3.so / librknn4j.so
└── java/com/rockchip/gpadc/demo/
├── ClipHelper.java
├── ImageBufferQueue.java
├── InferenceResult.java
├── DetectionResult.java
├── clip/ClipInferenceWrapper.java
├── yolo/InferenceWrapper.java
├── yolo/PostProcess.java
├── tracker/ObjectTracker.java
├── rga/RGA.java
├── rga/HALDefine.java
├── network/WebSocketManager.java
└── network/ApiClient.javaRebuild command (in the project root; requires JDK 17 + Android SDK):
gradlew.bat :sdk:assembleRelease
# Output: sdk/build/outputs/aar/sdk-release.aar